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