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