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