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