3 * WebCit "system dependent" code.
5 * Copyright (c) 1996-2021 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 3.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
23 #include <sys/types.h>
26 #include <sys/socket.h>
28 #include <sys/syslog.h>
31 #include <sys/resource.h>
32 #include <netinet/in.h>
33 #include <netinet/tcp.h>
34 #include <arpa/inet.h>
48 #ifdef HAVE_SYS_SELECT_H
49 #include <sys/select.h>
52 #include "webserver.h"
53 #include "modules_init.h"
58 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
59 pthread_key_t MyConKey; /* TSD key for MyContext() */
60 pthread_key_t MyReq; /* TSD key for MyReq() */
61 int msock; /* master listening socket */
62 int time_to_die = 0; /* Nonzero if server is shutting down */
64 extern void *context_loop(ParsedHttpHdrs * Hdr);
65 extern void *housekeeping_loop(void);
66 extern void do_housekeeping(void);
68 char file_etc_mimelist[PATH_MAX] = "";
70 char etc_dir[PATH_MAX];
71 char static_dir[PATH_MAX]; /* calculated on startup */
72 char static_local_dir[PATH_MAX]; /* calculated on startup */
73 char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
74 char *static_dirs[] = { /* needs same sort order as the web mapping */
78 "./static/webcit_icons"
82 HashList *GZMimeBlackList = NULL; /* mimetypes which shouldn't be gzip compressed */
84 void LoadMimeBlacklist(void) {
85 StrBuf *MimeBlackLine;
89 memset(&IOB, 0, sizeof(IOBuffer));
90 IOB.fd = open(file_etc_mimelist, O_RDONLY);
92 IOB.Buf = NewStrBuf();
93 MimeBlackLine = NewStrBuf();
94 GZMimeBlackList = NewHash(1, NULL);
97 state = StrBufChunkSipLine(MimeBlackLine, &IOB);
101 if (StrBuf_read_one_chunk_callback(IOB.fd, 0, &IOB) <= 0)
105 if ((StrLength(MimeBlackLine) > 1) && (*ChrPtr(MimeBlackLine) != '#')) {
106 Put(GZMimeBlackList, SKEY(MimeBlackLine), (void *) 1, reference_free_handler);
108 FlushStrBuf(MimeBlackLine);
112 case eBufferNotEmpty:
116 while (state != eReadFail);
120 FreeStrBuf(&IOB.Buf);
121 FreeStrBuf(&MimeBlackLine);
124 void CheckGZipCompressionAllowed(const char *MimeType, long MLen) {
127 if (WC->Hdr->HR.gzip_ok)
128 WC->Hdr->HR.gzip_ok = GetHash(GZMimeBlackList, MimeType, MLen, &v) == 0;
131 void InitialiseSemaphores(void) {
134 /* Set up a bunch of semaphores to be used for critical sections */
135 for (i = 0; i < MAX_SEMAPHORES; ++i) {
136 pthread_mutex_init(&Critters[i], NULL);
139 if (pipe(ExitPipe)) {
140 syslog(LOG_WARNING, "Failed to open exit pipe: %d [%s]\n", errno, strerror(errno));
147 * Obtain a semaphore lock to begin a critical section.
149 void begin_critical_section(int which_one) {
150 pthread_mutex_lock(&Critters[which_one]);
154 * Release a semaphore lock to end a critical section.
156 void end_critical_section(int which_one) {
157 pthread_mutex_unlock(&Critters[which_one]);
161 void ShutDownWebcit(void) {
163 DeleteHash(&GZMimeBlackList);
164 free_zone_directory();
165 icaltimezone_release_zone_tab();
166 icalmemory_free_ring();
167 ShutDownLibCitadel();
172 * Entry point for worker threads
174 void worker_entry(void) {
177 int fail_this_transaction = 0;
180 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
181 Hdr.HR.eReqType = eGET;
182 http_new_modules(&Hdr);
185 /* Each worker thread blocks on accept() while waiting for something to do. */
186 fail_this_transaction = 0;
191 --num_threads_executing;
193 FD_SET(msock, &wset);
194 FD_SET(ExitPipe[1], &wset);
196 select(msock + 1, NULL, &wset, NULL, NULL);
200 ssock = accept(msock, NULL, 0);
201 ++num_threads_executing;
203 fail_this_transaction = 1;
204 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
206 if ((msock == -1) || (time_to_die)) { /* ok, we're going down. */
209 /* The first thread to get here will have to do the cleanup.
210 * Make sure it's really just one.
212 begin_critical_section(S_SHUTDOWN);
217 end_critical_section(S_SHUTDOWN);
218 if (shutdown == 1) { /* we're the one to cleanup the mess. */
219 http_destroy_modules(&Hdr);
220 syslog(LOG_DEBUG, "I'm master shutdown: tagging sessions to be killed.\n");
222 syslog(LOG_DEBUG, "master shutdown: waiting for others\n");
223 sleeeeeeeeeep(1); /* wait so some others might finish... */
224 syslog(LOG_DEBUG, "master shutdown: cleaning up sessions\n");
226 syslog(LOG_DEBUG, "master shutdown: cleaning up libical\n");
230 syslog(LOG_DEBUG, "master shutdown exiting.\n");
238 check_thread_pool_size();
240 /* Now do something. */
244 syslog(LOG_DEBUG, "in between.");
248 /* Got it? do some real work! */
249 /* Set the SO_REUSEADDR socket option */
251 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
253 /* If we are an HTTPS server, go crypto now. */
256 if (starttls(ssock) != 0) {
257 fail_this_transaction = 1;
265 fdflags = fcntl(ssock, F_GETFL);
267 syslog(LOG_WARNING, "unable to get server socket flags! %s \n", strerror(errno));
268 fdflags = fdflags | O_NONBLOCK;
269 if (fcntl(ssock, F_SETFL, fdflags) < 0)
270 syslog(LOG_WARNING, "unable to set server socket nonblocking flags! %s \n",
274 if (fail_this_transaction == 0) {
275 Hdr.http_sock = ssock;
277 /* Perform an HTTP transaction... */
280 /* Shut down SSL/TLS if required... */
287 /* ...and close the socket. */
288 if (Hdr.http_sock > 0) {
289 lingering_close(ssock);
291 http_detach_modules(&Hdr);
297 } while (!time_to_die);
299 http_destroy_modules(&Hdr);
300 syslog(LOG_DEBUG, "Thread exiting.\n");
306 * Shut us down the regular way.
307 * signum is the signal we want to forward
310 void graceful_shutdown_watcher(int signum) {
311 syslog(LOG_INFO, "Watcher thread exiting.\n");
312 write(ExitPipe[0], HKEY(" "));
313 kill(current_child, signum);
314 if (signum != SIGHUP)
320 * Shut us down the regular way.
321 * signum is the signal we want to forward
324 void graceful_shutdown(int signum) {
328 syslog(LOG_INFO, "WebCit is being shut down on signal %d.\n", signum);
332 FD = fdopen(fd, "a+");
336 write(ExitPipe[0], HKEY(" "));
341 * Start running as a daemon.
343 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 freopen("/dev/null", "r", stdin);
369 freopen("/dev/null", "w", stdout);
370 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));
437 * Spawn an additional worker thread into the pool.
439 void spawn_another_worker_thread() {
440 pthread_t SessThread; /* Thread descriptor */
441 pthread_attr_t attr; /* Thread attributes */
444 ++num_threads_existing;
445 ++num_threads_executing;
447 /* set attributes for the new thread */
448 pthread_attr_init(&attr);
449 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
452 * Our per-thread stacks need to be bigger than the default size,
453 * otherwise the MIME parser crashes on FreeBSD.
455 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
456 syslog(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(ret));
457 pthread_attr_destroy(&attr);
460 /* now create the thread */
461 if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
462 syslog(LOG_WARNING, "Can't create thread: %s\n", strerror(errno));
465 /* free up the attributes */
466 pthread_attr_destroy(&attr);
470 void webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome) {
471 char dirbuffer[PATH_MAX] = "";
472 /* calculate all our path on a central place */
473 /* where to keep our config */
475 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
476 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
477 (home&!relh)?webcitdir:basedir, \
478 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
479 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
481 (relhome[0]!='\0')?"/":"",\
483 (dirbuffer[0]!='\0')?"/":"");
485 COMPUTE_DIRECTORY(socket_dir);
486 basedir = WWWDIR "/static";
487 COMPUTE_DIRECTORY(static_dir);
488 basedir = WWWDIR "/static/icons";
489 COMPUTE_DIRECTORY(static_icon_dir);
490 basedir = WWWDIR "/static.local";
491 COMPUTE_DIRECTORY(static_local_dir);
492 StripSlashes(static_dir, 1);
493 StripSlashes(static_icon_dir, 1);
494 StripSlashes(static_local_dir, 1);
497 COMPUTE_DIRECTORY(etc_dir);
498 StripSlashes(etc_dir, 1);
499 snprintf(file_etc_mimelist, sizeof file_etc_mimelist, "%s/nogz-mimetypes.txt", etc_dir);
501 /* we should go somewhere we can leave our coredump, if enabled... */
502 syslog(LOG_INFO, "Changing directory to %s\n", socket_dir);
503 if (chdir(webcitdir) != 0) {
508 void drop_root(uid_t UID) {
509 struct passwd pw, *pwp = NULL;
510 #ifdef HAVE_GETPWUID_R
515 * Now that we've bound the sockets, change to the Citadel user id and its
516 * corresponding group ids
520 #ifdef HAVE_GETPWUID_R
521 #ifdef SOLARIS_GETPWUID
522 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
523 #else /* SOLARIS_GETPWUID */
524 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
525 #endif /* SOLARIS_GETPWUID */
526 #else /* HAVE_GETPWUID_R */
528 #endif /* HAVE_GETPWUID_R */
531 syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n" "Group IDs will be incorrect.\n", UID, strerror(errno));
533 initgroups(pw.pw_name, pw.pw_gid);
534 if (setgid(pw.pw_gid))
535 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long) pw.pw_gid, strerror(errno));
537 syslog(LOG_INFO, "Changing uid to %ld\n", (long) UID);
538 if (setuid(UID) != 0) {
539 syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
541 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
542 prctl(PR_SET_DUMPABLE, 1);
549 * print the actual stack frame.
551 void wc_backtrace(long LogLevel) {
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 syslog(LogLevel, "%s\n", strings[i]);
564 syslog(LogLevel, "%p\n", stack_frames[i]);