2 * WebCit "system dependent" code.
4 * Copyright (c) 1996-2012 by the citadel.org team
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.
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.
22 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <sys/syslog.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
34 # include <sys/time.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
58 #ifdef HAVE_SYS_SELECT_H
59 #include <sys/select.h>
65 #include "webserver.h"
66 #include "modules_init.h"
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 */
77 extern void *context_loop(ParsedHttpHdrs *Hdr);
78 extern void *housekeeping_loop(void);
79 extern void do_housekeeping(void);
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]="";
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... */
99 void InitialiseSemaphores(void)
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);
110 syslog(2, "Failed to open exit pipe: %d [%s]\n",
119 * Obtain a semaphore lock to begin a critical section.
121 void begin_critical_section(int which_one)
123 pthread_mutex_lock(&Critters[which_one]);
127 * Release a semaphore lock to end a critical section.
129 void end_critical_section(int which_one)
131 pthread_mutex_unlock(&Critters[which_one]);
135 void ShutDownWebcit(void)
137 free_zone_directory ();
138 icaltimezone_release_zone_tab ();
139 icalmemory_free_ring ();
140 ShutDownLibCitadel ();
150 * Entry point for worker threads
152 void worker_entry(void)
156 int fail_this_transaction = 0;
159 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
160 Hdr.HR.eReqType = eGET;
161 http_new_modules(&Hdr);
164 /* Each worker thread blocks on accept() while waiting for something to do. */
165 fail_this_transaction = 0;
170 --num_threads_executing;
172 FD_SET(msock, &wset);
173 FD_SET(ExitPipe[1], &wset);
175 select(msock + 1, NULL, &wset, NULL, NULL);
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));
184 if ((msock == -1)||(time_to_die))
185 {/* ok, we're going down. */
188 /* The first thread to get here will have to do the cleanup.
189 * Make sure it's really just one.
191 begin_critical_section(S_SHUTDOWN);
197 end_critical_section(S_SHUTDOWN);
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");
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");
207 syslog(2, "master shutdown: cleaning up libical\n");
211 syslog(2, "master shutdown exiting.\n");
216 if (ssock < 0 ) continue;
218 check_thread_pool_size();
220 /* Now do something. */
222 if (ssock > 0) close (ssock);
223 syslog(2, "in between.");
226 /* Got it? do some real work! */
227 /* Set the SO_REUSEADDR socket option */
229 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
231 /* If we are an HTTPS server, go crypto now. */
234 if (starttls(ssock) != 0) {
235 fail_this_transaction = 1;
243 fdflags = fcntl(ssock, F_GETFL);
245 syslog(1, "unable to get server socket flags! %s \n",
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",
253 if (fail_this_transaction == 0) {
254 Hdr.http_sock = ssock;
256 /* Perform an HTTP transaction... */
259 /* Shut down SSL/TLS if required... */
266 /* ...and close the socket. */
267 if (Hdr.http_sock > 0) {
268 lingering_close(ssock);
270 http_detach_modules(&Hdr);
276 } while (!time_to_die);
278 http_destroy_modules(&Hdr);
279 syslog(1, "Thread exiting.\n");
285 * Shut us down the regular way.
286 * signum is the signal we want to forward
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)
299 * Shut us down the regular way.
300 * signum is the signal we want to forward
303 void graceful_shutdown(int signum) {
307 syslog(1, "WebCit is being shut down on signal %d.\n", signum);
315 write(ExitPipe[0], HKEY(" "));
320 * Start running as a daemon.
322 void start_daemon(char *pid_file)
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.
337 signal(SIGHUP, SIG_IGN);
338 signal(SIGINT, SIG_IGN);
339 signal(SIGQUIT, SIG_IGN);
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);
355 current_child = fork();
358 if (current_child < 0) {
360 ShutDownLibCitadel ();
364 else if (current_child == 0) { /* child process */
365 signal(SIGHUP, graceful_shutdown);
367 return; /* continue starting webcit. */
369 else { /* watcher process */
371 fp = fopen(pid_file, "w");
373 fprintf(fp, "%d\n", getpid());
377 waitpid(current_child, &status, 0);
382 /* Did the main process exit with an actual exit code? */
383 if (WIFEXITED(status)) {
385 /* Exit code 0 means the watcher should exit */
386 if (WEXITSTATUS(status) == 0) {
390 /* Exit code 101-109 means the watcher should exit */
391 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
395 /* Any other exit code means we should restart. */
401 /* Any other type of termination (signals, etc.) should also restart. */
406 } while (do_restart);
411 ShutDownLibCitadel ();
412 exit(WEXITSTATUS(status));
417 * Spawn an additional worker thread into the pool.
419 void spawn_another_worker_thread()
421 pthread_t SessThread; /* Thread descriptor */
422 pthread_attr_t attr; /* Thread attributes */
425 ++num_threads_existing;
426 ++num_threads_executing;
428 /* set attributes for the new thread */
429 pthread_attr_init(&attr);
430 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
433 * Our per-thread stacks need to be bigger than the default size,
434 * otherwise the MIME parser crashes on FreeBSD.
436 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
437 syslog(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
438 pthread_attr_destroy(&attr);
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));
446 /* free up the attributes */
447 pthread_attr_destroy(&attr);
452 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
454 char dirbuffer[PATH_MAX]="";
455 /* calculate all our path on a central place */
456 /* where to keep our config */
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))?"/":"", \
464 (relhome[0]!='\0')?"/":"",\
466 (dirbuffer[0]!='\0')?"/":"");
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);
479 snprintf(file_crpt_file_key,
480 sizeof file_crpt_file_key,
483 snprintf(file_crpt_file_csr,
484 sizeof file_crpt_file_csr,
487 snprintf(file_crpt_file_cer,
488 sizeof file_crpt_file_cer,
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) {
499 void drop_root(uid_t UID)
501 struct passwd pw, *pwp = NULL;
504 * Now that we've bound the sockets, change to the Citadel user id and its
505 * corresponding group ids
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 */
517 #endif /* HAVE_GETPWUID_R */
520 syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n"
521 "Group IDs will be incorrect.\n", UID,
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,
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));
533 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
534 prctl(PR_SET_DUMPABLE, 1);
541 * print the actual stack frame.
543 void wc_backtrace(void)
545 #ifdef HAVE_BACKTRACE
546 void *stack_frames[50];
551 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
552 strings = backtrace_symbols(stack_frames, size);
553 for (i = 0; i < size; i++) {
555 syslog(1, "%s\n", strings[i]);
557 syslog(1, "%p\n", stack_frames[i]);