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