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