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