4 * Citadel "system dependent" stuff.
5 * See copyright.txt for copyright information.
7 * Here's where we (hopefully) have most parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * If we ever port to a different platform and either have multiple
11 * variants of this file or simply load it up with #ifdefs.
21 #include <sys/types.h>
24 #include <sys/socket.h>
26 #include <sys/syslog.h>
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
33 # include <sys/time.h>
40 #include <sys/resource.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #include <arpa/inet.h>
57 #ifdef HAVE_SYS_SELECT_H
58 #include <sys/select.h>
64 #include "webserver.h"
65 #include "modules_init.h"
70 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
71 pthread_key_t MyConKey; /* TSD key for MyContext() */
72 pthread_key_t MyReq; /* TSD key for MyReq() */
73 int msock; /* master listening socket */
74 int time_to_die = 0; /* Nonzero if server is shutting down */
75 int verbosity = 9; /* Logging level */
77 extern void *context_loop(ParsedHttpHdrs *Hdr);
78 extern void *housekeeping_loop(void);
80 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
81 char file_crpt_file_key[PATH_MAX]="";
82 char file_crpt_file_csr[PATH_MAX]="";
83 char file_crpt_file_cer[PATH_MAX]="";
85 const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /* nailed to what configure gives us. */
86 char static_dir[PATH_MAX]; /* calculated on startup */
87 char static_local_dir[PATH_MAX]; /* calculated on startup */
88 char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
89 char *static_dirs[]={ /* needs same sort order as the web mapping */
90 (char*)static_dir, /* our templates on disk */
91 (char*)static_local_dir, /* user provided templates disk */
92 (char*)editor_absolut_dir, /* the editor on disk */
93 (char*)static_icon_dir /* our icons... */
96 void InitialiseSemaphores(void)
100 /* Set up a bunch of semaphores to be used for critical sections */
101 for (i=0; i<MAX_SEMAPHORES; ++i) {
102 pthread_mutex_init(&Critters[i], NULL);
107 * Obtain a semaphore lock to begin a critical section.
109 void begin_critical_section(int which_one)
111 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
112 pthread_mutex_lock(&Critters[which_one]);
116 * Release a semaphore lock to end a critical section.
118 void end_critical_section(int which_one)
120 pthread_mutex_unlock(&Critters[which_one]);
124 void ShutDownWebcit(void)
126 free_zone_directory ();
127 icaltimezone_release_zone_tab ();
128 icalmemory_free_ring ();
129 ShutDownLibCitadel ();
139 * Entry point for worker threads
141 void worker_entry(void)
145 int fail_this_transaction = 0;
148 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
149 Hdr.HR.eReqType = eGET;
150 http_new_modules(&Hdr);
153 /* Only one thread can accept at a time */
154 fail_this_transaction = 0;
158 ssock = accept(msock, NULL, 0);
159 lprintf(9, "Thread %u woke up, accept() returned %d %s\n",
160 ((pthread_self() % 6) + 1),
163 ((ssock >= 0) ? "" : strerror(errno))
165 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
167 if ((msock == -1)||(time_to_die))
168 {/* ok, we're going down. */
171 /* the first to come here will have to do the cleanup.
172 * make shure its realy just one.
174 begin_critical_section(S_SHUTDOWN);
180 end_critical_section(S_SHUTDOWN);
182 {/* we're the one to cleanup the mess. */
183 http_destroy_modules(&Hdr);
184 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
186 lprintf(2, "master shutdown: waiting for others\n");
187 sleeeeeeeeeep(1); /* wait so some others might finish... */
188 lprintf(2, "master shutdown: cleaning up sessions\n");
190 lprintf(2, "master shutdown: cleaning up libical\n");
194 lprintf(2, "master shutdown exiting!.\n");
199 if (ssock < 0 ) continue;
202 if (ssock > 0) close (ssock);
203 lprintf(2, "inbetween.");
205 } else { /* Got it? do some real work! */
206 /* Set the SO_REUSEADDR socket option */
208 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
211 /* If we are an HTTPS server, go crypto now. */
214 if (starttls(ssock) != 0) {
215 fail_this_transaction = 1;
223 fdflags = fcntl(ssock, F_GETFL);
225 lprintf(1, "unable to get server socket flags! %s \n",
227 fdflags = fdflags | O_NONBLOCK;
228 if (fcntl(ssock, F_SETFL, fdflags) < 0)
229 lprintf(1, "unable to set server socket nonblocking flags! %s \n",
233 if (fail_this_transaction == 0) {
234 Hdr.http_sock = ssock;
236 /* Perform an HTTP transaction... */
239 /* Shut down SSL/TLS if required... */
246 /* ...and close the socket. */
247 if (Hdr.http_sock > 0)
248 lingering_close(ssock);
249 http_detach_modules(&Hdr);
255 } while (!time_to_die);
257 http_destroy_modules(&Hdr);
258 lprintf (1, "bye\n");
264 * logs to stderr if loglevel is lower than the verbosity set at startup
266 * loglevel level of the message
267 * format the printf like format string
268 * ... the strings to put into format
270 int lprintf(int loglevel, const char *format, ...)
274 if (loglevel <= verbosity) {
275 va_start(ap, format);
276 vfprintf(stderr, format, ap);
284 * Shut us down the regular way.
285 * signum is the signal we want to forward
288 void graceful_shutdown_watcher(int signum) {
289 lprintf (1, "bye; shutting down watcher.");
290 kill(current_child, signum);
291 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 lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
319 * Start running as a daemon.
321 void start_daemon(char *pid_file)
332 /* Close stdin/stdout/stderr and replace them with /dev/null.
333 * We don't just call close() because we don't want these fd's
334 * to be reused for other files.
338 signal(SIGHUP, SIG_IGN);
339 signal(SIGINT, SIG_IGN);
340 signal(SIGQUIT, SIG_IGN);
349 rvfp = freopen("/dev/null", "r", stdin);
350 rvfp = freopen("/dev/null", "w", stdout);
351 rvfp = freopen("/dev/null", "w", stderr);
352 signal(SIGTERM, graceful_shutdown_watcher);
353 signal(SIGHUP, graceful_shutdown_watcher);
356 current_child = fork();
359 if (current_child < 0) {
361 ShutDownLibCitadel ();
365 else if (current_child == 0) { /* child process */
366 signal(SIGHUP, graceful_shutdown);
368 return; /* continue starting webcit. */
370 else { /* watcher process */
372 fp = fopen(pid_file, "w");
374 fprintf(fp, "%d\n", getpid());
378 waitpid(current_child, &status, 0);
383 /* Did the main process exit with an actual exit code? */
384 if (WIFEXITED(status)) {
386 /* Exit code 0 means the watcher should exit */
387 if (WEXITSTATUS(status) == 0) {
391 /* Exit code 101-109 means the watcher should exit */
392 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
396 /* Any other exit code means we should restart. */
402 /* Any other type of termination (signals, etc.) should also restart. */
407 } while (do_restart);
412 ShutDownLibCitadel ();
413 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 lprintf(3, "Creating a new thread. Pool size is now %d\n", ++num_threads);
427 /* set attributes for the new thread */
428 pthread_attr_init(&attr);
429 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
432 * Our per-thread stacks need to be bigger than the default size,
433 * otherwise the MIME parser crashes on FreeBSD.
435 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
436 lprintf(1, "pthread_attr_setstacksize: %s\n",
438 pthread_attr_destroy(&attr);
441 /* now create the thread */
442 if (pthread_create(&SessThread, &attr,
443 (void *(*)(void *)) worker_entry, NULL)
445 lprintf(1, "Can't create thread: %s\n", strerror(errno));
448 /* free up the attributes */
449 pthread_attr_destroy(&attr);
454 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
456 char dirbuffer[PATH_MAX]="";
457 /* calculate all our path on a central place */
458 /* where to keep our config */
460 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
461 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
462 (home&!relh)?webcitdir:basedir, \
463 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
464 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
466 (relhome[0]!='\0')?"/":"",\
468 (dirbuffer[0]!='\0')?"/":"");
470 COMPUTE_DIRECTORY(socket_dir);
471 basedir=WWWDIR "/static";
472 COMPUTE_DIRECTORY(static_dir);
473 basedir=WWWDIR "/static/icons";
474 COMPUTE_DIRECTORY(static_icon_dir);
475 basedir=WWWDIR "/static.local";
476 COMPUTE_DIRECTORY(static_local_dir);
477 StripSlashes(static_dir, 1);
478 StripSlashes(static_icon_dir, 1);
479 StripSlashes(static_local_dir, 1);
481 snprintf(file_crpt_file_key,
482 sizeof file_crpt_file_key,
485 snprintf(file_crpt_file_csr,
486 sizeof file_crpt_file_csr,
489 snprintf(file_crpt_file_cer,
490 sizeof file_crpt_file_cer,
494 /* we should go somewhere we can leave our coredump, if enabled... */
495 lprintf(9, "Changing directory to %s\n", socket_dir);
496 if (chdir(webcitdir) != 0) {
500 void drop_root(uid_t UID)
502 struct passwd pw, *pwp = NULL;
505 * Now that we've bound the sockets, change to the Citadel user id and its
506 * corresponding group ids
510 #ifdef HAVE_GETPWUID_R
511 #ifdef SOLARIS_GETPWUID
512 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
513 #else // SOLARIS_GETPWUID
514 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
515 #endif // SOLARIS_GETPWUID
516 #else // HAVE_GETPWUID_R
518 #endif // HAVE_GETPWUID_R
521 lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
522 "Group IDs will be incorrect.\n", UID,
525 initgroups(pw.pw_name, pw.pw_gid);
526 if (setgid(pw.pw_gid))
527 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
530 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)UID);
531 if (setuid(UID) != 0) {
532 lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
534 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
535 prctl(PR_SET_DUMPABLE, 1);
542 * print the actual stack frame.
544 void wc_backtrace(void)
546 #ifdef HAVE_BACKTRACE
547 void *stack_frames[50];
552 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
553 strings = backtrace_symbols(stack_frames, size);
554 for (i = 0; i < size; i++) {
556 lprintf(1, "%s\n", strings[i]);
558 lprintf(1, "%p\n", stack_frames[i]);