* Change to main server loop. All threads block on accept() instead of using a mutex...
[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                         ssock = accept(msock, NULL, 0);
159                         lprintf(9, "\033[3%dmthread %u woke up, accept() returned %d %s\033[0m\n",
160                                 ((pthread_self() % 6) + 1),
161                                 pthread_self(),
162                                 ssock,
163                                 ((ssock >= 0) ? "" : strerror(errno))
164                         );
165                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
166
167                 if ((msock == -1)||(time_to_die))
168                 {/* ok, we're going down. */
169                         int shutdown = 0;
170
171                         /* the first to come here will have to do the cleanup.
172                          * make shure its realy just one.
173                          */
174                         begin_critical_section(S_SHUTDOWN);
175                         if (msock == -1)
176                         {
177                                 msock = -2;
178                                 shutdown = 1;
179                         }
180                         end_critical_section(S_SHUTDOWN);
181                         if (shutdown == 1)
182                         {/* we're the one to cleanup the mess. */
183                                 http_destroy_modules(&Hdr);
184                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
185                                 shutdown_sessions();
186                                 lprintf(2, "master shutdown: waiting for others\n");
187                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
188                                 lprintf(2, "master shutdown: cleaning up sessions\n");
189                                 do_housekeeping();
190                                 lprintf(2, "master shutdown: cleaning up libical\n");
191
192                                 ShutDownWebcit();
193
194                                 lprintf(2, "master shutdown exiting!.\n");                              
195                                 exit(0);
196                         }
197                         break;
198                 }
199                 if (ssock < 0 ) continue;
200
201                 if (msock < 0) {
202                         if (ssock > 0) close (ssock);
203                         lprintf(2, "inbetween.");
204                         pthread_exit(NULL);
205                 } else { /* Got it? do some real work! */
206                         /* Set the SO_REUSEADDR socket option */
207                         i = 1;
208                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
209                                    &i, sizeof(i));
210
211                         /* If we are an HTTPS server, go crypto now. */
212 #ifdef HAVE_OPENSSL
213                         if (is_https) {
214                                 if (starttls(ssock) != 0) {
215                                         fail_this_transaction = 1;
216                                         close(ssock);
217                                 }
218                         }
219                         else 
220 #endif
221                         {
222                                 int fdflags; 
223                                 fdflags = fcntl(ssock, F_GETFL);
224                                 if (fdflags < 0)
225                                         lprintf(1, "unable to get server socket flags! %s \n",
226                                                 strerror(errno));
227                                 fdflags = fdflags | O_NONBLOCK;
228                                 if (fcntl(ssock, F_SETFL, fdflags) < 0)
229                                         lprintf(1, "unable to set server socket nonblocking flags! %s \n",
230                                                 strerror(errno));
231                         }
232
233                         if (fail_this_transaction == 0) {
234                                 Hdr.http_sock = ssock;
235
236                                 /* Perform an HTTP transaction... */
237                                 context_loop(&Hdr);
238
239                                 /* Shut down SSL/TLS if required... */
240 #ifdef HAVE_OPENSSL
241                                 if (is_https) {
242                                         endtls();
243                                 }
244 #endif
245
246                                 /* ...and close the socket. */
247                                 if (Hdr.http_sock > 0)
248                                         lingering_close(ssock);
249                                 http_detach_modules(&Hdr);
250
251                         }
252
253                 }
254
255         } while (!time_to_die);
256
257         http_destroy_modules(&Hdr);
258         lprintf (1, "bye\n");
259         pthread_exit(NULL);
260 }
261
262 /*
263  * print log messages 
264  * logs to stderr if loglevel is lower than the verbosity set at startup
265  *
266  * loglevel     level of the message
267  * format       the printf like format string
268  * ...          the strings to put into format
269  */
270 int lprintf(int loglevel, const char *format, ...)
271 {
272         va_list ap;
273
274         if (loglevel <= verbosity) {
275                 va_start(ap, format);
276                 vfprintf(stderr, format, ap);
277                 va_end(ap);
278                 fflush(stderr);
279         }
280         return 1;
281 }
282
283 /*
284  * Shut us down the regular way.
285  * signum is the signal we want to forward
286  */
287 pid_t current_child;
288 void graceful_shutdown_watcher(int signum) {
289         lprintf (1, "bye; shutting down watcher.");
290         kill(current_child, signum);
291         if (signum != SIGHUP)
292                 exit(0);
293 }
294
295
296
297
298 /*
299  * Shut us down the regular way.
300  * signum is the signal we want to forward
301  */
302 pid_t current_child;
303 void graceful_shutdown(int signum) {
304         FILE *FD;
305         int fd;
306
307         lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
308         fd = msock;
309         msock = -1;
310         time_to_die = 1;
311         FD=fdopen(fd, "a+");
312         fflush (FD);
313         fclose (FD);
314         close(fd);
315 }
316
317
318 /*
319  * Start running as a daemon.
320  */
321 void start_daemon(char *pid_file) 
322 {
323         int status = 0;
324         pid_t child = 0;
325         FILE *fp;
326         int do_restart = 0;
327         int rv;
328         FILE *rvfp = NULL;
329
330         current_child = 0;
331
332         /* Close stdin/stdout/stderr and replace them with /dev/null.
333          * We don't just call close() because we don't want these fd's
334          * to be reused for other files.
335          */
336         rv = chdir("/");
337
338         signal(SIGHUP, SIG_IGN);
339         signal(SIGINT, SIG_IGN);
340         signal(SIGQUIT, SIG_IGN);
341
342         child = fork();
343         if (child != 0) {
344                 exit(0);
345         }
346
347         setsid();
348         umask(0);
349         rvfp = freopen("/dev/null", "r", stdin);
350         rvfp = freopen("/dev/null", "w", stdout);
351         rvfp = freopen("/dev/null", "w", stderr);
352         signal(SIGTERM, graceful_shutdown_watcher);
353         signal(SIGHUP, graceful_shutdown_watcher);
354
355         do {
356                 current_child = fork();
357
358         
359                 if (current_child < 0) {
360                         perror("fork");
361                         ShutDownLibCitadel ();
362                         exit(errno);
363                 }
364         
365                 else if (current_child == 0) {  /* child process */
366                         signal(SIGHUP, graceful_shutdown);
367
368                         return; /* continue starting webcit. */
369                 }
370                 else { /* watcher process */
371                         if (pid_file) {
372                                 fp = fopen(pid_file, "w");
373                                 if (fp != NULL) {
374                                         fprintf(fp, "%d\n", getpid());
375                                         fclose(fp);
376                                 }
377                         }
378                         waitpid(current_child, &status, 0);
379                 }
380
381                 do_restart = 0;
382
383                 /* Did the main process exit with an actual exit code? */
384                 if (WIFEXITED(status)) {
385
386                         /* Exit code 0 means the watcher should exit */
387                         if (WEXITSTATUS(status) == 0) {
388                                 do_restart = 0;
389                         }
390
391                         /* Exit code 101-109 means the watcher should exit */
392                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
393                                 do_restart = 0;
394                         }
395
396                         /* Any other exit code means we should restart. */
397                         else {
398                                 do_restart = 1;
399                         }
400                 }
401
402                 /* Any other type of termination (signals, etc.) should also restart. */
403                 else {
404                         do_restart = 1;
405                 }
406
407         } while (do_restart);
408
409         if (pid_file) {
410                 unlink(pid_file);
411         }
412         ShutDownLibCitadel ();
413         exit(WEXITSTATUS(status));
414 }
415
416 /*
417  * Spawn an additional worker thread into the pool.
418  */
419 void spawn_another_worker_thread()
420 {
421         pthread_t SessThread;   /* Thread descriptor */
422         pthread_attr_t attr;    /* Thread attributes */
423         int ret;
424
425         lprintf(3, "Creating a new thread.  Pool size is now %d\n", ++num_threads);
426
427         /* set attributes for the new thread */
428         pthread_attr_init(&attr);
429         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
430
431         /*
432          * Our per-thread stacks need to be bigger than the default size,
433          * otherwise the MIME parser crashes on FreeBSD.
434          */
435         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
436                 lprintf(1, "pthread_attr_setstacksize: %s\n",
437                         strerror(ret));
438                 pthread_attr_destroy(&attr);
439         }
440
441         /* now create the thread */
442         if (pthread_create(&SessThread, &attr,
443                            (void *(*)(void *)) worker_entry, NULL)
444             != 0) {
445                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
446         }
447
448         /* free up the attributes */
449         pthread_attr_destroy(&attr);
450 }
451
452
453 void
454 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
455 {
456         char dirbuffer[PATH_MAX]="";
457         /* calculate all our path on a central place */
458     /* where to keep our config */
459         
460 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
461         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
462                          (home&!relh)?webcitdir:basedir, \
463              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
464              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
465                          relhome, \
466              (relhome[0]!='\0')?"/":"",\
467                          dirbuffer,\
468                          (dirbuffer[0]!='\0')?"/":"");
469         basedir=RUNDIR;
470         COMPUTE_DIRECTORY(socket_dir);
471         basedir=WWWDIR "/static";
472         COMPUTE_DIRECTORY(static_dir);
473         basedir=WWWDIR "/static/icons";
474         COMPUTE_DIRECTORY(static_icon_dir);
475         basedir=WWWDIR "/static.local";
476         COMPUTE_DIRECTORY(static_local_dir);
477         StripSlashes(static_dir, 1);
478         StripSlashes(static_icon_dir, 1);
479         StripSlashes(static_local_dir, 1);
480
481         snprintf(file_crpt_file_key,
482                  sizeof file_crpt_file_key, 
483                  "%s/citadel.key",
484                  ctdl_key_dir);
485         snprintf(file_crpt_file_csr,
486                  sizeof file_crpt_file_csr, 
487                  "%s/citadel.csr",
488                  ctdl_key_dir);
489         snprintf(file_crpt_file_cer,
490                  sizeof file_crpt_file_cer, 
491                  "%s/citadel.cer",
492                  ctdl_key_dir);
493
494         /* we should go somewhere we can leave our coredump, if enabled... */
495         lprintf(9, "Changing directory to %s\n", socket_dir);
496         if (chdir(webcitdir) != 0) {
497                 perror("chdir");
498         }
499 }
500 void drop_root(uid_t UID)
501 {
502         struct passwd pw, *pwp = NULL;
503
504         /*
505          * Now that we've bound the sockets, change to the Citadel user id and its
506          * corresponding group ids
507          */
508         if (UID != -1) {
509                 
510 #ifdef HAVE_GETPWUID_R
511 #ifdef SOLARIS_GETPWUID
512                 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
513 #else // SOLARIS_GETPWUID
514                 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
515 #endif // SOLARIS_GETPWUID
516 #else // HAVE_GETPWUID_R
517                 pwp = NULL;
518 #endif // HAVE_GETPWUID_R
519
520                 if (pwp == NULL)
521                         lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
522                                 "Group IDs will be incorrect.\n", UID,
523                                 strerror(errno));
524                 else {
525                         initgroups(pw.pw_name, pw.pw_gid);
526                         if (setgid(pw.pw_gid))
527                                 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
528                                         strerror(errno));
529                 }
530                 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)UID);
531                 if (setuid(UID) != 0) {
532                         lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
533                 }
534 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
535                 prctl(PR_SET_DUMPABLE, 1);
536 #endif
537         }
538 }
539
540
541 /*
542  * print the actual stack frame.
543  */
544 void wc_backtrace(void)
545 {
546 #ifdef HAVE_BACKTRACE
547         void *stack_frames[50];
548         size_t size, i;
549         char **strings;
550
551
552         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
553         strings = backtrace_symbols(stack_frames, size);
554         for (i = 0; i < size; i++) {
555                 if (strings != NULL)
556                         lprintf(1, "%s\n", strings[i]);
557                 else
558                         lprintf(1, "%p\n", stack_frames[i]);
559         }
560         free(strings);
561 #endif
562 }