/* Copyright (C) 1997 Aladdin Enterprises.  All rights reserved.
  
  This file is part of GNU Ghostscript.
  
  GNU Ghostscript is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility to
  anyone for the consequences of using it or for whether it serves any
  particular purpose or works at all, unless he says so in writing.  Refer to
  the GNU General Public License for full details.
  
  Everyone is granted permission to copy, modify and redistribute GNU
  Ghostscript, but only under the conditions described in the GNU General
  Public License.  A copy of this license is supposed to have been given to
  you along with GNU Ghostscript so you can know your rights and
  responsibilities.  It should be in a file named COPYING.  Among other
  things, the copyright notice and this notice must be preserved on all
  copies.
  
  Aladdin Enterprises is not affiliated with the Free Software Foundation or
  the GNU Project.  GNU Ghostscript, as distributed by Aladdin Enterprises,
  does not depend on any other GNU software.

  However Display Ghostscript System depends on GLib. */

/* $Id: dgsserve.c,v 1.3 2000/04/16 18:33:04 masata-y Exp $ */
/* Display Ghostscript listener (server) */


#include <glib.h>		/* For Hash tables */
#include "stdpre.h"		/* for 'private' */
#include <stdio.h>
#include <X11/Xlib.h>

/* network headers */
#include <sys/socket.h>
#include <netinet/in.h>		/* for ntohs */
#include <unistd.h>

#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

/* headers for select(2) */
#include <sys/time.h>
#include <errno.h>
#include <sys/un.h>

#if defined(HAVE_TCPD_H)
#if defined(HAVE_SYSLOG_H)
#include <syslog.h>
#else
#define LOG_INFO 6
#define LOG_WARNING 4
#endif
#include "tcpd.h"
int allow_severity = LOG_INFO;
int deny_severity = LOG_WARNING;
#endif

#include "dgs.h"
#include "dgsconn.h"
#include "dgsmisc.h"
#include "dgsagent.h"

private void proc_server_wait_agent(int);
private void proc_server_finalize(int);
private void proc_server_setup_signal(void);
private void proc_server_control(int);

int billboard_atom_needs_cleanup;

Window server_win_unix;
Window server_win_tcp;

private int server_socket_unix;
private int server_socket_tcp;
private struct sockaddr_un server_sockaddr_unix;	/*! NOT GOOD */
private struct sockaddr_in server_sockaddr_tcp;	/*! NOT GOOD */

private int server_agent_counter = 0;
GSet *server_agent_pids = NULL;

/* Try to eliminate these ?? */
Display *shared_dpy;		/*! NOT GOOD NAME */
unsigned char shared_byteorder;


int
start_dpsnx_server(int argc, char *argv[])
{
    int server_port_unix, server_port_tcp;
    int base_port;
    fd_set rfds;
    int max_port;
    int result;
    int indian = 1;

    if (DGS_DEBUG) {
	fprintf(stderr, "start_dpsnx_agent: argc = %d\n", argc);
	{
	    int i;

	    for (i = 0; i < argc; i++)
		fprintf(stderr, "start_dpsnx_agent: gs arg = %s\n",
			argv[i]);
	}
    }

    conn_sock_initialize();

    /** Check server side byteorder, see dps/cxlibext.c */
    if (*(char *)&indian)
	shared_byteorder = 'l';
    else
	shared_byteorder = 'B';

    /** open the display, this will last the entire session and be used for
       every window used */
    shared_dpy = XOpenDisplay(NULL);
    if (!shared_dpy) {
	fprintf(stderr,
		"Cannot open X Display(server): %s\nABORTING!\n",
		XDisplayName(NULL));
	return -1;
    }

    /** create us a socket to listen on */
    server_socket_unix = conn_server_create(&server_sockaddr_unix, UNIXCONN);
    if (server_socket_unix == -1)
	goto close_display;

    server_socket_tcp = conn_server_create(&server_sockaddr_tcp, TCPCONN);
    if (server_socket_tcp == -1)
	goto close_socket_unix;

    /** find an open port */
    base_port = conn_base_port_find();
    server_port_unix = conn_server_bind(server_socket_unix,
					&server_sockaddr_unix,
					base_port, UNIXCONN);
    if (server_port_unix == -1)
	goto close_socket_unix;

    server_port_tcp = conn_server_bind(server_socket_tcp,
				       &server_sockaddr_tcp,
				       base_port, TCPCONN);

    if (server_port_tcp == -1)
	goto finalize_sock_tcp;

    /** a base window */
    /* UNIXCONN */
    server_win_unix
	= XCreateSimpleWindow(shared_dpy,
			      DefaultRootWindow(shared_dpy), 0, 0, 1, 1,	/* min X window size */
			      0,	/* no border either */
			      BlackPixel(shared_dpy,
					 DefaultScreen(shared_dpy)),
			      WhitePixel(shared_dpy,
					 DefaultScreen(shared_dpy)));
    if (!server_win_unix) {
	fprintf(stderr,
		"Unable to create main comm window for UNIXCONN.\n");
	goto close_socket_tcp;
    }
    /* we want basically no input, but that does give us Client messages */
    XSelectInput(shared_dpy, server_win_unix, NoEventMask);

    /* TCPCONN */
    server_win_tcp
	= XCreateSimpleWindow(shared_dpy,
			      DefaultRootWindow(shared_dpy), 0, 0, 1, 1,	/* min X window size */
			      0,	/* no border either */
			      BlackPixel(shared_dpy,
					 DefaultScreen(shared_dpy)),
			      WhitePixel(shared_dpy,
					 DefaultScreen(shared_dpy)));
    if (!server_win_tcp) {
	fprintf(stderr,
		"Unable to create main comm window for TCPCONN.\n");
	goto destory_win_unix;
    }
    /* we want basically no input, but that does give us Client messages */
    XSelectInput(shared_dpy, server_win_tcp, NoEventMask);

    /** that we are ready to accept connections, we must inform the server */
    result = conn_atom_setup(shared_dpy,
			     server_win_unix,
			     base_port + server_port_unix,
			     server_win_tcp, base_port + server_port_tcp);
    if (-1 == result)
	goto destory_win_tcp;
    billboard_atom_needs_cleanup = 1;
    /* flush all remaining X events */
    XSync(shared_dpy, False);

    /******* alright, its time to really accept a connection and get to work ********/
    /* this code will all have to be rewritten with multiple contexts in mind */

    while (1) {
	int in_sock = -1;
	enum conn_type type = 0;
	int xfd = XConnectionNumber(shared_dpy);

	result = listen(server_socket_unix, 5);
	if (result < 0) {
	    perror("[UNIX]listen: ");
	    goto atom_cleanup;
	}

	result = listen(server_socket_tcp, 5);
	if (result < 0) {
	    perror("[TCP]listen: ");
	    goto atom_cleanup;
	}
	max_port = (server_socket_unix < server_socket_tcp) ?
	    server_socket_tcp : server_socket_unix;
	max_port = (xfd < max_port) ? max_port : xfd;

	FD_ZERO(&rfds);
	FD_SET(server_socket_unix, &rfds);
	FD_SET(server_socket_tcp, &rfds);
	FD_SET(xfd, &rfds);
	proc_server_setup_signal();
	result = select(max_port + 1, &rfds, NULL, NULL, NULL);
	if (-1 == result) {
	    if (errno != EINTR) {
		perror("select: ");
		goto atom_cleanup;
	    } else
		continue;	/* SIGCHLD */
	}

	if (FD_ISSET(server_socket_unix, &rfds)) {
	    in_sock = conn_insock_accept(server_socket_unix, UNIXCONN);
	    type = UNIXCONN;
	    fprintf(stderr,
		    "Connection accepted on socket number %d via %s\n",
		    in_sock, "UNIXCONN");
	} else if (FD_ISSET(server_socket_tcp, &rfds)) {
	    in_sock = conn_insock_accept(server_socket_tcp, TCPCONN);
	    type = TCPCONN;

#if defined(HAVE_TCPD_H)
	    {
		struct request_info request;

		request_init(&request, RQ_DAEMON, "dgs", RQ_FILE, in_sock, 0);
		fromhost(&request);
		if (!hosts_access(&request)) {
		    fprintf(stderr,
			    "Connection refused on socket number %d via %s from %s\n",
			    in_sock, "TCPCONN", eval_client(&request));
		    close(in_sock);
		    continue;
		}
	    }
#endif

	    fprintf(stderr,
		    "Connection accepted on socket number %d via %s\n",
		    in_sock, "TCPCONN");
	} else if (FD_ISSET(xfd, &rfds))
	    goto finalize_sock_tcp;

	if (in_sock == -1)
	    goto atom_cleanup;

	/** setup basic connection info and run */
	result = proc_agent_start(in_sock,
				  server_socket_unix,
				  server_socket_tcp,
				  argc, argv, ++server_agent_counter, type);
	if (-1 == result)
	    goto atom_cleanup;
    }
  atom_cleanup:
    conn_atom_cleanup();
  destory_win_tcp:
    XDestroyWindow(shared_dpy, server_win_tcp);
  destory_win_unix:
    XDestroyWindow(shared_dpy, server_win_unix);
  finalize_sock_tcp:
    conn_sock_finalize(&server_sockaddr_tcp, TCPCONN);
  finalize_sock_unix:
    conn_sock_finalize(&server_sockaddr_unix, UNIXCONN);
  close_socket_tcp:
    conn_server_close(server_socket_tcp);
  close_socket_unix:
    conn_server_close(server_socket_unix);
  close_display:
    XCloseDisplay(shared_dpy);
    return -1;			/* if we got here, it is an error */
}


private void
proc_server_wait_agent(int sig)
{
    pid_t pid;
    int status;

    while ((pid = waitpid(-1, &status, WNOHANG)) > 0);	/* Do NOTHING */
    server_agent_pids = g_set_remove(server_agent_pids, (gpointer) pid);
    signal(SIGCHLD, proc_server_wait_agent);	/* Re-set */
}

private void
proc_server_finalize(int sig)
{
    if (DGS_DEBUG) {
	const char *signame = util_signal_int2str(sig);

	fprintf(stderr, "proc_server_finalize: %s...\n", signame);
    }
    conn_atom_cleanup();
    XDestroyWindow(shared_dpy, server_win_tcp);
    XDestroyWindow(shared_dpy, server_win_unix);
    conn_sock_finalize(&server_sockaddr_unix, UNIXCONN);
    conn_sock_finalize(&server_sockaddr_tcp, TCPCONN);
    conn_server_close(server_socket_tcp);
    conn_server_close(server_socket_unix);
    XCloseDisplay(shared_dpy);
    if (DGS_DEBUG)
	fprintf(stderr, "done\n");
    _exit(-1);
}

private void
proc_server_setup_signal(void)
{
    signal(SIGCHLD, proc_server_wait_agent);
    signal(SIGHUP, proc_server_finalize);
    signal(SIGINT, proc_server_finalize);
    signal(SIGTERM, proc_server_finalize);
    signal(SIGSEGV, proc_server_finalize);
    signal(SIGUSR1, proc_server_control);
}

/* print agent pids */
private void proc_server_control_pids(void);
private void
proc_server_control(int sig)
{
    proc_server_control_pids();
}

private void
proc_server_control_pids(void)
{
    if (0 == g_set_count(server_agent_pids)) {
	fprintf(stderr, "agent pids: no agents\n");
    } else {
	fprintf(stderr, "agent pids: \n");
	g_set_foreach(server_agent_pids, proc_agent_control_ppid_print, NULL);
    }
}
