* Changed module loading path to simply "modules" because after calling
[citadel.git] / citadel / sysdep.c
1 /*
2  * Citadel/UX "system dependent" stuff.
3  * See copyright.txt for copyright information.
4  *
5  * $Id$
6  *
7  * Here's where we (hopefully) have all the parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * Wherever possible, we use function wrappers and type definitions to create
10  * abstractions that are platform-independent from the calling side.
11  * 
12  * Eventually we'll try porting to a different platform and either have
13  * multiple variants of this file or simply load it up with #ifdefs.
14  */
15
16
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <signal.h>
23 #include <sys/types.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <sys/time.h>
27 #include <limits.h>
28 #include <netinet/in.h>
29 #include <netdb.h>
30 #include <string.h>
31 #include <pwd.h>
32 #include <errno.h>
33 #include <stdarg.h>
34 #include <syslog.h>
35 #include <pthread.h>
36 #include "citadel.h"
37 #include "server.h"
38 #include "sysdep_decls.h"
39 #include "citserver.h"
40 #include "support.h"
41 #include "config.h"
42 #include "database.h"
43 #include "housekeeping.h"
44 #include "dynloader.h"
45 #include "tools.h"
46
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
49 #endif
50
51 #ifndef HAVE_SNPRINTF
52 #include "snprintf.h"
53 #endif
54
55 #ifdef DEBUG_MEMORY_LEAKS
56 struct TheHeap *heap = NULL;
57 #endif
58
59 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
60 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
61
62 int msock;                                      /* master listening socket */
63 int verbosity = 3;                              /* Logging level */
64
65 struct CitContext masterCC;
66
67
68 /*
69  * lprintf()  ...   Write logging information
70  */
71 void lprintf(int loglevel, const char *format, ...) {   
72         va_list arg_ptr;
73         char buf[512];
74   
75         va_start(arg_ptr, format);   
76         vsprintf(buf, format, arg_ptr);   
77         va_end(arg_ptr);   
78
79         if (loglevel <= verbosity) { 
80                 fprintf(stderr, "%s", buf);
81                 fflush(stderr);
82                 }
83
84         PerformLogHooks(loglevel, buf);
85         }   
86
87
88
89 #ifdef DEBUG_MEMORY_LEAKS
90 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
91         void *ptr;
92         struct TheHeap *hptr;
93
94         ptr = malloc(tsize);
95         if (ptr == NULL) return(NULL);
96
97         hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
98         strcpy(hptr->h_file, tfile);
99         hptr->h_line = tline;
100         hptr->next = heap;
101         hptr->h_ptr = ptr;
102         heap = hptr;
103         return ptr;
104         }
105
106
107 void tracked_free(void *ptr) {
108         struct TheHeap *hptr, *freeme;
109
110         if (heap->h_ptr == ptr) {
111                 hptr = heap->next;
112                 free(heap);
113                 heap = hptr;
114                 }
115         else {
116                 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
117                         if (hptr->next->h_ptr == ptr) {
118                                 freeme = hptr->next;
119                                 hptr->next = hptr->next->next;
120                                 free(freeme);
121                                 }
122                         }
123                 }
124
125         free(ptr);
126         }
127
128 void *tracked_realloc(void *ptr, size_t size) {
129         void *newptr;
130         struct TheHeap *hptr;
131         
132         newptr = realloc(ptr, size);
133
134         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
135                 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
136                 }
137
138         return newptr;
139         }
140
141
142 void dump_tracked() {
143         struct TheHeap *hptr;
144
145         cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);    
146         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
147                 cprintf("%20s %5d\n",
148                         hptr->h_file, hptr->h_line);
149                 }
150         cprintf("000\n");
151         }
152 #endif
153
154
155
156 /*
157  * Some initialization stuff...
158  */
159 void init_sysdep(void) {
160         int a;
161
162         /* Set up a bunch of semaphores to be used for critical sections */
163         for (a=0; a<MAX_SEMAPHORES; ++a) {
164                 pthread_mutex_init(&Critters[a], NULL);
165                 }
166
167         /*
168          * Set up a place to put thread-specific data.
169          * We only need a single pointer per thread - it points to the
170          * thread's CitContext structure in the ContextList linked list.
171          */
172         if (pthread_key_create(&MyConKey, NULL) != 0) {
173                 lprintf(1, "Can't create TSD key!!  %s\n", strerror(errno));
174                 }
175
176         /*
177          * The action for unexpected signals and exceptions should be to
178          * call master_cleanup() to gracefully shut down the server.
179          */
180         signal(SIGINT, (void(*)(int))master_cleanup);
181         signal(SIGQUIT, (void(*)(int))master_cleanup);
182         signal(SIGHUP, (void(*)(int))master_cleanup);
183         signal(SIGTERM, (void(*)(int))master_cleanup);
184         signal(SIGPIPE, SIG_IGN);
185         }
186
187
188 /*
189  * Obtain a semaphore lock to begin a critical section.
190  */
191 void begin_critical_section(int which_one)
192 {
193         int oldval;
194
195         /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
196
197         /* Don't get interrupted during the critical section */
198         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
199
200         /* Obtain a semaphore */
201         pthread_mutex_lock(&Critters[which_one]);
202
203         }
204
205 /*
206  * Release a semaphore lock to end a critical section.
207  */
208 void end_critical_section(int which_one)
209 {
210         int oldval;
211
212         /* lprintf(8, "  end_critical_section(%d)\n", which_one); */
213
214         /* Let go of the semaphore */
215         pthread_mutex_unlock(&Critters[which_one]);
216
217         /* If a cancel was sent during the critical section, do it now.
218          * Then re-enable thread cancellation.
219          */
220         pthread_testcancel();
221         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
222         pthread_testcancel();
223
224         }
225
226
227
228 /*
229  * This is a generic function to set up a master socket for listening on
230  * a TCP port.  The server shuts down if the bind fails.
231  */
232 int ig_tcp_server(int port_number, int queue_len)
233 {
234         struct sockaddr_in sin;
235         int s, i;
236
237         memset(&sin, 0, sizeof(sin));
238         sin.sin_family = AF_INET;
239         sin.sin_addr.s_addr = INADDR_ANY;
240
241         if (port_number == 0) {
242                 lprintf(1,
243                         "citserver: No port number specified.  Run setup.\n");
244                 exit(1);
245                 }
246         
247         sin.sin_port = htons((u_short)port_number);
248
249         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
250         if (s < 0) {
251                 lprintf(1, "citserver: Can't create a socket: %s\n",
252                         strerror(errno));
253                 exit(errno);
254                 }
255
256         /* Set the SO_REUSEADDR socket option, because it makes sense. */
257         i = 1;
258         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
259
260         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
261                 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
262                 exit(errno);
263                 }
264
265         if (listen(s, queue_len) < 0) {
266                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
267                 exit(errno);
268                 }
269
270         return(s);
271         }
272
273
274 /*
275  * Return a pointer to a thread's own CitContext structure (old)
276  * NOTE: this version of MyContext() is commented out because it is no longer
277  * in use.  It was written before I discovered TSD keys.  This
278  * version pounds through the context list until it finds the one matching
279  * the currently running thread.  It remains here, commented out, in case it
280  * is needed for future ports to threading libraries which have the equivalent
281  * of pthread_self() but not pthread_key_create() and its ilk.
282  *
283  * struct CitContext *MyContext() {
284  *      struct CitContext *ptr;
285  *      THREAD me;
286  *
287  *      me = pthread_self();
288  *      for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
289  *              if (ptr->mythread == me) return(ptr);
290  *              }
291  *      return(NULL);
292  *      }
293  */
294
295 /*
296  * Return a pointer to a thread's own CitContext structure (new)
297  */
298 struct CitContext *MyContext(void) {
299         struct CitContext *retCC;
300         retCC = (struct CitContext *) pthread_getspecific(MyConKey);
301         if (retCC == NULL) retCC = &masterCC;
302         return(retCC);
303         }
304
305
306 /*
307  * Wedge our way into the context list.
308  */
309 struct CitContext *CreateNewContext(void) {
310         struct CitContext *me;
311
312         lprintf(9, "CreateNewContext: calling malloc()\n");
313         me = (struct CitContext *) mallok(sizeof(struct CitContext));
314         if (me == NULL) {
315                 lprintf(1, "citserver: can't allocate memory!!\n");
316                 pthread_exit(NULL);
317                 }
318         memset(me, 0, sizeof(struct CitContext));
319
320         begin_critical_section(S_SESSION_TABLE);
321         me->next = ContextList;
322         ContextList = me;
323         end_critical_section(S_SESSION_TABLE);
324         return(me);
325         }
326
327 /*
328  * Add a thread's thread ID to the context
329  */
330 void InitMyContext(struct CitContext *con)
331 {
332         int oldval;
333
334         con->mythread = pthread_self();
335         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
336         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
337         if (pthread_setspecific(MyConKey, (void *)con) != 0) {
338                 lprintf(1, "ERROR!  pthread_setspecific() failed: %s\n",
339                         strerror(errno));
340                 }
341         }
342
343 /*
344  * Remove a context from the context list.
345  */
346 void RemoveContext(struct CitContext *con)
347 {
348         struct CitContext *ptr;
349
350         lprintf(7, "Starting RemoveContext()\n");
351         lprintf(9, "Session count before RemoveContext is %d\n",
352                 session_count());
353         if (con==NULL) {
354                 lprintf(7, "WARNING: RemoveContext() called with null!\n");
355                 return;
356                 }
357
358         /*
359          * session_count() starts its own S_SESSION_TABLE critical section;
360          * so do not call it from within this loop.
361          */
362         begin_critical_section(S_SESSION_TABLE);
363         lprintf(7, "Closing socket %d\n", con->client_socket);
364         close(con->client_socket);
365
366         lprintf(9, "Dereferencing session context\n");
367         if (ContextList==con) {
368                 ContextList = ContextList->next;
369                 }
370         else {
371                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
372                         if (ptr->next == con) {
373                                 ptr->next = con->next;
374                                 }
375                         }
376                 }
377
378         lprintf(9, "Freeing session context...\n");     
379         phree(con);
380         lprintf(9, "...done.\n");
381         end_critical_section(S_SESSION_TABLE);
382
383         lprintf(9, "Session count after RemoveContext is %d\n",
384                 session_count());
385
386         lprintf(7, "Done with RemoveContext\n");
387         }
388
389
390 /*
391  * Return the number of sessions currently running.
392  * (This should probably be moved out of sysdep.c)
393  */
394 int session_count(void) {
395         struct CitContext *ptr;
396         int TheCount = 0;
397
398         lprintf(9, "session_count() starting\n");
399         begin_critical_section(S_SESSION_TABLE);
400         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
401                 ++TheCount;
402                 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
403                 }
404         end_critical_section(S_SESSION_TABLE);
405
406         lprintf(9, "session_count() finishing\n");
407         return(TheCount);
408         }
409
410
411 /*
412  * client_write()   ...    Send binary data to the client.
413  */
414 void client_write(char *buf, int nbytes)
415 {
416         int bytes_written = 0;
417         int retval;
418         while (bytes_written < nbytes) {
419                 retval = write(CC->client_socket, &buf[bytes_written],
420                         nbytes - bytes_written);
421                 if (retval < 1) {
422                         lprintf(2, "client_write() failed: %s\n",
423                                 strerror(errno));
424                         cleanup(errno);
425                         }
426                 bytes_written = bytes_written + retval;
427                 }
428         }
429
430
431 /*
432  * cprintf()  ...   Send formatted printable data to the client.   It is
433  *                  implemented in terms of client_write() but remains in
434  *                  sysdep.c in case we port to somewhere without va_args...
435  */
436 void cprintf(const char *format, ...) {   
437         va_list arg_ptr;   
438         char buf[256];   
439    
440         va_start(arg_ptr, format);   
441         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
442                 buf[sizeof buf - 2] = '\n';
443         client_write(buf, strlen(buf)); 
444         va_end(arg_ptr);
445         }   
446
447
448 /*
449  * Read data from the client socket.
450  * Return values are:
451  *      1       Requested number of bytes has been read.
452  *      0       Request timed out.
453  * If the socket breaks, the session is immediately terminated.
454  */
455 int client_read_to(char *buf, int bytes, int timeout)
456 {
457         int len,rlen;
458         fd_set rfds;
459         struct timeval tv;
460         int retval;
461
462         len = 0;
463         while(len<bytes) {
464                 FD_ZERO(&rfds);
465                 FD_SET(CC->client_socket, &rfds);
466                 tv.tv_sec = timeout;
467                 tv.tv_usec = 0;
468
469                 retval = select( (CC->client_socket)+1, 
470                                         &rfds, NULL, NULL, &tv);
471                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
472                         return(0);
473                         }
474
475                 rlen = read(CC->client_socket, &buf[len], bytes-len);
476                 if (rlen<1) {
477                         lprintf(2, "client_read() failed: %s\n",
478                                 strerror(errno));
479                         cleanup(errno);
480                         }
481                 len = len + rlen;
482                 }
483         return(1);
484         }
485
486 /*
487  * Read data from the client socket with default timeout.
488  * (This is implemented in terms of client_read_to() and could be
489  * justifiably moved out of sysdep.c)
490  */
491 int client_read(char *buf, int bytes)
492 {
493         return(client_read_to(buf, bytes, config.c_sleeping));
494         }
495
496
497 /*
498  * client_gets()   ...   Get a LF-terminated line of text from the client.
499  * (This is implemented in terms of client_read() and could be
500  * justifiably moved out of sysdep.c)
501  */
502 int client_gets(char *buf)
503 {
504         int i, retval;
505
506         /* Read one character at a time.
507          */
508         for (i = 0;;i++) {
509                 retval = client_read(&buf[i], 1);
510                 if (retval != 1 || buf[i] == '\n' || i == 255)
511                         break;
512                 }
513
514         /* If we got a long line, discard characters until the newline.
515          */
516         if (i == 255)
517                 while (buf[i] != '\n' && retval == 1)
518                         retval = client_read(&buf[i], 1);
519
520         /* Strip the trailing newline and any trailing nonprintables (cr's)
521          */
522         buf[i] = 0;
523         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
524                 buf[strlen(buf)-1] = 0;
525         return(retval);
526         }
527
528
529
530 /*
531  * The system-dependent part of master_cleanup() - close the master socket.
532  */
533 void sysdep_master_cleanup(void) {
534         lprintf(7, "Closing master socket %d\n", msock);
535         close(msock);
536         }
537
538 /*
539  * Cleanup routine to be called when one thread is shutting down.
540  */
541 void cleanup(int exit_code)
542 {
543         /* Terminate the thread.
544          * Its cleanup handler will call cleanup_stuff()
545          */
546         lprintf(7, "Calling pthread_exit()\n");
547         pthread_exit(NULL);
548         }
549
550 /*
551  * Terminate another session.
552  */
553 void kill_session(int session_to_kill) {
554         struct CitContext *ptr;
555         THREAD killme = 0;
556
557         lprintf(9, "kill_session() scanning for thread to cancel...\n");
558         begin_critical_section(S_SESSION_TABLE);
559         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
560                 if (ptr->cs_pid == session_to_kill) {
561                         killme = ptr->mythread;
562                         }
563                 }
564         end_critical_section(S_SESSION_TABLE);
565         lprintf(9, "kill_session() finished scanning.\n");
566
567         if (killme != 0) {
568                 lprintf(9, "calling pthread_cancel()\n");
569                 pthread_cancel(killme);
570                 }
571         }
572
573
574 /*
575  * The system-dependent wrapper around the main context loop.
576  */
577 void *sd_context_loop(struct CitContext *con) {
578         pthread_cleanup_push(*cleanup_stuff, NULL);
579         context_loop(con);
580         pthread_cleanup_pop(0);
581         return NULL;
582         }
583
584
585 /*
586  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
587  */
588 void start_daemon(int do_close_stdio) {
589         if (do_close_stdio) {
590                 /* close(0); */
591                 close(1);
592                 close(2);
593                 }
594         signal(SIGHUP,SIG_IGN);
595         signal(SIGINT,SIG_IGN);
596         signal(SIGQUIT,SIG_IGN);
597         if (fork()!=0) exit(0);
598         }
599
600
601
602 /*
603  * Tie in to the 'netsetup' program.
604  *
605  * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
606  */
607 void cmd_nset(char *cmdbuf)
608 {
609         int retcode;
610         char fbuf[4096];
611         FILE *netsetup;
612         int ch;
613         int a, b;
614         char netsetup_args[3][256];
615
616         if (CC->usersupp.axlevel < 6) {
617                 cprintf("%d Higher access required.\n", 
618                         ERROR + HIGHER_ACCESS_REQUIRED);
619                 return;
620                 }
621
622         for (a=1; a<=3; ++a) {
623                 if (num_parms(cmdbuf) >= a) {
624                         extract(netsetup_args[a-1], cmdbuf, a-1);
625                         for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
626                                 if (netsetup_args[a-1][b] == 34) {
627                                         netsetup_args[a-1][b] = '_';
628                                         }
629                                 }
630                         }
631                 else {
632                         netsetup_args[a-1][0] = 0;
633                         }
634                 }
635
636         sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
637                 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
638         netsetup = popen(fbuf, "r");
639         if (netsetup == NULL) {
640                 cprintf("%d %s\n", ERROR, strerror(errno));
641                 return;
642                 }
643
644         fbuf[0] = 0;
645         while (ch = getc(netsetup), (ch > 0)) {
646                 fbuf[strlen(fbuf)+1] = 0;
647                 fbuf[strlen(fbuf)] = ch;
648                 }
649
650         retcode = pclose(netsetup);
651
652         if (retcode != 0) {
653                 for (a=0; a<strlen(fbuf); ++a) {
654                         if (fbuf[a] < 32) fbuf[a] = 32;
655                         }
656                 fbuf[245] = 0;
657                 cprintf("%d %s\n", ERROR, fbuf);
658                 return;
659                 }
660
661         cprintf("%d Command succeeded.  Output follows:\n", LISTING_FOLLOWS);
662         cprintf("%s", fbuf);
663         if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
664         cprintf("000\n");
665         }
666
667
668
669 /*
670  * Generic routine to convert a login name to a full name (gecos)
671  * Returns nonzero if a conversion took place
672  */
673 int convert_login(char NameToConvert[]) {
674         struct passwd *pw;
675         int a;
676
677         pw = getpwnam(NameToConvert);
678         if (pw == NULL) {
679                 return(0);
680                 }
681         else {
682                 strcpy(NameToConvert, pw->pw_gecos);
683                 for (a=0; a<strlen(NameToConvert); ++a) {
684                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
685                         }
686                 return(1);
687                 }
688         }
689
690
691
692
693         
694
695 /*
696  * Here's where it all begins.
697  */
698 int main(int argc, char **argv)
699 {
700         struct sockaddr_in fsin;        /* Data for master socket */
701         int alen;                       /* Data for master socket */
702         int ssock;                      /* Descriptor for master socket */
703         THREAD SessThread;              /* Thread descriptor */
704         pthread_attr_t attr;            /* Thread attributes */
705         struct CitContext *con;         /* Temporary context pointer */
706         char tracefile[128];            /* Name of file to log traces to */
707         int a, i;                       /* General-purpose variables */
708         char convbuf[128];
709         
710         /* specify default port name and trace file */
711         strcpy(tracefile, "");
712
713         /* parse command-line arguments */
714         for (a=1; a<argc; ++a) {
715
716                 /* -t specifies where to log trace messages to */
717                 if (!strncmp(argv[a], "-t", 2)) {
718                         strcpy(tracefile, argv[a]);
719                         strcpy(tracefile, &tracefile[2]);
720                         freopen(tracefile, "r", stdin);
721                         freopen(tracefile, "w", stdout);
722                         freopen(tracefile, "w", stderr);
723                         }
724
725                 /* run in the background if -d was specified */
726                 else if (!strcmp(argv[a], "-d")) {
727                         start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
728                         }
729
730                 /* -x specifies the desired logging level */
731                 else if (!strncmp(argv[a], "-x", 2)) {
732                         strcpy(convbuf, argv[a]);
733                         verbosity = atoi(&convbuf[2]);
734                         }
735
736                 else if (!strncmp(argv[a], "-h", 2)) {
737                         strcpy(convbuf, argv[a]);
738                         strcpy(bbs_home_directory, &convbuf[2]);
739                         home_specified = 1;
740                         }
741
742                 /* any other parameter makes it crash and burn */
743                 else {
744                         lprintf(1, "citserver: usage: ");
745                         lprintf(1, "citserver [-tTraceFile]");
746                         lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
747                         exit(1);
748                         }
749
750                 }
751
752         /* Tell 'em who's in da house */
753         lprintf(1, "Multithreaded message server for %s\n", CITADEL);
754         lprintf(1, "Copyright (C) 1987-1998 by Art Cancro.  ");
755         lprintf(1, "All rights reserved.\n\n");
756
757         /* Initialize... */
758         init_sysdep();
759         openlog("citserver",LOG_PID,LOG_USER);
760         /* Load site-specific parameters */
761         lprintf(7, "Loading citadel.config\n");
762         get_config();
763
764         lprintf(7, "Initializing loadable modules\n");
765         DLoader_Init("./modules");
766         lprintf(9, "Modules done initializing.\n");
767
768         /* Do non system dependent startup functions */
769         master_startup();
770
771         /*
772          * Bind the server to our favourite port.
773          * There is no need to check for errors, because ig_tcp_server()
774          * exits if it doesn't succeed.
775          */
776         lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
777         msock = ig_tcp_server(config.c_port_number, 5);
778         lprintf(7, "Listening on socket %d\n", msock);
779
780         /*
781          * Now that we've bound the socket, change to the BBS user id
782         lprintf(7, "Changing uid to %d\n", BBSUID);
783         if (setuid(BBSUID) != 0) {
784                 lprintf(3, "setuid() failed: %s", strerror(errno));
785                 }
786          */
787
788         /* 
789          * Endless loop.  Listen on the master socket.  When a connection
790          * comes in, create a socket, a context, and a thread.
791          */     
792         while (1) {
793                 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
794                 if (ssock < 0) {
795                         lprintf(2, "citserver: accept() failed: %s\n",
796                                 strerror(errno));
797                         }
798                 else {
799                         lprintf(7, "citserver: Client socket %d\n", ssock);
800                         lprintf(9, "creating context\n");
801                         con = CreateNewContext();
802                         con->client_socket = ssock;
803
804                         /* Set the SO_REUSEADDR socket option */
805                         lprintf(9, "setting socket options\n");
806                         i = 1;
807                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
808                                 &i, sizeof(i));
809
810                         /* set attributes for the new thread */
811                         lprintf(9, "setting thread attributes\n");
812                         pthread_attr_init(&attr);
813                         pthread_attr_setdetachstate(&attr,
814                                 PTHREAD_CREATE_DETACHED);
815
816                         /* now create the thread */
817                         lprintf(9, "creating thread\n");
818                         if (pthread_create(&SessThread, &attr,
819                                            (void* (*)(void*)) sd_context_loop,
820                                            con)
821                             != 0) {
822                                 lprintf(1,
823                                         "citserver: can't create thread: %s\n",
824                                         strerror(errno));
825                                 }
826
827                         /* detach the thread 
828                          * (defunct -- now done at thread creation time)
829                          * if (pthread_detach(&SessThread) != 0) {
830                          *      lprintf(1,
831                          *              "citserver: can't detach thread: %s\n",
832                          *              strerror(errno));
833                          *      }
834                          */
835                         lprintf(9, "done!\n");
836                         }
837                 }
838         }
839