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