4 * WebCit "system dependent" code.
6 * Copyright (c) 1996-2010 by the citadel.org team
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 #include <sys/types.h>
33 #include <sys/socket.h>
35 #include <sys/syslog.h>
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
42 # include <sys/time.h>
49 #include <sys/resource.h>
50 #include <netinet/in.h>
51 #include <netinet/tcp.h>
52 #include <arpa/inet.h>
66 #ifdef HAVE_SYS_SELECT_H
67 #include <sys/select.h>
73 #include "webserver.h"
74 #include "modules_init.h"
79 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
80 pthread_key_t MyConKey; /* TSD key for MyContext() */
81 pthread_key_t MyReq; /* TSD key for MyReq() */
82 int msock; /* master listening socket */
83 int time_to_die = 0; /* Nonzero if server is shutting down */
84 int verbosity = 9; /* Logging level */
86 extern void *context_loop(ParsedHttpHdrs *Hdr);
87 extern void *housekeeping_loop(void);
89 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
90 char file_crpt_file_key[PATH_MAX]="";
91 char file_crpt_file_csr[PATH_MAX]="";
92 char file_crpt_file_cer[PATH_MAX]="";
94 const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /* nailed to what configure gives us. */
95 char static_dir[PATH_MAX]; /* calculated on startup */
96 char static_local_dir[PATH_MAX]; /* calculated on startup */
97 char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
98 char *static_dirs[]={ /* needs same sort order as the web mapping */
99 (char*)static_dir, /* our templates on disk */
100 (char*)static_local_dir, /* user provided templates disk */
101 (char*)editor_absolut_dir, /* the editor on disk */
102 (char*)static_icon_dir /* our icons... */
105 void InitialiseSemaphores(void)
109 /* Set up a bunch of semaphores to be used for critical sections */
110 for (i=0; i<MAX_SEMAPHORES; ++i) {
111 pthread_mutex_init(&Critters[i], NULL);
116 * Obtain a semaphore lock to begin a critical section.
118 void begin_critical_section(int which_one)
120 /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
121 pthread_mutex_lock(&Critters[which_one]);
125 * Release a semaphore lock to end a critical section.
127 void end_critical_section(int which_one)
129 pthread_mutex_unlock(&Critters[which_one]);
133 void ShutDownWebcit(void)
135 free_zone_directory ();
136 icaltimezone_release_zone_tab ();
137 icalmemory_free_ring ();
138 ShutDownLibCitadel ();
148 * Entry point for worker threads
150 void worker_entry(void)
154 int fail_this_transaction = 0;
157 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
158 Hdr.HR.eReqType = eGET;
159 http_new_modules(&Hdr);
162 /* Only one thread can accept at a time */
163 fail_this_transaction = 0;
167 --num_threads_executing;
168 ssock = accept(msock, NULL, 0);
169 ++num_threads_executing;
170 lprintf(9, "Thread %u woke up, accept() returned %d %s\n",
173 ((ssock >= 0) ? "" : strerror(errno))
175 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
177 if ((msock == -1)||(time_to_die))
178 {/* ok, we're going down. */
181 /* The first thread to get here will have to do the cleanup.
182 * Make sure it's really just one.
184 begin_critical_section(S_SHUTDOWN);
190 end_critical_section(S_SHUTDOWN);
192 {/* we're the one to cleanup the mess. */
193 http_destroy_modules(&Hdr);
194 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
196 lprintf(2, "master shutdown: waiting for others\n");
197 sleeeeeeeeeep(1); /* wait so some others might finish... */
198 lprintf(2, "master shutdown: cleaning up sessions\n");
200 lprintf(2, "master shutdown: cleaning up libical\n");
204 lprintf(2, "master shutdown exiting!.\n");
209 if (ssock < 0 ) continue;
211 /* Now do something. */
213 if (ssock > 0) close (ssock);
214 lprintf(2, "in between.");
217 /* Got it? do some real work! */
218 /* Set the SO_REUSEADDR socket option */
220 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
222 /* If we are an HTTPS server, go crypto now. */
225 if (starttls(ssock) != 0) {
226 fail_this_transaction = 1;
234 fdflags = fcntl(ssock, F_GETFL);
236 lprintf(1, "unable to get server socket flags! %s \n",
238 fdflags = fdflags | O_NONBLOCK;
239 if (fcntl(ssock, F_SETFL, fdflags) < 0)
240 lprintf(1, "unable to set server socket nonblocking flags! %s \n",
244 if (fail_this_transaction == 0) {
245 Hdr.http_sock = ssock;
247 /* Perform an HTTP transaction... */
250 /* Shut down SSL/TLS if required... */
257 /* ...and close the socket. */
258 if (Hdr.http_sock > 0) {
259 lingering_close(ssock);
261 http_detach_modules(&Hdr);
267 } while (!time_to_die);
269 http_destroy_modules(&Hdr);
270 lprintf (1, "bye\n");
276 * logs to stderr if loglevel is lower than the verbosity set at startup
278 * loglevel level of the message
279 * format the printf like format string
280 * ... the strings to put into format
282 int lprintf(int loglevel, const char *format, ...)
286 if (loglevel <= verbosity) {
287 va_start(ap, format);
288 vfprintf(stderr, format, ap);
296 * Shut us down the regular way.
297 * signum is the signal we want to forward
300 void graceful_shutdown_watcher(int signum) {
301 lprintf (1, "bye; shutting down watcher.");
302 kill(current_child, signum);
303 if (signum != SIGHUP)
309 * Shut us down the regular way.
310 * signum is the signal we want to forward
313 void graceful_shutdown(int signum) {
317 lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
329 * Start running as a daemon.
331 void start_daemon(char *pid_file)
342 /* Close stdin/stdout/stderr and replace them with /dev/null.
343 * We don't just call close() because we don't want these fd's
344 * to be reused for other files.
348 signal(SIGHUP, SIG_IGN);
349 signal(SIGINT, SIG_IGN);
350 signal(SIGQUIT, SIG_IGN);
359 rvfp = freopen("/dev/null", "r", stdin);
360 rvfp = freopen("/dev/null", "w", stdout);
361 rvfp = freopen("/dev/null", "w", stderr);
362 signal(SIGTERM, graceful_shutdown_watcher);
363 signal(SIGHUP, graceful_shutdown_watcher);
366 current_child = fork();
369 if (current_child < 0) {
371 ShutDownLibCitadel ();
375 else if (current_child == 0) { /* child process */
376 signal(SIGHUP, graceful_shutdown);
378 return; /* continue starting webcit. */
380 else { /* watcher process */
382 fp = fopen(pid_file, "w");
384 fprintf(fp, "%d\n", getpid());
388 waitpid(current_child, &status, 0);
393 /* Did the main process exit with an actual exit code? */
394 if (WIFEXITED(status)) {
396 /* Exit code 0 means the watcher should exit */
397 if (WEXITSTATUS(status) == 0) {
401 /* Exit code 101-109 means the watcher should exit */
402 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
406 /* Any other exit code means we should restart. */
412 /* Any other type of termination (signals, etc.) should also restart. */
417 } while (do_restart);
422 ShutDownLibCitadel ();
423 exit(WEXITSTATUS(status));
428 * Spawn an additional worker thread into the pool.
430 void spawn_another_worker_thread()
432 pthread_t SessThread; /* Thread descriptor */
433 pthread_attr_t attr; /* Thread attributes */
436 lprintf(3, "Creating a new thread.\n");
438 ++num_threads_existing;
439 ++num_threads_executing;
441 /* set attributes for the new thread */
442 pthread_attr_init(&attr);
443 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
446 * Our per-thread stacks need to be bigger than the default size,
447 * otherwise the MIME parser crashes on FreeBSD.
449 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
450 lprintf(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
451 pthread_attr_destroy(&attr);
454 /* now create the thread */
455 if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
456 lprintf(1, "Can't create thread: %s\n", strerror(errno));
459 /* free up the attributes */
460 pthread_attr_destroy(&attr);
465 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
467 char dirbuffer[PATH_MAX]="";
468 /* calculate all our path on a central place */
469 /* where to keep our config */
471 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
472 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
473 (home&!relh)?webcitdir:basedir, \
474 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
475 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
477 (relhome[0]!='\0')?"/":"",\
479 (dirbuffer[0]!='\0')?"/":"");
481 COMPUTE_DIRECTORY(socket_dir);
482 basedir=WWWDIR "/static";
483 COMPUTE_DIRECTORY(static_dir);
484 basedir=WWWDIR "/static/icons";
485 COMPUTE_DIRECTORY(static_icon_dir);
486 basedir=WWWDIR "/static.local";
487 COMPUTE_DIRECTORY(static_local_dir);
488 StripSlashes(static_dir, 1);
489 StripSlashes(static_icon_dir, 1);
490 StripSlashes(static_local_dir, 1);
492 snprintf(file_crpt_file_key,
493 sizeof file_crpt_file_key,
496 snprintf(file_crpt_file_csr,
497 sizeof file_crpt_file_csr,
500 snprintf(file_crpt_file_cer,
501 sizeof file_crpt_file_cer,
505 /* we should go somewhere we can leave our coredump, if enabled... */
506 lprintf(9, "Changing directory to %s\n", socket_dir);
507 if (chdir(webcitdir) != 0) {
512 void drop_root(uid_t UID)
514 struct passwd pw, *pwp = NULL;
517 * Now that we've bound the sockets, change to the Citadel user id and its
518 * corresponding group ids
522 #ifdef HAVE_GETPWUID_R
523 #ifdef SOLARIS_GETPWUID
524 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
525 #else // SOLARIS_GETPWUID
526 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
527 #endif // SOLARIS_GETPWUID
528 #else // HAVE_GETPWUID_R
530 #endif // HAVE_GETPWUID_R
533 lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
534 "Group IDs will be incorrect.\n", UID,
537 initgroups(pw.pw_name, pw.pw_gid);
538 if (setgid(pw.pw_gid))
539 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
542 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)UID);
543 if (setuid(UID) != 0) {
544 lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
546 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
547 prctl(PR_SET_DUMPABLE, 1);
554 * print the actual stack frame.
556 void wc_backtrace(void)
558 #ifdef HAVE_BACKTRACE
559 void *stack_frames[50];
564 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
565 strings = backtrace_symbols(stack_frames, size);
566 for (i = 0; i < size; i++) {
568 lprintf(1, "%s\n", strings[i]);
570 lprintf(1, "%p\n", stack_frames[i]);