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, "sysdep: 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, "sysdep: 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, "Error binding to [%s] : %s", ip_addr, strerror(errno));
159 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
163 else /* specific IPv6 */
166 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
167 snprintf(errormessage, SIZ,
168 "Error binding to [%s] : %s", ip_addr, strerror(errno)
170 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
175 if (port_number == 0) {
176 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
177 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
180 sin6.sin6_port = htons((u_short) port_number);
181 sin4.sin_port = htons((u_short) port_number);
183 p = getprotobyname("tcp");
185 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
187 snprintf(errormessage, SIZ, "Can't create a listening socket: %s", strerror(errno));
188 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
191 /* Set some socket options that make sense. */
193 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
195 if (ip_version == 6) {
196 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
199 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
203 snprintf(errormessage, SIZ, "Can't bind: %s", strerror(errno));
204 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
208 fcntl(s, F_SETFL, O_NONBLOCK);
210 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
211 snprintf(errormessage, SIZ, "Can't listen: %s", strerror(errno));
212 syslog(LOG_ALERT, "tcpserver: %s", errormessage);
220 * Create a Unix domain socket and listen on it
222 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
224 struct sockaddr_un addr;
227 int actual_queue_len;
228 #ifdef HAVE_STRUCT_UCRED
232 actual_queue_len = queue_len;
233 if (actual_queue_len < 5) actual_queue_len = 5;
235 i = unlink(sockpath);
236 if ((i != 0) && (errno != ENOENT)) {
237 snprintf(errormessage, SIZ, "can't unlink %s: %s", sockpath, strerror(errno));
238 syslog(LOG_EMERG, "udsserver: %s", errormessage);
242 memset(&addr, 0, sizeof(addr));
243 addr.sun_family = AF_UNIX;
244 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
246 s = socket(AF_UNIX, SOCK_STREAM, 0);
248 snprintf(errormessage, SIZ, "can't create a socket: %s", strerror(errno));
249 syslog(LOG_EMERG, "udsserver: %s", errormessage);
253 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
254 snprintf(errormessage, SIZ, "can't bind: %s", strerror(errno));
255 syslog(LOG_EMERG, "udsserver: %s", errormessage);
259 /* set to nonblock - we need this for some obscure situations */
260 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
261 snprintf(errormessage, SIZ, "can't set socket to non-blocking: %s", strerror(errno));
262 syslog(LOG_EMERG, "udsserver: %s", errormessage);
267 if (listen(s, actual_queue_len) < 0) {
268 snprintf(errormessage, SIZ, "can't listen: %s", strerror(errno));
269 syslog(LOG_EMERG, "udsserver: %s", errormessage);
273 #ifdef HAVE_STRUCT_UCRED
274 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
277 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
283 * The following functions implement output buffering on operating systems which
284 * support it (such as Linux and various BSD flavors).
288 # define HAVE_TCP_BUFFERING
291 # define HAVE_TCP_BUFFERING
292 # define TCP_CORK TCP_NOPUSH
294 #endif /* TCP_CORK */
295 #endif /* HAVE_DARWIN */
297 static unsigned on = 1, off = 0;
299 void buffer_output(void) {
300 #ifdef HAVE_TCP_BUFFERING
302 if (!CC->redirect_ssl)
304 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
308 void unbuffer_output(void) {
309 #ifdef HAVE_TCP_BUFFERING
311 if (!CC->redirect_ssl)
313 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
317 void flush_output(void) {
318 #ifdef HAVE_TCP_BUFFERING
319 struct CitContext *CCC = CC;
320 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
321 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
326 static void flush_client_inbuf(void)
330 FlushStrBuf(CCC->ReadBuf);
331 CCC->RecvBuf->ReadWritePointer = NULL;
338 * client_close() ... close the client socket
340 void client_close(void) {
341 CitContext *CCC = CC;
344 if (CCC->client_socket <= 0) return;
345 syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
346 close(CCC->client_socket);
347 CCC->client_socket = -1 ;
352 * client_write() ... Send binary data to the client.
354 int client_write(const char *buf, int nbytes)
356 int bytes_written = 0;
358 #ifndef HAVE_TCP_BUFFERING
359 int old_buffer_len = 0;
365 if (nbytes < 1) return(0);
375 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
377 fd = fopen(fn, "a+");
379 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
383 fprintf(fd, "Sending: BufSize: %d BufContent: [", nbytes);
384 rv = fwrite(buf, nbytes, 1, fd);
389 // flush_client_inbuf();
390 if (Ctx->redirect_buffer != NULL) {
391 StrBufAppendBufPlain(Ctx->redirect_buffer,
397 if (Ctx->redirect_ssl) {
398 client_write_ssl(buf, nbytes);
402 if (Ctx->client_socket == -1) return -1;
404 fdflags = fcntl(Ctx->client_socket, F_GETFL);
406 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
407 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
409 FD_SET(Ctx->client_socket, &wset);
410 if (select(1, NULL, &wset, NULL, NULL) == -1) {
413 syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
414 if (server_shutting_down) {
415 CC->kill_me = KILLME_SELECT_INTERRUPTED;
418 /* can't trust fd's and stuff so we need to re-create them */
423 "sysdep: client_write(%d bytes) select failed: %s (%d)",
424 nbytes - bytes_written,
425 strerror(errno), errno
429 Ctx->kill_me = KILLME_SELECT_FAILED;
435 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
438 "sysdep: client_write(%d bytes) failed: %s (%d)",
439 nbytes - bytes_written,
440 strerror(errno), errno
444 Ctx->kill_me = KILLME_WRITE_FAILED;
447 bytes_written = bytes_written + retval;
452 void cputbuf(const StrBuf *Buf) {
453 client_write(ChrPtr(Buf), StrLength(Buf));
458 * cprintf() Send formatted printable data to the client.
459 * Implemented in terms of client_write() so it's technically not sysdep...
461 void cprintf(const char *format, ...) {
465 va_start(arg_ptr, format);
466 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
467 buf[sizeof buf - 2] = '\n';
468 client_write(buf, strlen(buf));
474 * Read data from the client socket.
476 * sock socket fd to read from
477 * buf buffer to read into
478 * bytes number of bytes to read
479 * timeout Number of seconds to wait before timing out
481 * Possible return values:
482 * 1 Requested number of bytes has been read.
483 * 0 Request timed out.
484 * -1 Connection is broken, or other error.
486 int client_read_blob(StrBuf *Target, int bytes, int timeout)
493 if (CCC->redirect_ssl) {
499 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
501 fd = fopen(fn, "a+");
503 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
507 fprintf(fd, "Reading BLOB: BufSize: %d ", bytes);
508 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
514 retval = client_read_sslblob(Target, bytes, timeout);
516 syslog(LOG_ERR, "sysdep: client_read_blob() failed");
519 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
521 fd = fopen(fn, "a+");
523 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
527 fprintf(fd, "Read: %d BufContent: [", StrLength(Target));
528 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
541 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
543 fd = fopen(fn, "a+");
545 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
549 fprintf(fd, "Reading BLOB: BufSize: %d ",
551 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
555 retval = StrBufReadBLOBBuffered(Target,
557 &CCC->RecvBuf.ReadWritePointer,
565 syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
570 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
572 fd = fopen(fn, "a+");
574 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
578 fprintf(fd, "Read: %d BufContent: [",
580 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
590 * to make client_read_random_blob() more efficient, increase buffer size.
591 * just use in greeting function, else your buffer may be flushed
593 void client_set_inbound_buf(long N)
596 FlushStrBuf(CCC->RecvBuf.Buf);
597 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
600 int client_read_random_blob(StrBuf *Target, int timeout)
605 rc = client_read_blob(Target, 1, timeout);
611 len = StrLength(CCC->RecvBuf.Buf);
612 pch = ChrPtr(CCC->RecvBuf.Buf);
616 if (CCC->RecvBuf.ReadWritePointer != NULL) {
617 len -= CCC->RecvBuf.ReadWritePointer - pch;
618 pch = CCC->RecvBuf.ReadWritePointer;
620 StrBufAppendBufPlain(Target, pch, len, 0);
621 FlushStrBuf(CCC->RecvBuf.Buf);
622 CCC->RecvBuf.ReadWritePointer = NULL;
629 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
631 fd = fopen(fn, "a+");
633 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
637 fprintf(fd, "Read: BufSize: %d BufContent: [",
639 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
644 return StrLength(Target);
652 int client_read_to(char *buf, int bytes, int timeout)
657 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
666 ChrPtr(CCC->MigrateBuf),
667 StrLength(CCC->MigrateBuf) + 1);
668 FlushStrBuf(CCC->MigrateBuf);
674 int HaveMoreLinesWaiting(CitContext *CCC)
676 if ((CCC->kill_me != 0) ||
677 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
678 (StrLength(CCC->RecvBuf.Buf) == 0) &&
679 (CCC->client_socket != -1)) )
687 * Read data from the client socket with default timeout.
688 * (This is implemented in terms of client_read_to() and could be
689 * justifiably moved out of sysdep.c)
691 INLINE int client_read(char *buf, int bytes)
693 return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
696 int CtdlClientGetLine(StrBuf *Target)
704 if (CCC->redirect_ssl) {
714 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
716 fd = fopen(fn, "a+");
718 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
722 pch = ChrPtr(CCC->RecvBuf.Buf);
723 len = StrLength(CCC->RecvBuf.Buf);
724 if (CCC->RecvBuf.ReadWritePointer != NULL)
725 rlen = CCC->RecvBuf.ReadWritePointer - pch;
729 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
732 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
735 rc = client_readline_sslbuffer(Target,
737 &CCC->RecvBuf.ReadWritePointer,
740 pch = ChrPtr(CCC->RecvBuf.Buf);
741 nlen = StrLength(CCC->RecvBuf.Buf);
742 if (CCC->RecvBuf.ReadWritePointer != NULL)
743 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
747 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
748 len, nlen, rlen, nrlen, pch);
750 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
751 len, nlen, rlen, nrlen);
753 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
754 StrLength(Target), ChrPtr(Target));
758 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed");
769 int len, rlen, nlen, nrlen;
772 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
774 fd = fopen(fn, "a+");
776 syslog(LOG_ERR, "%s: %s", fn, strerror(errno));
780 pch = ChrPtr(CCC->RecvBuf.Buf);
781 len = StrLength(CCC->RecvBuf.Buf);
782 if (CCC->RecvBuf.ReadWritePointer != NULL)
783 rlen = CCC->RecvBuf.ReadWritePointer - pch;
787 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
790 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
793 rc = StrBufTCP_read_buffered_line_fast(Target,
795 &CCC->RecvBuf.ReadWritePointer,
803 pch = ChrPtr(CCC->RecvBuf.Buf);
804 nlen = StrLength(CCC->RecvBuf.Buf);
805 if (CCC->RecvBuf.ReadWritePointer != NULL)
806 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
810 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
811 len, nlen, rlen, nrlen, pch);
813 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
814 len, nlen, rlen, nrlen);
816 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
817 StrLength(Target), ChrPtr(Target));
820 if ((rc < 0) && (Error != NULL)) {
821 syslog(LOG_ERR, "sysdep: CtdlClientGetLine() failed: %s", Error);
830 * client_getln() ... Get a LF-terminated line of text from the client.
831 * (This is implemented in terms of client_read() and could be
832 * justifiably moved out of sysdep.c)
834 int client_getln(char *buf, int bufsize)
840 retval = CtdlClientGetLine(CCC->MigrateBuf);
845 i = StrLength(CCC->MigrateBuf);
846 pCh = ChrPtr(CCC->MigrateBuf);
847 /* Strip the trailing LF, and the trailing CR if present.
852 && ( (pCh[i - 1]==13)
853 || ( pCh[i - 1]==10)) ) {
859 FlushStrBuf(CCC->MigrateBuf);
861 safestrncpy(&buf[i], "000", bufsize - i);
868 * Cleanup any contexts that are left lying around
872 void close_masters (void)
874 struct ServiceFunctionHook *serviceptr;
878 * close all protocol master sockets
880 for (serviceptr = ServiceHookTable; serviceptr != NULL;
881 serviceptr = serviceptr->next ) {
883 if (serviceptr->tcp_port > 0)
885 if (serviceptr->msock == -1) {
886 Text = "not closing again";
891 syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
896 serviceptr->tcp_port = 0;
899 if (serviceptr->sockpath != NULL)
901 if (serviceptr->msock == -1) {
902 Text = "not closing again";
907 syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
914 if (serviceptr->msock != -1)
916 close(serviceptr->msock);
917 serviceptr->msock = -1;
920 /* If it's a Unix domain socket, remove the file. */
921 if (serviceptr->sockpath != NULL) {
922 unlink(serviceptr->sockpath);
923 serviceptr->sockpath = NULL;
930 * The system-dependent part of master_cleanup() - close the master socket.
932 void sysdep_master_cleanup(void) {
941 CtdlDestroyProtoHooks();
942 CtdlDestroyDeleteHooks();
943 CtdlDestroyXmsgHooks();
944 CtdlDestroyNetprocHooks();
945 CtdlDestroyUserHooks();
946 CtdlDestroyMessageHook();
947 CtdlDestroyCleanupHooks();
948 CtdlDestroyFixedOutputHooks();
949 CtdlDestroySessionHooks();
950 CtdlDestroyServiceHook();
951 CtdlDestroyRoomHooks();
952 CtdlDestroySearchHooks();
953 CtdlDestroyDebugTable();
954 #ifdef HAVE_BACKTRACE
962 void graceful_shutdown(int signum) {
963 kill(current_child, signum);
964 unlink(file_pid_file);
969 int nFireUpsNonRestart = 0;
973 * Start running as a daemon.
975 void start_daemon(int unused) {
983 /* Close stdin/stdout/stderr and replace them with /dev/null.
984 * We don't just call close() because we don't want these fd's
985 * to be reused for other files.
987 if (chdir(ctdl_run_dir) != 0) {
988 syslog(LOG_ERR, "%s: %s", ctdl_run_dir, strerror(errno));
996 signal(SIGHUP, SIG_IGN);
997 signal(SIGINT, SIG_IGN);
998 signal(SIGQUIT, SIG_IGN);
1002 if ( (freopen("/dev/null", "r", stdin) != stdin) ||
1003 (freopen("/dev/null", "w", stdout) != stdout) ||
1004 (freopen("/dev/null", "w", stderr) != stderr)
1006 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %s", strerror(errno));
1010 current_child = fork();
1011 signal(SIGTERM, graceful_shutdown);
1012 if (current_child < 0) {
1016 else if (current_child == 0) {
1017 return; /* continue starting citadel. */
1020 fp = fopen(file_pid_file, "w");
1022 fprintf(fp, ""F_PID_T"\n", getpid());
1025 waitpid(current_child, &status, 0);
1027 nFireUpsNonRestart = nFireUps;
1029 /* Exit code 0 means the watcher should exit */
1030 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1034 /* Exit code 101-109 means the watcher should exit */
1035 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1039 /* Any other exit code, or no exit code, means we should restart. */
1043 ForkedPid = current_child;
1046 } while (do_restart);
1048 unlink(file_pid_file);
1049 exit(WEXITSTATUS(status));
1054 void checkcrash(void)
1056 if (nFireUpsNonRestart != nFireUps)
1059 CrashMail = NewStrBuf();
1060 syslog(LOG_ALERT, "sysdep: posting crash message");
1061 StrBufPrintf(CrashMail,
1063 " The Citadel server process (citserver) terminated unexpectedly."
1065 " This could be the result of a bug in the server program, or some external "
1067 " You can obtain more information about this by enabling core dumps.\n \n"
1068 " For more information, please see:\n \n"
1069 " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1072 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1074 ctdl_run_dir, ForkedPid);
1075 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1076 FreeStrBuf(&CrashMail);
1082 * Generic routine to convert a login name to a full name (gecos)
1083 * Returns nonzero if a conversion took place
1085 int convert_login(char NameToConvert[]) {
1089 pw = getpwnam(NameToConvert);
1094 strcpy(NameToConvert, pw->pw_gecos);
1095 for (a=0; a<strlen(NameToConvert); ++a) {
1096 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1104 void HuntBadSession(void)
1110 struct ServiceFunctionHook *serviceptr;
1114 /* Next, add all of the client sockets. */
1115 begin_critical_section(S_SESSION_TABLE);
1116 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1117 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1119 /* Initialize the fdset. */
1122 tv.tv_sec = 0; /* wake up every second if no input */
1125 /* Don't select on dead sessions, only truly idle ones */
1126 if ( (ptr->state == CON_IDLE)
1127 && (ptr->kill_me == 0)
1128 && (ptr->client_socket > 0)
1130 FD_SET(ptr->client_socket, &readfds);
1131 if (ptr->client_socket > highest)
1132 highest = ptr->client_socket;
1134 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1139 "sysdep: killing session CC[%d] bad FD: [%d:%d] User[%s] Host[%s:%s]",
1142 ptr->is_local_socket,
1144 ptr->cs_host,ptr->cs_addr);
1147 ptr->client_socket = -1;
1153 end_critical_section(S_SESSION_TABLE);
1156 /* First, add the various master sockets to the fdset. */
1157 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1159 /* Initialize the fdset. */
1161 tv.tv_sec = 0; /* wake up every second if no input */
1164 FD_SET(serviceptr->msock, &readfds);
1165 if (serviceptr->msock > highest) {
1166 highest = serviceptr->msock;
1168 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
1171 /* Gotcha! server socket dead? commit suicide! */
1172 syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
1173 server_shutting_down = 1;
1181 const char *WorkerLogStr = "W";
1183 * This loop just keeps going and going and going...
1185 void *worker_thread(void *blah) {
1188 CitContext *bind_me = NULL;
1192 int force_purge = 0;
1193 struct ServiceFunctionHook *serviceptr;
1194 int ssock; /* Descriptor for client socket */
1195 CitContext *con = NULL; /* Temporary context pointer */
1198 pthread_mutex_lock(&ThreadCountMutex);
1200 pthread_mutex_unlock(&ThreadCountMutex);
1202 while (!server_shutting_down) {
1204 /* make doubly sure we're not holding any stale db handles
1205 * which might cause a deadlock.
1207 cdb_check_handles();
1208 do_select: force_purge = 0;
1209 bind_me = NULL; /* Which session shall we handle? */
1211 /* Initialize the fdset. */
1215 /* First, add the various master sockets to the fdset. */
1216 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1217 FD_SET(serviceptr->msock, &readfds);
1218 if (serviceptr->msock > highest) {
1219 highest = serviceptr->msock;
1223 /* Next, add all of the client sockets. */
1224 begin_critical_section(S_SESSION_TABLE);
1225 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1226 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1229 /* Don't select on dead sessions, only truly idle ones */
1230 if ( (ptr->state == CON_IDLE)
1231 && (ptr->kill_me == 0)
1232 && (ptr->client_socket > 0)
1234 FD_SET(ptr->client_socket, &readfds);
1235 if (ptr->client_socket > highest)
1236 highest = ptr->client_socket;
1238 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1240 ptr->state = CON_EXECUTING;
1243 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1245 ptr->state = CON_STARTING;
1249 end_critical_section(S_SESSION_TABLE);
1255 /* If we got this far, it means that there are no sessions
1256 * which a previous thread marked for attention, so we go
1257 * ahead and get ready to select().
1260 if (!server_shutting_down) {
1261 tv.tv_sec = 1; /* wake up every second if no input */
1263 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1270 /* Now figure out who made this select() unblock.
1271 * First, check for an error or exit condition.
1274 if (errno == EBADF) {
1275 syslog(LOG_ERR, "sysdep: select() failed: (%s)", strerror(errno));
1279 if (errno != EINTR) {
1280 syslog(LOG_ERR, "sysdep: exiting (%s)", strerror(errno));
1281 server_shutting_down = 1;
1284 if (server_shutting_down) {
1291 else if (retval == 0) {
1292 if (server_shutting_down) {
1298 /* Next, check to see if it's a new client connecting * on a master socket. */
1300 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1302 if (FD_ISSET(serviceptr->msock, &readfds)) {
1303 ssock = accept(serviceptr->msock, NULL, 0);
1305 syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1307 /* The master socket is non-blocking but the client
1308 * sockets need to be blocking, otherwise certain
1309 * operations barf on FreeBSD. Not a fatal error.
1311 if (fcntl(ssock, F_SETFL, 0) < 0) {
1312 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %s", strerror(errno));
1315 /* New context will be created already
1316 * set up in the CON_EXECUTING state.
1318 con = CreateNewContext();
1320 /* Assign our new socket number to it. */
1321 con->tcp_port = serviceptr->tcp_port;
1322 con->client_socket = ssock;
1323 con->h_command_function = serviceptr->h_command_function;
1324 con->h_async_function = serviceptr->h_async_function;
1325 con->h_greeting_function = serviceptr->h_greeting_function;
1326 con->ServiceName = serviceptr->ServiceName;
1328 /* Determine whether it's a local socket */
1329 if (serviceptr->sockpath != NULL) {
1330 con->is_local_socket = 1;
1333 /* Set the SO_REUSEADDR socket option */
1335 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1336 con->state = CON_GREETING;
1344 /* It must be a client socket. Find a context that has data
1345 * waiting on its socket *and* is in the CON_IDLE state. Any
1346 * active sockets other than our chosen one are marked as
1347 * CON_READY so the next thread that comes around can just bind
1348 * to one without having to select() again.
1350 begin_critical_section(S_SESSION_TABLE);
1351 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1352 int checkfd = ptr->client_socket;
1353 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1354 if (FD_ISSET(checkfd, &readfds)) {
1355 ptr->input_waiting = 1;
1357 bind_me = ptr; /* I choose you! */
1358 bind_me->state = CON_EXECUTING;
1361 ptr->state = CON_READY;
1363 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1365 bind_me = ptr; /* I choose you! */
1366 bind_me->state = CON_EXECUTING;
1369 ptr->state = CON_READY;
1374 end_critical_section(S_SESSION_TABLE);
1377 /* We're bound to a session */
1378 pthread_mutex_lock(&ThreadCountMutex);
1380 pthread_mutex_unlock(&ThreadCountMutex);
1382 if (bind_me != NULL) {
1383 become_session(bind_me);
1385 if (bind_me->state == CON_STARTING) {
1386 bind_me->state = CON_EXECUTING;
1387 begin_session(bind_me);
1388 bind_me->h_greeting_function();
1390 /* If the client has sent a command, execute it. */
1391 if (CC->input_waiting) {
1392 CC->h_command_function();
1394 while (HaveMoreLinesWaiting(CC))
1395 CC->h_command_function();
1397 CC->input_waiting = 0;
1400 /* If there are asynchronous messages waiting and the
1401 * client supports it, do those now */
1402 if ((CC->is_async) && (CC->async_waiting)
1403 && (CC->h_async_function != NULL)) {
1404 CC->h_async_function();
1405 CC->async_waiting = 0;
1408 force_purge = CC->kill_me;
1409 become_session(NULL);
1410 bind_me->state = CON_IDLE;
1413 dead_session_purge(force_purge);
1416 pthread_mutex_lock(&ThreadCountMutex);
1418 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1419 (num_workers > CtdlGetConfigInt("c_min_workers")))
1422 pthread_mutex_unlock(&ThreadCountMutex);
1425 pthread_mutex_unlock(&ThreadCountMutex);
1428 /* If control reaches this point, the server is shutting down */
1429 pthread_mutex_lock(&ThreadCountMutex);
1431 pthread_mutex_unlock(&ThreadCountMutex);
1439 * Translate text facility name to syslog.h defined value.
1441 int SyslogFacility(char *name)
1450 { LOG_KERN, "kern" },
1451 { LOG_USER, "user" },
1452 { LOG_MAIL, "mail" },
1453 { LOG_DAEMON, "daemon" },
1454 { LOG_AUTH, "auth" },
1455 { LOG_SYSLOG, "syslog" },
1457 { LOG_NEWS, "news" },
1458 { LOG_UUCP, "uucp" },
1459 { LOG_LOCAL0, "local0" },
1460 { LOG_LOCAL1, "local1" },
1461 { LOG_LOCAL2, "local2" },
1462 { LOG_LOCAL3, "local3" },
1463 { LOG_LOCAL4, "local4" },
1464 { LOG_LOCAL5, "local5" },
1465 { LOG_LOCAL6, "local6" },
1466 { LOG_LOCAL7, "local7" },
1469 for(i = 0; facTbl[i].name != NULL; i++) {
1470 if(!strcasecmp(name, facTbl[i].name))
1471 return facTbl[i].facility;