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