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