HUGE PATCH. This moves all of mime_parser.c and all
[citadel.git] / citadel / citserver.c
1 /* 
2  * $Id$
3  *
4  * Main source module for the Citadel server
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #if HAVE_BACKTRACE
30 #include <execinfo.h>
31 #endif
32
33 #include <ctype.h>
34 #include <string.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <limits.h>
38 #include <netdb.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <libcitadel.h>
44 #include "citadel.h"
45 #include "server.h"
46 #include "sysdep_decls.h"
47 #include "citserver.h"
48 #include "config.h"
49 #include "database.h"
50 #include "housekeeping.h"
51 #include "user_ops.h"
52 #include "msgbase.h"
53 #include "support.h"
54 #include "locate_host.h"
55 #include "room_ops.h"
56 #include "file_ops.h"
57 #include "policy.h"
58 #include "control.h"
59 #include "euidindex.h"
60
61 #ifndef HAVE_SNPRINTF
62 #include "snprintf.h"
63 #endif
64
65 struct CitContext *ContextList = NULL;
66 struct CitContext* next_session = NULL;
67 char *unique_session_numbers;
68 int ScheduledShutdown = 0;
69 int do_defrag = 0;
70 time_t server_startup_time;
71 int panic_fd;
72
73 /**
74  * \brief print the actual stack frame.
75  */
76 void cit_backtrace(void)
77 {
78 #ifdef HAVE_BACKTRACE
79         void *stack_frames[50];
80         size_t size, i;
81         char **strings;
82
83
84         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
85         strings = backtrace_symbols(stack_frames, size);
86         for (i = 0; i < size; i++) {
87                 if (strings != NULL)
88                         lprintf(1, "%s\n", strings[i]);
89                 else
90                         lprintf(1, "%p\n", stack_frames[i]);
91         }
92         free(strings);
93 #endif
94 }
95
96 /**
97  * \brief print the actual stack frame.
98  */
99 void cit_panic_backtrace(int SigNum)
100 {
101 #ifdef HAVE_BACKTRACE
102         void *stack_frames[10];
103         size_t size, i;
104         char **strings;
105
106         printf("caught signal 11\n");
107         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
108         strings = backtrace_symbols(stack_frames, size);
109         for (i = 0; i < size; i++) {
110                 if (strings != NULL)
111                         lprintf(1, "%s\n", strings[i]);
112                 else
113                         lprintf(1, "%p\n", stack_frames[i]);
114         }
115         free(strings);
116 #endif
117         exit(-1);
118 }
119
120 /*
121  * Various things that need to be initialized at startup
122  */
123 void master_startup(void) {
124         struct timeval tv;
125         unsigned int seed;
126         FILE *urandom;
127         struct ctdlroom qrbuf;
128         
129         lprintf(CTDL_DEBUG, "master_startup() started\n");
130         time(&server_startup_time);
131
132         lprintf(CTDL_INFO, "Opening databases\n");
133         open_databases();
134
135         if (do_defrag) {
136                 defrag_databases();
137         }
138
139         check_ref_counts();
140
141         lprintf(CTDL_INFO, "Creating base rooms (if necessary)\n");
142         create_room(config.c_baseroom,  0, "", 0, 1, 0, VIEW_BBS);
143         create_room(AIDEROOM,           3, "", 0, 1, 0, VIEW_BBS);
144         create_room(SYSCONFIGROOM,      3, "", 0, 1, 0, VIEW_BBS);
145         create_room(config.c_twitroom,  0, "", 0, 1, 0, VIEW_BBS);
146
147         /* The "Local System Configuration" room doesn't need to be visible */
148         if (lgetroom(&qrbuf, SYSCONFIGROOM) == 0) {
149                 qrbuf.QRflags2 |= QR2_SYSTEM;
150                 lputroom(&qrbuf);
151         }
152
153         lprintf(CTDL_INFO, "Seeding the pseudo-random number generator...\n");
154         urandom = fopen("/dev/urandom", "r");
155         if (urandom != NULL) {
156                 fread(&seed, sizeof seed, 1, urandom);
157                 fclose(urandom);
158         }
159         else {
160                 gettimeofday(&tv, NULL);
161                 seed = tv.tv_usec;
162         }
163         srandom(seed);
164
165         lprintf(CTDL_INFO, "Initializing ipgm secret\n");
166         get_config();
167         config.c_ipgm_secret = rand();
168         put_config();
169
170         lprintf(CTDL_DEBUG, "master_startup() finished\n");
171 }
172
173
174 /*
175  * Cleanup routine to be called when the server is shutting down.
176  */
177 void master_cleanup(int exitcode) {
178         struct CleanupFunctionHook *fcn;
179         struct MaintenanceThreadHook *m_fcn;
180         static int already_cleaning_up = 0;
181
182         if (already_cleaning_up) while(1) sleep(1);
183         already_cleaning_up = 1;
184
185         /* Run any cleanup routines registered by loadable modules */
186         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
187                 (*fcn->h_function_pointer)();
188         }
189
190         /* Close the AdjRefCount queue file */
191         AdjRefCount(-1, 0);
192
193         for (m_fcn = MaintenanceThreadHookTable; m_fcn != NULL; m_fcn = m_fcn->next) {
194                 lprintf(CTDL_INFO, "Waiting for maintenance thread \"%s\" to shut down\n", m_fcn->name);
195                 pthread_join(m_fcn->MaintenanceThread_tid, NULL);
196         }
197         
198
199         /* Close databases */
200         lprintf(CTDL_INFO, "Closing databases\n");
201         close_databases();
202
203         /* Do system-dependent stuff */
204         sysdep_master_cleanup();
205         
206 #ifdef DEBUG_MEMORY_LEAKS
207         dump_heap();
208 #endif
209
210         /* If the operator requested a halt but not an exit, halt here. */
211         if (shutdown_and_halt) {
212                 lprintf(CTDL_NOTICE, "citserver: Halting server without exiting.\n");
213                 fflush(stdout); fflush(stderr);
214                 while(1) {
215                         sleep(32767);
216                 }
217         }
218         
219         release_control();
220
221         /* Now go away. */
222         lprintf(CTDL_NOTICE, "citserver: Exiting with status %d\n", exitcode);
223         fflush(stdout); fflush(stderr);
224         
225         if (restart_server != 0)
226                 exit(1);
227         exit(exitcode);
228 }
229
230
231
232 /*
233  * Terminate a session.
234  */
235 void RemoveContext (struct CitContext *con)
236 {
237         if (con==NULL) {
238                 lprintf(CTDL_ERR,
239                         "WARNING: RemoveContext() called with NULL!\n");
240                 return;
241         }
242         lprintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
243
244         /* Run any cleanup routines registered by loadable modules.
245          * Note: We have to "become_session()" because the cleanup functions
246          *       might make references to "CC" assuming it's the right one.
247          */
248         become_session(con);
249         PerformSessionHooks(EVT_STOP);
250         become_session(NULL);
251
252         /* Now handle all of the administrivia. */
253         lprintf(CTDL_DEBUG, "Calling logout(%d)\n", con->cs_pid);
254         logout(con);
255
256         lprintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
257
258         /* If the client is still connected, blow 'em away. */
259         lprintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
260         close(con->client_socket);
261
262         lprintf(CTDL_DEBUG, "Done with RemoveContext()\n");
263 }
264
265
266
267
268
269 /*
270  * cmd_info()  -  tell the client about this server
271  */
272 void cmd_info(void) {
273         cprintf("%d Server info:\n", LISTING_FOLLOWS);
274         cprintf("%d\n", CC->cs_pid);
275         cprintf("%s\n", config.c_nodename);
276         cprintf("%s\n", config.c_humannode);
277         cprintf("%s\n", config.c_fqdn);
278         cprintf("%s\n", CITADEL);
279         cprintf("%d\n", REV_LEVEL);
280         cprintf("%s\n", config.c_site_location);
281         cprintf("%s\n", config.c_sysadm);
282         cprintf("%d\n", SERVER_TYPE);
283         cprintf("%s\n", config.c_moreprompt);
284         cprintf("1\n"); /* 1 = yes, this system supports floors */
285         cprintf("1\n"); /* 1 = we support the extended paging options */
286         cprintf("%s\n", CC->cs_nonce);
287         cprintf("1\n"); /* 1 = yes, this system supports the QNOP command */
288
289 #ifdef HAVE_LDAP
290         cprintf("1\n"); /* 1 = yes, this server is LDAP-enabled */
291 #else
292         cprintf("0\n"); /* 1 = no, this server is not LDAP-enabled */
293 #endif
294
295         if (config.c_auth_mode == 1) {
296                 cprintf("1\n"); /* "create new user" never works with host auth */
297         }
298         else {
299                 cprintf("%d\n", config.c_disable_newu); /* otherwise, site defined */
300         }
301
302         cprintf("%s\n", config.c_default_cal_zone);
303
304         cprintf("000\n");
305 }
306
307
308 /*
309  * returns an asterisk if there are any instant messages waiting,
310  * space otherwise.
311  */
312 char CtdlCheckExpress(void) {
313         if (CC->FirstExpressMessage == NULL) {
314                 return(' ');
315         }
316         else {
317                 return('*');
318         }
319 }
320
321 void cmd_time(void)
322 {
323    time_t tv;
324    struct tm tmp;
325    
326    tv = time(NULL);
327    localtime_r(&tv, &tmp);
328    
329    /* timezone and daylight global variables are not portable. */
330 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
331    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, tmp.tm_gmtoff, tmp.tm_isdst);
332 #else
333    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, timezone, tmp.tm_isdst);
334 #endif
335 }
336
337
338 /*
339  * Check originating host against the public_clients file.  This determines
340  * whether the client is allowed to change the hostname for this session
341  * (for example, to show the location of the user rather than the location
342  * of the client).
343  */
344 int is_public_client(void)
345 {
346         char buf[1024];
347         char addrbuf[1024];
348         FILE *fp;
349         int i;
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         snprintf(public_clients_file, 
356                          sizeof public_clients_file,
357                          "%s/public_clients",
358                          ctdl_etc_dir);
359
360         /*
361          * Check the time stamp on the public_clients file.  If it's been
362          * updated since the last time we were here (or if this is the first
363          * time we've been through the loop), read its contents and learn
364          * the IP addresses of the listed hosts.
365          */
366         if (stat(public_clients_file, &statbuf) != 0) {
367                 /* No public_clients file exists, so bail out */
368                 lprintf(CTDL_WARNING, "Warning: '%s' does not exist\n", 
369                                 public_clients_file);
370                 return(0);
371         }
372
373         if (statbuf.st_mtime > pc_timestamp) {
374                 begin_critical_section(S_PUBLIC_CLIENTS);
375                 lprintf(CTDL_INFO, "Loading %s\n", public_clients_file);
376
377                 safestrncpy(public_clients, "127.0.0.1", sizeof public_clients);
378                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
379                         strcat(public_clients, "|");
380                         strcat(public_clients, addrbuf);
381                 }
382
383                 fp = fopen(public_clients_file, "r");
384                 if (fp != NULL) while (fgets(buf, sizeof buf, fp)!=NULL) {
385                         char *ptr;
386                         ptr = buf;
387                         while (!IsEmptyStr(ptr)) {
388                                 if (*ptr == '#') {
389                                         *ptr = 0;
390                                         break;
391                                 }
392                                 else ptr++;
393                         }
394                         ptr--;
395                         while (ptr>buf && isspace(*ptr)) {
396                                 *(ptr--) = 0;
397                         }
398                         if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
399                                 if ((strlen(public_clients) +
400                                    strlen(addrbuf) + 2)
401                                    < sizeof(public_clients)) {
402                                         strcat(public_clients, "|");
403                                         strcat(public_clients, addrbuf);
404                                 }
405                         }
406                 }
407                 fclose(fp);
408                 pc_timestamp = time(NULL);
409                 end_critical_section(S_PUBLIC_CLIENTS);
410         }
411
412         lprintf(CTDL_DEBUG, "Checking whether %s is a local or public client\n",
413                 CC->cs_addr);
414         for (i=0; i<num_parms(public_clients); ++i) {
415                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
416                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
417                         lprintf(CTDL_DEBUG, "... yes it is.\n");
418                         return(1);
419                 }
420         }
421
422         /* No hits.  This is not a public client. */
423         lprintf(CTDL_DEBUG, "... no it isn't.\n");
424         return(0);
425 }
426
427
428 /*
429  * the client is identifying itself to the server
430  */
431 void cmd_iden(char *argbuf)
432 {
433         int dev_code;
434         int cli_code;
435         int rev_level;
436         char desc[128];
437         char from_host[128];
438         struct in_addr addr;
439         int do_lookup = 0;
440
441         if (num_parms(argbuf)<4) {
442                 cprintf("%d usage error\n", ERROR + ILLEGAL_VALUE);
443                 return;
444         }
445
446         dev_code = extract_int(argbuf,0);
447         cli_code = extract_int(argbuf,1);
448         rev_level = extract_int(argbuf,2);
449         extract_token(desc, argbuf, 3, '|', sizeof desc);
450
451         safestrncpy(from_host, config.c_fqdn, sizeof from_host);
452         from_host[sizeof from_host - 1] = 0;
453         if (num_parms(argbuf)>=5) extract_token(from_host, argbuf, 4, '|', sizeof from_host);
454
455         CC->cs_clientdev = dev_code;
456         CC->cs_clienttyp = cli_code;
457         CC->cs_clientver = rev_level;
458         safestrncpy(CC->cs_clientname, desc, sizeof CC->cs_clientname);
459         CC->cs_clientname[31] = 0;
460
461         if (!IsEmptyStr(from_host)) {
462                 if (CC->is_local_socket) do_lookup = 1;
463                 else if (is_public_client()) do_lookup = 1;
464         }
465
466         if (do_lookup) {
467                 lprintf(CTDL_DEBUG, "Looking up hostname '%s'\n", from_host);
468                 if ((addr.s_addr = inet_addr(from_host)) != -1) {
469                         locate_host(CC->cs_host, sizeof CC->cs_host,
470                                 CC->cs_addr, sizeof CC->cs_addr,
471                                 &addr);
472                 }
473                 else {
474                         safestrncpy(CC->cs_host, from_host, sizeof CC->cs_host);
475                         CC->cs_host[sizeof CC->cs_host - 1] = 0;
476                 }
477         }
478
479         lprintf(CTDL_NOTICE, "Client %d/%d/%01d.%02d (%s) from %s\n",
480                 dev_code,
481                 cli_code,
482                 (rev_level / 100),
483                 (rev_level % 100),
484                 desc,
485                 CC->cs_host);
486         cprintf("%d Ok\n",CIT_OK);
487 }
488
489
490 /*
491  * display system messages or help
492  */
493 void cmd_mesg(char *mname)
494 {
495         FILE *mfp;
496         char targ[256];
497         char buf[256];
498         char buf2[256];
499         char *dirs[2];
500         DIR *dp;
501         struct dirent *d;
502
503         extract_token(buf, mname, 0, '|', sizeof buf);
504
505         dirs[0] = strdup(ctdl_message_dir);
506         dirs[1] = strdup(ctdl_hlp_dir);
507
508         snprintf(buf2, sizeof buf2, "%s.%d.%d",
509                 buf, CC->cs_clientdev, CC->cs_clienttyp);
510
511         /* If the client requested "?" then produce a listing */
512         if (!strcmp(buf, "?")) {
513                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
514                 dp = opendir(dirs[1]);
515                 if (dp != NULL) {
516                         while (d = readdir(dp), d != NULL) {
517                                 if (d->d_name[0] != '.') {
518                                         cprintf(" %s\n", d->d_name);
519                                 }
520                         }
521                         closedir(dp);
522                 }
523                 cprintf("000\n");
524                 free(dirs[0]);
525                 free(dirs[1]);
526                 return;
527         }
528
529         /* Otherwise, look for the requested file by name. */
530         else {
531                 mesg_locate(targ, sizeof targ, buf2, 2, (const char **)dirs);
532                 if (IsEmptyStr(targ)) {
533                         snprintf(buf2, sizeof buf2, "%s.%d",
534                                                         buf, CC->cs_clientdev);
535                         mesg_locate(targ, sizeof targ, buf2, 2,
536                                                         (const char **)dirs);
537                         if (IsEmptyStr(targ)) {
538                                 mesg_locate(targ, sizeof targ, buf, 2,
539                                                         (const char **)dirs);
540                         }       
541                 }
542         }
543
544         free(dirs[0]);
545         free(dirs[1]);
546
547         if (IsEmptyStr(targ)) {
548                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
549                         ERROR + FILE_NOT_FOUND,
550                         mname,
551                         ctdl_message_dir,
552                         ctdl_hlp_dir
553                 );
554                 return;
555         }
556
557         mfp = fopen(targ, "r");
558         if (mfp==NULL) {
559                 cprintf("%d Cannot open '%s': %s\n",
560                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
561                 return;
562         }
563         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
564
565         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
566                 buf[strlen(buf)-1] = 0;
567                 do_help_subst(buf);
568                 cprintf("%s\n",buf);
569         }
570
571         fclose(mfp);
572         cprintf("000\n");
573 }
574
575
576 /*
577  * enter system messages or help
578  */
579 void cmd_emsg(char *mname)
580 {
581         FILE *mfp;
582         char targ[256];
583         char buf[256];
584         char *dirs[2];
585         int a;
586
587         unbuffer_output();
588
589         if (CtdlAccessCheck(ac_aide)) return;
590
591         extract_token(buf, mname, 0, '|', sizeof buf);
592         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
593                 if (buf[a] == '/') buf[a] = '.';
594         }
595
596         dirs[0] = strdup(ctdl_message_dir);
597         dirs[1] = strdup(ctdl_hlp_dir);
598
599         mesg_locate(targ, sizeof targ, buf, 2, (const char**)dirs);
600         free(dirs[0]);
601         free(dirs[1]);
602
603         if (IsEmptyStr(targ)) {
604                 snprintf(targ, sizeof targ, 
605                                  "%s/%s",
606                                  ctdl_hlp_dir, buf);
607         }
608
609         mfp = fopen(targ,"w");
610         if (mfp==NULL) {
611                 cprintf("%d Cannot open '%s': %s\n",
612                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
613                 return;
614         }
615         cprintf("%d %s\n", SEND_LISTING, targ);
616
617         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
618                 fprintf(mfp, "%s\n", buf);
619         }
620
621         fclose(mfp);
622 }
623
624
625 /* Don't show the names of private rooms unless the viewing
626  * user also knows the rooms.
627  */
628 void GenerateRoomDisplay(char *real_room,
629                         struct CitContext *viewed,
630                         struct CitContext *viewer) {
631
632         int ra;
633
634         strcpy(real_room, viewed->room.QRname);
635         if (viewed->room.QRflags & QR_MAILBOX) {
636                 strcpy(real_room, &real_room[11]);
637         }
638         if (viewed->room.QRflags & QR_PRIVATE) {
639                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
640                 if ( (ra & UA_KNOWN) == 0) {
641                         strcpy(real_room, "<private room>");
642                 }
643         }
644
645         if (viewed->cs_flags & CS_CHAT) {
646                 while (strlen(real_room) < 14)
647                         strcat(real_room, " ");
648
649                 strcpy(&real_room[14], "<chat>");
650         }
651
652 }
653
654 /*
655  * Convenience function.
656  */
657 int CtdlAccessCheck(int required_level) {
658
659         if (CC->internal_pgm) return(0);
660         if (required_level >= ac_internal) {
661                 cprintf("%d This is not a user-level command.\n",
662                         ERROR + HIGHER_ACCESS_REQUIRED);
663                 return(-1);
664         }
665
666         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
667                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
668                 return(-1);
669         }
670
671         if (CC->user.axlevel >= 6) return(0);
672         if (required_level >= ac_aide) {
673                 cprintf("%d This command requires Aide access.\n",
674                         ERROR + HIGHER_ACCESS_REQUIRED);
675                 return(-1);
676         }
677
678         if (is_room_aide()) return(0);
679         if (required_level >= ac_room_aide) {
680                 cprintf("%d This command requires Aide or Room Aide access.\n",
681                         ERROR + HIGHER_ACCESS_REQUIRED);
682                 return(-1);
683         }
684
685         /* shhh ... succeed quietly */
686         return(0);
687 }
688
689
690
691 /*
692  * Terminate another running session
693  */
694 void cmd_term(char *cmdbuf)
695 {
696         int session_num;
697         struct CitContext *ccptr;
698         int found_it = 0;
699         int allowed = 0;
700
701         session_num = extract_int(cmdbuf, 0);
702         if (session_num == CC->cs_pid) {
703                 cprintf("%d You can't kill your own session.\n", ERROR + ILLEGAL_VALUE);
704                 return;
705         }
706
707         lprintf(CTDL_DEBUG, "Locating session to kill\n");
708         begin_critical_section(S_SESSION_TABLE);
709         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
710                 if (session_num == ccptr->cs_pid) {
711                         found_it = 1;
712                         if ((ccptr->user.usernum == CC->user.usernum)
713                            || (CC->user.axlevel >= 6)) {
714                                 allowed = 1;
715                                 ccptr->kill_me = 1;
716                         }
717                         else {
718                                 allowed = 0;
719                         }
720                 }
721         }
722         end_critical_section(S_SESSION_TABLE);
723
724         if (found_it) {
725                 if (allowed) {
726                         cprintf("%d Session terminated.\n", CIT_OK);
727                 }
728                 else {
729                         cprintf("%d You are not allowed to do that.\n",
730                                 ERROR + HIGHER_ACCESS_REQUIRED);
731                 }
732         }
733         else {
734                 cprintf("%d No such session.\n", ERROR + ILLEGAL_VALUE);
735         }
736 }
737
738
739
740
741
742 /* 
743  * get the paginator prompt
744  */
745 void cmd_more(void) {
746         cprintf("%d %s\n", CIT_OK, config.c_moreprompt);
747 }
748
749 /*
750  * echo 
751  */
752 void cmd_echo(char *etext)
753 {
754         cprintf("%d %s\n", CIT_OK, etext);
755 }
756
757
758
759 /* 
760  * identify as internal program
761  */
762 void cmd_ipgm(char *argbuf)
763 {
764         int secret;
765
766         secret = extract_int(argbuf, 0);
767
768         /* For security reasons, we do NOT allow this command to run
769          * over the network.  Local sockets only.
770          */
771         if (!CC->is_local_socket) {
772                 sleep(5);
773                 cprintf("%d Authentication failed.\n",
774                         ERROR + PASSWORD_REQUIRED);
775         }
776         else if (secret == config.c_ipgm_secret) {
777                 CC->internal_pgm = 1;
778                 strcpy(CC->curr_user, "<internal program>");
779                 CC->cs_flags = CC->cs_flags|CS_STEALTH;
780                 cprintf("%d Authenticated as an internal program.\n", CIT_OK);
781         }
782         else {
783                 sleep(5);
784                 cprintf("%d Authentication failed.\n",
785                         ERROR + PASSWORD_REQUIRED);
786                 lprintf(CTDL_ERR, "Warning: ipgm authentication failed.\n");
787                 CC->kill_me = 1;
788         }
789
790         /* Now change the ipgm secret for the next round.
791          * (Disabled because it breaks concurrent scripts.  The fact that
792          * we no longer accept IPGM over the network should be sufficient
793          * to prevent brute-force attacks.  If you don't agree, uncomment
794          * this block.)
795         get_config();
796         config.c_ipgm_secret = rand();
797         put_config();
798         */
799 }
800
801
802 /*
803  * Shut down the server
804  */
805 void cmd_down(char *argbuf) {
806         char *Reply ="%d Shutting down server.  Goodbye.\n";
807
808         if (CtdlAccessCheck(ac_aide)) return;
809
810         if (!IsEmptyStr(argbuf))
811         {
812                 int state = CIT_OK;
813                 restart_server = extract_int(argbuf, 0);
814                 
815                 if (restart_server > 0)
816                         Reply = "%d Restarting server.  See you soon.\n";
817                 if ((restart_server > 0) && !running_as_daemon)
818                 {
819                         lprintf(CTDL_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
820                         Reply = "%d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
821                         state = ERROR;
822                 }
823                 cprintf(Reply, state);
824         }
825         else
826         {
827                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN);
828         }
829         time_to_die = 1;
830 }
831
832 /*
833  * Halt the server without exiting the server process.
834  */
835 void cmd_halt(void) {
836
837         if (CtdlAccessCheck(ac_aide)) return;
838
839         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
840         time_to_die = 1;
841         shutdown_and_halt = 1;
842 }
843
844 /*
845  * Schedule or cancel a server shutdown
846  */
847 void cmd_scdn(char *argbuf)
848 {
849         int new_state;
850         int state = CIT_OK;
851         char *Reply = "%d %d\n";
852
853         if (CtdlAccessCheck(ac_aide)) return;
854
855         new_state = extract_int(argbuf, 0);
856         if ((new_state == 2) || (new_state == 3))
857         {
858                 restart_server = 1;
859                 if (!running_as_daemon)
860                 {
861                         lprintf(CTDL_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
862                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
863                         state = ERROR;
864                 }
865
866                 restart_server = extract_int(argbuf, 0);
867                 new_state -= 2;
868         }
869         if ((new_state == 0) || (new_state == 1)) {
870                 ScheduledShutdown = new_state;
871         }
872         cprintf(Reply, state, ScheduledShutdown);
873 }
874
875
876 /*
877  * Set or unset asynchronous protocol mode
878  */
879 void cmd_asyn(char *argbuf)
880 {
881         int new_state;
882
883         new_state = extract_int(argbuf, 0);
884         if ((new_state == 0) || (new_state == 1)) {
885                 CC->is_async = new_state;
886         }
887         cprintf("%d %d\n", CIT_OK, CC->is_async);
888 }
889
890
891 /*
892  * Generate a "nonce" for APOP-style authentication.
893  *
894  * RFC 1725 et al specify a PID to be placed in front of the nonce.
895  * Quoth BTX: That would be stupid.
896  */
897 void generate_nonce(struct CitContext *con) {
898         struct timeval tv;
899
900         memset(con->cs_nonce, NONCE_SIZE, 0);
901         gettimeofday(&tv, NULL);
902         memset(con->cs_nonce, NONCE_SIZE, 0);
903         snprintf(con->cs_nonce, NONCE_SIZE, "<%d%ld@%s>",
904                 rand(), (long)tv.tv_usec, config.c_fqdn);
905 }
906
907
908
909
910 /*
911  * Back-end function for starting a session
912  */
913 void begin_session(struct CitContext *con)
914 {
915         socklen_t len;
916         struct sockaddr_in sin;
917
918         /* 
919          * Initialize some variables specific to our context.
920          */
921         con->logged_in = 0;
922         con->internal_pgm = 0;
923         con->download_fp = NULL;
924         con->upload_fp = NULL;
925         con->FirstExpressMessage = NULL;
926         time(&con->lastcmd);
927         time(&con->lastidle);
928         strcpy(con->lastcmdname, "    ");
929         strcpy(con->cs_clientname, "(unknown)");
930         strcpy(con->curr_user, NLI);
931         *con->net_node = '\0';
932         *con->fake_username = '\0';
933         *con->fake_hostname = '\0';
934         *con->fake_roomname = '\0';
935         generate_nonce(con);
936         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
937         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
938         con->cs_host[sizeof con->cs_host - 1] = 0;
939         len = sizeof sin;
940         if (!CC->is_local_socket) {
941                 if (!getpeername(con->client_socket, (struct sockaddr *) &sin, &len)) {
942                         locate_host(con->cs_host, sizeof con->cs_host,
943                                 con->cs_addr, sizeof con->cs_addr,
944                                 &sin.sin_addr
945                         );
946                 }
947         }
948         else {
949                 strcpy(con->cs_host, "");
950         }
951         con->cs_flags = 0;
952         con->upload_type = UPL_FILE;
953         con->dl_is_net = 0;
954
955         con->nologin = 0;
956         if ((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) {
957                 con->nologin = 1;
958         }
959
960         lprintf(CTDL_NOTICE, "Session started.\n");
961
962         /* Run any session startup routines registered by loadable modules */
963         PerformSessionHooks(EVT_START);
964 }
965
966
967 void citproto_begin_session() {
968         if (CC->nologin==1) {
969                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
970                         ERROR + MAX_SESSIONS_EXCEEDED,
971                         config.c_nodename, config.c_maxsessions
972                 );
973                 CC->kill_me = 1;
974         }
975         else {
976                 cprintf("%d %s Citadel server ready.\n",
977                         CIT_OK, config.c_nodename);
978         }
979 }
980
981
982
983
984 /*
985  * This loop recognizes all server commands.
986  */
987 void do_command_loop(void) {
988         char cmdbuf[SIZ];
989
990         time(&CC->lastcmd);
991         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
992         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
993                 lprintf(CTDL_ERR, "Client disconnected: ending session.\n");
994                 CC->kill_me = 1;
995                 return;
996         }
997
998         /* Log the server command, but don't show passwords... */
999         if ( (strncasecmp(cmdbuf, "PASS", 4))
1000            && (strncasecmp(cmdbuf, "SETP", 4)) ) {
1001                 lprintf(CTDL_INFO, "%s\n", cmdbuf);
1002         }
1003         else {
1004                 lprintf(CTDL_INFO, "<password command sent>\n");
1005         }
1006
1007         buffer_output();
1008
1009         /*
1010          * Let other clients see the last command we executed, and
1011          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
1012          */
1013         if ( (strncasecmp(cmdbuf, "NOOP", 4))
1014            && (strncasecmp(cmdbuf, "QNOP", 4))
1015            && (strncasecmp(cmdbuf, "PEXP", 4))
1016            && (strncasecmp(cmdbuf, "GEXP", 4))
1017            && (strncasecmp(cmdbuf, "RWHO", 4))
1018            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
1019                 strcpy(CC->lastcmdname, "    ");
1020                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
1021                 time(&CC->lastidle);
1022         }
1023                 
1024         if ((strncasecmp(cmdbuf, "ENT0", 4))
1025            && (strncasecmp(cmdbuf, "MESG", 4))
1026            && (strncasecmp(cmdbuf, "MSGS", 4)))
1027         {
1028            CC->cs_flags &= ~CS_POSTING;
1029         }
1030                    
1031         if (!strncasecmp(cmdbuf, "NOOP", 4)) {
1032                 cprintf("%d%cok\n", CIT_OK, CtdlCheckExpress() );
1033         }
1034         
1035         else if (!strncasecmp(cmdbuf, "QNOP", 4)) {
1036                 /* do nothing, this command returns no response */
1037         }
1038
1039         else if (!strncasecmp(cmdbuf,"QUIT",4)) {
1040                 cprintf("%d Goodbye.\n", CIT_OK);
1041                 CC->kill_me = 1;
1042         }
1043
1044         else if (!strncasecmp(cmdbuf,"ASYN",4)) {
1045                 cmd_asyn(&cmdbuf[5]);
1046         }
1047
1048         else if (!strncasecmp(cmdbuf,"LOUT",4)) {
1049                 if (CC->logged_in) logout(CC);
1050                 cprintf("%d logged out.\n", CIT_OK);
1051         }
1052
1053         else if (!strncasecmp(cmdbuf,"USER",4)) {
1054                 cmd_user(&cmdbuf[5]);
1055         }
1056
1057         else if (!strncasecmp(cmdbuf,"PASS",4)) {
1058                 cmd_pass(&cmdbuf[5]);
1059         }
1060
1061         else if (!strncasecmp(cmdbuf,"NEWU",4)) {
1062                 cmd_newu(&cmdbuf[5]);
1063         }
1064
1065         else if (!strncasecmp(cmdbuf,"CREU",4)) {
1066                 cmd_creu(&cmdbuf[5]);
1067         }
1068
1069         else if (!strncasecmp(cmdbuf,"SETP",4)) {
1070                 cmd_setp(&cmdbuf[5]);
1071         }
1072
1073         else if (!strncasecmp(cmdbuf,"LRMS",4)) {
1074                 cmd_lrms(&cmdbuf[5]);
1075         }
1076
1077         else if (!strncasecmp(cmdbuf,"LKRA",4)) {
1078                 cmd_lkra(&cmdbuf[5]);
1079         }
1080
1081         else if (!strncasecmp(cmdbuf,"LKRN",4)) {
1082                 cmd_lkrn(&cmdbuf[5]);
1083         }
1084
1085         else if (!strncasecmp(cmdbuf,"LKRO",4)) {
1086                 cmd_lkro(&cmdbuf[5]);
1087         }
1088
1089         else if (!strncasecmp(cmdbuf,"LZRM",4)) {
1090                 cmd_lzrm(&cmdbuf[5]);
1091         }
1092
1093         else if (!strncasecmp(cmdbuf,"LPRM",4)) {
1094                 cmd_lprm(&cmdbuf[5]);
1095         }
1096
1097         else if (!strncasecmp(cmdbuf,"GETU",4)) {
1098                 cmd_getu();
1099         }
1100
1101         else if (!strncasecmp(cmdbuf,"SETU",4)) {
1102                 cmd_setu(&cmdbuf[5]);
1103         }
1104
1105         else if (!strncasecmp(cmdbuf,"GOTO",4)) {
1106                 cmd_goto(&cmdbuf[5]);
1107         }
1108
1109         else if (!strncasecmp(cmdbuf,"MSGS",4)) {
1110                 cmd_msgs(&cmdbuf[5]);
1111         }
1112
1113         else if (!strncasecmp(cmdbuf,"WHOK",4)) {
1114                 cmd_whok();
1115         }
1116
1117         else if (!strncasecmp(cmdbuf,"RDIR",4)) {
1118                 cmd_rdir();
1119         }
1120
1121         else if (!strncasecmp(cmdbuf,"EUID",4)) {
1122                 cmd_euid(&cmdbuf[5]);
1123         }
1124
1125         else if (!strncasecmp(cmdbuf,"MSG0",4)) {
1126                 cmd_msg0(&cmdbuf[5]);
1127         }
1128
1129         else if (!strncasecmp(cmdbuf,"MSG2",4)) {
1130                 cmd_msg2(&cmdbuf[5]);
1131         }
1132
1133         else if (!strncasecmp(cmdbuf,"MSG3",4)) {
1134                 cmd_msg3(&cmdbuf[5]);
1135         }
1136
1137         else if (!strncasecmp(cmdbuf,"MSG4",4)) {
1138                 cmd_msg4(&cmdbuf[5]);
1139         }
1140
1141         else if (!strncasecmp(cmdbuf,"MSGP",4)) {
1142                 cmd_msgp(&cmdbuf[5]);
1143         }
1144
1145         else if (!strncasecmp(cmdbuf,"OPNA",4)) {
1146                 cmd_opna(&cmdbuf[5]);
1147         }
1148
1149         else if (!strncasecmp(cmdbuf,"DLAT",4)) {
1150                 cmd_dlat(&cmdbuf[5]);
1151         }
1152
1153         else if (!strncasecmp(cmdbuf,"INFO",4)) {
1154                 cmd_info();
1155         }
1156
1157         else if (!strncasecmp(cmdbuf,"SLRP",4)) {
1158                 cmd_slrp(&cmdbuf[5]);
1159         }
1160
1161         else if (!strncasecmp(cmdbuf,"INVT",4)) {
1162                 cmd_invt_kick(&cmdbuf[5],1);
1163         }
1164
1165         else if (!strncasecmp(cmdbuf,"KICK",4)) {
1166                 cmd_invt_kick(&cmdbuf[5],0);
1167         }
1168
1169         else if (!strncasecmp(cmdbuf,"GETR",4)) {
1170                 cmd_getr();
1171         }
1172
1173         else if (!strncasecmp(cmdbuf,"SETR",4)) {
1174                 cmd_setr(&cmdbuf[5]);
1175         }
1176
1177         else if (!strncasecmp(cmdbuf,"GETA",4)) {
1178                 cmd_geta();
1179         }
1180
1181         else if (!strncasecmp(cmdbuf,"SETA",4)) {
1182                 cmd_seta(&cmdbuf[5]);
1183         }
1184
1185         else if (!strncasecmp(cmdbuf,"ENT0",4)) {
1186                 cmd_ent0(&cmdbuf[5]);
1187         }
1188
1189         else if (!strncasecmp(cmdbuf,"RINF",4)) {
1190                 cmd_rinf();
1191         }
1192
1193         else if (!strncasecmp(cmdbuf,"DELE",4)) {
1194                 cmd_dele(&cmdbuf[5]);
1195         }
1196
1197         else if (!strncasecmp(cmdbuf,"KILL",4)) {
1198                 cmd_kill(&cmdbuf[5]);
1199         }
1200
1201         else if (!strncasecmp(cmdbuf,"CRE8",4)) {
1202                 cmd_cre8(&cmdbuf[5]);
1203         }
1204
1205         else if (!strncasecmp(cmdbuf,"MOVE",4)) {
1206                 cmd_move(&cmdbuf[5]);
1207         }
1208
1209         else if (!strncasecmp(cmdbuf,"FORG",4)) {
1210                 cmd_forg();
1211         }
1212
1213         else if (!strncasecmp(cmdbuf,"MESG",4)) {
1214                 cmd_mesg(&cmdbuf[5]);
1215         }
1216
1217         else if (!strncasecmp(cmdbuf,"EMSG",4)) {
1218                 cmd_emsg(&cmdbuf[5]);
1219         }
1220
1221         else if (!strncasecmp(cmdbuf,"GNUR",4)) {
1222                 cmd_gnur();
1223         }
1224
1225         else if (!strncasecmp(cmdbuf,"VALI",4)) {
1226                 cmd_vali(&cmdbuf[5]);
1227         }
1228
1229         else if (!strncasecmp(cmdbuf,"EINF",4)) {
1230                 cmd_einf(&cmdbuf[5]);
1231         }
1232
1233         else if (!strncasecmp(cmdbuf,"LIST",4)) {
1234                 cmd_list(&cmdbuf[5]);
1235         }
1236
1237         else if (!strncasecmp(cmdbuf,"CHEK",4)) {
1238                 cmd_chek();
1239         }
1240
1241         else if (!strncasecmp(cmdbuf,"DELF",4)) {
1242                 cmd_delf(&cmdbuf[5]);
1243         }
1244
1245         else if (!strncasecmp(cmdbuf,"MOVF",4)) {
1246                 cmd_movf(&cmdbuf[5]);
1247         }
1248
1249         else if (!strncasecmp(cmdbuf,"NETF",4)) {
1250                 cmd_netf(&cmdbuf[5]);
1251         }
1252
1253         else if (!strncasecmp(cmdbuf,"OPEN",4)) {
1254                 cmd_open(&cmdbuf[5]);
1255         }
1256
1257         else if (!strncasecmp(cmdbuf,"CLOS",4)) {
1258                 cmd_clos();
1259         }
1260
1261         else if (!strncasecmp(cmdbuf,"UOPN",4)) {
1262                 cmd_uopn(&cmdbuf[5]);
1263         }
1264
1265         else if (!strncasecmp(cmdbuf,"UCLS",4)) {
1266                 cmd_ucls(&cmdbuf[5]);
1267         }
1268
1269         else if (!strncasecmp(cmdbuf,"READ",4)) {
1270                 cmd_read(&cmdbuf[5]);
1271         }
1272
1273         else if (!strncasecmp(cmdbuf,"WRIT",4)) {
1274                 cmd_writ(&cmdbuf[5]);
1275         }
1276
1277         else if (!strncasecmp(cmdbuf,"QUSR",4)) {
1278                 cmd_qusr(&cmdbuf[5]);
1279         }
1280
1281         else if (!strncasecmp(cmdbuf,"ECHO",4)) {
1282                 cmd_echo(&cmdbuf[5]);
1283         }
1284
1285         else if (!strncasecmp(cmdbuf,"OIMG",4)) {
1286                 cmd_oimg(&cmdbuf[5]);
1287         }
1288
1289         else if (!strncasecmp(cmdbuf,"MORE",4)) {
1290                 cmd_more();
1291         }
1292
1293         else if (!strncasecmp(cmdbuf,"NDOP",4)) {
1294                 cmd_ndop(&cmdbuf[5]);
1295         }
1296
1297         else if (!strncasecmp(cmdbuf,"NUOP",4)) {
1298                 cmd_nuop(&cmdbuf[5]);
1299         }
1300
1301         else if (!strncasecmp(cmdbuf,"LFLR",4)) {
1302                 cmd_lflr();
1303         }
1304
1305         else if (!strncasecmp(cmdbuf,"CFLR",4)) {
1306                 cmd_cflr(&cmdbuf[5]);
1307         }
1308
1309         else if (!strncasecmp(cmdbuf,"KFLR",4)) {
1310                 cmd_kflr(&cmdbuf[5]);
1311         }
1312
1313         else if (!strncasecmp(cmdbuf,"EFLR",4)) {
1314                 cmd_eflr(&cmdbuf[5]);
1315         }
1316
1317         else if (!strncasecmp(cmdbuf,"IDEN",4)) {
1318                 cmd_iden(&cmdbuf[5]);
1319         }
1320
1321         else if (!strncasecmp(cmdbuf,"IPGM",4)) {
1322                 cmd_ipgm(&cmdbuf[5]);
1323         }
1324
1325         else if (!strncasecmp(cmdbuf,"TERM",4)) {
1326                 cmd_term(&cmdbuf[5]);
1327         }
1328
1329         else if (!strncasecmp(cmdbuf,"DOWN",4)) {
1330                 cmd_down(&cmdbuf[5]);
1331         }
1332
1333         else if (!strncasecmp(cmdbuf,"HALT",4)) {
1334                 cmd_halt();
1335         }
1336
1337         else if (!strncasecmp(cmdbuf,"SCDN",4)) {
1338                 cmd_scdn(&cmdbuf[5]);
1339         }
1340
1341         else if (!strncasecmp(cmdbuf, "UIMG", 4)) {
1342                 cmd_uimg(&cmdbuf[5]);
1343         }
1344
1345         else if (!strncasecmp(cmdbuf, "TIME", 4)) {
1346                 cmd_time();
1347         }
1348
1349         else if (!strncasecmp(cmdbuf, "AGUP", 4)) {
1350                 cmd_agup(&cmdbuf[5]);
1351         }
1352
1353         else if (!strncasecmp(cmdbuf, "ASUP", 4)) {
1354                 cmd_asup(&cmdbuf[5]);
1355         }
1356
1357         else if (!strncasecmp(cmdbuf, "GPEX", 4)) {
1358                 cmd_gpex(&cmdbuf[5]);
1359         }
1360
1361         else if (!strncasecmp(cmdbuf, "SPEX", 4)) {
1362                 cmd_spex(&cmdbuf[5]);
1363         }
1364
1365         else if (!strncasecmp(cmdbuf, "CONF", 4)) {
1366                 cmd_conf(&cmdbuf[5]);
1367         }
1368
1369         else if (!strncasecmp(cmdbuf, "SEEN", 4)) {
1370                 cmd_seen(&cmdbuf[5]);
1371         }
1372
1373         else if (!strncasecmp(cmdbuf, "GTSN", 4)) {
1374                 cmd_gtsn(&cmdbuf[5]);
1375         }
1376
1377         else if (!strncasecmp(cmdbuf, "VIEW", 4)) {
1378                 cmd_view(&cmdbuf[5]);
1379         }
1380
1381         else if (!strncasecmp(cmdbuf, "ISME", 4)) {
1382                 cmd_isme(&cmdbuf[5]);
1383         }
1384
1385         else if (!DLoader_Exec_Cmd(cmdbuf)) {
1386                 cprintf("%d Unrecognized or unsupported command.\n",
1387                         ERROR + CMD_NOT_SUPPORTED);
1388                }
1389
1390         unbuffer_output();
1391
1392         /* Run any after-each-command routines registered by modules */
1393         PerformSessionHooks(EVT_CMD);
1394 }
1395
1396
1397 /*
1398  * This loop performs all asynchronous functions.
1399  */
1400 void do_async_loop(void) {
1401         PerformSessionHooks(EVT_ASYNC);
1402 }