cleanup webcit.h; utils.c, remove unneeded stuff
[citadel.git] / webcit / sysdep.c
1 /*
2  * WebCit "system dependent" code.
3  *
4  * Copyright (c) 1996-2011 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 as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <ctype.h>
27 #include <signal.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31 #include <sys/socket.h>
32 #include <syslog.h>
33 #include <sys/syslog.h>
34
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #include <limits.h>
47 #include <sys/resource.h>
48 #include <netinet/in.h>
49 #include <netinet/tcp.h>
50 #include <arpa/inet.h>
51 #include <netdb.h>
52 #include <sys/un.h>
53 #include <string.h>
54 #include <pwd.h>
55 #include <errno.h>
56 #include <stdarg.h>
57 #include <grp.h>
58 #ifdef HAVE_PTHREAD_H
59 #include <pthread.h>
60 #endif
61 #include "webcit.h"
62 #include "sysdep.h"
63
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
66 #endif
67
68 #ifndef HAVE_SNPRINTF
69 #include "snprintf.h"
70 #endif
71 #include "webserver.h"
72 #include "modules_init.h"
73 #if HAVE_BACKTRACE
74 #include <execinfo.h>
75 #endif
76
77 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
78 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
79 pthread_key_t MyReq;                            /* TSD key for MyReq() */
80 int msock;                      /* master listening socket */
81 int time_to_die = 0;            /* Nonzero if server is shutting down */
82 int verbosity = 9;              /* Logging level */
83
84 extern void *context_loop(ParsedHttpHdrs *Hdr);
85 extern void *housekeeping_loop(void);
86 extern void do_housekeeping(void);
87
88 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
89 char file_crpt_file_key[PATH_MAX]="";
90 char file_crpt_file_csr[PATH_MAX]="";
91 char file_crpt_file_cer[PATH_MAX]="";
92
93 const char editor_absolut_dir[PATH_MAX]=EDITORDIR;      /* nailed to what configure gives us. */
94 char static_dir[PATH_MAX];              /* calculated on startup */
95 char static_local_dir[PATH_MAX];                /* calculated on startup */
96 char static_icon_dir[PATH_MAX];          /* where should we find our mime icons? */
97 char  *static_dirs[]={                          /* needs same sort order as the web mapping */
98         (char*)static_dir,                      /* our templates on disk */
99         (char*)static_local_dir,                /* user provided templates disk */
100         (char*)editor_absolut_dir,              /* the editor on disk */
101         (char*)static_icon_dir                  /* our icons... */
102 };
103
104 int ExitPipe[2];
105
106 void InitialiseSemaphores(void)
107 {
108         int i;
109
110         /* Set up a bunch of semaphores to be used for critical sections */
111         for (i=0; i<MAX_SEMAPHORES; ++i) {
112                 pthread_mutex_init(&Critters[i], NULL);
113         }
114
115         if (pipe(ExitPipe))
116         {
117                 syslog(2, "Failed to open exit pipe: %d [%s]\n", 
118                        errno, 
119                        strerror(errno));
120                 
121                 exit(-1);
122         }
123 }
124
125 /*
126  * Obtain a semaphore lock to begin a critical section.
127  */
128 void begin_critical_section(int which_one)
129 {
130         pthread_mutex_lock(&Critters[which_one]);
131 }
132
133 /*
134  * Release a semaphore lock to end a critical section.
135  */
136 void end_critical_section(int which_one)
137 {
138         pthread_mutex_unlock(&Critters[which_one]);
139 }
140
141
142 void ShutDownWebcit(void)
143 {
144         free_zone_directory ();
145         icaltimezone_release_zone_tab ();
146         icalmemory_free_ring ();
147         ShutDownLibCitadel ();
148         shutdown_modules ();
149 #ifdef HAVE_OPENSSL
150         if (is_https) {
151                 shutdown_ssl();
152         }
153 #endif
154 }
155
156 /*
157  * Entry point for worker threads
158  */
159 void worker_entry(void)
160 {
161         int ssock;
162         int i = 0;
163         int fail_this_transaction = 0;
164         ParsedHttpHdrs Hdr;
165
166         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
167         Hdr.HR.eReqType = eGET;
168         http_new_modules(&Hdr); 
169
170         do {
171                 /* Each worker thread blocks on accept() while waiting for something to do. */
172                 fail_this_transaction = 0;
173                 ssock = -1; 
174                 errno = EAGAIN;
175                 do {
176                         fd_set wset;
177                         --num_threads_executing;
178                         FD_ZERO(&wset);
179                         FD_SET(msock, &wset);
180                         FD_SET(ExitPipe[1], &wset);
181
182                         select(msock + 1, NULL, &wset, NULL, NULL);
183                         if (time_to_die)
184                                 break;
185
186                         ssock = accept(msock, NULL, 0);
187                         ++num_threads_executing;
188                         if (ssock < 0) fail_this_transaction = 1;
189                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
190
191                 if ((msock == -1)||(time_to_die))
192                 {/* ok, we're going down. */
193                         int shutdown = 0;
194
195                         /* The first thread to get here will have to do the cleanup.
196                          * Make sure it's really just one.
197                          */
198                         begin_critical_section(S_SHUTDOWN);
199                         if (msock == -1)
200                         {
201                                 msock = -2;
202                                 shutdown = 1;
203                         }
204                         end_critical_section(S_SHUTDOWN);
205                         if (shutdown == 1)
206                         {/* we're the one to cleanup the mess. */
207                                 http_destroy_modules(&Hdr);
208                                 syslog(2, "I'm master shutdown: tagging sessions to be killed.\n");
209                                 shutdown_sessions();
210                                 syslog(2, "master shutdown: waiting for others\n");
211                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
212                                 syslog(2, "master shutdown: cleaning up sessions\n");
213                                 do_housekeeping();
214                                 syslog(2, "master shutdown: cleaning up libical\n");
215
216                                 ShutDownWebcit();
217
218                                 syslog(2, "master shutdown exiting.\n");                                
219                                 exit(0);
220                         }
221                         break;
222                 }
223                 if (ssock < 0 ) continue;
224
225                 check_thread_pool_size();
226
227                 /* Now do something. */
228                 if (msock < 0) {
229                         if (ssock > 0) close (ssock);
230                         syslog(2, "in between.");
231                         pthread_exit(NULL);
232                 } else {
233                         /* Got it? do some real work! */
234                         /* Set the SO_REUSEADDR socket option */
235                         i = 1;
236                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
237
238                         /* If we are an HTTPS server, go crypto now. */
239 #ifdef HAVE_OPENSSL
240                         if (is_https) {
241                                 if (starttls(ssock) != 0) {
242                                         fail_this_transaction = 1;
243                                         close(ssock);
244                                 }
245                         }
246                         else 
247 #endif
248                         {
249                                 int fdflags; 
250                                 fdflags = fcntl(ssock, F_GETFL);
251                                 if (fdflags < 0)
252                                         syslog(1, "unable to get server socket flags! %s \n",
253                                                 strerror(errno));
254                                 fdflags = fdflags | O_NONBLOCK;
255                                 if (fcntl(ssock, F_SETFL, fdflags) < 0)
256                                         syslog(1, "unable to set server socket nonblocking flags! %s \n",
257                                                 strerror(errno));
258                         }
259
260                         if (fail_this_transaction == 0) {
261                                 Hdr.http_sock = ssock;
262
263                                 /* Perform an HTTP transaction... */
264                                 context_loop(&Hdr);
265
266                                 /* Shut down SSL/TLS if required... */
267 #ifdef HAVE_OPENSSL
268                                 if (is_https) {
269                                         endtls();
270                                 }
271 #endif
272
273                                 /* ...and close the socket. */
274                                 if (Hdr.http_sock > 0) {
275                                         lingering_close(ssock);
276                                 }
277                                 http_detach_modules(&Hdr);
278
279                         }
280
281                 }
282
283         } while (!time_to_die);
284
285         http_destroy_modules(&Hdr);
286         syslog(1, "Thread exiting.\n");
287         pthread_exit(NULL);
288 }
289
290
291 /*
292  * Shut us down the regular way.
293  * signum is the signal we want to forward
294  */
295 pid_t current_child;
296 void graceful_shutdown_watcher(int signum) {
297         syslog(1, "Watcher thread exiting.\n");
298         write(ExitPipe[0], HKEY("                              "));
299         kill(current_child, signum);
300         if (signum != SIGHUP)
301                 exit(0);
302 }
303
304
305 /*
306  * Shut us down the regular way.
307  * signum is the signal we want to forward
308  */
309 pid_t current_child;
310 void graceful_shutdown(int signum) {
311         FILE *FD;
312         int fd;
313
314         syslog(1, "WebCit is being shut down on signal %d.\n", signum);
315         fd = msock;
316         msock = -1;
317         time_to_die = 1;
318         FD=fdopen(fd, "a+");
319         fflush (FD);
320         fclose (FD);
321         close(fd);
322         write(ExitPipe[0], HKEY("                              "));
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                 syslog(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                 syslog(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         syslog(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                         syslog(LOG_CRIT, "WARNING: getpwuid(%d): %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                                 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
536                                         strerror(errno));
537                 }
538                 syslog(LOG_INFO, "Changing uid to %ld\n", (long)UID);
539                 if (setuid(UID) != 0) {
540                         syslog(LOG_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                         syslog(1, "%s\n", strings[i]);
565                 else
566                         syslog(1, "%p\n", stack_frames[i]);
567         }
568         free(strings);
569 #endif
570 }