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