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