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