2 * Citadel "system dependent" stuff.
4 * Here's where we (hopefully) have most parts of the Citadel server that
5 * might need tweaking when run on different operating system variants.
7 * Copyright (c) 1987-2017 by the citadel.org team
9 * This program is open source software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License, version 3.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
26 #include <sys/syslog.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <netinet/tcp.h>
34 #include <arpa/inet.h>
35 #define SHOW_ME_VAPPEND_PRINTF
36 #include <libcitadel.h>
37 #include "citserver.h"
39 #include "ctdl_module.h"
40 #include "sysdep_decls.h"
41 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
42 #include "housekeeping.h"
45 * Signal handler to shut down the server.
48 volatile int exit_signal = 0;
49 volatile int shutdown_and_halt = 0;
50 volatile int restart_server = 0;
51 volatile int running_as_daemon = 0;
53 static RETSIGTYPE signal_cleanup(int signum) {
54 syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
56 server_shutting_down = 1;
59 static RETSIGTYPE signal_exit(int signum) {
66 * Some initialization stuff...
68 void init_sysdep(void) {
71 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
75 getrlimit(RLIMIT_NOFILE, &rl);
76 rl.rlim_cur = FD_SETSIZE;
77 rl.rlim_max = FD_SETSIZE;
78 setrlimit(RLIMIT_NOFILE, &rl);
82 /* If we've got OpenSSL, we're going to use it. */
88 * Set up a place to put thread-specific data.
89 * We only need a single pointer per thread - it points to the
90 * CitContext structure (in the ContextList linked list) of the
91 * session to which the calling thread is currently bound.
93 if (pthread_key_create(&MyConKey, NULL) != 0) {
94 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
98 * Interript, hangup, and terminate signals should cause the server
99 * to gracefully clean up and shut down.
102 sigaddset(&set, SIGINT);
103 sigaddset(&set, SIGHUP);
104 sigaddset(&set, SIGTERM);
105 sigprocmask(SIG_UNBLOCK, &set, NULL);
107 signal(SIGINT, signal_cleanup);
108 signal(SIGHUP, signal_cleanup);
109 signal(SIGTERM, signal_cleanup);
110 signal(SIGUSR2, signal_exit);
113 * Do not shut down the server on broken pipe signals, otherwise the
114 * whole Citadel service would come down whenever a single client
117 signal(SIGPIPE, SIG_IGN);
122 * This is a generic function to set up a master socket for listening on
123 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
125 * ip_addr IP address to bind
126 * port_number port number to bind
127 * queue_len number of incoming connections to allow in the queue
129 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
132 struct sockaddr_in6 sin6;
133 struct sockaddr_in sin4;
137 memset(&sin6, 0, sizeof(sin6));
138 memset(&sin4, 0, sizeof(sin4));
139 sin6.sin6_family = AF_INET6;
140 sin4.sin_family = AF_INET;
142 if ( (ip_addr == NULL) /* any IPv6 */
143 || (IsEmptyStr(ip_addr))
144 || (!strcmp(ip_addr, "*"))
147 sin6.sin6_addr = in6addr_any;
149 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
152 sin4.sin_addr.s_addr = INADDR_ANY;
154 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
157 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
158 snprintf(errormessage, SIZ,
159 "Error binding to [%s] : %s", ip_addr, strerror(errno)
161 syslog(LOG_ALERT, "%s", errormessage);
165 else /* specific IPv6 */
168 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
169 snprintf(errormessage, SIZ,
170 "Error binding to [%s] : %s", ip_addr, strerror(errno)
172 syslog(LOG_ALERT, "%s", errormessage);
177 if (port_number == 0) {
178 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
179 syslog(LOG_ALERT, "%s", errormessage);
182 sin6.sin6_port = htons((u_short) port_number);
183 sin4.sin_port = htons((u_short) port_number);
185 p = getprotobyname("tcp");
187 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
189 snprintf(errormessage, SIZ,
190 "Can't create a listening socket: %s", strerror(errno)
192 syslog(LOG_ALERT, "%s", errormessage);
195 /* Set some socket options that make sense. */
197 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
199 if (ip_version == 6) {
200 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
203 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
207 snprintf(errormessage, SIZ,
208 "Can't bind: %s", strerror(errno)
210 syslog(LOG_ALERT, "%s", errormessage);
214 fcntl(s, F_SETFL, O_NONBLOCK);
216 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
217 snprintf(errormessage, SIZ,
218 "Can't listen: %s", strerror(errno)
220 syslog(LOG_ALERT, "%s", errormessage);
231 * Create a Unix domain socket and listen on it
233 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
235 struct sockaddr_un addr;
238 int actual_queue_len;
239 #ifdef HAVE_STRUCT_UCRED
243 actual_queue_len = queue_len;
244 if (actual_queue_len < 5) actual_queue_len = 5;
246 i = unlink(sockpath);
247 if ((i != 0) && (errno != ENOENT)) {
248 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
249 sockpath, strerror(errno)
251 syslog(LOG_EMERG, "%s", errormessage);
255 memset(&addr, 0, sizeof(addr));
256 addr.sun_family = AF_UNIX;
257 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
259 s = socket(AF_UNIX, SOCK_STREAM, 0);
261 snprintf(errormessage, SIZ, "citserver: Can't create a socket: %s", strerror(errno));
262 syslog(LOG_EMERG, "%s", errormessage);
266 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
267 snprintf(errormessage, SIZ, "citserver: Can't bind: %s", strerror(errno));
268 syslog(LOG_EMERG, "%s", errormessage);
272 /* set to nonblock - we need this for some obscure situations */
273 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
274 snprintf(errormessage, SIZ, "citserver: Can't set socket to non-blocking: %s", strerror(errno));
275 syslog(LOG_EMERG, "%s", errormessage);
280 if (listen(s, actual_queue_len) < 0) {
281 snprintf(errormessage, SIZ, "citserver: Can't listen: %s", strerror(errno));
282 syslog(LOG_EMERG, "%s", errormessage);
286 #ifdef HAVE_STRUCT_UCRED
287 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
290 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
297 * The following functions implement output buffering on operating systems which
298 * support it (such as Linux and various BSD flavors).
302 # define HAVE_TCP_BUFFERING
305 # define HAVE_TCP_BUFFERING
306 # define TCP_CORK TCP_NOPUSH
308 #endif /* TCP_CORK */
309 #endif /* HAVE_DARWIN */
311 static unsigned on = 1, off = 0;
313 void buffer_output(void) {
314 #ifdef HAVE_TCP_BUFFERING
316 if (!CC->redirect_ssl)
318 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
322 void unbuffer_output(void) {
323 #ifdef HAVE_TCP_BUFFERING
325 if (!CC->redirect_ssl)
327 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
331 void flush_output(void) {
332 #ifdef HAVE_TCP_BUFFERING
333 struct CitContext *CCC = CC;
334 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
335 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
340 static void flush_client_inbuf(void)
344 FlushStrBuf(CCC->ReadBuf);
345 CCC->RecvBuf->ReadWritePointer = NULL;
352 * client_close() ... close the client socket
354 void client_close(void) {
355 CitContext *CCC = CC;
358 if (CCC->client_socket <= 0) return;
359 syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
361 close(CCC->client_socket);
362 CCC->client_socket = -1 ;
369 * client_write() ... Send binary data to the client.
371 int client_write(const char *buf, int nbytes)
373 int bytes_written = 0;
375 #ifndef HAVE_TCP_BUFFERING
376 int old_buffer_len = 0;
382 if (nbytes < 1) return(0);
392 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
394 fd = fopen(fn, "a+");
396 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
400 fprintf(fd, "Sending: BufSize: %d BufContent: [", nbytes);
401 rv = fwrite(buf, nbytes, 1, fd);
406 // flush_client_inbuf();
407 if (Ctx->redirect_buffer != NULL) {
408 StrBufAppendBufPlain(Ctx->redirect_buffer,
414 if (Ctx->redirect_ssl) {
415 client_write_ssl(buf, nbytes);
419 if (Ctx->client_socket == -1) return -1;
421 fdflags = fcntl(Ctx->client_socket, F_GETFL);
423 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
424 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
426 FD_SET(Ctx->client_socket, &wset);
427 if (select(1, NULL, &wset, NULL, NULL) == -1) {
430 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
433 if (server_shutting_down) {
434 CC->kill_me = KILLME_SELECT_INTERRUPTED;
437 /* can't trust fd's and stuff so we need to re-create them */
442 "client_write(%d bytes) select failed: %s (%d)",
443 nbytes - bytes_written,
444 strerror(errno), errno
448 Ctx->kill_me = KILLME_SELECT_FAILED;
454 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
457 "client_write(%d bytes) failed: %s (%d)",
458 nbytes - bytes_written,
459 strerror(errno), errno
463 Ctx->kill_me = KILLME_WRITE_FAILED;
466 bytes_written = bytes_written + retval;
471 void cputbuf(const StrBuf *Buf) {
472 client_write(ChrPtr(Buf), StrLength(Buf));
477 * cprintf() Send formatted printable data to the client.
478 * Implemented in terms of client_write() so it's technically not sysdep...
480 void cprintf(const char *format, ...) {
484 va_start(arg_ptr, format);
485 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
486 buf[sizeof buf - 2] = '\n';
487 client_write(buf, strlen(buf));
493 * Read data from the client socket.
495 * sock socket fd to read from
496 * buf buffer to read into
497 * bytes number of bytes to read
498 * timeout Number of seconds to wait before timing out
500 * Possible return values:
501 * 1 Requested number of bytes has been read.
502 * 0 Request timed out.
503 * -1 Connection is broken, or other error.
505 int client_read_blob(StrBuf *Target, int bytes, int timeout)
512 if (CCC->redirect_ssl) {
518 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
520 fd = fopen(fn, "a+");
522 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
526 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
527 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
533 retval = client_read_sslblob(Target, bytes, timeout);
535 syslog(LOG_CRIT, "client_read_blob() failed");
538 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
540 fd = fopen(fn, "a+");
542 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
546 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
547 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
560 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
562 fd = fopen(fn, "a+");
564 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
568 fprintf(fd, "Reading BLOB: BufSize: %d ",
570 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
574 retval = StrBufReadBLOBBuffered(Target,
576 &CCC->RecvBuf.ReadWritePointer,
584 syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
589 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
591 fd = fopen(fn, "a+");
593 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
597 fprintf(fd, "Read: %d BufContent: [",
599 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
609 * to make client_read_random_blob() more efficient, increase buffer size.
610 * just use in greeting function, else your buffer may be flushed
612 void client_set_inbound_buf(long N)
615 FlushStrBuf(CCC->RecvBuf.Buf);
616 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
619 int client_read_random_blob(StrBuf *Target, int timeout)
624 rc = client_read_blob(Target, 1, timeout);
630 len = StrLength(CCC->RecvBuf.Buf);
631 pch = ChrPtr(CCC->RecvBuf.Buf);
635 if (CCC->RecvBuf.ReadWritePointer != NULL) {
636 len -= CCC->RecvBuf.ReadWritePointer - pch;
637 pch = CCC->RecvBuf.ReadWritePointer;
639 StrBufAppendBufPlain(Target, pch, len, 0);
640 FlushStrBuf(CCC->RecvBuf.Buf);
641 CCC->RecvBuf.ReadWritePointer = NULL;
648 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
650 fd = fopen(fn, "a+");
652 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
656 fprintf(fd, "Read: BufSize: %d BufContent: [",
658 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
663 return StrLength(Target);
671 int client_read_to(char *buf, int bytes, int timeout)
676 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
685 ChrPtr(CCC->MigrateBuf),
686 StrLength(CCC->MigrateBuf) + 1);
687 FlushStrBuf(CCC->MigrateBuf);
693 int HaveMoreLinesWaiting(CitContext *CCC)
695 if ((CCC->kill_me != 0) ||
696 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
697 (StrLength(CCC->RecvBuf.Buf) == 0) &&
698 (CCC->client_socket != -1)) )
706 * Read data from the client socket with default timeout.
707 * (This is implemented in terms of client_read_to() and could be
708 * justifiably moved out of sysdep.c)
710 INLINE int client_read(char *buf, int bytes)
712 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
715 int CtdlClientGetLine(StrBuf *Target)
723 if (CCC->redirect_ssl) {
733 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
735 fd = fopen(fn, "a+");
737 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
741 pch = ChrPtr(CCC->RecvBuf.Buf);
742 len = StrLength(CCC->RecvBuf.Buf);
743 if (CCC->RecvBuf.ReadWritePointer != NULL)
744 rlen = CCC->RecvBuf.ReadWritePointer - pch;
748 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
751 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
754 rc = client_readline_sslbuffer(Target,
756 &CCC->RecvBuf.ReadWritePointer,
759 pch = ChrPtr(CCC->RecvBuf.Buf);
760 nlen = StrLength(CCC->RecvBuf.Buf);
761 if (CCC->RecvBuf.ReadWritePointer != NULL)
762 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
766 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
767 len, nlen, rlen, nrlen, pch);
769 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
770 len, nlen, rlen, nrlen);
772 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
773 StrLength(Target), ChrPtr(Target));
777 syslog(LOG_CRIT, "CtdlClientGetLine() failed");
788 int len, rlen, nlen, nrlen;
791 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
793 fd = fopen(fn, "a+");
795 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
799 pch = ChrPtr(CCC->RecvBuf.Buf);
800 len = StrLength(CCC->RecvBuf.Buf);
801 if (CCC->RecvBuf.ReadWritePointer != NULL)
802 rlen = CCC->RecvBuf.ReadWritePointer - pch;
806 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
809 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
812 rc = StrBufTCP_read_buffered_line_fast(Target,
814 &CCC->RecvBuf.ReadWritePointer,
822 pch = ChrPtr(CCC->RecvBuf.Buf);
823 nlen = StrLength(CCC->RecvBuf.Buf);
824 if (CCC->RecvBuf.ReadWritePointer != NULL)
825 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
829 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
830 len, nlen, rlen, nrlen, pch);
832 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
833 len, nlen, rlen, nrlen);
835 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
836 StrLength(Target), ChrPtr(Target));
839 if ((rc < 0) && (Error != NULL)) {
840 syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
849 * client_getln() ... Get a LF-terminated line of text from the client.
850 * (This is implemented in terms of client_read() and could be
851 * justifiably moved out of sysdep.c)
853 int client_getln(char *buf, int bufsize)
859 retval = CtdlClientGetLine(CCC->MigrateBuf);
864 i = StrLength(CCC->MigrateBuf);
865 pCh = ChrPtr(CCC->MigrateBuf);
866 /* Strip the trailing LF, and the trailing CR if present.
871 && ( (pCh[i - 1]==13)
872 || ( pCh[i - 1]==10)) ) {
878 FlushStrBuf(CCC->MigrateBuf);
880 safestrncpy(&buf[i], "000", bufsize - i);
887 * Cleanup any contexts that are left lying around
891 void close_masters (void)
893 struct ServiceFunctionHook *serviceptr;
897 * close all protocol master sockets
899 for (serviceptr = ServiceHookTable; serviceptr != NULL;
900 serviceptr = serviceptr->next ) {
902 if (serviceptr->tcp_port > 0)
904 if (serviceptr->msock == -1)
905 Text = "not closing again";
909 syslog(LOG_INFO, "%s %d listener on port %d",
914 serviceptr->tcp_port = 0;
917 if (serviceptr->sockpath != NULL)
919 if (serviceptr->msock == -1)
920 Text = "not closing again";
924 syslog(LOG_INFO, "%s %d listener on '%s'",
931 if (serviceptr->msock != -1)
933 close(serviceptr->msock);
934 serviceptr->msock = -1;
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 CtdlDestroyDebugTable();
971 #ifdef HAVE_BACKTRACE
979 void graceful_shutdown(int signum) {
980 kill(current_child, signum);
981 unlink(file_pid_file);
986 int nFireUpsNonRestart = 0;
990 * Start running as a daemon.
992 void start_daemon(int unused) {
1000 /* Close stdin/stdout/stderr and replace them with /dev/null.
1001 * We don't just call close() because we don't want these fd's
1002 * to be reused for other files.
1004 if (chdir(ctdl_run_dir) != 0)
1006 "unable to change into directory [%s]: %s",
1007 ctdl_run_dir, strerror(errno));
1014 signal(SIGHUP, SIG_IGN);
1015 signal(SIGINT, SIG_IGN);
1016 signal(SIGQUIT, SIG_IGN);
1020 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1021 (freopen("/dev/null", "w", stdout) != stdout) ||
1022 (freopen("/dev/null", "w", stderr) != stderr))
1024 "unable to reopen stdin/out/err %s",
1029 current_child = fork();
1031 signal(SIGTERM, graceful_shutdown);
1033 if (current_child < 0) {
1038 else if (current_child == 0) {
1039 return; /* continue starting citadel. */
1043 fp = fopen(file_pid_file, "w");
1045 fprintf(fp, ""F_PID_T"\n", getpid());
1048 waitpid(current_child, &status, 0);
1051 nFireUpsNonRestart = nFireUps;
1053 /* Exit code 0 means the watcher should exit */
1054 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1058 /* Exit code 101-109 means the watcher should exit */
1059 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1063 /* Any other exit code, or no exit code, means we should restart. */
1067 ForkedPid = current_child;
1070 } while (do_restart);
1072 unlink(file_pid_file);
1073 exit(WEXITSTATUS(status));
1078 void checkcrash(void)
1080 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?id=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;
1128 void HuntBadSession(void)
1134 struct ServiceFunctionHook *serviceptr;
1138 /* Next, add all of the client sockets. */
1139 begin_critical_section(S_SESSION_TABLE);
1140 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1141 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1143 /* Initialize the fdset. */
1146 tv.tv_sec = 0; /* wake up every second if no input */
1149 /* Don't select on dead sessions, only truly idle ones */
1150 if ( (ptr->state == CON_IDLE)
1151 && (ptr->kill_me == 0)
1152 && (ptr->client_socket > 0)
1154 FD_SET(ptr->client_socket, &readfds);
1155 if (ptr->client_socket > highest)
1156 highest = ptr->client_socket;
1158 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1163 "Killing Session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]\n",
1166 ptr->is_local_socket,
1168 ptr->cs_host,ptr->cs_addr);
1171 ptr->client_socket = -1;
1177 end_critical_section(S_SESSION_TABLE);
1180 /* First, add the various master sockets to the fdset. */
1181 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1183 /* Initialize the fdset. */
1185 tv.tv_sec = 0; /* wake up every second if no input */
1188 FD_SET(serviceptr->msock, &readfds);
1189 if (serviceptr->msock > highest) {
1190 highest = serviceptr->msock;
1192 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1195 /* Gotcha! server socket dead? commit suicide! */
1197 "Found bad FD: %d and its a server socket! Shutting Down!\n",
1200 server_shutting_down = 1;
1208 const char *WorkerLogStr = "W";
1210 * This loop just keeps going and going and going...
1212 void *worker_thread(void *blah) {
1215 CitContext *bind_me = NULL;
1219 int force_purge = 0;
1220 struct ServiceFunctionHook *serviceptr;
1221 int ssock; /* Descriptor for client socket */
1222 CitContext *con = NULL; /* Temporary context pointer */
1225 pthread_mutex_lock(&ThreadCountMutex);
1227 pthread_mutex_unlock(&ThreadCountMutex);
1229 while (!server_shutting_down) {
1231 /* make doubly sure we're not holding any stale db handles
1232 * which might cause a deadlock.
1234 cdb_check_handles();
1235 do_select: force_purge = 0;
1236 bind_me = NULL; /* Which session shall we handle? */
1238 /* Initialize the fdset. */
1242 /* First, add the various master sockets to the fdset. */
1243 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1244 FD_SET(serviceptr->msock, &readfds);
1245 if (serviceptr->msock > highest) {
1246 highest = serviceptr->msock;
1250 /* Next, add all of the client sockets. */
1251 begin_critical_section(S_SESSION_TABLE);
1252 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1253 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1256 /* Don't select on dead sessions, only truly idle ones */
1257 if ( (ptr->state == CON_IDLE)
1258 && (ptr->kill_me == 0)
1259 && (ptr->client_socket > 0)
1261 FD_SET(ptr->client_socket, &readfds);
1262 if (ptr->client_socket > highest)
1263 highest = ptr->client_socket;
1265 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1267 ptr->state = CON_EXECUTING;
1270 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1272 ptr->state = CON_STARTING;
1276 end_critical_section(S_SESSION_TABLE);
1282 /* If we got this far, it means that there are no sessions
1283 * which a previous thread marked for attention, so we go
1284 * ahead and get ready to select().
1287 if (!server_shutting_down) {
1288 tv.tv_sec = 1; /* wake up every second if no input */
1290 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1297 /* Now figure out who made this select() unblock.
1298 * First, check for an error or exit condition.
1301 if (errno == EBADF) {
1302 syslog(LOG_EMERG, "select() failed: (%s)\n", strerror(errno));
1306 if (errno != EINTR) {
1307 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1308 server_shutting_down = 1;
1311 if (server_shutting_down) {
1318 else if (retval == 0) {
1319 if (server_shutting_down) {
1325 /* Next, check to see if it's a new client connecting * on a master socket. */
1327 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1329 if (FD_ISSET(serviceptr->msock, &readfds)) {
1330 ssock = accept(serviceptr->msock, NULL, 0);
1332 syslog(LOG_DEBUG, "New client socket %d", ssock);
1334 /* The master socket is non-blocking but the client
1335 * sockets need to be blocking, otherwise certain
1336 * operations barf on FreeBSD. Not a fatal error.
1338 if (fcntl(ssock, F_SETFL, 0) < 0) {
1339 syslog(LOG_EMERG, "citserver: Can't set socket to blocking: %s", strerror(errno));
1342 /* New context will be created already
1343 * set up in the CON_EXECUTING state.
1345 con = CreateNewContext();
1347 /* Assign our new socket number to it. */
1348 con->tcp_port = serviceptr->tcp_port;
1349 con->client_socket = ssock;
1350 con->h_command_function = serviceptr->h_command_function;
1351 con->h_async_function = serviceptr->h_async_function;
1352 con->h_greeting_function = serviceptr->h_greeting_function;
1353 con->ServiceName = serviceptr->ServiceName;
1355 /* Determine whether it's a local socket */
1356 if (serviceptr->sockpath != NULL) {
1357 con->is_local_socket = 1;
1360 /* Set the SO_REUSEADDR socket option */
1362 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1363 con->state = CON_GREETING;
1371 /* It must be a client socket. Find a context that has data
1372 * waiting on its socket *and* is in the CON_IDLE state. Any
1373 * active sockets other than our chosen one are marked as
1374 * CON_READY so the next thread that comes around can just bind
1375 * to one without having to select() again.
1377 begin_critical_section(S_SESSION_TABLE);
1378 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1379 int checkfd = ptr->client_socket;
1380 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1381 if (FD_ISSET(checkfd, &readfds)) {
1382 ptr->input_waiting = 1;
1384 bind_me = ptr; /* I choose you! */
1385 bind_me->state = CON_EXECUTING;
1388 ptr->state = CON_READY;
1390 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1392 bind_me = ptr; /* I choose you! */
1393 bind_me->state = CON_EXECUTING;
1396 ptr->state = CON_READY;
1401 end_critical_section(S_SESSION_TABLE);
1404 /* We're bound to a session */
1405 pthread_mutex_lock(&ThreadCountMutex);
1407 pthread_mutex_unlock(&ThreadCountMutex);
1409 if (bind_me != NULL) {
1410 become_session(bind_me);
1412 if (bind_me->state == CON_STARTING) {
1413 bind_me->state = CON_EXECUTING;
1414 begin_session(bind_me);
1415 bind_me->h_greeting_function();
1417 /* If the client has sent a command, execute it. */
1418 if (CC->input_waiting) {
1419 CC->h_command_function();
1421 while (HaveMoreLinesWaiting(CC))
1422 CC->h_command_function();
1424 CC->input_waiting = 0;
1427 /* If there are asynchronous messages waiting and the
1428 * client supports it, do those now */
1429 if ((CC->is_async) && (CC->async_waiting)
1430 && (CC->h_async_function != NULL)) {
1431 CC->h_async_function();
1432 CC->async_waiting = 0;
1435 force_purge = CC->kill_me;
1436 become_session(NULL);
1437 bind_me->state = CON_IDLE;
1440 dead_session_purge(force_purge);
1443 pthread_mutex_lock(&ThreadCountMutex);
1445 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1446 (num_workers > CtdlGetConfigInt("c_min_workers")))
1449 pthread_mutex_unlock(&ThreadCountMutex);
1452 pthread_mutex_unlock(&ThreadCountMutex);
1455 /* If control reaches this point, the server is shutting down */
1456 pthread_mutex_lock(&ThreadCountMutex);
1458 pthread_mutex_unlock(&ThreadCountMutex);
1466 * Translate text facility name to syslog.h defined value.
1468 int SyslogFacility(char *name)
1477 { LOG_KERN, "kern" },
1478 { LOG_USER, "user" },
1479 { LOG_MAIL, "mail" },
1480 { LOG_DAEMON, "daemon" },
1481 { LOG_AUTH, "auth" },
1482 { LOG_SYSLOG, "syslog" },
1484 { LOG_NEWS, "news" },
1485 { LOG_UUCP, "uucp" },
1486 { LOG_LOCAL0, "local0" },
1487 { LOG_LOCAL1, "local1" },
1488 { LOG_LOCAL2, "local2" },
1489 { LOG_LOCAL3, "local3" },
1490 { LOG_LOCAL4, "local4" },
1491 { LOG_LOCAL5, "local5" },
1492 { LOG_LOCAL6, "local6" },
1493 { LOG_LOCAL7, "local7" },
1496 for(i = 0; facTbl[i].name != NULL; i++) {
1497 if(!strcasecmp(name, facTbl[i].name))
1498 return facTbl[i].facility;