Updated the copyright declaration in several modules, removing any language which...
[citadel.git] / citadel / sysdep.c
1 /*
2  * Citadel "system dependent" stuff.
3  *
4  * Here's where we (hopefully) have most parts of the Citadel server that
5  * would need to be altered to run the server in a non-POSIX environment.
6  * 
7  * If we ever port to a different platform and either have multiple
8  * variants of this file or simply load it up with #ifdefs.
9  *
10  * Copyright (c) 1987-2011 by the citadel.org team
11  *
12  * This program is open source software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License, version 3.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  */
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <ctype.h>
27 #include <signal.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31 #include <sys/socket.h>
32 #include <syslog.h>
33 #include <sys/syslog.h>
34
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #include <limits.h>
47 #include <sys/resource.h>
48 #include <netinet/in.h>
49 #include <netinet/tcp.h>
50 #include <arpa/inet.h>
51 #include <netdb.h>
52 #include <sys/un.h>
53 #include <string.h>
54 #include <pwd.h>
55 #include <errno.h>
56 #include <stdarg.h>
57 #include <grp.h>
58 #define SHOW_ME_VAPPEND_PRINTF
59 #include <libcitadel.h>
60 #include "citadel.h"
61 #include "server.h"
62 #include "sysdep_decls.h"
63 #include "citserver.h"
64 #include "support.h"
65 #include "config.h"
66 #include "database.h"
67 #include "housekeeping.h"
68 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
69 #include "ecrash.h"
70 #include "context.h"
71
72 #ifdef HAVE_SYS_SELECT_H
73 #include <sys/select.h>
74 #endif
75
76 #ifndef HAVE_SNPRINTF
77 #include "snprintf.h"
78 #endif
79
80 #include "ctdl_module.h"
81 #include "threads.h"
82 #include "user_ops.h"
83 #include "control.h"
84
85
86 /*
87  * Signal handler to shut down the server.
88  */
89
90 volatile int exit_signal = 0;
91 volatile int shutdown_and_halt = 0;
92 volatile int restart_server = 0;
93 volatile int running_as_daemon = 0;
94
95 static RETSIGTYPE signal_cleanup(int signum) {
96         syslog(LOG_DEBUG, "Caught signal %d; shutting down.", signum);
97         exit_signal = signum;
98         server_shutting_down = 1;
99 }
100
101 static RETSIGTYPE signal_exit(int signum) {
102         exit(1);
103 }
104
105
106
107 /*
108  * Some initialization stuff...
109  */
110 void init_sysdep(void) {
111         sigset_t set;
112
113         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
114 #ifdef FD_SETSIZE
115 #ifdef RLIMIT_NOFILE
116         struct rlimit rl;
117         getrlimit(RLIMIT_NOFILE, &rl);
118         rl.rlim_cur = FD_SETSIZE;
119         rl.rlim_max = FD_SETSIZE;
120         setrlimit(RLIMIT_NOFILE, &rl);
121 #endif
122 #endif
123
124         /* If we've got OpenSSL, we're going to use it. */
125 #ifdef HAVE_OPENSSL
126         init_ssl();
127 #endif
128
129         /*
130          * Set up a place to put thread-specific data.
131          * We only need a single pointer per thread - it points to the
132          * CitContext structure (in the ContextList linked list) of the
133          * session to which the calling thread is currently bound.
134          */
135         if (pthread_key_create(&MyConKey, NULL) != 0) {
136                 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
137         }
138
139         /*
140          * Interript, hangup, and terminate signals should cause the server
141          * to gracefully clean up and shut down.
142          */
143         sigemptyset(&set);
144         sigaddset(&set, SIGINT);
145         sigaddset(&set, SIGHUP);
146         sigaddset(&set, SIGTERM);
147         sigprocmask(SIG_UNBLOCK, &set, NULL);
148
149         signal(SIGINT, signal_cleanup);
150         signal(SIGHUP, signal_cleanup);
151         signal(SIGTERM, signal_cleanup);
152         signal(SIGUSR2, signal_exit);
153
154         /*
155          * Do not shut down the server on broken pipe signals, otherwise the
156          * whole Citadel service would come down whenever a single client
157          * socket breaks.
158          */
159         signal(SIGPIPE, SIG_IGN);
160 }
161
162
163 /* 
164  * This is a generic function to set up a master socket for listening on
165  * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
166  *
167  * ip_addr      IP address to bind
168  * port_number  port number to bind
169  * queue_len    number of incoming connections to allow in the queue
170  */
171 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
172 {
173         struct protoent *p;
174         struct sockaddr_in6 sin6;
175         struct sockaddr_in sin4;
176         int s, i, b;
177         int ip_version = 6;
178
179         memset(&sin6, 0, sizeof(sin6));
180         memset(&sin4, 0, sizeof(sin4));
181         sin6.sin6_family = AF_INET6;
182         sin4.sin_family = AF_INET;
183
184         if (    (ip_addr == NULL)                                                       /* any IPv6 */
185                 || (IsEmptyStr(ip_addr))
186                 || (!strcmp(ip_addr, "*"))
187         ) {
188                 ip_version = 6;
189                 sin6.sin6_addr = in6addr_any;
190         }
191         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
192         {
193                 ip_version = 4;
194                 sin4.sin_addr.s_addr = INADDR_ANY;
195         }
196         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
197         {
198                 ip_version = 4;
199                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
200                         snprintf(errormessage, SIZ,
201                                  "Error binding to [%s] : %s", ip_addr, strerror(errno)
202                         );
203                         syslog(LOG_ALERT, "%s", errormessage);
204                         return (-1);
205                 }
206         }
207         else                                                                            /* specific IPv6 */
208         {
209                 ip_version = 6;
210                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
211                         snprintf(errormessage, SIZ,
212                                  "Error binding to [%s] : %s", ip_addr, strerror(errno)
213                         );
214                         syslog(LOG_ALERT, "%s", errormessage);
215                         return (-1);
216                 }
217         }
218
219         if (port_number == 0) {
220                 snprintf(errormessage, SIZ, "Can't start: no port number specified.");
221                 syslog(LOG_ALERT, "%s", errormessage);
222                 return (-1);
223         }
224         sin6.sin6_port = htons((u_short) port_number);
225         sin4.sin_port = htons((u_short) port_number);
226
227         p = getprotobyname("tcp");
228
229         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
230         if (s < 0) {
231                 snprintf(errormessage, SIZ,
232                          "Can't create a listening socket: %s", strerror(errno)
233                 );
234                 syslog(LOG_ALERT, "%s", errormessage);
235                 return (-1);
236         }
237         /* Set some socket options that make sense. */
238         i = 1;
239         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
240
241         if (ip_version == 6) {
242                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
243         }
244         else {
245                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
246         }
247
248         if (b < 0) {
249                 snprintf(errormessage, SIZ,
250                          "Can't bind: %s", strerror(errno)
251                 );
252                 syslog(LOG_ALERT, "%s", errormessage);
253                 return (-1);
254         }
255
256         fcntl(s, F_SETFL, O_NONBLOCK);
257
258         if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
259                 snprintf(errormessage, SIZ,
260                          "Can't listen: %s", strerror(errno)
261                 );
262                 syslog(LOG_ALERT, "%s", errormessage);
263                 return (-1);
264         }
265         return (s);
266 }
267
268
269
270
271
272 /*
273  * Create a Unix domain socket and listen on it
274  */
275 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
276 {
277         struct sockaddr_un addr;
278         int s;
279         int i;
280         int actual_queue_len;
281 #ifdef HAVE_STRUCT_UCRED
282         int passcred = 1;
283 #endif
284
285         actual_queue_len = queue_len;
286         if (actual_queue_len < 5) actual_queue_len = 5;
287
288         i = unlink(sockpath);
289         if ((i != 0) && (errno != ENOENT)) {
290                 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
291                         sockpath, strerror(errno)
292                 );
293                 syslog(LOG_EMERG, "%s", errormessage);
294                 return(-1);
295         }
296
297         memset(&addr, 0, sizeof(addr));
298         addr.sun_family = AF_UNIX;
299         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
300
301         s = socket(AF_UNIX, SOCK_STREAM, 0);
302         if (s < 0) {
303                 snprintf(errormessage, SIZ, 
304                          "citserver: Can't create a socket: %s",
305                          strerror(errno));
306                 syslog(LOG_EMERG, "%s", errormessage);
307                 return(-1);
308         }
309
310         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
311                 snprintf(errormessage, SIZ, 
312                          "citserver: Can't bind: %s",
313                          strerror(errno));
314                 syslog(LOG_EMERG, "%s", errormessage);
315                 return(-1);
316         }
317
318         /* set to nonblock - we need this for some obscure situations */
319         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
320                 snprintf(errormessage, SIZ, 
321                          "citserver: Can't set socket to non-blocking: %s",
322                          strerror(errno));
323                 syslog(LOG_EMERG, "%s", errormessage);
324                 close(s);
325                 return(-1);
326         }
327
328         if (listen(s, actual_queue_len) < 0) {
329                 snprintf(errormessage, SIZ, 
330                          "citserver: Can't listen: %s",
331                          strerror(errno));
332                 syslog(LOG_EMERG, "%s", errormessage);
333                 return(-1);
334         }
335
336 #ifdef HAVE_STRUCT_UCRED
337         setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
338 #endif
339
340         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
341         return(s);
342 }
343
344
345
346 /*
347  * The following functions implement output buffering on operating systems which
348  * support it (such as Linux and various BSD flavors).
349  */
350 #ifndef HAVE_DARWIN
351 #ifdef TCP_CORK
352 #       define HAVE_TCP_BUFFERING
353 #else
354 #       ifdef TCP_NOPUSH
355 #               define HAVE_TCP_BUFFERING
356 #               define TCP_CORK TCP_NOPUSH
357 #       endif
358 #endif /* TCP_CORK */
359 #endif /* HAVE_DARWIN */
360
361 static unsigned on = 1, off = 0;
362
363 void buffer_output(void) {
364 #ifdef HAVE_TCP_BUFFERING
365 #ifdef HAVE_OPENSSL
366         if (!CC->redirect_ssl)
367 #endif
368                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
369 #endif
370 }
371
372 void unbuffer_output(void) {
373 #ifdef HAVE_TCP_BUFFERING
374 #ifdef HAVE_OPENSSL
375         if (!CC->redirect_ssl)
376 #endif
377                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
378 #endif
379 }
380
381 void flush_output(void) {
382 #ifdef HAVE_TCP_BUFFERING
383         struct CitContext *CCC = CC;
384         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
385         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
386 #endif
387 }
388
389 /*
390 static void flush_client_inbuf(void)
391 {
392         CitContext *CCC=CC;
393
394         FlushStrBuf(CCC->ReadBuf);
395         CCC->RecvBuf->ReadWritePointer = NULL;
396
397 }
398 */
399
400
401 /*
402  * client_close()       ...     close the client socket
403  */
404 void client_close(void) {
405         CitContext *CCC = CC;
406
407         if (!CCC) return;
408         if (CCC->client_socket <= 0) return;
409         syslog(LOG_DEBUG, "Closing socket %d", CCC->client_socket);
410
411         close(CCC->client_socket);
412         CCC->client_socket = -1 ;
413 }
414
415
416
417
418 /*
419  * client_write()   ...    Send binary data to the client.
420  */
421 int client_write(const char *buf, int nbytes)
422 {
423         int bytes_written = 0;
424         int retval;
425 #ifndef HAVE_TCP_BUFFERING
426         int old_buffer_len = 0;
427 #endif
428         fd_set wset;
429         CitContext *Ctx;
430         int fdflags;
431
432         if (nbytes < 1) return(0);
433
434         Ctx = CC;
435
436 #ifdef BIGBAD_IODBG
437         {
438                 int rv = 0;
439                 char fn [SIZ];
440                 FILE *fd;
441                 
442                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
443                 
444                 fd = fopen(fn, "a+");
445                 if (fd)
446                 {
447                     fprintf(fd, "Sending: BufSize: %d BufContent: [",
448                             nbytes);
449                     rv = fwrite(buf, nbytes, 1, fd);
450                     fprintf(fd, "]\n");
451                     fclose(fd);
452                 }
453         }
454 #endif
455 //      flush_client_inbuf();
456         if (Ctx->redirect_buffer != NULL) {
457                 StrBufAppendBufPlain(Ctx->redirect_buffer,
458                                      buf, nbytes, 0);
459                 return 0;
460         }
461
462 #ifdef HAVE_OPENSSL
463         if (Ctx->redirect_ssl) {
464                 client_write_ssl(buf, nbytes);
465                 return 0;
466         }
467 #endif
468         if (Ctx->client_socket == -1) return -1;
469
470         fdflags = fcntl(Ctx->client_socket, F_GETFL);
471
472         while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
473                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
474                         FD_ZERO(&wset);
475                         FD_SET(Ctx->client_socket, &wset);
476                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
477                                 if (errno == EINTR)
478                                 {
479                                         syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.",
480                                                 nbytes-bytes_written
481                                         );
482                                         if (server_shutting_down) {
483                                                 CC->kill_me = KILLME_SELECT_INTERRUPTED;
484                                                 return (-1);
485                                         } else {
486                                                 /* can't trust fd's and stuff so we need to re-create them */
487                                                 continue;
488                                         }
489                                 } else {
490                                         syslog(LOG_ERR,
491                                                 "client_write(%d bytes) select failed: %s (%d)",
492                                                 nbytes - bytes_written,
493                                                 strerror(errno), errno
494                                         );
495                                         cit_backtrace();
496                                         client_close();
497                                         Ctx->kill_me = KILLME_SELECT_FAILED;
498                                         return -1;
499                                 }
500                         }
501                 }
502
503                 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
504                 if (retval < 1) {
505                         syslog(LOG_ERR,
506                                 "client_write(%d bytes) failed: %s (%d)",
507                                 nbytes - bytes_written,
508                                 strerror(errno), errno
509                         );
510                         cit_backtrace();
511                         client_close();
512                         Ctx->kill_me = KILLME_WRITE_FAILED;
513                         return -1;
514                 }
515                 bytes_written = bytes_written + retval;
516         }
517         return 0;
518 }
519
520 void cputbuf(const StrBuf *Buf) {   
521         client_write(ChrPtr(Buf), StrLength(Buf)); 
522 }   
523
524
525 /*
526  * cprintf()    Send formatted printable data to the client.
527  *              Implemented in terms of client_write() so it's technically not sysdep...
528  */
529 void cprintf(const char *format, ...) {   
530         va_list arg_ptr;   
531         char buf[1024];
532    
533         va_start(arg_ptr, format);   
534         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
535                 buf[sizeof buf - 2] = '\n';
536         client_write(buf, strlen(buf)); 
537         va_end(arg_ptr);
538 }   
539
540
541 /*
542  * Read data from the client socket.
543  *
544  * sock         socket fd to read from
545  * buf          buffer to read into 
546  * bytes        number of bytes to read
547  * timeout      Number of seconds to wait before timing out
548  *
549  * Possible return values:
550  *      1       Requested number of bytes has been read.
551  *      0       Request timed out.
552  *      -1      Connection is broken, or other error.
553  */
554 int client_read_blob(StrBuf *Target, int bytes, int timeout)
555 {
556         CitContext *CCC=CC;
557         const char *Error;
558         int retval = 0;
559
560 #ifdef HAVE_OPENSSL
561         if (CCC->redirect_ssl) {
562 #ifdef BIGBAD_IODBG
563                 int rv = 0;
564                 char fn [SIZ];
565                 FILE *fd;
566                 
567                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
568                         
569                 fd = fopen(fn, "a+");
570                 fprintf(fd, "Reading BLOB: BufSize: %d ",
571                         bytes);
572                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
573                 fprintf(fd, "]\n");
574                 
575                         
576                 fclose(fd);
577 #endif
578                 retval = client_read_sslblob(Target, bytes, timeout);
579                 if (retval < 0) {
580                         syslog(LOG_CRIT, "client_read_blob() failed");
581                 }
582 #ifdef BIGBAD_IODBG
583                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
584                 
585                 fd = fopen(fn, "a+");
586                 fprintf(fd, "Read: %d BufContent: [",
587                         StrLength(Target));
588                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
589                 fprintf(fd, "]\n");
590                 
591                 
592                 fclose(fd);
593 #endif
594         }
595         else 
596 #endif
597         {
598 #ifdef BIGBAD_IODBG
599                 int rv = 0;
600                 char fn [SIZ];
601                 FILE *fd;
602                 
603                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
604                         
605                 fd = fopen(fn, "a+");
606                 fprintf(fd, "Reading BLOB: BufSize: %d ",
607                         bytes);
608                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
609                 fprintf(fd, "]\n");
610                 
611                         
612                 fclose(fd);
613 #endif
614                 retval = StrBufReadBLOBBuffered(Target, 
615                                                 CCC->RecvBuf.Buf,
616                                                 &CCC->RecvBuf.ReadWritePointer,
617                                                 &CCC->client_socket,
618                                                 1, 
619                                                 bytes,
620                                                 O_TERM,
621                                                 &Error);
622                 if (retval < 0) {
623                         syslog(LOG_CRIT, "client_read_blob() failed: %s", Error);
624                         client_close();
625                         return retval;
626                 }
627 #ifdef BIGBAD_IODBG
628                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
629                 
630                 fd = fopen(fn, "a+");
631                 fprintf(fd, "Read: %d BufContent: [",
632                         StrLength(Target));
633                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
634                 fprintf(fd, "]\n");
635                 fclose(fd);
636 #endif
637         }
638         return retval;
639 }
640
641
642 /*
643  * to make client_read_random_blob() more efficient, increase buffer size.
644  * just use in greeting function, else your buffer may be flushed
645  */
646 void client_set_inbound_buf(long N)
647 {
648         CitContext *CCC=CC;
649         FlushStrBuf(CCC->RecvBuf.Buf);
650         ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
651 }
652
653 int client_read_random_blob(StrBuf *Target, int timeout)
654 {
655         CitContext *CCC=CC;
656         int rc;
657
658         rc =  client_read_blob(Target, 1, timeout);
659         if (rc > 0)
660         {
661                 long len;
662                 const char *pch;
663                 
664                 len = StrLength(CCC->RecvBuf.Buf);
665                 pch = ChrPtr(CCC->RecvBuf.Buf);
666
667                 if (len > 0)
668                 {
669                         if (CCC->RecvBuf.ReadWritePointer != NULL) {
670                                 len -= CCC->RecvBuf.ReadWritePointer - pch;
671                                 pch = CCC->RecvBuf.ReadWritePointer;
672                         }
673                         StrBufAppendBufPlain(Target, pch, len, 0);
674                         FlushStrBuf(CCC->RecvBuf.Buf);
675                         CCC->RecvBuf.ReadWritePointer = NULL;
676 #ifdef BIGBAD_IODBG
677                         {
678                                 int rv = 0;
679                                 char fn [SIZ];
680                                 FILE *fd;
681                         
682                                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
683                         
684                                 fd = fopen(fn, "a+");
685                                 fprintf(fd, "Read: BufSize: %d BufContent: [",
686                                         StrLength(Target));
687                                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
688                                 fprintf(fd, "]\n");
689                         
690                         
691                                 fclose(fd);
692                         }
693 #endif
694         
695                         return StrLength(Target);
696                 }
697                 return rc;
698         }
699         else
700                 return rc;
701 }
702
703 int client_read_to(char *buf, int bytes, int timeout)
704 {
705         CitContext *CCC=CC;
706         int rc;
707
708         rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
709         if (rc < 0)
710         {
711                 *buf = '\0';
712                 return rc;
713         }
714         else
715         {
716                 memcpy(buf, 
717                        ChrPtr(CCC->MigrateBuf),
718                        StrLength(CCC->MigrateBuf) + 1);
719                 FlushStrBuf(CCC->MigrateBuf);
720                 return rc;
721         }
722 }
723
724
725 int HaveMoreLinesWaiting(CitContext *CCC)
726 {
727         if ((CCC->kill_me != 0) ||
728             ( (CCC->RecvBuf.ReadWritePointer == NULL) && 
729               (StrLength(CCC->RecvBuf.Buf) == 0) && 
730               (CCC->client_socket != -1)) )
731                 return 0;
732         else
733                 return 1;
734 }
735
736
737 /*
738  * Read data from the client socket with default timeout.
739  * (This is implemented in terms of client_read_to() and could be
740  * justifiably moved out of sysdep.c)
741  */
742 INLINE int client_read(char *buf, int bytes)
743 {
744         return(client_read_to(buf, bytes, config.c_sleeping));
745 }
746
747 int CtdlClientGetLine(StrBuf *Target)
748 {
749         CitContext *CCC=CC;
750         const char *Error;
751         int rc;
752
753         FlushStrBuf(Target);
754 #ifdef HAVE_OPENSSL
755         if (CCC->redirect_ssl) {
756 #ifdef BIGBAD_IODBG
757                 char fn [SIZ];
758                 FILE *fd;
759                 int len = 0;
760                 int rlen = 0;
761                 int  nlen = 0;
762                 int nrlen = 0;
763                 const char *pch;
764
765                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
766
767                 fd = fopen(fn, "a+");
768                 pch = ChrPtr(CCC->RecvBuf.Buf);
769                 len = StrLength(CCC->RecvBuf.Buf);
770                 if (CCC->RecvBuf.ReadWritePointer != NULL)
771                         rlen = CCC->RecvBuf.ReadWritePointer - pch;
772                 else
773                         rlen = 0;
774
775 /*              fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
776                         len, rlen, pch);
777 */
778                 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
779                         len, rlen);
780 #endif
781                 rc = client_readline_sslbuffer(Target,
782                                                CCC->RecvBuf.Buf,
783                                                &CCC->RecvBuf.ReadWritePointer,
784                                                1);
785 #ifdef BIGBAD_IODBG
786                 pch = ChrPtr(CCC->RecvBuf.Buf);
787                 nlen = StrLength(CCC->RecvBuf.Buf);
788                 if (CCC->RecvBuf.ReadWritePointer != NULL)
789                         nrlen = CCC->RecvBuf.ReadWritePointer - pch;
790                 else
791                         nrlen = 0;
792 /*
793                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
794                         len, nlen, rlen, nrlen, pch);
795 */
796                 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
797                         len, nlen, rlen, nrlen);
798
799                 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
800                         StrLength(Target), ChrPtr(Target));
801                 fclose(fd);
802
803                 if (rc < 0) {
804                         syslog(LOG_CRIT, "CtdlClientGetLine() failed");
805                 }
806 #endif
807                 return rc;
808         }
809         else 
810 #endif
811         {
812 #ifdef BIGBAD_IODBG
813                 char fn [SIZ];
814                 FILE *fd;
815                 int len, rlen, nlen, nrlen;
816                 const char *pch;
817
818                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
819
820                 fd = fopen(fn, "a+");
821                 pch = ChrPtr(CCC->RecvBuf.Buf);
822                 len = StrLength(CCC->RecvBuf.Buf);
823                 if (CCC->RecvBuf.ReadWritePointer != NULL)
824                         rlen = CCC->RecvBuf.ReadWritePointer - pch;
825                 else
826                         rlen = 0;
827
828 /*              fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
829                         len, rlen, pch);
830 */
831                 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
832                         len, rlen);
833 #endif
834                 rc = StrBufTCP_read_buffered_line_fast(Target, 
835                                                        CCC->RecvBuf.Buf,
836                                                        &CCC->RecvBuf.ReadWritePointer,
837                                                        &CCC->client_socket,
838                                                        5,
839                                                        1,
840                                                        &Error);
841
842 #ifdef BIGBAD_IODBG
843                 pch = ChrPtr(CCC->RecvBuf.Buf);
844                 nlen = StrLength(CCC->RecvBuf.Buf);
845                 if (CCC->RecvBuf.ReadWritePointer != NULL)
846                         nrlen = CCC->RecvBuf.ReadWritePointer - pch;
847                 else
848                         nrlen = 0;
849 /*
850                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
851                         len, nlen, rlen, nrlen, pch);
852 */
853                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
854                         len, nlen, rlen, nrlen);
855
856                 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
857                         StrLength(Target), ChrPtr(Target));
858                 fclose(fd);
859
860                 if ((rc < 0) && (Error != NULL)) {
861                         syslog(LOG_CRIT, "CtdlClientGetLine() failed: %s", Error);
862                 }
863 #endif
864                 return rc;
865         }
866 }
867
868
869 /*
870  * client_getln()   ...   Get a LF-terminated line of text from the client.
871  * (This is implemented in terms of client_read() and could be
872  * justifiably moved out of sysdep.c)
873  */
874 int client_getln(char *buf, int bufsize)
875 {
876         int i, retval;
877         CitContext *CCC=CC;
878         const char *pCh;
879
880         retval = CtdlClientGetLine(CCC->MigrateBuf);
881         if (retval < 0)
882           return(retval >= 0);
883
884
885         i = StrLength(CCC->MigrateBuf);
886         pCh = ChrPtr(CCC->MigrateBuf);
887         /* Strip the trailing LF, and the trailing CR if present.
888          */
889         if (bufsize <= i)
890                 i = bufsize - 1;
891         while ( (i > 0)
892                 && ( (pCh[i - 1]==13)
893                      || ( pCh[i - 1]==10)) ) {
894                 i--;
895         }
896         memcpy(buf, pCh, i);
897         buf[i] = 0;
898
899         FlushStrBuf(CCC->MigrateBuf);
900         if (retval < 0) {
901                 safestrncpy(&buf[i], "000", bufsize - i);
902         }
903         return(retval >= 0);
904 }
905
906
907 /*
908  * Cleanup any contexts that are left lying around
909  */
910
911
912 void close_masters (void)
913 {
914         struct ServiceFunctionHook *serviceptr;
915         
916         /*
917          * close all protocol master sockets
918          */
919         for (serviceptr = ServiceHookTable; serviceptr != NULL;
920             serviceptr = serviceptr->next ) {
921
922                 if (serviceptr->tcp_port > 0)
923                 {
924                         syslog(LOG_INFO, "Closing %d listener on port %d\n",
925                                serviceptr->msock,
926                                serviceptr->tcp_port);
927                         serviceptr->tcp_port = 0;
928                 }
929                 
930                 if (serviceptr->sockpath != NULL)
931                         syslog(LOG_INFO, "Closing %d listener on '%s'\n",
932                                serviceptr->msock,
933                                serviceptr->sockpath);
934                 if (serviceptr->msock != -1)
935                         close(serviceptr->msock);
936                 /* If it's a Unix domain socket, remove the file. */
937                 if (serviceptr->sockpath != NULL) {
938                         unlink(serviceptr->sockpath);
939                         serviceptr->sockpath = NULL;
940                 }
941         }
942 }
943
944
945 /*
946  * The system-dependent part of master_cleanup() - close the master socket.
947  */
948 void sysdep_master_cleanup(void) {
949         
950         close_masters();
951         
952         context_cleanup();
953         
954 #ifdef HAVE_OPENSSL
955         destruct_ssl();
956 #endif
957         CtdlDestroyProtoHooks();
958         CtdlDestroyDeleteHooks();
959         CtdlDestroyXmsgHooks();
960         CtdlDestroyNetprocHooks();
961         CtdlDestroyUserHooks();
962         CtdlDestroyMessageHook();
963         CtdlDestroyCleanupHooks();
964         CtdlDestroyFixedOutputHooks();  
965         CtdlDestroySessionHooks();
966         CtdlDestroyServiceHook();
967         CtdlDestroyRoomHooks();
968         CtdlDestroySearchHooks();
969         CtdlDestroyDebugTable();
970         #ifdef HAVE_BACKTRACE
971 ///     eCrash_Uninit();
972         #endif
973 }
974
975
976
977 pid_t current_child;
978 void graceful_shutdown(int signum) {
979         kill(current_child, signum);
980         unlink(file_pid_file);
981         exit(0);
982 }
983
984 int nFireUps = 0;
985 int nFireUpsNonRestart = 0;
986 pid_t ForkedPid = 1;
987
988 /*
989  * Start running as a daemon.
990  */
991 void start_daemon(int unused) {
992         int status = 0;
993         pid_t child = 0;
994         FILE *fp;
995         int do_restart = 0;
996
997         current_child = 0;
998
999         /* Close stdin/stdout/stderr and replace them with /dev/null.
1000          * We don't just call close() because we don't want these fd's
1001          * to be reused for other files.
1002          */
1003         if (chdir(ctdl_run_dir) != 0)
1004                 syslog(LOG_EMERG, 
1005                               "unable to change into directory [%s]: %s", 
1006                               ctdl_run_dir, strerror(errno));
1007
1008         child = fork();
1009         if (child != 0) {
1010                 exit(0);
1011         }
1012         
1013         signal(SIGHUP, SIG_IGN);
1014         signal(SIGINT, SIG_IGN);
1015         signal(SIGQUIT, SIG_IGN);
1016
1017         setsid();
1018         umask(0);
1019         if ((freopen("/dev/null", "r", stdin) != stdin) || 
1020             (freopen("/dev/null", "w", stdout) != stdout) || 
1021             (freopen("/dev/null", "w", stderr) != stderr))
1022                 syslog(LOG_EMERG, 
1023                               "unable to reopen stdin/out/err %s", 
1024                               strerror(errno));
1025                 
1026
1027         do {
1028                 current_child = fork();
1029
1030                 signal(SIGTERM, graceful_shutdown);
1031         
1032                 if (current_child < 0) {
1033                         perror("fork");
1034                         exit(errno);
1035                 }
1036         
1037                 else if (current_child == 0) {
1038                         return; /* continue starting citadel. */
1039                 }
1040         
1041                 else {
1042                         fp = fopen(file_pid_file, "w");
1043                         if (fp != NULL) {
1044                                 fprintf(fp, ""F_PID_T"\n", getpid());
1045                                 fclose(fp);
1046                         }
1047                         waitpid(current_child, &status, 0);
1048                 }
1049
1050                 nFireUpsNonRestart = nFireUps;
1051                 
1052                 /* Exit code 0 means the watcher should exit */
1053                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1054                         do_restart = 0;
1055                 }
1056
1057                 /* Exit code 101-109 means the watcher should exit */
1058                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1059                         do_restart = 0;
1060                 }
1061
1062                 /* Any other exit code, or no exit code, means we should restart. */
1063                 else {
1064                         do_restart = 1;
1065                         nFireUps++;
1066                         ForkedPid = current_child;
1067                 }
1068
1069         } while (do_restart);
1070
1071         unlink(file_pid_file);
1072         exit(WEXITSTATUS(status));
1073 }
1074
1075
1076
1077 void checkcrash(void)
1078 {
1079         if (nFireUpsNonRestart != nFireUps)
1080         {
1081                 StrBuf *CrashMail;
1082
1083                 CrashMail = NewStrBuf();
1084                 syslog(LOG_ALERT, "Posting crash message\n");
1085                 StrBufPrintf(CrashMail, 
1086                         " \n"
1087                         " The Citadel server process (citserver) terminated unexpectedly."
1088                         "\n \n"
1089                         " This could be the result of a bug in the server program, or some external "
1090                         "factor.\n \n"
1091                         " You can obtain more information about this by enabling core dumps.\n \n"
1092                         " For more information, please see:\n \n"
1093                         " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1094                         "\n \n"
1095
1096                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
1097                         ,
1098                         ctdl_run_dir, ForkedPid);
1099                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1100                 FreeStrBuf(&CrashMail);
1101         }
1102 }
1103
1104
1105 /*
1106  * Generic routine to convert a login name to a full name (gecos)
1107  * Returns nonzero if a conversion took place
1108  */
1109 int convert_login(char NameToConvert[]) {
1110         struct passwd *pw;
1111         int a;
1112
1113         pw = getpwnam(NameToConvert);
1114         if (pw == NULL) {
1115                 return(0);
1116         }
1117         else {
1118                 strcpy(NameToConvert, pw->pw_gecos);
1119                 for (a=0; a<strlen(NameToConvert); ++a) {
1120                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1121                 }
1122                 return(1);
1123         }
1124 }
1125
1126
1127
1128 /* 
1129  * This loop just keeps going and going and going...
1130  */
1131 void *worker_thread(void *blah) {
1132         int highest;
1133         CitContext *ptr;
1134         CitContext *bind_me = NULL;
1135         fd_set readfds;
1136         int retval = 0;
1137         struct timeval tv;
1138         int force_purge = 0;
1139         struct ServiceFunctionHook *serviceptr;
1140         int ssock;                      /* Descriptor for client socket */
1141         CitContext *con = NULL;         /* Temporary context pointer */
1142         int i;
1143
1144         ++num_workers;
1145
1146         while (!server_shutting_down) {
1147
1148                 /* make doubly sure we're not holding any stale db handles
1149                  * which might cause a deadlock.
1150                  */
1151                 cdb_check_handles();
1152 do_select:      force_purge = 0;
1153                 bind_me = NULL;         /* Which session shall we handle? */
1154
1155                 /* Initialize the fdset. */
1156                 FD_ZERO(&readfds);
1157                 highest = 0;
1158
1159                 /* First, add the various master sockets to the fdset. */
1160                 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1161                         FD_SET(serviceptr->msock, &readfds);
1162                         if (serviceptr->msock > highest) {
1163                                 highest = serviceptr->msock;
1164                         }
1165                 }
1166
1167                 /* Next, add all of the client sockets. */
1168                 begin_critical_section(S_SESSION_TABLE);
1169                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1170                         if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
1171                             continue;
1172
1173                         /* Don't select on dead sessions, only truly idle ones */
1174                         if (    (ptr->state == CON_IDLE)
1175                                 && (ptr->kill_me == 0)
1176                                 && (ptr->client_socket > 0)
1177                         ) {
1178                                 FD_SET(ptr->client_socket, &readfds);
1179                                 if (ptr->client_socket > highest)
1180                                         highest = ptr->client_socket;
1181                         }
1182                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1183                                 bind_me = ptr;
1184                                 ptr->state = CON_EXECUTING;
1185                                 break;
1186                         }
1187                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1188                                 bind_me = ptr;
1189                                 ptr->state = CON_STARTING;
1190                                 break;
1191                         }
1192                 }
1193                 end_critical_section(S_SESSION_TABLE);
1194
1195                 if (bind_me) {
1196                         goto SKIP_SELECT;
1197                 }
1198
1199                 /* If we got this far, it means that there are no sessions
1200                  * which a previous thread marked for attention, so we go
1201                  * ahead and get ready to select().
1202                  */
1203
1204                 if (!server_shutting_down) {
1205                         tv.tv_sec = 1;          /* wake up every second if no input */
1206                         tv.tv_usec = 0;
1207                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1208                 }
1209                 else {
1210                         --num_workers;
1211                         return NULL;
1212                 }
1213
1214                 /* Now figure out who made this select() unblock.
1215                  * First, check for an error or exit condition.
1216                  */
1217                 if (retval < 0) {
1218                         if (errno == EBADF) {
1219                                 syslog(LOG_NOTICE, "select() failed: (%s)\n", strerror(errno));
1220                                 goto do_select;
1221                         }
1222                         if (errno != EINTR) {
1223                                 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1224                                 server_shutting_down = 1;
1225                                 continue;
1226                         } else {
1227 #if 0
1228                                 syslog(LOG_DEBUG, "Interrupted select()\n");
1229 #endif
1230                                 if (server_shutting_down) {
1231                                         --num_workers;
1232                                         return(NULL);
1233                                 }
1234                                 goto do_select;
1235                         }
1236                 }
1237                 else if (retval == 0) {
1238                         if (server_shutting_down) {
1239                                 --num_workers;
1240                                 return(NULL);
1241                         }
1242                 }
1243
1244                 /* Next, check to see if it's a new client connecting * on a master socket. */
1245
1246                 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1247
1248                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1249                                 ssock = accept(serviceptr->msock, NULL, 0);
1250                                 if (ssock >= 0) {
1251                                         syslog(LOG_DEBUG, "New client socket %d", ssock);
1252
1253                                         /* The master socket is non-blocking but the client
1254                                          * sockets need to be blocking, otherwise certain
1255                                          * operations barf on FreeBSD.  Not a fatal error.
1256                                          */
1257                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1258                                                 syslog(LOG_EMERG,
1259                                                         "citserver: Can't set socket to blocking: %s\n",
1260                                                         strerror(errno));
1261                                         }
1262
1263                                         /* New context will be created already
1264                                          * set up in the CON_EXECUTING state.
1265                                          */
1266                                         con = CreateNewContext();
1267
1268                                         /* Assign our new socket number to it. */
1269                                         con->tcp_port = serviceptr->tcp_port;
1270                                         con->client_socket = ssock;
1271                                         con->h_command_function = serviceptr->h_command_function;
1272                                         con->h_async_function = serviceptr->h_async_function;
1273                                         con->h_greeting_function = serviceptr->h_greeting_function;
1274                                         con->ServiceName = serviceptr->ServiceName;
1275                                         
1276                                         /* Determine whether it's a local socket */
1277                                         if (serviceptr->sockpath != NULL) {
1278                                                 con->is_local_socket = 1;
1279                                         }
1280         
1281                                         /* Set the SO_REUSEADDR socket option */
1282                                         i = 1;
1283                                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1284                                         con->state = CON_GREETING;
1285                                         retval--;
1286                                         if (retval == 0)
1287                                                 break;
1288                                 }
1289                         }
1290                 }
1291
1292                 /* It must be a client socket.  Find a context that has data
1293                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1294                  * active sockets other than our chosen one are marked as
1295                  * CON_READY so the next thread that comes around can just bind
1296                  * to one without having to select() again.
1297                  */
1298                 begin_critical_section(S_SESSION_TABLE);
1299                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1300                         int checkfd = ptr->client_socket;
1301                         if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1302                                 if (FD_ISSET(checkfd, &readfds)) {
1303                                         ptr->input_waiting = 1;
1304                                         if (!bind_me) {
1305                                                 bind_me = ptr;  /* I choose you! */
1306                                                 bind_me->state = CON_EXECUTING;
1307                                         }
1308                                         else {
1309                                                 ptr->state = CON_READY;
1310                                         }
1311                                 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1312                                         if (!bind_me) {
1313                                                 bind_me = ptr;  /* I choose you! */
1314                                                 bind_me->state = CON_EXECUTING;
1315                                         }
1316                                         else {
1317                                                 ptr->state = CON_READY;
1318                                         }
1319                                 }
1320                         }
1321                 }
1322                 end_critical_section(S_SESSION_TABLE);
1323
1324 SKIP_SELECT:
1325                 /* We're bound to a session */
1326                 ++active_workers;
1327                 if (bind_me != NULL) {
1328                         become_session(bind_me);
1329
1330                         if (bind_me->state == CON_STARTING) {
1331                                 bind_me->state = CON_EXECUTING;
1332                                 begin_session(bind_me);
1333                                 bind_me->h_greeting_function();
1334                         }
1335                         /* If the client has sent a command, execute it. */
1336                         if (CC->input_waiting) {
1337                                 CC->h_command_function();
1338
1339                                 while (HaveMoreLinesWaiting(CC))
1340                                        CC->h_command_function();
1341
1342                                 CC->input_waiting = 0;
1343                         }
1344
1345                         /* If there are asynchronous messages waiting and the
1346                          * client supports it, do those now */
1347                         if ((CC->is_async) && (CC->async_waiting)
1348                            && (CC->h_async_function != NULL)) {
1349                                 CC->h_async_function();
1350                                 CC->async_waiting = 0;
1351                         }
1352                         
1353                         force_purge = CC->kill_me;
1354                         become_session(NULL);
1355                         bind_me->state = CON_IDLE;
1356                 }
1357
1358                 dead_session_purge(force_purge);
1359                 do_housekeeping();
1360                 --active_workers;
1361         }
1362
1363         /* If control reaches this point, the server is shutting down */
1364         --num_workers;
1365         return(NULL);
1366 }
1367
1368
1369
1370 /*
1371  * SyslogFacility()
1372  * Translate text facility name to syslog.h defined value.
1373  */
1374 int SyslogFacility(char *name)
1375 {
1376         int i;
1377         struct
1378         {
1379                 int facility;
1380                 char *name;
1381         }   facTbl[] =
1382         {
1383                 {   LOG_KERN,   "kern"          },
1384                 {   LOG_USER,   "user"          },
1385                 {   LOG_MAIL,   "mail"          },
1386                 {   LOG_DAEMON, "daemon"        },
1387                 {   LOG_AUTH,   "auth"          },
1388                 {   LOG_SYSLOG, "syslog"        },
1389                 {   LOG_LPR,    "lpr"           },
1390                 {   LOG_NEWS,   "news"          },
1391                 {   LOG_UUCP,   "uucp"          },
1392                 {   LOG_LOCAL0, "local0"        },
1393                 {   LOG_LOCAL1, "local1"        },
1394                 {   LOG_LOCAL2, "local2"        },
1395                 {   LOG_LOCAL3, "local3"        },
1396                 {   LOG_LOCAL4, "local4"        },
1397                 {   LOG_LOCAL5, "local5"        },
1398                 {   LOG_LOCAL6, "local6"        },
1399                 {   LOG_LOCAL7, "local7"        },
1400                 {   0,            NULL          }
1401         };
1402         for(i = 0; facTbl[i].name != NULL; i++) {
1403                 if(!strcasecmp(name, facTbl[i].name))
1404                         return facTbl[i].facility;
1405         }
1406         return LOG_DAEMON;
1407 }