164cafd5a70e2e530d888cb2b4df3695d5fb057e
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <syslog.h>
27 #include <sys/syslog.h>
28
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
31 # include <time.h>
32 #else
33 # if HAVE_SYS_TIME_H
34 #  include <sys/time.h>
35 # else
36 #  include <time.h>
37 # endif
38 #endif
39
40 #include <limits.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <sys/un.h>
47 #include <string.h>
48 #include <pwd.h>
49 #include <errno.h>
50 #include <stdarg.h>
51 #include <grp.h>
52 #include <libcitadel.h>
53 #include "citadel.h"
54 #include "server.h"
55 #include "sysdep_decls.h"
56 #include "citserver.h"
57 #include "support.h"
58 #include "config.h"
59 #include "database.h"
60 #include "housekeeping.h"
61 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
62 #include "ecrash.h"
63
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
66 #endif
67
68 #ifndef HAVE_SNPRINTF
69 #include "snprintf.h"
70 #endif
71
72 #include "ctdl_module.h"
73 #include "threads.h"
74
75 #ifdef DEBUG_MEMORY_LEAKS
76 struct igheap {
77         struct igheap *next;
78         char file[32];
79         int line;
80         void *block;
81 };
82
83 struct igheap *igheap = NULL;
84 #endif
85
86
87 citthread_key_t MyConKey;                               /* TSD key for MyContext() */
88
89 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
90
91 struct CitContext masterCC;
92 time_t last_purge = 0;                          /* Last dead session purge */
93 int num_sessions = 0;                           /* Current number of sessions */
94
95 int syslog_facility = LOG_DAEMON;
96 int enable_syslog = 0;
97
98
99 /*
100  * Create an interface to lprintf that follows the coding convention.
101  * This is here until such time as we have replaced all calls to lprintf with CtdlLogPrintf
102  */
103  
104 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...)
105 {
106         va_list arg_ptr;
107         va_start(arg_ptr, format);
108         vlprintf(loglevel, format, arg_ptr);
109         va_end(arg_ptr);
110 }
111
112
113 /*
114  * lprintf()  ...   Write logging information
115  */
116 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
117         va_list arg_ptr;
118         va_start(arg_ptr, format);
119         vlprintf(loglevel, format, arg_ptr);
120         va_end(arg_ptr);
121 }
122
123 void vlprintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
124 {
125         char buf[SIZ], buf2[SIZ];
126
127         if (enable_syslog) {
128                 vsyslog((syslog_facility | loglevel), format, arg_ptr);
129         }
130
131         /* stderr output code */
132         if (enable_syslog || running_as_daemon) return;
133
134         /* if we run in forground and syslog is disabled, log to terminal */
135         if (loglevel <= verbosity) { 
136                 struct timeval tv;
137                 struct tm tim;
138                 time_t unixtime;
139
140                 gettimeofday(&tv, NULL);
141                 /* Promote to time_t; types differ on some OSes (like darwin) */
142                 unixtime = tv.tv_sec;
143                 localtime_r(&unixtime, &tim);
144                 if (CC->cs_pid != 0) {
145                         sprintf(buf,
146                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
147                                 tim.tm_year + 1900, tim.tm_mon + 1,
148                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
149                                 tim.tm_sec, (long)tv.tv_usec,
150                                 CC->cs_pid);
151                 } else {
152                         sprintf(buf,
153                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
154                                 tim.tm_year + 1900, tim.tm_mon + 1,
155                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
156                                 tim.tm_sec, (long)tv.tv_usec);
157                 }
158                 vsnprintf(buf2, SIZ, format, arg_ptr);   
159
160                 fprintf(stderr, "%s%s", buf, buf2);
161                 fflush(stderr);
162         }
163 }   
164
165
166
167 /*
168  * Signal handler to shut down the server.
169  */
170
171 volatile int exit_signal = 0;
172 volatile int shutdown_and_halt = 0;
173 volatile int restart_server = 0;
174 volatile int running_as_daemon = 0;
175
176 static RETSIGTYPE signal_cleanup(int signum) {
177         CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
178 #ifdef THREADS_USESIGNALS
179         if (CT)
180         {
181                 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, signum);
182                 CT->signal = signum;
183         }
184         else
185 #endif
186                 exit_signal = signum;
187 }
188
189
190
191 /*
192  * Some initialization stuff...
193  */
194 void init_sysdep(void) {
195         sigset_t set;
196
197         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
198 #ifdef FD_SETSIZE
199 #ifdef RLIMIT_NOFILE
200         struct rlimit rl;
201         getrlimit(RLIMIT_NOFILE, &rl);
202         rl.rlim_cur = FD_SETSIZE;
203         rl.rlim_max = FD_SETSIZE;
204         setrlimit(RLIMIT_NOFILE, &rl);
205 #endif
206 #endif
207
208         /* If we've got OpenSSL, we're going to use it. */
209 #ifdef HAVE_OPENSSL
210         init_ssl();
211 #endif
212
213         /*
214          * Set up a place to put thread-specific data.
215          * We only need a single pointer per thread - it points to the
216          * CitContext structure (in the ContextList linked list) of the
217          * session to which the calling thread is currently bound.
218          */
219         if (citthread_key_create(&MyConKey, NULL) != 0) {
220                 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
221                         strerror(errno));
222         }
223
224         /*
225          * The action for unexpected signals and exceptions should be to
226          * call signal_cleanup() to gracefully shut down the server.
227          */
228         sigemptyset(&set);
229         sigaddset(&set, SIGINT);
230         sigaddset(&set, SIGQUIT);
231         sigaddset(&set, SIGHUP);
232         sigaddset(&set, SIGTERM);
233         // sigaddset(&set, SIGSEGV);    commented out because
234         // sigaddset(&set, SIGILL);     we want core dumps
235         // sigaddset(&set, SIGBUS);
236         sigprocmask(SIG_UNBLOCK, &set, NULL);
237
238         signal(SIGINT, signal_cleanup);
239         signal(SIGQUIT, signal_cleanup);
240         signal(SIGHUP, signal_cleanup);
241         signal(SIGTERM, signal_cleanup);
242         // signal(SIGSEGV, signal_cleanup);     commented out because
243         // signal(SIGILL, signal_cleanup);      we want core dumps
244         // signal(SIGBUS, signal_cleanup);
245
246         /*
247          * Do not shut down the server on broken pipe signals, otherwise the
248          * whole Citadel service would come down whenever a single client
249          * socket breaks.
250          */
251         signal(SIGPIPE, SIG_IGN);
252 }
253
254
255
256
257 /*
258  * This is a generic function to set up a master socket for listening on
259  * a TCP port.  The server shuts down if the bind fails.
260  *
261  */
262 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
263 {
264         struct sockaddr_in sin;
265         int s, i;
266         int actual_queue_len;
267
268         actual_queue_len = queue_len;
269         if (actual_queue_len < 5) actual_queue_len = 5;
270
271         memset(&sin, 0, sizeof(sin));
272         sin.sin_family = AF_INET;
273         sin.sin_port = htons((u_short)port_number);
274         if (ip_addr == NULL) {
275                 sin.sin_addr.s_addr = INADDR_ANY;
276         }
277         else {
278                 sin.sin_addr.s_addr = inet_addr(ip_addr);
279         }
280                                                                                 
281         if (sin.sin_addr.s_addr == !INADDR_ANY) {
282                 sin.sin_addr.s_addr = INADDR_ANY;
283         }
284
285         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
286
287         if (s < 0) {
288                 *errormessage = (char*) malloc(SIZ + 1);
289                 snprintf(*errormessage, SIZ, 
290                                  "citserver: Can't create a socket: %s",
291                                  strerror(errno));
292                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
293                 return(-1);
294         }
295
296         i = 1;
297         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
298
299         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
300                 *errormessage = (char*) malloc(SIZ + 1);
301                 snprintf(*errormessage, SIZ, 
302                                  "citserver: Can't bind: %s",
303                                  strerror(errno));
304                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
305                 close(s);
306                 return(-1);
307         }
308
309         /* set to nonblock - we need this for some obscure situations */
310         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
311                 *errormessage = (char*) malloc(SIZ + 1);
312                 snprintf(*errormessage, SIZ, 
313                                  "citserver: Can't set socket to non-blocking: %s",
314                                  strerror(errno));
315                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
316                 close(s);
317                 return(-1);
318         }
319
320         if (listen(s, actual_queue_len) < 0) {
321                 *errormessage = (char*) malloc(SIZ + 1);
322                 snprintf(*errormessage, SIZ, 
323                                  "citserver: Can't listen: %s",
324                                  strerror(errno));
325                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
326                 close(s);
327                 return(-1);
328         }
329
330         return(s);
331 }
332
333
334
335 /*
336  * Create a Unix domain socket and listen on it
337  */
338 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
339 {
340         struct sockaddr_un addr;
341         int s;
342         int i;
343         int actual_queue_len;
344
345         actual_queue_len = queue_len;
346         if (actual_queue_len < 5) actual_queue_len = 5;
347
348         i = unlink(sockpath);
349         if (i != 0) if (errno != ENOENT) {
350                 *errormessage = (char*) malloc(SIZ + 1);
351                 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
352                         sockpath, strerror(errno));
353                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
354                 return(-1);
355         }
356
357         memset(&addr, 0, sizeof(addr));
358         addr.sun_family = AF_UNIX;
359         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
360
361         s = socket(AF_UNIX, SOCK_STREAM, 0);
362         if (s < 0) {
363                 *errormessage = (char*) malloc(SIZ + 1);
364                 snprintf(*errormessage, SIZ, 
365                          "citserver: Can't create a socket: %s",
366                          strerror(errno));
367                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
368                 return(-1);
369         }
370
371         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
372                 *errormessage = (char*) malloc(SIZ + 1);
373                 snprintf(*errormessage, SIZ, 
374                          "citserver: Can't bind: %s",
375                          strerror(errno));
376                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
377                 return(-1);
378         }
379
380         /* set to nonblock - we need this for some obscure situations */
381         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
382                 *errormessage = (char*) malloc(SIZ + 1);
383                 snprintf(*errormessage, SIZ, 
384                          "citserver: Can't set socket to non-blocking: %s",
385                          strerror(errno));
386                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
387                 close(s);
388                 return(-1);
389         }
390
391         if (listen(s, actual_queue_len) < 0) {
392                 *errormessage = (char*) malloc(SIZ + 1);
393                 snprintf(*errormessage, SIZ, 
394                          "citserver: Can't listen: %s",
395                          strerror(errno));
396                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
397                 return(-1);
398         }
399
400         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
401         return(s);
402 }
403
404
405
406 /*
407  * Return a pointer to the CitContext structure bound to the thread which
408  * called this function.  If there's no such binding (for example, if it's
409  * called by the housekeeper thread) then a generic 'master' CC is returned.
410  *
411  * This function is used *VERY* frequently and must be kept small.
412  */
413 struct CitContext *MyContext(void) {
414
415         register struct CitContext *c;
416
417         return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
418                 c == NULL) ? &masterCC : c
419         );
420 }
421
422
423 /*
424  * Initialize a new context and place it in the list.  The session number
425  * used to be the PID (which is why it's called cs_pid), but that was when we
426  * had one process per session.  Now we just assign them sequentially, starting
427  * at 1 (don't change it to 0 because masterCC uses 0).
428  */
429 struct CitContext *CreateNewContext(void) {
430         struct CitContext *me;
431         static int next_pid = 0;
432
433         me = (struct CitContext *) malloc(sizeof(struct CitContext));
434         if (me == NULL) {
435                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
436                 return NULL;
437         }
438         memset(me, 0, sizeof(struct CitContext));
439
440         /* The new context will be created already in the CON_EXECUTING state
441          * in order to prevent another thread from grabbing it while it's
442          * being set up.
443          */
444         me->state = CON_EXECUTING;
445         /*
446          * Generate a unique session number and insert this context into
447          * the list.
448          */
449         begin_critical_section(S_SESSION_TABLE);
450         me->cs_pid = ++next_pid;
451         me->prev = NULL;
452         me->next = ContextList;
453         ContextList = me;
454         if (me->next != NULL) {
455                 me->next->prev = me;
456         }
457         ++num_sessions;
458         end_critical_section(S_SESSION_TABLE);
459         return (me);
460 }
461
462
463 /*
464  * The following functions implement output buffering. If the kernel supplies
465  * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
466  * user-space buffering.
467  */
468 #ifndef HAVE_DARWIN
469 #ifdef TCP_CORK
470 #       define HAVE_TCP_BUFFERING
471 #else
472 #       ifdef TCP_NOPUSH
473 #               define HAVE_TCP_BUFFERING
474 #               define TCP_CORK TCP_NOPUSH
475 #       endif
476 #endif /* TCP_CORK */
477 #endif /* HAVE_DARWIN */
478
479 #ifdef HAVE_TCP_BUFFERING
480 static unsigned on = 1, off = 0;
481 void buffer_output(void) {
482         struct CitContext *ctx = MyContext();
483         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
484         ctx->buffering = 1;
485 }
486
487 void unbuffer_output(void) {
488         struct CitContext *ctx = MyContext();
489         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
490         ctx->buffering = 0;
491 }
492
493 void flush_output(void) {
494         struct CitContext *ctx = MyContext();
495         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
496         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
497 }
498 #else 
499 #ifdef HAVE_DARWIN
500 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
501 void buffer_output(void) {
502         CC->buffering = 0;
503 }
504 void unbuffer_output(void) {
505         CC->buffering = 0;
506 }
507 void flush_output(void) {
508 }
509 #else
510 void buffer_output(void) {
511         if (CC->buffering == 0) {
512                 CC->buffering = 1;
513                 CC->buffer_len = 0;
514                 CC->output_buffer = malloc(SIZ);
515         }
516 }
517
518 void flush_output(void) {
519         if (CC->buffering == 1) {
520                 client_write(CC->output_buffer, CC->buffer_len);
521                 CC->buffer_len = 0;
522         }
523 }
524
525 void unbuffer_output(void) {
526         if (CC->buffering == 1) {
527                 CC->buffering = 0;
528                 /* We don't call flush_output because we can't. */
529                 client_write(CC->output_buffer, CC->buffer_len);
530                 CC->buffer_len = 0;
531                 free(CC->output_buffer);
532                 CC->output_buffer = NULL;
533         }
534 }
535 #endif /* HAVE_DARWIN */
536 #endif /* HAVE_TCP_BUFFERING */
537
538
539
540 /*
541  * client_write()   ...    Send binary data to the client.
542  */
543 void client_write(char *buf, int nbytes)
544 {
545         int bytes_written = 0;
546         int retval;
547 #ifndef HAVE_TCP_BUFFERING
548         int old_buffer_len = 0;
549 #endif
550         fd_set wset;
551         t_context *Ctx;
552         int fdflags;
553
554         Ctx = CC;
555         if (Ctx->redirect_buffer != NULL) {
556                 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
557                         Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
558                         Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
559                                                 Ctx->redirect_alloc);
560                 }
561                 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
562                 Ctx->redirect_len += nbytes;
563                 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
564                 return;
565         }
566
567 #ifndef HAVE_TCP_BUFFERING
568         /* If we're buffering for later, do that now. */
569         if (Ctx->buffering) {
570                 old_buffer_len = Ctx->buffer_len;
571                 Ctx->buffer_len += nbytes;
572                 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
573                 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
574                 return;
575         }
576 #endif
577
578         /* Ok, at this point we're not buffering.  Go ahead and write. */
579
580 #ifdef HAVE_OPENSSL
581         if (Ctx->redirect_ssl) {
582                 client_write_ssl(buf, nbytes);
583                 return;
584         }
585 #endif
586
587         fdflags = fcntl(Ctx->client_socket, F_GETFL);
588
589         while (bytes_written < nbytes) {
590                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
591                         FD_ZERO(&wset);
592                         FD_SET(Ctx->client_socket, &wset);
593                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
594                                 CtdlLogPrintf(CTDL_ERR,
595                                         "client_write(%d bytes) select failed: %s (%d)\n",
596                                         nbytes - bytes_written,
597                                         strerror(errno), errno);
598                                 cit_backtrace();
599                                 Ctx->kill_me = 1;
600                                 return;
601                         }
602                 }
603
604                 retval = write(Ctx->client_socket, &buf[bytes_written],
605                         nbytes - bytes_written);
606                 if (retval < 1) {
607                         CtdlLogPrintf(CTDL_ERR,
608                                 "client_write(%d bytes) failed: %s (%d)\n",
609                                 nbytes - bytes_written,
610                                 strerror(errno), errno);
611                         cit_backtrace();
612                         // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
613                         Ctx->kill_me = 1;
614                         return;
615                 }
616                 bytes_written = bytes_written + retval;
617         }
618 }
619
620
621 /*
622  * cprintf()  ...   Send formatted printable data to the client.   It is
623  *                implemented in terms of client_write() but remains in
624  *                sysdep.c in case we port to somewhere without va_args...
625  */
626 void cprintf(const char *format, ...) {   
627         va_list arg_ptr;   
628         char buf[1024];   
629    
630         va_start(arg_ptr, format);   
631         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
632                 buf[sizeof buf - 2] = '\n';
633         client_write(buf, strlen(buf)); 
634         va_end(arg_ptr);
635 }   
636
637
638 /*
639  * Read data from the client socket.
640  * Return values are:
641  *      1       Requested number of bytes has been read.
642  *      0       Request timed out.
643  *      -1      The socket is broken.
644  * If the socket breaks, the session will be terminated.
645  */
646 int client_read_to(char *buf, int bytes, int timeout)
647 {
648         int len,rlen;
649         fd_set rfds;
650         int fd;
651         struct timeval tv;
652         int retval;
653
654 #ifdef HAVE_OPENSSL
655         if (CC->redirect_ssl) {
656                 return (client_read_ssl(buf, bytes, timeout));
657         }
658 #endif
659         len = 0;
660         fd = CC->client_socket;
661         while(len<bytes) {
662                 FD_ZERO(&rfds);
663                 FD_SET(fd, &rfds);
664                 tv.tv_sec = timeout;
665                 tv.tv_usec = 0;
666
667                 retval = select( (fd)+1, 
668                                  &rfds, NULL, NULL, &tv);
669
670                 if (FD_ISSET(fd, &rfds) == 0) {
671                         return(0);
672                 }
673
674                 rlen = read(fd, &buf[len], bytes-len);
675                 if (rlen<1) {
676                         /* The socket has been disconnected! */
677                         CC->kill_me = 1;
678                         return(-1);
679                 }
680                 len = len + rlen;
681         }
682         return(1);
683 }
684
685 /*
686  * Read data from the client socket with default timeout.
687  * (This is implemented in terms of client_read_to() and could be
688  * justifiably moved out of sysdep.c)
689  */
690 INLINE int client_read(char *buf, int bytes)
691 {
692         return(client_read_to(buf, bytes, config.c_sleeping));
693 }
694
695
696 /*
697  * client_getln()   ...   Get a LF-terminated line of text from the client.
698  * (This is implemented in terms of client_read() and could be
699  * justifiably moved out of sysdep.c)
700  */
701 int client_getln(char *buf, int bufsize)
702 {
703         int i, retval;
704
705         /* Read one character at a time.
706          */
707         for (i = 0;;i++) {
708                 retval = client_read(&buf[i], 1);
709                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
710                         break;
711         }
712
713         /* If we got a long line, discard characters until the newline.
714          */
715         if (i == (bufsize-1))
716                 while (buf[i] != '\n' && retval == 1)
717                         retval = client_read(&buf[i], 1);
718
719         /* Strip the trailing LF, and the trailing CR if present.
720          */
721         buf[i] = 0;
722         while ( (i > 0)
723                 && ( (buf[i - 1]==13)
724                      || ( buf[i - 1]==10)) ) {
725                 i--;
726                 buf[i] = 0;
727         }
728         if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
729         return(retval);
730 }
731
732
733 /*
734  * Cleanup any contexts that are left lying around
735  */
736 void context_cleanup(void)
737 {
738         struct CitContext *ptr = NULL;
739         struct CitContext *rem = NULL;
740
741         /*
742          * Clean up the contexts.
743          * There are no threads so no critical_section stuff is needed.
744          */
745         ptr = ContextList;
746         
747         /* We need to update the ContextList because some modules may want to itterate it
748          * Question is should we NULL it before iterating here or should we just keep updating it
749          * as we remove items?
750          *
751          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
752          */
753         ContextList=NULL;
754         while (ptr != NULL){
755                 /* Remove the session from the active list */
756                 rem = ptr->next;
757                 --num_sessions;
758                 
759                 lprintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
760                 RemoveContext(ptr);
761                 free (ptr);
762                 ptr = rem;
763         }
764 }
765
766
767
768 void close_masters (void)
769 {
770         struct ServiceFunctionHook *serviceptr;
771         
772         /*
773          * close all protocol master sockets
774          */
775         for (serviceptr = ServiceHookTable; serviceptr != NULL;
776             serviceptr = serviceptr->next ) {
777
778                 if (serviceptr->tcp_port > 0)
779                 {
780                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
781                                 serviceptr->tcp_port);
782                         serviceptr->tcp_port = 0;
783                 }
784                 
785                 if (serviceptr->sockpath != NULL)
786                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
787                                 serviceptr->sockpath);
788
789                 close(serviceptr->msock);
790                 /* If it's a Unix domain socket, remove the file. */
791                 if (serviceptr->sockpath != NULL) {
792                         unlink(serviceptr->sockpath);
793                         serviceptr->sockpath = NULL;
794                 }
795         }
796 }
797
798
799 /*
800  * The system-dependent part of master_cleanup() - close the master socket.
801  */
802 void sysdep_master_cleanup(void) {
803         
804         close_masters();
805         
806         context_cleanup();
807         
808 #ifdef HAVE_OPENSSL
809         destruct_ssl();
810 #endif
811         CtdlDestroyProtoHooks();
812         CtdlDestroyDeleteHooks();
813         CtdlDestroyXmsgHooks();
814         CtdlDestroyNetprocHooks();
815         CtdlDestroyUserHooks();
816         CtdlDestroyMessageHook();
817         CtdlDestroyCleanupHooks();
818         CtdlDestroyFixedOutputHooks();  
819         CtdlDestroySessionHooks();
820         CtdlDestroyServiceHook();
821         CtdlDestroyRoomHooks();
822         CtdlDestroyDirectoryServiceFuncs();
823         #ifdef HAVE_BACKTRACE
824         eCrash_Uninit();
825         #endif
826 }
827
828
829
830 /*
831  * Terminate another session.
832  * (This could justifiably be moved out of sysdep.c because it
833  * no longer does anything that is system-dependent.)
834  */
835 void kill_session(int session_to_kill) {
836         struct CitContext *ptr;
837
838         begin_critical_section(S_SESSION_TABLE);
839         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
840                 if (ptr->cs_pid == session_to_kill) {
841                         ptr->kill_me = 1;
842                 }
843         }
844         end_critical_section(S_SESSION_TABLE);
845 }
846
847 pid_t current_child;
848 void graceful_shutdown(int signum) {
849         kill(current_child, signum);
850         unlink(file_pid_file);
851         exit(0);
852 }
853
854
855 /*
856  * Start running as a daemon.
857  */
858 void start_daemon(int unused) {
859         int status = 0;
860         pid_t child = 0;
861         FILE *fp;
862         int do_restart = 0;
863
864         current_child = 0;
865
866         /* Close stdin/stdout/stderr and replace them with /dev/null.
867          * We don't just call close() because we don't want these fd's
868          * to be reused for other files.
869          */
870         chdir(ctdl_run_dir);
871
872         child = fork();
873         if (child != 0) {
874                 exit(0);
875         }
876         
877         signal(SIGHUP, SIG_IGN);
878         signal(SIGINT, SIG_IGN);
879         signal(SIGQUIT, SIG_IGN);
880
881         setsid();
882         umask(0);
883         freopen("/dev/null", "r", stdin);
884         freopen("/dev/null", "w", stdout);
885         freopen("/dev/null", "w", stderr);
886
887         do {
888                 current_child = fork();
889
890                 signal(SIGTERM, graceful_shutdown);
891         
892                 if (current_child < 0) {
893                         perror("fork");
894                         exit(errno);
895                 }
896         
897                 else if (current_child == 0) {
898                         return; /* continue starting citadel. */
899                 }
900         
901                 else {
902                         fp = fopen(file_pid_file, "w");
903                         if (fp != NULL) {
904                                 fprintf(fp, ""F_PID_T"\n", getpid());
905                                 fclose(fp);
906                         }
907                         waitpid(current_child, &status, 0);
908                 }
909
910                 do_restart = 0;
911
912                 /* Did the main process exit with an actual exit code? */
913                 if (WIFEXITED(status)) {
914
915                         /* Exit code 0 means the watcher should exit */
916                         if (WEXITSTATUS(status) == 0) {
917                                 do_restart = 0;
918                         }
919
920                         /* Exit code 101-109 means the watcher should exit */
921                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
922                                 do_restart = 0;
923                         }
924
925                         /* Any other exit code means we should restart. */
926                         else {
927                                 do_restart = 1;
928                         }
929                 }
930
931                 /* Any other type of termination (signals, etc.) should also restart. */
932                 else {
933                         do_restart = 1;
934                 }
935
936         } while (do_restart);
937
938         unlink(file_pid_file);
939         exit(WEXITSTATUS(status));
940 }
941
942
943
944 /*
945  * Generic routine to convert a login name to a full name (gecos)
946  * Returns nonzero if a conversion took place
947  */
948 int convert_login(char NameToConvert[]) {
949         struct passwd *pw;
950         int a;
951
952         pw = getpwnam(NameToConvert);
953         if (pw == NULL) {
954                 return(0);
955         }
956         else {
957                 strcpy(NameToConvert, pw->pw_gecos);
958                 for (a=0; a<strlen(NameToConvert); ++a) {
959                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
960                 }
961                 return(1);
962         }
963 }
964
965 /*
966  * Purge all sessions which have the 'kill_me' flag set.
967  * This function has code to prevent it from running more than once every
968  * few seconds, because running it after every single unbind would waste a lot
969  * of CPU time and keep the context list locked too much.  To force it to run
970  * anyway, set "force" to nonzero.
971  */
972 void dead_session_purge(int force) {
973         struct CitContext *ptr, *ptr2;          /* general-purpose utility pointer */
974         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
975         
976         if (force == 0) {
977                 if ( (time(NULL) - last_purge) < 5 ) {
978                         return; /* Too soon, go away */
979                 }
980         }
981         time(&last_purge);
982
983         if (try_critical_section(S_SESSION_TABLE))
984                 return;
985                 
986         ptr = ContextList;
987         while (ptr) {
988                 ptr2 = ptr;
989                 ptr = ptr->next;
990                 
991                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
992                         /* Remove the session from the active list */
993                         if (ptr2->prev) {
994                                 ptr2->prev->next = ptr2->next;
995                         }
996                         else {
997                                 ContextList = ptr2->next;
998                         }
999                         if (ptr2->next) {
1000                                 ptr2->next->prev = ptr2->prev;
1001                         }
1002
1003                         --num_sessions;
1004                         /* And put it on our to-be-destroyed list */
1005                         ptr2->next = rem;
1006                         rem = ptr2;
1007                 }
1008         }
1009         end_critical_section(S_SESSION_TABLE);
1010
1011         /* Now that we no longer have the session list locked, we can take
1012          * our time and destroy any sessions on the to-be-killed list, which
1013          * is allocated privately on this thread's stack.
1014          */
1015         while (rem != NULL) {
1016                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1017                 RemoveContext(rem);
1018                 ptr = rem;
1019                 rem = rem->next;
1020                 free(ptr);
1021         }
1022 }
1023
1024
1025
1026
1027
1028 /*
1029  * masterCC is the context we use when not attached to a session.  This
1030  * function initializes it.
1031  */
1032 void InitializeMasterCC(void) {
1033         memset(&masterCC, 0, sizeof(struct CitContext));
1034         masterCC.internal_pgm = 1;
1035         masterCC.cs_pid = 0;
1036 }
1037
1038
1039
1040
1041
1042
1043 /*
1044  * Bind a thread to a context.  (It's inline merely to speed things up.)
1045  */
1046 INLINE void become_session(struct CitContext *which_con) {
1047         citthread_setspecific(MyConKey, (void *)which_con );
1048 }
1049
1050
1051
1052 /* 
1053  * This loop just keeps going and going and going...
1054  */
1055 /*
1056  * FIXME:
1057  * This current implimentation of worker_thread creates a bottle neck in several situations
1058  * The first thing to remember is that a single thread can handle more than one connection at a time.
1059  * More threads mean less memory for the system to run in.
1060  * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
1061  * something to happen anywhere.
1062  * This current implimentation requires worker threads to wait in other locations, after it has
1063  * been committed to a single connection which is very wasteful.
1064  * As an extreme case consider this:
1065  * A slow client connects and this slow client sends only one character each second.
1066  * With this current implimentation a single worker thread is dispatched to handle that connection
1067  * until such times as the client timeout expires, an error occurs on the socket or the client
1068  * completes its transmission.
1069  * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
1070  * second interval between chars.
1071  *
1072  * It is my intention to re-write this code and the associated client_getln, client_read functions
1073  * to allow any thread to read data on behalf of any connection (context).
1074  * To do this I intend to have this main loop read chars into a buffer stored in the context.
1075  * Once the correct criteria for a full buffer is met then we will dispatch a thread to 
1076  * process it.
1077  * This worker thread loop also needs to be able to handle binary data.
1078  */
1079  
1080 void *worker_thread(void *arg) {
1081         int i;
1082         int highest;
1083         struct CitContext *ptr;
1084         struct CitContext *bind_me = NULL;
1085         fd_set readfds;
1086         int retval = 0;
1087         struct CitContext *con= NULL;   /* Temporary context pointer */
1088         struct ServiceFunctionHook *serviceptr;
1089         int ssock;                      /* Descriptor for client socket */
1090         struct timeval tv;
1091         int force_purge = 0;
1092         int m;
1093         
1094
1095         while (!CtdlThreadCheckStop()) {
1096
1097                 /* make doubly sure we're not holding any stale db handles
1098                  * which might cause a deadlock.
1099                  */
1100                 cdb_check_handles();
1101 do_select:      force_purge = 0;
1102                 bind_me = NULL;         /* Which session shall we handle? */
1103
1104                 /* Initialize the fdset. */
1105                 FD_ZERO(&readfds);
1106                 highest = 0;
1107
1108                 begin_critical_section(S_SESSION_TABLE);
1109                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1110                         if (ptr->state == CON_IDLE) {
1111                                 FD_SET(ptr->client_socket, &readfds);
1112                                 if (ptr->client_socket > highest)
1113                                         highest = ptr->client_socket;
1114                         }
1115                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1116                                 bind_me = ptr;
1117                                 ptr->state = CON_EXECUTING;
1118                         }
1119                 }
1120                 end_critical_section(S_SESSION_TABLE);
1121
1122                 if (bind_me) {
1123                         goto SKIP_SELECT;
1124                 }
1125
1126                 /* If we got this far, it means that there are no sessions
1127                  * which a previous thread marked for attention, so we go
1128                  * ahead and get ready to select().
1129                  */
1130
1131                 /* First, add the various master sockets to the fdset. */
1132                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1133                 serviceptr = serviceptr->next ) {
1134                         m = serviceptr->msock;
1135                         FD_SET(m, &readfds);
1136                         if (m > highest) {
1137                                 highest = m;
1138                         }
1139                 }
1140
1141                 if (!CtdlThreadCheckStop()) {
1142                         tv.tv_sec = 1;          /* wake up every second if no input */
1143                         tv.tv_usec = 0;
1144                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1145                 }
1146
1147                 if (CtdlThreadCheckStop()) return(NULL);
1148
1149                 /* Now figure out who made this select() unblock.
1150                  * First, check for an error or exit condition.
1151                  */
1152                 if (retval < 0) {
1153                         if (errno == EBADF) {
1154                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1155                                         strerror(errno));
1156                                 goto do_select;
1157                         }
1158                         if (errno != EINTR) {
1159                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1160                                 CtdlThreadStopAll();
1161                         } else if (!CtdlThreadCheckStop()) {
1162                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select.\n");
1163                                 goto do_select;
1164                         }
1165                 }
1166                 else if(retval == 0) {
1167                         goto SKIP_SELECT;
1168                 }
1169                 /* Next, check to see if it's a new client connecting
1170                  * on a master socket.
1171                  */
1172                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1173                      serviceptr = serviceptr->next ) {
1174
1175                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1176                                 ssock = accept(serviceptr->msock, NULL, 0);
1177                                 if (ssock >= 0) {
1178                                         CtdlLogPrintf(CTDL_DEBUG,
1179                                                 "New client socket %d\n",
1180                                                 ssock);
1181
1182                                         /* The master socket is non-blocking but the client
1183                                          * sockets need to be blocking, otherwise certain
1184                                          * operations barf on FreeBSD.  Not a fatal error.
1185                                          */
1186                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1187                                                 CtdlLogPrintf(CTDL_EMERG,
1188                                                         "citserver: Can't set socket to blocking: %s\n",
1189                                                         strerror(errno));
1190                                         }
1191
1192                                         /* New context will be created already
1193                                          * set up in the CON_EXECUTING state.
1194                                          */
1195                                         con = CreateNewContext();
1196
1197                                         /* Assign our new socket number to it. */
1198                                         con->client_socket = ssock;
1199                                         con->h_command_function =
1200                                                 serviceptr->h_command_function;
1201                                         con->h_async_function =
1202                                                 serviceptr->h_async_function;
1203                                         con->ServiceName =
1204                                                 serviceptr->ServiceName;
1205                                         
1206                                         /* Determine whether it's a local socket */
1207                                         if (serviceptr->sockpath != NULL)
1208                                                 con->is_local_socket = 1;
1209         
1210                                         /* Set the SO_REUSEADDR socket option */
1211                                         i = 1;
1212                                         setsockopt(ssock, SOL_SOCKET,
1213                                                 SO_REUSEADDR,
1214                                                 &i, sizeof(i));
1215
1216                                         become_session(con);
1217                                         begin_session(con);
1218                                         serviceptr->h_greeting_function();
1219                                         become_session(NULL);
1220                                         con->state = CON_IDLE;
1221                                         goto do_select;
1222                                 }
1223                         }
1224                 }
1225
1226                 /* It must be a client socket.  Find a context that has data
1227                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1228                  * active sockets other than our chosen one are marked as
1229                  * CON_READY so the next thread that comes around can just bind
1230                  * to one without having to select() again.
1231                  */
1232                 begin_critical_section(S_SESSION_TABLE);
1233                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1234                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1235                            && (ptr->state != CON_EXECUTING) ) {
1236                                 ptr->input_waiting = 1;
1237                                 if (!bind_me) {
1238                                         bind_me = ptr;  /* I choose you! */
1239                                         bind_me->state = CON_EXECUTING;
1240                                 }
1241                                 else {
1242                                         ptr->state = CON_READY;
1243                                 }
1244                         }
1245                 }
1246                 end_critical_section(S_SESSION_TABLE);
1247
1248 SKIP_SELECT:
1249                 /* We're bound to a session */
1250                 if (bind_me != NULL) {
1251                         become_session(bind_me);
1252
1253                         /* If the client has sent a command, execute it. */
1254                         if (CC->input_waiting) {
1255                                 CC->h_command_function();
1256                                 CC->input_waiting = 0;
1257                         }
1258
1259                         /* If there are asynchronous messages waiting and the
1260                          * client supports it, do those now */
1261                         if ((CC->is_async) && (CC->async_waiting)
1262                            && (CC->h_async_function != NULL)) {
1263                                 CC->h_async_function();
1264                                 CC->async_waiting = 0;
1265                         }
1266                         
1267                         force_purge = CC->kill_me;
1268                         become_session(NULL);
1269                         bind_me->state = CON_IDLE;
1270                 }
1271
1272                 dead_session_purge(force_purge);
1273                 do_housekeeping();
1274         }
1275         /* If control reaches this point, the server is shutting down */        
1276         return(NULL);
1277 }
1278
1279
1280
1281
1282 /*
1283  * SyslogFacility()
1284  * Translate text facility name to syslog.h defined value.
1285  */
1286 int SyslogFacility(char *name)
1287 {
1288         int i;
1289         struct
1290         {
1291                 int facility;
1292                 char *name;
1293         }   facTbl[] =
1294         {
1295                 {   LOG_KERN,   "kern"          },
1296                 {   LOG_USER,   "user"          },
1297                 {   LOG_MAIL,   "mail"          },
1298                 {   LOG_DAEMON, "daemon"        },
1299                 {   LOG_AUTH,   "auth"          },
1300                 {   LOG_SYSLOG, "syslog"        },
1301                 {   LOG_LPR,    "lpr"           },
1302                 {   LOG_NEWS,   "news"          },
1303                 {   LOG_UUCP,   "uucp"          },
1304                 {   LOG_LOCAL0, "local0"        },
1305                 {   LOG_LOCAL1, "local1"        },
1306                 {   LOG_LOCAL2, "local2"        },
1307                 {   LOG_LOCAL3, "local3"        },
1308                 {   LOG_LOCAL4, "local4"        },
1309                 {   LOG_LOCAL5, "local5"        },
1310                 {   LOG_LOCAL6, "local6"        },
1311                 {   LOG_LOCAL7, "local7"        },
1312                 {   0,            NULL          }
1313         };
1314         for(i = 0; facTbl[i].name != NULL; i++) {
1315                 if(!strcasecmp(name, facTbl[i].name))
1316                         return facTbl[i].facility;
1317         }
1318         enable_syslog = 0;
1319         return LOG_DAEMON;
1320 }
1321
1322
1323 /********** MEM CHEQQER ***********/
1324
1325 #ifdef DEBUG_MEMORY_LEAKS
1326
1327 #undef malloc
1328 #undef realloc
1329 #undef strdup
1330 #undef free
1331
1332 void *tracked_malloc(size_t size, char *file, int line) {
1333         struct igheap *thisheap;
1334         void *block;
1335
1336         block = malloc(size);
1337         if (block == NULL) return(block);
1338
1339         thisheap = malloc(sizeof(struct igheap));
1340         if (thisheap == NULL) {
1341                 free(block);
1342                 return(NULL);
1343         }
1344
1345         thisheap->block = block;
1346         strcpy(thisheap->file, file);
1347         thisheap->line = line;
1348         
1349         begin_critical_section(S_DEBUGMEMLEAKS);
1350         thisheap->next = igheap;
1351         igheap = thisheap;
1352         end_critical_section(S_DEBUGMEMLEAKS);
1353
1354         return(block);
1355 }
1356
1357
1358 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1359         struct igheap *thisheap;
1360         void *block;
1361
1362         block = realloc(ptr, size);
1363         if (block == NULL) return(block);
1364
1365         thisheap = malloc(sizeof(struct igheap));
1366         if (thisheap == NULL) {
1367                 free(block);
1368                 return(NULL);
1369         }
1370
1371         thisheap->block = block;
1372         strcpy(thisheap->file, file);
1373         thisheap->line = line;
1374         
1375         begin_critical_section(S_DEBUGMEMLEAKS);
1376         thisheap->next = igheap;
1377         igheap = thisheap;
1378         end_critical_section(S_DEBUGMEMLEAKS);
1379
1380         return(block);
1381 }
1382
1383
1384
1385 void tracked_free(void *ptr) {
1386         struct igheap *thisheap;
1387         struct igheap *trash;
1388
1389         free(ptr);
1390
1391         if (igheap == NULL) return;
1392         begin_critical_section(S_DEBUGMEMLEAKS);
1393         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1394                 if (thisheap->next != NULL) {
1395                         if (thisheap->next->block == ptr) {
1396                                 trash = thisheap->next;
1397                                 thisheap->next = thisheap->next->next;
1398                                 free(trash);
1399                         }
1400                 }
1401         }
1402         if (igheap->block == ptr) {
1403                 trash = igheap;
1404                 igheap = igheap->next;
1405                 free(trash);
1406         }
1407         end_critical_section(S_DEBUGMEMLEAKS);
1408 }
1409
1410 char *tracked_strdup(const char *s, char *file, int line) {
1411         char *ptr;
1412
1413         if (s == NULL) return(NULL);
1414         ptr = tracked_malloc(strlen(s) + 1, file, line);
1415         if (ptr == NULL) return(NULL);
1416         strncpy(ptr, s, strlen(s));
1417         return(ptr);
1418 }
1419
1420 void dump_heap(void) {
1421         struct igheap *thisheap;
1422
1423         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1424                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1425                         thisheap->file, thisheap->line);
1426         }
1427 }
1428
1429 #endif /*  DEBUG_MEMORY_LEAKS */