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