71ec7e05e935dfcf5a1b945fdc9729ba367c61d8
[citadel.git] / citadel / citserver.c
1 /* 
2  * Main source module for the Citadel server
3  *
4  * Copyright (c) 1987-2010 by the citadel.org team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
32 # include <time.h>
33 #else
34 # if HAVE_SYS_TIME_H
35 #  include <sys/time.h>
36 # else
37 #  include <time.h>
38 # endif
39 #endif
40
41 #if HAVE_BACKTRACE
42 #include <execinfo.h>
43 #endif
44
45 #include <ctype.h>
46 #include <string.h>
47 #include <dirent.h>
48 #include <errno.h>
49 #include <limits.h>
50 #include <netdb.h>
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <libcitadel.h>
56 #include "citadel.h"
57 #include "server.h"
58 #include "sysdep_decls.h"
59 #include "threads.h"
60 #include "citserver.h"
61 #include "config.h"
62 #include "database.h"
63 #include "housekeeping.h"
64 #include "user_ops.h"
65 #include "msgbase.h"
66 #include "support.h"
67 #include "locate_host.h"
68 #include "room_ops.h"
69 #include "file_ops.h"
70 #include "control.h"
71 #include "euidindex.h"
72 #include "context.h"
73 #include "svn_revision.h"
74
75 #ifndef HAVE_SNPRINTF
76 #include "snprintf.h"
77 #endif
78
79 #include "ctdl_module.h"
80
81 char *unique_session_numbers;
82 int ScheduledShutdown = 0;
83 time_t server_startup_time;
84 int panic_fd;
85
86 /*
87  * print the actual stack frame.
88  */
89 void cit_backtrace(void)
90 {
91 #ifdef HAVE_BACKTRACE
92         void *stack_frames[50];
93         size_t size, i;
94         char **strings;
95
96
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                         CtdlLogPrintf(CTDL_ALERT, "%s\n", strings[i]);
102                 else
103                         CtdlLogPrintf(CTDL_ALERT, "%p\n", stack_frames[i]);
104         }
105         free(strings);
106 #endif
107 }
108
109 void cit_oneline_backtrace(void)
110 {
111 #ifdef HAVE_BACKTRACE
112         void *stack_frames[50];
113         size_t size, i;
114         char **strings;
115         StrBuf *Buf;
116
117         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
118         strings = backtrace_symbols(stack_frames, size);
119         if (size > 0)
120         {
121                 Buf = NewStrBuf();
122                 for (i = 1; i < size; i++) {
123                         if (strings != NULL)
124                                 StrBufAppendPrintf(Buf, "%s : ", strings[i]);
125                         else
126                                 StrBufAppendPrintf(Buf, "%p : ", stack_frames[i]);
127                 }
128                 free(strings);
129                 CtdlLogPrintf(CTDL_ALERT, "%s\n", ChrPtr(Buf));
130                 FreeStrBuf(&Buf);
131         }
132 #endif
133 }
134
135 /*
136  * print the actual stack frame.
137  */
138 void cit_panic_backtrace(int SigNum)
139 {
140 #ifdef HAVE_BACKTRACE
141         void *stack_frames[10];
142         size_t size, i;
143         char **strings;
144
145         printf("caught signal 11\n");
146         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
147         strings = backtrace_symbols(stack_frames, size);
148         for (i = 0; i < size; i++) {
149                 if (strings != NULL)
150                         CtdlLogPrintf(CTDL_ALERT, "%s\n", strings[i]);
151                 else
152                         CtdlLogPrintf(CTDL_ALERT, "%p\n", stack_frames[i]);
153         }
154         free(strings);
155 #endif
156         exit(-1);
157 }
158
159 /*
160  * Various things that need to be initialized at startup
161  */
162 void master_startup(void) {
163         struct timeval tv;
164         unsigned int seed;
165         FILE *urandom;
166         struct ctdlroom qrbuf;
167         int rv;
168         
169         CtdlLogPrintf(CTDL_DEBUG, "master_startup() started\n");
170         time(&server_startup_time);
171
172         CtdlLogPrintf(CTDL_INFO, "Opening databases\n");
173         open_databases();
174
175         ctdl_thread_internal_init_tsd();
176         
177         CtdlThreadAllocTSD();
178         
179         check_ref_counts();
180
181         CtdlLogPrintf(CTDL_INFO, "Creating base rooms (if necessary)\n");
182         CtdlCreateRoom(config.c_baseroom,       0, "", 0, 1, 0, VIEW_BBS);
183         CtdlCreateRoom(AIDEROOM,                3, "", 0, 1, 0, VIEW_BBS);
184         CtdlCreateRoom(SYSCONFIGROOM,           3, "", 0, 1, 0, VIEW_BBS);
185         CtdlCreateRoom(config.c_twitroom,       0, "", 0, 1, 0, VIEW_BBS);
186
187         /* The "Local System Configuration" room doesn't need to be visible */
188         if (CtdlGetRoomLock(&qrbuf, SYSCONFIGROOM) == 0) {
189                 qrbuf.QRflags2 |= QR2_SYSTEM;
190                 CtdlPutRoomLock(&qrbuf);
191         }
192
193         /* Aide needs to be public postable, else we're not RFC conformant. */
194         if (CtdlGetRoomLock(&qrbuf, AIDEROOM) == 0) {
195                 qrbuf.QRflags2 |= QR2_SMTP_PUBLIC;
196                 CtdlPutRoomLock(&qrbuf);
197         }
198
199         CtdlLogPrintf(CTDL_INFO, "Seeding the pseudo-random number generator...\n");
200         urandom = fopen("/dev/urandom", "r");
201         if (urandom != NULL) {
202                 rv = fread(&seed, sizeof seed, 1, urandom);
203                 fclose(urandom);
204         }
205         else {
206                 gettimeofday(&tv, NULL);
207                 seed = tv.tv_usec;
208         }
209         srand(seed);
210         srandom(seed);
211
212         CtdlLogPrintf(CTDL_INFO, "Initializing ipgm secret\n");
213         get_config();
214         config.c_ipgm_secret = rand();
215         put_config();
216
217         CtdlLogPrintf(CTDL_DEBUG, "master_startup() finished\n");
218 }
219
220
221 /*
222  * Cleanup routine to be called when the server is shutting down.
223  */
224 void master_cleanup(int exitcode) {
225         struct CleanupFunctionHook *fcn;
226         static int already_cleaning_up = 0;
227
228         if (already_cleaning_up) while(1) sleep(1);
229         already_cleaning_up = 1;
230
231         /* Run any cleanup routines registered by loadable modules */
232         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
233                 (*fcn->h_function_pointer)();
234         }
235
236         /* Close the AdjRefCount queue file */
237         AdjRefCount(-1, 0);
238
239         /* Do system-dependent stuff */
240         sysdep_master_cleanup();
241         
242         /* Close databases */
243         CtdlLogPrintf(CTDL_INFO, "Closing databases\n");
244         close_databases();
245
246 #ifdef DEBUG_MEMORY_LEAKS
247         dump_heap();
248 #endif
249
250         /* If the operator requested a halt but not an exit, halt here. */
251         if (shutdown_and_halt) {
252                 CtdlLogPrintf(CTDL_NOTICE, "citserver: Halting server without exiting.\n");
253                 fflush(stdout); fflush(stderr);
254                 while(1) {
255                         sleep(32767);
256                 }
257         }
258         
259         release_control();
260
261         /* Now go away. */
262         CtdlLogPrintf(CTDL_NOTICE, "citserver: Exiting with status %d\n", exitcode);
263         fflush(stdout); fflush(stderr);
264         
265         if (restart_server != 0)
266                 exit(1);
267         if ((running_as_daemon != 0) && ((exitcode == 0) ))
268                 exitcode = CTDLEXIT_SHUTDOWN;
269         exit(exitcode);
270 }
271
272
273
274 /*
275  * cmd_info()  -  tell the client about this server
276  */
277 void cmd_info(char *cmdbuf) {
278         cprintf("%d Server info:\n", LISTING_FOLLOWS);
279         cprintf("%d\n", CC->cs_pid);
280         cprintf("%s\n", config.c_nodename);
281         cprintf("%s\n", config.c_humannode);
282         cprintf("%s\n", config.c_fqdn);
283         cprintf("%s\n", CITADEL);
284         cprintf("%d\n", REV_LEVEL);
285         cprintf("%s\n", config.c_site_location);
286         cprintf("%s\n", config.c_sysadm);
287         cprintf("%d\n", SERVER_TYPE);
288         cprintf("%s\n", config.c_moreprompt);
289         cprintf("1\n"); /* 1 = yes, this system supports floors */
290         cprintf("1\n"); /* 1 = we support the extended paging options */
291         cprintf("%s\n", CC->cs_nonce);
292         cprintf("1\n"); /* 1 = yes, this system supports the QNOP command */
293
294 #ifdef HAVE_LDAP
295         cprintf("1\n"); /* 1 = yes, this server is LDAP-enabled */
296 #else
297         cprintf("0\n"); /* 1 = no, this server is not LDAP-enabled */
298 #endif
299
300         if (config.c_auth_mode == AUTHMODE_NATIVE) {
301                 cprintf("%d\n", config.c_disable_newu);
302         }
303         else {
304                 cprintf("1\n"); /* "create new user" does not work with non-native auth modes */
305         }
306
307         cprintf("%s\n", config.c_default_cal_zone);
308
309         /* Output load averages */
310         cprintf("%f\n", CtdlThreadLoadAvg);
311         cprintf("%f\n", CtdlThreadWorkerAvg);
312         cprintf("%d\n", CtdlThreadGetCount());
313
314         cprintf("1\n");         /* yes, Sieve mail filtering is supported */
315         cprintf("%d\n", config.c_enable_fulltext);
316         cprintf("%s\n", svn_revision());
317
318         if (config.c_auth_mode == AUTHMODE_NATIVE) {
319                 cprintf("1\n"); /* OpenID is enabled when using native auth */
320         }
321         else {
322                 cprintf("0\n"); /* OpenID is disabled when using non-native auth */
323         }
324
325         cprintf("%d\n", config.c_guest_logins);
326         
327         cprintf("000\n");
328 }
329
330
331 /*
332  * returns an asterisk if there are any instant messages waiting,
333  * space otherwise.
334  */
335 char CtdlCheckExpress(void) {
336         if (CC->FirstExpressMessage == NULL) {
337                 return(' ');
338         }
339         else {
340                 return('*');
341         }
342 }
343
344 void cmd_time(char *argbuf)
345 {
346    time_t tv;
347    struct tm tmp;
348    
349    tv = time(NULL);
350    localtime_r(&tv, &tmp);
351    
352    /* timezone and daylight global variables are not portable. */
353 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
354    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, tmp.tm_gmtoff, tmp.tm_isdst);
355 #else
356    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, timezone, tmp.tm_isdst);
357 #endif
358 }
359
360
361 /*
362  * Check originating host against the public_clients file.  This determines
363  * whether the client is allowed to change the hostname for this session
364  * (for example, to show the location of the user rather than the location
365  * of the client).
366  */
367 int is_public_client(void)
368 {
369         char buf[1024];
370         char addrbuf[1024];
371         FILE *fp;
372         int i;
373         char *public_clientspos;
374         char *public_clientsend;
375         char *paddr = NULL;
376         struct stat statbuf;
377         static time_t pc_timestamp = 0;
378         static char public_clients[SIZ];
379         static char public_clients_file[SIZ];
380
381 #define LOCALHOSTSTR "127.0.0.1"
382
383         snprintf(public_clients_file, sizeof public_clients_file, "%s/public_clients", ctdl_etc_dir);
384
385         /*
386          * Check the time stamp on the public_clients file.  If it's been
387          * updated since the last time we were here (or if this is the first
388          * time we've been through the loop), read its contents and learn
389          * the IP addresses of the listed hosts.
390          */
391         if (stat(public_clients_file, &statbuf) != 0) {
392                 /* No public_clients file exists, so bail out */
393                 CtdlLogPrintf(CTDL_WARNING, "Warning: '%s' does not exist\n", 
394                                 public_clients_file);
395                 return(0);
396         }
397
398         if (statbuf.st_mtime > pc_timestamp) {
399                 begin_critical_section(S_PUBLIC_CLIENTS);
400                 CtdlLogPrintf(CTDL_INFO, "Loading %s\n", public_clients_file);
401
402                 public_clientspos = &public_clients[0];
403                 public_clientsend = public_clientspos + SIZ;
404                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
405                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
406                 
407                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
408                         *(public_clientspos++) = '|';
409                         paddr = &addrbuf[0];
410                         while (!IsEmptyStr (paddr) && 
411                                (public_clientspos < public_clientsend))
412                                 *(public_clientspos++) = *(paddr++);
413                 }
414
415                 fp = fopen(public_clients_file, "r");
416                 if (fp != NULL) 
417                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
418                                (public_clientspos < public_clientsend)){
419                                 char *ptr;
420                                 ptr = buf;
421                                 while (!IsEmptyStr(ptr)) {
422                                         if (*ptr == '#') {
423                                                 *ptr = 0;
424                                                 break;
425                                         }
426                                 else ptr++;
427                                 }
428                                 ptr--;
429                                 while (ptr>buf && isspace(*ptr)) {
430                                         *(ptr--) = 0;
431                                 }
432                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
433                                         *(public_clientspos++) = '|';
434                                         paddr = addrbuf;
435                                         while (!IsEmptyStr(paddr) && 
436                                                (public_clientspos < public_clientsend)){
437                                                 *(public_clientspos++) = *(paddr++);
438                                         }
439                                 }
440                         }
441                 fclose(fp);
442                 pc_timestamp = time(NULL);
443                 end_critical_section(S_PUBLIC_CLIENTS);
444         }
445
446         CtdlLogPrintf(CTDL_DEBUG, "Checking whether %s is a local or public client\n",
447                 CC->cs_addr);
448         for (i=0; i<num_parms(public_clients); ++i) {
449                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
450                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
451                         CtdlLogPrintf(CTDL_DEBUG, "... yes it is.\n");
452                         return(1);
453                 }
454         }
455
456         /* No hits.  This is not a public client. */
457         CtdlLogPrintf(CTDL_DEBUG, "... no it isn't.\n");
458         return(0);
459 }
460
461
462 /*
463  * the client is identifying itself to the server
464  */
465 void cmd_iden(char *argbuf)
466 {
467         int dev_code;
468         int cli_code;
469         int rev_level;
470         char desc[128];
471         char from_host[128];
472
473         if (num_parms(argbuf)<4) {
474                 cprintf("%d usage error\n", ERROR + ILLEGAL_VALUE);
475                 return;
476         }
477
478         dev_code = extract_int(argbuf,0);
479         cli_code = extract_int(argbuf,1);
480         rev_level = extract_int(argbuf,2);
481         extract_token(desc, argbuf, 3, '|', sizeof desc);
482
483         safestrncpy(from_host, config.c_fqdn, sizeof from_host);
484         from_host[sizeof from_host - 1] = 0;
485         if (num_parms(argbuf)>=5) extract_token(from_host, argbuf, 4, '|', sizeof from_host);
486
487         CC->cs_clientdev = dev_code;
488         CC->cs_clienttyp = cli_code;
489         CC->cs_clientver = rev_level;
490         safestrncpy(CC->cs_clientname, desc, sizeof CC->cs_clientname);
491         CC->cs_clientname[31] = 0;
492
493         /* For local sockets and public clients, trust the hostname supplied by the client */
494         if ( (CC->is_local_socket) || (is_public_client()) ) {
495                 safestrncpy(CC->cs_host, from_host, sizeof CC->cs_host);
496                 CC->cs_host[sizeof CC->cs_host - 1] = 0;
497                 CC->cs_addr[0] = 0;
498         }
499
500         CtdlLogPrintf(CTDL_NOTICE, "Client %d/%d/%01d.%02d (%s) from %s\n",
501                 dev_code,
502                 cli_code,
503                 (rev_level / 100),
504                 (rev_level % 100),
505                 desc,
506                 CC->cs_host
507         );
508         cprintf("%d Ok\n",CIT_OK);
509 }
510
511 typedef const char *ccharp;
512 /*
513  * display system messages or help
514  */
515 void cmd_mesg(char *mname)
516 {
517         FILE *mfp;
518         char targ[256];
519         char buf[256];
520         char buf2[256];
521         char *dirs[2];
522         DIR *dp;
523         struct dirent *d;
524
525         extract_token(buf, mname, 0, '|', sizeof buf);
526
527         dirs[0] = strdup(ctdl_message_dir);
528         dirs[1] = strdup(ctdl_hlp_dir);
529
530         snprintf(buf2, sizeof buf2, "%s.%d.%d",
531                 buf, CC->cs_clientdev, CC->cs_clienttyp);
532
533         /* If the client requested "?" then produce a listing */
534         if (!strcmp(buf, "?")) {
535                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
536                 dp = opendir(dirs[1]);
537                 if (dp != NULL) {
538                         while (d = readdir(dp), d != NULL) {
539                                 if (d->d_name[0] != '.') {
540                                         cprintf(" %s\n", d->d_name);
541                                 }
542                         }
543                         closedir(dp);
544                 }
545                 cprintf("000\n");
546                 free(dirs[0]);
547                 free(dirs[1]);
548                 return;
549         }
550
551         /* Otherwise, look for the requested file by name. */
552         else {
553                 mesg_locate(targ, sizeof targ, buf2, 2, (const ccharp*)dirs);
554                 if (IsEmptyStr(targ)) {
555                         snprintf(buf2, sizeof buf2, "%s.%d",
556                                                         buf, CC->cs_clientdev);
557                         mesg_locate(targ, sizeof targ, buf2, 2,
558                                     (const ccharp*)dirs);
559                         if (IsEmptyStr(targ)) {
560                                 mesg_locate(targ, sizeof targ, buf, 2,
561                                             (const ccharp*)dirs);
562                         }       
563                 }
564         }
565
566         free(dirs[0]);
567         free(dirs[1]);
568
569         if (IsEmptyStr(targ)) {
570                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
571                         ERROR + FILE_NOT_FOUND,
572                         mname,
573                         ctdl_message_dir,
574                         ctdl_hlp_dir
575                 );
576                 return;
577         }
578
579         mfp = fopen(targ, "r");
580         if (mfp==NULL) {
581                 cprintf("%d Cannot open '%s': %s\n",
582                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
583                 return;
584         }
585         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
586
587         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
588                 buf[strlen(buf)-1] = 0;
589                 do_help_subst(buf);
590                 cprintf("%s\n",buf);
591         }
592
593         fclose(mfp);
594         cprintf("000\n");
595 }
596
597
598 /*
599  * enter system messages or help
600  */
601 void cmd_emsg(char *mname)
602 {
603         FILE *mfp;
604         char targ[256];
605         char buf[256];
606         char *dirs[2];
607         int a;
608
609         unbuffer_output();
610
611         if (CtdlAccessCheck(ac_aide)) return;
612
613         extract_token(buf, mname, 0, '|', sizeof buf);
614         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
615                 if (buf[a] == '/') buf[a] = '.';
616         }
617
618         dirs[0] = strdup(ctdl_message_dir);
619         dirs[1] = strdup(ctdl_hlp_dir);
620
621         mesg_locate(targ, sizeof targ, buf, 2, (const ccharp*)dirs);
622         free(dirs[0]);
623         free(dirs[1]);
624
625         if (IsEmptyStr(targ)) {
626                 snprintf(targ, sizeof targ, 
627                                  "%s/%s",
628                                  ctdl_hlp_dir, buf);
629         }
630
631         mfp = fopen(targ,"w");
632         if (mfp==NULL) {
633                 cprintf("%d Cannot open '%s': %s\n",
634                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
635                 return;
636         }
637         cprintf("%d %s\n", SEND_LISTING, targ);
638
639         while (client_getln(buf, sizeof buf) >=0 && strcmp(buf, "000")) {
640                 fprintf(mfp, "%s\n", buf);
641         }
642
643         fclose(mfp);
644 }
645
646
647 /* Don't show the names of private rooms unless the viewing
648  * user also knows the rooms.
649  */
650 void GenerateRoomDisplay(char *real_room,
651                         CitContext *viewed,
652                         CitContext *viewer) {
653
654         int ra;
655
656         strcpy(real_room, viewed->room.QRname);
657         if (viewed->room.QRflags & QR_MAILBOX) {
658                 strcpy(real_room, &real_room[11]);
659         }
660         if (viewed->room.QRflags & QR_PRIVATE) {
661                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
662                 if ( (ra & UA_KNOWN) == 0) {
663                         strcpy(real_room, "<private room>");
664                 }
665         }
666
667         if (viewed->cs_flags & CS_CHAT) {
668                 while (strlen(real_room) < 14) {
669                         strcat(real_room, " ");
670                 }
671                 strcpy(&real_room[14], "<chat>");
672         }
673
674 }
675
676 /*
677  * Convenience function.
678  */
679 int CtdlAccessCheck(int required_level) {
680
681         if (CC->internal_pgm) return(0);
682         if (required_level >= ac_internal) {
683                 cprintf("%d This is not a user-level command.\n",
684                         ERROR + HIGHER_ACCESS_REQUIRED);
685                 return(-1);
686         }
687
688         if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (!config.c_guest_logins)) {
689                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
690                 return(-1);
691         }
692
693         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
694                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
695                 return(-1);
696         }
697
698         if (CC->user.axlevel >= AxAideU) return(0);
699         if (required_level >= ac_aide) {
700                 cprintf("%d This command requires Aide access.\n",
701                         ERROR + HIGHER_ACCESS_REQUIRED);
702                 return(-1);
703         }
704
705         if (is_room_aide()) return(0);
706         if (required_level >= ac_room_aide) {
707                 cprintf("%d This command requires Aide or Room Aide access.\n",
708                         ERROR + HIGHER_ACCESS_REQUIRED);
709                 return(-1);
710         }
711
712         /* shhh ... succeed quietly */
713         return(0);
714 }
715
716
717
718 /*
719  * Terminate another running session
720  */
721 void cmd_term(char *cmdbuf)
722 {
723         int session_num;
724         int terminated = 0;
725
726         session_num = extract_int(cmdbuf, 0);
727
728         terminated = CtdlTerminateOtherSession(session_num);
729
730         if (terminated < 0) {
731                 cprintf("%d You can't kill your own session.\n", ERROR + ILLEGAL_VALUE);
732                 return;
733         }
734
735         if (terminated & TERM_FOUND) {
736                 if (terminated == TERM_KILLED) {
737                         cprintf("%d Session terminated.\n", CIT_OK);
738                 }
739                 else {
740                         cprintf("%d You are not allowed to do that.\n",
741                                 ERROR + HIGHER_ACCESS_REQUIRED);
742                 }
743         }
744         else {
745                 cprintf("%d No such session.\n", ERROR + ILLEGAL_VALUE);
746         }
747 }
748
749
750 /* 
751  * get the paginator prompt
752  */
753 void cmd_more(char *argbuf) {
754         cprintf("%d %s\n", CIT_OK, config.c_moreprompt);
755 }
756
757
758 /*
759  * echo 
760  */
761 void cmd_echo(char *etext)
762 {
763         cprintf("%d %s\n", CIT_OK, etext);
764 }
765
766
767 /* 
768  * Perform privilege escalation for an internal program
769  */
770 void cmd_ipgm(char *argbuf)
771 {
772         int secret;
773
774         secret = extract_int(argbuf, 0);
775
776         /* For security reasons, we do NOT allow this command to run
777          * over the network.  Local sockets only.
778          */
779         if (!CC->is_local_socket) {
780                 sleep(5);
781                 cprintf("%d Authentication failed.\n", ERROR + PASSWORD_REQUIRED);
782         }
783         else if (secret == config.c_ipgm_secret) {
784                 CC->internal_pgm = 1;
785                 strcpy(CC->curr_user, "<internal program>");
786                 CC->cs_flags = CC->cs_flags|CS_STEALTH;
787                 cprintf("%d Authenticated as an internal program.\n", CIT_OK);
788         }
789         else {
790                 sleep(5);
791                 cprintf("%d Authentication failed.\n", ERROR + PASSWORD_REQUIRED);
792                 CtdlLogPrintf(CTDL_ERR, "Warning: ipgm authentication failed.\n");
793                 CC->kill_me = 1;
794         }
795 }
796
797
798 /*
799  * Shut down the server
800  */
801 void cmd_down(char *argbuf) {
802         char *Reply ="%d Shutting down server.  Goodbye.\n";
803
804         if (CtdlAccessCheck(ac_aide)) return;
805
806         if (!IsEmptyStr(argbuf))
807         {
808                 int state = CIT_OK;
809                 restart_server = extract_int(argbuf, 0);
810                 
811                 if (restart_server > 0)
812                 {
813                         Reply = "%d citserver will now shut down and automatically restart.\n";
814                 }
815                 if ((restart_server > 0) && !running_as_daemon)
816                 {
817                         CtdlLogPrintf(CTDL_ERR, "The user requested restart, but not running as daemon! Geronimooooooo!\n");
818                         Reply = "%d Warning: citserver is not running in daemon mode and is therefore unlikely to restart automatically.\n";
819                         state = ERROR;
820                 }
821                 cprintf(Reply, state);
822         }
823         else
824         {
825                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN); 
826         }
827         CC->kill_me = 1; /* Even the DOWN command has to follow correct proceedure when disconecting */
828         CtdlThreadStopAll();
829 }
830
831
832 /*
833  * Halt the server without exiting the server process.
834  */
835 void cmd_halt(char *argbuf) {
836
837         if (CtdlAccessCheck(ac_aide)) return;
838
839         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
840         CtdlThreadStopAll();
841         shutdown_and_halt = 1;
842 }
843
844
845 /*
846  * Schedule or cancel a server shutdown
847  */
848 void cmd_scdn(char *argbuf)
849 {
850         int new_state;
851         int state = CIT_OK;
852         char *Reply = "%d %d\n";
853
854         if (CtdlAccessCheck(ac_aide)) return;
855
856         new_state = extract_int(argbuf, 0);
857         if ((new_state == 2) || (new_state == 3))
858         {
859                 restart_server = 1;
860                 if (!running_as_daemon)
861                 {
862                         CtdlLogPrintf(CTDL_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
863                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
864                         state = ERROR;
865                 }
866
867                 restart_server = extract_int(argbuf, 0);
868                 new_state -= 2;
869         }
870         if ((new_state == 0) || (new_state == 1)) {
871                 ScheduledShutdown = new_state;
872         }
873         cprintf(Reply, state, ScheduledShutdown);
874 }
875
876
877 /*
878  * Set or unset asynchronous protocol mode
879  */
880 void cmd_asyn(char *argbuf)
881 {
882         int new_state;
883
884         new_state = extract_int(argbuf, 0);
885         if ((new_state == 0) || (new_state == 1)) {
886                 CC->is_async = new_state;
887         }
888         cprintf("%d %d\n", CIT_OK, CC->is_async);
889 }
890
891
892 /*
893  * Generate a "nonce" for APOP-style authentication.
894  *
895  * RFC 1725 et al specify a PID to be placed in front of the nonce.
896  * Quoth BTX: That would be stupid.
897  */
898 void generate_nonce(CitContext *con) {
899         struct timeval tv;
900
901         memset(con->cs_nonce, NONCE_SIZE, 0);
902         gettimeofday(&tv, NULL);
903         memset(con->cs_nonce, NONCE_SIZE, 0);
904         snprintf(con->cs_nonce, NONCE_SIZE, "<%d%ld@%s>",
905                 rand(), (long)tv.tv_usec, config.c_fqdn);
906 }
907
908
909 /*
910  * Back-end function for starting a session
911  */
912 void begin_session(CitContext *con)
913 {
914         socklen_t len;
915         struct sockaddr_in sin;
916
917         /* 
918          * Initialize some variables specific to our context.
919          */
920         con->logged_in = 0;
921         con->internal_pgm = 0;
922         con->download_fp = NULL;
923         con->upload_fp = NULL;
924         con->FirstExpressMessage = NULL;
925         time(&con->lastcmd);
926         time(&con->lastidle);
927         strcpy(con->lastcmdname, "    ");
928         strcpy(con->cs_clientname, "(unknown)");
929         strcpy(con->curr_user, NLI);
930         *con->net_node = '\0';
931         *con->fake_username = '\0';
932         *con->fake_hostname = '\0';
933         *con->fake_roomname = '\0';
934         *con->cs_clientinfo = '\0';
935         generate_nonce(con);
936         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
937         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
938         con->cs_UDSclientUID = -1;
939         con->cs_host[sizeof con->cs_host - 1] = 0;
940         len = sizeof sin;
941         if (!CC->is_local_socket) {
942                 locate_host(con->cs_host, sizeof con->cs_host,
943                         con->cs_addr, sizeof con->cs_addr,
944                         con->client_socket
945                 );
946         }
947         else {
948                 con->cs_host[0] = 0;
949                 con->cs_addr[0] = 0;
950 #ifdef HAVE_STRUCT_UCRED
951                 {
952                         /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
953                         struct ucred credentials;
954                         socklen_t ucred_length = sizeof(struct ucred);
955                         
956                         /*fill in the user data structure */
957                         if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
958                                 CtdlLogPrintf(CTDL_NOTICE, "could obtain credentials from unix domain socket");
959                                 
960                         }
961                         else {          
962                                 /* the process ID of the process on the other side of the socket */
963                                 /* credentials.pid; */
964                                 
965                                 /* the effective UID of the process on the other side of the socket  */
966                                 con->cs_UDSclientUID = credentials.uid;
967                                 
968                                 /* the effective primary GID of the process on the other side of the socket */
969                                 /* credentials.gid; */
970                                 
971                                 /* To get supplemental groups, we will have to look them up in our account
972                                    database, after a reverse lookup on the UID to get the account name.
973                                    We can take this opportunity to check to see if this is a legit account.
974                                 */
975                                 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
976                                          "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ", 
977                                          credentials.pid,
978                                          credentials.uid,
979                                          credentials.gid);
980                         }
981                 }
982 #endif
983         }
984         con->cs_flags = 0;
985         con->upload_type = UPL_FILE;
986         con->dl_is_net = 0;
987
988         con->nologin = 0;
989         if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
990                 con->nologin = 1;
991         }
992
993         if (!CC->is_local_socket) {
994                 CtdlLogPrintf(CTDL_NOTICE, "Session (%s) started from %s (%s).\n", con->ServiceName, con->cs_host, con->cs_addr);
995         }
996         else {
997                 CtdlLogPrintf(CTDL_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
998         }
999
1000         /* Run any session startup routines registered by loadable modules */
1001         PerformSessionHooks(EVT_START);
1002 }
1003
1004
1005 void citproto_begin_session() {
1006         if (CC->nologin==1) {
1007                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
1008                         ERROR + MAX_SESSIONS_EXCEEDED,
1009                         config.c_nodename, config.c_maxsessions
1010                 );
1011                 CC->kill_me = 1;
1012         }
1013         else {
1014                 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
1015                 CC->can_receive_im = 1;
1016         }
1017 }
1018
1019
1020 void cmd_noop(char *argbuf)
1021 {
1022         cprintf("%d%cok\n", CIT_OK, CtdlCheckExpress() );
1023 }
1024
1025
1026 void cmd_qnop(char *argbuf)
1027 {
1028         /* do nothing, this command returns no response */
1029 }
1030
1031
1032 void cmd_quit(char *argbuf)
1033 {
1034         cprintf("%d Goodbye.\n", CIT_OK);
1035         CC->kill_me = 1;
1036 }
1037
1038
1039 void cmd_lout(char *argbuf)
1040 {
1041         if (CC->logged_in) 
1042                 CtdlUserLogout();
1043         cprintf("%d logged out.\n", CIT_OK);
1044 }
1045
1046
1047 /*
1048  * This loop recognizes all server commands.
1049  */
1050 void do_command_loop(void) {
1051         char cmdbuf[SIZ];
1052         const char *old_name = NULL;
1053         
1054         old_name = CtdlThreadName("do_command_loop");
1055         
1056         time(&CC->lastcmd);
1057         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1058         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1059                 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\n");
1060                 CC->kill_me = 1;
1061                 CtdlThreadName(old_name);
1062                 return;
1063         }
1064
1065         /* Log the server command, but don't show passwords... */
1066         if ( (strncasecmp(cmdbuf, "PASS", 4)) && (strncasecmp(cmdbuf, "SETP", 4)) ) {
1067                 CtdlLogPrintf(CTDL_INFO, "CtdlCommand [%s] [%s] %s\n", CTDLUSERIP, CC->curr_user, cmdbuf);
1068         }
1069         else {
1070                 CtdlLogPrintf(CTDL_INFO, "CtdlCommand [%s] [%s] <password command hidden from log>\n", CTDLUSERIP, CC->curr_user);
1071         }
1072
1073         buffer_output();
1074
1075         /*
1076          * Let other clients see the last command we executed, and
1077          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
1078          */
1079         if ( (strncasecmp(cmdbuf, "NOOP", 4))
1080            && (strncasecmp(cmdbuf, "QNOP", 4))
1081            && (strncasecmp(cmdbuf, "PEXP", 4))
1082            && (strncasecmp(cmdbuf, "GEXP", 4))
1083            && (strncasecmp(cmdbuf, "RWHO", 4))
1084            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
1085                 strcpy(CC->lastcmdname, "    ");
1086                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
1087                 time(&CC->lastidle);
1088         }
1089         
1090         CtdlThreadName(cmdbuf);
1091                 
1092         if ((strncasecmp(cmdbuf, "ENT0", 4))
1093            && (strncasecmp(cmdbuf, "MESG", 4))
1094            && (strncasecmp(cmdbuf, "MSGS", 4)))
1095         {
1096            CC->cs_flags &= ~CS_POSTING;
1097         }
1098                    
1099         if (!DLoader_Exec_Cmd(cmdbuf)) {
1100                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
1101         }       
1102
1103         unbuffer_output();
1104
1105         /* Run any after-each-command routines registered by modules */
1106         PerformSessionHooks(EVT_CMD);
1107         CtdlThreadName(old_name);
1108 }
1109
1110
1111 /*
1112  * This loop performs all asynchronous functions.
1113  */
1114 void do_async_loop(void) {
1115         PerformSessionHooks(EVT_ASYNC);
1116 }
1117
1118
1119 /*****************************************************************************/
1120 /*                      MODULE INITIALIZATION STUFF                          */
1121 /*****************************************************************************/
1122
1123 CTDL_MODULE_INIT(citserver)
1124 {
1125         if (!threading) {
1126                 CtdlRegisterProtoHook(cmd_noop, "NOOP", "no operation");
1127                 CtdlRegisterProtoHook(cmd_qnop, "QNOP", "no operation with no response");
1128                 CtdlRegisterProtoHook(cmd_quit, "QUIT", "log out and disconnect from server");
1129                 CtdlRegisterProtoHook(cmd_lout, "LOUT", "log out but do not disconnect from server");
1130                 CtdlRegisterProtoHook(cmd_asyn, "ASYN", "enable asynchronous server responses");
1131                 CtdlRegisterProtoHook(cmd_info, "INFO", "fetch server capabilities and configuration");
1132                 CtdlRegisterProtoHook(cmd_mesg, "MESG", "fetch system banners");
1133                 CtdlRegisterProtoHook(cmd_emsg, "EMSG", "submit system banners");
1134                 CtdlRegisterProtoHook(cmd_echo, "ECHO", "echo text back to the client");
1135                 CtdlRegisterProtoHook(cmd_more, "MORE", "fetch the paginator prompt");
1136                 CtdlRegisterProtoHook(cmd_iden, "IDEN", "identify the client software and location");
1137                 CtdlRegisterProtoHook(cmd_ipgm, "IPGM", "perform privilege escalation for internal programs");
1138                 CtdlRegisterProtoHook(cmd_term, "TERM", "terminate another running session");
1139                 CtdlRegisterProtoHook(cmd_down, "DOWN", "perform a server shutdown");
1140                 CtdlRegisterProtoHook(cmd_halt, "HALT", "halt the server without exiting the server process");
1141                 CtdlRegisterProtoHook(cmd_scdn, "SCDN", "schedule or cancel a server shutdown");
1142                 CtdlRegisterProtoHook(cmd_time, "TIME", "fetch the date and time from the server");
1143         }
1144         /* return our id for the Log */
1145         return "citserver";
1146 }