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