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 fd_set readset, tempset;
151 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
152 Hdr.HR.eReqType = eGET;
153 http_new_modules(&Hdr);
157 FD_SET(msock, &readset);
160 /* Only one thread can accept at a time */
161 fail_this_transaction = 0;
165 ret = -1; /* just one at once should select... */
166 begin_critical_section(S_SELECT);
169 if (msock > 0) FD_SET(msock, &tempset);
172 if (msock > 0) ret = select(msock+1, &tempset, NULL, NULL, &tv);
173 end_critical_section(S_SELECT);
174 if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
175 {/* EINTR and EAGAIN are thrown but not of interest. */
176 lprintf(2, "accept() failed:%d %s\n",
177 errno, strerror(errno));
179 else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
180 {/* Successfully selected, and still not shutting down? Accept! */
181 ssock = accept(msock, NULL, 0);
184 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
186 if ((msock == -1)||(time_to_die))
187 {/* ok, we're going down. */
190 /* the first to come here will have to do the cleanup.
191 * make shure its realy just one.
193 begin_critical_section(S_SHUTDOWN);
199 end_critical_section(S_SHUTDOWN);
201 {/* we're the one to cleanup the mess. */
202 http_destroy_modules(&Hdr);
203 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
205 lprintf(2, "master shutdown: waiting for others\n");
206 sleeeeeeeeeep(1); /* wait so some others might finish... */
207 lprintf(2, "master shutdown: cleaning up sessions\n");
209 lprintf(2, "master shutdown: cleaning up libical\n");
213 lprintf(2, "master shutdown exiting!.\n");
218 if (ssock < 0 ) continue;
221 if (ssock > 0) close (ssock);
222 lprintf(2, "inbetween.");
224 } else { /* Got it? do some real work! */
225 /* Set the SO_REUSEADDR socket option */
227 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
230 /* If we are an HTTPS server, go crypto now. */
233 if (starttls(ssock) != 0) {
234 fail_this_transaction = 1;
242 fdflags = fcntl(ssock, F_GETFL);
244 lprintf(1, "unable to get server socket flags! %s \n",
246 fdflags = fdflags | O_NONBLOCK;
247 if (fcntl(ssock, F_SETFL, fdflags) < 0)
248 lprintf(1, "unable to set server socket nonblocking flags! %s \n",
252 if (fail_this_transaction == 0) {
253 Hdr.http_sock = ssock;
255 /* Perform an HTTP transaction... */
258 /* Shut down SSL/TLS if required... */
265 /* ...and close the socket. */
266 if (Hdr.http_sock > 0)
267 lingering_close(ssock);
268 http_detach_modules(&Hdr);
274 } while (!time_to_die);
276 http_destroy_modules(&Hdr);
277 lprintf (1, "bye\n");
283 * logs to stderr if loglevel is lower than the verbosity set at startup
285 * loglevel level of the message
286 * format the printf like format string
287 * ... the strings to put into format
289 int lprintf(int loglevel, const char *format, ...)
293 if (loglevel <= verbosity) {
294 va_start(ap, format);
295 vfprintf(stderr, format, ap);
303 * Shut us down the regular way.
304 * signum is the signal we want to forward
307 void graceful_shutdown_watcher(int signum) {
308 lprintf (1, "bye; shutting down watcher.");
309 kill(current_child, signum);
310 if (signum != SIGHUP)
318 * Shut us down the regular way.
319 * signum is the signal we want to forward
322 void graceful_shutdown(int signum) {
326 lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
338 * Start running as a daemon.
340 void start_daemon(char *pid_file)
351 /* Close stdin/stdout/stderr and replace them with /dev/null.
352 * We don't just call close() because we don't want these fd's
353 * to be reused for other files.
357 signal(SIGHUP, SIG_IGN);
358 signal(SIGINT, SIG_IGN);
359 signal(SIGQUIT, SIG_IGN);
368 rvfp = freopen("/dev/null", "r", stdin);
369 rvfp = freopen("/dev/null", "w", stdout);
370 rvfp = freopen("/dev/null", "w", stderr);
371 signal(SIGTERM, graceful_shutdown_watcher);
372 signal(SIGHUP, graceful_shutdown_watcher);
375 current_child = fork();
378 if (current_child < 0) {
380 ShutDownLibCitadel ();
384 else if (current_child == 0) { /* child process */
385 signal(SIGHUP, graceful_shutdown);
387 return; /* continue starting webcit. */
389 else { /* watcher process */
391 fp = fopen(pid_file, "w");
393 fprintf(fp, "%d\n", getpid());
397 waitpid(current_child, &status, 0);
402 /* Did the main process exit with an actual exit code? */
403 if (WIFEXITED(status)) {
405 /* Exit code 0 means the watcher should exit */
406 if (WEXITSTATUS(status) == 0) {
410 /* Exit code 101-109 means the watcher should exit */
411 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
415 /* Any other exit code means we should restart. */
421 /* Any other type of termination (signals, etc.) should also restart. */
426 } while (do_restart);
431 ShutDownLibCitadel ();
432 exit(WEXITSTATUS(status));
436 * Spawn an additional worker thread into the pool.
438 void spawn_another_worker_thread()
440 pthread_t SessThread; /* Thread descriptor */
441 pthread_attr_t attr; /* Thread attributes */
444 lprintf(3, "Creating a new thread. Pool size is now %d\n", ++num_threads);
446 /* set attributes for the new thread */
447 pthread_attr_init(&attr);
448 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
451 * Our per-thread stacks need to be bigger than the default size,
452 * otherwise the MIME parser crashes on FreeBSD.
454 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
455 lprintf(1, "pthread_attr_setstacksize: %s\n",
457 pthread_attr_destroy(&attr);
460 /* now create the thread */
461 if (pthread_create(&SessThread, &attr,
462 (void *(*)(void *)) worker_entry, NULL)
464 lprintf(1, "Can't create thread: %s\n", strerror(errno));
467 /* free up the attributes */
468 pthread_attr_destroy(&attr);
473 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
475 char dirbuffer[PATH_MAX]="";
476 /* calculate all our path on a central place */
477 /* where to keep our config */
479 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
480 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
481 (home&!relh)?webcitdir:basedir, \
482 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
483 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
485 (relhome[0]!='\0')?"/":"",\
487 (dirbuffer[0]!='\0')?"/":"");
489 COMPUTE_DIRECTORY(socket_dir);
490 basedir=WWWDIR "/static";
491 COMPUTE_DIRECTORY(static_dir);
492 basedir=WWWDIR "/static/icons";
493 COMPUTE_DIRECTORY(static_icon_dir);
494 basedir=WWWDIR "/static.local";
495 COMPUTE_DIRECTORY(static_local_dir);
496 StripSlashes(static_dir, 1);
497 StripSlashes(static_icon_dir, 1);
498 StripSlashes(static_local_dir, 1);
500 snprintf(file_crpt_file_key,
501 sizeof file_crpt_file_key,
504 snprintf(file_crpt_file_csr,
505 sizeof file_crpt_file_csr,
508 snprintf(file_crpt_file_cer,
509 sizeof file_crpt_file_cer,
513 /* we should go somewhere we can leave our coredump, if enabled... */
514 lprintf(9, "Changing directory to %s\n", socket_dir);
515 if (chdir(webcitdir) != 0) {
519 void drop_root(uid_t UID)
521 struct passwd pw, *pwp = NULL;
524 * Now that we've bound the sockets, change to the Citadel user id and its
525 * corresponding group ids
529 #ifdef HAVE_GETPWUID_R
530 #ifdef SOLARIS_GETPWUID
531 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
532 #else // SOLARIS_GETPWUID
533 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
534 #endif // SOLARIS_GETPWUID
535 #else // HAVE_GETPWUID_R
537 #endif // HAVE_GETPWUID_R
540 lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
541 "Group IDs will be incorrect.\n", UID,
544 initgroups(pw.pw_name, pw.pw_gid);
545 if (setgid(pw.pw_gid))
546 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
549 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)UID);
550 if (setuid(UID) != 0) {
551 lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
553 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
554 prctl(PR_SET_DUMPABLE, 1);
561 * print the actual stack frame.
563 void wc_backtrace(void)
565 #ifdef HAVE_BACKTRACE
566 void *stack_frames[50];
571 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
572 strings = backtrace_symbols(stack_frames, size);
573 for (i = 0; i < size; i++) {
575 lprintf(1, "%s\n", strings[i]);
577 lprintf(1, "%p\n", stack_frames[i]);