Happy new year
[yaz-moved-to-github.git] / src / statserv.c
index fafff6b..ab15c21 100644 (file)
@@ -1,5 +1,5 @@
 /* This file is part of the YAZ toolkit.
- * Copyright (C) 1995-2008 Index Data
+ * Copyright (C) 1995-2011 Index Data
  * See the file LICENSE for details.
  */
 
@@ -8,6 +8,10 @@
  * \brief Implements GFS logic
  */
 
+#if HAVE_CONFIG_H
+#include <config.h>
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -42,8 +46,6 @@
 
 #if YAZ_POSIX_THREADS
 #include <pthread.h>
-#elif YAZ_GNU_THREADS
-#include <pth.h>
 #endif
 
 #include <fcntl.h>
@@ -53,6 +55,7 @@
 #include <yaz/comstack.h>
 #include <yaz/tcpip.h>
 #include <yaz/options.h>
+#include <yaz/errno.h>
 #ifdef USE_XTIMOSI
 #include <yaz/xmosi.h>
 #endif
@@ -60,6 +63,7 @@
 #include "eventl.h"
 #include "session.h"
 #include <yaz/statserv.h>
+#include <yaz/daemon.h>
 
 static IOCHAN pListener = NULL;
 
@@ -94,7 +98,7 @@ statserv_options_block control_block = {
     "",                         /* diagnostic output to stderr */
     "tcp:@:9999",               /* default listener port */
     PROTO_Z3950,                /* default application protocol */
-    15,                         /* idle timeout (minutes) */
+    900,                        /* idle timeout (seconds) */
     1024*1024,                  /* maximum PDU size (approx.) to allow */
     "default-config",           /* configuration name to pass to backend */
     "",                         /* set user id */
@@ -117,7 +121,8 @@ statserv_options_block control_block = {
     "",                         /* PID fname */
     0,                          /* background daemon */
     "",                         /* SSL certificate filename */
-    ""                          /* XML config filename */
+    "",                         /* XML config filename */
+    1                           /* keepalive */
 };
 
 static int max_sessions = 0;
@@ -208,6 +213,7 @@ static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
 }
 #endif
 
+#if YAZ_HAVE_XML2
 static struct gfs_server * gfs_server_new(void)
 {
     struct gfs_server *n = (struct gfs_server *)
@@ -222,12 +228,12 @@ static struct gfs_server * gfs_server_new(void)
     n->directory = 0;
     n->docpath = 0;
     n->stylesheet = 0;
-#if YAZ_HAVE_XML2
     n->retrieval = yaz_retrieval_create();
-#endif
     return n;
 }
+#endif
 
+#if YAZ_HAVE_XML2
 static struct gfs_listen * gfs_listen_new(const char *id, 
                                           const char *address)
 {
@@ -241,6 +247,7 @@ static struct gfs_listen * gfs_listen_new(const char *id,
     n->address = nmem_strdup(gfs_nmem, address);
     return n;
 }
+#endif
 
 static void gfs_server_chdir(struct gfs_server *gfs)
 {
@@ -326,11 +333,11 @@ int control_association(association *assoc, const char *host, int force_open)
     return 1;
 }
 
+#if YAZ_HAVE_XML2
 static void xml_config_read(void)
 {
     struct gfs_server **gfsp = &gfs_server_list;
     struct gfs_listen **gfslp = &gfs_listen_list;
-#if YAZ_HAVE_XML2
     xmlNodePtr ptr = xml_config_get_root();
 
     if (!ptr)
@@ -475,9 +482,9 @@ static void xml_config_read(void)
             gfsp = &(*gfsp)->next;
         }
     }
-#endif
     *gfsp = 0;
 }
+#endif
 
 static void xml_config_open(void)
 {
@@ -697,7 +704,7 @@ void statserv_remove(IOCHAN pIOChannel)
 }
 
 /* WIN32 statserv_closedown */
-void statserv_closedown()
+static void statserv_closedown()
 {
     /* Shouldn't do anything if we are not initialized */
     if (bInitialized)
@@ -767,9 +774,9 @@ void statserv_closedown()
     xml_config_close();
 }
 
-void __cdecl event_loop_thread (IOCHAN iochan)
+void __cdecl event_loop_thread(IOCHAN iochan)
 {
-    iochan_event_loop (&iochan);
+    iochan_event_loop(&iochan);
 }
 
 /* WIN32 listener */
@@ -850,27 +857,16 @@ static void listener(IOCHAN h, int event)
     }
 }
 
-int statserv_must_terminate(void)
-{
-    return 0;
-}
-
 #else /* ! WIN32 */
 
-static int term_flag = 0;
 /* To save having an #ifdef in event_loop we need to
    define this empty function 
 */
-int statserv_must_terminate(void)
-{
-    return term_flag;
-}
-
 void statserv_remove(IOCHAN pIOChannel)
 {
 }
 
-void statserv_closedown()
+static void statserv_closedown(void)
 {
     IOCHAN p;
 
@@ -882,12 +878,7 @@ void statserv_closedown()
     xml_config_close();
 }
 
-void sigterm(int sig)
-{
-    term_flag = 1;
-}
-
-static void *new_session (void *vp);
+static void *new_session(void *vp);
 static int no_sessions = 0;
 
 /* UNIX listener */
@@ -957,20 +948,8 @@ static void listener(IOCHAN h, int event)
         {
 #if YAZ_POSIX_THREADS
             pthread_t child_thread;
-            pthread_create (&child_thread, 0, new_session, new_line);
-            pthread_detach (child_thread);
-#elif YAZ_GNU_THREADS
-            pth_attr_t attr;
-            pth_t child_thread;
-
-            attr = pth_attr_new ();
-            pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
-            pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
-            pth_attr_set (attr, PTH_ATTR_NAME, "session");
-            yaz_log (YLOG_DEBUG, "pth_spawn begin");
-            child_thread = pth_spawn (attr, new_session, new_line);
-            yaz_log (YLOG_DEBUG, "pth_spawn finish");
-            pth_attr_destroy (attr);
+            pthread_create(&child_thread, 0, new_session, new_line);
+            pthread_detach(child_thread);
 #else
             new_session(new_line);
 #endif
@@ -990,9 +969,9 @@ static void listener(IOCHAN h, int event)
     }
 }
 
-static void *new_session (void *vp)
+static void *new_session(void *vp)
 {
-    char *a;
+    const char *a;
     association *newas;
     IOCHAN new_chan;
     COMSTACK new_line = (COMSTACK) vp;
@@ -1035,6 +1014,7 @@ static void *new_session (void *vp)
 #else
     a = 0;
 #endif
+    yaz_log_xml_errors(0, YLOG_WARN);
     yaz_log(log_session, "Session - OK %d %s %ld",
             no_sessions, a ? a : "[Unknown]", (long) getpid());
     if (max_sessions && no_sessions >= max_sessions)
@@ -1059,7 +1039,7 @@ static void inetd_connection(int what)
     COMSTACK line;
     IOCHAN chan;
     association *assoc;
-    char *addr;
+    const char *addr;
 
     if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
     {
@@ -1130,14 +1110,14 @@ static int add_listener(char *where, int listen_id)
         else
             yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
                     cs_strerror(l));
-        cs_close (l);
+        cs_close(l);
         return -1;
     }
     if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
                               EVENT_EXCEPT, listen_id)))
     {
         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
-        cs_close (l);
+        cs_close(l);
         return -1;
     }
     iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
@@ -1181,7 +1161,11 @@ statserv_options_block *statserv_getcontrol(void)
 
 void statserv_setcontrol(statserv_options_block *block)
 {
-    chdir(gfs_root_dir);
+    if (gfs_root_dir[0])
+    {
+        if (chdir(gfs_root_dir))
+            yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
+    }
 #ifdef WIN32
     if (init_control_tls)
         TlsSetValue(current_control_tls, block);
@@ -1197,7 +1181,13 @@ static void statserv_reset(void)
 {
 }
 
-int statserv_start(int argc, char **argv)
+static void daemon_handler(void *data)
+{
+    IOCHAN *pListener = data;
+    iochan_event_loop(pListener);
+}
+
+static int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
 {
     char sep;
 #ifdef WIN32
@@ -1212,7 +1202,7 @@ int statserv_start(int argc, char **argv)
 #else
     sep = '/';
 #endif
-    if ((me = strrchr (argv[0], sep)))
+    if ((me = strrchr(argv[0], sep)))
         me++; /* get the basename */
     else
         me = argv[0];
@@ -1225,123 +1215,38 @@ int statserv_start(int argc, char **argv)
     
     xml_config_bend_start();
 
+    if (control_block.inetd)
+    {
 #ifdef WIN32
-    xml_config_add_listeners();
-
-    yaz_log (log_server, "Starting server %s", me);
-    if (!pListener && *control_block.default_listen)
-        add_listener(control_block.default_listen, 0);
+        ; /* no inetd on Windows */
 #else
-/* UNIX */
-    if (control_block.inetd)
         inetd_connection(control_block.default_proto);
+#endif
+    }
     else
     {
-        static int hand[2];
-        if (control_block.background)
-        {
-            /* create pipe so that parent waits until child has created
-               PID (or failed) */
-            if (pipe(hand) < 0)
-            {
-                yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
-                return 1;
-            }
-            switch (fork())
-            {
-            case 0: 
-                break;
-            case -1:
-                return 1;
-            default:
-                close(hand[1]);
-                while(1)
-                {
-                    char dummy[1];
-                    int res = read(hand[0], dummy, 1);
-                    if (res < 0 && yaz_errno() != EINTR)
-                    {
-                        yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
-                        break;
-                    }
-                    else if (res >= 0)
-                        break;
-                }
-                close(hand[0]);
-                _exit(0);
-            }
-            /* child */
-            close(hand[0]);
-            if (setsid() < 0)
-                return 1;
-            
-            close(0);
-            close(1);
-            close(2);
-            open("/dev/null", O_RDWR);
-            dup(0); dup(0);
-        }
         xml_config_add_listeners();
 
         if (!pListener && *control_block.default_listen)
             add_listener(control_block.default_listen, 0);
-        
-        if (!pListener)
-            return 1;
 
-        if (*control_block.pid_fname)
-        {
-            FILE *f = fopen(control_block.pid_fname, "w");
-            if (!f)
-            {
-                yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s", 
-                        control_block.pid_fname);
-                exit(0);
-            }
-            fprintf(f, "%ld", (long) getpid());
-            fclose(f);
-        }
-        
-        if (control_block.background)
-            close(hand[1]);
-
-
-        yaz_log (log_server, "Starting server %s pid=%ld", programname, 
-                 (long) getpid());
-#if 0
-        sigset_t sigs_to_block;
-        
-        sigemptyset(&sigs_to_block);
-        sigaddset (&sigs_to_block, SIGTERM);
-        pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
-        /* missing... */
-#endif
+#ifndef WIN32
         if (control_block.dynamic)
             signal(SIGCHLD, catchchld);
-    }
-    signal (SIGPIPE, SIG_IGN);
-    signal (SIGTERM, sigterm);
-    if (*control_block.setuid)
-    {
-        struct passwd *pw;
-        
-        if (!(pw = getpwnam(control_block.setuid)))
-        {
-            yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
-            return(1);
-        }
-        if (setuid(pw->pw_uid) < 0)
-        {
-            yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
-            exit(1);
-        }
-    }
-/* UNIX */
 #endif
+    }
     if (pListener == NULL)
         return 1;
+    if (s)
+        yaz_sc_running(s);
     yaz_log(YLOG_DEBUG, "Entering event loop.");
-    return iochan_event_loop(&pListener);
+
+    yaz_daemon(programname,
+               (control_block.background ? YAZ_DAEMON_FORK : 0),
+               daemon_handler, &pListener,
+               *control_block.pid_fname ? control_block.pid_fname : 0,
+               *control_block.setuid ? control_block.setuid : 0);
+    return 0;
 }
 
 static void option_copy(char *dst, const char *src)
@@ -1357,10 +1262,9 @@ int check_options(int argc, char **argv)
 
     yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL)); 
 
-    yaz_log_xml_errors(0, YLOG_WARN);
     get_logbits(1); 
 
-    while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
+    while ((ret = options("1a:iszSTl:v:u:c:w:t:k:Kd:A:p:DC:f:m:r:",
                           argv, argc, &arg)) != -2)
     {
         switch (ret)
@@ -1377,8 +1281,8 @@ int check_options(int argc, char **argv)
             control_block.default_proto = PROTO_Z3950;
             break;
         case 's':
-            fprintf (stderr, "%s: SR protocol no longer supported\n", me);
-            exit (1);
+            fprintf(stderr, "%s: SR protocol no longer supported\n", me);
+            exit(1);
             break;
         case 'S':
             control_block.dynamic = 0;
@@ -1387,9 +1291,6 @@ int check_options(int argc, char **argv)
 #if YAZ_POSIX_THREADS
             control_block.dynamic = 0;
             control_block.threads = 1;
-#elif YAZ_GNU_THREADS
-            control_block.dynamic = 0;
-            control_block.threads = 1;
 #else
             fprintf(stderr, "%s: Threaded mode not available.\n", me);
             return 1;
@@ -1431,7 +1332,7 @@ int check_options(int argc, char **argv)
                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
                 return(1);
             }
-            control_block.idle_timeout = r;
+            control_block.idle_timeout = strchr(arg, 's') ? r : 60 * r;
             break;
         case  'k':
             if (!arg || !(r = atoi(arg)))
@@ -1441,6 +1342,9 @@ int check_options(int argc, char **argv)
             }
             control_block.maxrecordsize = r * 1024;
             break;
+        case 'K':
+            control_block.keepalive = 0;
+            break;
         case 'i':
             control_block.inetd = 1;
             break;
@@ -1493,12 +1397,6 @@ void statserv_sc_stop(yaz_sc_t s)
     statserv_reset();
 }
 
-int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
-{
-    yaz_sc_running(s);
-    return statserv_start(argc, argv);
-}
-
 int statserv_main(int argc, char **argv,
                   bend_initresult *(*bend_init)(bend_initrequest *r),
                   void (*bend_close)(void *handle))
@@ -1506,8 +1404,14 @@ int statserv_main(int argc, char **argv,
     int ret;
     struct statserv_options_block *cb = &control_block;
 
-    yaz_sc_t s = yaz_sc_create(cb->service_name,
-                               cb->service_display_name);
+    /* control block does not have service_name member on Unix */
+    yaz_sc_t s = yaz_sc_create(
+#ifdef WIN32
+        cb->service_name, cb->service_display_name
+#else
+        0, 0
+#endif
+        );
 
     cb->bend_init = bend_init;
     cb->bend_close = bend_close;
@@ -1520,6 +1424,7 @@ int statserv_main(int argc, char **argv,
 /*
  * Local variables:
  * c-basic-offset: 4
+ * c-file-style: "Stroustrup"
  * indent-tabs-mode: nil
  * End:
  * vim: shiftwidth=4 tabstop=8 expandtab