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 --num_threads_executing;
159 ssock = accept(msock, NULL, 0);
160 ++num_threads_executing;
161 lprintf(9, "Thread %u woke up, accept() returned %d %s\n",
164 ((ssock >= 0) ? "" : strerror(errno))
166 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
168 if ((msock == -1)||(time_to_die))
169 {/* ok, we're going down. */
172 /* The first thread to get here will have to do the cleanup.
173 * Make sure it's really just one.
175 begin_critical_section(S_SHUTDOWN);
181 end_critical_section(S_SHUTDOWN);
183 {/* we're the one to cleanup the mess. */
184 http_destroy_modules(&Hdr);
185 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
187 lprintf(2, "master shutdown: waiting for others\n");
188 sleeeeeeeeeep(1); /* wait so some others might finish... */
189 lprintf(2, "master shutdown: cleaning up sessions\n");
191 lprintf(2, "master shutdown: cleaning up libical\n");
195 lprintf(2, "master shutdown exiting!.\n");
200 if (ssock < 0 ) continue;
202 /* Now do something. */
204 if (ssock > 0) close (ssock);
205 lprintf(2, "in between.");
208 /* Got it? do some real work! */
209 /* Set the SO_REUSEADDR socket option */
211 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
213 /* If we are an HTTPS server, go crypto now. */
216 if (starttls(ssock) != 0) {
217 fail_this_transaction = 1;
225 fdflags = fcntl(ssock, F_GETFL);
227 lprintf(1, "unable to get server socket flags! %s \n",
229 fdflags = fdflags | O_NONBLOCK;
230 if (fcntl(ssock, F_SETFL, fdflags) < 0)
231 lprintf(1, "unable to set server socket nonblocking flags! %s \n",
235 if (fail_this_transaction == 0) {
236 Hdr.http_sock = ssock;
238 /* Perform an HTTP transaction... */
241 /* Shut down SSL/TLS if required... */
248 /* ...and close the socket. */
249 if (Hdr.http_sock > 0) {
250 lingering_close(ssock);
252 http_detach_modules(&Hdr);
258 } while (!time_to_die);
260 http_destroy_modules(&Hdr);
261 lprintf (1, "bye\n");
267 * logs to stderr if loglevel is lower than the verbosity set at startup
269 * loglevel level of the message
270 * format the printf like format string
271 * ... the strings to put into format
273 int lprintf(int loglevel, const char *format, ...)
277 if (loglevel <= verbosity) {
278 va_start(ap, format);
279 vfprintf(stderr, format, ap);
287 * Shut us down the regular way.
288 * signum is the signal we want to forward
291 void graceful_shutdown_watcher(int signum) {
292 lprintf (1, "bye; shutting down watcher.");
293 kill(current_child, signum);
294 if (signum != SIGHUP)
302 * Shut us down the regular way.
303 * signum is the signal we want to forward
306 void graceful_shutdown(int signum) {
310 lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
322 * Start running as a daemon.
324 void start_daemon(char *pid_file)
335 /* Close stdin/stdout/stderr and replace them with /dev/null.
336 * We don't just call close() because we don't want these fd's
337 * to be reused for other files.
341 signal(SIGHUP, SIG_IGN);
342 signal(SIGINT, SIG_IGN);
343 signal(SIGQUIT, SIG_IGN);
352 rvfp = freopen("/dev/null", "r", stdin);
353 rvfp = freopen("/dev/null", "w", stdout);
354 rvfp = freopen("/dev/null", "w", stderr);
355 signal(SIGTERM, graceful_shutdown_watcher);
356 signal(SIGHUP, graceful_shutdown_watcher);
359 current_child = fork();
362 if (current_child < 0) {
364 ShutDownLibCitadel ();
368 else if (current_child == 0) { /* child process */
369 signal(SIGHUP, graceful_shutdown);
371 return; /* continue starting webcit. */
373 else { /* watcher process */
375 fp = fopen(pid_file, "w");
377 fprintf(fp, "%d\n", getpid());
381 waitpid(current_child, &status, 0);
386 /* Did the main process exit with an actual exit code? */
387 if (WIFEXITED(status)) {
389 /* Exit code 0 means the watcher should exit */
390 if (WEXITSTATUS(status) == 0) {
394 /* Exit code 101-109 means the watcher should exit */
395 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
399 /* Any other exit code means we should restart. */
405 /* Any other type of termination (signals, etc.) should also restart. */
410 } while (do_restart);
415 ShutDownLibCitadel ();
416 exit(WEXITSTATUS(status));
420 * Spawn an additional worker thread into the pool.
422 void spawn_another_worker_thread()
424 pthread_t SessThread; /* Thread descriptor */
425 pthread_attr_t attr; /* Thread attributes */
428 lprintf(3, "Creating a new thread.\n");
430 ++num_threads_existing;
431 ++num_threads_executing;
433 /* set attributes for the new thread */
434 pthread_attr_init(&attr);
435 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
438 * Our per-thread stacks need to be bigger than the default size,
439 * otherwise the MIME parser crashes on FreeBSD.
441 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
442 lprintf(1, "pthread_attr_setstacksize: %s\n",
444 pthread_attr_destroy(&attr);
447 /* now create the thread */
448 if (pthread_create(&SessThread, &attr,
449 (void *(*)(void *)) worker_entry, NULL)
451 lprintf(1, "Can't create thread: %s\n", strerror(errno));
454 /* free up the attributes */
455 pthread_attr_destroy(&attr);
460 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
462 char dirbuffer[PATH_MAX]="";
463 /* calculate all our path on a central place */
464 /* where to keep our config */
466 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
467 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
468 (home&!relh)?webcitdir:basedir, \
469 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
470 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
472 (relhome[0]!='\0')?"/":"",\
474 (dirbuffer[0]!='\0')?"/":"");
476 COMPUTE_DIRECTORY(socket_dir);
477 basedir=WWWDIR "/static";
478 COMPUTE_DIRECTORY(static_dir);
479 basedir=WWWDIR "/static/icons";
480 COMPUTE_DIRECTORY(static_icon_dir);
481 basedir=WWWDIR "/static.local";
482 COMPUTE_DIRECTORY(static_local_dir);
483 StripSlashes(static_dir, 1);
484 StripSlashes(static_icon_dir, 1);
485 StripSlashes(static_local_dir, 1);
487 snprintf(file_crpt_file_key,
488 sizeof file_crpt_file_key,
491 snprintf(file_crpt_file_csr,
492 sizeof file_crpt_file_csr,
495 snprintf(file_crpt_file_cer,
496 sizeof file_crpt_file_cer,
500 /* we should go somewhere we can leave our coredump, if enabled... */
501 lprintf(9, "Changing directory to %s\n", socket_dir);
502 if (chdir(webcitdir) != 0) {
506 void drop_root(uid_t UID)
508 struct passwd pw, *pwp = NULL;
511 * Now that we've bound the sockets, change to the Citadel user id and its
512 * corresponding group ids
516 #ifdef HAVE_GETPWUID_R
517 #ifdef SOLARIS_GETPWUID
518 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
519 #else // SOLARIS_GETPWUID
520 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
521 #endif // SOLARIS_GETPWUID
522 #else // HAVE_GETPWUID_R
524 #endif // HAVE_GETPWUID_R
527 lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
528 "Group IDs will be incorrect.\n", UID,
531 initgroups(pw.pw_name, pw.pw_gid);
532 if (setgid(pw.pw_gid))
533 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
536 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)UID);
537 if (setuid(UID) != 0) {
538 lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
540 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
541 prctl(PR_SET_DUMPABLE, 1);
548 * print the actual stack frame.
550 void wc_backtrace(void)
552 #ifdef HAVE_BACKTRACE
553 void *stack_frames[50];
558 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
559 strings = backtrace_symbols(stack_frames, size);
560 for (i = 0; i < size; i++) {
562 lprintf(1, "%s\n", strings[i]);
564 lprintf(1, "%p\n", stack_frames[i]);