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