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