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