Back to index

webcit  8.12-dfsg
sysdep.c
Go to the documentation of this file.
00001 /*
00002  * WebCit "system dependent" code.
00003  *
00004  * Copyright (c) 1996-2012 by the citadel.org team
00005  *
00006  * This program is open source software; you can redistribute it and/or modify
00007  * it under the terms of the GNU General Public License, version 3.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  */
00014 
00015 #include "sysdep.h"
00016 #include <stdlib.h>
00017 #include <unistd.h>
00018 #include <stdio.h>
00019 #include <fcntl.h>
00020 #include <ctype.h>
00021 #include <signal.h>
00022 #include <sys/types.h>
00023 #include <sys/stat.h>
00024 #include <sys/wait.h>
00025 #include <sys/socket.h>
00026 #include <syslog.h>
00027 #include <sys/syslog.h>
00028 
00029 #if TIME_WITH_SYS_TIME
00030 # include <sys/time.h>
00031 # include <time.h>
00032 #else
00033 # if HAVE_SYS_TIME_H
00034 #  include <sys/time.h>
00035 # else
00036 #  include <time.h>
00037 # endif
00038 #endif
00039 
00040 #include <limits.h>
00041 #include <sys/resource.h>
00042 #include <netinet/in.h>
00043 #include <netinet/tcp.h>
00044 #include <arpa/inet.h>
00045 #include <netdb.h>
00046 #include <sys/un.h>
00047 #include <string.h>
00048 #include <pwd.h>
00049 #include <errno.h>
00050 #include <stdarg.h>
00051 #include <grp.h>
00052 #ifdef HAVE_PTHREAD_H
00053 #include <pthread.h>
00054 #endif
00055 #include "webcit.h"
00056 #include "sysdep.h"
00057 
00058 #ifdef HAVE_SYS_SELECT_H
00059 #include <sys/select.h>
00060 #endif
00061 
00062 #ifndef HAVE_SNPRINTF
00063 #include "snprintf.h"
00064 #endif
00065 #include "webserver.h"
00066 #include "modules_init.h"
00067 #if HAVE_BACKTRACE
00068 #include <execinfo.h>
00069 #endif
00070 
00071 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
00072 pthread_key_t MyConKey;                          /* TSD key for MyContext() */
00073 pthread_key_t MyReq;                      /* TSD key for MyReq() */
00074 int msock;                  /* master listening socket */
00075 int time_to_die = 0;            /* Nonzero if server is shutting down */
00076 
00077 extern void *context_loop(ParsedHttpHdrs *Hdr);
00078 extern void *housekeeping_loop(void);
00079 extern void do_housekeeping(void);
00080 
00081 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
00082 char file_crpt_file_key[PATH_MAX]="";
00083 char file_crpt_file_csr[PATH_MAX]="";
00084 char file_crpt_file_cer[PATH_MAX]="";
00085 
00086 const char editor_absolut_dir[PATH_MAX]=EDITORDIR;      /* nailed to what configure gives us. */
00087 char static_dir[PATH_MAX];         /* calculated on startup */
00088 char static_local_dir[PATH_MAX];          /* calculated on startup */
00089 char static_icon_dir[PATH_MAX];          /* where should we find our mime icons? */
00090 char  *static_dirs[]={                           /* needs same sort order as the web mapping */
00091        (char*)static_dir,                 /* our templates on disk */
00092        (char*)static_local_dir,           /* user provided templates disk */
00093        (char*)editor_absolut_dir,         /* the editor on disk */
00094        (char*)static_icon_dir                  /* our icons... */
00095 };
00096 
00097 int ExitPipe[2];
00098 
00099 void InitialiseSemaphores(void)
00100 {
00101        int i;
00102 
00103        /* Set up a bunch of semaphores to be used for critical sections */
00104        for (i=0; i<MAX_SEMAPHORES; ++i) {
00105               pthread_mutex_init(&Critters[i], NULL);
00106        }
00107 
00108        if (pipe(ExitPipe))
00109        {
00110               syslog(2, "Failed to open exit pipe: %d [%s]\n", 
00111                      errno, 
00112                      strerror(errno));
00113               
00114               exit(-1);
00115        }
00116 }
00117 
00118 /*
00119  * Obtain a semaphore lock to begin a critical section.
00120  */
00121 void begin_critical_section(int which_one)
00122 {
00123        pthread_mutex_lock(&Critters[which_one]);
00124 }
00125 
00126 /*
00127  * Release a semaphore lock to end a critical section.
00128  */
00129 void end_critical_section(int which_one)
00130 {
00131        pthread_mutex_unlock(&Critters[which_one]);
00132 }
00133 
00134 
00135 void ShutDownWebcit(void)
00136 {
00137        free_zone_directory ();
00138        icaltimezone_release_zone_tab ();
00139        icalmemory_free_ring ();
00140        ShutDownLibCitadel ();
00141        shutdown_modules ();
00142 #ifdef HAVE_OPENSSL
00143        if (is_https) {
00144               shutdown_ssl();
00145        }
00146 #endif
00147 }
00148 
00149 /*
00150  * Entry point for worker threads
00151  */
00152 void worker_entry(void)
00153 {
00154        int ssock;
00155        int i = 0;
00156        int fail_this_transaction = 0;
00157        ParsedHttpHdrs Hdr;
00158 
00159        memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
00160        Hdr.HR.eReqType = eGET;
00161        http_new_modules(&Hdr);     
00162 
00163        do {
00164               /* Each worker thread blocks on accept() while waiting for something to do. */
00165               fail_this_transaction = 0;
00166               ssock = -1; 
00167               errno = EAGAIN;
00168               do {
00169                      fd_set wset;
00170                      --num_threads_executing;
00171                         FD_ZERO(&wset);
00172                         FD_SET(msock, &wset);
00173                         FD_SET(ExitPipe[1], &wset);
00174 
00175                         select(msock + 1, NULL, &wset, NULL, NULL);
00176                      if (time_to_die)
00177                             break;
00178 
00179                      ssock = accept(msock, NULL, 0);
00180                      ++num_threads_executing;
00181                      if (ssock < 0) fail_this_transaction = 1;
00182               } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
00183 
00184               if ((msock == -1)||(time_to_die))
00185               {/* ok, we're going down. */
00186                      int shutdown = 0;
00187 
00188                      /* The first thread to get here will have to do the cleanup.
00189                       * Make sure it's really just one.
00190                       */
00191                      begin_critical_section(S_SHUTDOWN);
00192                      if (msock == -1)
00193                      {
00194                             msock = -2;
00195                             shutdown = 1;
00196                      }
00197                      end_critical_section(S_SHUTDOWN);
00198                      if (shutdown == 1)
00199                      {/* we're the one to cleanup the mess. */
00200                             http_destroy_modules(&Hdr);
00201                             syslog(2, "I'm master shutdown: tagging sessions to be killed.\n");
00202                             shutdown_sessions();
00203                             syslog(2, "master shutdown: waiting for others\n");
00204                             sleeeeeeeeeep(1); /* wait so some others might finish... */
00205                             syslog(2, "master shutdown: cleaning up sessions\n");
00206                             do_housekeeping();
00207                             syslog(2, "master shutdown: cleaning up libical\n");
00208 
00209                             ShutDownWebcit();
00210 
00211                             syslog(2, "master shutdown exiting.\n");                       
00212                             exit(0);
00213                      }
00214                      break;
00215               }
00216               if (ssock < 0 ) continue;
00217 
00218               check_thread_pool_size();
00219 
00220               /* Now do something. */
00221               if (msock < 0) {
00222                      if (ssock > 0) close (ssock);
00223                      syslog(2, "in between.");
00224                      pthread_exit(NULL);
00225               } else {
00226                      /* Got it? do some real work! */
00227                      /* Set the SO_REUSEADDR socket option */
00228                      i = 1;
00229                      setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
00230 
00231                      /* If we are an HTTPS server, go crypto now. */
00232 #ifdef HAVE_OPENSSL
00233                      if (is_https) {
00234                             if (starttls(ssock) != 0) {
00235                                    fail_this_transaction = 1;
00236                                    close(ssock);
00237                             }
00238                      }
00239                      else 
00240 #endif
00241                      {
00242                             int fdflags; 
00243                             fdflags = fcntl(ssock, F_GETFL);
00244                             if (fdflags < 0)
00245                                    syslog(1, "unable to get server socket flags! %s \n",
00246                                           strerror(errno));
00247                             fdflags = fdflags | O_NONBLOCK;
00248                             if (fcntl(ssock, F_SETFL, fdflags) < 0)
00249                                    syslog(1, "unable to set server socket nonblocking flags! %s \n",
00250                                           strerror(errno));
00251                      }
00252 
00253                      if (fail_this_transaction == 0) {
00254                             Hdr.http_sock = ssock;
00255 
00256                             /* Perform an HTTP transaction... */
00257                             context_loop(&Hdr);
00258 
00259                             /* Shut down SSL/TLS if required... */
00260 #ifdef HAVE_OPENSSL
00261                             if (is_https) {
00262                                    endtls();
00263                             }
00264 #endif
00265 
00266                             /* ...and close the socket. */
00267                             if (Hdr.http_sock > 0) {
00268                                    lingering_close(ssock);
00269                             }
00270                             http_detach_modules(&Hdr);
00271 
00272                      }
00273 
00274               }
00275 
00276        } while (!time_to_die);
00277 
00278        http_destroy_modules(&Hdr);
00279        syslog(1, "Thread exiting.\n");
00280        pthread_exit(NULL);
00281 }
00282 
00283 
00284 /*
00285  * Shut us down the regular way.
00286  * signum is the signal we want to forward
00287  */
00288 pid_t current_child;
00289 void graceful_shutdown_watcher(int signum) {
00290        syslog(1, "Watcher thread exiting.\n");
00291        write(ExitPipe[0], HKEY("                              "));
00292        kill(current_child, signum);
00293        if (signum != SIGHUP)
00294               exit(0);
00295 }
00296 
00297 
00298 /*
00299  * Shut us down the regular way.
00300  * signum is the signal we want to forward
00301  */
00302 pid_t current_child;
00303 void graceful_shutdown(int signum) {
00304        FILE *FD;
00305        int fd;
00306 
00307        syslog(1, "WebCit is being shut down on signal %d.\n", signum);
00308        fd = msock;
00309        msock = -1;
00310        time_to_die = 1;
00311        FD=fdopen(fd, "a+");
00312        fflush (FD);
00313        fclose (FD);
00314        close(fd);
00315        write(ExitPipe[0], HKEY("                              "));
00316 }
00317 
00318 
00319 /*
00320  * Start running as a daemon.
00321  */
00322 void start_daemon(char *pid_file) 
00323 {
00324        int status = 0;
00325        pid_t child = 0;
00326        FILE *fp;
00327        int do_restart = 0;
00328 
00329        current_child = 0;
00330 
00331        /* Close stdin/stdout/stderr and replace them with /dev/null.
00332         * We don't just call close() because we don't want these fd's
00333         * to be reused for other files.
00334         */
00335        chdir("/");
00336 
00337        signal(SIGHUP, SIG_IGN);
00338        signal(SIGINT, SIG_IGN);
00339        signal(SIGQUIT, SIG_IGN);
00340 
00341        child = fork();
00342        if (child != 0) {
00343               exit(0);
00344        }
00345 
00346        setsid();
00347        umask(0);
00348        freopen("/dev/null", "r", stdin);
00349        freopen("/dev/null", "w", stdout);
00350        freopen("/dev/null", "w", stderr);
00351        signal(SIGTERM, graceful_shutdown_watcher);
00352        signal(SIGHUP, graceful_shutdown_watcher);
00353 
00354        do {
00355               current_child = fork();
00356 
00357        
00358               if (current_child < 0) {
00359                      perror("fork");
00360                      ShutDownLibCitadel ();
00361                      exit(errno);
00362               }
00363        
00364               else if (current_child == 0) {     /* child process */
00365                      signal(SIGHUP, graceful_shutdown);
00366 
00367                      return; /* continue starting webcit. */
00368               }
00369               else { /* watcher process */
00370                      if (pid_file) {
00371                             fp = fopen(pid_file, "w");
00372                             if (fp != NULL) {
00373                                    fprintf(fp, "%d\n", getpid());
00374                                    fclose(fp);
00375                             }
00376                      }
00377                      waitpid(current_child, &status, 0);
00378               }
00379 
00380               do_restart = 0;
00381 
00382               /* Did the main process exit with an actual exit code? */
00383               if (WIFEXITED(status)) {
00384 
00385                      /* Exit code 0 means the watcher should exit */
00386                      if (WEXITSTATUS(status) == 0) {
00387                             do_restart = 0;
00388                      }
00389 
00390                      /* Exit code 101-109 means the watcher should exit */
00391                      else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
00392                             do_restart = 0;
00393                      }
00394 
00395                      /* Any other exit code means we should restart. */
00396                      else {
00397                             do_restart = 1;
00398                      }
00399               }
00400 
00401               /* Any other type of termination (signals, etc.) should also restart. */
00402               else {
00403                      do_restart = 1;
00404               }
00405 
00406        } while (do_restart);
00407 
00408        if (pid_file) {
00409               unlink(pid_file);
00410        }
00411        ShutDownLibCitadel ();
00412        exit(WEXITSTATUS(status));
00413 }
00414 
00415 
00416 /*
00417  * Spawn an additional worker thread into the pool.
00418  */
00419 void spawn_another_worker_thread()
00420 {
00421        pthread_t SessThread;       /* Thread descriptor */
00422        pthread_attr_t attr; /* Thread attributes */
00423        int ret;
00424 
00425        ++num_threads_existing;
00426        ++num_threads_executing;
00427 
00428        /* set attributes for the new thread */
00429        pthread_attr_init(&attr);
00430        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00431 
00432        /*
00433         * Our per-thread stacks need to be bigger than the default size,
00434         * otherwise the MIME parser crashes on FreeBSD.
00435         */
00436        if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
00437               syslog(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
00438               pthread_attr_destroy(&attr);
00439        }
00440 
00441        /* now create the thread */
00442        if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
00443               syslog(1, "Can't create thread: %s\n", strerror(errno));
00444        }
00445 
00446        /* free up the attributes */
00447        pthread_attr_destroy(&attr);
00448 }
00449 
00450 
00451 void
00452 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
00453 {
00454        char dirbuffer[PATH_MAX]="";
00455        /* calculate all our path on a central place */
00456     /* where to keep our config */
00457        
00458 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
00459        snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
00460                       (home&!relh)?webcitdir:basedir, \
00461              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
00462              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
00463                       relhome, \
00464              (relhome[0]!='\0')?"/":"",\
00465                       dirbuffer,\
00466                       (dirbuffer[0]!='\0')?"/":"");
00467        basedir=RUNDIR;
00468        COMPUTE_DIRECTORY(socket_dir);
00469        basedir=WWWDIR "/static";
00470        COMPUTE_DIRECTORY(static_dir);
00471        basedir=WWWDIR "/static/icons";
00472        COMPUTE_DIRECTORY(static_icon_dir);
00473        basedir=WWWDIR "/static.local";
00474        COMPUTE_DIRECTORY(static_local_dir);
00475        StripSlashes(static_dir, 1);
00476        StripSlashes(static_icon_dir, 1);
00477        StripSlashes(static_local_dir, 1);
00478 
00479        snprintf(file_crpt_file_key,
00480                sizeof file_crpt_file_key, 
00481                "%s/citadel.key",
00482                ctdl_key_dir);
00483        snprintf(file_crpt_file_csr,
00484                sizeof file_crpt_file_csr, 
00485                "%s/citadel.csr",
00486                ctdl_key_dir);
00487        snprintf(file_crpt_file_cer,
00488                sizeof file_crpt_file_cer, 
00489                "%s/citadel.cer",
00490                ctdl_key_dir);
00491 
00492        /* we should go somewhere we can leave our coredump, if enabled... */
00493        syslog(9, "Changing directory to %s\n", socket_dir);
00494        if (chdir(webcitdir) != 0) {
00495               perror("chdir");
00496        }
00497 }
00498 
00499 void drop_root(uid_t UID)
00500 {
00501        struct passwd pw, *pwp = NULL;
00502 
00503        /*
00504         * Now that we've bound the sockets, change to the Citadel user id and its
00505         * corresponding group ids
00506         */
00507        if (UID != -1) {
00508               
00509 #ifdef HAVE_GETPWUID_R
00510 #ifdef SOLARIS_GETPWUID
00511               pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
00512 #else /* SOLARIS_GETPWUID */
00513               getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
00514 #endif /* SOLARIS_GETPWUID */
00515 #else /* HAVE_GETPWUID_R */
00516               pwp = NULL;
00517 #endif /* HAVE_GETPWUID_R */
00518 
00519               if (pwp == NULL)
00520                      syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n"
00521                             "Group IDs will be incorrect.\n", UID,
00522                             strerror(errno));
00523               else {
00524                      initgroups(pw.pw_name, pw.pw_gid);
00525                      if (setgid(pw.pw_gid))
00526                             syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
00527                                    strerror(errno));
00528               }
00529               syslog(LOG_INFO, "Changing uid to %ld\n", (long)UID);
00530               if (setuid(UID) != 0) {
00531                      syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
00532               }
00533 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
00534               prctl(PR_SET_DUMPABLE, 1);
00535 #endif
00536        }
00537 }
00538 
00539 
00540 /*
00541  * print the actual stack frame.
00542  */
00543 void wc_backtrace(void)
00544 {
00545 #ifdef HAVE_BACKTRACE
00546        void *stack_frames[50];
00547        size_t size, i;
00548        char **strings;
00549 
00550 
00551        size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
00552        strings = backtrace_symbols(stack_frames, size);
00553        for (i = 0; i < size; i++) {
00554               if (strings != NULL)
00555                      syslog(1, "%s\n", strings[i]);
00556               else
00557                      syslog(1, "%p\n", stack_frames[i]);
00558        }
00559        free(strings);
00560 #endif
00561 }