4a1070b23563876a03ca5b84c10951497888665f
[citadel.git] / citadel / citserver.c
1 /* 
2  * Main source module for the Citadel server
3  *
4  * Copyright (c) 1987-2014 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <stdio.h>
16 #include "sysdep.h"
17 #include <time.h>
18 #if HAVE_BACKTRACE
19 #include <execinfo.h>
20 #endif
21 #include <libcitadel.h>
22
23 #include "ctdl_module.h"
24 #include "housekeeping.h"
25 #include "locate_host.h"
26 #include "citserver.h"
27 #include "user_ops.h"
28 #include "control.h"
29 #include "config.h"
30
31 char *unique_session_numbers;
32 int ScheduledShutdown = 0;
33 time_t server_startup_time;
34 int panic_fd;
35 int openid_level_supported = 0;
36
37 /*
38  * print the actual stack frame.
39  */
40 void cit_backtrace(void)
41 {
42 #ifdef HAVE_BACKTRACE
43         void *stack_frames[50];
44         size_t size, i;
45         char **strings;
46
47         const char *p = IOSTR;
48         if (p == NULL) p = "";
49         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
50         strings = backtrace_symbols(stack_frames, size);
51         for (i = 0; i < size; i++) {
52                 if (strings != NULL)
53                         syslog(LOG_ALERT, "%s %s\n", p, strings[i]);
54                 else
55                         syslog(LOG_ALERT, "%s %p\n", p, stack_frames[i]);
56         }
57         free(strings);
58 #endif
59 }
60
61 void cit_oneline_backtrace(void)
62 {
63 #ifdef HAVE_BACKTRACE
64         void *stack_frames[50];
65         size_t size, i;
66         char **strings;
67         StrBuf *Buf;
68
69         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
70         strings = backtrace_symbols(stack_frames, size);
71         if (size > 0)
72         {
73                 Buf = NewStrBuf();
74                 for (i = 1; i < size; i++) {
75                         if (strings != NULL)
76                                 StrBufAppendPrintf(Buf, "%s : ", strings[i]);
77                         else
78                                 StrBufAppendPrintf(Buf, "%p : ", stack_frames[i]);
79                 }
80                 free(strings);
81                 syslog(LOG_ALERT, "%s %s\n", IOSTR, ChrPtr(Buf));
82                 FreeStrBuf(&Buf);
83         }
84 #endif
85 }
86
87 /*
88  * print the actual stack frame.
89  */
90 void cit_panic_backtrace(int SigNum)
91 {
92 #ifdef HAVE_BACKTRACE
93         void *stack_frames[10];
94         size_t size, i;
95         char **strings;
96
97         printf("caught signal 11\n");
98         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
99         strings = backtrace_symbols(stack_frames, size);
100         for (i = 0; i < size; i++) {
101                 if (strings != NULL)
102                         syslog(LOG_ALERT, "%s\n", strings[i]);
103                 else
104                         syslog(LOG_ALERT, "%p\n", stack_frames[i]);
105         }
106         free(strings);
107 #endif
108         exit(-1);
109 }
110
111 /*
112  * Various things that need to be initialized at startup
113  */
114 void master_startup(void) {
115         struct timeval tv;
116         unsigned int seed;
117         FILE *urandom;
118         struct ctdlroom qrbuf;
119         int rv;
120         struct passwd *pw;
121         gid_t gid;
122         
123         syslog(LOG_DEBUG, "master_startup() started\n");
124         time(&server_startup_time);
125         get_config();
126         validate_config();
127
128         syslog(LOG_INFO, "Checking directory access");
129         if ((pw = getpwuid(CTDLUID)) == NULL) {
130                 gid = getgid();
131         } else {
132                 gid = pw->pw_gid;
133         }
134
135         if (create_run_directories(CTDLUID, gid) != 0) {
136                 syslog(LOG_EMERG, "failed to access & create directories");
137                 exit(1);
138         }
139         syslog(LOG_INFO, "Opening databases");
140         open_databases();
141         check_ref_counts();
142
143         syslog(LOG_INFO, "Creating base rooms (if necessary)\n");
144         CtdlCreateRoom(config.c_baseroom,       0, "", 0, 1, 0, VIEW_BBS);
145         CtdlCreateRoom(AIDEROOM,                3, "", 0, 1, 0, VIEW_BBS);
146         CtdlCreateRoom(SYSCONFIGROOM,           3, "", 0, 1, 0, VIEW_BBS);
147         CtdlCreateRoom(config.c_twitroom,       0, "", 0, 1, 0, VIEW_BBS);
148
149         /* The "Local System Configuration" room doesn't need to be visible */
150         if (CtdlGetRoomLock(&qrbuf, SYSCONFIGROOM) == 0) {
151                 qrbuf.QRflags2 |= QR2_SYSTEM;
152                 CtdlPutRoomLock(&qrbuf);
153         }
154
155         /* Aide needs to be public postable, else we're not RFC conformant. */
156         if (CtdlGetRoomLock(&qrbuf, AIDEROOM) == 0) {
157                 qrbuf.QRflags2 |= QR2_SMTP_PUBLIC;
158                 CtdlPutRoomLock(&qrbuf);
159         }
160
161         syslog(LOG_INFO, "Seeding the pseudo-random number generator...\n");
162         urandom = fopen("/dev/urandom", "r");
163         if (urandom != NULL) {
164                 rv = fread(&seed, sizeof seed, 1, urandom);
165                 if (rv == -1)
166                         syslog(LOG_EMERG, "failed to read random seed: %s\n", 
167                                strerror(errno));
168                 fclose(urandom);
169         }
170         else {
171                 gettimeofday(&tv, NULL);
172                 seed = tv.tv_usec;
173         }
174         srand(seed);
175         srandom(seed);
176
177         put_config();
178
179         syslog(LOG_DEBUG, "master_startup() finished\n");
180 }
181
182
183 /*
184  * Cleanup routine to be called when the server is shutting down.
185  */
186 void master_cleanup(int exitcode) {
187         struct CleanupFunctionHook *fcn;
188         static int already_cleaning_up = 0;
189
190         if (already_cleaning_up) while(1) usleep(1000000);
191         already_cleaning_up = 1;
192
193         /* Run any cleanup routines registered by loadable modules */
194         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
195                 (*fcn->h_function_pointer)();
196         }
197
198         /* Close the AdjRefCount queue file */
199         AdjRefCount(-1, 0);
200
201         /* Do system-dependent stuff */
202         sysdep_master_cleanup();
203         
204         /* Close databases */
205         syslog(LOG_INFO, "Closing databases\n");
206         close_databases();
207
208         /* If the operator requested a halt but not an exit, halt here. */
209         if (shutdown_and_halt) {
210                 syslog(LOG_NOTICE, "citserver: Halting server without exiting.\n");
211                 fflush(stdout); fflush(stderr);
212                 while(1) {
213                         sleep(32767);
214                 }
215         }
216         
217         release_control();
218
219         /* Now go away. */
220         syslog(LOG_NOTICE, "citserver: Exiting with status %d\n", exitcode);
221         fflush(stdout); fflush(stderr);
222         
223         if (restart_server != 0)
224                 exit(1);
225         if ((running_as_daemon != 0) && ((exitcode == 0) ))
226                 exitcode = CTDLEXIT_SHUTDOWN;
227         exit(exitcode);
228 }
229
230
231
232 /*
233  * returns an asterisk if there are any instant messages waiting,
234  * space otherwise.
235  */
236 char CtdlCheckExpress(void) {
237         if (CC->FirstExpressMessage == NULL) {
238                 return(' ');
239         }
240         else {
241                 return('*');
242         }
243 }
244
245
246 /*
247  * Check originating host against the public_clients file.  This determines
248  * whether the client is allowed to change the hostname for this session
249  * (for example, to show the location of the user rather than the location
250  * of the client).
251  */
252 int CtdlIsPublicClient(void)
253 {
254         char buf[1024];
255         char addrbuf[1024];
256         FILE *fp;
257         int i;
258         char *public_clientspos;
259         char *public_clientsend;
260         char *paddr = NULL;
261         struct stat statbuf;
262         static time_t pc_timestamp = 0;
263         static char public_clients[SIZ];
264         static char public_clients_file[SIZ];
265
266 #define LOCALHOSTSTR "127.0.0.1"
267
268         snprintf(public_clients_file, sizeof public_clients_file, "%s/public_clients", ctdl_etc_dir);
269
270         /*
271          * Check the time stamp on the public_clients file.  If it's been
272          * updated since the last time we were here (or if this is the first
273          * time we've been through the loop), read its contents and learn
274          * the IP addresses of the listed hosts.
275          */
276         if (stat(public_clients_file, &statbuf) != 0) {
277                 /* No public_clients file exists, so bail out */
278                 syslog(LOG_WARNING, "Warning: '%s' does not exist\n", 
279                                 public_clients_file);
280                 return(0);
281         }
282
283         if (statbuf.st_mtime > pc_timestamp) {
284                 begin_critical_section(S_PUBLIC_CLIENTS);
285                 syslog(LOG_INFO, "Loading %s\n", public_clients_file);
286
287                 public_clientspos = &public_clients[0];
288                 public_clientsend = public_clientspos + SIZ;
289                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
290                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
291                 
292                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
293                         *(public_clientspos++) = '|';
294                         paddr = &addrbuf[0];
295                         while (!IsEmptyStr (paddr) && 
296                                (public_clientspos < public_clientsend))
297                                 *(public_clientspos++) = *(paddr++);
298                 }
299
300                 fp = fopen(public_clients_file, "r");
301                 if (fp != NULL) 
302                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
303                                (public_clientspos < public_clientsend)){
304                                 char *ptr;
305                                 ptr = buf;
306                                 while (!IsEmptyStr(ptr)) {
307                                         if (*ptr == '#') {
308                                                 *ptr = 0;
309                                                 break;
310                                         }
311                                 else ptr++;
312                                 }
313                                 ptr--;
314                                 while (ptr>buf && isspace(*ptr)) {
315                                         *(ptr--) = 0;
316                                 }
317                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
318                                         *(public_clientspos++) = '|';
319                                         paddr = addrbuf;
320                                         while (!IsEmptyStr(paddr) && 
321                                                (public_clientspos < public_clientsend)){
322                                                 *(public_clientspos++) = *(paddr++);
323                                         }
324                                 }
325                         }
326                 if (fp != NULL) fclose(fp);
327                 pc_timestamp = time(NULL);
328                 end_critical_section(S_PUBLIC_CLIENTS);
329         }
330
331         syslog(LOG_DEBUG, "Checking whether %s is a local or public client\n",
332                 CC->cs_addr);
333         for (i=0; i<num_parms(public_clients); ++i) {
334                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
335                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
336                         syslog(LOG_DEBUG, "... yes its local.\n");
337                         return(1);
338                 }
339         }
340
341         /* No hits.  This is not a public client. */
342         syslog(LOG_DEBUG, "... no it isn't.\n");
343         return(0);
344 }
345
346
347
348
349
350 void citproto_begin_session() {
351         if (CC->nologin==1) {
352                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
353                         ERROR + MAX_SESSIONS_EXCEEDED,
354                         config.c_nodename, config.c_maxsessions
355                 );
356                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
357         }
358         else {
359                 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
360                 CC->can_receive_im = 1;
361         }
362 }
363
364
365 void citproto_begin_admin_session() {
366         CC->internal_pgm = 1;
367         cprintf("%d %s Citadel server ADMIN CONNECTION ready.\n", CIT_OK, config.c_nodename);
368 }
369
370
371
372
373 /*
374  * This loop recognizes all server commands.
375  */
376 void do_command_loop(void) {
377         char cmdbuf[SIZ];
378         
379         time(&CC->lastcmd);
380         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
381         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
382                 syslog(LOG_ERR, "Citadel client disconnected: ending session.\n");
383                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
384                 return;
385         }
386
387         /* Log the server command, but don't show passwords... */
388         if ( (strncasecmp(cmdbuf, "PASS", 4)) && (strncasecmp(cmdbuf, "SETP", 4)) ) {
389                 syslog(LOG_INFO, "[%d][%s(%ld)] %s",
390                         CC->cs_pid, CC->curr_user, CC->user.usernum, cmdbuf
391                 );
392         }
393         else {
394                 syslog(LOG_INFO, "[%d][%s(%ld)] <password command hidden from log>",
395                         CC->cs_pid, CC->curr_user, CC->user.usernum
396                 );
397         }
398
399         buffer_output();
400
401         /*
402          * Let other clients see the last command we executed, and
403          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
404          */
405         if ( (strncasecmp(cmdbuf, "NOOP", 4))
406            && (strncasecmp(cmdbuf, "QNOP", 4))
407            && (strncasecmp(cmdbuf, "PEXP", 4))
408            && (strncasecmp(cmdbuf, "GEXP", 4))
409            && (strncasecmp(cmdbuf, "RWHO", 4))
410            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
411                 strcpy(CC->lastcmdname, "    ");
412                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
413                 time(&CC->lastidle);
414         }
415         
416         if ((strncasecmp(cmdbuf, "ENT0", 4))
417            && (strncasecmp(cmdbuf, "MESG", 4))
418            && (strncasecmp(cmdbuf, "MSGS", 4)))
419         {
420            CC->cs_flags &= ~CS_POSTING;
421         }
422                    
423         if (!DLoader_Exec_Cmd(cmdbuf)) {
424                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
425         }       
426
427         unbuffer_output();
428
429         /* Run any after-each-command routines registered by modules */
430         PerformSessionHooks(EVT_CMD);
431 }
432
433
434 /*
435  * This loop performs all asynchronous functions.
436  */
437 void do_async_loop(void) {
438         PerformSessionHooks(EVT_ASYNC);
439 }
440