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