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>
62 #include "webserver.h"
63 #include "modules_init.h"
68 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
69 pthread_key_t MyConKey; /* TSD key for MyContext() */
70 pthread_key_t MyReq; /* TSD key for MyReq() */
71 int msock; /* master listening socket */
72 int time_to_die = 0; /* Nonzero if server is shutting down */
74 extern void *context_loop(ParsedHttpHdrs *Hdr);
75 extern void *housekeeping_loop(void);
76 extern void do_housekeeping(void);
78 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
79 char file_crpt_file_key[PATH_MAX]="";
80 char file_crpt_file_csr[PATH_MAX]="";
81 char file_crpt_file_cer[PATH_MAX]="";
82 char file_etc_mimelist[PATH_MAX]="";
84 const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /* nailed to what configure gives us. */
85 char etc_dir[PATH_MAX];
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... */
97 HashList *GZMimeBlackList = NULL; /* mimetypes which shouldn't be gzip compressed */
99 void LoadMimeBlacklist(void)
101 StrBuf *MimeBlackLine;
105 memset(&IOB, 0, sizeof(IOBuffer));
106 IOB.fd = open(file_etc_mimelist, O_RDONLY);
108 IOB.Buf = NewStrBuf();
109 MimeBlackLine = NewStrBuf();
110 GZMimeBlackList = NewHash(1, NULL);
114 state = StrBufChunkSipLine(MimeBlackLine, &IOB);
119 if (StrBuf_read_one_chunk_callback(IOB.fd, 0, &IOB) <= 0)
123 if ((StrLength(MimeBlackLine) > 1) &&
124 (*ChrPtr(MimeBlackLine) != '#'))
126 Put(GZMimeBlackList, SKEY(MimeBlackLine),
127 (void*) 1, reference_free_handler);
129 FlushStrBuf(MimeBlackLine);
133 case eBufferNotEmpty:
137 while (state != eReadFail);
141 FreeStrBuf(&IOB.Buf);
142 FreeStrBuf(&MimeBlackLine);
145 void CheckGZipCompressionAllowed(const char *MimeType, long MLen)
150 if (WCC->Hdr->HR.gzip_ok)
151 WCC->Hdr->HR.gzip_ok = GetHash(GZMimeBlackList, MimeType, MLen, &v) == 0;
154 void InitialiseSemaphores(void)
158 /* Set up a bunch of semaphores to be used for critical sections */
159 for (i=0; i<MAX_SEMAPHORES; ++i) {
160 pthread_mutex_init(&Critters[i], NULL);
165 syslog(LOG_WARNING, "Failed to open exit pipe: %d [%s]\n",
174 * Obtain a semaphore lock to begin a critical section.
176 void begin_critical_section(int which_one)
178 pthread_mutex_lock(&Critters[which_one]);
182 * Release a semaphore lock to end a critical section.
184 void end_critical_section(int which_one)
186 pthread_mutex_unlock(&Critters[which_one]);
190 void ShutDownWebcit(void)
192 free_zone_directory ();
193 icaltimezone_release_zone_tab ();
194 icalmemory_free_ring ();
195 ShutDownLibCitadel ();
205 * Entry point for worker threads
207 void worker_entry(void)
211 int fail_this_transaction = 0;
214 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
215 Hdr.HR.eReqType = eGET;
216 http_new_modules(&Hdr);
219 /* Each worker thread blocks on accept() while waiting for something to do. */
220 fail_this_transaction = 0;
225 --num_threads_executing;
227 FD_SET(msock, &wset);
228 FD_SET(ExitPipe[1], &wset);
230 select(msock + 1, NULL, &wset, NULL, NULL);
234 ssock = accept(msock, NULL, 0);
235 ++num_threads_executing;
236 if (ssock < 0) fail_this_transaction = 1;
237 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
239 if ((msock == -1)||(time_to_die))
240 {/* ok, we're going down. */
243 /* The first thread to get here will have to do the cleanup.
244 * Make sure it's really just one.
246 begin_critical_section(S_SHUTDOWN);
252 end_critical_section(S_SHUTDOWN);
254 {/* we're the one to cleanup the mess. */
255 http_destroy_modules(&Hdr);
256 syslog(LOG_DEBUG, "I'm master shutdown: tagging sessions to be killed.\n");
258 syslog(LOG_DEBUG, "master shutdown: waiting for others\n");
259 sleeeeeeeeeep(1); /* wait so some others might finish... */
260 syslog(LOG_DEBUG, "master shutdown: cleaning up sessions\n");
262 syslog(LOG_DEBUG, "master shutdown: cleaning up libical\n");
266 syslog(LOG_DEBUG, "master shutdown exiting.\n");
271 if (ssock < 0 ) continue;
273 check_thread_pool_size();
275 /* Now do something. */
277 if (ssock > 0) close (ssock);
278 syslog(LOG_DEBUG, "in between.");
281 /* Got it? do some real work! */
282 /* Set the SO_REUSEADDR socket option */
284 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
286 /* If we are an HTTPS server, go crypto now. */
289 if (starttls(ssock) != 0) {
290 fail_this_transaction = 1;
298 fdflags = fcntl(ssock, F_GETFL);
300 syslog(LOG_WARNING, "unable to get server socket flags! %s \n",
302 fdflags = fdflags | O_NONBLOCK;
303 if (fcntl(ssock, F_SETFL, fdflags) < 0)
304 syslog(LOG_WARNING, "unable to set server socket nonblocking flags! %s \n",
308 if (fail_this_transaction == 0) {
309 Hdr.http_sock = ssock;
311 /* Perform an HTTP transaction... */
314 /* Shut down SSL/TLS if required... */
321 /* ...and close the socket. */
322 if (Hdr.http_sock > 0) {
323 lingering_close(ssock);
325 http_detach_modules(&Hdr);
331 } while (!time_to_die);
333 http_destroy_modules(&Hdr);
334 syslog(LOG_DEBUG, "Thread exiting.\n");
340 * Shut us down the regular way.
341 * signum is the signal we want to forward
344 void graceful_shutdown_watcher(int signum) {
345 syslog(LOG_INFO, "Watcher thread exiting.\n");
346 write(ExitPipe[0], HKEY(" "));
347 kill(current_child, signum);
348 if (signum != SIGHUP)
354 * Shut us down the regular way.
355 * signum is the signal we want to forward
358 void graceful_shutdown(int signum) {
362 syslog(LOG_INFO, "WebCit is being shut down on signal %d.\n", signum);
370 write(ExitPipe[0], HKEY(" "));
375 * Start running as a daemon.
377 void start_daemon(char *pid_file)
386 /* Close stdin/stdout/stderr and replace them with /dev/null.
387 * We don't just call close() because we don't want these fd's
388 * to be reused for other files.
392 signal(SIGHUP, SIG_IGN);
393 signal(SIGINT, SIG_IGN);
394 signal(SIGQUIT, SIG_IGN);
403 freopen("/dev/null", "r", stdin);
404 freopen("/dev/null", "w", stdout);
405 freopen("/dev/null", "w", stderr);
406 signal(SIGTERM, graceful_shutdown_watcher);
407 signal(SIGHUP, graceful_shutdown_watcher);
410 current_child = fork();
413 if (current_child < 0) {
415 ShutDownLibCitadel ();
419 else if (current_child == 0) { /* child process */
420 signal(SIGHUP, graceful_shutdown);
422 return; /* continue starting webcit. */
424 else { /* watcher process */
426 fp = fopen(pid_file, "w");
428 fprintf(fp, "%d\n", getpid());
432 waitpid(current_child, &status, 0);
437 /* Did the main process exit with an actual exit code? */
438 if (WIFEXITED(status)) {
440 /* Exit code 0 means the watcher should exit */
441 if (WEXITSTATUS(status) == 0) {
445 /* Exit code 101-109 means the watcher should exit */
446 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
450 /* Any other exit code means we should restart. */
456 /* Any other type of termination (signals, etc.) should also restart. */
461 } while (do_restart);
466 ShutDownLibCitadel ();
467 exit(WEXITSTATUS(status));
472 * Spawn an additional worker thread into the pool.
474 void spawn_another_worker_thread()
476 pthread_t SessThread; /* Thread descriptor */
477 pthread_attr_t attr; /* Thread attributes */
480 ++num_threads_existing;
481 ++num_threads_executing;
483 /* set attributes for the new thread */
484 pthread_attr_init(&attr);
485 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
488 * Our per-thread stacks need to be bigger than the default size,
489 * otherwise the MIME parser crashes on FreeBSD.
491 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
492 syslog(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(ret));
493 pthread_attr_destroy(&attr);
496 /* now create the thread */
497 if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
498 syslog(LOG_WARNING, "Can't create thread: %s\n", strerror(errno));
501 /* free up the attributes */
502 pthread_attr_destroy(&attr);
507 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
509 char dirbuffer[PATH_MAX]="";
510 /* calculate all our path on a central place */
511 /* where to keep our config */
513 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
514 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
515 (home&!relh)?webcitdir:basedir, \
516 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
517 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
519 (relhome[0]!='\0')?"/":"",\
521 (dirbuffer[0]!='\0')?"/":"");
523 COMPUTE_DIRECTORY(socket_dir);
524 basedir=WWWDIR "/static";
525 COMPUTE_DIRECTORY(static_dir);
526 basedir=WWWDIR "/static/icons";
527 COMPUTE_DIRECTORY(static_icon_dir);
528 basedir=WWWDIR "/static.local";
529 COMPUTE_DIRECTORY(static_local_dir);
530 StripSlashes(static_dir, 1);
531 StripSlashes(static_icon_dir, 1);
532 StripSlashes(static_local_dir, 1);
534 snprintf(file_crpt_file_key,
535 sizeof file_crpt_file_key,
538 snprintf(file_crpt_file_csr,
539 sizeof file_crpt_file_csr,
542 snprintf(file_crpt_file_cer,
543 sizeof file_crpt_file_cer,
549 COMPUTE_DIRECTORY(etc_dir);
550 StripSlashes(etc_dir, 1);
551 snprintf(file_etc_mimelist,
552 sizeof file_etc_mimelist,
553 "%s/nogz-mimetypes.txt",
556 /* we should go somewhere we can leave our coredump, if enabled... */
557 syslog(LOG_INFO, "Changing directory to %s\n", socket_dir);
558 if (chdir(webcitdir) != 0) {
563 void drop_root(uid_t UID)
565 struct passwd pw, *pwp = NULL;
568 * Now that we've bound the sockets, change to the Citadel user id and its
569 * corresponding group ids
573 #ifdef HAVE_GETPWUID_R
574 #ifdef SOLARIS_GETPWUID
575 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
576 #else /* SOLARIS_GETPWUID */
577 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
578 #endif /* SOLARIS_GETPWUID */
579 #else /* HAVE_GETPWUID_R */
581 #endif /* HAVE_GETPWUID_R */
584 syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n"
585 "Group IDs will be incorrect.\n", UID,
588 initgroups(pw.pw_name, pw.pw_gid);
589 if (setgid(pw.pw_gid))
590 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
593 syslog(LOG_INFO, "Changing uid to %ld\n", (long)UID);
594 if (setuid(UID) != 0) {
595 syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
597 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
598 prctl(PR_SET_DUMPABLE, 1);
605 * print the actual stack frame.
607 void wc_backtrace(long LogLevel)
609 #ifdef HAVE_BACKTRACE
610 void *stack_frames[50];
615 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
616 strings = backtrace_symbols(stack_frames, size);
617 for (i = 0; i < size; i++) {
619 syslog(LogLevel, "%s\n", strings[i]);
621 syslog(LogLevel, "%p\n", stack_frames[i]);