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