Copyright dates are now 2008.
[citadel.git] / webcit / webserver.c
index 038ab57ae2c19cc6d18ae89facc2967943222502..83554298d54c43164a64996c97adb7ef6ca0ad2c 100644 (file)
@@ -21,43 +21,53 @@ int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
 #endif
 
 int verbosity = 9;             /**< Logging level */
-int msock;                         /**< master listening socket */
+int msock;                     /**< master listening socket */
 int is_https = 0;              /**< Nonzero if I am an HTTPS service */
 int follow_xff = 0;            /**< Follow X-Forwarded-For: header */
-int home_specified = 0; /**< did the user specify a homedir? */
+int home_specified = 0;                /**< did the user specify a homedir? */
+int time_to_die = 0;            /**< Nonzero if server is shutting down */
 extern void *context_loop(int);
 extern void *housekeeping_loop(void);
 extern pthread_mutex_t SessionListMutex;
 extern pthread_key_t MyConKey;
 
-char socket_dir[PATH_MAX];      /**< where to talk to our citadel server */
-static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /**< nailed to what configure gives us. */
-static char static_dir[PATH_MAX]; /**< calculated on startup */
-char  *static_dirs[]={ /**< needs same sort order as the web mapping */
-       (char*)static_dir,                  /** our templates on disk */
-       (char*)editor_absolut_dir           /** the editor on disk */
+
+char ctdl_key_dir[PATH_MAX]=SSL_DIR;
+char file_crpt_file_key[PATH_MAX]="";
+char file_crpt_file_csr[PATH_MAX]="";
+char file_crpt_file_cer[PATH_MAX]="";
+
+char socket_dir[PATH_MAX];                     /**< where to talk to our citadel server */
+static const char editor_absolut_dir[PATH_MAX]=EDITORDIR;      /**< nailed to what configure gives us. */
+static char static_dir[PATH_MAX];              /**< calculated on startup */
+static char static_local_dir[PATH_MAX];                /**< calculated on startup */
+char  *static_dirs[]={                         /**< needs same sort order as the web mapping */
+       (char*)static_dir,                      /** our templates on disk */
+       (char*)static_local_dir,                /** user provided templates disk */
+       (char*)editor_absolut_dir               /** the editor on disk */
 };
-int ndirs=2; //sizeof(static_content_dirs);//sizeof(char *);
 
 /**
  * Subdirectories from which the client may request static content
+ *
+ * (If you add more, remember to increment 'ndirs' below)
  */
 char *static_content_dirs[] = {
        "static",                     /** static templates */
-       "tiny_mce"                    /** the JS editor */
+       "static.local",               /** site local static templates */
+       "tiny_mce"                    /** rich text editor */
 };
 
+int ndirs=3;
 
 
-char *server_cookie = NULL; /**< our Cookie connection to the client */
-
+char *server_cookie = NULL;    /**< our Cookie connection to the client */
 int http_port = PORT_NUM;      /**< Port to listen on */
-
-char *ctdlhost = DEFAULT_HOST; /**< our name */
-char *ctdlport = DEFAULT_PORT; /**< our Port */
-int setup_wizard = 0;          /**< should we run the setup wizard? \todo */
-char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
-int running_as_daemon = 0;     /**< should we deamonize on startup? */
+char *ctdlhost = DEFAULT_HOST; /**< our name */
+char *ctdlport = DEFAULT_PORT; /**< our Port */
+int setup_wizard = 0;          /**< should we run the setup wizard? \todo */
+char wizard_filename[PATH_MAX];        /**< where's the setup wizard? */
+int running_as_daemon = 0;     /**< should we deamonize on startup? */
 
 
 /** 
@@ -65,7 +75,7 @@ int running_as_daemon = 0;     /**< should we deamonize on startup? */
  * a TCP port.  The server shuts down if the bind fails.
  * \param ip_addr ip to bind to
  * \param port_number the port to bind to 
- * \param queue_len the size of the input queue ????
+ * \param queue_len Number of incoming connections to allow in the queue
  */
 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
 {
@@ -86,26 +96,28 @@ int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
 
        if (port_number == 0) {
                lprintf(1, "Cannot start: no port number specified.\n");
-               exit(1);
+               exit(WC_EXIT_BIND);
        }
        sin.sin_port = htons((u_short) port_number);
 
        s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
        if (s < 0) {
                lprintf(1, "Can't create a socket: %s\n", strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
        /** Set some socket options that make sense. */
        i = 1;
        setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
 
+       fcntl(s, F_SETFL, O_NONBLOCK);/// TODO
+       
        if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
                lprintf(1, "Can't bind: %s\n", strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
        if (listen(s, queue_len) < 0) {
                lprintf(1, "Can't listen: %s\n", strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
        return (s);
 }
@@ -115,7 +127,7 @@ int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
 /**
  * \brief Create a Unix domain socket and listen on it
  * \param sockpath file name of the unix domain socket
- * \param queue_len queue size of the kernel fifo????
+ * \param queue_len Number of incoming connections to allow in the queue
  */
 int ig_uds_server(char *sockpath, int queue_len)
 {
@@ -131,7 +143,7 @@ int ig_uds_server(char *sockpath, int queue_len)
        if (i != 0) if (errno != ENOENT) {
                lprintf(1, "citserver: can't unlink %s: %s\n",
                        sockpath, strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
 
        memset(&addr, 0, sizeof(addr));
@@ -142,19 +154,19 @@ int ig_uds_server(char *sockpath, int queue_len)
        if (s < 0) {
                lprintf(1, "citserver: Can't create a socket: %s\n",
                        strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
 
        if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
                lprintf(1, "citserver: Can't bind: %s\n",
                        strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
 
        if (listen(s, actual_queue_len) < 0) {
                lprintf(1, "citserver: Can't listen: %s\n",
                        strerror(errno));
-               exit(errno);
+               exit(WC_EXIT_BIND);
        }
 
        chmod(sockpath, 0777);
@@ -166,10 +178,10 @@ int ig_uds_server(char *sockpath, int queue_len)
 
 /**
  * \brief Read data from the client socket.
- * \param sock socket fd to read from ???
+ * \param sock socket fd to read from
  * \param buf buffer to read into 
- * \param bytes how large is the read buffer?
- * \param timeout how long should we wait for input?
+ * \param bytes number of bytes to read
+ * \param timeout Number of seconds to wait before timing out
  * \return values are\
  *      1       Requested number of bytes has been read.\
  *      0       Request timed out.\
@@ -265,7 +277,7 @@ ssize_t client_write(const void *buf, size_t count)
 }
 
 /**
- * \brief what burst???
+ * \brief Begin buffering HTTP output so we can transmit it all in one write operation later.
  */
 void begin_burst(void)
 {
@@ -287,10 +299,10 @@ void begin_burst(void)
 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
 #define OS_CODE 0x03   /**< unix */
 int ZEXPORT compress_gzip(Bytef * dest,         /**< compressed buffer*/
-                                                 uLongf * destLen,     /**< length of the compresed data */
-                                                 const Bytef * source, /**< source to encode */
-                                                 uLong sourceLen,      /**< length of the source to encode */
-                                                 int level)            /**< what level??? */
+                         uLongf * destLen,     /**< length of the compresed data */
+                         const Bytef * source, /**< source to encode */
+                         uLong sourceLen,      /**< length of source to encode */
+                         int level)            /**< compression level */
 {
        const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
 
@@ -344,7 +356,7 @@ int ZEXPORT compress_gzip(Bytef * dest,         /**< compressed buffer*/
 #endif
 
 /**
- * \brief what burst???
+ * \brief Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
  */
 void end_burst(void)
 {
@@ -362,7 +374,7 @@ void end_burst(void)
        WC->burst = NULL;
 
 #ifdef HAVE_ZLIB
-       /* Handle gzip compression */
+       /* Perform gzip compression, if enabled and supported by client */
        if (WC->gzip_ok) {
                char *compressed_data = NULL;
                uLongf compressed_len;
@@ -382,7 +394,7 @@ void end_burst(void)
                        free(compressed_data);
                }
        }
-#endif                         /* HAVE_ZLIB */
+#endif /* HAVE_ZLIB */
 
        wprintf("Content-length: %d\r\n\r\n", the_len);
        client_write(the_data, the_len);
@@ -396,9 +408,9 @@ void end_burst(void)
  * \brief Read data from the client socket with default timeout.
  * (This is implemented in terms of client_read_to() and could be
  * justifiably moved out of sysdep.c)
- * \param sock the socket fd to read from???
+ * \param sock the socket fd to read from
  * \param buf the buffer to write to
- * \param bytes how large is the buffer
+ * \param bytes Number of bytes to read
  */
 int client_read(int sock, char *buf, int bytes)
 {
@@ -410,10 +422,10 @@ int client_read(int sock, char *buf, int bytes)
  * \brief Get a LF-terminated line of text from the client.
  * (This is implemented in terms of client_read() and could be
  * justifiably moved out of sysdep.c)
- * \param sock socket fd to get client line from???
+ * \param sock socket fd to get client line from
  * \param buf buffer to write read data to
  * \param bufsiz how many bytes to read
- * \return  numer of bytes read???
+ * \return  number of bytes read???
  */
 int client_getln(int sock, char *buf, int bufsiz)
 {
@@ -439,8 +451,8 @@ int client_getln(int sock, char *buf, int bufsiz)
         * Strip any trailing non-printable characters.
         */
        buf[i] = 0;
-       while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
-               buf[strlen(buf) - 1] = 0;
+       while ((i > 0) && (!isprint(buf[i - 1]))) {
+               buf[--i] = 0;
        }
        return (retval);
 }
@@ -450,11 +462,33 @@ int client_getln(int sock, char *buf, int bufsiz)
  * param signum the signal we want to forward
  */
 pid_t current_child;
-void graceful_shutdown(int signum) {
+void graceful_shutdown_watcher(int signum) {
+       lprintf (1, "bye; shutting down watcher.");
        kill(current_child, signum);
        exit(0);
 }
 
+/**
+ * \brief shut us down the regular way.
+ * param signum the signal we want to forward
+ */
+pid_t current_child;
+void graceful_shutdown(int signum) {
+//     kill(current_child, signum);
+       char wd[SIZ];
+       FILE *FD;
+       int fd;
+       getcwd(wd, SIZ);
+       lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
+       fd = msock;
+       msock = -1;
+       time_to_die = 1;
+       FD=fdopen(fd, "a+");
+       fflush (FD);
+       fclose (FD);
+       close(fd);
+}
+
 
 /**
  * \brief      Start running as a daemon.  
@@ -465,7 +499,7 @@ void graceful_shutdown(int signum) {
 /*
  * Start running as a daemon.
  */
-void start_daemon(int do_close_stdio, char *pid_file) 
+void start_daemon(char *pid_file) 
 {
        int status = 0;
        pid_t child = 0;
@@ -480,31 +514,26 @@ void start_daemon(int do_close_stdio, char *pid_file)
         */
        chdir("/");
 
+       signal(SIGHUP, SIG_IGN);
+       signal(SIGINT, SIG_IGN);
+       signal(SIGQUIT, SIG_IGN);
+
        child = fork();
        if (child != 0) {
-               fp = fopen(pid_file, "w");
-               if (fp != NULL) {
-                       fprintf(fp, "%d\n", child);
-                       fclose(fp);
-               }
                exit(0);
        }
-       
-       signal(SIGHUP, SIG_IGN);
-       signal(SIGINT, SIG_IGN);
-       signal(SIGQUIT, SIG_IGN);
 
        setsid();
        umask(0);
-       if (do_close_stdio) {
-               freopen("/dev/null", "r", stdin);
-               freopen("/dev/null", "w", stdout);
-               freopen("/dev/null", "w", stderr);
-       }
+       freopen("/dev/null", "r", stdin);
+       freopen("/dev/null", "w", stdout);
+       freopen("/dev/null", "w", stderr);
+///    signal(SIGTERM, graceful_shutdown_watcher);
+       signal(SIGHUP, graceful_shutdown_watcher);
+
        do {
                current_child = fork();
 
-               signal(SIGTERM, graceful_shutdown);
        
                if (current_child < 0) {
                        perror("fork");
@@ -512,10 +541,22 @@ void start_daemon(int do_close_stdio, char *pid_file)
                }
        
                else if (current_child == 0) {
-                       return; /* continue starting citadel. */
+////                   signal(SIGTERM, graceful_shutdown);
+                       signal(SIGHUP, graceful_shutdown);
+
+                       return; /* continue starting webcit. */
                }
        
                else {
+////                   signal(SIGTERM, SIG_IGN);
+                       signal(SIGHUP, SIG_IGN);
+                       if (pid_file) {
+                               fp = fopen(pid_file, "w");
+                               if (fp != NULL) {
+                                       fprintf(fp, "%d\n", current_child);
+                                       fclose(fp);
+                               }
+                       }
                        waitpid(current_child, &status, 0);
                }
 
@@ -547,7 +588,9 @@ void start_daemon(int do_close_stdio, char *pid_file)
 
        } while (do_restart);
 
-       unlink(pid_file);
+       if (pid_file) {
+               unlink(pid_file);
+       }
        exit(WEXITSTATUS(status));
 }
 
@@ -599,14 +642,14 @@ int main(int argc, char **argv)
        pthread_attr_t attr;    /**< Thread attributes */
        int a, i;                       /**< General-purpose variables */
        char tracefile[PATH_MAX];
-       char ip_addr[256];
+       char ip_addr[256]="0.0.0.0";
        char dirbuffer[PATH_MAX]="";
        int relh=0;
        int home=0;
        int home_specified=0;
        char relhome[PATH_MAX]="";
        char webcitdir[PATH_MAX] = DATADIR;
-       char pidfile[PATH_MAX] = "";
+       char *pidfile = NULL;
        char *hdir;
        const char *basedir;
 #ifdef ENABLE_NLS
@@ -619,9 +662,9 @@ int main(int argc, char **argv)
 
        /** Parse command line */
 #ifdef HAVE_OPENSSL
-       while ((a = getopt(argc, argv, "h:i:p:t:x:d:cfs")) != EOF)
+       while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
 #else
-       while ((a = getopt(argc, argv, "h:i:p:t:x:d:cf")) != EOF)
+       while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
 #endif
                switch (a) {
                case 'h':
@@ -637,8 +680,10 @@ int main(int argc, char **argv)
                        home=1;
                        break;
                case 'd':
-                       hdir = strdup(optarg);
-                       safestrncpy(pidfile, hdir,sizeof pidfile);
+                       running_as_daemon = 1;
+                       break;
+               case 'D':
+                       pidfile = strdup(optarg);
                        running_as_daemon = 1;
                        break;
                case 'i':
@@ -700,12 +745,16 @@ int main(int argc, char **argv)
 
        /* daemonize, if we were asked to */
        if (running_as_daemon) {
-               start_daemon(0, pidfile);
+               start_daemon(pidfile);
+       }
+       else {
+///            signal(SIGTERM, graceful_shutdown);
+               signal(SIGHUP, graceful_shutdown);
        }
 
        /** Tell 'em who's in da house */
-       lprintf(1, SERVER "\n");
-       lprintf(1, "Copyright (C) 1996-2006 by the Citadel development team.\n"
+       lprintf(1, PACKAGE_STRING "\n");
+       lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
                "This software is distributed under the terms of the "
                "GNU General Public License.\n\n"
        );
@@ -716,7 +765,7 @@ int main(int argc, char **argv)
        initialize_locales();
        locale = setlocale(LC_ALL, "");
        mo = malloc(strlen(webcitdir) + 20);
-       lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR));
+       lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
        free(mo);
        lprintf(9, "Text domain: %s\n", textdomain("webcit"));
        lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
@@ -737,8 +786,24 @@ int main(int argc, char **argv)
                         (dirbuffer[0]!='\0')?"/":"");
        basedir=RUNDIR;
        COMPUTE_DIRECTORY(socket_dir);
-       basedir=DATADIR;
+       basedir=WWWDIR "/static";
        COMPUTE_DIRECTORY(static_dir);
+       basedir=WWWDIR "/static.local";
+       COMPUTE_DIRECTORY(static_local_dir);
+
+       snprintf(file_crpt_file_key,
+                sizeof file_crpt_file_key, 
+                "%s/citadel.key",
+                ctdl_key_dir);
+       snprintf(file_crpt_file_csr,
+                sizeof file_crpt_file_csr, 
+                "%s/citadel.csr",
+                ctdl_key_dir);
+       snprintf(file_crpt_file_cer,
+                sizeof file_crpt_file_cer, 
+                "%s/citadel.cer",
+                ctdl_key_dir);
+
        /** we should go somewhere we can leave our coredump, if enabled... */
        lprintf(9, "Changing directory to %s\n", socket_dir);
        if (chdir(webcitdir) != 0) {
@@ -755,6 +820,7 @@ int main(int argc, char **argv)
        if (pthread_key_create(&MyConKey, NULL) != 0) {
                lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
        }
+       InitialiseSemaphores ();
 
        /**
         * Set up a place to put thread-specific SSL data.
@@ -774,7 +840,7 @@ int main(int argc, char **argv)
         * exits if it doesn't succeed.
         */
 
-       if (strlen(uds_listen_path) > 0) {
+       if (!IsEmptyStr(uds_listen_path)) {
                lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
                msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
        }
@@ -824,17 +890,81 @@ void worker_entry(void)
 {
        int ssock;
        int i = 0;
-       int time_to_die = 0;
        int fail_this_transaction = 0;
+       int ret;
+       struct timeval tv;
+       fd_set readset, tempset;
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 10000;
+       FD_ZERO(&readset);
+       FD_SET(msock, &readset);
 
        do {
                /** Only one thread can accept at a time */
                fail_this_transaction = 0;
-               ssock = accept(msock, NULL, 0);
-               if (ssock < 0) {
-                       lprintf(2, "accept() failed: %s\n",
-                               strerror(errno));
-               } else {
+               ssock = -1; 
+               errno = EAGAIN;
+               do {
+                       ret = -1; /* just one at once should select... */
+                       begin_critical_section(S_SELECT);
+
+                       FD_ZERO(&tempset);
+                       if (msock > 0) FD_SET(msock, &tempset);
+                       tv.tv_sec = 0;
+                       tv.tv_usec = 10000;
+                       if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
+                       end_critical_section(S_SELECT);
+                       if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
+                       {// EINTR and EAGAIN are thrown but not of interest.
+                               lprintf(2, "accept() failed:%d %s\n",
+                                       errno, strerror(errno));
+                       }
+                       else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
+                       {// Successfully selected, and still not shutting down? Accept!
+                               ssock = accept(msock, NULL, 0);
+                       }
+                       
+               } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
+
+               if ((msock == -1)||(time_to_die))
+               {// ok, we're going down.
+                       int shutdown = 0;
+
+                       /* the first to come here will have to do the cleanup.
+                        * make shure its realy just one.
+                        */
+                       begin_critical_section(S_SHUTDOWN);
+                       if (msock == -1)
+                       {
+                               msock = -2;
+                               shutdown = 1;
+                       }
+                       end_critical_section(S_SHUTDOWN);
+                       if (shutdown == 1)
+                       {// we're the one to cleanup the mess.
+                               lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
+                               shutdown_sessions();
+                               lprintf(2, "master shutdown: waiting for others\n");
+                               sleeeeeeeeeep(1); // wait so some others might finish...
+                               lprintf(2, "master shutdown: cleaning up sessions\n");
+                               do_housekeeping();
+#ifdef WEBCIT_WITH_CALENDAR_SERVICE
+                               free_zone_directory ();
+                               icaltimezone_release_zone_tab ();
+#endif
+                               lprintf(2, "master shutdown exiting!.\n");                              
+                               exit(0);
+                       }
+                       break;
+               }
+               if (ssock < 0 ) continue;
+
+               if (msock < 0) {
+                       if (ssock > 0) close (ssock);
+                       lprintf(2, "inbetween.");
+                       pthread_exit(NULL);
+               } else { // Got it? do some real work!
                        /** Set the SO_REUSEADDR socket option */
                        i = 1;
                        setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
@@ -870,6 +1000,7 @@ void worker_entry(void)
 
        } while (!time_to_die);
 
+       lprintf (1, "bye\n");
        pthread_exit(NULL);
 }