2 * Citadel "system dependent" stuff.
4 * Here's where we (hopefully) have most parts of the Citadel server that
5 * would need to be altered to run the server in a non-POSIX environment.
7 * If we ever port to a different platform and either have multiple
8 * variants of this file or simply load it up with #ifdefs.
10 * Copyright (c) 1987-2011 by the citadel.org team
12 * This program is open source software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <sys/syslog.h>
41 #if TIME_WITH_SYS_TIME
42 # include <sys/time.h>
46 # include <sys/time.h>
53 #include <sys/resource.h>
54 #include <netinet/in.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
64 #define SHOW_ME_VAPPEND_PRINTF
65 #include <libcitadel.h>
68 #include "sysdep_decls.h"
69 #include "citserver.h"
73 #include "housekeeping.h"
74 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
78 #ifdef HAVE_SYS_SELECT_H
79 #include <sys/select.h>
86 #include "ctdl_module.h"
93 * Signal handler to shut down the server.
96 volatile int exit_signal = 0;
97 volatile int shutdown_and_halt = 0;
98 volatile int restart_server = 0;
99 volatile int running_as_daemon = 0;
101 static RETSIGTYPE signal_cleanup(int signum) {
102 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
103 exit_signal = signum;
104 server_shutting_down = 1;
107 static RETSIGTYPE signal_exit(int signum) {
114 * Some initialization stuff...
116 void init_sysdep(void) {
119 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
123 getrlimit(RLIMIT_NOFILE, &rl);
124 rl.rlim_cur = FD_SETSIZE;
125 rl.rlim_max = FD_SETSIZE;
126 setrlimit(RLIMIT_NOFILE, &rl);
130 /* If we've got OpenSSL, we're going to use it. */
136 * Set up a place to put thread-specific data.
137 * We only need a single pointer per thread - it points to the
138 * CitContext structure (in the ContextList linked list) of the
139 * session to which the calling thread is currently bound.
141 if (pthread_key_create(&MyConKey, NULL) != 0) {
142 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
146 * Interript, hangup, and terminate signals should cause the server
147 * to gracefully clean up and shut down.
150 sigaddset(&set, SIGINT);
151 sigaddset(&set, SIGHUP);
152 sigaddset(&set, SIGTERM);
153 sigprocmask(SIG_UNBLOCK, &set, NULL);
155 signal(SIGINT, signal_cleanup);
156 signal(SIGHUP, signal_cleanup);
157 signal(SIGTERM, signal_cleanup);
158 signal(SIGUSR2, signal_exit);
161 * Do not shut down the server on broken pipe signals, otherwise the
162 * whole Citadel service would come down whenever a single client
165 signal(SIGPIPE, SIG_IGN);
170 * This is a generic function to set up a master socket for listening on
171 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
173 * ip_addr IP address to bind
174 * port_number port number to bind
175 * queue_len number of incoming connections to allow in the queue
177 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
180 struct sockaddr_in6 sin6;
181 struct sockaddr_in sin4;
185 memset(&sin6, 0, sizeof(sin6));
186 memset(&sin4, 0, sizeof(sin4));
187 sin6.sin6_family = AF_INET6;
188 sin4.sin_family = AF_INET;
190 if ( (ip_addr == NULL) /* any IPv6 */
191 || (IsEmptyStr(ip_addr))
192 || (!strcmp(ip_addr, "*"))
195 sin6.sin6_addr = in6addr_any;
197 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
200 sin4.sin_addr.s_addr = INADDR_ANY;
202 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
205 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
206 snprintf(errormessage, SIZ,
207 "Error binding to [%s] : %s", ip_addr, strerror(errno)
209 syslog(LOG_ALERT, "%s", errormessage);
213 else /* specific IPv6 */
216 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
217 snprintf(errormessage, SIZ,
218 "Error binding to [%s] : %s", ip_addr, strerror(errno)
220 syslog(LOG_ALERT, "%s", errormessage);
225 if (port_number == 0) {
226 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
227 syslog(LOG_ALERT, "%s", errormessage);
230 sin6.sin6_port = htons((u_short) port_number);
231 sin4.sin_port = htons((u_short) port_number);
233 p = getprotobyname("tcp");
235 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
237 snprintf(errormessage, SIZ,
238 "Can't create a listening socket: %s", strerror(errno)
240 syslog(LOG_ALERT, "%s", errormessage);
243 /* Set some socket options that make sense. */
245 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
247 if (ip_version == 6) {
248 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
251 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
255 snprintf(errormessage, SIZ,
256 "Can't bind: %s", strerror(errno)
258 syslog(LOG_ALERT, "%s", errormessage);
262 fcntl(s, F_SETFL, O_NONBLOCK);
264 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
265 snprintf(errormessage, SIZ,
266 "Can't listen: %s", strerror(errno)
268 syslog(LOG_ALERT, "%s", errormessage);
279 * Create a Unix domain socket and listen on it
281 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
283 struct sockaddr_un addr;
286 int actual_queue_len;
287 #ifdef HAVE_STRUCT_UCRED
291 actual_queue_len = queue_len;
292 if (actual_queue_len < 5) actual_queue_len = 5;
294 i = unlink(sockpath);
295 if ((i != 0) && (errno != ENOENT)) {
296 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
297 sockpath, strerror(errno)
299 syslog(LOG_EMERG, "%s", errormessage);
303 memset(&addr, 0, sizeof(addr));
304 addr.sun_family = AF_UNIX;
305 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
307 s = socket(AF_UNIX, SOCK_STREAM, 0);
309 snprintf(errormessage, SIZ,
310 "citserver: Can't create a socket: %s",
312 syslog(LOG_EMERG, "%s", errormessage);
316 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
317 snprintf(errormessage, SIZ,
318 "citserver: Can't bind: %s",
320 syslog(LOG_EMERG, "%s", errormessage);
324 /* set to nonblock - we need this for some obscure situations */
325 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
326 snprintf(errormessage, SIZ,
327 "citserver: Can't set socket to non-blocking: %s",
329 syslog(LOG_EMERG, "%s", errormessage);
334 if (listen(s, actual_queue_len) < 0) {
335 snprintf(errormessage, SIZ,
336 "citserver: Can't listen: %s",
338 syslog(LOG_EMERG, "%s", errormessage);
342 #ifdef HAVE_STRUCT_UCRED
343 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
346 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
353 * The following functions implement output buffering on operating systems which
354 * support it (such as Linux and various BSD flavors).
358 # define HAVE_TCP_BUFFERING
361 # define HAVE_TCP_BUFFERING
362 # define TCP_CORK TCP_NOPUSH
364 #endif /* TCP_CORK */
365 #endif /* HAVE_DARWIN */
367 static unsigned on = 1, off = 0;
369 void buffer_output(void) {
370 #ifdef HAVE_TCP_BUFFERING
372 if (!CC->redirect_ssl)
374 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
378 void unbuffer_output(void) {
379 #ifdef HAVE_TCP_BUFFERING
381 if (!CC->redirect_ssl)
383 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
387 void flush_output(void) {
388 #ifdef HAVE_TCP_BUFFERING
389 struct CitContext *CCC = CC;
390 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
391 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
396 static void flush_client_inbuf(void)
400 FlushStrBuf(CCC->ReadBuf);
408 * client_close() ... close the client socket
410 void client_close(void) {
411 CitContext *CCC = CC;
414 if (CCC->client_socket < 0) return;
415 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
416 close(CCC->client_socket);
417 CCC->client_socket = -1 ;
424 * client_write() ... Send binary data to the client.
426 int client_write(const char *buf, int nbytes)
428 int bytes_written = 0;
430 #ifndef HAVE_TCP_BUFFERING
431 int old_buffer_len = 0;
437 if (nbytes < 1) return(0);
447 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
449 fd = fopen(fn, "a+");
450 fprintf(fd, "Sending: BufSize: %d BufContent: [",
452 rv = fwrite(buf, nbytes, 1, fd);
459 // flush_client_inbuf();
460 if (Ctx->redirect_buffer != NULL) {
461 StrBufAppendBufPlain(Ctx->redirect_buffer,
467 if (Ctx->redirect_ssl) {
468 client_write_ssl(buf, nbytes);
472 if (Ctx->client_socket == -1) return -1;
474 fdflags = fcntl(Ctx->client_socket, F_GETFL);
476 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
477 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
479 FD_SET(Ctx->client_socket, &wset);
480 if (select(1, NULL, &wset, NULL, NULL) == -1) {
483 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
486 if (server_shutting_down) {
487 CC->kill_me = KILLME_SELECT_INTERRUPTED;
490 /* can't trust fd's and stuff so we need to re-create them */
495 "client_write(%d bytes) select failed: %s (%d)",
496 nbytes - bytes_written,
497 strerror(errno), errno
501 Ctx->kill_me = KILLME_SELECT_FAILED;
507 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
510 "client_write(%d bytes) failed: %s (%d)",
511 nbytes - bytes_written,
512 strerror(errno), errno
516 Ctx->kill_me = KILLME_WRITE_FAILED;
519 bytes_written = bytes_written + retval;
524 void cputbuf(const StrBuf *Buf) {
525 client_write(ChrPtr(Buf), StrLength(Buf));
530 * cprintf() Send formatted printable data to the client.
531 * Implemented in terms of client_write() so it's technically not sysdep...
533 void cprintf(const char *format, ...) {
537 va_start(arg_ptr, format);
538 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
539 buf[sizeof buf - 2] = '\n';
540 client_write(buf, strlen(buf));
546 * Read data from the client socket.
548 * sock socket fd to read from
549 * buf buffer to read into
550 * bytes number of bytes to read
551 * timeout Number of seconds to wait before timing out
553 * Possible return values:
554 * 1 Requested number of bytes has been read.
555 * 0 Request timed out.
556 * -1 Connection is broken, or other error.
558 int client_read_blob(StrBuf *Target, int bytes, int timeout)
565 if (CCC->redirect_ssl) {
571 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
573 fd = fopen(fn, "a+");
574 fprintf(fd, "Reading BLOB: BufSize: %d ",
576 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
582 retval = client_read_sslblob(Target, bytes, timeout);
584 syslog(LOG_CRIT, "client_read_blob() failed");
587 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
589 fd = fopen(fn, "a+");
590 fprintf(fd, "Read: %d BufContent: [",
592 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
607 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
609 fd = fopen(fn, "a+");
610 fprintf(fd, "Reading BLOB: BufSize: %d ",
612 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
618 retval = StrBufReadBLOBBuffered(Target,
627 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
632 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
634 fd = fopen(fn, "a+");
635 fprintf(fd, "Read: %d BufContent: [",
637 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
647 * to make client_read_random_blob() more efficient, increase buffer size.
648 * just use in greeting function, else your buffer may be flushed
650 void client_set_inbound_buf(long N)
652 FlushStrBuf(CC->ReadBuf);
653 ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
656 int client_read_random_blob(StrBuf *Target, int timeout)
661 rc = client_read_blob(Target, 1, timeout);
667 len = StrLength(CCC->ReadBuf);
668 pch = ChrPtr(CCC->ReadBuf);
672 if (CCC->Pos != NULL) {
673 len -= CCC->Pos - pch;
676 StrBufAppendBufPlain(Target, pch, len, 0);
677 FlushStrBuf(CCC->ReadBuf);
685 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
687 fd = fopen(fn, "a+");
688 fprintf(fd, "Read: BufSize: %d BufContent: [",
690 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
698 return StrLength(Target);
706 int client_read_to(char *buf, int bytes, int timeout)
711 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
720 ChrPtr(CCC->MigrateBuf),
721 StrLength(CCC->MigrateBuf) + 1);
722 FlushStrBuf(CCC->MigrateBuf);
728 int HaveMoreLinesWaiting(CitContext *CCC)
730 if ((CCC->kill_me != 0) || (
731 (CCC->Pos == NULL) &&
732 (StrLength(CCC->ReadBuf) == 0) &&
733 (CCC->client_socket != -1)) )
741 * Read data from the client socket with default timeout.
742 * (This is implemented in terms of client_read_to() and could be
743 * justifiably moved out of sysdep.c)
745 INLINE int client_read(char *buf, int bytes)
747 return(client_read_to(buf, bytes, config.c_sleeping));
750 int CtdlClientGetLine(StrBuf *Target)
758 if (CCC->redirect_ssl) {
768 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
770 fd = fopen(fn, "a+");
771 pch = ChrPtr(CCC->ReadBuf);
772 len = StrLength(CCC->ReadBuf);
773 if (CCC->Pos != NULL)
774 rlen = CC->Pos - pch;
778 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
781 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
784 rc = client_readline_sslbuffer(Target,
789 pch = ChrPtr(CCC->ReadBuf);
790 nlen = StrLength(CCC->ReadBuf);
791 if (CCC->Pos != NULL)
792 nrlen = CC->Pos - pch;
796 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
797 len, nlen, rlen, nrlen, pch);
799 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
800 len, nlen, rlen, nrlen);
802 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
803 StrLength(Target), ChrPtr(Target));
807 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
818 int len, rlen, nlen, nrlen;
821 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
823 fd = fopen(fn, "a+");
824 pch = ChrPtr(CCC->ReadBuf);
825 len = StrLength(CCC->ReadBuf);
826 if (CCC->Pos != NULL)
827 rlen = CC->Pos - pch;
831 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
834 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
837 rc = StrBufTCP_read_buffered_line_fast(Target,
846 pch = ChrPtr(CCC->ReadBuf);
847 nlen = StrLength(CCC->ReadBuf);
848 if (CCC->Pos != NULL)
849 nrlen = CC->Pos - pch;
853 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
854 len, nlen, rlen, nrlen, pch);
856 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
857 len, nlen, rlen, nrlen);
859 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
860 StrLength(Target), ChrPtr(Target));
863 if ((rc < 0) && (Error != NULL)) {
864 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
873 * client_getln() ... Get a LF-terminated line of text from the client.
874 * (This is implemented in terms of client_read() and could be
875 * justifiably moved out of sysdep.c)
877 int client_getln(char *buf, int bufsize)
883 retval = CtdlClientGetLine(CCC->MigrateBuf);
888 i = StrLength(CCC->MigrateBuf);
889 pCh = ChrPtr(CCC->MigrateBuf);
890 /* Strip the trailing LF, and the trailing CR if present.
895 && ( (pCh[i - 1]==13)
896 || ( pCh[i - 1]==10)) ) {
902 FlushStrBuf(CCC->MigrateBuf);
904 safestrncpy(&buf[i], "000", bufsize - i);
911 * Cleanup any contexts that are left lying around
915 void close_masters (void)
917 struct ServiceFunctionHook *serviceptr;
920 * close all protocol master sockets
922 for (serviceptr = ServiceHookTable; serviceptr != NULL;
923 serviceptr = serviceptr->next ) {
925 if (serviceptr->tcp_port > 0)
927 syslog(LOG_INFO, "Closing listener on port %d\n",
928 serviceptr->tcp_port);
929 serviceptr->tcp_port = 0;
932 if (serviceptr->sockpath != NULL)
933 syslog(LOG_INFO, "Closing listener on '%s'\n",
934 serviceptr->sockpath);
936 close(serviceptr->msock);
937 /* If it's a Unix domain socket, remove the file. */
938 if (serviceptr->sockpath != NULL) {
939 unlink(serviceptr->sockpath);
940 serviceptr->sockpath = NULL;
947 * The system-dependent part of master_cleanup() - close the master socket.
949 void sysdep_master_cleanup(void) {
958 CtdlDestroyProtoHooks();
959 CtdlDestroyDeleteHooks();
960 CtdlDestroyXmsgHooks();
961 CtdlDestroyNetprocHooks();
962 CtdlDestroyUserHooks();
963 CtdlDestroyMessageHook();
964 CtdlDestroyCleanupHooks();
965 CtdlDestroyFixedOutputHooks();
966 CtdlDestroySessionHooks();
967 CtdlDestroyServiceHook();
968 CtdlDestroyRoomHooks();
969 CtdlDestroySearchHooks();
970 #ifdef HAVE_BACKTRACE
978 void graceful_shutdown(int signum) {
979 kill(current_child, signum);
980 unlink(file_pid_file);
985 int nFireUpsNonRestart = 0;
989 * Start running as a daemon.
991 void start_daemon(int unused) {
999 /* Close stdin/stdout/stderr and replace them with /dev/null.
1000 * We don't just call close() because we don't want these fd's
1001 * to be reused for other files.
1003 if (chdir(ctdl_run_dir) != 0)
1005 "unable to change into directory [%s]: %s",
1006 ctdl_run_dir, strerror(errno));
1013 signal(SIGHUP, SIG_IGN);
1014 signal(SIGINT, SIG_IGN);
1015 signal(SIGQUIT, SIG_IGN);
1019 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1020 (freopen("/dev/null", "w", stdout) != stdout) ||
1021 (freopen("/dev/null", "w", stderr) != stderr))
1023 "unable to reopen stdin/out/err %s",
1028 current_child = fork();
1030 signal(SIGTERM, graceful_shutdown);
1032 if (current_child < 0) {
1037 else if (current_child == 0) {
1038 return; /* continue starting citadel. */
1042 fp = fopen(file_pid_file, "w");
1044 fprintf(fp, ""F_PID_T"\n", getpid());
1047 waitpid(current_child, &status, 0);
1050 nFireUpsNonRestart = nFireUps;
1052 /* Exit code 0 means the watcher should exit */
1053 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1057 /* Exit code 101-109 means the watcher should exit */
1058 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1062 /* Any other exit code, or no exit code, means we should restart. */
1066 ForkedPid = current_child;
1069 } while (do_restart);
1071 unlink(file_pid_file);
1072 exit(WEXITSTATUS(status));
1077 void checkcrash(void)
1079 if (nFireUpsNonRestart != nFireUps)
1083 CrashMail = NewStrBuf();
1084 syslog(LOG_ALERT, "Posting crash message\n");
1085 StrBufPrintf(CrashMail,
1087 " The Citadel server process (citserver) terminated unexpectedly."
1089 " This could be the result of a bug in the server program, or some external "
1091 " You can obtain more information about this by enabling core dumps.\n \n"
1092 " For more information, please see:\n \n"
1093 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1096 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1098 ctdl_run_dir, ForkedPid);
1099 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1100 FreeStrBuf(&CrashMail);
1106 * Generic routine to convert a login name to a full name (gecos)
1107 * Returns nonzero if a conversion took place
1109 int convert_login(char NameToConvert[]) {
1113 pw = getpwnam(NameToConvert);
1118 strcpy(NameToConvert, pw->pw_gecos);
1119 for (a=0; a<strlen(NameToConvert); ++a) {
1120 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1129 * This loop just keeps going and going and going...
1131 void *worker_thread(void *blah) {
1134 CitContext *bind_me = NULL;
1138 int force_purge = 0;
1139 struct ServiceFunctionHook *serviceptr;
1140 int ssock; /* Descriptor for client socket */
1141 CitContext *con = NULL; /* Temporary context pointer */
1146 while (!server_shutting_down) {
1148 /* make doubly sure we're not holding any stale db handles
1149 * which might cause a deadlock.
1151 cdb_check_handles();
1152 do_select: force_purge = 0;
1153 bind_me = NULL; /* Which session shall we handle? */
1155 /* Initialize the fdset. */
1159 /* First, add the various master sockets to the fdset. */
1160 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1161 FD_SET(serviceptr->msock, &readfds);
1162 if (serviceptr->msock > highest) {
1163 highest = serviceptr->msock;
1167 /* Next, add all of the client sockets. */
1168 begin_critical_section(S_SESSION_TABLE);
1169 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1170 /* Don't select on dead sessions, only truly idle ones */
1171 if ( (ptr->state == CON_IDLE)
1172 && (ptr->kill_me == 0)
1173 && (ptr->client_socket != -1)
1175 FD_SET(ptr->client_socket, &readfds);
1176 if (ptr->client_socket > highest)
1177 highest = ptr->client_socket;
1179 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1181 ptr->state = CON_EXECUTING;
1184 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1186 ptr->state = CON_STARTING;
1190 end_critical_section(S_SESSION_TABLE);
1196 /* If we got this far, it means that there are no sessions
1197 * which a previous thread marked for attention, so we go
1198 * ahead and get ready to select().
1201 if (!server_shutting_down) {
1202 tv.tv_sec = 1; /* wake up every second if no input */
1204 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1211 /* Now figure out who made this select() unblock.
1212 * First, check for an error or exit condition.
1215 if (errno == EBADF) {
1216 syslog(LOG_NOTICE, "select() failed: (%s)\n", strerror(errno));
1219 if (errno != EINTR) {
1220 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1221 server_shutting_down = 1;
1224 syslog(LOG_DEBUG, "Interrupted select()\n");
1225 if (server_shutting_down) {
1232 else if (retval == 0) {
1233 if (server_shutting_down) {
1239 /* Next, check to see if it's a new client connecting * on a master socket. */
1241 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1243 if (FD_ISSET(serviceptr->msock, &readfds)) {
1244 ssock = accept(serviceptr->msock, NULL, 0);
1246 syslog(LOG_DEBUG, "New client socket %d", ssock);
1248 /* The master socket is non-blocking but the client
1249 * sockets need to be blocking, otherwise certain
1250 * operations barf on FreeBSD. Not a fatal error.
1252 if (fcntl(ssock, F_SETFL, 0) < 0) {
1254 "citserver: Can't set socket to blocking: %s\n",
1258 /* New context will be created already
1259 * set up in the CON_EXECUTING state.
1261 con = CreateNewContext();
1263 /* Assign our new socket number to it. */
1264 con->client_socket = ssock;
1265 con->h_command_function = serviceptr->h_command_function;
1266 con->h_async_function = serviceptr->h_async_function;
1267 con->h_greeting_function = serviceptr->h_greeting_function;
1268 con->ServiceName = serviceptr->ServiceName;
1270 /* Determine whether it's a local socket */
1271 if (serviceptr->sockpath != NULL) {
1272 con->is_local_socket = 1;
1275 /* Set the SO_REUSEADDR socket option */
1277 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1278 con->state = CON_GREETING;
1286 /* It must be a client socket. Find a context that has data
1287 * waiting on its socket *and* is in the CON_IDLE state. Any
1288 * active sockets other than our chosen one are marked as
1289 * CON_READY so the next thread that comes around can just bind
1290 * to one without having to select() again.
1292 begin_critical_section(S_SESSION_TABLE);
1293 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1294 int checkfd = ptr->client_socket;
1295 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1296 if (FD_ISSET(checkfd, &readfds)) {
1297 ptr->input_waiting = 1;
1299 bind_me = ptr; /* I choose you! */
1300 bind_me->state = CON_EXECUTING;
1303 ptr->state = CON_READY;
1305 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1307 bind_me = ptr; /* I choose you! */
1308 bind_me->state = CON_EXECUTING;
1311 ptr->state = CON_READY;
1316 end_critical_section(S_SESSION_TABLE);
1319 /* We're bound to a session */
1321 if (bind_me != NULL) {
1322 become_session(bind_me);
1324 if (bind_me->state == CON_STARTING) {
1325 bind_me->state = CON_EXECUTING;
1326 begin_session(bind_me);
1327 bind_me->h_greeting_function();
1329 /* If the client has sent a command, execute it. */
1330 if (CC->input_waiting) {
1331 CC->h_command_function();
1333 while (HaveMoreLinesWaiting(CC))
1334 CC->h_command_function();
1336 CC->input_waiting = 0;
1339 /* If there are asynchronous messages waiting and the
1340 * client supports it, do those now */
1341 if ((CC->is_async) && (CC->async_waiting)
1342 && (CC->h_async_function != NULL)) {
1343 CC->h_async_function();
1344 CC->async_waiting = 0;
1347 force_purge = CC->kill_me;
1348 become_session(NULL);
1349 bind_me->state = CON_IDLE;
1352 dead_session_purge(force_purge);
1357 /* If control reaches this point, the server is shutting down */
1373 * Translate text facility name to syslog.h defined value.
1375 int SyslogFacility(char *name)
1384 { LOG_KERN, "kern" },
1385 { LOG_USER, "user" },
1386 { LOG_MAIL, "mail" },
1387 { LOG_DAEMON, "daemon" },
1388 { LOG_AUTH, "auth" },
1389 { LOG_SYSLOG, "syslog" },
1391 { LOG_NEWS, "news" },
1392 { LOG_UUCP, "uucp" },
1393 { LOG_LOCAL0, "local0" },
1394 { LOG_LOCAL1, "local1" },
1395 { LOG_LOCAL2, "local2" },
1396 { LOG_LOCAL3, "local3" },
1397 { LOG_LOCAL4, "local4" },
1398 { LOG_LOCAL5, "local5" },
1399 { LOG_LOCAL6, "local6" },
1400 { LOG_LOCAL7, "local7" },
1403 for(i = 0; facTbl[i].name != NULL; i++) {
1404 if(!strcasecmp(name, facTbl[i].name))
1405 return facTbl[i].facility;