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