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