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 free 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"
92 #ifdef DEBUG_MEMORY_LEAKS
100 struct igheap *igheap = NULL;
105 * Signal handler to shut down the server.
108 volatile int exit_signal = 0;
109 volatile int shutdown_and_halt = 0;
110 volatile int restart_server = 0;
111 volatile int running_as_daemon = 0;
113 static RETSIGTYPE signal_cleanup(int signum) {
118 Cc->self->signal = signum;
121 syslog(LOG_DEBUG, "Caught signal %d; shutting down.\n", signum);
122 exit_signal = signum;
126 static RETSIGTYPE signal_exit(int signum) {
133 * Some initialization stuff...
135 void init_sysdep(void) {
138 /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
142 getrlimit(RLIMIT_NOFILE, &rl);
143 rl.rlim_cur = FD_SETSIZE;
144 rl.rlim_max = FD_SETSIZE;
145 setrlimit(RLIMIT_NOFILE, &rl);
149 /* If we've got OpenSSL, we're going to use it. */
155 * Set up a place to put thread-specific data.
156 * We only need a single pointer per thread - it points to the
157 * CitContext structure (in the ContextList linked list) of the
158 * session to which the calling thread is currently bound.
160 if (citthread_key_create(&MyConKey, NULL) != 0) {
161 syslog(LOG_CRIT, "Can't create TSD key: %s\n",
166 * The action for unexpected signals and exceptions should be to
167 * call signal_cleanup() to gracefully shut down the server.
170 sigaddset(&set, SIGINT); // intr = shutdown
171 // sigaddset(&set, SIGQUIT); // quit = force quit
172 sigaddset(&set, SIGHUP);
173 sigaddset(&set, SIGTERM);
174 // sigaddset(&set, SIGSEGV); // we want core dumps
175 // sigaddset(&set, SIGILL); // we want core dumps
176 // sigaddset(&set, SIGBUS);
177 sigprocmask(SIG_UNBLOCK, &set, NULL);
179 signal(SIGINT, signal_cleanup); // intr = shutdown
180 // signal(SIGQUIT, signal_cleanup); // quit = force quit
181 signal(SIGHUP, signal_cleanup);
182 signal(SIGTERM, signal_cleanup);
183 signal(SIGUSR2, signal_exit);
184 // signal(SIGSEGV, signal_cleanup); // we want coredumps
185 // signal(SIGILL, signal_cleanup); // we want core dumps
186 // signal(SIGBUS, signal_cleanup);
189 * Do not shut down the server on broken pipe signals, otherwise the
190 * whole Citadel service would come down whenever a single client
193 signal(SIGPIPE, SIG_IGN);
198 * This is a generic function to set up a master socket for listening on
199 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
201 * ip_addr IP address to bind
202 * port_number port number to bind
203 * queue_len number of incoming connections to allow in the queue
205 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
208 struct sockaddr_in6 sin6;
209 struct sockaddr_in sin4;
213 memset(&sin6, 0, sizeof(sin6));
214 memset(&sin4, 0, sizeof(sin4));
215 sin6.sin6_family = AF_INET6;
216 sin4.sin_family = AF_INET;
218 if ( (ip_addr == NULL) /* any IPv6 */
219 || (IsEmptyStr(ip_addr))
220 || (!strcmp(ip_addr, "*"))
223 sin6.sin6_addr = in6addr_any;
225 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
228 sin4.sin_addr.s_addr = INADDR_ANY;
230 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
233 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
234 snprintf(errormessage, SIZ,
235 "Error binding to [%s] : %s", ip_addr, strerror(errno)
237 syslog(LOG_ALERT, "%s\n", errormessage);
241 else /* specific IPv6 */
244 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
245 snprintf(errormessage, SIZ,
246 "Error binding to [%s] : %s", ip_addr, strerror(errno)
248 syslog(LOG_ALERT, "%s\n", errormessage);
253 if (port_number == 0) {
254 snprintf(errormessage, SIZ,
255 "Can't start: no port number specified."
257 syslog(LOG_ALERT, "%s\n", errormessage);
260 sin6.sin6_port = htons((u_short) port_number);
261 sin4.sin_port = htons((u_short) port_number);
263 p = getprotobyname("tcp");
265 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
267 snprintf(errormessage, SIZ,
268 "Can't create a listening socket: %s", strerror(errno)
270 syslog(LOG_ALERT, "%s\n", errormessage);
273 /* Set some socket options that make sense. */
275 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
277 if (ip_version == 6) {
278 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
281 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
285 snprintf(errormessage, SIZ,
286 "Can't bind: %s", strerror(errno)
288 syslog(LOG_ALERT, "%s\n", errormessage);
292 fcntl(s, F_SETFL, O_NONBLOCK);
294 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
295 snprintf(errormessage, SIZ,
296 "Can't listen: %s", strerror(errno)
298 syslog(LOG_ALERT, "%s\n", errormessage);
309 * Create a Unix domain socket and listen on it
311 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
313 struct sockaddr_un addr;
316 int actual_queue_len;
317 #ifdef HAVE_STRUCT_UCRED
321 actual_queue_len = queue_len;
322 if (actual_queue_len < 5) actual_queue_len = 5;
324 i = unlink(sockpath);
325 if ((i != 0) && (errno != ENOENT)) {
326 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
327 sockpath, strerror(errno)
329 syslog(LOG_EMERG, "%s\n", errormessage);
333 memset(&addr, 0, sizeof(addr));
334 addr.sun_family = AF_UNIX;
335 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
337 s = socket(AF_UNIX, SOCK_STREAM, 0);
339 snprintf(errormessage, SIZ,
340 "citserver: Can't create a socket: %s",
342 syslog(LOG_EMERG, "%s\n", errormessage);
346 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
347 snprintf(errormessage, SIZ,
348 "citserver: Can't bind: %s",
350 syslog(LOG_EMERG, "%s\n", errormessage);
354 /* set to nonblock - we need this for some obscure situations */
355 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
356 snprintf(errormessage, SIZ,
357 "citserver: Can't set socket to non-blocking: %s",
359 syslog(LOG_EMERG, "%s\n", errormessage);
364 if (listen(s, actual_queue_len) < 0) {
365 snprintf(errormessage, SIZ,
366 "citserver: Can't listen: %s",
368 syslog(LOG_EMERG, "%s\n", errormessage);
372 #ifdef HAVE_STRUCT_UCRED
373 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
376 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
383 * The following functions implement output buffering on operating systems which
384 * support it (such as Linux and various BSD flavors).
388 # define HAVE_TCP_BUFFERING
391 # define HAVE_TCP_BUFFERING
392 # define TCP_CORK TCP_NOPUSH
394 #endif /* TCP_CORK */
395 #endif /* HAVE_DARWIN */
397 static unsigned on = 1, off = 0;
399 void buffer_output(void) {
400 #ifdef HAVE_TCP_BUFFERING
402 if (!CC->redirect_ssl)
404 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
408 void unbuffer_output(void) {
409 #ifdef HAVE_TCP_BUFFERING
411 if (!CC->redirect_ssl)
413 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
417 void flush_output(void) {
418 #ifdef HAVE_TCP_BUFFERING
419 struct CitContext *CCC = CC;
420 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
421 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
426 static void flush_client_inbuf(void)
430 FlushStrBuf(CCC->ReadBuf);
431 CCC->RecvBuf->ReadWritePointer = NULL;
437 * client_write() ... Send binary data to the client.
439 int client_write(const char *buf, int nbytes)
441 int bytes_written = 0;
443 #ifndef HAVE_TCP_BUFFERING
444 int old_buffer_len = 0;
450 if (nbytes < 1) return(0);
460 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
462 fd = fopen(fn, "a+");
465 fprintf(fd, "Sending: BufSize: %d BufContent: [",
467 rv = fwrite(buf, nbytes, 1, fd);
473 // flush_client_inbuf();
474 if (Ctx->redirect_buffer != NULL) {
475 StrBufAppendBufPlain(Ctx->redirect_buffer,
481 if (Ctx->redirect_ssl) {
482 client_write_ssl(buf, nbytes);
486 if (Ctx->client_socket == -1) return -1;
488 fdflags = fcntl(Ctx->client_socket, F_GETFL);
490 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
491 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
493 FD_SET(Ctx->client_socket, &wset);
494 if (select(1, NULL, &wset, NULL, NULL) == -1) {
497 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
498 if (CtdlThreadCheckStop()) {
502 /* can't trust fd's and stuff so we need to re-create them */
507 "client_write(%d bytes) select failed: %s (%d)\n",
508 nbytes - bytes_written,
509 strerror(errno), errno);
517 retval = write(Ctx->client_socket, &buf[bytes_written],
518 nbytes - bytes_written);
521 "client_write(%d bytes) failed: %s (%d)\n",
522 nbytes - bytes_written,
523 strerror(errno), errno);
525 // syslog(LOG_DEBUG, "Tried to send: %s", &buf[bytes_written]);
529 bytes_written = bytes_written + retval;
534 void cputbuf(const StrBuf *Buf) {
535 client_write(ChrPtr(Buf), StrLength(Buf));
540 * cprintf() Send formatted printable data to the client.
541 * Implemented in terms of client_write() so it's technically not sysdep...
543 void cprintf(const char *format, ...) {
547 va_start(arg_ptr, format);
548 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
549 buf[sizeof buf - 2] = '\n';
550 client_write(buf, strlen(buf));
556 * Read data from the client socket.
558 * sock socket fd to read from
559 * buf buffer to read into
560 * bytes number of bytes to read
561 * timeout Number of seconds to wait before timing out
563 * Possible return values:
564 * 1 Requested number of bytes has been read.
565 * 0 Request timed out.
566 * -1 Connection is broken, or other error.
568 int client_read_blob(StrBuf *Target, int bytes, int timeout)
575 if (CCC->redirect_ssl) {
581 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
583 fd = fopen(fn, "a+");
584 fprintf(fd, "Reading BLOB: BufSize: %d ",
586 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
592 retval = client_read_sslblob(Target, bytes, timeout);
599 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
601 fd = fopen(fn, "a+");
602 fprintf(fd, "Read: %d BufContent: [",
604 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
619 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
621 fd = fopen(fn, "a+");
622 fprintf(fd, "Reading BLOB: BufSize: %d ",
624 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
630 retval = StrBufReadBLOBBuffered(Target,
632 &CCC->RecvBuf.ReadWritePointer,
646 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
648 fd = fopen(fn, "a+");
649 fprintf(fd, "Read: %d BufContent: [",
651 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
663 * to make client_read_random_blob() more efficient, increase buffer size.
664 * just use in greeting function, else your buffer may be flushed
666 void client_set_inbound_buf(long N)
669 FlushStrBuf(CCC->RecvBuf.Buf);
670 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
673 int client_read_random_blob(StrBuf *Target, int timeout)
678 rc = client_read_blob(Target, 1, timeout);
684 len = StrLength(CCC->RecvBuf.Buf);
685 pch = ChrPtr(CCC->RecvBuf.Buf);
689 if (CCC->RecvBuf.ReadWritePointer != NULL) {
690 len -= CCC->RecvBuf.ReadWritePointer - pch;
691 pch = CCC->RecvBuf.ReadWritePointer;
693 StrBufAppendBufPlain(Target, pch, len, 0);
694 FlushStrBuf(CCC->RecvBuf.Buf);
695 CCC->RecvBuf.ReadWritePointer = NULL;
702 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
704 fd = fopen(fn, "a+");
705 fprintf(fd, "Read: BufSize: %d BufContent: [",
707 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
715 return StrLength(Target);
723 int client_read_to(char *buf, int bytes, int timeout)
728 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
737 ChrPtr(CCC->MigrateBuf),
738 StrLength(CCC->MigrateBuf) + 1);
739 FlushStrBuf(CCC->MigrateBuf);
745 int HaveMoreLinesWaiting(CitContext *CCC)
747 if ((CCC->kill_me == 1) || (
748 (CCC->RecvBuf.ReadWritePointer == NULL) &&
749 (StrLength(CCC->RecvBuf.Buf) == 0) &&
750 (CCC->client_socket != -1)) )
758 * Read data from the client socket with default timeout.
759 * (This is implemented in terms of client_read_to() and could be
760 * justifiably moved out of sysdep.c)
762 INLINE int client_read(char *buf, int bytes)
764 return(client_read_to(buf, bytes, config.c_sleeping));
767 int CtdlClientGetLine(StrBuf *Target)
775 if (CCC->redirect_ssl) {
785 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
787 fd = fopen(fn, "a+");
788 pch = ChrPtr(CCC->RecvBuf.Buf);
789 len = StrLength(CCC->RecvBuf.Buf);
790 if (CCC->RecvBuf.ReadWritePointer != NULL)
791 rlen = CCC->RecvBuf.ReadWritePointer - pch;
795 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
798 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
801 rc = client_readline_sslbuffer(Target,
803 &CCC->RecvBuf.ReadWritePointer,
806 pch = ChrPtr(CCC->RecvBuf.Buf);
807 nlen = StrLength(CCC->RecvBuf.Buf);
808 if (CCC->RecvBuf.ReadWritePointer != NULL)
809 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
813 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
814 len, nlen, rlen, nrlen, pch);
816 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
817 len, nlen, rlen, nrlen);
819 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
820 StrLength(Target), ChrPtr(Target));
836 int len, rlen, nlen, nrlen;
839 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
841 fd = fopen(fn, "a+");
842 pch = ChrPtr(CCC->RecvBuf.Buf);
843 len = StrLength(CCC->RecvBuf.Buf);
844 if (CCC->RecvBuf.ReadWritePointer != NULL)
845 rlen = CCC->RecvBuf.ReadWritePointer - pch;
849 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
852 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
855 rc = StrBufTCP_read_buffered_line_fast(Target,
857 &CCC->RecvBuf.ReadWritePointer,
864 pch = ChrPtr(CCC->RecvBuf.Buf);
865 nlen = StrLength(CCC->RecvBuf.Buf);
866 if (CCC->RecvBuf.ReadWritePointer != NULL)
867 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
871 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
872 len, nlen, rlen, nrlen, pch);
874 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
875 len, nlen, rlen, nrlen);
877 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
878 StrLength(Target), ChrPtr(Target));
881 if ((rc < 0) && (Error != NULL))
893 * client_getln() ... Get a LF-terminated line of text from the client.
894 * (This is implemented in terms of client_read() and could be
895 * justifiably moved out of sysdep.c)
897 int client_getln(char *buf, int bufsize)
903 retval = CtdlClientGetLine(CCC->MigrateBuf);
908 i = StrLength(CCC->MigrateBuf);
909 pCh = ChrPtr(CCC->MigrateBuf);
910 /* Strip the trailing LF, and the trailing CR if present.
915 && ( (pCh[i - 1]==13)
916 || ( pCh[i - 1]==10)) ) {
922 FlushStrBuf(CCC->MigrateBuf);
924 safestrncpy(&buf[i], "000", bufsize - i);
931 * Cleanup any contexts that are left lying around
935 void close_masters (void)
937 struct ServiceFunctionHook *serviceptr;
940 * close all protocol master sockets
942 for (serviceptr = ServiceHookTable; serviceptr != NULL;
943 serviceptr = serviceptr->next ) {
945 if (serviceptr->tcp_port > 0)
947 syslog(LOG_INFO, "Closing listener on port %d\n",
948 serviceptr->tcp_port);
949 serviceptr->tcp_port = 0;
952 if (serviceptr->sockpath != NULL)
953 syslog(LOG_INFO, "Closing listener on '%s'\n",
954 serviceptr->sockpath);
956 close(serviceptr->msock);
957 /* If it's a Unix domain socket, remove the file. */
958 if (serviceptr->sockpath != NULL) {
959 unlink(serviceptr->sockpath);
960 serviceptr->sockpath = NULL;
967 * The system-dependent part of master_cleanup() - close the master socket.
969 void sysdep_master_cleanup(void) {
978 CtdlDestroyProtoHooks();
979 CtdlDestroyDeleteHooks();
980 CtdlDestroyXmsgHooks();
981 CtdlDestroyNetprocHooks();
982 CtdlDestroyUserHooks();
983 CtdlDestroyMessageHook();
984 CtdlDestroyCleanupHooks();
985 CtdlDestroyFixedOutputHooks();
986 CtdlDestroySessionHooks();
987 CtdlDestroyServiceHook();
988 CtdlDestroyRoomHooks();
989 CtdlDestroySearchHooks();
990 #ifdef HAVE_BACKTRACE
998 void graceful_shutdown(int signum) {
999 kill(current_child, signum);
1000 unlink(file_pid_file);
1005 int nFireUpsNonRestart = 0;
1006 pid_t ForkedPid = 1;
1009 * Start running as a daemon.
1011 void start_daemon(int unused) {
1019 /* Close stdin/stdout/stderr and replace them with /dev/null.
1020 * We don't just call close() because we don't want these fd's
1021 * to be reused for other files.
1023 if (chdir(ctdl_run_dir) != 0)
1025 "unable to change into directory [%s]: %s",
1026 ctdl_run_dir, strerror(errno));
1033 signal(SIGHUP, SIG_IGN);
1034 signal(SIGINT, SIG_IGN);
1035 signal(SIGQUIT, SIG_IGN);
1039 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1040 (freopen("/dev/null", "w", stdout) != stdout) ||
1041 (freopen("/dev/null", "w", stderr) != stderr))
1043 "unable to reopen stdin/out/err %s",
1048 current_child = fork();
1050 signal(SIGTERM, graceful_shutdown);
1052 if (current_child < 0) {
1057 else if (current_child == 0) {
1058 return; /* continue starting citadel. */
1062 fp = fopen(file_pid_file, "w");
1064 fprintf(fp, ""F_PID_T"\n", getpid());
1067 waitpid(current_child, &status, 0);
1070 nFireUpsNonRestart = nFireUps;
1072 /* Exit code 0 means the watcher should exit */
1073 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1077 /* Exit code 101-109 means the watcher should exit */
1078 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1082 /* Any other exit code, or no exit code, means we should restart. */
1086 ForkedPid = current_child;
1089 } while (do_restart);
1091 unlink(file_pid_file);
1092 exit(WEXITSTATUS(status));
1097 void checkcrash(void)
1099 if (nFireUpsNonRestart != nFireUps)
1103 CrashMail = NewStrBuf();
1104 syslog(LOG_ALERT, "Posting crash message\n");
1105 StrBufPrintf(CrashMail,
1107 " The Citadel server process (citserver) terminated unexpectedly."
1109 " This could be the result of a bug in the server program, or some external "
1111 " You can obtain more information about this by enabling core dumps.\n \n"
1112 " For more information, please see:\n \n"
1113 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1116 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1118 ctdl_run_dir, ForkedPid);
1119 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1120 FreeStrBuf(&CrashMail);
1126 * Generic routine to convert a login name to a full name (gecos)
1127 * Returns nonzero if a conversion took place
1129 int convert_login(char NameToConvert[]) {
1133 pw = getpwnam(NameToConvert);
1138 strcpy(NameToConvert, pw->pw_gecos);
1139 for (a=0; a<strlen(NameToConvert); ++a) {
1140 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1149 * This loop just keeps going and going and going...
1153 * This current implimentation of worker_thread creates a bottle neck in several situations
1154 * The first thing to remember is that a single thread can handle more than one connection at a time.
1155 * More threads mean less memory for the system to run in.
1156 * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1157 * something to happen anywhere.
1158 * This current implimentation requires worker threads to wait in other locations, after it has
1159 * been committed to a single connection which is very wasteful.
1160 * As an extreme case consider this:
1161 * A slow client connects and this slow client sends only one character each second.
1162 * With this current implimentation a single worker thread is dispatched to handle that connection
1163 * until such times as the client timeout expires, an error occurs on the socket or the client
1164 * completes its transmission.
1165 * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1166 * second interval between chars.
1168 * It is my intention to re-write this code and the associated client_getln, client_read functions
1169 * to allow any thread to read data on behalf of any connection (context).
1170 * To do this I intend to have this main loop read chars into a buffer stored in the context.
1171 * Once the correct criteria for a full buffer is met then we will dispatch a thread to
1173 * This worker thread loop also needs to be able to handle binary data.
1176 void *worker_thread(void *arg) {
1179 CitContext *bind_me = NULL;
1183 int force_purge = 0;
1186 while (!CtdlThreadCheckStop()) {
1188 /* make doubly sure we're not holding any stale db handles
1189 * which might cause a deadlock.
1191 cdb_check_handles();
1192 do_select: force_purge = 0;
1193 bind_me = NULL; /* Which session shall we handle? */
1195 /* Initialize the fdset. */
1199 begin_critical_section(S_SESSION_TABLE);
1200 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1202 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1204 client_socket = ptr->client_socket;
1205 /* Dont select on dead sessions only truly idle ones */
1206 if ((ptr->state == CON_IDLE) &&
1207 (CC->kill_me == 0) &&
1208 (client_socket > 0))
1210 FD_SET(client_socket, &readfds);
1211 if (client_socket > highest)
1212 highest = client_socket;
1214 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1216 ptr->state = CON_EXECUTING;
1219 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1221 ptr->state = CON_STARTING;
1225 end_critical_section(S_SESSION_TABLE);
1231 /* If we got this far, it means that there are no sessions
1232 * which a previous thread marked for attention, so we go
1233 * ahead and get ready to select().
1236 if (!CtdlThreadCheckStop()) {
1237 tv.tv_sec = 1; /* wake up every second if no input */
1239 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1244 /* Now figure out who made this select() unblock.
1245 * First, check for an error or exit condition.
1248 if (errno == EBADF) {
1249 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1253 if (errno != EINTR) {
1254 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1255 CtdlThreadStopAll();
1259 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1261 if (CtdlThreadCheckStop()) return(NULL);
1265 else if(retval == 0) {
1266 if (CtdlThreadCheckStop()) return(NULL);
1269 /* It must be a client socket. Find a context that has data
1270 * waiting on its socket *and* is in the CON_IDLE state. Any
1271 * active sockets other than our chosen one are marked as
1272 * CON_READY so the next thread that comes around can just bind
1273 * to one without having to select() again.
1275 begin_critical_section(S_SESSION_TABLE);
1276 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1277 int checkfd = ptr->client_socket;
1278 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1279 if (FD_ISSET(checkfd, &readfds)) {
1280 ptr->input_waiting = 1;
1282 bind_me = ptr; /* I choose you! */
1283 bind_me->state = CON_EXECUTING;
1286 ptr->state = CON_READY;
1288 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1290 bind_me = ptr; /* I choose you! */
1291 bind_me->state = CON_EXECUTING;
1294 ptr->state = CON_READY;
1299 end_critical_section(S_SESSION_TABLE);
1302 /* We're bound to a session */
1303 if (bind_me != NULL) {
1304 become_session(bind_me);
1306 if (bind_me->state == CON_STARTING) {
1307 bind_me->state = CON_EXECUTING;
1308 begin_session(bind_me);
1309 bind_me->h_greeting_function();
1311 /* If the client has sent a command, execute it. */
1312 if (CC->input_waiting) {
1313 CC->h_command_function();
1315 while (HaveMoreLinesWaiting(CC))
1316 CC->h_command_function();
1318 CC->input_waiting = 0;
1321 /* If there are asynchronous messages waiting and the
1322 * client supports it, do those now */
1323 if ((CC->is_async) && (CC->async_waiting)
1324 && (CC->h_async_function != NULL)) {
1325 CC->h_async_function();
1326 CC->async_waiting = 0;
1329 force_purge = CC->kill_me;
1330 become_session(NULL);
1331 bind_me->state = CON_IDLE;
1334 dead_session_purge(force_purge);
1337 /* If control reaches this point, the server is shutting down */
1345 * A function to handle selecting on master sockets.
1346 * In other words it handles new connections.
1349 void *select_on_master (void *arg)
1351 struct ServiceFunctionHook *serviceptr;
1355 int ssock; /* Descriptor for client socket */
1356 CitContext *con= NULL; /* Temporary context pointer */
1360 struct CitContext select_on_master_CC;
1362 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1363 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1365 while (!CtdlThreadCheckStop()) {
1366 /* Initialize the fdset. */
1367 FD_ZERO(&master_fds);
1370 /* First, add the various master sockets to the fdset. */
1371 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1372 serviceptr = serviceptr->next ) {
1373 m = serviceptr->msock;
1374 FD_SET(m, &master_fds);
1380 if (!CtdlThreadCheckStop()) {
1381 tv.tv_sec = 60; /* wake up every second if no input */
1383 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1388 /* Now figure out who made this select() unblock.
1389 * First, check for an error or exit condition.
1392 if (errno == EBADF) {
1393 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1397 if (errno != EINTR) {
1398 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1399 CtdlThreadStopAll();
1402 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1404 if (CtdlThreadCheckStop()) return(NULL);
1408 else if(retval == 0) {
1409 if (CtdlThreadCheckStop()) return(NULL);
1412 /* Next, check to see if it's a new client connecting
1413 * on a master socket.
1415 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1416 serviceptr = serviceptr->next ) {
1418 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1419 ssock = accept(serviceptr->msock, NULL, 0);
1422 "New client socket %d\n",
1425 /* The master socket is non-blocking but the client
1426 * sockets need to be blocking, otherwise certain
1427 * operations barf on FreeBSD. Not a fatal error.
1429 if (fcntl(ssock, F_SETFL, 0) < 0) {
1431 "citserver: Can't set socket to blocking: %s\n",
1435 /* New context will be created already
1436 * set up in the CON_EXECUTING state.
1438 con = CreateNewContext();
1440 /* Assign our new socket number to it. */
1441 con->client_socket = ssock;
1442 con->h_command_function =
1443 serviceptr->h_command_function;
1444 con->h_async_function =
1445 serviceptr->h_async_function;
1446 con->h_greeting_function = serviceptr->h_greeting_function;
1448 serviceptr->ServiceName;
1450 /* Determine whether it's a local socket */
1451 if (serviceptr->sockpath != NULL)
1452 con->is_local_socket = 1;
1454 /* Set the SO_REUSEADDR socket option */
1456 setsockopt(ssock, SOL_SOCKET,
1460 con->state = CON_GREETING;
1469 CtdlClearSystemContext();
1478 * Translate text facility name to syslog.h defined value.
1480 int SyslogFacility(char *name)
1489 { LOG_KERN, "kern" },
1490 { LOG_USER, "user" },
1491 { LOG_MAIL, "mail" },
1492 { LOG_DAEMON, "daemon" },
1493 { LOG_AUTH, "auth" },
1494 { LOG_SYSLOG, "syslog" },
1496 { LOG_NEWS, "news" },
1497 { LOG_UUCP, "uucp" },
1498 { LOG_LOCAL0, "local0" },
1499 { LOG_LOCAL1, "local1" },
1500 { LOG_LOCAL2, "local2" },
1501 { LOG_LOCAL3, "local3" },
1502 { LOG_LOCAL4, "local4" },
1503 { LOG_LOCAL5, "local5" },
1504 { LOG_LOCAL6, "local6" },
1505 { LOG_LOCAL7, "local7" },
1508 for(i = 0; facTbl[i].name != NULL; i++) {
1509 if(!strcasecmp(name, facTbl[i].name))
1510 return facTbl[i].facility;
1516 /********** MEM CHEQQER ***********/
1518 #ifdef DEBUG_MEMORY_LEAKS
1525 void *tracked_malloc(size_t size, char *file, int line) {
1526 struct igheap *thisheap;
1529 block = malloc(size);
1530 if (block == NULL) return(block);
1532 thisheap = malloc(sizeof(struct igheap));
1533 if (thisheap == NULL) {
1538 thisheap->block = block;
1539 strcpy(thisheap->file, file);
1540 thisheap->line = line;
1542 begin_critical_section(S_DEBUGMEMLEAKS);
1543 thisheap->next = igheap;
1545 end_critical_section(S_DEBUGMEMLEAKS);
1551 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1552 struct igheap *thisheap;
1555 block = realloc(ptr, size);
1556 if (block == NULL) return(block);
1558 thisheap = malloc(sizeof(struct igheap));
1559 if (thisheap == NULL) {
1564 thisheap->block = block;
1565 strcpy(thisheap->file, file);
1566 thisheap->line = line;
1568 begin_critical_section(S_DEBUGMEMLEAKS);
1569 thisheap->next = igheap;
1571 end_critical_section(S_DEBUGMEMLEAKS);
1578 void tracked_free(void *ptr) {
1579 struct igheap *thisheap;
1580 struct igheap *trash;
1584 if (igheap == NULL) return;
1585 begin_critical_section(S_DEBUGMEMLEAKS);
1586 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1587 if (thisheap->next != NULL) {
1588 if (thisheap->next->block == ptr) {
1589 trash = thisheap->next;
1590 thisheap->next = thisheap->next->next;
1595 if (igheap->block == ptr) {
1597 igheap = igheap->next;
1600 end_critical_section(S_DEBUGMEMLEAKS);
1603 char *tracked_strdup(const char *s, char *file, int line) {
1606 if (s == NULL) return(NULL);
1607 ptr = tracked_malloc(strlen(s) + 1, file, line);
1608 if (ptr == NULL) return(NULL);
1609 strncpy(ptr, s, strlen(s));
1613 void dump_heap(void) {
1614 struct igheap *thisheap;
1616 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1617 syslog(LOG_CRIT, "UNFREED: %30s : %d\n",
1618 thisheap->file, thisheap->line);
1622 #endif /* DEBUG_MEMORY_LEAKS */