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