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