/* This file is part of Mailfromd.
   Copyright (C) 2005-2022 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#ifndef __mfd_srvman_h
#define __mfd_srvman_h

typedef struct mfd_server *mfd_server_t;

typedef	int (*mfd_server_func_t) (const char *id,
				  int fd,
				  struct sockaddr const *sa, socklen_t len,
				  void *server_data, void *srvman_data);
typedef	int (*mfd_server_prefork_hook_t) (const char *id,
					  struct sockaddr const *sa,
					  socklen_t len,
					  void *server_data,
					  void *srvman_data);
typedef	int (*mfd_srvman_hook_t) (void *data);
typedef int (*mfd_srvman_prefork_hook_t) (struct sockaddr const *sa,
					  socklen_t len,
					  void *data);

#define DEFAULT_PIDTAB_SIZE 64
#define DEFAULT_SHUTDOWN_TIMEOUT 5

#define SRV_SINGLE_PROCESS 0x01
#define SRV_KEEP_EXISTING  0x02

struct srvman_param {
	void *data;                 /* Server manager data */
	mu_acl_t acl;               /* Global Access Control List */
	time_t shutdown_timeout;
	mfd_srvman_hook_t idle_hook;             /* Idle function */
	mfd_srvman_prefork_hook_t prefork_hook;  /* Pre-fork function */
	mfd_srvman_hook_t free_hook;             /* Free function */
	size_t max_children;        /* Maximum number of sub-processes
				       to run. */
	int flags;                  /* Global flags */
	fd_set keepfds;             /* Keep these fds open when spawning
				       children */
};

extern struct srvman_param srvman_param;

void srvman_init(void);

void mfd_server_shutdown(mfd_server_t srv);
mfd_server_t mfd_server_new(const char *id, mu_url_t url,
			    mfd_server_func_t conn, int flags);
void mfd_server_free(mfd_server_t srv);
void mfd_server_set_prefork_hook(mfd_server_t srv,
				 mfd_server_prefork_hook_t hook);
void mfd_server_set_data(mfd_server_t srv,
			 void *data,
			 mfd_srvman_hook_t free_hook);
void mfd_server_set_max_children(mfd_server_t srv, size_t n);
void mfd_server_set_acl(struct mfd_server *srv, mu_acl_t acl);
void mfd_server_set_backlog(struct mfd_server *srv, int value);

void mfd_srvman_attach_server(mfd_server_t srv);
void mfd_srvman_run(sigset_t *);
int mfd_srvman_open(void);
void mfd_srvman_shutdown(void);
void mfd_srvman_free(void);
size_t mfd_srvman_count_servers(void);
void mfd_srvman_stop(void);

struct sockaddr *srvman_url_to_sockaddr(mu_url_t url, socklen_t *psalen);

#endif
