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