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