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