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