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