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