4 * Citadel "system dependent" stuff.
5 * See COPYING for copyright information.
7 * Here's where we (hopefully) have most parts of the Citadel server that
8 * would need to be altered to run the server in a non-POSIX environment.
10 * If we ever port to a different platform and either have multiple
11 * variants of this file or simply load it up with #ifdefs.
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>
52 #include <libcitadel.h>
55 #include "sysdep_decls.h"
56 #include "citserver.h"
60 #include "housekeeping.h"
61 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
72 #include "ctdl_module.h"
78 #ifdef DEBUG_MEMORY_LEAKS
86 struct igheap *igheap = NULL;
90 citthread_key_t MyConKey; /* TSD key for MyContext() */
92 int verbosity = DEFAULT_VERBOSITY; /* Logging level */
94 struct CitContext masterCC;
95 time_t last_purge = 0; /* Last dead session purge */
96 int num_sessions = 0; /* Current number of sessions */
98 int syslog_facility = LOG_DAEMON;
99 int enable_syslog = 0;
102 /* Flag for single user mode */
103 static int want_single_user = 0;
105 /* Try to go single user */
107 int CtdlTrySingleUser(void)
111 begin_critical_section(S_SINGLE_USER);
112 if (want_single_user)
117 want_single_user = 1;
119 end_critical_section(S_SINGLE_USER);
123 void CtdlEndSingleUser(void)
125 begin_critical_section(S_SINGLE_USER);
126 want_single_user = 0;
127 end_critical_section(S_SINGLE_USER);
131 int CtdlWantSingleUser(void)
133 return want_single_user;
136 int CtdlIsSingleUser(void)
138 if (want_single_user)
140 /* check for only one context here */
141 if (num_sessions == 1)
149 * CtdlLogPrintf() ... Write logging information
151 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {
153 va_start(arg_ptr, format);
154 vCtdlLogPrintf(loglevel, format, arg_ptr);
158 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
160 char buf[SIZ], buf2[SIZ];
163 vsyslog((syslog_facility | loglevel), format, arg_ptr);
166 /* stderr output code */
167 if (enable_syslog || running_as_daemon) return;
169 /* if we run in forground and syslog is disabled, log to terminal */
170 if (loglevel <= verbosity) {
174 struct CitContext *CCC = CC;
176 gettimeofday(&tv, NULL);
177 /* Promote to time_t; types differ on some OSes (like darwin) */
178 unixtime = tv.tv_sec;
179 localtime_r(&unixtime, &tim);
180 if ((CCC != NULL) && (CCC->cs_pid != 0)) {
182 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
183 tim.tm_year + 1900, tim.tm_mon + 1,
184 tim.tm_mday, tim.tm_hour, tim.tm_min,
185 tim.tm_sec, (long)tv.tv_usec,
189 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
190 tim.tm_year + 1900, tim.tm_mon + 1,
191 tim.tm_mday, tim.tm_hour, tim.tm_min,
192 tim.tm_sec, (long)tv.tv_usec);
194 vsnprintf(buf2, SIZ, format, arg_ptr);
196 fprintf(stderr, "%s%s", buf, buf2);
204 * Signal handler to shut down the server.
207 volatile int exit_signal = 0;
208 volatile int shutdown_and_halt = 0;
209 volatile int restart_server = 0;
210 volatile int running_as_daemon = 0;
212 static RETSIGTYPE signal_cleanup(int signum) {
213 #ifdef THREADS_USESIGNALS
219 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
220 exit_signal = signum;
227 * Some initialization stuff...
229 void init_sysdep(void) {
232 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
236 getrlimit(RLIMIT_NOFILE, &rl);
237 rl.rlim_cur = FD_SETSIZE;
238 rl.rlim_max = FD_SETSIZE;
239 setrlimit(RLIMIT_NOFILE, &rl);
243 /* If we've got OpenSSL, we're going to use it. */
249 * Set up a place to put thread-specific data.
250 * We only need a single pointer per thread - it points to the
251 * CitContext structure (in the ContextList linked list) of the
252 * session to which the calling thread is currently bound.
254 if (citthread_key_create(&MyConKey, NULL) != 0) {
255 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
260 * The action for unexpected signals and exceptions should be to
261 * call signal_cleanup() to gracefully shut down the server.
264 sigaddset(&set, SIGINT);
265 sigaddset(&set, SIGQUIT);
266 sigaddset(&set, SIGHUP);
267 sigaddset(&set, SIGTERM);
268 // sigaddset(&set, SIGSEGV); commented out because
269 // sigaddset(&set, SIGILL); we want core dumps
270 // sigaddset(&set, SIGBUS);
271 sigprocmask(SIG_UNBLOCK, &set, NULL);
273 signal(SIGINT, signal_cleanup);
274 signal(SIGQUIT, signal_cleanup);
275 signal(SIGHUP, signal_cleanup);
276 signal(SIGTERM, signal_cleanup);
277 // signal(SIGSEGV, signal_cleanup); commented out because
278 // signal(SIGILL, signal_cleanup); we want core dumps
279 // signal(SIGBUS, signal_cleanup);
282 * Do not shut down the server on broken pipe signals, otherwise the
283 * whole Citadel service would come down whenever a single client
286 signal(SIGPIPE, SIG_IGN);
293 * This is a generic function to set up a master socket for listening on
294 * a TCP port. The server shuts down if the bind fails.
297 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
299 struct sockaddr_in sin;
301 int actual_queue_len;
303 actual_queue_len = queue_len;
304 if (actual_queue_len < 5) actual_queue_len = 5;
306 memset(&sin, 0, sizeof(sin));
307 sin.sin_family = AF_INET;
308 sin.sin_port = htons((u_short)port_number);
309 if (ip_addr == NULL) {
310 sin.sin_addr.s_addr = INADDR_ANY;
313 sin.sin_addr.s_addr = inet_addr(ip_addr);
316 if (sin.sin_addr.s_addr == !INADDR_ANY) {
317 sin.sin_addr.s_addr = INADDR_ANY;
320 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
323 *errormessage = (char*) malloc(SIZ + 1);
324 snprintf(*errormessage, SIZ,
325 "citserver: Can't create a socket: %s",
327 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
332 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
334 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
335 *errormessage = (char*) malloc(SIZ + 1);
336 snprintf(*errormessage, SIZ,
337 "citserver: Can't bind: %s",
339 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
344 /* set to nonblock - we need this for some obscure situations */
345 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
346 *errormessage = (char*) malloc(SIZ + 1);
347 snprintf(*errormessage, SIZ,
348 "citserver: Can't set socket to non-blocking: %s",
350 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
355 if (listen(s, actual_queue_len) < 0) {
356 *errormessage = (char*) malloc(SIZ + 1);
357 snprintf(*errormessage, SIZ,
358 "citserver: Can't listen: %s",
360 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
371 * Create a Unix domain socket and listen on it
373 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
375 struct sockaddr_un addr;
378 int actual_queue_len;
379 #ifdef HAVE_STRUCT_UCRED
383 actual_queue_len = queue_len;
384 if (actual_queue_len < 5) actual_queue_len = 5;
386 i = unlink(sockpath);
387 if ((i != 0) && (errno != ENOENT)) {
388 *errormessage = (char*) malloc(SIZ + 1);
389 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
390 sockpath, strerror(errno));
391 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
395 memset(&addr, 0, sizeof(addr));
396 addr.sun_family = AF_UNIX;
397 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
399 s = socket(AF_UNIX, SOCK_STREAM, 0);
401 *errormessage = (char*) malloc(SIZ + 1);
402 snprintf(*errormessage, SIZ,
403 "citserver: Can't create a socket: %s",
405 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
409 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
410 *errormessage = (char*) malloc(SIZ + 1);
411 snprintf(*errormessage, SIZ,
412 "citserver: Can't bind: %s",
414 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
418 /* set to nonblock - we need this for some obscure situations */
419 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
420 *errormessage = (char*) malloc(SIZ + 1);
421 snprintf(*errormessage, SIZ,
422 "citserver: Can't set socket to non-blocking: %s",
424 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
429 if (listen(s, actual_queue_len) < 0) {
430 *errormessage = (char*) malloc(SIZ + 1);
431 snprintf(*errormessage, SIZ,
432 "citserver: Can't listen: %s",
434 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
438 #ifdef HAVE_STRUCT_UCRED
439 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
442 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
449 * Return a pointer to the CitContext structure bound to the thread which
450 * called this function. If there's no such binding (for example, if it's
451 * called by the housekeeper thread) then a generic 'master' CC is returned.
453 * This function is used *VERY* frequently and must be kept small.
455 struct CitContext *MyContext(void) {
457 register struct CitContext *c;
459 return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
460 c == NULL) ? &masterCC : c
466 * Initialize a new context and place it in the list. The session number
467 * used to be the PID (which is why it's called cs_pid), but that was when we
468 * had one process per session. Now we just assign them sequentially, starting
469 * at 1 (don't change it to 0 because masterCC uses 0).
471 struct CitContext *CreateNewContext(void) {
472 struct CitContext *me;
473 static int next_pid = 0;
475 me = (struct CitContext *) malloc(sizeof(struct CitContext));
477 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
481 memset(me, 0, sizeof(struct CitContext));
483 /* Give the contaxt a name. Hopefully makes it easier to track */
484 strcpy (me->user.fullname, "SYS_notauth");
486 /* The new context will be created already in the CON_EXECUTING state
487 * in order to prevent another thread from grabbing it while it's
490 me->state = CON_EXECUTING;
492 * Generate a unique session number and insert this context into
495 begin_critical_section(S_SESSION_TABLE);
496 me->cs_pid = ++next_pid;
498 me->next = ContextList;
500 if (me->next != NULL) {
504 end_critical_section(S_SESSION_TABLE);
509 struct CitContext *CtdlGetContextArray(int *count)
512 struct CitContext *nptr, *cptr;
514 nContexts = num_sessions;
515 nptr = malloc(sizeof(struct CitContext) * nContexts);
518 begin_critical_section(S_SESSION_TABLE);
519 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
520 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
521 end_critical_section (S_SESSION_TABLE);
530 * This function fills in a context and its user field correctly
531 * Then creates/loads that user
533 void CtdlFillSystemContext(struct CitContext *context, char *name)
535 char sysname[USERNAME_SIZE];
537 memset(context, 0, sizeof(struct CitContext));
538 context->internal_pgm = 1;
540 strcpy (sysname, "SYS_");
541 strcat (sysname, name);
542 /* internal_create_user has the side effect of loading the user regardless of wether they
543 * already existed or needed to be created
545 internal_create_user (sysname, &(context->user), -1) ;
547 /* Check to see if the system user needs upgrading */
548 if (context->user.usernum == 0)
549 { /* old system user with number 0, upgrade it */
550 context->user.usernum = get_new_user_number();
551 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
552 /* add user to the database */
553 CtdlPutUser(&(context->user));
554 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
559 * The following functions implement output buffering on operating systems which
560 * support it (such as Linux and various BSD flavors).
564 # define HAVE_TCP_BUFFERING
567 # define HAVE_TCP_BUFFERING
568 # define TCP_CORK TCP_NOPUSH
570 #endif /* TCP_CORK */
571 #endif /* HAVE_DARWIN */
573 static unsigned on = 1, off = 0;
575 void buffer_output(void) {
576 #ifdef HAVE_TCP_BUFFERING
578 if (!CC->redirect_ssl)
580 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
584 void unbuffer_output(void) {
585 #ifdef HAVE_TCP_BUFFERING
587 if (!CC->redirect_ssl)
589 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
593 void flush_output(void) {
594 #ifdef HAVE_TCP_BUFFERING
595 struct CitContext *CCC = CC;
596 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
597 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
604 * client_write() ... Send binary data to the client.
606 int client_write(char *buf, int nbytes)
608 int bytes_written = 0;
610 #ifndef HAVE_TCP_BUFFERING
611 int old_buffer_len = 0;
618 if (Ctx->redirect_buffer != NULL) {
619 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
620 Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
621 Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
622 Ctx->redirect_alloc);
624 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
625 Ctx->redirect_len += nbytes;
626 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
631 if (Ctx->redirect_ssl) {
632 client_write_ssl(buf, nbytes);
637 fdflags = fcntl(Ctx->client_socket, F_GETFL);
639 while (bytes_written < nbytes) {
640 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
642 FD_SET(Ctx->client_socket, &wset);
643 if (select(1, NULL, &wset, NULL, NULL) == -1) {
644 CtdlLogPrintf(CTDL_ERR,
645 "client_write(%d bytes) select failed: %s (%d)\n",
646 nbytes - bytes_written,
647 strerror(errno), errno);
654 retval = write(Ctx->client_socket, &buf[bytes_written],
655 nbytes - bytes_written);
657 CtdlLogPrintf(CTDL_ERR,
658 "client_write(%d bytes) failed: %s (%d)\n",
659 nbytes - bytes_written,
660 strerror(errno), errno);
662 // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s", &buf[bytes_written]);
666 bytes_written = bytes_written + retval;
673 * cprintf() Send formatted printable data to the client.
674 * Implemented in terms of client_write() so it's technically not sysdep...
676 void cprintf(const char *format, ...) {
680 va_start(arg_ptr, format);
681 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
682 buf[sizeof buf - 2] = '\n';
683 client_write(buf, strlen(buf));
689 * Read data from the client socket.
691 * 1 Requested number of bytes has been read.
692 * 0 Request timed out.
693 * -1 The socket is broken.
694 * If the socket breaks, the session will be terminated.
696 int client_read_to(char *buf, int bytes, int timeout)
705 if (CC->redirect_ssl) {
706 return (client_read_ssl(buf, bytes, timeout));
710 fd = CC->client_socket;
717 retval = select( (fd)+1,
718 &rfds, NULL, NULL, &tv);
723 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select().\n");
729 if (FD_ISSET(fd, &rfds) == 0) {
733 rlen = read(fd, &buf[len], bytes-len);
735 /* The socket has been disconnected! */
745 * Read data from the client socket with default timeout.
746 * (This is implemented in terms of client_read_to() and could be
747 * justifiably moved out of sysdep.c)
749 INLINE int client_read(char *buf, int bytes)
751 return(client_read_to(buf, bytes, config.c_sleeping));
756 * client_getln() ... Get a LF-terminated line of text from the client.
757 * (This is implemented in terms of client_read() and could be
758 * justifiably moved out of sysdep.c)
760 int client_getln(char *buf, int bufsize)
764 /* Read one character at a time.
767 retval = client_read(&buf[i], 1);
768 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
772 /* If we got a long line, discard characters until the newline.
774 if (i == (bufsize-1))
775 while (buf[i] != '\n' && retval == 1)
776 retval = client_read(&buf[i], 1);
778 /* Strip the trailing LF, and the trailing CR if present.
782 && ( (buf[i - 1]==13)
783 || ( buf[i - 1]==10)) ) {
787 if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
793 * Cleanup any contexts that are left lying around
795 void context_cleanup(void)
797 struct CitContext *ptr = NULL;
798 struct CitContext *rem = NULL;
801 * Clean up the contexts.
802 * There are no threads so no critical_section stuff is needed.
806 /* We need to update the ContextList because some modules may want to itterate it
807 * Question is should we NULL it before iterating here or should we just keep updating it
808 * as we remove items?
810 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
814 /* Remove the session from the active list */
818 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
827 void close_masters (void)
829 struct ServiceFunctionHook *serviceptr;
832 * close all protocol master sockets
834 for (serviceptr = ServiceHookTable; serviceptr != NULL;
835 serviceptr = serviceptr->next ) {
837 if (serviceptr->tcp_port > 0)
839 CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
840 serviceptr->tcp_port);
841 serviceptr->tcp_port = 0;
844 if (serviceptr->sockpath != NULL)
845 CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
846 serviceptr->sockpath);
848 close(serviceptr->msock);
849 /* If it's a Unix domain socket, remove the file. */
850 if (serviceptr->sockpath != NULL) {
851 unlink(serviceptr->sockpath);
852 serviceptr->sockpath = NULL;
859 * The system-dependent part of master_cleanup() - close the master socket.
861 void sysdep_master_cleanup(void) {
870 CtdlDestroyProtoHooks();
871 CtdlDestroyDeleteHooks();
872 CtdlDestroyXmsgHooks();
873 CtdlDestroyNetprocHooks();
874 CtdlDestroyUserHooks();
875 CtdlDestroyMessageHook();
876 CtdlDestroyCleanupHooks();
877 CtdlDestroyFixedOutputHooks();
878 CtdlDestroySessionHooks();
879 CtdlDestroyServiceHook();
880 CtdlDestroyRoomHooks();
881 #ifdef HAVE_BACKTRACE
889 * Terminate another session.
890 * (This could justifiably be moved out of sysdep.c because it
891 * no longer does anything that is system-dependent.)
893 void kill_session(int session_to_kill) {
894 struct CitContext *ptr;
896 begin_critical_section(S_SESSION_TABLE);
897 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
898 if (ptr->cs_pid == session_to_kill) {
902 end_critical_section(S_SESSION_TABLE);
906 void graceful_shutdown(int signum) {
907 kill(current_child, signum);
908 unlink(file_pid_file);
913 int nFireUpsNonRestart = 0;
917 * Start running as a daemon.
919 void start_daemon(int unused) {
927 /* Close stdin/stdout/stderr and replace them with /dev/null.
928 * We don't just call close() because we don't want these fd's
929 * to be reused for other files.
938 signal(SIGHUP, SIG_IGN);
939 signal(SIGINT, SIG_IGN);
940 signal(SIGQUIT, SIG_IGN);
944 freopen("/dev/null", "r", stdin);
945 freopen("/dev/null", "w", stdout);
946 freopen("/dev/null", "w", stderr);
949 current_child = fork();
951 signal(SIGTERM, graceful_shutdown);
953 if (current_child < 0) {
958 else if (current_child == 0) {
959 return; /* continue starting citadel. */
963 fp = fopen(file_pid_file, "w");
965 fprintf(fp, ""F_PID_T"\n", getpid());
968 waitpid(current_child, &status, 0);
971 nFireUpsNonRestart = nFireUps;
973 /* Exit code 0 means the watcher should exit */
974 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
978 /* Exit code 101-109 means the watcher should exit */
979 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
983 /* Any other exit code, or no exit code, means we should restart. */
987 ForkedPid = current_child;
990 } while (do_restart);
992 unlink(file_pid_file);
993 exit(WEXITSTATUS(status));
998 void checkcrash(void)
1000 if (nFireUpsNonRestart != nFireUps)
1004 CrashMail = NewStrBuf();
1005 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
1006 StrBufPrintf(CrashMail,
1008 " The Citadel server process (citserver) terminated unexpectedly."
1010 " This could be the result of a bug in the server program, or some external "
1012 " You can obtain more information about this by enabling core dumps.\n \n"
1013 " For more information, please see:\n \n"
1014 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1016 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1018 ctdl_run_dir, ForkedPid);
1019 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1020 FreeStrBuf(&CrashMail);
1026 * Generic routine to convert a login name to a full name (gecos)
1027 * Returns nonzero if a conversion took place
1029 int convert_login(char NameToConvert[]) {
1033 pw = getpwnam(NameToConvert);
1038 strcpy(NameToConvert, pw->pw_gecos);
1039 for (a=0; a<strlen(NameToConvert); ++a) {
1040 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1047 * Purge all sessions which have the 'kill_me' flag set.
1048 * This function has code to prevent it from running more than once every
1049 * few seconds, because running it after every single unbind would waste a lot
1050 * of CPU time and keep the context list locked too much. To force it to run
1051 * anyway, set "force" to nonzero.
1053 void dead_session_purge(int force) {
1054 struct CitContext *ptr, *ptr2; /* general-purpose utility pointer */
1055 struct CitContext *rem = NULL; /* list of sessions to be destroyed */
1058 if ( (time(NULL) - last_purge) < 5 ) {
1059 return; /* Too soon, go away */
1064 if (try_critical_section(S_SESSION_TABLE))
1072 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1073 /* Remove the session from the active list */
1075 ptr2->prev->next = ptr2->next;
1078 ContextList = ptr2->next;
1081 ptr2->next->prev = ptr2->prev;
1085 /* And put it on our to-be-destroyed list */
1090 end_critical_section(S_SESSION_TABLE);
1092 /* Now that we no longer have the session list locked, we can take
1093 * our time and destroy any sessions on the to-be-killed list, which
1094 * is allocated privately on this thread's stack.
1096 while (rem != NULL) {
1097 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1110 * masterCC is the context we use when not attached to a session. This
1111 * function initializes it.
1113 void InitializeMasterCC(void) {
1114 memset(&masterCC, 0, sizeof(struct CitContext));
1115 masterCC.internal_pgm = 1;
1116 masterCC.cs_pid = 0;
1123 * Bind a thread to a context. (It's inline merely to speed things up.)
1125 INLINE void become_session(struct CitContext *which_con) {
1127 ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1129 citthread_setspecific(MyConKey, (void *)which_con );
1135 * This loop just keeps going and going and going...
1139 * This current implimentation of worker_thread creates a bottle neck in several situations
1140 * The first thing to remember is that a single thread can handle more than one connection at a time.
1141 * More threads mean less memory for the system to run in.
1142 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1143 * something to happen anywhere.
1144 * This current implimentation requires worker threads to wait in other locations, after it has
1145 * been committed to a single connection which is very wasteful.
1146 * As an extreme case consider this:
1147 * A slow client connects and this slow client sends only one character each second.
1148 * With this current implimentation a single worker thread is dispatched to handle that connection
1149 * until such times as the client timeout expires, an error occurs on the socket or the client
1150 * completes its transmission.
1151 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1152 * second interval between chars.
1154 * It is my intention to re-write this code and the associated client_getln, client_read functions
1155 * to allow any thread to read data on behalf of any connection (context).
1156 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1157 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1159 * This worker thread loop also needs to be able to handle binary data.
1162 void *worker_thread(void *arg) {
1165 struct CitContext *ptr;
1166 struct CitContext *bind_me = NULL;
1169 struct CitContext *con= NULL; /* Temporary context pointer */
1170 struct ServiceFunctionHook *serviceptr;
1171 int ssock; /* Descriptor for client socket */
1173 int force_purge = 0;
1177 while (!CtdlThreadCheckStop()) {
1179 /* make doubly sure we're not holding any stale db handles
1180 * which might cause a deadlock.
1182 cdb_check_handles();
1183 do_select: force_purge = 0;
1184 bind_me = NULL; /* Which session shall we handle? */
1186 /* Initialize the fdset. */
1190 begin_critical_section(S_SESSION_TABLE);
1191 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1192 if (ptr->state == CON_IDLE) {
1193 FD_SET(ptr->client_socket, &readfds);
1194 if (ptr->client_socket > highest)
1195 highest = ptr->client_socket;
1197 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1199 ptr->state = CON_EXECUTING;
1202 end_critical_section(S_SESSION_TABLE);
1208 /* If we got this far, it means that there are no sessions
1209 * which a previous thread marked for attention, so we go
1210 * ahead and get ready to select().
1213 /* First, add the various master sockets to the fdset. */
1214 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1215 serviceptr = serviceptr->next ) {
1216 m = serviceptr->msock;
1217 FD_SET(m, &readfds);
1223 if (!CtdlThreadCheckStop()) {
1224 tv.tv_sec = 1; /* wake up every second if no input */
1226 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1231 /* Now figure out who made this select() unblock.
1232 * First, check for an error or exit condition.
1235 if (errno == EBADF) {
1236 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1240 if (errno != EINTR) {
1241 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1242 CtdlThreadStopAll();
1244 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1245 if (CtdlThreadCheckStop()) return(NULL);
1249 else if(retval == 0) {
1250 if (CtdlThreadCheckStop()) return(NULL);
1253 /* Next, check to see if it's a new client connecting
1254 * on a master socket.
1256 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1257 serviceptr = serviceptr->next ) {
1259 if (FD_ISSET(serviceptr->msock, &readfds)) {
1260 ssock = accept(serviceptr->msock, NULL, 0);
1262 CtdlLogPrintf(CTDL_DEBUG,
1263 "New client socket %d\n",
1266 /* The master socket is non-blocking but the client
1267 * sockets need to be blocking, otherwise certain
1268 * operations barf on FreeBSD. Not a fatal error.
1270 if (fcntl(ssock, F_SETFL, 0) < 0) {
1271 CtdlLogPrintf(CTDL_EMERG,
1272 "citserver: Can't set socket to blocking: %s\n",
1276 /* New context will be created already
1277 * set up in the CON_EXECUTING state.
1279 con = CreateNewContext();
1281 /* Assign our new socket number to it. */
1282 con->client_socket = ssock;
1283 con->h_command_function =
1284 serviceptr->h_command_function;
1285 con->h_async_function =
1286 serviceptr->h_async_function;
1288 serviceptr->ServiceName;
1290 /* Determine whether it's a local socket */
1291 if (serviceptr->sockpath != NULL)
1292 con->is_local_socket = 1;
1294 /* Set the SO_REUSEADDR socket option */
1296 setsockopt(ssock, SOL_SOCKET,
1300 become_session(con);
1302 serviceptr->h_greeting_function();
1303 become_session(NULL);
1304 con->state = CON_IDLE;
1310 /* It must be a client socket. Find a context that has data
1311 * waiting on its socket *and* is in the CON_IDLE state. Any
1312 * active sockets other than our chosen one are marked as
1313 * CON_READY so the next thread that comes around can just bind
1314 * to one without having to select() again.
1316 begin_critical_section(S_SESSION_TABLE);
1317 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1318 if ( (FD_ISSET(ptr->client_socket, &readfds))
1319 && (ptr->state != CON_EXECUTING) ) {
1320 ptr->input_waiting = 1;
1322 bind_me = ptr; /* I choose you! */
1323 bind_me->state = CON_EXECUTING;
1326 ptr->state = CON_READY;
1330 end_critical_section(S_SESSION_TABLE);
1333 /* We're bound to a session */
1334 if (bind_me != NULL) {
1335 become_session(bind_me);
1337 /* If the client has sent a command, execute it. */
1338 if (CC->input_waiting) {
1339 CC->h_command_function();
1340 CC->input_waiting = 0;
1343 /* If there are asynchronous messages waiting and the
1344 * client supports it, do those now */
1345 if ((CC->is_async) && (CC->async_waiting)
1346 && (CC->h_async_function != NULL)) {
1347 CC->h_async_function();
1348 CC->async_waiting = 0;
1351 force_purge = CC->kill_me;
1352 become_session(NULL);
1353 bind_me->state = CON_IDLE;
1356 dead_session_purge(force_purge);
1359 /* If control reaches this point, the server is shutting down */
1368 * Translate text facility name to syslog.h defined value.
1370 int SyslogFacility(char *name)
1379 { LOG_KERN, "kern" },
1380 { LOG_USER, "user" },
1381 { LOG_MAIL, "mail" },
1382 { LOG_DAEMON, "daemon" },
1383 { LOG_AUTH, "auth" },
1384 { LOG_SYSLOG, "syslog" },
1386 { LOG_NEWS, "news" },
1387 { LOG_UUCP, "uucp" },
1388 { LOG_LOCAL0, "local0" },
1389 { LOG_LOCAL1, "local1" },
1390 { LOG_LOCAL2, "local2" },
1391 { LOG_LOCAL3, "local3" },
1392 { LOG_LOCAL4, "local4" },
1393 { LOG_LOCAL5, "local5" },
1394 { LOG_LOCAL6, "local6" },
1395 { LOG_LOCAL7, "local7" },
1398 for(i = 0; facTbl[i].name != NULL; i++) {
1399 if(!strcasecmp(name, facTbl[i].name))
1400 return facTbl[i].facility;
1407 /********** MEM CHEQQER ***********/
1409 #ifdef DEBUG_MEMORY_LEAKS
1416 void *tracked_malloc(size_t size, char *file, int line) {
1417 struct igheap *thisheap;
1420 block = malloc(size);
1421 if (block == NULL) return(block);
1423 thisheap = malloc(sizeof(struct igheap));
1424 if (thisheap == NULL) {
1429 thisheap->block = block;
1430 strcpy(thisheap->file, file);
1431 thisheap->line = line;
1433 begin_critical_section(S_DEBUGMEMLEAKS);
1434 thisheap->next = igheap;
1436 end_critical_section(S_DEBUGMEMLEAKS);
1442 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1443 struct igheap *thisheap;
1446 block = realloc(ptr, size);
1447 if (block == NULL) return(block);
1449 thisheap = malloc(sizeof(struct igheap));
1450 if (thisheap == NULL) {
1455 thisheap->block = block;
1456 strcpy(thisheap->file, file);
1457 thisheap->line = line;
1459 begin_critical_section(S_DEBUGMEMLEAKS);
1460 thisheap->next = igheap;
1462 end_critical_section(S_DEBUGMEMLEAKS);
1469 void tracked_free(void *ptr) {
1470 struct igheap *thisheap;
1471 struct igheap *trash;
1475 if (igheap == NULL) return;
1476 begin_critical_section(S_DEBUGMEMLEAKS);
1477 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1478 if (thisheap->next != NULL) {
1479 if (thisheap->next->block == ptr) {
1480 trash = thisheap->next;
1481 thisheap->next = thisheap->next->next;
1486 if (igheap->block == ptr) {
1488 igheap = igheap->next;
1491 end_critical_section(S_DEBUGMEMLEAKS);
1494 char *tracked_strdup(const char *s, char *file, int line) {
1497 if (s == NULL) return(NULL);
1498 ptr = tracked_malloc(strlen(s) + 1, file, line);
1499 if (ptr == NULL) return(NULL);
1500 strncpy(ptr, s, strlen(s));
1504 void dump_heap(void) {
1505 struct igheap *thisheap;
1507 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1508 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1509 thisheap->file, thisheap->line);
1513 #endif /* DEBUG_MEMORY_LEAKS */