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