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