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