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