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"
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, SIGHUP);
172 sigaddset(&set, SIGTERM);
173 sigprocmask(SIG_UNBLOCK, &set, NULL);
175 signal(SIGINT, signal_cleanup); // intr = shutdown
176 signal(SIGHUP, signal_cleanup);
177 signal(SIGTERM, signal_cleanup);
178 signal(SIGUSR2, signal_exit);
181 * Do not shut down the server on broken pipe signals, otherwise the
182 * whole Citadel service would come down whenever a single client
185 signal(SIGPIPE, SIG_IGN);
190 * This is a generic function to set up a master socket for listening on
191 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
193 * ip_addr IP address to bind
194 * port_number port number to bind
195 * queue_len number of incoming connections to allow in the queue
197 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
200 struct sockaddr_in6 sin6;
201 struct sockaddr_in sin4;
205 memset(&sin6, 0, sizeof(sin6));
206 memset(&sin4, 0, sizeof(sin4));
207 sin6.sin6_family = AF_INET6;
208 sin4.sin_family = AF_INET;
210 if ( (ip_addr == NULL) /* any IPv6 */
211 || (IsEmptyStr(ip_addr))
212 || (!strcmp(ip_addr, "*"))
215 sin6.sin6_addr = in6addr_any;
217 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
220 sin4.sin_addr.s_addr = INADDR_ANY;
222 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
225 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
226 snprintf(errormessage, SIZ,
227 "Error binding to [%s] : %s", ip_addr, strerror(errno)
229 syslog(LOG_ALERT, "%s\n", errormessage);
233 else /* specific IPv6 */
236 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
237 snprintf(errormessage, SIZ,
238 "Error binding to [%s] : %s", ip_addr, strerror(errno)
240 syslog(LOG_ALERT, "%s\n", errormessage);
245 if (port_number == 0) {
246 snprintf(errormessage, SIZ,
247 "Can't start: no port number specified."
249 syslog(LOG_ALERT, "%s\n", errormessage);
252 sin6.sin6_port = htons((u_short) port_number);
253 sin4.sin_port = htons((u_short) port_number);
255 p = getprotobyname("tcp");
257 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
259 snprintf(errormessage, SIZ,
260 "Can't create a listening socket: %s", strerror(errno)
262 syslog(LOG_ALERT, "%s\n", errormessage);
265 /* Set some socket options that make sense. */
267 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
269 if (ip_version == 6) {
270 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
273 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
277 snprintf(errormessage, SIZ,
278 "Can't bind: %s", strerror(errno)
280 syslog(LOG_ALERT, "%s\n", errormessage);
284 fcntl(s, F_SETFL, O_NONBLOCK);
286 if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
287 snprintf(errormessage, SIZ,
288 "Can't listen: %s", strerror(errno)
290 syslog(LOG_ALERT, "%s\n", errormessage);
301 * Create a Unix domain socket and listen on it
303 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
305 struct sockaddr_un addr;
308 int actual_queue_len;
309 #ifdef HAVE_STRUCT_UCRED
313 actual_queue_len = queue_len;
314 if (actual_queue_len < 5) actual_queue_len = 5;
316 i = unlink(sockpath);
317 if ((i != 0) && (errno != ENOENT)) {
318 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
319 sockpath, strerror(errno)
321 syslog(LOG_EMERG, "%s\n", errormessage);
325 memset(&addr, 0, sizeof(addr));
326 addr.sun_family = AF_UNIX;
327 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
329 s = socket(AF_UNIX, SOCK_STREAM, 0);
331 snprintf(errormessage, SIZ,
332 "citserver: Can't create a socket: %s",
334 syslog(LOG_EMERG, "%s\n", errormessage);
338 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
339 snprintf(errormessage, SIZ,
340 "citserver: Can't bind: %s",
342 syslog(LOG_EMERG, "%s\n", errormessage);
346 /* set to nonblock - we need this for some obscure situations */
347 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
348 snprintf(errormessage, SIZ,
349 "citserver: Can't set socket to non-blocking: %s",
351 syslog(LOG_EMERG, "%s\n", errormessage);
356 if (listen(s, actual_queue_len) < 0) {
357 snprintf(errormessage, SIZ,
358 "citserver: Can't listen: %s",
360 syslog(LOG_EMERG, "%s\n", errormessage);
364 #ifdef HAVE_STRUCT_UCRED
365 setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
368 chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
375 * The following functions implement output buffering on operating systems which
376 * support it (such as Linux and various BSD flavors).
380 # define HAVE_TCP_BUFFERING
383 # define HAVE_TCP_BUFFERING
384 # define TCP_CORK TCP_NOPUSH
386 #endif /* TCP_CORK */
387 #endif /* HAVE_DARWIN */
389 static unsigned on = 1, off = 0;
391 void buffer_output(void) {
392 #ifdef HAVE_TCP_BUFFERING
394 if (!CC->redirect_ssl)
396 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
400 void unbuffer_output(void) {
401 #ifdef HAVE_TCP_BUFFERING
403 if (!CC->redirect_ssl)
405 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
409 void flush_output(void) {
410 #ifdef HAVE_TCP_BUFFERING
411 struct CitContext *CCC = CC;
412 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
413 setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
418 static void flush_client_inbuf(void)
422 FlushStrBuf(CCC->ReadBuf);
423 CCC->RecvBuf->ReadWritePointer = NULL;
430 * client_close() ... close the client socket
432 void client_close(void) {
433 CitContext *CCC = CC;
437 if (CCC->client_socket <= 0) return;
438 syslog(LOG_DEBUG, "Closing socket %d\n", CCC->client_socket);
439 r = close(CCC->client_socket);
440 if (!r) syslog(LOG_INFO, "close() failed: %s\n", strerror(errno));
441 CCC->client_socket = -1 ;
448 * client_write() ... Send binary data to the client.
450 int client_write(const char *buf, int nbytes)
452 int bytes_written = 0;
454 #ifndef HAVE_TCP_BUFFERING
455 int old_buffer_len = 0;
461 if (nbytes < 1) return(0);
471 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
473 fd = fopen(fn, "a+");
476 fprintf(fd, "Sending: BufSize: %d BufContent: [",
478 rv = fwrite(buf, nbytes, 1, fd);
484 // flush_client_inbuf();
485 if (Ctx->redirect_buffer != NULL) {
486 StrBufAppendBufPlain(Ctx->redirect_buffer,
492 if (Ctx->redirect_ssl) {
493 client_write_ssl(buf, nbytes);
497 if (Ctx->client_socket == -1) return -1;
499 fdflags = fcntl(Ctx->client_socket, F_GETFL);
501 while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
502 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
504 FD_SET(Ctx->client_socket, &wset);
505 if (select(1, NULL, &wset, NULL, NULL) == -1) {
508 syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
509 if (CtdlThreadCheckStop()) {
510 CC->kill_me = KILLME_SELECT_INTERRUPTED;
513 /* can't trust fd's and stuff so we need to re-create them */
518 "client_write(%d bytes) select failed: %s (%d)\n",
519 nbytes - bytes_written,
520 strerror(errno), errno
524 Ctx->kill_me = KILLME_SELECT_FAILED;
530 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
533 "client_write(%d bytes) failed: %s (%d)\n",
534 nbytes - bytes_written,
535 strerror(errno), errno
539 // syslog(LOG_DEBUG, "Tried to send: %s", &buf[bytes_written]);
540 Ctx->kill_me = KILLME_WRITE_FAILED;
543 bytes_written = bytes_written + retval;
548 void cputbuf(const StrBuf *Buf) {
549 client_write(ChrPtr(Buf), StrLength(Buf));
554 * cprintf() Send formatted printable data to the client.
555 * Implemented in terms of client_write() so it's technically not sysdep...
557 void cprintf(const char *format, ...) {
561 va_start(arg_ptr, format);
562 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
563 buf[sizeof buf - 2] = '\n';
564 client_write(buf, strlen(buf));
570 * Read data from the client socket.
572 * sock socket fd to read from
573 * buf buffer to read into
574 * bytes number of bytes to read
575 * timeout Number of seconds to wait before timing out
577 * Possible return values:
578 * 1 Requested number of bytes has been read.
579 * 0 Request timed out.
580 * -1 Connection is broken, or other error.
582 int client_read_blob(StrBuf *Target, int bytes, int timeout)
589 if (CCC->redirect_ssl) {
595 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
597 fd = fopen(fn, "a+");
598 fprintf(fd, "Reading BLOB: BufSize: %d ",
600 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
606 retval = client_read_sslblob(Target, bytes, timeout);
613 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
615 fd = fopen(fn, "a+");
616 fprintf(fd, "Read: %d BufContent: [",
618 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
633 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
635 fd = fopen(fn, "a+");
636 fprintf(fd, "Reading BLOB: BufSize: %d ",
638 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
644 retval = StrBufReadBLOBBuffered(Target,
646 &CCC->RecvBuf.ReadWritePointer,
653 syslog(LOG_CRIT, "%s failed: %s\n", __FUNCTION__, Error);
658 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
660 fd = fopen(fn, "a+");
661 fprintf(fd, "Read: %d BufContent: [",
663 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
673 * to make client_read_random_blob() more efficient, increase buffer size.
674 * just use in greeting function, else your buffer may be flushed
676 void client_set_inbound_buf(long N)
679 FlushStrBuf(CCC->RecvBuf.Buf);
680 ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
683 int client_read_random_blob(StrBuf *Target, int timeout)
688 rc = client_read_blob(Target, 1, timeout);
694 len = StrLength(CCC->RecvBuf.Buf);
695 pch = ChrPtr(CCC->RecvBuf.Buf);
699 if (CCC->RecvBuf.ReadWritePointer != NULL) {
700 len -= CCC->RecvBuf.ReadWritePointer - pch;
701 pch = CCC->RecvBuf.ReadWritePointer;
703 StrBufAppendBufPlain(Target, pch, len, 0);
704 FlushStrBuf(CCC->RecvBuf.Buf);
705 CCC->RecvBuf.ReadWritePointer = NULL;
712 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
714 fd = fopen(fn, "a+");
715 fprintf(fd, "Read: BufSize: %d BufContent: [",
717 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
725 return StrLength(Target);
733 int client_read_to(char *buf, int bytes, int timeout)
738 rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
747 ChrPtr(CCC->MigrateBuf),
748 StrLength(CCC->MigrateBuf) + 1);
749 FlushStrBuf(CCC->MigrateBuf);
755 int HaveMoreLinesWaiting(CitContext *CCC)
757 if ((CCC->kill_me != 0) ||
758 ( (CCC->RecvBuf.ReadWritePointer == NULL) &&
759 (StrLength(CCC->RecvBuf.Buf) == 0) &&
760 (CCC->client_socket != -1)) )
768 * Read data from the client socket with default timeout.
769 * (This is implemented in terms of client_read_to() and could be
770 * justifiably moved out of sysdep.c)
772 INLINE int client_read(char *buf, int bytes)
774 return(client_read_to(buf, bytes, config.c_sleeping));
777 int CtdlClientGetLine(StrBuf *Target)
785 if (CCC->redirect_ssl) {
795 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
797 fd = fopen(fn, "a+");
798 pch = ChrPtr(CCC->RecvBuf.Buf);
799 len = StrLength(CCC->RecvBuf.Buf);
800 if (CCC->RecvBuf.ReadWritePointer != NULL)
801 rlen = CCC->RecvBuf.ReadWritePointer - pch;
805 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
808 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
811 rc = client_readline_sslbuffer(Target,
813 &CCC->RecvBuf.ReadWritePointer,
816 pch = ChrPtr(CCC->RecvBuf.Buf);
817 nlen = StrLength(CCC->RecvBuf.Buf);
818 if (CCC->RecvBuf.ReadWritePointer != NULL)
819 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
823 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
824 len, nlen, rlen, nrlen, pch);
826 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
827 len, nlen, rlen, nrlen);
829 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
830 StrLength(Target), ChrPtr(Target));
846 int len, rlen, nlen, nrlen;
849 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
851 fd = fopen(fn, "a+");
852 pch = ChrPtr(CCC->RecvBuf.Buf);
853 len = StrLength(CCC->RecvBuf.Buf);
854 if (CCC->RecvBuf.ReadWritePointer != NULL)
855 rlen = CCC->RecvBuf.ReadWritePointer - pch;
859 /* fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
862 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
865 rc = StrBufTCP_read_buffered_line_fast(Target,
867 &CCC->RecvBuf.ReadWritePointer,
874 pch = ChrPtr(CCC->RecvBuf.Buf);
875 nlen = StrLength(CCC->RecvBuf.Buf);
876 if (CCC->RecvBuf.ReadWritePointer != NULL)
877 nrlen = CCC->RecvBuf.ReadWritePointer - pch;
881 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
882 len, nlen, rlen, nrlen, pch);
884 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
885 len, nlen, rlen, nrlen);
887 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
888 StrLength(Target), ChrPtr(Target));
891 if ((rc < 0) && (Error != NULL))
903 * client_getln() ... Get a LF-terminated line of text from the client.
904 * (This is implemented in terms of client_read() and could be
905 * justifiably moved out of sysdep.c)
907 int client_getln(char *buf, int bufsize)
913 retval = CtdlClientGetLine(CCC->MigrateBuf);
918 i = StrLength(CCC->MigrateBuf);
919 pCh = ChrPtr(CCC->MigrateBuf);
920 /* Strip the trailing LF, and the trailing CR if present.
925 && ( (pCh[i - 1]==13)
926 || ( pCh[i - 1]==10)) ) {
932 FlushStrBuf(CCC->MigrateBuf);
934 safestrncpy(&buf[i], "000", bufsize - i);
941 * Cleanup any contexts that are left lying around
945 void close_masters (void)
947 struct ServiceFunctionHook *serviceptr;
950 * close all protocol master sockets
952 for (serviceptr = ServiceHookTable; serviceptr != NULL;
953 serviceptr = serviceptr->next ) {
955 if (serviceptr->tcp_port > 0)
957 syslog(LOG_INFO, "Closing listener on port %d\n",
958 serviceptr->tcp_port);
959 serviceptr->tcp_port = 0;
962 if (serviceptr->sockpath != NULL)
963 syslog(LOG_INFO, "Closing listener on '%s'\n",
964 serviceptr->sockpath);
966 close(serviceptr->msock);
967 /* If it's a Unix domain socket, remove the file. */
968 if (serviceptr->sockpath != NULL) {
969 unlink(serviceptr->sockpath);
970 serviceptr->sockpath = NULL;
977 * The system-dependent part of master_cleanup() - close the master socket.
979 void sysdep_master_cleanup(void) {
988 CtdlDestroyProtoHooks();
989 CtdlDestroyDeleteHooks();
990 CtdlDestroyXmsgHooks();
991 CtdlDestroyNetprocHooks();
992 CtdlDestroyUserHooks();
993 CtdlDestroyMessageHook();
994 CtdlDestroyCleanupHooks();
995 CtdlDestroyFixedOutputHooks();
996 CtdlDestroySessionHooks();
997 CtdlDestroyServiceHook();
998 CtdlDestroyRoomHooks();
999 CtdlDestroySearchHooks();
1000 #ifdef HAVE_BACKTRACE
1001 /// eCrash_Uninit();
1007 pid_t current_child;
1008 void graceful_shutdown(int signum) {
1009 kill(current_child, signum);
1010 unlink(file_pid_file);
1015 int nFireUpsNonRestart = 0;
1016 pid_t ForkedPid = 1;
1019 * Start running as a daemon.
1021 void start_daemon(int unused) {
1029 /* Close stdin/stdout/stderr and replace them with /dev/null.
1030 * We don't just call close() because we don't want these fd's
1031 * to be reused for other files.
1033 if (chdir(ctdl_run_dir) != 0)
1035 "unable to change into directory [%s]: %s",
1036 ctdl_run_dir, strerror(errno));
1043 signal(SIGHUP, SIG_IGN);
1044 signal(SIGINT, SIG_IGN);
1045 signal(SIGQUIT, SIG_IGN);
1049 if ((freopen("/dev/null", "r", stdin) != stdin) ||
1050 (freopen("/dev/null", "w", stdout) != stdout) ||
1051 (freopen("/dev/null", "w", stderr) != stderr))
1053 "unable to reopen stdin/out/err %s",
1058 current_child = fork();
1060 signal(SIGTERM, graceful_shutdown);
1062 if (current_child < 0) {
1067 else if (current_child == 0) {
1068 return; /* continue starting citadel. */
1072 fp = fopen(file_pid_file, "w");
1074 fprintf(fp, ""F_PID_T"\n", getpid());
1077 waitpid(current_child, &status, 0);
1080 nFireUpsNonRestart = nFireUps;
1082 /* Exit code 0 means the watcher should exit */
1083 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1087 /* Exit code 101-109 means the watcher should exit */
1088 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1092 /* Any other exit code, or no exit code, means we should restart. */
1096 ForkedPid = current_child;
1099 } while (do_restart);
1101 unlink(file_pid_file);
1102 exit(WEXITSTATUS(status));
1107 void checkcrash(void)
1109 if (nFireUpsNonRestart != nFireUps)
1113 CrashMail = NewStrBuf();
1114 syslog(LOG_ALERT, "Posting crash message\n");
1115 StrBufPrintf(CrashMail,
1117 " The Citadel server process (citserver) terminated unexpectedly."
1119 " This could be the result of a bug in the server program, or some external "
1121 " You can obtain more information about this by enabling core dumps.\n \n"
1122 " For more information, please see:\n \n"
1123 " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1126 " If you have already done this, the core dump is likely to be found at %score.%d\n"
1128 ctdl_run_dir, ForkedPid);
1129 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1130 FreeStrBuf(&CrashMail);
1136 * Generic routine to convert a login name to a full name (gecos)
1137 * Returns nonzero if a conversion took place
1139 int convert_login(char NameToConvert[]) {
1143 pw = getpwnam(NameToConvert);
1148 strcpy(NameToConvert, pw->pw_gecos);
1149 for (a=0; a<strlen(NameToConvert); ++a) {
1150 if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1159 * This loop just keeps going and going and going...
1161 void *worker_thread(void *arg) {
1164 CitContext *bind_me = NULL;
1168 int force_purge = 0;
1171 while (!CtdlThreadCheckStop()) {
1173 /* make doubly sure we're not holding any stale db handles
1174 * which might cause a deadlock.
1176 cdb_check_handles();
1177 do_select: force_purge = 0;
1178 bind_me = NULL; /* Which session shall we handle? */
1180 /* Initialize the fdset. */
1184 begin_critical_section(S_SESSION_TABLE);
1185 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1186 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1189 /* Don't select on dead sessions, only truly idle ones */
1190 if ( (ptr->state == CON_IDLE)
1191 && (ptr->kill_me == 0)
1192 && (ptr->client_socket > 0)
1194 FD_SET(ptr->client_socket, &readfds);
1195 if (ptr->client_socket > highest)
1196 highest = ptr->client_socket;
1198 if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1200 ptr->state = CON_EXECUTING;
1203 if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1205 ptr->state = CON_STARTING;
1209 end_critical_section(S_SESSION_TABLE);
1215 /* If we got this far, it means that there are no sessions
1216 * which a previous thread marked for attention, so we go
1217 * ahead and get ready to select().
1220 if (!CtdlThreadCheckStop()) {
1221 tv.tv_sec = 1; /* wake up every second if no input */
1223 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1228 /* Now figure out who made this select() unblock.
1229 * First, check for an error or exit condition.
1232 if (errno == EBADF) {
1233 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1237 if (errno != EINTR) {
1238 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1239 CtdlThreadStopAll();
1243 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1245 if (CtdlThreadCheckStop()) return(NULL);
1249 else if(retval == 0) {
1250 if (CtdlThreadCheckStop()) return(NULL);
1253 /* It must be a client socket. Find a context that has data
1254 * waiting on its socket *and* is in the CON_IDLE state. Any
1255 * active sockets other than our chosen one are marked as
1256 * CON_READY so the next thread that comes around can just bind
1257 * to one without having to select() again.
1259 begin_critical_section(S_SESSION_TABLE);
1260 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1261 int checkfd = ptr->client_socket;
1262 if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1263 if (FD_ISSET(checkfd, &readfds)) {
1264 ptr->input_waiting = 1;
1266 bind_me = ptr; /* I choose you! */
1267 bind_me->state = CON_EXECUTING;
1270 ptr->state = CON_READY;
1272 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1274 bind_me = ptr; /* I choose you! */
1275 bind_me->state = CON_EXECUTING;
1278 ptr->state = CON_READY;
1283 end_critical_section(S_SESSION_TABLE);
1286 /* We're bound to a session */
1287 if (bind_me != NULL) {
1288 become_session(bind_me);
1290 if (bind_me->state == CON_STARTING) {
1291 bind_me->state = CON_EXECUTING;
1292 begin_session(bind_me);
1293 bind_me->h_greeting_function();
1295 /* If the client has sent a command, execute it. */
1296 if (CC->input_waiting) {
1297 CC->h_command_function();
1299 while (HaveMoreLinesWaiting(CC))
1300 CC->h_command_function();
1302 CC->input_waiting = 0;
1305 /* If there are asynchronous messages waiting and the
1306 * client supports it, do those now */
1307 if ((CC->is_async) && (CC->async_waiting)
1308 && (CC->h_async_function != NULL)) {
1309 CC->h_async_function();
1310 CC->async_waiting = 0;
1313 force_purge = CC->kill_me;
1314 become_session(NULL);
1315 bind_me->state = CON_IDLE;
1318 dead_session_purge(force_purge);
1321 /* If control reaches this point, the server is shutting down */
1329 * A function to handle selecting on master sockets.
1330 * In other words it handles new connections.
1333 void *select_on_master (void *arg)
1335 struct ServiceFunctionHook *serviceptr;
1339 int ssock; /* Descriptor for client socket */
1340 CitContext *con= NULL; /* Temporary context pointer */
1344 struct CitContext select_on_master_CC;
1346 CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1347 citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1349 while (!CtdlThreadCheckStop()) {
1350 /* Initialize the fdset. */
1351 FD_ZERO(&master_fds);
1354 /* First, add the various master sockets to the fdset. */
1355 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1356 serviceptr = serviceptr->next ) {
1357 m = serviceptr->msock;
1358 FD_SET(m, &master_fds);
1364 if (!CtdlThreadCheckStop()) {
1365 tv.tv_sec = 60; /* wake up every second if no input */
1367 retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1372 /* Now figure out who made this select() unblock.
1373 * First, check for an error or exit condition.
1376 if (errno == EBADF) {
1377 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1381 if (errno != EINTR) {
1382 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1383 CtdlThreadStopAll();
1386 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1388 if (CtdlThreadCheckStop()) return(NULL);
1392 else if(retval == 0) {
1393 if (CtdlThreadCheckStop()) return(NULL);
1396 /* Next, check to see if it's a new client connecting
1397 * on a master socket.
1399 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1400 serviceptr = serviceptr->next ) {
1402 if (FD_ISSET(serviceptr->msock, &master_fds)) {
1403 ssock = accept(serviceptr->msock, NULL, 0);
1405 syslog(LOG_DEBUG, "New client socket %d\n", ssock);
1407 /* The master socket is non-blocking but the client
1408 * sockets need to be blocking, otherwise certain
1409 * operations barf on FreeBSD. Not a fatal error.
1411 if (fcntl(ssock, F_SETFL, 0) < 0) {
1413 "citserver: Can't set socket to blocking: %s\n",
1417 /* New context will be created already
1418 * set up in the CON_EXECUTING state.
1420 con = CreateNewContext();
1422 /* Assign our new socket number to it. */
1423 con->client_socket = ssock;
1424 con->h_command_function = serviceptr->h_command_function;
1425 con->h_async_function = serviceptr->h_async_function;
1426 con->h_greeting_function = serviceptr->h_greeting_function;
1427 con->ServiceName = serviceptr->ServiceName;
1429 /* Determine whether it's a local socket */
1430 if (serviceptr->sockpath != NULL) {
1431 con->is_local_socket = 1;
1434 /* Set the SO_REUSEADDR socket option */
1436 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1437 con->state = CON_GREETING;
1445 CtdlClearSystemContext();
1454 * Translate text facility name to syslog.h defined value.
1456 int SyslogFacility(char *name)
1465 { LOG_KERN, "kern" },
1466 { LOG_USER, "user" },
1467 { LOG_MAIL, "mail" },
1468 { LOG_DAEMON, "daemon" },
1469 { LOG_AUTH, "auth" },
1470 { LOG_SYSLOG, "syslog" },
1472 { LOG_NEWS, "news" },
1473 { LOG_UUCP, "uucp" },
1474 { LOG_LOCAL0, "local0" },
1475 { LOG_LOCAL1, "local1" },
1476 { LOG_LOCAL2, "local2" },
1477 { LOG_LOCAL3, "local3" },
1478 { LOG_LOCAL4, "local4" },
1479 { LOG_LOCAL5, "local5" },
1480 { LOG_LOCAL6, "local6" },
1481 { LOG_LOCAL7, "local7" },
1484 for(i = 0; facTbl[i].name != NULL; i++) {
1485 if(!strcasecmp(name, facTbl[i].name))
1486 return facTbl[i].facility;
1492 /********** MEM CHEQQER ***********/
1494 #ifdef DEBUG_MEMORY_LEAKS
1501 void *tracked_malloc(size_t size, char *file, int line) {
1502 struct igheap *thisheap;
1505 block = malloc(size);
1506 if (block == NULL) return(block);
1508 thisheap = malloc(sizeof(struct igheap));
1509 if (thisheap == NULL) {
1514 thisheap->block = block;
1515 strcpy(thisheap->file, file);
1516 thisheap->line = line;
1518 begin_critical_section(S_DEBUGMEMLEAKS);
1519 thisheap->next = igheap;
1521 end_critical_section(S_DEBUGMEMLEAKS);
1527 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1528 struct igheap *thisheap;
1531 block = realloc(ptr, size);
1532 if (block == NULL) return(block);
1534 thisheap = malloc(sizeof(struct igheap));
1535 if (thisheap == NULL) {
1540 thisheap->block = block;
1541 strcpy(thisheap->file, file);
1542 thisheap->line = line;
1544 begin_critical_section(S_DEBUGMEMLEAKS);
1545 thisheap->next = igheap;
1547 end_critical_section(S_DEBUGMEMLEAKS);
1554 void tracked_free(void *ptr) {
1555 struct igheap *thisheap;
1556 struct igheap *trash;
1560 if (igheap == NULL) return;
1561 begin_critical_section(S_DEBUGMEMLEAKS);
1562 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1563 if (thisheap->next != NULL) {
1564 if (thisheap->next->block == ptr) {
1565 trash = thisheap->next;
1566 thisheap->next = thisheap->next->next;
1571 if (igheap->block == ptr) {
1573 igheap = igheap->next;
1576 end_critical_section(S_DEBUGMEMLEAKS);
1579 char *tracked_strdup(const char *s, char *file, int line) {
1582 if (s == NULL) return(NULL);
1583 ptr = tracked_malloc(strlen(s) + 1, file, line);
1584 if (ptr == NULL) return(NULL);
1585 strncpy(ptr, s, strlen(s));
1589 void dump_heap(void) {
1590 struct igheap *thisheap;
1592 for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1593 syslog(LOG_CRIT, "UNFREED: %30s : %d\n",
1594 thisheap->file, thisheap->line);
1598 #endif /* DEBUG_MEMORY_LEAKS */