* Removed the idle timer from the client. Dialup is dead.
[citadel.git] / citadel / commands.c
1 /*
2  * $Id$
3  *
4  * This file contains functions which implement parts of the
5  * text-mode user interface.
6  *
7  */
8
9 #include "sysdep.h"
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <stdio.h>
13 #include <fcntl.h>
14 #include <ctype.h>
15 #include <string.h>
16 #include <sys/types.h>
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 #ifdef HAVE_TERMIOS_H
30 #include <termios.h>
31 #else
32 #include <sgtty.h>
33 #endif
34
35 #ifdef HAVE_SYS_SELECT_H
36 #include <sys/select.h>
37 #endif
38
39 #ifdef THREADED_CLIENT
40 #include <pthread.h>
41 #endif
42
43 #include <signal.h>
44 #include <errno.h>
45 #include <stdarg.h>
46 #include "citadel.h"
47 #include "commands.h"
48 #include "messages.h"
49 #include "citadel_decls.h"
50 #include "routines.h"
51 #include "routines2.h"
52 #include "tools.h"
53 #include "rooms.h"
54 #include "client_chat.h"
55 #ifndef HAVE_SNPRINTF
56 #include "snprintf.h"
57 #endif
58
59 struct citcmd {
60         struct citcmd *next;
61         int c_cmdnum;
62         int c_axlevel;
63         char c_keys[5][64];
64 };
65
66 #define IFNEXPERT if ((userflags&US_EXPERT)==0)
67
68
69 int rc_exp_beep;
70 char rc_exp_cmd[1024];
71 int rc_allow_attachments;
72 int rc_display_message_numbers;
73 int rc_force_mail_prompts;
74 int rc_remember_passwords;
75 int rc_ansi_color;
76 int num_urls = 0;
77 char urls[MAXURLS][SIZ];
78 char rc_url_cmd[SIZ];
79
80 char *gl_string;
81 int next_lazy_cmd = 5;
82
83 int lines_printed = 0;          /* line count for paginator */
84 extern int screenwidth, screenheight;
85 extern int termn8;
86
87 struct citcmd *cmdlist = NULL;
88
89
90 /* these variables are local to this module */
91 char keepalives_enabled = KA_YES;       /* send NOOPs to server when idle */
92 int ok_to_interrupt = 0;                /* print express msgs asynchronously */
93 time_t AnsiDetect;                      /* when did we send the detect code? */
94 int enable_color = 0;                   /* nonzero for ANSI color */
95
96
97
98
99 /*
100  * If an interesting key has been pressed, return its value, otherwise 0
101  */
102 char was_a_key_pressed(void) {
103         fd_set rfds;
104         struct timeval tv;
105         int the_character;
106         int retval;
107
108         FD_ZERO(&rfds);
109         FD_SET(0, &rfds);
110         tv.tv_sec = 0;
111         tv.tv_usec = 0;
112         retval = select(1, &rfds, NULL, NULL, &tv); 
113
114         /* Careful!  Disable keepalives during keyboard polling; we're probably
115          * in the middle of a data transfer from the server, in which case
116          * sending a NOOP would throw the client protocol out of sync.
117          */
118         if (FD_ISSET(0, &rfds)) {
119                 set_keepalives(KA_NO);
120                 the_character = inkey();
121                 set_keepalives(KA_YES);
122         }
123         else {
124                 the_character = 0;
125         }
126         return(the_character);
127 }
128
129
130
131
132
133 /*
134  * Check to see if we need to pause at the end of a screen.
135  * If we do, we have to disable server keepalives during the pause because
136  * we are probably in the middle of a server operation and the NOOP command
137  * would confuse everything.
138  */
139 int checkpagin(int lp, int pagin, int height)
140 {
141         int thekey;
142
143         if (sigcaught) return(lp);
144         thekey = was_a_key_pressed();
145         if ( (thekey == NEXT_KEY) || (thekey == STOP_KEY)) sigcaught = thekey;
146         if (sigcaught) return(lp);
147
148         if (!pagin) return(0);
149         if (lp>=(height-1)) {
150                 set_keepalives(KA_NO);
151                 hit_any_key();
152                 set_keepalives(KA_YES);
153                 return(0);
154         }
155         return(lp);
156 }
157
158
159
160
161 /*
162  * pprintf()  ...   paginated version of printf()
163  */
164 void pprintf(const char *format, ...) {   
165         va_list arg_ptr;
166         static char buf[4096];  /* static for performance, change if needed */
167         int i;
168
169         /* If sigcaught is nonzero, a keypress has interrupted this and we
170          * should just drain output.
171          */
172         if (sigcaught) return;
173  
174         /* Otherwise, start spewing... */ 
175         va_start(arg_ptr, format);   
176         vsprintf(buf, format, arg_ptr);   
177         va_end(arg_ptr);   
178
179         for (i=0; i<strlen(buf); ++i) {
180                 putc(buf[i], stdout);
181                 if (buf[i]==10) {
182                         ++lines_printed;
183                         lines_printed = checkpagin(lines_printed,
184                                 (userflags & US_PAGINATOR),
185                                 screenheight);
186                 }
187         }
188 }   
189
190
191
192 /*
193  * print_express()  -  print express messages if there are any
194  */
195 void print_express(void)
196 {
197         char buf[1024];
198         FILE *outpipe;
199         time_t timestamp;
200         struct tm *stamp;
201         int flags = 0;
202         char sender[64];
203         char node[64];
204
205         if (express_msgs == 0)
206                 return;
207
208         if (rc_exp_beep) {
209                 putc(7, stdout);
210         }
211         if (strlen(rc_exp_cmd) == 0) {
212                 color(BRIGHT_RED);
213                 printf("\r---");
214         }
215         
216         while (express_msgs != 0) {
217                 serv_puts("GEXP");
218                 serv_gets(buf);
219                 if (buf[0] != '1')
220                         return;
221         
222                 express_msgs = extract_int(&buf[4], 0);
223                 timestamp = extract_long(&buf[4], 1);
224                 flags = extract_int(&buf[4], 2);
225                 extract(sender, &buf[4], 3);
226                 extract(node, &buf[4], 4);
227                 strcpy(last_paged, sender);
228         
229                 stamp = localtime(&timestamp);
230
231                 /* If the page is a Logoff Request, honor it. */
232                 if (flags & 2) {
233                         termn8 = 1;
234                         return;
235                 }
236         
237                 if (strlen(rc_exp_cmd) > 0) {
238                         outpipe = popen(rc_exp_cmd, "w");
239                         if (outpipe != NULL) {
240                                 /* Header derived from flags */
241                                 if (flags & 2)
242                                         fprintf(outpipe,
243                                                "Please log off now, as requested ");
244                                 else if (flags & 1)
245                                         fprintf(outpipe, "Broadcast message ");
246                                 else if (flags & 4)
247                                         fprintf(outpipe, "Chat request ");
248                                 else
249                                         fprintf(outpipe, "Message ");
250                                 /* Timestamp.  Can this be improved? */
251                                 if (stamp->tm_hour == 0 || stamp->tm_hour == 12)
252                                         fprintf(outpipe, "at 12:%02d%cm",
253                                                 stamp->tm_min, 
254                                                 stamp->tm_hour ? 'p' : 'a');
255                                 else if (stamp->tm_hour > 12)           /* pm */
256                                         fprintf(outpipe, "at %d:%02dpm",
257                                                 stamp->tm_hour - 12,
258                                                 stamp->tm_min);
259                                 else                                    /* am */
260                                         fprintf(outpipe, "at %d:%02dam",
261                                                 stamp->tm_hour, stamp->tm_min);
262                                 fprintf(outpipe, " from %s", sender);
263                                 if (strncmp(serv_info.serv_nodename, node, 32))
264                                         fprintf(outpipe, " @%s", node);
265                                 fprintf(outpipe, ":\n");
266                                 while (serv_gets(buf), strcmp(buf, "000")) {
267                                         fprintf(outpipe, "%s\n", buf);
268                                 }
269                                 pclose(outpipe);
270                                 if (express_msgs == 0)
271                                         return;
272                                 continue;
273                         }
274                 }
275                 /* fall back to built-in express message display */
276                 printf("\n");
277
278                 /* Header derived from flags */
279                 if (flags & 2)
280                         printf("Please log off now, as requested ");
281                 else if (flags & 1)
282                         printf("Broadcast message ");
283                 else if (flags & 4)
284                         printf("Chat request ");
285                 else
286                         printf("Message ");
287         
288                 /* Timestamp.  Can this be improved? */
289                 if (stamp->tm_hour == 0 || stamp->tm_hour == 12)/* 12am/12pm */
290                         printf("at 12:%02d%cm", stamp->tm_min, 
291                                 stamp->tm_hour ? 'p' : 'a');
292                 else if (stamp->tm_hour > 12)                   /* pm */
293                         printf("at %d:%02dpm",
294                                 stamp->tm_hour - 12, stamp->tm_min);
295                 else                                            /* am */
296                         printf("at %d:%02dam", stamp->tm_hour, stamp->tm_min);
297                 
298                 /* Sender */
299                 printf(" from %s", sender);
300         
301                 /* Remote node, if any */
302                 if (strncmp(serv_info.serv_nodename, node, 32))
303                         printf(" @%s", node);
304         
305                 printf(":\n");
306         
307                 while (serv_gets(buf), strcmp(buf, "000")) {
308                         printf("%s", buf);
309                 }
310         }
311         printf("\n---\n");
312         color(BRIGHT_WHITE);
313
314
315 }
316
317
318 void set_keepalives(int s)
319 {
320         keepalives_enabled = (char) s;
321 }
322
323 /* 
324  * This loop handles the "keepalive" messages sent to the server when idling.
325  */
326
327 static time_t idlet = 0;
328 static void really_do_keepalive(void) {
329         char buf[1024];
330
331         time(&idlet);
332         if (keepalives_enabled == KA_YES) {
333                 serv_puts("NOOP");
334                 serv_gets(buf);
335                 if (buf[3] == '*') {
336                         express_msgs = 1;
337                         if (ok_to_interrupt == 1) {
338                                 printf("\r%64s\r", "");
339                                 print_express();
340                                 printf("%s%c ", room_name,
341                                        room_prompt(room_flags));
342                                 fflush(stdout);
343                         }
344                 }
345         }
346 }
347
348 /* threaded nonblocking keepalive stuff starts here. I'm going for a simple
349    encapsulated interface; in theory there should be no need to touch these
350    globals outside of the async_ka_* functions. */
351
352 #ifdef THREADED_CLIENT
353 static pthread_t ka_thr_handle;
354 static int ka_thr_active = 0;
355 static int async_ka_enabled = 0;
356
357 static void *ka_thread(void *arg)
358 {
359         really_do_keepalive();
360         pthread_detach(ka_thr_handle);
361         ka_thr_active = 0;
362         return NULL;
363 }
364
365 /* start up a thread to handle a keepalive in the background */
366 static void async_ka_exec(void)
367 {
368         if (!ka_thr_active) {
369                 ka_thr_active = 1;
370                 if (pthread_create(&ka_thr_handle, NULL, ka_thread, NULL)) {
371                         perror("pthread_create");
372                         exit(1);
373                 }
374         }
375 }
376 #endif /* THREADED_CLIENT */
377
378 static void do_keepalive(void)
379 {
380         time_t now;
381
382         time(&now);
383         if ((now - idlet) < ((long) S_KEEPALIVE))
384                 return;
385
386         /* Do a space-backspace to keep telnet sessions from idling out */
387         printf(" %c", 8);
388         fflush(stdout);
389
390 #ifdef THREADED_CLIENT
391         if (async_ka_enabled)
392                 async_ka_exec();
393         else
394 #endif
395                 really_do_keepalive();
396 }
397
398
399 /* Now the actual async-keepalve API that we expose to higher levels:
400    async_ka_start() and async_ka_end(). These do nothing when we don't have
401    threading enabled, so we avoid sprinkling ifdef's throughout the code. */
402
403 /* wait for a background keepalive to complete. this must be done before
404    attempting any further server requests! */
405 void async_ka_end(void)
406 {
407 #ifdef THREADED_CLIENT
408         if (ka_thr_active)
409                 pthread_join(ka_thr_handle, NULL);
410
411         async_ka_enabled--;
412 #endif
413 }
414
415 /* tell do_keepalive() that keepalives are asynchronous. */
416 void async_ka_start(void)
417 {
418 #ifdef THREADED_CLIENT
419         async_ka_enabled++;
420 #endif
421 }
422
423
424 int inkey(void)
425 {                               /* get a character from the keyboard, with   */
426         int a;                  /* the watchdog timer in effect if necessary */
427         fd_set rfds;
428         struct timeval tv;
429         time_t start_time, now;
430         char inbuf[2];
431
432         fflush(stdout);
433         lines_printed = 0;
434         time(&start_time);
435
436         do {
437
438                 /* This loop waits for keyboard input.  If the keepalive
439                  * timer expires, it sends a keepalive to the server if
440                  * necessary and then waits again.
441                  */
442                 do {
443                         do_keepalive();
444
445                         FD_ZERO(&rfds);
446                         FD_SET(0, &rfds);
447                         tv.tv_sec = S_KEEPALIVE;
448                         tv.tv_usec = 0;
449
450                         time(&now);
451                         select(1, &rfds, NULL, NULL, &tv);
452                 } while (!FD_ISSET(0, &rfds));
453
454
455
456
457                 /* At this point, there's input, so fetch it.
458                  * (There's a hole in the bucket...)
459                  */
460                 read(0, inbuf, 1);
461                 a = inbuf[0];
462                 if (a == 127)
463                         a = 8;
464                 if (a > 126)
465                         a = 0;
466                 if (a == 10)
467                         a = 13;
468                 if (((a != 4) && (a != 13) && (a != 8) && (a != NEXT_KEY) && (a != STOP_KEY))
469                     && ((a < 32) || (a > 126)))
470                         a = 0;
471         } while (a == 0);
472         return (a);
473 }
474
475
476 int yesno(void)
477 {                               /* Returns 1 for yes, 0 for no */
478         int a;
479         while (1) {
480                 a = inkey();
481                 a = tolower(a);
482                 if (a == 'y') {
483                         printf("Yes\n");
484                         return (1);
485                 }
486                 if (a == 'n') {
487                         printf("No\n");
488                         return (0);
489                 }
490         }
491 }
492
493 /* Returns 1 for yes, 0 for no, arg is default value */
494 int yesno_d(int d)
495 {
496         int a;
497         while (1) {
498                 a = inkey();
499                 a = tolower(a);
500                 if (a == 13)
501                         a = (d ? 'y' : 'n');
502                 if (a == 'y') {
503                         printf("Yes\n");
504                         return (1);
505                 }
506                 if (a == 'n') {
507                         printf("No\n");
508                         return (0);
509                 }
510         }
511 }
512
513
514
515
516 /* Gets a line from the terminal */
517 /* string == Pointer to string buffer */
518 /* lim == Maximum length - if negative, no-show */
519 void getline(char *string, int lim) 
520 {
521         int a, b;
522         char flag = 0;
523
524         if (lim < 0) {
525                 lim = (0 - lim);
526                 flag = 1;
527         }
528         strcpy(string, "");
529         gl_string = string;
530         async_ka_start();
531       GLA:a = inkey();
532         a = (a & 127);
533         if ((a == 8) && (strlen(string) == 0))
534                 goto GLA;
535         if ((a != 13) && (a != 8) && (strlen(string) == lim))
536                 goto GLA;
537         if ((a == 8) && (string[0] != 0)) {
538                 string[strlen(string) - 1] = 0;
539                 putc(8, stdout);
540                 putc(32, stdout);
541                 putc(8, stdout);
542                 goto GLA;
543         }
544         if ((a == 13) || (a == 10)) {
545                 putc(13, stdout);
546                 putc(10, stdout);
547                 async_ka_end();
548                 return;
549         }
550         if (a < 32)
551                 a = '.';
552         b = strlen(string);
553         string[b] = a;
554         string[b + 1] = 0;
555         if (flag == 0)
556                 putc(a, stdout);
557         if (flag == 1)
558                 putc('*', stdout);
559         goto GLA;
560 }
561
562
563 /*
564  * strprompt()  -  prompt for a string, print the existing value and
565  *                 allow the user to press return to keep it...
566  */
567 void strprompt(char *prompt, char *str, int len)
568 {
569         char buf[128];
570         print_express();
571         color(DIM_WHITE);
572         printf("%s ", prompt);
573         color(DIM_MAGENTA);
574         printf("[");
575         color(BRIGHT_MAGENTA);
576         printf("%s", str);
577         color(DIM_MAGENTA);
578         printf("]");
579         color(DIM_WHITE);
580         printf(": ");
581         color(BRIGHT_CYAN);
582         getline(buf, len);
583         if (buf[0] != 0)
584                 strcpy(str, buf);
585         color(DIM_WHITE);
586 }
587
588 /*
589  * boolprompt()  -  prompt for a yes/no, print the existing value and
590  *                  allow the user to press return to keep it...
591  */
592 int boolprompt(char *prompt, int prev_val)
593 {
594         int r;
595
596         color(DIM_WHITE);
597         printf("%s ", prompt);
598         color(DIM_MAGENTA);
599         printf(" [");
600         color(BRIGHT_MAGENTA);
601         printf("%s", (prev_val ? "Yes" : "No"));
602         color(DIM_MAGENTA);
603         printf("]: ");
604         color(BRIGHT_CYAN);
605         r = (yesno_d(prev_val));
606         color(DIM_WHITE);
607         return r;
608 }
609
610 /* 
611  * intprompt()  -  like strprompt(), except for an integer
612  *                 (note that it RETURNS the new value!)
613  */
614 int intprompt(char *prompt, int ival, int imin, int imax)
615 {
616         char buf[16];
617         int i;
618         int p;
619
620         do {
621                 i = ival;
622                 snprintf(buf, sizeof buf, "%d", i);
623                 strprompt(prompt, buf, 15);
624                 i = atoi(buf);
625                 for (p=0; p<strlen(buf); ++p) {
626                         if ( (!isdigit(buf[p]))
627                            && ( (buf[p]!='-') || (p!=0) )  )
628                                 i = imin - 1;
629                 }
630                 if (i < imin)
631                         printf("*** Must be no less than %d.\n", imin);
632                 if (i > imax)
633                         printf("*** Must be no more than %d.\n", imax);
634         } while ((i < imin) || (i > imax));
635         return (i);
636 }
637
638 /* 
639  * newprompt()  -  prompt for a string with no existing value
640  *                 (clears out string buffer first)
641  */
642 void newprompt(char *prompt, char *str, int len)
643 {
644         color(BRIGHT_MAGENTA);
645         printf("%s", prompt);
646         color(DIM_MAGENTA);
647         getline(str, len);
648         color(DIM_WHITE);
649 }
650
651
652 int lkey(void)
653 {                               /* returns a lower case value */
654         int a;
655         a = inkey();
656         if (isupper(a))
657                 a = tolower(a);
658         return (a);
659 }
660
661 /*
662  * parse the citadel.rc file
663  */
664 void load_command_set(void)
665 {
666         FILE *ccfile;
667         char buf[1024];
668         struct citcmd *cptr;
669         struct citcmd *lastcmd = NULL;
670         int a, d;
671         int b = 0;
672
673
674         /* first, set up some defaults for non-required variables */
675
676         strcpy(editor_path, "");
677         strcpy(printcmd, "");
678         strcpy(rc_username, "");
679         strcpy(rc_password, "");
680         rc_floor_mode = 0;
681         rc_exp_beep = 1;
682         rc_allow_attachments = 0;
683         rc_remember_passwords = 0;
684         strcpy(rc_exp_cmd, "");
685         rc_display_message_numbers = 0;
686         rc_force_mail_prompts = 0;
687         rc_ansi_color = 0;
688         strcpy(rc_url_cmd, "");
689
690         /* now try to open the citadel.rc file */
691
692         ccfile = NULL;
693         if (getenv("HOME") != NULL) {
694                 snprintf(buf, sizeof buf, "%s/.citadelrc", getenv("HOME"));
695                 ccfile = fopen(buf, "r");
696         }
697         if (ccfile == NULL) {
698                 ccfile = fopen("/usr/local/lib/citadel.rc", "r");
699         }
700         if (ccfile == NULL) {
701                 snprintf(buf, sizeof buf, "%s/citadel.rc", BBSDIR);
702                 ccfile = fopen(buf, "r");
703         }
704         if (ccfile == NULL) {
705                 ccfile = fopen("./citadel.rc", "r");
706         }
707         if (ccfile == NULL) {
708                 perror("commands: cannot open citadel.rc");
709                 logoff(errno);
710         }
711         while (fgets(buf, sizeof buf, ccfile) != NULL) {
712                 while ((strlen(buf) > 0) ? (isspace(buf[strlen(buf) - 1])) : 0)
713                         buf[strlen(buf) - 1] = 0;
714
715                 if (!strncasecmp(buf, "editor=", 7))
716                         strcpy(editor_path, &buf[7]);
717
718                 if (!strncasecmp(buf, "printcmd=", 9))
719                         strcpy(printcmd, &buf[9]);
720
721                 if (!strncasecmp(buf, "expcmd=", 7))
722                         strcpy(rc_exp_cmd, &buf[7]);
723
724                 if (!strncasecmp(buf, "local_screen_dimensions=", 24))
725                         have_xterm = (char) atoi(&buf[24]);
726
727                 if (!strncasecmp(buf, "use_floors=", 11)) {
728                         if (!strcasecmp(&buf[11], "yes"))
729                                 rc_floor_mode = RC_YES;
730                         if (!strcasecmp(&buf[11], "no"))
731                                 rc_floor_mode = RC_NO;
732                         if (!strcasecmp(&buf[11], "default"))
733                                 rc_floor_mode = RC_DEFAULT;
734                 }
735                 if (!strncasecmp(buf, "beep=", 5)) {
736                         rc_exp_beep = atoi(&buf[5]);
737                 }
738                 if (!strncasecmp(buf, "allow_attachments=", 18)) {
739                         rc_allow_attachments = atoi(&buf[18]);
740                 }
741                 if (!strncasecmp(buf, "remember_passwords=", 19)) {
742                         rc_remember_passwords = atoi(&buf[19]);
743                 }
744                 if (!strncasecmp(buf, "display_message_numbers=", 24)) {
745                         rc_display_message_numbers = atoi(&buf[24]);
746                 }
747                 if (!strncasecmp(buf, "force_mail_prompts=", 19)) {
748                         rc_force_mail_prompts = atoi(&buf[19]);
749                 }
750                 if (!strncasecmp(buf, "ansi_color=", 11)) {
751                         if (!strncasecmp(&buf[11], "on", 2))
752                                 rc_ansi_color = 1;
753                         if (!strncasecmp(&buf[11], "auto", 4))
754                                 rc_ansi_color = 2;      /* autodetect */
755                         if (!strncasecmp(&buf[11], "user", 4))
756                                 rc_ansi_color = 3;      /* user config */
757                 }
758                 if (!strncasecmp(buf, "username=", 9))
759                         strcpy(rc_username, &buf[9]);
760
761                 if (!strncasecmp(buf, "password=", 9))
762                         strcpy(rc_password, &buf[9]);
763
764                 if (!strncasecmp(buf, "urlcmd=", 7))
765                         strcpy(rc_url_cmd, &buf[7]);
766
767                 if (!strncasecmp(buf, "cmd=", 4)) {
768                         strcpy(buf, &buf[4]);
769
770                         cptr = (struct citcmd *) malloc(sizeof(struct citcmd));
771
772                         cptr->c_cmdnum = atoi(buf);
773                         for (d = strlen(buf); d >= 0; --d)
774                                 if (buf[d] == ',')
775                                         b = d;
776                         strcpy(buf, &buf[b + 1]);
777
778                         cptr->c_axlevel = atoi(buf);
779                         for (d = strlen(buf); d >= 0; --d)
780                                 if (buf[d] == ',')
781                                         b = d;
782                         strcpy(buf, &buf[b + 1]);
783
784                         for (a = 0; a < 5; ++a)
785                                 cptr->c_keys[a][0] = 0;
786
787                         a = 0;
788                         b = 0;
789                         buf[strlen(buf) + 1] = 0;
790                         while (strlen(buf) > 0) {
791                                 b = strlen(buf);
792                                 for (d = strlen(buf); d >= 0; --d)
793                                         if (buf[d] == ',')
794                                                 b = d;
795                                 strncpy(cptr->c_keys[a], buf, b);
796                                 cptr->c_keys[a][b] = 0;
797                                 if (buf[b] == ',')
798                                         strcpy(buf, &buf[b + 1]);
799                                 else
800                                         strcpy(buf, "");
801                                 ++a;
802                         }
803
804                         cptr->next = NULL;
805                         if (cmdlist == NULL)
806                                 cmdlist = cptr;
807                         else
808                                 lastcmd->next = cptr;
809                         lastcmd = cptr;
810                 }
811         }
812         fclose(ccfile);
813 }
814
815
816
817 /*
818  * return the key associated with a command
819  */
820 char keycmd(char *cmdstr)
821 {
822         int a;
823
824         for (a = 0; a < strlen(cmdstr); ++a)
825                 if (cmdstr[a] == '&')
826                         return (tolower(cmdstr[a + 1]));
827         return (0);
828 }
829
830
831 /*
832  * Output the string from a key command without the ampersand
833  * "mode" should be set to 0 for normal or 1 for <C>ommand key highlighting
834  */
835 char *cmd_expand(char *strbuf, int mode)
836 {
837         int a;
838         static char exp[64];
839         char buf[1024];
840
841         strcpy(exp, strbuf);
842
843         for (a = 0; a < strlen(exp); ++a) {
844                 if (strbuf[a] == '&') {
845
846                         if (mode == 0) {
847                                 strcpy(&exp[a], &exp[a + 1]);
848                         }
849                         if (mode == 1) {
850                                 exp[a] = '<';
851                                 strcpy(buf, &exp[a + 2]);
852                                 exp[a + 2] = '>';
853                                 exp[a + 3] = 0;
854                                 strcat(exp, buf);
855                         }
856                 }
857                 if (!strncmp(&exp[a], "^r", 2)) {
858                         strcpy(buf, exp);
859                         strcpy(&exp[a], room_name);
860                         strcat(exp, &buf[a + 2]);
861                 }
862                 if (!strncmp(&exp[a], "^c", 2)) {
863                         exp[a] = ',';
864                         strcpy(&exp[a + 1], &exp[a + 2]);
865                 }
866         }
867
868         return (exp);
869 }
870
871
872
873 /*
874  * Comparison function to determine if entered commands match a
875  * command loaded from the config file.
876  */
877 int cmdmatch(char *cmdbuf, struct citcmd *cptr, int ncomp)
878 {
879         int a;
880         int cmdax;
881
882         cmdax = 0;
883         if (is_room_aide)
884                 cmdax = 1;
885         if (axlevel >= 6)
886                 cmdax = 2;
887
888         for (a = 0; a < ncomp; ++a) {
889                 if ((tolower(cmdbuf[a]) != keycmd(cptr->c_keys[a]))
890                     || (cptr->c_axlevel > cmdax))
891                         return (0);
892         }
893         return (1);
894 }
895
896
897 /*
898  * This function returns 1 if a given command requires a string input
899  */
900 int requires_string(struct citcmd *cptr, int ncomp)
901 {
902         int a;
903         char buf[64];
904
905         strcpy(buf, cptr->c_keys[ncomp - 1]);
906         for (a = 0; a < strlen(buf); ++a) {
907                 if (buf[a] == ':')
908                         return (1);
909         }
910         return (0);
911 }
912
913
914 /*
915  * Input a command at the main prompt.
916  * This function returns an integer command number.  If the command prompts
917  * for a string then it is placed in the supplied buffer.
918  */
919 int getcmd(char *argbuf)
920 {
921         char cmdbuf[5];
922         int cmdspaces[5];
923         int cmdpos;
924         int ch;
925         int a;
926         int got;
927         int this_lazy_cmd;
928         struct citcmd *cptr;
929
930         /*
931          * Starting a new command now, so set sigcaught to 0.  This variable
932          * is set to nonzero (usually NEXT_KEY or STOP_KEY) if a command has
933          * been interrupted by a keypress.
934          */
935         sigcaught = 0;
936
937         /* Switch color support on or off if we're in user mode */
938         if (rc_ansi_color == 3) {
939                 if (userflags & US_COLOR)
940                         enable_color = 1;
941                 else
942                         enable_color = 0;
943         }
944         /* if we're running in idiot mode, display a cute little menu */
945         IFNEXPERT formout("mainmenu");
946
947         print_express();        /* print express messages if there are any */
948         strcpy(argbuf, "");
949         cmdpos = 0;
950         for (a = 0; a < 5; ++a)
951                 cmdbuf[a] = 0;
952         /* now the room prompt... */
953         ok_to_interrupt = 1;
954         color(BRIGHT_WHITE);
955         printf("\n%s", room_name);
956         color(DIM_WHITE);
957         printf("%c ", room_prompt(room_flags));
958         fflush(stdout);
959
960         while (1) {
961                 ch = inkey();
962                 ok_to_interrupt = 0;
963
964                 /* Handle the backspace key, but only if there's something
965                  * to backspace over...
966                  */
967                 if ((ch == 8) && (cmdpos > 0)) {
968                         back(cmdspaces[cmdpos - 1] + 1);
969                         cmdbuf[cmdpos] = 0;
970                         --cmdpos;
971                 }
972                 /* Spacebar invokes "lazy traversal" commands */
973                 if ((ch == 32) && (cmdpos == 0)) {
974                         this_lazy_cmd = next_lazy_cmd;
975                         if (this_lazy_cmd == 13)
976                                 next_lazy_cmd = 5;
977                         if (this_lazy_cmd == 5)
978                                 next_lazy_cmd = 13;
979                         for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
980                                 if (cptr->c_cmdnum == this_lazy_cmd) {
981                                         for (a = 0; a < 5; ++a)
982                                                 if (cptr->c_keys[a][0] != 0)
983                                                         printf("%s ", cmd_expand(
984                                                                                         cptr->c_keys[a], 0));
985                                         printf("\n");
986                                         return (this_lazy_cmd);
987                                 }
988                         }
989                         printf("\n");
990                         return (this_lazy_cmd);
991                 }
992                 /* Otherwise, process the command */
993                 cmdbuf[cmdpos] = tolower(ch);
994
995                 for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
996                         if (cmdmatch(cmdbuf, cptr, cmdpos + 1)) {
997
998                                 printf("%s", cmd_expand(cptr->c_keys[cmdpos], 0));
999                                 cmdspaces[cmdpos] = strlen(
1000                                     cmd_expand(cptr->c_keys[cmdpos], 0));
1001                                 if (cmdpos < 4)
1002                                         if ((cptr->c_keys[cmdpos + 1]) != 0)
1003                                                 putc(' ', stdout);
1004                                 ++cmdpos;
1005                         }
1006                 }
1007
1008                 for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1009                         if (cmdmatch(cmdbuf, cptr, 5)) {
1010                                 /* We've found our command. */
1011                                 if (requires_string(cptr, cmdpos)) {
1012                                         getline(argbuf, 32);
1013                                 } else {
1014                                         printf("\n");
1015                                 }
1016
1017                                 /* If this command is one that changes rooms,
1018                                  * then the next lazy-command (space bar)
1019                                  * should be "read new" instead of "goto"
1020                                  */
1021                                 if ((cptr->c_cmdnum == 5)
1022                                     || (cptr->c_cmdnum == 6)
1023                                     || (cptr->c_cmdnum == 47)
1024                                     || (cptr->c_cmdnum == 52)
1025                                     || (cptr->c_cmdnum == 16)
1026                                     || (cptr->c_cmdnum == 20))
1027                                         next_lazy_cmd = 13;
1028
1029                                 return (cptr->c_cmdnum);
1030
1031                         }
1032                 }
1033
1034                 if (ch == '?') {
1035                         pprintf("\rOne of ...                         \n");
1036                         for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1037                                 if (cmdmatch(cmdbuf, cptr, cmdpos)) {
1038                                         for (a = 0; a < 5; ++a) {
1039                                                 pprintf("%s ", cmd_expand(cptr->c_keys[a], 1));
1040                                         }
1041                                         pprintf("\n");
1042                                 }
1043                         }
1044
1045                         pprintf("\n%s%c ", room_name, room_prompt(room_flags));
1046                         got = 0;
1047                         for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1048                                 if ((got == 0) && (cmdmatch(cmdbuf, cptr, cmdpos))) {
1049                                         for (a = 0; a < cmdpos; ++a) {
1050                                                 pprintf("%s ",
1051                                                        cmd_expand(cptr->c_keys[a], 0));
1052                                         }
1053                                         got = 1;
1054                                 }
1055                         }
1056                 }
1057         }
1058
1059 }
1060
1061
1062
1063
1064
1065 /*
1066  * set tty modes.  commands are:
1067  * 
1068  * 01- set to bbs mode
1069  * 2 - save current settings for later restoral
1070  * 3 - restore saved settings
1071  */
1072 #ifdef HAVE_TERMIOS_H
1073 void sttybbs(int cmd)
1074 {                               /* SysV version of sttybbs() */
1075         struct termios live;
1076         static struct termios saved_settings;
1077         static int last_cmd = 0;
1078
1079         if (cmd == SB_LAST)
1080                 cmd = last_cmd;
1081         else
1082                 last_cmd = cmd;
1083
1084         if ((cmd == 0) || (cmd == 1)) {
1085                 tcgetattr(0, &live);
1086                 live.c_iflag = ISTRIP | IXON | IXANY;
1087                 live.c_oflag = OPOST | ONLCR;
1088                 live.c_lflag = ISIG | NOFLSH;
1089
1090                 live.c_cc[VINTR] = (-1);
1091                 live.c_cc[VQUIT] = (-1);
1092
1093 #ifdef hpux
1094                 live.c_cc[VMIN] = 0;
1095                 live.c_cc[VTIME] = 0;
1096 #endif
1097
1098                 /* do we even need this stuff anymore? */
1099                 /* live.c_line=0; */
1100                 live.c_cc[VERASE] = 8;
1101                 live.c_cc[VKILL] = 24;
1102                 live.c_cc[VEOF] = 1;
1103                 live.c_cc[VEOL] = 255;
1104                 live.c_cc[VEOL2] = 0;
1105                 live.c_cc[VSTART] = 0;
1106                 tcsetattr(0, TCSADRAIN, &live);
1107         }
1108         if (cmd == 2) {
1109                 tcgetattr(0, &saved_settings);
1110         }
1111         if (cmd == 3) {
1112                 tcsetattr(0, TCSADRAIN, &saved_settings);
1113         }
1114 }
1115 #else
1116 void sttybbs(int cmd)
1117 {                               /* BSD version of sttybbs() */
1118         struct sgttyb live;
1119         static struct sgttyb saved_settings;
1120
1121         if ((cmd == 0) || (cmd == 1)) {
1122                 gtty(0, &live);
1123                 live.sg_flags |= CBREAK;
1124                 live.sg_flags |= CRMOD;
1125                 live.sg_flags |= NL1;
1126                 live.sg_flags &= ~ECHO;
1127                 if (cmd == 1)
1128                         live.sg_flags |= NOFLSH;
1129                 stty(0, &live);
1130         }
1131         if (cmd == 2) {
1132                 gtty(0, &saved_settings);
1133         }
1134         if (cmd == 3) {
1135                 stty(0, &saved_settings);
1136         }
1137 }
1138 #endif
1139
1140
1141 /*
1142  * display_help()  -  help file viewer
1143  */
1144 void display_help(char *name)
1145 {
1146         formout(name);
1147 }
1148
1149
1150 /*
1151  * fmout()  -  Citadel text formatter and paginator
1152  */
1153 int fmout(
1154         int width,      /* screen width to use */
1155         FILE *fp,       /* file to read from, or NULL to read from server */
1156         char pagin,     /* nonzero if we should use the paginator */
1157         int height,     /* screen height to use */
1158         int starting_lp,/* starting value for lines_printed, -1 for global */
1159         char subst)     /* nonzero if we should use hypertext mode */
1160 {
1161         int a, b, c, d, old;
1162         int real = (-1);
1163         char aaa[140];
1164         char buffer[512];
1165         int eof_flag = 0;
1166
1167         num_urls = 0;   /* Start with a clean slate of embedded URL's */
1168
1169         if (starting_lp >= 0) {
1170                 lines_printed = starting_lp;
1171         }
1172         strcpy(aaa, "");
1173         old = 255;
1174         strcpy(buffer, "");
1175         c = 1;                  /* c is the current pos */
1176
1177 FMTA:   while ((eof_flag == 0) && (strlen(buffer) < 126)) {
1178                 if (fp != NULL) {       /* read from file */
1179                         if (feof(fp))
1180                                 eof_flag = 1;
1181                         if (eof_flag == 0) {
1182                                 a = getc(fp);
1183                                 buffer[strlen(buffer) + 1] = 0;
1184                                 buffer[strlen(buffer)] = a;
1185                         }
1186                 } else {        /* read from server */
1187                         d = strlen(buffer);
1188                         serv_gets(&buffer[d]);
1189                         while ((!isspace(buffer[d])) && (isspace(buffer[strlen(buffer) - 1])))
1190                                 buffer[strlen(buffer) - 1] = 0;
1191                         if (!strcmp(&buffer[d], "000")) {
1192                                 buffer[d] = 0;
1193                                 eof_flag = 1;
1194                                 while (isspace(buffer[strlen(buffer) - 1]))
1195                                         buffer[strlen(buffer) - 1] = 0;
1196                         }
1197                         d = strlen(buffer);
1198                         buffer[d] = 10;
1199                         buffer[d + 1] = 0;
1200                 }
1201         }
1202
1203         if ( (!strncasecmp(buffer, "http://", 7))
1204            || (!strncasecmp(buffer, "ftp://", 6)) ) {
1205                 safestrncpy(urls[num_urls], buffer, (SIZ-1));
1206                 for (a=0; a<strlen(urls[num_urls]); ++a) {
1207                         b = urls[num_urls][a];
1208                         if ( (b==' ') || (b==')') || (b=='>') || (b==10)
1209                            || (b==13) || (b==9) || (b=='\"') )
1210                                 urls[num_urls][a] = 0;
1211                 }
1212                 ++num_urls;
1213         }
1214
1215         buffer[strlen(buffer) + 1] = 0;
1216         a = buffer[0];
1217         strcpy(buffer, &buffer[1]);
1218
1219         old = real;
1220         real = a;
1221         if (a <= 0)
1222                 goto FMTEND;
1223
1224         if (((a == 13) || (a == 10)) && (old != 13) && (old != 10))
1225                 a = 32;
1226         if (((old == 13) || (old == 10)) && (isspace(real))) {
1227                 printf("\n");
1228                 ++lines_printed;
1229                 lines_printed = checkpagin(lines_printed, pagin, height);
1230                 c = 1;
1231         }
1232         if (a > 126)
1233                 goto FMTA;
1234
1235         if (a > 32) {
1236                 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
1237                         printf("\n%s", aaa);
1238                         c = strlen(aaa);
1239                         aaa[0] = 0;
1240                         ++lines_printed;
1241                         lines_printed = checkpagin(lines_printed, pagin, height);
1242                 }
1243                 b = strlen(aaa);
1244                 aaa[b] = a;
1245                 aaa[b + 1] = 0;
1246         }
1247         if (a == 32) {
1248                 if ((strlen(aaa) + c) > (width - 5)) {
1249                         c = 1;
1250                         printf("\n");
1251                         ++lines_printed;
1252                         lines_printed = checkpagin(lines_printed, pagin, height);
1253                 }
1254                 printf("%s ", aaa);
1255                 ++c;
1256                 c = c + strlen(aaa);
1257                 strcpy(aaa, "");
1258                 goto FMTA;
1259         }
1260         if ((a == 13) || (a == 10)) {
1261                 printf("%s\n", aaa);
1262                 c = 1;
1263                 ++lines_printed;
1264                 lines_printed = checkpagin(lines_printed, pagin, height);
1265                 if (sigcaught) goto OOPS;
1266                 strcpy(aaa, "");
1267                 goto FMTA;
1268         }
1269         goto FMTA;
1270
1271         /* keypress caught; drain the server */
1272 OOPS:   do {
1273                 serv_gets(aaa);
1274         } while (strcmp(aaa, "000"));
1275
1276 FMTEND: printf("\n");
1277         ++lines_printed;
1278         lines_printed = checkpagin(lines_printed, pagin, height);
1279         return (sigcaught);
1280 }
1281
1282
1283 /*
1284  * support ANSI color if defined
1285  */
1286 void color(int colornum)
1287 {
1288         static int is_bold = 0;
1289         static int hold_color, current_color;
1290
1291         if (colornum == COLOR_PUSH) {
1292                 hold_color = current_color;
1293                 return;
1294         }
1295
1296         if (colornum == COLOR_POP) {
1297                 color(hold_color);
1298                 return;
1299         }
1300
1301         current_color = colornum;
1302         if (enable_color) {
1303                 /* When switching to dim white, actually output an 'original
1304                  * pair' sequence -- this looks better on black-on-white
1305                  * terminals.
1306                  */
1307                 if (colornum == DIM_WHITE)
1308                         printf("\033[39;49m");
1309                 else
1310                         printf("\033[3%d;40m", (colornum & 7));
1311
1312                 if ((colornum >= 8) && (is_bold == 0)) {
1313                         printf("\033[1m");
1314                         is_bold = 1;
1315                 } else if ((colornum < 8) && (is_bold == 1)) {
1316                         printf("\033[0m");
1317                         is_bold = 0;
1318                 }
1319                 fflush(stdout);
1320         }
1321 }
1322
1323 void cls(int colornum)
1324 {
1325         if (enable_color) {
1326                 printf("\033[4%dm\033[2J\033[H\033[0m", colornum);
1327                 fflush(stdout);
1328         }
1329 }
1330
1331
1332 /*
1333  * Detect whether ANSI color is available (answerback)
1334  */
1335 void send_ansi_detect(void)
1336 {
1337         if (rc_ansi_color == 2) {
1338                 printf("\033[c");
1339                 fflush(stdout);
1340                 time(&AnsiDetect);
1341         }
1342 }
1343
1344 void look_for_ansi(void)
1345 {
1346         fd_set rfds;
1347         struct timeval tv;
1348         char abuf[512];
1349         time_t now;
1350         int a;
1351
1352         if (rc_ansi_color == 0) {
1353                 enable_color = 0;
1354         } else if (rc_ansi_color == 1) {
1355                 enable_color = 1;
1356         } else if (rc_ansi_color == 2) {
1357
1358                 /* otherwise, do the auto-detect */
1359
1360                 strcpy(abuf, "");
1361
1362                 time(&now);
1363                 if ((now - AnsiDetect) < 2)
1364                         sleep(1);
1365
1366                 do {
1367                         FD_ZERO(&rfds);
1368                         FD_SET(0, &rfds);
1369                         tv.tv_sec = 0;
1370                         tv.tv_usec = 1;
1371
1372                         select(1, &rfds, NULL, NULL, &tv);
1373                         if (FD_ISSET(0, &rfds)) {
1374                                 abuf[strlen(abuf) + 1] = 0;
1375                                 read(0, &abuf[strlen(abuf)], 1);
1376                         }
1377                 } while (FD_ISSET(0, &rfds));
1378
1379                 for (a = 0; a < strlen(abuf); ++a) {
1380                         if ((abuf[a] == 27) && (abuf[a + 1] == '[')
1381                             && (abuf[a + 2] == '?')) {
1382                                 enable_color = 1;
1383                         }
1384                 }
1385         }
1386 }
1387
1388
1389 /*
1390  * Display key options (highlight hotkeys inside angle brackets)
1391  */
1392 void keyopt(char *buf) {
1393         int i;
1394
1395         color(DIM_WHITE);
1396         for (i=0; i<strlen(buf); ++i) {
1397                 if (buf[i]=='<') {
1398                         putc(buf[i], stdout);
1399                         color(BRIGHT_MAGENTA);
1400                 } else {
1401                         if (buf[i]=='>') {
1402                                 color(DIM_WHITE);
1403                         }
1404                         putc(buf[i], stdout);
1405                 }
1406         }
1407         color(DIM_WHITE);
1408 }
1409
1410
1411
1412 /*
1413  * Present a key-menu line choice type of thing
1414  */
1415 char keymenu(char *menuprompt, char *menustring) {
1416         int i, c, a;
1417         int choices;
1418         int do_prompt = 0;
1419         char buf[1024];
1420         int ch;
1421         int display_prompt = 1;
1422
1423         choices = num_tokens(menustring, '|');
1424
1425         if (menuprompt != NULL) do_prompt = 1;
1426         if (menuprompt != NULL) if (strlen(menuprompt)==0) do_prompt = 0;
1427
1428         while (1) {
1429                 if (display_prompt) {
1430                         if (do_prompt) {
1431                                 printf("%s ", menuprompt);
1432                         } 
1433                         else {
1434                                 for (i=0; i<choices; ++i) {
1435                                         extract(buf, menustring, i);
1436                                         keyopt(buf);
1437                                         printf(" ");
1438                                 }
1439                         }
1440                         printf(" -> ");
1441                         display_prompt = 0;
1442                 }
1443                 ch = lkey();
1444         
1445                 if ( (do_prompt) && (ch=='?') ) {
1446                         printf("\rOne of...                               ");
1447                         printf("                                      \n");
1448                         for (i=0; i<choices; ++i) {
1449                                 extract(buf, menustring, i);
1450                                 printf("   ");
1451                                 keyopt(buf);
1452                                 printf("\n");
1453                         }
1454                         printf("\n");
1455                         display_prompt = 1;
1456                 }
1457
1458                 for (i=0; i<choices; ++i) {
1459                         extract(buf, menustring, i);
1460                         for (c=1; c<strlen(buf); ++c) {
1461                                 if ( (ch == tolower(buf[c]))
1462                                    && (buf[c-1]=='<')
1463                                    && (buf[c+1]=='>') ) {
1464                                         for (a=0; a<strlen(buf); ++a) {
1465                                                 if ( (a!=(c-1)) && (a!=(c+1))) {
1466                                                         putc(buf[a], stdout);
1467                                                 }
1468                                         }
1469                                         printf("\n\n");
1470                                         return ch;
1471                                 }
1472                         }
1473                 }
1474         }
1475 }