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