* WebCit thread pool is no longer tied to the number of server sessions. MIN_WORKER_...
[citadel.git] / webcit / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14 #include "sysdep.h"
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <stdio.h>
18 #include <fcntl.h>
19 #include <ctype.h>
20 #include <signal.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
24 #include <sys/socket.h>
25 #include <syslog.h>
26 #include <sys/syslog.h>
27
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 #  include <sys/time.h>
34 # else
35 #  include <time.h>
36 # endif
37 #endif
38
39 #include <limits.h>
40 #include <sys/resource.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #include <arpa/inet.h>
44 #include <netdb.h>
45 #include <sys/un.h>
46 #include <string.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <stdarg.h>
50 #include <grp.h>
51 #ifdef HAVE_PTHREAD_H
52 #include <pthread.h>
53 #endif
54 #include "webcit.h"
55 #include "sysdep.h"
56
57 #ifdef HAVE_SYS_SELECT_H
58 #include <sys/select.h>
59 #endif
60
61 #ifndef HAVE_SNPRINTF
62 #include "snprintf.h"
63 #endif
64 #include "webserver.h"
65 #include "modules_init.h"
66 #if HAVE_BACKTRACE
67 #include <execinfo.h>
68 #endif
69
70 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
71 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
72 pthread_key_t MyReq;                            /* TSD key for MyReq() */
73 int msock;                      /* master listening socket */
74 int time_to_die = 0;            /* Nonzero if server is shutting down */
75 int verbosity = 9;              /* Logging level */
76
77 extern void *context_loop(ParsedHttpHdrs *Hdr);
78 extern void *housekeeping_loop(void);
79
80 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
81 char file_crpt_file_key[PATH_MAX]="";
82 char file_crpt_file_csr[PATH_MAX]="";
83 char file_crpt_file_cer[PATH_MAX]="";
84
85 const char editor_absolut_dir[PATH_MAX]=EDITORDIR;      /* nailed to what configure gives us. */
86 char static_dir[PATH_MAX];              /* calculated on startup */
87 char static_local_dir[PATH_MAX];                /* calculated on startup */
88 char static_icon_dir[PATH_MAX];          /* where should we find our mime icons? */
89 char  *static_dirs[]={                          /* needs same sort order as the web mapping */
90         (char*)static_dir,                      /* our templates on disk */
91         (char*)static_local_dir,                /* user provided templates disk */
92         (char*)editor_absolut_dir,              /* the editor on disk */
93         (char*)static_icon_dir                  /* our icons... */
94 };
95
96 void InitialiseSemaphores(void)
97 {
98         int i;
99
100         /* Set up a bunch of semaphores to be used for critical sections */
101         for (i=0; i<MAX_SEMAPHORES; ++i) {
102                 pthread_mutex_init(&Critters[i], NULL);
103         }
104 }
105
106 /*
107  * Obtain a semaphore lock to begin a critical section.
108  */
109 void begin_critical_section(int which_one)
110 {
111         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
112         pthread_mutex_lock(&Critters[which_one]);
113 }
114
115 /*
116  * Release a semaphore lock to end a critical section.
117  */
118 void end_critical_section(int which_one)
119 {
120         pthread_mutex_unlock(&Critters[which_one]);
121 }
122
123
124 void ShutDownWebcit(void)
125 {
126         free_zone_directory ();
127         icaltimezone_release_zone_tab ();
128         icalmemory_free_ring ();
129         ShutDownLibCitadel ();
130         shutdown_modules ();
131 #ifdef HAVE_OPENSSL
132         if (is_https) {
133                 shutdown_ssl();
134         }
135 #endif
136 }
137
138 /*
139  * Entry point for worker threads
140  */
141 void worker_entry(void)
142 {
143         int ssock;
144         int i = 0;
145         int fail_this_transaction = 0;
146         ParsedHttpHdrs Hdr;
147
148         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
149         Hdr.HR.eReqType = eGET;
150         http_new_modules(&Hdr); 
151
152         do {
153                 /* Only one thread can accept at a time */
154                 fail_this_transaction = 0;
155                 ssock = -1; 
156                 errno = EAGAIN;
157                 do {
158                         --num_threads_executing;
159                         ssock = accept(msock, NULL, 0);
160                         ++num_threads_executing;
161                         lprintf(9, "Thread %u woke up, accept() returned %d %s\n",
162                                 pthread_self(),
163                                 ssock,
164                                 ((ssock >= 0) ? "" : strerror(errno))
165                         );
166                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
167
168                 if ((msock == -1)||(time_to_die))
169                 {/* ok, we're going down. */
170                         int shutdown = 0;
171
172                         /* The first thread to get here will have to do the cleanup.
173                          * Make sure it's really just one.
174                          */
175                         begin_critical_section(S_SHUTDOWN);
176                         if (msock == -1)
177                         {
178                                 msock = -2;
179                                 shutdown = 1;
180                         }
181                         end_critical_section(S_SHUTDOWN);
182                         if (shutdown == 1)
183                         {/* we're the one to cleanup the mess. */
184                                 http_destroy_modules(&Hdr);
185                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
186                                 shutdown_sessions();
187                                 lprintf(2, "master shutdown: waiting for others\n");
188                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
189                                 lprintf(2, "master shutdown: cleaning up sessions\n");
190                                 do_housekeeping();
191                                 lprintf(2, "master shutdown: cleaning up libical\n");
192
193                                 ShutDownWebcit();
194
195                                 lprintf(2, "master shutdown exiting!.\n");                              
196                                 exit(0);
197                         }
198                         break;
199                 }
200                 if (ssock < 0 ) continue;
201
202                 /* Now do something. */
203                 if (msock < 0) {
204                         if (ssock > 0) close (ssock);
205                         lprintf(2, "in between.");
206                         pthread_exit(NULL);
207                 } else {
208                         /* Got it? do some real work! */
209                         /* Set the SO_REUSEADDR socket option */
210                         i = 1;
211                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
212
213                         /* If we are an HTTPS server, go crypto now. */
214 #ifdef HAVE_OPENSSL
215                         if (is_https) {
216                                 if (starttls(ssock) != 0) {
217                                         fail_this_transaction = 1;
218                                         close(ssock);
219                                 }
220                         }
221                         else 
222 #endif
223                         {
224                                 int fdflags; 
225                                 fdflags = fcntl(ssock, F_GETFL);
226                                 if (fdflags < 0)
227                                         lprintf(1, "unable to get server socket flags! %s \n",
228                                                 strerror(errno));
229                                 fdflags = fdflags | O_NONBLOCK;
230                                 if (fcntl(ssock, F_SETFL, fdflags) < 0)
231                                         lprintf(1, "unable to set server socket nonblocking flags! %s \n",
232                                                 strerror(errno));
233                         }
234
235                         if (fail_this_transaction == 0) {
236                                 Hdr.http_sock = ssock;
237
238                                 /* Perform an HTTP transaction... */
239                                 context_loop(&Hdr);
240
241                                 /* Shut down SSL/TLS if required... */
242 #ifdef HAVE_OPENSSL
243                                 if (is_https) {
244                                         endtls();
245                                 }
246 #endif
247
248                                 /* ...and close the socket. */
249                                 if (Hdr.http_sock > 0) {
250                                         lingering_close(ssock);
251                                 }
252                                 http_detach_modules(&Hdr);
253
254                         }
255
256                 }
257
258         } while (!time_to_die);
259
260         http_destroy_modules(&Hdr);
261         lprintf (1, "bye\n");
262         pthread_exit(NULL);
263 }
264
265 /*
266  * print log messages 
267  * logs to stderr if loglevel is lower than the verbosity set at startup
268  *
269  * loglevel     level of the message
270  * format       the printf like format string
271  * ...          the strings to put into format
272  */
273 int lprintf(int loglevel, const char *format, ...)
274 {
275         va_list ap;
276
277         if (loglevel <= verbosity) {
278                 va_start(ap, format);
279                 vfprintf(stderr, format, ap);
280                 va_end(ap);
281                 fflush(stderr);
282         }
283         return 1;
284 }
285
286 /*
287  * Shut us down the regular way.
288  * signum is the signal we want to forward
289  */
290 pid_t current_child;
291 void graceful_shutdown_watcher(int signum) {
292         lprintf (1, "bye; shutting down watcher.");
293         kill(current_child, signum);
294         if (signum != SIGHUP)
295                 exit(0);
296 }
297
298
299
300
301 /*
302  * Shut us down the regular way.
303  * signum is the signal we want to forward
304  */
305 pid_t current_child;
306 void graceful_shutdown(int signum) {
307         FILE *FD;
308         int fd;
309
310         lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
311         fd = msock;
312         msock = -1;
313         time_to_die = 1;
314         FD=fdopen(fd, "a+");
315         fflush (FD);
316         fclose (FD);
317         close(fd);
318 }
319
320
321 /*
322  * Start running as a daemon.
323  */
324 void start_daemon(char *pid_file) 
325 {
326         int status = 0;
327         pid_t child = 0;
328         FILE *fp;
329         int do_restart = 0;
330         int rv;
331         FILE *rvfp = NULL;
332
333         current_child = 0;
334
335         /* Close stdin/stdout/stderr and replace them with /dev/null.
336          * We don't just call close() because we don't want these fd's
337          * to be reused for other files.
338          */
339         rv = chdir("/");
340
341         signal(SIGHUP, SIG_IGN);
342         signal(SIGINT, SIG_IGN);
343         signal(SIGQUIT, SIG_IGN);
344
345         child = fork();
346         if (child != 0) {
347                 exit(0);
348         }
349
350         setsid();
351         umask(0);
352         rvfp = freopen("/dev/null", "r", stdin);
353         rvfp = freopen("/dev/null", "w", stdout);
354         rvfp = freopen("/dev/null", "w", stderr);
355         signal(SIGTERM, graceful_shutdown_watcher);
356         signal(SIGHUP, graceful_shutdown_watcher);
357
358         do {
359                 current_child = fork();
360
361         
362                 if (current_child < 0) {
363                         perror("fork");
364                         ShutDownLibCitadel ();
365                         exit(errno);
366                 }
367         
368                 else if (current_child == 0) {  /* child process */
369                         signal(SIGHUP, graceful_shutdown);
370
371                         return; /* continue starting webcit. */
372                 }
373                 else { /* watcher process */
374                         if (pid_file) {
375                                 fp = fopen(pid_file, "w");
376                                 if (fp != NULL) {
377                                         fprintf(fp, "%d\n", getpid());
378                                         fclose(fp);
379                                 }
380                         }
381                         waitpid(current_child, &status, 0);
382                 }
383
384                 do_restart = 0;
385
386                 /* Did the main process exit with an actual exit code? */
387                 if (WIFEXITED(status)) {
388
389                         /* Exit code 0 means the watcher should exit */
390                         if (WEXITSTATUS(status) == 0) {
391                                 do_restart = 0;
392                         }
393
394                         /* Exit code 101-109 means the watcher should exit */
395                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
396                                 do_restart = 0;
397                         }
398
399                         /* Any other exit code means we should restart. */
400                         else {
401                                 do_restart = 1;
402                         }
403                 }
404
405                 /* Any other type of termination (signals, etc.) should also restart. */
406                 else {
407                         do_restart = 1;
408                 }
409
410         } while (do_restart);
411
412         if (pid_file) {
413                 unlink(pid_file);
414         }
415         ShutDownLibCitadel ();
416         exit(WEXITSTATUS(status));
417 }
418
419 /*
420  * Spawn an additional worker thread into the pool.
421  */
422 void spawn_another_worker_thread()
423 {
424         pthread_t SessThread;   /* Thread descriptor */
425         pthread_attr_t attr;    /* Thread attributes */
426         int ret;
427
428         lprintf(3, "Creating a new thread.\n");
429
430         ++num_threads_existing;
431         ++num_threads_executing;
432
433         /* set attributes for the new thread */
434         pthread_attr_init(&attr);
435         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
436
437         /*
438          * Our per-thread stacks need to be bigger than the default size,
439          * otherwise the MIME parser crashes on FreeBSD.
440          */
441         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
442                 lprintf(1, "pthread_attr_setstacksize: %s\n",
443                         strerror(ret));
444                 pthread_attr_destroy(&attr);
445         }
446
447         /* now create the thread */
448         if (pthread_create(&SessThread, &attr,
449                            (void *(*)(void *)) worker_entry, NULL)
450             != 0) {
451                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
452         }
453
454         /* free up the attributes */
455         pthread_attr_destroy(&attr);
456 }
457
458
459 void
460 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
461 {
462         char dirbuffer[PATH_MAX]="";
463         /* calculate all our path on a central place */
464     /* where to keep our config */
465         
466 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
467         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
468                          (home&!relh)?webcitdir:basedir, \
469              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
470              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
471                          relhome, \
472              (relhome[0]!='\0')?"/":"",\
473                          dirbuffer,\
474                          (dirbuffer[0]!='\0')?"/":"");
475         basedir=RUNDIR;
476         COMPUTE_DIRECTORY(socket_dir);
477         basedir=WWWDIR "/static";
478         COMPUTE_DIRECTORY(static_dir);
479         basedir=WWWDIR "/static/icons";
480         COMPUTE_DIRECTORY(static_icon_dir);
481         basedir=WWWDIR "/static.local";
482         COMPUTE_DIRECTORY(static_local_dir);
483         StripSlashes(static_dir, 1);
484         StripSlashes(static_icon_dir, 1);
485         StripSlashes(static_local_dir, 1);
486
487         snprintf(file_crpt_file_key,
488                  sizeof file_crpt_file_key, 
489                  "%s/citadel.key",
490                  ctdl_key_dir);
491         snprintf(file_crpt_file_csr,
492                  sizeof file_crpt_file_csr, 
493                  "%s/citadel.csr",
494                  ctdl_key_dir);
495         snprintf(file_crpt_file_cer,
496                  sizeof file_crpt_file_cer, 
497                  "%s/citadel.cer",
498                  ctdl_key_dir);
499
500         /* we should go somewhere we can leave our coredump, if enabled... */
501         lprintf(9, "Changing directory to %s\n", socket_dir);
502         if (chdir(webcitdir) != 0) {
503                 perror("chdir");
504         }
505 }
506 void drop_root(uid_t UID)
507 {
508         struct passwd pw, *pwp = NULL;
509
510         /*
511          * Now that we've bound the sockets, change to the Citadel user id and its
512          * corresponding group ids
513          */
514         if (UID != -1) {
515                 
516 #ifdef HAVE_GETPWUID_R
517 #ifdef SOLARIS_GETPWUID
518                 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
519 #else // SOLARIS_GETPWUID
520                 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
521 #endif // SOLARIS_GETPWUID
522 #else // HAVE_GETPWUID_R
523                 pwp = NULL;
524 #endif // HAVE_GETPWUID_R
525
526                 if (pwp == NULL)
527                         lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
528                                 "Group IDs will be incorrect.\n", UID,
529                                 strerror(errno));
530                 else {
531                         initgroups(pw.pw_name, pw.pw_gid);
532                         if (setgid(pw.pw_gid))
533                                 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
534                                         strerror(errno));
535                 }
536                 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)UID);
537                 if (setuid(UID) != 0) {
538                         lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
539                 }
540 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
541                 prctl(PR_SET_DUMPABLE, 1);
542 #endif
543         }
544 }
545
546
547 /*
548  * print the actual stack frame.
549  */
550 void wc_backtrace(void)
551 {
552 #ifdef HAVE_BACKTRACE
553         void *stack_frames[50];
554         size_t size, i;
555         char **strings;
556
557
558         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
559         strings = backtrace_symbols(stack_frames, size);
560         for (i = 0; i < size; i++) {
561                 if (strings != NULL)
562                         lprintf(1, "%s\n", strings[i]);
563                 else
564                         lprintf(1, "%p\n", stack_frames[i]);
565         }
566         free(strings);
567 #endif
568 }