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