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>
30 #include <sys/resource.h>
31 #include <netinet/in.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
51 #include "webserver.h"
52 #include "modules_init.h"
57 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
58 pthread_key_t MyConKey; /* TSD key for MyContext() */
59 pthread_key_t MyReq; /* TSD key for MyReq() */
60 int msock; /* master listening socket */
61 int time_to_die = 0; /* Nonzero if server is shutting down */
63 extern void *context_loop(ParsedHttpHdrs *Hdr);
64 extern void *housekeeping_loop(void);
65 extern void do_housekeeping(void);
67 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
68 char file_crpt_file_key[PATH_MAX]="";
69 char file_crpt_file_csr[PATH_MAX]="";
70 char file_crpt_file_cer[PATH_MAX]="";
71 char file_etc_mimelist[PATH_MAX]="";
73 char etc_dir[PATH_MAX];
74 char static_dir[PATH_MAX]; /* calculated on startup */
75 char static_local_dir[PATH_MAX]; /* calculated on startup */
76 char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
77 char *static_dirs[]={ /* needs same sort order as the web mapping */
81 "./static/webcit_icons"
85 HashList *GZMimeBlackList = NULL; /* mimetypes which shouldn't be gzip compressed */
87 void LoadMimeBlacklist(void)
89 StrBuf *MimeBlackLine;
93 memset(&IOB, 0, sizeof(IOBuffer));
94 IOB.fd = open(file_etc_mimelist, O_RDONLY);
96 IOB.Buf = NewStrBuf();
97 MimeBlackLine = NewStrBuf();
98 GZMimeBlackList = NewHash(1, NULL);
102 state = StrBufChunkSipLine(MimeBlackLine, &IOB);
107 if (StrBuf_read_one_chunk_callback(IOB.fd, 0, &IOB) <= 0)
111 if ((StrLength(MimeBlackLine) > 1) &&
112 (*ChrPtr(MimeBlackLine) != '#'))
114 Put(GZMimeBlackList, SKEY(MimeBlackLine),
115 (void*) 1, reference_free_handler);
117 FlushStrBuf(MimeBlackLine);
121 case eBufferNotEmpty:
125 while (state != eReadFail);
129 FreeStrBuf(&IOB.Buf);
130 FreeStrBuf(&MimeBlackLine);
133 void CheckGZipCompressionAllowed(const char *MimeType, long MLen)
138 if (WCC->Hdr->HR.gzip_ok)
139 WCC->Hdr->HR.gzip_ok = GetHash(GZMimeBlackList, MimeType, MLen, &v) == 0;
142 void InitialiseSemaphores(void)
146 /* Set up a bunch of semaphores to be used for critical sections */
147 for (i=0; i<MAX_SEMAPHORES; ++i) {
148 pthread_mutex_init(&Critters[i], NULL);
153 syslog(LOG_WARNING, "Failed to open exit pipe: %d [%s]\n",
162 * Obtain a semaphore lock to begin a critical section.
164 void begin_critical_section(int which_one)
166 pthread_mutex_lock(&Critters[which_one]);
170 * Release a semaphore lock to end a critical section.
172 void end_critical_section(int which_one)
174 pthread_mutex_unlock(&Critters[which_one]);
178 void ShutDownWebcit(void)
181 DeleteHash(&GZMimeBlackList);
182 free_zone_directory ();
183 icaltimezone_release_zone_tab ();
184 icalmemory_free_ring ();
185 ShutDownLibCitadel ();
195 * Entry point for worker threads
197 void worker_entry(void)
201 int fail_this_transaction = 0;
204 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
205 Hdr.HR.eReqType = eGET;
206 http_new_modules(&Hdr);
209 /* Each worker thread blocks on accept() while waiting for something to do. */
210 fail_this_transaction = 0;
215 --num_threads_executing;
217 FD_SET(msock, &wset);
218 FD_SET(ExitPipe[1], &wset);
220 select(msock + 1, NULL, &wset, NULL, NULL);
224 ssock = accept(msock, NULL, 0);
225 ++num_threads_executing;
226 if (ssock < 0) fail_this_transaction = 1;
227 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
229 if ((msock == -1)||(time_to_die))
230 {/* ok, we're going down. */
233 /* The first thread to get here will have to do the cleanup.
234 * Make sure it's really just one.
236 begin_critical_section(S_SHUTDOWN);
242 end_critical_section(S_SHUTDOWN);
244 {/* we're the one to cleanup the mess. */
245 http_destroy_modules(&Hdr);
246 syslog(LOG_DEBUG, "I'm master shutdown: tagging sessions to be killed.\n");
248 syslog(LOG_DEBUG, "master shutdown: waiting for others\n");
249 sleeeeeeeeeep(1); /* wait so some others might finish... */
250 syslog(LOG_DEBUG, "master shutdown: cleaning up sessions\n");
252 syslog(LOG_DEBUG, "master shutdown: cleaning up libical\n");
256 syslog(LOG_DEBUG, "master shutdown exiting.\n");
261 if (ssock < 0 ) continue;
263 check_thread_pool_size();
265 /* Now do something. */
267 if (ssock > 0) close (ssock);
268 syslog(LOG_DEBUG, "in between.");
271 /* Got it? do some real work! */
272 /* Set the SO_REUSEADDR socket option */
274 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
276 /* If we are an HTTPS server, go crypto now. */
279 if (starttls(ssock) != 0) {
280 fail_this_transaction = 1;
288 fdflags = fcntl(ssock, F_GETFL);
290 syslog(LOG_WARNING, "unable to get server socket flags! %s \n",
292 fdflags = fdflags | O_NONBLOCK;
293 if (fcntl(ssock, F_SETFL, fdflags) < 0)
294 syslog(LOG_WARNING, "unable to set server socket nonblocking flags! %s \n",
298 if (fail_this_transaction == 0) {
299 Hdr.http_sock = ssock;
301 /* Perform an HTTP transaction... */
304 /* Shut down SSL/TLS if required... */
311 /* ...and close the socket. */
312 if (Hdr.http_sock > 0) {
313 lingering_close(ssock);
315 http_detach_modules(&Hdr);
321 } while (!time_to_die);
323 http_destroy_modules(&Hdr);
324 syslog(LOG_DEBUG, "Thread exiting.\n");
330 * Shut us down the regular way.
331 * signum is the signal we want to forward
334 void graceful_shutdown_watcher(int signum) {
335 syslog(LOG_INFO, "Watcher thread exiting.\n");
336 write(ExitPipe[0], HKEY(" "));
337 kill(current_child, signum);
338 if (signum != SIGHUP)
344 * Shut us down the regular way.
345 * signum is the signal we want to forward
348 void graceful_shutdown(int signum) {
352 syslog(LOG_INFO, "WebCit is being shut down on signal %d.\n", signum);
360 write(ExitPipe[0], HKEY(" "));
365 * Start running as a daemon.
367 void start_daemon(char *pid_file)
376 /* Close stdin/stdout/stderr and replace them with /dev/null.
377 * We don't just call close() because we don't want these fd's
378 * to be reused for other files.
382 signal(SIGHUP, SIG_IGN);
383 signal(SIGINT, SIG_IGN);
384 signal(SIGQUIT, SIG_IGN);
393 freopen("/dev/null", "r", stdin);
394 freopen("/dev/null", "w", stdout);
395 freopen("/dev/null", "w", stderr);
396 signal(SIGTERM, graceful_shutdown_watcher);
397 signal(SIGHUP, graceful_shutdown_watcher);
400 current_child = fork();
403 if (current_child < 0) {
405 ShutDownLibCitadel ();
409 else if (current_child == 0) { /* child process */
410 signal(SIGHUP, graceful_shutdown);
412 return; /* continue starting webcit. */
414 else { /* watcher process */
416 fp = fopen(pid_file, "w");
418 fprintf(fp, "%d\n", getpid());
422 waitpid(current_child, &status, 0);
427 /* Did the main process exit with an actual exit code? */
428 if (WIFEXITED(status)) {
430 /* Exit code 0 means the watcher should exit */
431 if (WEXITSTATUS(status) == 0) {
435 /* Exit code 101-109 means the watcher should exit */
436 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
440 /* Any other exit code means we should restart. */
446 /* Any other type of termination (signals, etc.) should also restart. */
451 } while (do_restart);
456 ShutDownLibCitadel ();
457 exit(WEXITSTATUS(status));
462 * Spawn an additional worker thread into the pool.
464 void spawn_another_worker_thread()
466 pthread_t SessThread; /* Thread descriptor */
467 pthread_attr_t attr; /* Thread attributes */
470 ++num_threads_existing;
471 ++num_threads_executing;
473 /* set attributes for the new thread */
474 pthread_attr_init(&attr);
475 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
478 * Our per-thread stacks need to be bigger than the default size,
479 * otherwise the MIME parser crashes on FreeBSD.
481 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
482 syslog(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(ret));
483 pthread_attr_destroy(&attr);
486 /* now create the thread */
487 if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
488 syslog(LOG_WARNING, "Can't create thread: %s\n", strerror(errno));
491 /* free up the attributes */
492 pthread_attr_destroy(&attr);
497 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
499 char dirbuffer[PATH_MAX]="";
500 /* calculate all our path on a central place */
501 /* where to keep our config */
503 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
504 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
505 (home&!relh)?webcitdir:basedir, \
506 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
507 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
509 (relhome[0]!='\0')?"/":"",\
511 (dirbuffer[0]!='\0')?"/":"");
513 COMPUTE_DIRECTORY(socket_dir);
514 basedir=WWWDIR "/static";
515 COMPUTE_DIRECTORY(static_dir);
516 basedir=WWWDIR "/static/icons";
517 COMPUTE_DIRECTORY(static_icon_dir);
518 basedir=WWWDIR "/static.local";
519 COMPUTE_DIRECTORY(static_local_dir);
520 StripSlashes(static_dir, 1);
521 StripSlashes(static_icon_dir, 1);
522 StripSlashes(static_local_dir, 1);
524 snprintf(file_crpt_file_key,
525 sizeof file_crpt_file_key,
528 snprintf(file_crpt_file_csr,
529 sizeof file_crpt_file_csr,
532 snprintf(file_crpt_file_cer,
533 sizeof file_crpt_file_cer,
539 COMPUTE_DIRECTORY(etc_dir);
540 StripSlashes(etc_dir, 1);
541 snprintf(file_etc_mimelist,
542 sizeof file_etc_mimelist,
543 "%s/nogz-mimetypes.txt",
546 /* we should go somewhere we can leave our coredump, if enabled... */
547 syslog(LOG_INFO, "Changing directory to %s\n", socket_dir);
548 if (chdir(webcitdir) != 0) {
553 void drop_root(uid_t UID)
555 struct passwd pw, *pwp = NULL;
556 #ifdef HAVE_GETPWUID_R
561 * Now that we've bound the sockets, change to the Citadel user id and its
562 * corresponding group ids
566 #ifdef HAVE_GETPWUID_R
567 #ifdef SOLARIS_GETPWUID
568 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
569 #else /* SOLARIS_GETPWUID */
570 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
571 #endif /* SOLARIS_GETPWUID */
572 #else /* HAVE_GETPWUID_R */
574 #endif /* HAVE_GETPWUID_R */
577 syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n"
578 "Group IDs will be incorrect.\n", UID,
581 initgroups(pw.pw_name, pw.pw_gid);
582 if (setgid(pw.pw_gid))
583 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
586 syslog(LOG_INFO, "Changing uid to %ld\n", (long)UID);
587 if (setuid(UID) != 0) {
588 syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
590 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
591 prctl(PR_SET_DUMPABLE, 1);
598 * print the actual stack frame.
600 void wc_backtrace(long LogLevel)
602 #ifdef HAVE_BACKTRACE
603 void *stack_frames[50];
608 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
609 strings = backtrace_symbols(stack_frames, size);
610 for (i = 0; i < size; i++) {
612 syslog(LogLevel, "%s\n", strings[i]);
614 syslog(LogLevel, "%p\n", stack_frames[i]);