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