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