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 const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /* nailed to what configure gives us. */
74 const char markdown_editor_absolutedir[]=MARKDOWNEDITORDIR;
76 char etc_dir[PATH_MAX];
77 char static_dir[PATH_MAX]; /* calculated on startup */
78 char static_local_dir[PATH_MAX]; /* calculated on startup */
79 char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
80 char *static_dirs[]={ /* needs same sort order as the web mapping */
81 (char*)static_dir, /* our templates on disk */
82 (char*)static_local_dir, /* user provided templates disk */
83 (char*)editor_absolut_dir, /* the editor on disk */
84 (char*)static_icon_dir, /* our icons... */
85 (char*)markdown_editor_absolutedir
89 HashList *GZMimeBlackList = NULL; /* mimetypes which shouldn't be gzip compressed */
91 void LoadMimeBlacklist(void)
93 StrBuf *MimeBlackLine;
97 memset(&IOB, 0, sizeof(IOBuffer));
98 IOB.fd = open(file_etc_mimelist, O_RDONLY);
100 IOB.Buf = NewStrBuf();
101 MimeBlackLine = NewStrBuf();
102 GZMimeBlackList = NewHash(1, NULL);
106 state = StrBufChunkSipLine(MimeBlackLine, &IOB);
111 if (StrBuf_read_one_chunk_callback(IOB.fd, 0, &IOB) <= 0)
115 if ((StrLength(MimeBlackLine) > 1) &&
116 (*ChrPtr(MimeBlackLine) != '#'))
118 Put(GZMimeBlackList, SKEY(MimeBlackLine),
119 (void*) 1, reference_free_handler);
121 FlushStrBuf(MimeBlackLine);
125 case eBufferNotEmpty:
129 while (state != eReadFail);
133 FreeStrBuf(&IOB.Buf);
134 FreeStrBuf(&MimeBlackLine);
137 void CheckGZipCompressionAllowed(const char *MimeType, long MLen)
142 if (WCC->Hdr->HR.gzip_ok)
143 WCC->Hdr->HR.gzip_ok = GetHash(GZMimeBlackList, MimeType, MLen, &v) == 0;
146 void InitialiseSemaphores(void)
150 /* Set up a bunch of semaphores to be used for critical sections */
151 for (i=0; i<MAX_SEMAPHORES; ++i) {
152 pthread_mutex_init(&Critters[i], NULL);
157 syslog(LOG_WARNING, "Failed to open exit pipe: %d [%s]\n",
166 * Obtain a semaphore lock to begin a critical section.
168 void begin_critical_section(int which_one)
170 pthread_mutex_lock(&Critters[which_one]);
174 * Release a semaphore lock to end a critical section.
176 void end_critical_section(int which_one)
178 pthread_mutex_unlock(&Critters[which_one]);
182 void ShutDownWebcit(void)
185 DeleteHash(&GZMimeBlackList);
186 free_zone_directory ();
187 icaltimezone_release_zone_tab ();
188 icalmemory_free_ring ();
189 ShutDownLibCitadel ();
199 * Entry point for worker threads
201 void worker_entry(void)
205 int fail_this_transaction = 0;
208 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
209 Hdr.HR.eReqType = eGET;
210 http_new_modules(&Hdr);
213 /* Each worker thread blocks on accept() while waiting for something to do. */
214 fail_this_transaction = 0;
219 --num_threads_executing;
221 FD_SET(msock, &wset);
222 FD_SET(ExitPipe[1], &wset);
224 select(msock + 1, NULL, &wset, NULL, NULL);
228 ssock = accept(msock, NULL, 0);
229 ++num_threads_executing;
230 if (ssock < 0) fail_this_transaction = 1;
231 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
233 if ((msock == -1)||(time_to_die))
234 {/* ok, we're going down. */
237 /* The first thread to get here will have to do the cleanup.
238 * Make sure it's really just one.
240 begin_critical_section(S_SHUTDOWN);
246 end_critical_section(S_SHUTDOWN);
248 {/* we're the one to cleanup the mess. */
249 http_destroy_modules(&Hdr);
250 syslog(LOG_DEBUG, "I'm master shutdown: tagging sessions to be killed.\n");
252 syslog(LOG_DEBUG, "master shutdown: waiting for others\n");
253 sleeeeeeeeeep(1); /* wait so some others might finish... */
254 syslog(LOG_DEBUG, "master shutdown: cleaning up sessions\n");
256 syslog(LOG_DEBUG, "master shutdown: cleaning up libical\n");
260 syslog(LOG_DEBUG, "master shutdown exiting.\n");
265 if (ssock < 0 ) continue;
267 check_thread_pool_size();
269 /* Now do something. */
271 if (ssock > 0) close (ssock);
272 syslog(LOG_DEBUG, "in between.");
275 /* Got it? do some real work! */
276 /* Set the SO_REUSEADDR socket option */
278 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
280 /* If we are an HTTPS server, go crypto now. */
283 if (starttls(ssock) != 0) {
284 fail_this_transaction = 1;
292 fdflags = fcntl(ssock, F_GETFL);
294 syslog(LOG_WARNING, "unable to get server socket flags! %s \n",
296 fdflags = fdflags | O_NONBLOCK;
297 if (fcntl(ssock, F_SETFL, fdflags) < 0)
298 syslog(LOG_WARNING, "unable to set server socket nonblocking flags! %s \n",
302 if (fail_this_transaction == 0) {
303 Hdr.http_sock = ssock;
305 /* Perform an HTTP transaction... */
308 /* Shut down SSL/TLS if required... */
315 /* ...and close the socket. */
316 if (Hdr.http_sock > 0) {
317 lingering_close(ssock);
319 http_detach_modules(&Hdr);
325 } while (!time_to_die);
327 http_destroy_modules(&Hdr);
328 syslog(LOG_DEBUG, "Thread exiting.\n");
334 * Shut us down the regular way.
335 * signum is the signal we want to forward
338 void graceful_shutdown_watcher(int signum) {
339 syslog(LOG_INFO, "Watcher thread exiting.\n");
340 write(ExitPipe[0], HKEY(" "));
341 kill(current_child, signum);
342 if (signum != SIGHUP)
348 * Shut us down the regular way.
349 * signum is the signal we want to forward
352 void graceful_shutdown(int signum) {
356 syslog(LOG_INFO, "WebCit is being shut down on signal %d.\n", signum);
364 write(ExitPipe[0], HKEY(" "));
369 * Start running as a daemon.
371 void start_daemon(char *pid_file)
380 /* Close stdin/stdout/stderr and replace them with /dev/null.
381 * We don't just call close() because we don't want these fd's
382 * to be reused for other files.
386 signal(SIGHUP, SIG_IGN);
387 signal(SIGINT, SIG_IGN);
388 signal(SIGQUIT, SIG_IGN);
397 freopen("/dev/null", "r", stdin);
398 freopen("/dev/null", "w", stdout);
399 freopen("/dev/null", "w", stderr);
400 signal(SIGTERM, graceful_shutdown_watcher);
401 signal(SIGHUP, graceful_shutdown_watcher);
404 current_child = fork();
407 if (current_child < 0) {
409 ShutDownLibCitadel ();
413 else if (current_child == 0) { /* child process */
414 signal(SIGHUP, graceful_shutdown);
416 return; /* continue starting webcit. */
418 else { /* watcher process */
420 fp = fopen(pid_file, "w");
422 fprintf(fp, "%d\n", getpid());
426 waitpid(current_child, &status, 0);
431 /* Did the main process exit with an actual exit code? */
432 if (WIFEXITED(status)) {
434 /* Exit code 0 means the watcher should exit */
435 if (WEXITSTATUS(status) == 0) {
439 /* Exit code 101-109 means the watcher should exit */
440 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
444 /* Any other exit code means we should restart. */
450 /* Any other type of termination (signals, etc.) should also restart. */
455 } while (do_restart);
460 ShutDownLibCitadel ();
461 exit(WEXITSTATUS(status));
466 * Spawn an additional worker thread into the pool.
468 void spawn_another_worker_thread()
470 pthread_t SessThread; /* Thread descriptor */
471 pthread_attr_t attr; /* Thread attributes */
474 ++num_threads_existing;
475 ++num_threads_executing;
477 /* set attributes for the new thread */
478 pthread_attr_init(&attr);
479 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
482 * Our per-thread stacks need to be bigger than the default size,
483 * otherwise the MIME parser crashes on FreeBSD.
485 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
486 syslog(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(ret));
487 pthread_attr_destroy(&attr);
490 /* now create the thread */
491 if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
492 syslog(LOG_WARNING, "Can't create thread: %s\n", strerror(errno));
495 /* free up the attributes */
496 pthread_attr_destroy(&attr);
501 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
503 char dirbuffer[PATH_MAX]="";
504 /* calculate all our path on a central place */
505 /* where to keep our config */
507 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
508 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
509 (home&!relh)?webcitdir:basedir, \
510 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
511 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
513 (relhome[0]!='\0')?"/":"",\
515 (dirbuffer[0]!='\0')?"/":"");
517 COMPUTE_DIRECTORY(socket_dir);
518 basedir=WWWDIR "/static";
519 COMPUTE_DIRECTORY(static_dir);
520 basedir=WWWDIR "/static/icons";
521 COMPUTE_DIRECTORY(static_icon_dir);
522 basedir=WWWDIR "/static.local";
523 COMPUTE_DIRECTORY(static_local_dir);
524 StripSlashes(static_dir, 1);
525 StripSlashes(static_icon_dir, 1);
526 StripSlashes(static_local_dir, 1);
528 snprintf(file_crpt_file_key,
529 sizeof file_crpt_file_key,
532 snprintf(file_crpt_file_csr,
533 sizeof file_crpt_file_csr,
536 snprintf(file_crpt_file_cer,
537 sizeof file_crpt_file_cer,
543 COMPUTE_DIRECTORY(etc_dir);
544 StripSlashes(etc_dir, 1);
545 snprintf(file_etc_mimelist,
546 sizeof file_etc_mimelist,
547 "%s/nogz-mimetypes.txt",
550 /* we should go somewhere we can leave our coredump, if enabled... */
551 syslog(LOG_INFO, "Changing directory to %s\n", socket_dir);
552 if (chdir(webcitdir) != 0) {
557 void drop_root(uid_t UID)
559 struct passwd pw, *pwp = NULL;
560 #ifdef HAVE_GETPWUID_R
565 * Now that we've bound the sockets, change to the Citadel user id and its
566 * corresponding group ids
570 #ifdef HAVE_GETPWUID_R
571 #ifdef SOLARIS_GETPWUID
572 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
573 #else /* SOLARIS_GETPWUID */
574 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
575 #endif /* SOLARIS_GETPWUID */
576 #else /* HAVE_GETPWUID_R */
578 #endif /* HAVE_GETPWUID_R */
581 syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n"
582 "Group IDs will be incorrect.\n", UID,
585 initgroups(pw.pw_name, pw.pw_gid);
586 if (setgid(pw.pw_gid))
587 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
590 syslog(LOG_INFO, "Changing uid to %ld\n", (long)UID);
591 if (setuid(UID) != 0) {
592 syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
594 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
595 prctl(PR_SET_DUMPABLE, 1);
602 * print the actual stack frame.
604 void wc_backtrace(long LogLevel)
606 #ifdef HAVE_BACKTRACE
607 void *stack_frames[50];
612 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
613 strings = backtrace_symbols(stack_frames, size);
614 for (i = 0; i < size; i++) {
616 syslog(LogLevel, "%s\n", strings[i]);
618 syslog(LogLevel, "%p\n", stack_frames[i]);