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