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