]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* sysdep.c: worker_thread(): Make scheduling a little more fair to higher
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel/UX "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14
15 #ifdef DLL_EXPORT
16 #define IN_LIBCIT
17 #endif
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <ctype.h>
25 #include <signal.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <sys/socket.h>
30 #include <sys/syslog.h>
31
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
34 # include <time.h>
35 #else
36 # if HAVE_SYS_TIME_H
37 #  include <sys/time.h>
38 # else
39 #  include <time.h>
40 # endif
41 #endif
42
43 #include <limits.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46 #include <sys/un.h>
47 #include <string.h>
48 #include <pwd.h>
49 #include <errno.h>
50 #include <stdarg.h>
51 #include <grp.h>
52 #ifdef HAVE_PTHREAD_H
53 #include <pthread.h>
54 #endif
55 #include "citadel.h"
56 #include "server.h"
57 #include "serv_extensions.h"
58 #include "sysdep_decls.h"
59 #include "citserver.h"
60 #include "support.h"
61 #include "config.h"
62 #include "database.h"
63 #include "housekeeping.h"
64 #include "tools.h"
65 #include "serv_crypto.h"
66
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
69 #endif
70
71 #ifndef HAVE_SNPRINTF
72 #include "snprintf.h"
73 #endif
74
75 #ifdef DEBUG_MEMORY_LEAKS
76 struct TheHeap *heap = NULL;
77 #endif
78
79 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
80 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
81
82 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
83
84 struct CitContext masterCC;
85 int rescan[2];                                  /* The Rescan Pipe */
86 time_t last_purge = 0;                          /* Last dead session purge */
87 static int num_threads = 0;                     /* Current number of threads */
88 int num_sessions = 0;                           /* Current number of sessions */
89
90 fd_set masterfds;                               /* Master sockets etc. */
91 int masterhighest;
92
93 pthread_t initial_thread;               /* tid for main() thread */
94
95 int syslog_facility = (-1);
96
97
98 /*
99  * lprintf()  ...   Write logging information
100  * 
101  * Note: the variable "buf" below needs to be large enough to handle any
102  * log data sent through this function.  BE CAREFUL!
103  */
104 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
105         va_list arg_ptr;
106         char buf[SIZ];
107  
108         va_start(arg_ptr, format);   
109         vsnprintf(buf, sizeof(buf), format, arg_ptr);   
110         va_end(arg_ptr);   
111
112         if (syslog_facility >= 0) {
113                 if (loglevel <= verbosity) {
114                         /* Hackery -IO */
115                         if (CC && CC->cs_pid) {
116                                 memmove(buf + 6, buf, sizeof(buf) - 6);
117                                 snprintf(buf, 6, "[%3d]", CC->cs_pid);
118                                 buf[5] = ' ';
119                         }
120                         syslog(loglevel, buf);
121                 }
122         }
123         else if (loglevel <= verbosity) { 
124                 struct timeval tv;
125                 struct tm *tim;
126                 time_t unixtime;
127
128                 gettimeofday(&tv, NULL);
129                 /* Promote to time_t; types differ on some OSes (like darwin) */
130                 unixtime = tv.tv_sec;
131                 tim = localtime(&unixtime);
132                 /*
133                  * Log provides millisecond accuracy.  If you need
134                  * microsecond accuracy and your OS supports it, change
135                  * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
136                  */
137                 if (CC && CC->cs_pid) {
138 #if 0
139                         /* Millisecond display */
140                         fprintf(stderr,
141                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%3d] %s",
142                                 tim->tm_year + 1900, tim->tm_mon + 1,
143                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
144                                 tim->tm_sec, (long)tv.tv_usec / 1000,
145                                 CC->cs_pid, buf);
146 #endif
147                         /* Microsecond display */
148                         fprintf(stderr,
149                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] %s",
150                                 tim->tm_year + 1900, tim->tm_mon + 1,
151                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
152                                 tim->tm_sec, (long)tv.tv_usec,
153                                 CC->cs_pid, buf);
154                 } else {
155 #if 0
156                         /* Millisecond display */
157                         fprintf(stderr,
158                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld %s",
159                                 tim->tm_year + 1900, tim->tm_mon + 1,
160                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
161                                 tim->tm_sec, (long)tv.tv_usec / 1000, buf);
162 #endif
163                         /* Microsecond display */
164                         fprintf(stderr,
165                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s",
166                                 tim->tm_year + 1900, tim->tm_mon + 1,
167                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
168                                 tim->tm_sec, (long)tv.tv_usec, buf);
169                 }
170                 fflush(stderr);
171         }
172
173         PerformLogHooks(loglevel, buf);
174 }   
175
176
177
178 #ifdef DEBUG_MEMORY_LEAKS
179 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
180         void *ptr;
181         struct TheHeap *hptr;
182
183         ptr = malloc(tsize);
184         if (ptr == NULL) {
185                 lprintf(CTDL_ALERT, "DANGER!  mallok(%d) at %s:%d failed!\n",
186                         tsize, tfile, tline);
187                 return(NULL);
188         }
189
190         hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
191         strcpy(hptr->h_file, tfile);
192         hptr->h_line = tline;
193         hptr->next = heap;
194         hptr->h_ptr = ptr;
195         heap = hptr;
196         return ptr;
197 }
198
199 char *tracked_strdup(const char *orig, char *tfile, int tline) {
200         char *s;
201
202         s = tracked_malloc( (strlen(orig)+1), tfile, tline);
203         if (s == NULL) return NULL;
204
205         strcpy(s, orig);
206         return s;
207 }
208
209 void tracked_free(void *ptr) {
210         struct TheHeap *hptr, *freeme;
211
212         if (heap->h_ptr == ptr) {
213                 hptr = heap->next;
214                 free(heap);
215                 heap = hptr;
216         }
217         else {
218                 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
219                         if (hptr->next->h_ptr == ptr) {
220                                 freeme = hptr->next;
221                                 hptr->next = hptr->next->next;
222                                 free(freeme);
223                         }
224                 }
225         }
226
227         free(ptr);
228 }
229
230 void *tracked_realloc(void *ptr, size_t size) {
231         void *newptr;
232         struct TheHeap *hptr;
233         
234         newptr = realloc(ptr, size);
235
236         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
237                 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
238         }
239
240         return newptr;
241 }
242
243
244 void dump_tracked() {
245         struct TheHeap *hptr;
246
247         cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);    
248         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
249                 cprintf("%20s %5d\n",
250                         hptr->h_file, hptr->h_line);
251         }
252 #ifdef __GNUC__
253         malloc_stats();
254 #endif
255
256         cprintf("000\n");
257 }
258 #endif
259
260
261 /*
262  * We used to use master_cleanup() as a signal handler to shut down the server.
263  * however, master_cleanup() and the functions it calls do some things that
264  * aren't such a good idea to do from a signal handler: acquiring mutexes,
265  * playing with signal masks on BSDI systems, etc. so instead we install the
266  * following signal handler to set a global variable to inform the main loop
267  * that it's time to call master_cleanup() and exit.
268  */
269
270 volatile int time_to_die = 0;
271
272 static RETSIGTYPE signal_cleanup(int signum) {
273         time_to_die = 1;
274 }
275
276
277 /*
278  * Some initialization stuff...
279  */
280 void init_sysdep(void) {
281         int a;
282
283 #ifdef HAVE_OPENSSL
284         init_ssl();
285 #endif
286
287         /* Set up a bunch of semaphores to be used for critical sections */
288         for (a=0; a<MAX_SEMAPHORES; ++a) {
289                 pthread_mutex_init(&Critters[a], NULL);
290         }
291
292         /*
293          * Set up a place to put thread-specific data.
294          * We only need a single pointer per thread - it points to the
295          * CitContext structure (in the ContextList linked list) of the
296          * session to which the calling thread is currently bound.
297          */
298         if (pthread_key_create(&MyConKey, NULL) != 0) {
299                 lprintf(CTDL_CRIT, "Can't create TSD key!!  %s\n", strerror(errno));
300         }
301
302         /*
303          * The action for unexpected signals and exceptions should be to
304          * call signal_cleanup() to gracefully shut down the server.
305          */
306         signal(SIGINT, signal_cleanup);
307         signal(SIGQUIT, signal_cleanup);
308         signal(SIGHUP, signal_cleanup);
309         signal(SIGTERM, signal_cleanup);
310
311         /*
312          * Do not shut down the server on broken pipe signals, otherwise the
313          * whole Citadel service would come down whenever a single client
314          * socket breaks.
315          */
316         signal(SIGPIPE, SIG_IGN);
317 }
318
319
320 /*
321  * Obtain a semaphore lock to begin a critical section.
322  */
323 void begin_critical_section(int which_one)
324 {
325         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
326         /* ensure nobody ever tries to do a critical section within a
327            transaction; this could lead to deadlock. */
328         cdb_check_handles();
329         pthread_mutex_lock(&Critters[which_one]);
330 }
331
332 /*
333  * Release a semaphore lock to end a critical section.
334  */
335 void end_critical_section(int which_one)
336 {
337         /* lprintf(CTDL_DEBUG, "end_critical_section(%d)\n", which_one); */
338         pthread_mutex_unlock(&Critters[which_one]);
339 }
340
341
342
343 /*
344  * This is a generic function to set up a master socket for listening on
345  * a TCP port.  The server shuts down if the bind fails.
346  *
347  */
348 int ig_tcp_server(int port_number, int queue_len)
349 {
350         struct sockaddr_in sin;
351         int s, i;
352         int actual_queue_len;
353
354         actual_queue_len = queue_len;
355         if (actual_queue_len < 5) actual_queue_len = 5;
356
357         memset(&sin, 0, sizeof(sin));
358         sin.sin_family = AF_INET;
359         sin.sin_addr.s_addr = INADDR_ANY;
360         sin.sin_port = htons((u_short)port_number);
361
362         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
363
364         if (s < 0) {
365                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
366                         strerror(errno));
367                 return(-1);
368         }
369
370         i = 1;
371         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
372
373         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
374                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
375                         strerror(errno));
376                 close(s);
377                 return(-1);
378         }
379
380         if (listen(s, actual_queue_len) < 0) {
381                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
382                 close(s);
383                 return(-1);
384         }
385
386         return(s);
387 }
388
389
390
391 /*
392  * Create a Unix domain socket and listen on it
393  */
394 int ig_uds_server(char *sockpath, int queue_len)
395 {
396         struct sockaddr_un addr;
397         int s;
398         int i;
399         int actual_queue_len;
400
401         actual_queue_len = queue_len;
402         if (actual_queue_len < 5) actual_queue_len = 5;
403
404         i = unlink(sockpath);
405         if (i != 0) if (errno != ENOENT) {
406                 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
407                         sockpath, strerror(errno));
408                 return(-1);
409         }
410
411         memset(&addr, 0, sizeof(addr));
412         addr.sun_family = AF_UNIX;
413         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
414
415         s = socket(AF_UNIX, SOCK_STREAM, 0);
416         if (s < 0) {
417                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
418                         strerror(errno));
419                 return(-1);
420         }
421
422         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
423                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
424                         strerror(errno));
425                 return(-1);
426         }
427
428         if (listen(s, actual_queue_len) < 0) {
429                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
430                 return(-1);
431         }
432
433         chmod(sockpath, 0777);
434         return(s);
435 }
436
437
438
439 /*
440  * Return a pointer to the CitContext structure bound to the thread which
441  * called this function.  If there's no such binding (for example, if it's
442  * called by the housekeeper thread) then a generic 'master' CC is returned.
443  *
444  * It's inlined because it's used *VERY* frequently.
445  */
446 INLINE struct CitContext *MyContext(void) {
447         return ((pthread_getspecific(MyConKey) == NULL)
448                 ? &masterCC
449                 : (struct CitContext *) pthread_getspecific(MyConKey)
450         );
451 }
452
453
454 /*
455  * Initialize a new context and place it in the list.  The session number
456  * used to be the PID (which is why it's called cs_pid), but that was when we
457  * had one process per session.  Now we just assign them sequentially, starting
458  * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
459  * sessions terminate.
460  */
461 struct CitContext *CreateNewContext(void) {
462         struct CitContext *me, *ptr;
463
464         me = (struct CitContext *) mallok(sizeof(struct CitContext));
465         if (me == NULL) {
466                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
467                 return NULL;
468         }
469         memset(me, 0, sizeof(struct CitContext));
470
471         /* The new context will be created already in the CON_EXECUTING state
472          * in order to prevent another thread from grabbing it while it's
473          * being set up.
474          */
475         me->state = CON_EXECUTING;
476
477
478         /*
479          * Generate a unique session number and insert this context into
480          * the list.
481          */
482         begin_critical_section(S_SESSION_TABLE);
483
484         if (ContextList == NULL) {
485                 ContextList = me;
486                 me->cs_pid = 1;
487                 me->next = NULL;
488         }
489
490         else if (ContextList->cs_pid > 1) {
491                 me->next = ContextList;
492                 ContextList = me;
493                 me->cs_pid = 1;
494         }
495
496         else {
497                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
498                         if (ptr->next == NULL) {
499                                 ptr->next = me;
500                                 me->cs_pid = ptr->cs_pid + 1;
501                                 me->next = NULL;
502                                 goto DONE;
503                         }
504                         else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
505                                 me->next = ptr->next;
506                                 ptr->next = me;
507                                 me->cs_pid = ptr->cs_pid + 1;
508                                 goto DONE;
509                         }
510                 }
511         }
512
513 DONE:   ++num_sessions;
514         end_critical_section(S_SESSION_TABLE);
515         return(me);
516 }
517
518
519 /*
520  * buffer_output() ... tell client_write to buffer all output until
521  *                     instructed to dump it all out later
522  */
523 void buffer_output(void) {
524         if (CC->buffering == 0) {
525                 CC->buffering = 1;
526                 CC->buffer_len = 0;
527                 CC->output_buffer = mallok(SIZ);
528         }
529 }
530
531 /*
532  * unbuffer_output()  ...  dump out all that output we've been buffering.
533  */
534 void unbuffer_output(void) {
535         if (CC->buffering == 1) {
536                 CC->buffering = 0;
537                 client_write(CC->output_buffer, CC->buffer_len);
538                 phree(CC->output_buffer);
539                 CC->output_buffer = NULL;
540                 CC->buffer_len = 0;
541         }
542 }
543
544
545
546 /*
547  * client_write()   ...    Send binary data to the client.
548  */
549 void client_write(char *buf, int nbytes)
550 {
551         int bytes_written = 0;
552         int retval;
553         int sock;
554         int old_buffer_len = 0;
555
556         if (CC->redirect_fp != NULL) {
557                 fwrite(buf, nbytes, 1, CC->redirect_fp);
558                 return;
559         }
560
561         if (CC->redirect_sock > 0) {
562                 sock = CC->redirect_sock;       /* and continue below... */
563         }
564         else {
565                 sock = CC->client_socket;
566         }
567
568         /* If we're buffering for later, do that now. */
569         if (CC->buffering) {
570                 old_buffer_len = CC->buffer_len;
571                 CC->buffer_len += nbytes;
572                 CC->output_buffer = reallok(CC->output_buffer, CC->buffer_len);
573                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
574                 return;
575         }
576
577         /* Ok, at this point we're not buffering.  Go ahead and write. */
578
579 #ifdef HAVE_OPENSSL
580         if (CC->redirect_ssl) {
581                 client_write_ssl(buf, nbytes);
582                 return;
583         }
584 #endif
585
586         while (bytes_written < nbytes) {
587                 retval = write(sock, &buf[bytes_written],
588                         nbytes - bytes_written);
589                 if (retval < 1) {
590                         lprintf(CTDL_ERR, "client_write() failed: %s\n",
591                                 strerror(errno));
592                         if (sock == CC->client_socket) CC->kill_me = 1;
593                         return;
594                 }
595                 bytes_written = bytes_written + retval;
596         }
597 }
598
599
600 /*
601  * cprintf()  ...   Send formatted printable data to the client.   It is
602  *                  implemented in terms of client_write() but remains in
603  *                  sysdep.c in case we port to somewhere without va_args...
604  */
605 void cprintf(const char *format, ...) {   
606         va_list arg_ptr;   
607         char buf[SIZ];   
608    
609         va_start(arg_ptr, format);   
610         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
611                 buf[sizeof buf - 2] = '\n';
612         client_write(buf, strlen(buf)); 
613         va_end(arg_ptr);
614 }   
615
616
617 /*
618  * Read data from the client socket.
619  * Return values are:
620  *      1       Requested number of bytes has been read.
621  *      0       Request timed out.
622  *      -1      The socket is broken.
623  * If the socket breaks, the session will be terminated.
624  */
625 int client_read_to(char *buf, int bytes, int timeout)
626 {
627         int len,rlen;
628         fd_set rfds;
629         struct timeval tv;
630         int retval;
631
632 #ifdef HAVE_OPENSSL
633         if (CC->redirect_ssl) {
634                 return (client_read_ssl(buf, bytes, timeout));
635         }
636 #endif
637         len = 0;
638         while(len<bytes) {
639                 FD_ZERO(&rfds);
640                 FD_SET(CC->client_socket, &rfds);
641                 tv.tv_sec = timeout;
642                 tv.tv_usec = 0;
643
644                 retval = select( (CC->client_socket)+1, 
645                                         &rfds, NULL, NULL, &tv);
646
647                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
648                         return(0);
649                 }
650
651                 rlen = read(CC->client_socket, &buf[len], bytes-len);
652                 if (rlen<1) {
653                         lprintf(CTDL_ERR, "client_read() failed: %s\n",
654                                 strerror(errno));
655                         CC->kill_me = 1;
656                         return(-1);
657                 }
658                 len = len + rlen;
659         }
660         return(1);
661 }
662
663 /*
664  * Read data from the client socket with default timeout.
665  * (This is implemented in terms of client_read_to() and could be
666  * justifiably moved out of sysdep.c)
667  */
668 INLINE int client_read(char *buf, int bytes)
669 {
670         return(client_read_to(buf, bytes, config.c_sleeping));
671 }
672
673
674 /*
675  * client_gets()   ...   Get a LF-terminated line of text from the client.
676  * (This is implemented in terms of client_read() and could be
677  * justifiably moved out of sysdep.c)
678  */
679 int client_gets(char *buf)
680 {
681         int i, retval;
682
683         /* Read one character at a time.
684          */
685         for (i = 0;;i++) {
686                 retval = client_read(&buf[i], 1);
687                 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
688                         break;
689         }
690
691         /* If we got a long line, discard characters until the newline.
692          */
693         if (i == (SIZ-1))
694                 while (buf[i] != '\n' && retval == 1)
695                         retval = client_read(&buf[i], 1);
696
697         /* Strip the trailing newline and any trailing nonprintables (cr's)
698          */
699         buf[i] = 0;
700         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
701                 buf[strlen(buf)-1] = 0;
702         if (retval < 0) strcpy(buf, "000");
703         return(retval);
704 }
705
706
707
708 /*
709  * The system-dependent part of master_cleanup() - close the master socket.
710  */
711 void sysdep_master_cleanup(void) {
712         struct ServiceFunctionHook *serviceptr;
713
714         /*
715          * close all protocol master sockets
716          */
717         for (serviceptr = ServiceHookTable; serviceptr != NULL;
718             serviceptr = serviceptr->next ) {
719
720                 if (serviceptr->tcp_port > 0)
721                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
722                                 serviceptr->tcp_port);
723
724                 if (serviceptr->sockpath != NULL)
725                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
726                                 serviceptr->sockpath);
727
728                 close(serviceptr->msock);
729
730                 /* If it's a Unix domain socket, remove the file. */
731                 if (serviceptr->sockpath != NULL) {
732                         unlink(serviceptr->sockpath);
733                 }
734         }
735 }
736
737
738 /*
739  * Terminate another session.
740  * (This could justifiably be moved out of sysdep.c because it
741  * no longer does anything that is system-dependent.)
742  */
743 void kill_session(int session_to_kill) {
744         struct CitContext *ptr;
745
746         begin_critical_section(S_SESSION_TABLE);
747         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
748                 if (ptr->cs_pid == session_to_kill) {
749                         ptr->kill_me = 1;
750                 }
751         }
752         end_critical_section(S_SESSION_TABLE);
753 }
754
755
756
757
758 /*
759  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
760  */
761 void start_daemon(int do_close_stdio) {
762         if (do_close_stdio) {
763                 /* close(0); */
764                 close(1);
765                 close(2);
766         }
767         signal(SIGHUP,SIG_IGN);
768         signal(SIGINT,SIG_IGN);
769         signal(SIGQUIT,SIG_IGN);
770         if (fork()!=0) exit(0);
771 }
772
773
774
775 /*
776  * Generic routine to convert a login name to a full name (gecos)
777  * Returns nonzero if a conversion took place
778  */
779 int convert_login(char NameToConvert[]) {
780         struct passwd *pw;
781         int a;
782
783         pw = getpwnam(NameToConvert);
784         if (pw == NULL) {
785                 return(0);
786         }
787         else {
788                 strcpy(NameToConvert, pw->pw_gecos);
789                 for (a=0; a<strlen(NameToConvert); ++a) {
790                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
791                 }
792                 return(1);
793         }
794 }
795
796 struct worker_node *worker_list = NULL;
797
798
799 /*
800  * create a worker thread. this function must always be called from within
801  * an S_WORKER_LIST critical section!
802  */
803 void create_worker(void) {
804         int ret;
805         struct worker_node *n;
806         pthread_attr_t attr;
807
808         n = mallok(sizeof(struct worker_node));
809         if (n == NULL) {
810                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
811                 time_to_die = -1;
812                 return;
813         }
814
815         if ((ret = pthread_attr_init(&attr))) {
816                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
817                 time_to_die = -1;
818                 return;
819         }
820
821         /* we seem to need something bigger than FreeBSD's default 64k stack */
822
823         if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
824                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
825                 time_to_die = -1;
826                 return;
827         }
828
829         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
830         {
831
832                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
833                         strerror(ret));
834         }
835
836         n->next = worker_list;
837         worker_list = n;
838 }
839
840
841
842 /*
843  * Purge all sessions which have the 'kill_me' flag set.
844  * This function has code to prevent it from running more than once every
845  * few seconds, because running it after every single unbind would waste a lot
846  * of CPU time and keep the context list locked too much.
847  *
848  * After that's done, we raise or lower the size of the worker thread pool
849  * if such an action is appropriate.
850  */
851 void dead_session_purge(void) {
852         struct CitContext *ptr, *rem;
853         struct worker_node **node, *tmp;
854         pthread_t self;
855
856         if ( (time(NULL) - last_purge) < 5 ) return;    /* Too soon, go away */
857         time(&last_purge);
858
859         do {
860                 rem = NULL;
861                 begin_critical_section(S_SESSION_TABLE);
862                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
863                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
864                                 rem = ptr;
865                         }
866                 }
867                 end_critical_section(S_SESSION_TABLE);
868
869                 /* RemoveContext() enters its own S_SESSION_TABLE critical
870                  * section, so we have to do it like this.
871                  */     
872                 if (rem != NULL) {
873                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
874                         RemoveContext(rem);
875                 }
876
877         } while (rem != NULL);
878
879
880         /* Raise or lower the size of the worker thread pool if such
881          * an action is appropriate.
882          */
883
884         self = pthread_self();
885
886         if ( (num_sessions > num_threads)
887            && (num_threads < config.c_max_workers) ) {
888                 begin_critical_section(S_WORKER_LIST);
889                 create_worker();
890                 end_critical_section(S_WORKER_LIST);
891         }
892         
893         /* don't let the initial thread die since it's responsible for
894            waiting for all the other threads to terminate. */
895         else if ( (num_sessions < num_threads)
896            && (num_threads > config.c_min_workers)
897            && (self != initial_thread) ) {
898                 cdb_free_tsd();
899                 begin_critical_section(S_WORKER_LIST);
900                 --num_threads;
901
902                 /* we're exiting before server shutdown... unlink ourself from
903                    the worker list and detach our thread to avoid memory leaks
904                  */
905
906                 for (node = &worker_list; *node != NULL; node = &(*node)->next)
907                         if ((*node)->tid == self) {
908                                 tmp = *node;
909                                 *node = (*node)->next;
910                                 phree(tmp);
911                                 break;
912                         }
913
914                 pthread_detach(self);
915                 end_critical_section(S_WORKER_LIST);
916                 pthread_exit(NULL);
917         }
918
919 }
920
921
922
923
924
925 /*
926  * Redirect a session's output to a file or socket.
927  * This function may be called with a file handle *or* a socket (but not
928  * both).  Call with neither to return output to its normal client socket.
929  */
930 void CtdlRedirectOutput(FILE *fp, int sock) {
931
932         if (fp != NULL) CC->redirect_fp = fp;
933         else CC->redirect_fp = NULL;
934
935         if (sock > 0) CC->redirect_sock = sock;
936         else CC->redirect_sock = (-1);
937
938 }
939
940
941 /*
942  * masterCC is the context we use when not attached to a session.  This
943  * function initializes it.
944  */
945 void InitializeMasterCC(void) {
946         memset(&masterCC, 0, sizeof(struct CitContext));
947         masterCC.internal_pgm = 1;
948         masterCC.cs_pid = 0;
949 }
950
951
952
953 /*
954  * Set up a fd_set containing all the master sockets to which we
955  * always listen.  It's computationally less expensive to just copy
956  * this to a local fd_set when starting a new select() and then add
957  * the client sockets than it is to initialize a new one and then
958  * figure out what to put there.
959  */
960 void init_master_fdset(void) {
961         struct ServiceFunctionHook *serviceptr;
962         int m;
963
964         lprintf(CTDL_DEBUG, "Initializing master fdset\n");
965
966         FD_ZERO(&masterfds);
967         masterhighest = 0;
968
969         lprintf(CTDL_DEBUG, "Will listen on rescan pipe %d\n", rescan[0]);
970         FD_SET(rescan[0], &masterfds);
971         if (rescan[0] > masterhighest) masterhighest = rescan[0];
972
973         for (serviceptr = ServiceHookTable; serviceptr != NULL;
974             serviceptr = serviceptr->next ) {
975                 m = serviceptr->msock;
976                 lprintf(CTDL_DEBUG, "Will listen on master socket %d\n", m);
977                 FD_SET(m, &masterfds);
978                 if (m > masterhighest) {
979                         masterhighest = m;
980                 }
981         }
982         lprintf(CTDL_DEBUG, "masterhighest = %d\n", masterhighest);
983 }
984
985
986 /*
987  * Bind a thread to a context.  (It's inline merely to speed things up.)
988  */
989 INLINE void become_session(struct CitContext *which_con) {
990         pthread_setspecific(MyConKey, (void *)which_con );
991 }
992
993
994
995 /* 
996  * This loop just keeps going and going and going...
997  */     
998 void *worker_thread(void *arg) {
999         int i;
1000         char junk;
1001         int highest;
1002         /* This is synchronized below; it helps implement round robin mode */
1003         static struct CitContext* next_session = NULL;
1004         struct CitContext *ptr;
1005         struct CitContext *bind_me = NULL;
1006         fd_set readfds;
1007         int retval;
1008         struct CitContext *con= NULL;   /* Temporary context pointer */
1009         struct ServiceFunctionHook *serviceptr;
1010         int ssock;                      /* Descriptor for client socket */
1011         struct timeval tv;
1012
1013         num_threads++;
1014
1015         cdb_allocate_tsd();
1016
1017         while (!time_to_die) {
1018
1019                 /* 
1020                  * A naive implementation would have all idle threads
1021                  * calling select() and then they'd all wake up at once
1022                  * (known in computer science as the "thundering herd"
1023                  * problem).  We solve this problem by putting the select()
1024                  * in a critical section, so only one thread has the
1025                  * opportunity to wake up.  If we wake up on a master
1026                  * socket, create a new session context; otherwise, just
1027                  * bind the thread to the context we want and go on our
1028                  * merry way.
1029                  */
1030
1031                 /* make doubly sure we're not holding any stale db handles
1032                  * which might cause a deadlock.
1033                  */
1034                 cdb_check_handles();
1035
1036                 begin_critical_section(S_I_WANNA_SELECT);
1037 SETUP_FD:       memcpy(&readfds, &masterfds, sizeof masterfds);
1038                 highest = masterhighest;
1039                 begin_critical_section(S_SESSION_TABLE);
1040                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1041                         if (ptr->state == CON_IDLE) {
1042                                 FD_SET(ptr->client_socket, &readfds);
1043                                 if (ptr->client_socket > highest)
1044                                         highest = ptr->client_socket;
1045                         }
1046                 }
1047                 end_critical_section(S_SESSION_TABLE);
1048
1049                 tv.tv_sec = 1;          /* wake up every second if no input */
1050                 tv.tv_usec = 0;
1051
1052                 do_select:
1053                 if (!time_to_die)
1054                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1055                 else {
1056                         end_critical_section(S_I_WANNA_SELECT);
1057                         break;
1058                 }
1059
1060                 /* Now figure out who made this select() unblock.
1061                  * First, check for an error or exit condition.
1062                  */
1063                 if (retval < 0) {
1064                         if (errno != EINTR) {
1065                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1066                                 time_to_die = 1;
1067                         } else if (!time_to_die)
1068                                 goto do_select;
1069                 }
1070
1071                 /* Next, check to see if it's a new client connecting
1072                  * on a master socket.
1073                  */
1074                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1075                      serviceptr = serviceptr->next ) {
1076
1077                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1078                                 ssock = accept(serviceptr->msock, NULL, 0);
1079                                 if (ssock < 0) {
1080                                         lprintf(CTDL_CRIT,
1081                                                 "citserver: accept(): %s\n",
1082                                                 strerror(errno));
1083                                 }
1084                                 else {
1085                                         lprintf(CTDL_NOTICE,
1086                                                 "New client socket %d\n",
1087                                                 ssock);
1088
1089                                         /* New context will be created already
1090                                         * set up in the CON_EXECUTING state.
1091                                         */
1092                                         con = CreateNewContext();
1093
1094                                         /* Assign new socket number to it. */
1095                                         con->client_socket = ssock;
1096                                         con->h_command_function =
1097                                                 serviceptr->h_command_function;
1098
1099                                         /* Determine whether local socket */
1100                                         if (serviceptr->sockpath != NULL)
1101                                                 con->is_local_socket = 1;
1102         
1103                                         /* Set the SO_REUSEADDR socket option */
1104                                         i = 1;
1105                                         setsockopt(ssock, SOL_SOCKET,
1106                                                 SO_REUSEADDR,
1107                                                 &i, sizeof(i));
1108
1109                                         become_session(con);
1110                                         begin_session(con);
1111                                         serviceptr->h_greeting_function();
1112                                         become_session(NULL);
1113                                         con->state = CON_IDLE;
1114                                         goto SETUP_FD;
1115                                 }
1116                         }
1117                 }
1118
1119                 /* If the rescan pipe went active, someone is telling this
1120                  * thread that the &readfds needs to be refreshed with more
1121                  * current data.
1122                  */
1123                 if (time_to_die) {
1124                         end_critical_section(S_I_WANNA_SELECT);
1125                         break;
1126                 }
1127
1128                 if (FD_ISSET(rescan[0], &readfds)) {
1129                         read(rescan[0], &junk, 1);
1130                         goto SETUP_FD;
1131                 }
1132
1133                 /* It must be a client socket.  Find a context that has data
1134                  * waiting on its socket *and* is in the CON_IDLE state.
1135                  */
1136                 else {
1137                         bind_me = NULL;
1138                         begin_critical_section(S_SESSION_TABLE);
1139                         /*
1140                          * We start where we left off.  If we get to the end
1141                          * we'll start from the beginning again, then give up
1142                          * if we still don't find anything.  This ensures
1143                          * that all contexts get a more-or-less equal chance
1144                          * to run. And yes, I did add a goto to the code. -IO
1145                          */
1146 find_session:           if (next_session == NULL)
1147                                 next_session = ContextList;
1148                         for (ptr = next_session;
1149                             ( (ptr != NULL) && (bind_me == NULL) );
1150                             ptr = ptr->next) {
1151                                 if ( (FD_ISSET(ptr->client_socket, &readfds))
1152                                    && (ptr->state == CON_IDLE) ) {
1153                                         bind_me = ptr;
1154                                 }
1155                         }
1156                         if (bind_me != NULL) {
1157                                 /* Found one.  Stake a claim to it before
1158                                  * letting anyone else touch the context list.
1159                                  */
1160                                 bind_me->state = CON_EXECUTING;
1161                                 next_session = bind_me->next;
1162                         } else if (next_session == ContextList) {
1163                                 next_session = NULL;
1164                         }
1165                         if (bind_me == NULL && next_session != NULL) {
1166                                 next_session = NULL;
1167                                 goto find_session;
1168                         }
1169
1170                         end_critical_section(S_SESSION_TABLE);
1171                         end_critical_section(S_I_WANNA_SELECT);
1172
1173                         /* We're bound to a session, now do *one* command */
1174                         if (bind_me != NULL) {
1175                                 become_session(bind_me);
1176                                 CC->h_command_function();
1177                                 become_session(NULL);
1178                                 bind_me->state = CON_IDLE;
1179                                 if (bind_me->kill_me == 1) {
1180                                         RemoveContext(bind_me);
1181                                 } 
1182                                 write(rescan[1], &junk, 1);
1183                         }
1184
1185                 }
1186                 dead_session_purge();
1187                 do_housekeeping();
1188                 check_sched_shutdown();
1189         }
1190
1191         /* If control reaches this point, the server is shutting down */        
1192         --num_threads;
1193         return NULL;
1194 }
1195
1196
1197
1198
1199 /*
1200  * SyslogFacility()
1201  * Translate text facility name to syslog.h defined value.
1202  */
1203 int SyslogFacility(char *name)
1204 {
1205         int i;
1206         struct
1207         {
1208                 int facility;
1209                 char *name;
1210         }   facTbl[] =
1211         {
1212                 {   LOG_KERN,   "kern"          },
1213                 {   LOG_USER,   "user"          },
1214                 {   LOG_MAIL,   "mail"          },
1215                 {   LOG_DAEMON, "daemon"        },
1216                 {   LOG_AUTH,   "auth"          },
1217                 {   LOG_SYSLOG, "syslog"        },
1218                 {   LOG_LPR,    "lpr"           },
1219                 {   LOG_NEWS,   "news"          },
1220                 {   LOG_UUCP,   "uucp"          },
1221                 {   LOG_LOCAL0, "local0"        },
1222                 {   LOG_LOCAL1, "local1"        },
1223                 {   LOG_LOCAL2, "local2"        },
1224                 {   LOG_LOCAL3, "local3"        },
1225                 {   LOG_LOCAL4, "local4"        },
1226                 {   LOG_LOCAL5, "local5"        },
1227                 {   LOG_LOCAL6, "local6"        },
1228                 {   LOG_LOCAL7, "local7"        },
1229                 {   0,            NULL          }
1230         };
1231         for(i = 0; facTbl[i].name != NULL; i++) {
1232                 if(!strcasecmp(name, facTbl[i].name))
1233                         return facTbl[i].facility;
1234         }
1235         return -1;
1236 }
1237