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