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