Switch from using RETSIGTYPE via autoconf to void, since POSIX says that's
[mmh] / uip / msh.c
1
2 /*
3  * msh.c -- The nmh shell
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 /*
11  * TODO:
12  *    Keep more status information in maildrop map
13  */
14
15 #include <h/mh.h>
16 #include <fcntl.h>
17 #include <h/signals.h>
18 #include <h/dropsbr.h>
19 #include <h/fmt_scan.h>
20 #include <h/scansbr.h>
21 #include <h/tws.h>
22 #include <h/mts.h>
23 #include <h/utils.h>
24
25 #include <termios.h>
26
27 #include <pwd.h>
28 #include <setjmp.h>
29 #include <signal.h>
30 #include <h/msh.h>
31 #include <h/vmhsbr.h>
32
33 #define QUOTE   '\\'            /* sigh */
34
35 static struct swit switches[] = {
36 #define IDSW                  0
37     { "idstart number", -7 },           /* interface from bbc */
38 #define FDSW                  1
39     { "idstop number", -6 },            /*  .. */
40 #define QDSW                  2
41     { "idquit number", -6 },            /*  .. */
42 #define NMSW                  3
43     { "idname BBoard", -6 },            /*  .. */
44 #define PRMPTSW               4
45     { "prompt string", 0 },
46 #define SCANSW                5
47     { "scan", 0 },
48 #define NSCANSW               6
49     { "noscan", 0 },
50 #define READSW                7
51     { "vmhread fd", -7 },
52 #define WRITESW               8
53     { "vmhwrite fd", -8 },      
54 #define PREADSW               9
55     { "popread fd", -7 },
56 #define PWRITSW              10
57     { "popwrite fd", -8 },
58 #define TCURSW               11
59     { "topcur", 0 },
60 #define NTCURSW              12
61     { "notopcur", 0 },
62 #define VERSIONSW            13
63     { "version", 0 },
64 #define HELPSW               14
65     { "help", 0 },
66     { NULL, 0 }
67 };
68
69 static int mbx_style = MMDF_FORMAT;
70
71 /*
72  * FOLDER
73  */
74 char*fmsh = NULL;                       /* folder instead of file              */
75 int modified;                           /* command modified folder             */
76 struct msgs *mp;                        /* used a lot                          */
77 static int nMsgs = 0;
78 struct Msg *Msgs = NULL;                /* Msgs[0] not used                    */
79 static FILE *fp;                        /* input file                          */
80 static FILE *yp = NULL;                 /* temporary file                      */
81 static int mode;                        /* mode of file                        */
82 static int numfds = 0;                  /* number of files cached              */
83 static int maxfds = 0;                  /* number of files cached to be cached */
84 static time_t mtime = (time_t) 0;       /* mtime of file                       */
85
86 /*
87  * VMH
88  */
89 #define ALARM   ((unsigned int) 10)
90 #define ttyN(c) ttyNaux ((c), NULL)
91
92 static int vmh = 0;
93
94 static int vmhpid = OK;
95 static int vmhfd0;
96 static int vmhfd1;
97 static int vmhfd2;
98
99 static int vmhtty = NOTOK;
100
101 #define SCAN    1
102 #define STATUS  2
103 #define DISPLAY 3
104 #define NWIN    DISPLAY
105
106 static int topcur = 0;
107
108 static int numwins = 0;
109 static int windows[NWIN + 1];
110
111 static jmp_buf peerenv;
112
113 /*
114  * PARENT
115  */
116 static int pfd = NOTOK;         /* fd parent is reading from */
117 static int ppid = 0;            /* pid of parent             */
118
119 /*
120  * COMMAND
121  */
122 int interactive;                /* running from a /dev/tty */
123 int redirected;                 /* re-directing output     */
124 FILE *sp = NULL;                /* original stdout         */
125
126 char *cmd_name;                 /* command being run   */
127 char myfilter[BUFSIZ];          /* path to mhl.forward */
128
129 static char *myprompt = "(%s) ";/* prompting string */
130
131 /*
132  * BBOARDS
133  */
134 static int gap;                 /* gap in BBoard-ID:s */
135 static char *myname = NULL;     /* BBoard name        */
136 char *BBoard_ID = "BBoard-ID";  /* BBoard-ID constant */
137
138 /*
139  * SIGNALS
140  */
141 SIGNAL_HANDLER istat;           /* original SIGINT  */
142 static SIGNAL_HANDLER pstat;    /* current SIGPIPE  */
143 SIGNAL_HANDLER qstat;           /* original SIGQUIT */
144
145 #ifdef SIGTSTP
146 SIGNAL_HANDLER tstat;           /* original SIGTSTP */
147 #endif
148
149 int interrupted;                /* SIGINT detected  */
150 int broken_pipe;                /* SIGPIPE detected */
151 int told_to_quit;               /* SIGQUIT detected */
152
153 #ifdef BSD42
154 int should_intr;                /* signal handler should interrupt call */
155 jmp_buf sigenv;                 /* the environment pointer              */
156 #endif
157
158 /*
159  * prototypes
160  */
161 int SOprintf (char *, ...);  /* from termsbr.c */
162 int sc_width (void);         /* from termsbr.c */
163 void fsetup (char *);
164 void setup (char *);
165 FILE *msh_ready (int, int);
166 void readids (int);
167 int readid (int);
168 void display_info (int);
169 int expand (char *);
170 void m_reset (void);
171 void seq_setcur (struct msgs *, int);
172 void padios (char *, char *, ...);
173 void padvise (char *, char *, ...);
174
175
176 /*
177  * static prototypes
178  */
179 static void msh (int);
180 static int read_map (char *, long);
181 static int read_file (long, int);
182
183 static void m_gMsgs (int);
184 FILE *msh_ready (int, int);
185 static int check_folder (int);
186 static void scanrange (int, int);
187 static void scanstring (char *);
188 static void write_ids (void);
189 static void quit (void);
190 static int getargs (char *, struct swit *, struct Cmd *);
191 static int getcmds (struct swit *, struct Cmd *, int);
192 static int parse (char *, struct Cmd *);
193 static int init_io (struct Cmd *, int);
194 static int initaux_io (struct Cmd *);
195 static void fin_io (struct Cmd *, int);
196 static void finaux_io (struct Cmd *);
197 static void m_init (void);
198 static void intrser (int);
199 static void pipeser (int);
200 static void quitser (int);
201 static void alrmser (int);
202 static int pINI (void);
203 static int pQRY (char *, int);
204 static int pQRY1 (int);
205 static int pQRY2 (void);
206 static int pCMD (char *, struct swit *, struct Cmd *);
207 static int pFIN (void);
208 static int peerwait (void);
209 static int ttyNaux (struct Cmd *, char *);
210 static int ttyR (struct Cmd *);
211 static int winN (struct Cmd *, int, int);
212 static int winR (struct Cmd *);
213 static int winX (int);
214
215
216 int
217 main (int argc, char **argv)
218 {
219     int id = 0, scansw = 0, vmh1 = 0, vmh2 = 0;
220     char *cp, *file = NULL, *folder = NULL;
221     char **argp, **arguments, buf[BUFSIZ];
222
223 #ifdef LOCALE
224     setlocale(LC_ALL, "");
225 #endif
226     invo_name = r1bindex (argv[0], '/');
227
228     /* read user profile/context */
229     context_read();
230
231     mts_init (invo_name);
232     arguments = getarguments (invo_name, argc,argv, 1);
233     argp = arguments;
234
235     while ((cp = *argp++)) {
236         if (*cp == '-')
237             switch (smatch (++cp, switches)) {
238                 case AMBIGSW: 
239                     ambigsw (cp, switches);
240                     done (1);
241                 case UNKWNSW: 
242                     adios (NULL, "-%s unknown", cp);
243
244                 case HELPSW: 
245                     snprintf (buf, sizeof(buf), "%s [switches] file", invo_name);
246                     print_help (buf, switches, 1);
247                     done (1);
248                 case VERSIONSW:
249                     print_version(invo_name);
250                     done (1);
251
252                 case IDSW: 
253                     if (!(cp = *argp++) || *cp == '-')
254                         adios (NULL, "missing argument to %s", argp[-2]);
255                     if ((id = atoi (cp)) < 1)
256                         adios (NULL, "bad argument %s %s", argp[-2], cp);
257                     continue;
258                 case FDSW: 
259                     if (!(cp = *argp++) || *cp == '-')
260                         adios (NULL, "missing argument to %s", argp[-2]);
261                     if ((pfd = atoi (cp)) <= 1)
262                         adios (NULL, "bad argument %s %s", argp[-2], cp);
263                     continue;
264                 case QDSW: 
265                     if (!(cp = *argp++) || *cp == '-')
266                         adios (NULL, "missing argument to %s", argp[-2]);
267                     if ((ppid = atoi (cp)) <= 1)
268                         adios (NULL, "bad argument %s %s", argp[-2], cp);
269                     continue;
270                 case NMSW:
271                     if (!(myname = *argp++) || *myname == '-')
272                         adios (NULL, "missing argument to %s", argp[-2]);
273                     continue;
274
275                 case SCANSW: 
276                     scansw++;
277                     continue;
278                 case NSCANSW: 
279                     scansw = 0;
280                     continue;
281
282                 case PRMPTSW:
283                     if (!(myprompt = *argp++) || *myprompt == '-')
284                         adios (NULL, "missing argument to %s", argp[-2]);
285                     continue;
286
287                 case READSW: 
288                     if (!(cp = *argp++) || *cp == '-')
289                         adios (NULL, "missing argument to %s", argp[-2]);
290                     if ((vmh1 = atoi (cp)) < 1)
291                         adios (NULL, "bad argument %s %s", argp[-2], cp);
292                     continue;
293                 case WRITESW: 
294                     if (!(cp = *argp++) || *cp == '-')
295                         adios (NULL, "missing argument to %s", argp[-2]);
296                     if ((vmh2 = atoi (cp)) < 1)
297                         adios (NULL, "bad argument %s %s", argp[-2], cp);
298                     continue;
299
300                 case PREADSW: 
301                     if (!(cp = *argp++) || *cp == '-')
302                         adios (NULL, "missing argument to %s", argp[-2]);
303                     continue;
304                 case PWRITSW: 
305                     if (!(cp = *argp++) || *cp == '-')
306                         adios (NULL, "missing argument to %s", argp[-2]);
307                     continue;
308
309                 case TCURSW:
310                     topcur++;
311                     continue;
312                 case NTCURSW:
313                     topcur = 0;
314                     continue;
315             }
316         if (*cp == '+' || *cp == '@') {
317             if (folder)
318                 adios (NULL, "only one folder at a time!");
319             else
320                 folder = pluspath (cp);
321         }
322         else
323             if (file)
324                 adios (NULL, "only one file at a time!");
325             else
326                 file = cp;
327     }
328
329     if (!file && !folder)
330         file = "./msgbox";
331     if (file && folder)
332         adios (NULL, "use a file or a folder, not both");
333     strncpy (myfilter, etcpath (mhlforward), sizeof(myfilter));
334 #ifdef FIOCLEX
335     if (pfd > 1)
336         ioctl (pfd, FIOCLEX, NULL);
337 #endif /* FIOCLEX */
338
339 #ifdef BSD42
340     should_intr = 0;
341 #endif  /* BSD42 */
342     istat = SIGNAL2 (SIGINT, intrser);
343     qstat = SIGNAL2 (SIGQUIT, quitser);
344
345     sc_width ();                /* MAGIC... */
346
347     if ((vmh = vmh1 && vmh2)) {
348         rcinit (vmh1, vmh2);
349         pINI ();
350         SIGNAL (SIGINT, SIG_IGN);
351         SIGNAL (SIGQUIT, SIG_IGN);
352 #ifdef SIGTSTP
353         tstat = SIGNAL (SIGTSTP, SIG_IGN);
354 #endif /* SIGTSTP */
355     }
356
357     if (folder)
358         fsetup (folder);
359     else
360         setup (file);
361     readids (id);
362     display_info (id > 0 ? scansw : 0);
363
364     msh (id > 0 ? scansw : 0);
365
366     m_reset ();
367     
368     done (0);
369     return 1;
370 }
371
372
373 static struct swit mshcmds[] = {
374 #define ADVCMD  0
375     { "advance", -7 },
376 #define ALICMD  1
377     { "ali", 0 },
378 #define EXPLCMD 2
379     { "burst", 0 },
380 #define COMPCMD 3
381     { "comp", 0 },
382 #define DISTCMD 4
383     { "dist", 0 },
384 #define EXITCMD 5
385     { "exit", 0 },
386 #define FOLDCMD 6
387     { "folder", 0 },
388 #define FORWCMD 7
389     { "forw", 0 },
390 #define HELPCMD 8
391     { "help", 0 },
392 #define INCMD   9
393     { "inc", 0 },
394 #define MARKCMD 10
395     { "mark", 0 },
396 #define MAILCMD 11
397     { "mhmail", 0 },
398 #define MHNCMD  12
399     { "mhn", 0 },
400 #define MSGKCMD 13
401     { "msgchk", 0 },
402 #define NEXTCMD 14
403     { "next", 0 },
404 #define PACKCMD 15
405     { "packf", 0 },
406 #define PICKCMD 16
407     { "pick", 0 },
408 #define PREVCMD 17
409     { "prev", 0 },
410 #define QUITCMD 18
411     { "quit", 0 },
412 #define FILECMD 19
413     { "refile", 0 },
414 #define REPLCMD 20
415     { "repl", 0 },
416 #define RMMCMD  21
417     { "rmm", 0 },
418 #define SCANCMD 22
419     { "scan", 0 },
420 #define SENDCMD 23
421     { "send", 0 },
422 #define SHOWCMD 24
423     { "show", 0 },
424 #define SORTCMD 25
425     { "sortm", 0 },
426 #define WHATCMD 26
427     { "whatnow", 0 },
428 #define WHOMCMD 27
429     { "whom", 0 },
430     { NULL, 0 }
431 };
432
433
434 static void
435 msh (int scansw)
436 {
437     int i;
438     register char *cp, **ap;
439     char prompt[BUFSIZ], *vec[MAXARGS];
440     struct Cmd typein;
441     register struct Cmd *cmdp;
442     static int once_only = ADVCMD;
443
444     snprintf (prompt, sizeof(prompt), myprompt, invo_name);
445     cmdp = &typein;
446
447     for (;;) {
448         if (yp) {
449             fclose (yp);
450             yp = NULL;
451         }
452         if (vmh) {
453             if ((i = getcmds (mshcmds, cmdp, scansw)) == EOF) {
454                 rcdone ();
455                 return;
456             }
457         } else {
458             check_folder (scansw);
459             if ((i = getargs (prompt, mshcmds, cmdp)) == EOF) {
460                 putchar ('\n');
461                 return;
462             }
463         }
464         cmd_name = mshcmds[i].sw;
465
466         switch (i) {
467             case QUITCMD: 
468                 quit ();
469                 return;
470
471             case ADVCMD:
472                 if (once_only == ADVCMD)
473                     once_only = i = SHOWCMD;
474                 else
475                     i = mp->curmsg != mp->hghmsg ? NEXTCMD : EXITCMD;
476                 cmd_name = mshcmds[i].sw;
477                 /* and fall... */
478
479             case EXITCMD:
480             case EXPLCMD: 
481             case FOLDCMD: 
482             case FORWCMD:       /* sigh */
483             case MARKCMD: 
484             case NEXTCMD: 
485             case PACKCMD: 
486             case PICKCMD: 
487             case PREVCMD: 
488             case RMMCMD: 
489             case SHOWCMD: 
490             case SCANCMD: 
491             case SORTCMD: 
492                 if ((cp = context_find (cmd_name))) {
493                     cp = getcpy (cp);
494                     ap = brkstring (cp, " ", "\n");
495                     ap = copyip (ap, vec, MAXARGS);
496                 } else {
497                     ap = vec;
498                 }
499                 break;
500
501             default: 
502                 cp = NULL;
503                 ap = vec;
504                 break;
505         }
506         copyip (cmdp->args + 1, ap, MAXARGS);
507
508         m_init ();
509
510         if (!vmh && init_io (cmdp, vmh) == NOTOK) {
511             if (cp != NULL)
512                 free (cp);
513             continue;
514         }
515         modified = 0;
516         redirected = vmh || cmdp->direction != STDIO;
517
518         switch (i) {
519             case ALICMD: 
520             case COMPCMD: 
521             case INCMD: 
522             case MAILCMD: 
523             case MSGKCMD: 
524             case SENDCMD: 
525             case WHATCMD: 
526             case WHOMCMD: 
527                 if (!vmh || ttyN (cmdp) != NOTOK)
528                     forkcmd (vec, cmd_name);
529                 break;
530
531             case DISTCMD: 
532                 if (!vmh || ttyN (cmdp) != NOTOK)
533                     distcmd (vec);
534                 break;
535
536             case EXPLCMD: 
537                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
538                     explcmd (vec);
539                 break;
540
541             case FILECMD: 
542                 if (!vmh 
543                         || (filehak (vec) == OK ? ttyN (cmdp)
544                                         : winN (cmdp, DISPLAY, 1)) != NOTOK)
545                     filecmd (vec);
546                 break;
547
548             case FOLDCMD: 
549                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
550                     foldcmd (vec);
551                 break;
552
553             case FORWCMD: 
554                 if (!vmh || ttyN (cmdp) != NOTOK)
555                     forwcmd (vec);
556                 break;
557
558             case HELPCMD: 
559                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
560                     helpcmd (vec);
561                 break;
562
563             case EXITCMD:
564             case MARKCMD: 
565                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
566                     markcmd (vec);
567                 break;
568
569             case MHNCMD:
570                 if (!vmh || ttyN (cmdp) != NOTOK)
571                     mhncmd (vec);
572                 break;
573
574             case NEXTCMD: 
575             case PREVCMD: 
576             case SHOWCMD: 
577                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
578                     showcmd (vec);
579                 break;
580
581             case PACKCMD: 
582                 if (!vmh 
583                         || (packhak (vec) == OK ? ttyN (cmdp)
584                                         : winN (cmdp, DISPLAY, 1)) != NOTOK)
585                     packcmd (vec);
586                 break;
587
588             case PICKCMD: 
589                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
590                     pickcmd (vec);
591                 break;
592
593             case REPLCMD: 
594                 if (!vmh || ttyN (cmdp) != NOTOK)
595                     replcmd (vec);
596                 break;
597
598             case RMMCMD: 
599                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
600                     rmmcmd (vec);
601                 break;
602
603             case SCANCMD: 
604                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
605                     scancmd (vec);
606                 break;
607
608             case SORTCMD: 
609                 if (!vmh || winN (cmdp, DISPLAY, 1) != NOTOK)
610                     sortcmd (vec);
611                 break;
612
613             default: 
614                 padios (NULL, "no dispatch for %s", cmd_name);
615         }
616
617         if (vmh) {
618             if (vmhtty != NOTOK)
619                 ttyR (cmdp);
620             if (vmhpid > OK)
621                 winR (cmdp);
622         }
623         else
624             fin_io (cmdp, vmh);
625         if (cp != NULL)
626             free (cp);
627         if (i == EXITCMD) {
628             quit ();
629             return;
630         }
631     }
632 }
633
634
635 void
636 fsetup (char *folder)
637 {
638     register int msgnum;
639     char *maildir;
640     struct stat st;
641
642     maildir = m_maildir (folder);
643     if (chdir (maildir) == NOTOK)
644         padios (maildir, "unable to change directory to");
645
646     /* read folder and create message structure */
647     if (!(mp = folder_read (folder)))
648         padios (NULL, "unable to read folder %s", folder);
649
650     /* check for empty folder */
651     if (mp->nummsg == 0)
652         padios (NULL, "no messages in %s", folder);
653
654     mode = m_gmprot ();
655     mtime = stat (mp->foldpath, &st) != NOTOK ? st.st_mtime : 0;
656
657     m_gMsgs (mp->hghmsg);
658
659     for (msgnum = mp->lowmsg; msgnum <= mp->hghmsg; msgnum++) {
660         Msgs[msgnum].m_bboard_id = 0;
661         Msgs[msgnum].m_top = NOTOK;
662         Msgs[msgnum].m_start = Msgs[msgnum].m_stop = 0L;
663         Msgs[msgnum].m_scanl = NULL;
664     }
665
666     m_init ();
667
668     fmsh = getcpy (folder);
669
670     maxfds = OPEN_MAX / 2;
671
672     if ((maxfds -= 2) < 1)
673         maxfds = 1;
674 }
675
676
677 void
678 setup (char *file)
679 {
680     int i, msgp;
681     struct stat st;
682     if ((fp = fopen (file, "r")) == NULL)
683         padios (file, "unable to read");
684 #ifdef FIOCLEX
685     ioctl (fileno (fp), FIOCLEX, NULL);
686 #endif /* FIOCLEX */
687     if (fstat (fileno (fp), &st) != NOTOK) {
688         mode = (int) (st.st_mode & 0777), mtime = st.st_mtime;
689         msgp = read_map (file, (long) st.st_size);
690     }
691     else {
692         mode = m_gmprot (), mtime = 0;
693         msgp = 0;
694     }
695
696     if ((msgp = read_file (msgp ? Msgs[msgp].m_stop : 0L, msgp + 1)) < 1)
697         padios (NULL, "no messages in %s", myname ? myname : file);
698
699     if (!(mp = (struct msgs  *) calloc ((size_t) 1, sizeof(*mp))))
700         padios (NULL, "unable to allocate folder storage");
701
702     if (!(mp->msgstats = calloc ((size_t) msgp + 3, sizeof(*(mp->msgstats)))))
703         padios (NULL, "unable to allocate message status storage");
704
705     mp->hghmsg = msgp;
706     mp->nummsg = msgp;
707     mp->lowmsg = 1;
708     mp->curmsg = 0;
709     mp->foldpath = getcpy (myname ? myname : file);
710     clear_folder_flags (mp);
711
712         stat (file, &st);
713         if (st.st_uid != getuid () || access (file, W_OK) == NOTOK)
714             set_readonly (mp);
715
716     mp->lowoff = 1;
717     mp->hghoff = mp->hghmsg + 1;
718
719     for (i = mp->lowmsg; i <= mp->hghmsg; i++) {
720         clear_msg_flags (mp, i);
721         set_exists (mp, i);
722     }
723     m_init ();
724
725     mp->msgattrs[0] = getcpy ("unseen");
726     mp->msgattrs[1] = NULL;
727
728     m_unknown (fp);             /* the MAGIC invocation */    
729     if (fmsh) {
730         free (fmsh);
731         fmsh = NULL;
732     }
733 }
734
735
736 static int
737 read_map (char *file, long size)
738 {
739     register int i, msgp;
740     register struct drop *dp, *mp;
741     struct drop *rp;
742
743     if ((i = map_read (file, size, &rp, 1)) == 0)
744         return 0;
745
746     m_gMsgs (i);
747
748     msgp = 1;
749     for (dp = rp + 1; i-- > 0; msgp++, dp++) {
750         mp = &Msgs[msgp].m_drop;
751         mp->d_id = dp->d_id;
752         mp->d_size = dp->d_size;
753         mp->d_start = dp->d_start;
754         mp->d_stop = dp->d_stop;
755         Msgs[msgp].m_scanl = NULL;
756     }
757     free ((char *) rp);
758
759     return (msgp - 1);
760 }
761
762
763 static int
764 read_file (long pos, int msgp)
765 {
766     register int i;
767     register struct drop *dp, *mp;
768     struct drop *rp;
769
770     if ((i = mbx_read (fp, pos, &rp, 1)) <= 0)
771         return (msgp - 1);
772
773     m_gMsgs ((msgp - 1) + i);
774
775     for (dp = rp; i-- > 0; msgp++, dp++) {
776         mp = &Msgs[msgp].m_drop;
777         mp->d_id = 0;
778         mp->d_size = dp->d_size;
779         mp->d_start = dp->d_start;
780         mp->d_stop = dp->d_stop;
781         Msgs[msgp].m_scanl = NULL;
782     }
783     free ((char *) rp);
784
785     return (msgp - 1);
786 }
787
788
789 static void
790 m_gMsgs (int n)
791 {
792     int nmsgs;
793
794     if (Msgs == NULL) {
795         nMsgs = n + MAXFOLDER / 2;
796         Msgs = (struct Msg *) calloc ((size_t) (nMsgs + 2), sizeof *Msgs);
797         if (Msgs == NULL)
798             padios (NULL, "unable to allocate Msgs structure");
799         return;
800     }
801
802     if (nMsgs >= n)
803         return;
804
805     nmsgs = nMsgs + n + MAXFOLDER / 2;
806     Msgs = (struct Msg *) mh_xrealloc ((char *) Msgs, (size_t) (nmsgs + 2) * sizeof *Msgs);
807     memset((char *) (Msgs + nMsgs + 2), 0, (size_t) ((nmsgs - nMsgs) * sizeof *Msgs));
808
809     nMsgs = nmsgs;
810 }
811
812
813 FILE *
814 msh_ready (int msgnum, int full)
815 {
816     register int msgp;
817     int fd;
818     char *cp;
819
820     if (yp) {
821         fclose (yp);
822         yp = NULL;
823     }
824
825     if (fmsh) {
826         if ((fd = Msgs[msgnum].m_top) == NOTOK) {
827             if (numfds >= maxfds)
828                 for (msgp = mp->lowmsg; msgp <= mp->hghmsg; msgp++)
829                     if (Msgs[msgp].m_top != NOTOK) {
830                         close (Msgs[msgp].m_top);
831                         Msgs[msgp].m_top = NOTOK;
832                         numfds--;
833                         break;
834                     }
835
836             if ((fd = open (cp = m_name (msgnum), O_RDONLY)) == NOTOK)
837                 padios (cp, "unable to open message");
838             Msgs[msgnum].m_top = fd;
839             numfds++;
840         }
841
842         if ((fd = dup (fd)) == NOTOK)
843             padios ("cached message", "unable to dup");
844         if ((yp = fdopen (fd, "r")) == NULL)
845             padios (NULL, "unable to fdopen cached message");
846         fseek (yp, 0L, SEEK_SET);
847         return yp;
848     }
849
850     m_eomsbr ((int (*)()) 0);   /* XXX */
851     fseek (fp, Msgs[msgnum].m_start, SEEK_SET);
852     return fp;
853 }
854
855
856 static int
857 check_folder (int scansw)
858 {
859     int seqnum, i, low, hgh, msgp;
860     struct stat st;
861
862     if (fmsh) {
863         if (stat (mp->foldpath, &st) == NOTOK)
864             padios (mp->foldpath, "unable to stat");
865         if (mtime == st.st_mtime)
866             return 0;
867         mtime = st.st_mtime;
868
869         low = mp->hghmsg + 1;
870         folder_free (mp);               /* free folder/message structure */
871
872         if (!(mp = folder_read (fmsh)))
873             padios (NULL, "unable to re-read folder %s", fmsh);
874
875         hgh = mp->hghmsg;
876
877         for (msgp = mp->lowmsg; msgp <= mp->hghmsg; msgp++) {
878             if (Msgs[msgp].m_top != NOTOK) {
879                 close (Msgs[msgp].m_top);
880                 Msgs[msgp].m_top = NOTOK;
881                 numfds--;
882             }
883             if (Msgs[msgp].m_scanl) {
884                 free (Msgs[msgp].m_scanl);
885                 Msgs[msgp].m_scanl = NULL;
886             }
887         }
888
889         m_init ();
890
891         if (modified || low > hgh)
892             return 1;
893         goto check_vmh;
894     }
895     if (fstat (fileno (fp), &st) == NOTOK)
896         padios (mp->foldpath, "unable to fstat");
897     if (mtime == st.st_mtime)
898         return 0;
899     mode = (int) (st.st_mode & 0777);
900     mtime = st.st_mtime;
901
902     if ((msgp = read_file (Msgs[mp->hghmsg].m_stop, mp->hghmsg + 1)) < 1)
903         padios (NULL, "no messages in %s", mp->foldpath);       /* XXX */
904     if (msgp >= MAXFOLDER)
905         padios (NULL, "more than %d messages in %s", MAXFOLDER,
906                 mp->foldpath);
907     if (msgp <= mp->hghmsg)
908         return 0;               /* XXX */
909
910     if (!(mp = folder_realloc (mp, mp->lowoff, msgp)))
911         padios (NULL, "unable to allocate folder storage");
912
913     low = mp->hghmsg + 1, hgh = msgp;
914     seqnum = scansw ? seq_getnum (mp, "unseen") : -1;
915     for (i = mp->hghmsg + 1; i <= msgp; i++) {
916         set_exists(mp, i);
917         if (seqnum != -1)
918             add_sequence(mp, seqnum, i);
919         mp->nummsg++;
920     }
921     mp->hghmsg = msgp;
922     m_init ();
923
924 check_vmh: ;
925     if (vmh)
926         return 1;
927
928     advise (NULL, "new messages have arrived!\007");
929     if (scansw)
930         scanrange (low, hgh);
931
932     return 1;
933 }
934
935
936 static void
937 scanrange (int low, int hgh)
938 {
939     char buffer[BUFSIZ];
940
941     snprintf (buffer, sizeof(buffer), "%d-%d", low, hgh);
942     scanstring (buffer);
943 }
944
945
946 static void
947 scanstring (char *arg)
948 {
949     char *cp, **ap, *vec[MAXARGS];
950
951     /*
952      * This should be replace with a call to getarguments()
953      */
954     if ((cp = context_find (cmd_name = "scan"))) {
955         cp = getcpy (cp);
956         ap = brkstring (cp, " ", "\n");
957         ap = copyip (ap, vec, MAXARGS);
958     } else {
959         ap = vec;
960     }
961     *ap++ = arg;
962     *ap = NULL;
963     m_init ();
964     scancmd (vec);
965     if (cp != NULL)
966         free (cp);
967 }
968
969
970 void
971 readids (int id)
972 {
973     register int cur, seqnum, i=0, msgnum;
974
975     if (mp->curmsg == 0)
976         seq_setcur (mp, mp->lowmsg);
977     if (id <= 0 || (seqnum = seq_getnum (mp, "unseen")) == -1)
978         return;
979
980     for (msgnum = mp->hghmsg; msgnum >= mp->lowmsg; msgnum--)
981         add_sequence(mp, seqnum, msgnum);
982
983     if (id != 1) {
984         cur = mp->curmsg;
985
986         for (msgnum = mp->hghmsg; msgnum >= mp->lowmsg; msgnum--)
987           if (does_exist(mp, msgnum))           /* FIX */
988             if ((i = readid (msgnum)) > 0 && i < id) {
989                 cur = msgnum + 1;
990                 clear_sequence(mp, seqnum, msgnum);
991                 break;
992             }
993         for (i = mp->lowmsg; i < msgnum; i++)
994             clear_sequence(mp, seqnum, i);
995
996         if (cur > mp->hghmsg)
997             cur = mp->hghmsg;
998
999         seq_setcur (mp, cur);
1000     }
1001
1002     if ((gap = 1 < id && id < (i = readid (mp->lowmsg)) ? id : 0) && !vmh)
1003         advise (NULL, "gap in ID:s, last seen %d, lowest present %d\n",
1004                 id - 1, i);
1005 }
1006
1007
1008 int
1009 readid (int msgnum)
1010 {
1011     int i, state;
1012     char *bp, buf[BUFSIZ], name[NAMESZ];
1013     register FILE *zp;
1014
1015     if (Msgs[msgnum].m_bboard_id)
1016         return Msgs[msgnum].m_bboard_id;
1017
1018     zp = msh_ready (msgnum, 0);
1019     for (state = FLD;;)
1020         switch (state = m_getfld (state, name, buf, sizeof(buf), zp)) {
1021             case FLD: 
1022             case FLDEOF: 
1023             case FLDPLUS: 
1024                 if (!mh_strcasecmp (name, BBoard_ID)) {
1025                     bp = getcpy (buf);
1026                     while (state == FLDPLUS) {
1027                         state = m_getfld (state, name, buf, sizeof(buf), zp);
1028                         bp = add (buf, bp);
1029                     }
1030                     i = atoi (bp);
1031                     free (bp);
1032                     if (i > 0)
1033                         return (Msgs[msgnum].m_bboard_id = i);
1034                     else
1035                         continue;
1036                 }
1037                 while (state == FLDPLUS)
1038                     state = m_getfld (state, name, buf, sizeof(buf), zp);
1039                 if (state != FLDEOF)
1040                     continue;
1041
1042             default: 
1043                 return 0;
1044         }
1045 }
1046
1047
1048 void
1049 display_info (int scansw)
1050 {
1051     int seqnum, sd;
1052
1053     interactive = isatty (fileno (stdout));
1054     if (sp == NULL) {
1055         if ((sd = dup (fileno (stdout))) == NOTOK)
1056             padios ("standard output", "unable to dup");
1057 #ifndef BSD42                   /* XXX */
1058 #ifdef FIOCLEX
1059         ioctl (sd, FIOCLEX, NULL);
1060 #endif /* FIOCLEX */
1061 #endif /* not BSD42 */
1062         if ((sp = fdopen (sd, "w")) == NULL)
1063             padios ("standard output", "unable to fdopen");
1064     }
1065
1066     m_putenv ("mhfolder", mp->foldpath);
1067     if (vmh)
1068         return;
1069
1070     if (myname) {
1071         printf ("Reading ");
1072         if (SOprintf ("%s", myname))
1073             printf ("%s", myname);
1074         printf (", currently at message %d of %d\n",
1075                 mp->curmsg, mp->hghmsg);
1076     }
1077     else {
1078         printf ("Reading ");
1079         if (fmsh)
1080             printf ("+%s", fmsh);
1081         else
1082             printf ("%s", mp->foldpath);
1083         printf (", currently at message %d of %d\n",
1084                 mp->curmsg, mp->hghmsg);
1085     }
1086
1087     if (((seqnum = seq_getnum (mp, "unseen")) != -1)
1088             && scansw
1089             && in_sequence(mp, seqnum, mp->hghmsg))
1090         scanstring ("unseen");
1091 }
1092
1093
1094 static void
1095 write_ids (void)
1096 {
1097     int i = 0, seqnum, msgnum;
1098     char buffer[80];
1099
1100     if (pfd <= 1)
1101         return;
1102
1103     if ((seqnum = seq_getnum (mp, "unseen")) != -1)
1104         for (msgnum = mp->hghmsg; msgnum >= mp->lowmsg; msgnum--)
1105             if (!in_sequence(mp, seqnum, msgnum)) {
1106                 if (Msgs[msgnum].m_bboard_id == 0)
1107                     readid (msgnum);
1108                 if ((i = Msgs[msgnum].m_bboard_id) > 0)
1109                     break;
1110             }
1111
1112     snprintf (buffer, sizeof(buffer), "%d %d\n", i, Msgs[mp->hghmsg].m_bboard_id);
1113     write (pfd, buffer, sizeof(buffer));
1114     close (pfd);
1115     pfd = NOTOK;
1116 }
1117
1118
1119 static void
1120 quit (void)
1121 {
1122     int i, md, msgnum;
1123     char *cp, tmpfil[BUFSIZ];
1124     char map1[BUFSIZ], map2[BUFSIZ];
1125     struct stat st;
1126     FILE *dp;
1127
1128     if (!(mp->msgflags & MODIFIED) || is_readonly(mp) || fmsh) {
1129             if (vmh)
1130                 rc2peer (RC_FIN, 0, NULL);
1131         return;
1132     }
1133
1134     if (vmh) 
1135         ttyNaux (NULLCMD, "FAST");
1136     cp = NULL;
1137     if ((dp = lkfopen (mp->foldpath, "r")) == NULL) {
1138         advise (mp->foldpath, "unable to lock");
1139         if (vmh) {
1140             ttyR (NULLCMD);
1141             pFIN ();
1142         }       
1143         return;
1144     }
1145     if (fstat (fileno (dp), &st) == NOTOK) {
1146         advise (mp->foldpath, "unable to stat");
1147         goto release;
1148     }
1149     if (mtime != st.st_mtime) {
1150         advise (NULL, "new messages have arrived, no update");
1151         goto release;
1152     }
1153     mode = (int) (st.st_mode & 0777);
1154
1155     if (mp->nummsg == 0) {
1156         cp = concat ("Zero file \"", mp->foldpath, "\"? ", NULL);
1157         if (getanswer (cp)) {
1158             if ((i = creat (mp->foldpath, mode)) != NOTOK)
1159                 close (i);
1160             else
1161                 advise (mp->foldpath, "error zero'ing");
1162             unlink (map_name (mp->foldpath));/* XXX */
1163         }
1164         goto release;
1165     }
1166
1167     cp = concat ("Update file \"", mp->foldpath, "\"? ", NULL);
1168     if (!getanswer (cp))
1169         goto release;
1170     strncpy (tmpfil, m_backup (mp->foldpath), sizeof(tmpfil));
1171     if ((md = mbx_open (tmpfil, mbx_style, st.st_uid, st.st_gid, mode)) == NOTOK) {
1172         advise (tmpfil, "unable to open");
1173         goto release;
1174     }
1175
1176     for (msgnum = mp->lowmsg; msgnum <= mp->hghmsg; msgnum++)
1177         if (does_exist(mp, msgnum) && pack (tmpfil, md, msgnum) == NOTOK) {
1178             mbx_close (tmpfil, md);
1179             unlink (tmpfil);
1180             unlink (map_name (tmpfil));
1181             goto release;
1182         }
1183     mbx_close (tmpfil, md);
1184
1185     if (rename (tmpfil, mp->foldpath) == NOTOK)
1186         admonish (mp->foldpath, "unable to rename %s to", tmpfil);
1187     else {
1188         strncpy (map1, map_name (tmpfil), sizeof(map1));
1189         strncpy (map2, map_name (mp->foldpath), sizeof(map2));
1190
1191         if (rename (map1, map2) == NOTOK) {
1192             admonish (map2, "unable to rename %s to", map1);
1193             unlink (map1);
1194             unlink (map2);
1195         }
1196     }
1197
1198 release: ;
1199     if (cp)
1200         free (cp);
1201     lkfclose (dp, mp->foldpath);
1202     if (vmh) {
1203         ttyR (NULLCMD);
1204         pFIN ();
1205     }
1206 }
1207
1208
1209 static int
1210 getargs (char *prompt, struct swit *sw, struct Cmd *cmdp)
1211 {
1212     int i;
1213     char *cp;
1214     static char buffer[BUFSIZ];
1215
1216     told_to_quit = 0;
1217     for (;;) {
1218         interrupted = 0;
1219 #ifdef BSD42
1220         switch (setjmp (sigenv)) {
1221             case OK:
1222                 should_intr = 1;
1223                 break;
1224
1225             default:
1226                 should_intr = 0;
1227                 if (interrupted && !told_to_quit) {
1228                     putchar ('\n');
1229                     continue;
1230                 }
1231                 if (ppid > 0)
1232 #ifdef SIGEMT
1233                     kill (ppid, SIGEMT);
1234 #else
1235                     kill (ppid, SIGTERM);
1236 #endif
1237                 return EOF;
1238         }
1239 #endif /* BSD42 */
1240         if (interactive) {
1241             printf ("%s", prompt);
1242             fflush (stdout);
1243         }
1244         for (cp = buffer; (i = getchar ()) != '\n';) {
1245 #ifndef BSD42
1246             if (interrupted && !told_to_quit) {
1247                 buffer[0] = '\0';
1248                 putchar ('\n');
1249                 break;
1250             }
1251             if (told_to_quit || i == EOF) {
1252                 if (ppid > 0)
1253 #ifdef SIGEMT
1254                     kill (ppid, SIGEMT);
1255 #else
1256                     kill (ppid, SIGTERM);
1257 #endif
1258                 return EOF;
1259             }
1260 #else /* BSD42 */
1261             if (i == EOF)
1262                 longjmp (sigenv, DONE);
1263 #endif /* BSD42 */
1264             if (cp < &buffer[sizeof buffer - 2])
1265                 *cp++ = i;
1266         }
1267         *cp = 0;
1268
1269         if (buffer[0] == 0)
1270             continue;
1271         if (buffer[0] == '?') {
1272             printf ("commands:\n");
1273             print_sw (ALL, sw, "", stdout);
1274             printf ("type CTRL-D or use ``quit'' to leave %s\n",
1275                     invo_name);
1276             continue;
1277         }
1278
1279         if (parse (buffer, cmdp) == NOTOK)
1280             continue;
1281
1282         switch (i = smatch (cmdp->args[0], sw)) {
1283             case AMBIGSW: 
1284                 ambigsw (cmdp->args[0], sw);
1285                 continue;
1286             case UNKWNSW: 
1287                 printf ("say what: ``%s'' -- type ? (or help) for help\n",
1288                         cmdp->args[0]);
1289                 continue;
1290             default: 
1291 #ifdef BSD42
1292                 should_intr = 0;
1293 #endif /* BSD42 */
1294                 return i;
1295         }
1296     }
1297 }
1298
1299
1300 static int
1301 getcmds (struct swit *sw, struct Cmd *cmdp, int scansw)
1302 {
1303     int i;
1304     struct record rcs, *rc;
1305
1306     rc = &rcs;
1307     initrc (rc);
1308
1309     for (;;)
1310         switch (peer2rc (rc)) {
1311             case RC_QRY: 
1312                 pQRY (rc->rc_data, scansw);
1313                 break;
1314
1315             case RC_CMD: 
1316                 if ((i = pCMD (rc->rc_data, sw, cmdp)) != NOTOK)
1317                     return i;
1318                 break;
1319
1320             case RC_FIN: 
1321                 if (ppid > 0)
1322 #ifdef SIGEMT
1323                     kill (ppid, SIGEMT);
1324 #else
1325                     kill (ppid, SIGTERM);
1326 #endif
1327                 return EOF;
1328
1329             case RC_XXX: 
1330                 padios (NULL, "%s", rc->rc_data);
1331
1332             default: 
1333                 fmt2peer (RC_ERR, "pLOOP protocol screw-up");
1334                 done (1);
1335         }
1336 }
1337
1338
1339 static int
1340 parse (char *buffer, struct Cmd *cmdp)
1341 {
1342     int argp = 0;
1343     unsigned char c, *cp;
1344     char *pp;
1345
1346     cmdp->line[0] = 0;
1347     pp = cmdp->args[argp++] = cmdp->line;
1348     cmdp->redirect = NULL;
1349     cmdp->direction = STDIO;
1350     cmdp->stream = NULL;
1351
1352     for (cp = buffer; (c = *cp); cp++) {
1353         if (!isspace (c))
1354             break;
1355     }
1356     if (c == '\0') {
1357         if (vmh)
1358             fmt2peer (RC_EOF, "null command");
1359         return NOTOK;
1360     }
1361
1362     while ((c = *cp++)) {
1363         if (isspace (c)) {
1364             while (isspace (c))
1365                 c = *cp++;
1366             if (c == 0)
1367                 break;
1368             *pp++ = 0;
1369             cmdp->args[argp++] = pp;
1370             *pp = 0;
1371         }
1372
1373         switch (c) {
1374             case '"': 
1375                 for (;;) {
1376                     switch (c = *cp++) {
1377                         case 0: 
1378                             padvise (NULL, "unmatched \"");
1379                             return NOTOK;
1380                         case '"': 
1381                             break;
1382                         case QUOTE: 
1383                             if ((c = *cp++) == 0)
1384                                 goto no_quoting;
1385                         default: 
1386                             *pp++ = c;
1387                             continue;
1388                     }
1389                     break;
1390                 }
1391                 continue;
1392
1393             case QUOTE: 
1394                 if ((c = *cp++) == 0) {
1395             no_quoting: ;
1396                     padvise (NULL, "the newline character can not be quoted");
1397                     return NOTOK;
1398                 }
1399
1400             default: ;
1401                 *pp++ = c;
1402                 continue;
1403
1404             case '>': 
1405             case '|': 
1406                 if (pp == cmdp->line) {
1407                     padvise (NULL, "invalid null command");
1408                     return NOTOK;
1409                 }
1410                 if (*cmdp->args[argp - 1] == 0)
1411                     argp--;
1412                 cmdp->direction = c == '>' ? CRTIO : PIPIO;
1413                 if (cmdp->direction == CRTIO && (c = *cp) == '>') {
1414                     cmdp->direction = APPIO;
1415                     cp++;
1416                 }
1417                 cmdp->redirect = pp + 1;/* sigh */
1418                 for (; (c = *cp); cp++)
1419                     if (!isspace (c))
1420                         break;
1421                 if (c == 0) {
1422                     padvise (NULL, cmdp->direction != PIPIO
1423                             ? "missing name for redirect"
1424                             : "invalid null command");
1425                     return NOTOK;
1426                 }
1427                 strcpy (cmdp->redirect, cp);
1428                 if (cmdp->direction != PIPIO) {
1429                     for (; *cp; cp++)
1430                         if (isspace (*cp)) {
1431                             padvise (NULL, "bad name for redirect");
1432                             return NOTOK;
1433                         }
1434                     if (expand (cmdp->redirect) == NOTOK)
1435                         return NOTOK;
1436                 }
1437                 break;
1438         }
1439         break;
1440     }
1441
1442     *pp++ = 0;
1443     cmdp->args[argp] = NULL;
1444
1445     return OK;
1446 }
1447
1448
1449 int
1450 expand (char *redirect)
1451 {
1452     char *cp, *pp;
1453     char path[BUFSIZ];
1454     struct passwd  *pw;
1455
1456     if (*redirect != '~')
1457         return OK;
1458
1459     if ((cp = strchr(pp = redirect + 1, '/')))
1460         *cp++ = 0;
1461     if (*pp == 0)
1462         pp = mypath;
1463     else
1464         if ((pw = getpwnam (pp)))
1465             pp = pw->pw_dir;
1466         else {
1467             padvise (NULL, "unknown user: %s", pp);
1468             return NOTOK;
1469         }
1470
1471     snprintf (path, sizeof(path), "%s/%s", pp, cp ? cp : "");
1472     strcpy (redirect, path);
1473     return OK;
1474 }
1475
1476
1477 static int
1478 init_io (struct Cmd *cmdp, int vio)
1479 {
1480     int io, result;
1481
1482     io = vmh;
1483
1484     vmh = vio;
1485     result = initaux_io (cmdp);
1486     vmh = io;
1487
1488     return result;
1489 }
1490
1491
1492 static int
1493 initaux_io (struct Cmd *cmdp)
1494 {
1495     char *mode;
1496
1497     switch (cmdp->direction) {
1498         case STDIO: 
1499             return OK;
1500
1501         case CRTIO: 
1502         case APPIO: 
1503             mode = cmdp->direction == CRTIO ? "write" : "append";
1504             if ((cmdp->stream = fopen (cmdp->redirect, mode)) == NULL) {
1505                 padvise (cmdp->redirect, "unable to %s ", mode);
1506                 cmdp->direction = STDIO;
1507                 return NOTOK;
1508             }
1509             break;
1510
1511         case PIPIO: 
1512             if ((cmdp->stream = popen (cmdp->redirect, "w")) == NULL) {
1513                 padvise (cmdp->redirect, "unable to pipe");
1514                 cmdp->direction = STDIO;
1515                 return NOTOK;
1516             }
1517             SIGNAL (SIGPIPE, pipeser);
1518             broken_pipe = 0;
1519             break;
1520
1521         default: 
1522             padios (NULL, "unknown redirection for command");
1523     }
1524
1525     fflush (stdout);
1526     if (dup2 (fileno (cmdp->stream), fileno (stdout)) == NOTOK)
1527         padios ("standard output", "unable to dup2");
1528     clearerr (stdout);
1529
1530     return OK;
1531 }
1532
1533
1534 static void
1535 fin_io (struct Cmd *cmdp, int vio)
1536 {
1537     int io;
1538
1539     io = vmh;
1540     vmh = vio;
1541     finaux_io (cmdp);
1542     vmh = io;
1543 }
1544
1545
1546 static void
1547 finaux_io (struct Cmd *cmdp)
1548 {
1549     switch (cmdp->direction) {
1550         case STDIO: 
1551             return;
1552
1553         case CRTIO: 
1554         case APPIO: 
1555             fflush (stdout);
1556             close (fileno (stdout));
1557             if (ferror (stdout))
1558                 padvise (NULL, "problems writing %s", cmdp->redirect);
1559             fclose (cmdp->stream);
1560             break;
1561
1562         case PIPIO: 
1563             fflush (stdout);
1564             close (fileno (stdout));
1565             pclose (cmdp->stream);
1566             SIGNAL (SIGPIPE, SIG_DFL);
1567             break;
1568
1569         default: 
1570             padios (NULL, "unknown redirection for command");
1571     }
1572
1573     if (dup2 (fileno (sp), fileno (stdout)) == NOTOK)
1574         padios ("standard output", "unable to dup2");
1575     clearerr (stdout);
1576
1577     cmdp->direction = STDIO;
1578 }
1579
1580
1581 static void
1582 m_init (void)
1583 {
1584     int msgnum;
1585
1586     for (msgnum = mp->lowmsg; msgnum <= mp->hghmsg; msgnum++)
1587         unset_selected (mp, msgnum);
1588     mp->lowsel = mp->hghsel = mp->numsel = 0;
1589 }
1590
1591
1592 void
1593 m_reset (void)
1594 {
1595     write_ids ();
1596     folder_free (mp);   /* free folder/message structure */
1597     myname = NULL;
1598 }
1599
1600
1601 void
1602 seq_setcur (struct msgs *mp, int msgnum)
1603 {
1604     if (mp->curmsg == msgnum)
1605         return;
1606
1607     if (mp->curmsg && Msgs[mp->curmsg].m_scanl) {
1608         free (Msgs[mp->curmsg].m_scanl);
1609         Msgs[mp->curmsg].m_scanl = NULL;
1610     }
1611     if (Msgs[msgnum].m_scanl) {
1612         free (Msgs[msgnum].m_scanl);
1613         Msgs[msgnum].m_scanl = NULL;
1614     }
1615
1616     mp->curmsg = msgnum;
1617 }
1618
1619
1620
1621 static void
1622 intrser (int i)
1623 {
1624 #ifndef RELIABLE_SIGNALS
1625     SIGNAL (SIGINT, intrser);
1626 #endif
1627
1628     discard (stdout);
1629     interrupted++;
1630
1631 #ifdef BSD42
1632     if (should_intr)
1633         longjmp (sigenv, NOTOK);
1634 #endif
1635 }
1636
1637
1638 static void
1639 pipeser (int i)
1640 {
1641 #ifndef RELIABLE_SIGNALS
1642     SIGNAL (SIGPIPE, pipeser);
1643 #endif
1644
1645     if (broken_pipe++ == 0)
1646         fprintf (stderr, "broken pipe\n");
1647     told_to_quit++;
1648     interrupted++;
1649
1650 #ifdef BSD42
1651     if (should_intr)
1652         longjmp (sigenv, NOTOK);
1653 #endif
1654 }
1655
1656
1657 static void
1658 quitser (int i)
1659 {
1660 #ifndef RELIABLE_SIGNALS
1661     SIGNAL (SIGQUIT, quitser);
1662 #endif
1663
1664     told_to_quit++;
1665     interrupted++;
1666
1667 #ifdef BSD42
1668     if (should_intr)
1669         longjmp (sigenv, NOTOK);
1670 #endif
1671 }
1672
1673
1674 static void
1675 alrmser (int i)
1676 {
1677     longjmp (peerenv, DONE);
1678 }
1679
1680
1681 static int
1682 pINI (void)
1683 {
1684     int i, vrsn;
1685     unsigned char *bp;
1686     struct record rcs, *rc;
1687
1688     rc = &rcs;
1689     initrc (rc);
1690
1691     switch (peer2rc (rc)) {
1692         case RC_INI: 
1693             bp = rc->rc_data;
1694             while (isspace (*bp))
1695                 bp++;
1696             if (sscanf (bp, "%d", &vrsn) != 1) {
1697         bad_init: ;
1698                 fmt2peer (RC_ERR, "bad init \"%s\"", rc->rc_data);
1699                 done (1);
1700             }
1701             if (vrsn != RC_VRSN) {
1702                 fmt2peer (RC_ERR, "version %d unsupported", vrsn);
1703                 done (1);
1704             }
1705
1706             while (*bp && !isspace (*bp))
1707                 bp++;
1708             while (isspace (*bp))
1709                 bp++;
1710             if (sscanf (bp, "%d", &numwins) != 1 || numwins <= 0)
1711                 goto bad_init;
1712             if (numwins > NWIN)
1713                 numwins = NWIN;
1714
1715             for (i = 1; i <= numwins; i++) {
1716                 while (*bp && !isspace (*bp))
1717                     bp++;
1718                 while (isspace (*bp))
1719                     bp++;
1720                 if (sscanf (bp, "%d", &windows[i]) != 1 || windows[i] <= 0)
1721                     goto bad_init;
1722             }
1723             rc2peer (RC_ACK, 0, NULL);
1724             return OK;
1725
1726         case RC_XXX: 
1727             padios (NULL, "%s", rc->rc_data);
1728
1729         default: 
1730             fmt2peer (RC_ERR, "pINI protocol screw-up");
1731             done (1);           /* NOTREACHED */
1732     }
1733
1734     return 1;  /* dead code to satisfy the compiler */
1735 }
1736
1737
1738 static int
1739 pQRY (char *str, int scansw)
1740 {
1741     if (pQRY1 (scansw) == NOTOK || pQRY2 () == NOTOK)
1742         return NOTOK;
1743
1744     rc2peer (RC_EOF, 0, NULL);
1745     return OK;
1746 }
1747         
1748
1749 static int
1750 pQRY1 (int scansw)
1751 {
1752     int oldhgh;
1753     static int lastlow = 0,
1754                lastcur = 0,
1755                lasthgh = 0,
1756                lastnum = 0;
1757
1758     oldhgh = mp->hghmsg;
1759     if (check_folder (scansw) && oldhgh < mp->hghmsg) {
1760         switch (winX (STATUS)) {
1761             case NOTOK: 
1762                 return NOTOK;
1763
1764             case OK: 
1765                 printf ("new messages have arrived!");
1766                 fflush (stdout);
1767                 fflush (stderr);
1768                 _exit (0);      /* NOTREACHED */
1769
1770             default: 
1771                 lastlow = lastcur = lasthgh = lastnum = 0;
1772                 break;
1773         }
1774
1775         switch (winX (DISPLAY)) {
1776             case NOTOK: 
1777                 return NOTOK;
1778
1779             case OK: 
1780                 scanrange (oldhgh + 1, mp->hghmsg);
1781                 fflush (stdout);
1782                 fflush (stderr);
1783                 _exit (0);      /* NOTREACHED */
1784
1785             default: 
1786                 break;
1787         }
1788         return OK;
1789     }
1790
1791     if (gap)
1792         switch (winX (STATUS)) {
1793             case NOTOK:
1794                 return NOTOK;
1795
1796             case OK:
1797                 printf ("%s: gap in ID:s, last seen %d, lowest present %d\n",
1798                     myname ? myname : fmsh ? fmsh : mp->foldpath, gap - 1,
1799                     readid (mp->lowmsg));
1800                 fflush (stdout);
1801                 fflush (stderr);
1802                 _exit (0);      /* NOTREACHED */
1803
1804             default:
1805                 gap = 0;
1806                 return OK;
1807         }
1808
1809     if (mp->lowmsg != lastlow
1810             || mp->curmsg != lastcur
1811             || mp->hghmsg != lasthgh
1812             || mp->nummsg != lastnum)
1813         switch (winX (STATUS)) {
1814             case NOTOK: 
1815                 return NOTOK;
1816
1817             case OK: 
1818                 foldcmd (NULL);
1819                 fflush (stdout);
1820                 fflush (stderr);
1821                 _exit (0);      /* NOTREACHED */
1822
1823             default: 
1824                 lastlow = mp->lowmsg;
1825                 lastcur = mp->curmsg;
1826                 lasthgh = mp->hghmsg;
1827                 lastnum = mp->nummsg;
1828                 return OK;
1829         }
1830
1831     return OK;
1832 }
1833
1834
1835 static int
1836 pQRY2 (void)
1837 {
1838     int i, j, k, msgnum, n;
1839     static int cur = 0,
1840                num = 0,
1841                lo = 0,
1842                hi = 0;
1843
1844     if (mp->nummsg == 0 && mp->nummsg != num)
1845         switch (winX (SCAN)) {
1846             case NOTOK: 
1847                 return NOTOK;
1848
1849             case OK: 
1850                 printf ("empty!");
1851                 fflush (stdout);
1852                 fflush (stderr);
1853                 _exit (0);      /* NOTREACHED */
1854
1855             default: 
1856                 num = mp->nummsg;
1857                 return OK;
1858         }
1859     num = mp->nummsg;
1860
1861     i = 0;
1862     j = (k = windows[SCAN]) / 2;
1863     for (msgnum = mp->curmsg; msgnum <= mp->hghmsg; msgnum++)
1864         if (does_exist (mp, msgnum))
1865             i++;
1866     if (i-- > 0) {
1867         if (topcur)
1868             k = i >= k ? 1 : k - i;
1869         else
1870             k -= i > j ? j : i;
1871     }
1872
1873     i = j = 0;
1874     n = 1;
1875     for (msgnum = mp->curmsg; msgnum >= mp->lowmsg; msgnum--)
1876         if (does_exist (mp, msgnum)) {
1877             i = msgnum;
1878             if (j == 0)
1879                 j = msgnum;
1880             if (n++ >= k)
1881                 break;
1882         }
1883     for (msgnum = mp->curmsg + 1; msgnum <= mp->hghmsg; msgnum++)
1884         if (does_exist (mp, msgnum)) {
1885             if (i == 0)
1886                 i = msgnum;
1887             j = msgnum;
1888             if (n++ >= windows[SCAN])
1889                 break;
1890         }
1891     if (!topcur
1892             && lo > 0
1893             && hi > 0
1894             && does_exist (mp, lo)
1895             && does_exist (mp, hi)
1896             && (lo < mp->curmsg
1897                     || (lo == mp->curmsg && lo == mp->lowmsg))
1898             && (mp->curmsg < hi
1899                     || (hi == mp->curmsg && hi == mp->hghmsg))
1900             && hi - lo == j - i)
1901         i = lo, j = hi;
1902
1903     if (mp->curmsg != cur || modified)
1904         switch (winN (NULLCMD, SCAN, 0)) {
1905             case NOTOK: 
1906                 return NOTOK;
1907
1908             case OK:
1909                 return OK;
1910
1911             default: 
1912                 scanrange (lo = i, hi = j);
1913                 cur = mp->curmsg;
1914                 winR (NULLCMD);
1915                 return OK;
1916         }
1917
1918     return OK;
1919 }
1920
1921
1922 static int
1923 pCMD (char *str, struct swit *sw, struct Cmd *cmdp)
1924 {
1925     int i;
1926
1927     if (*str == '?')
1928         switch (winX (DISPLAY)) {
1929             case NOTOK: 
1930                 return NOTOK;
1931
1932             case OK: 
1933                 printf ("commands:\n");
1934                 print_sw (ALL, sw, "", stdout);
1935                 printf ("type ``quit'' to leave %s\n", invo_name);
1936                 fflush (stdout);
1937                 fflush (stderr);
1938                 _exit (0);      /* NOTREACHED */
1939
1940             default: 
1941                 rc2peer (RC_EOF, 0, NULL);
1942                 return NOTOK;
1943         }
1944
1945     if (parse (str, cmdp) == NOTOK)
1946         return NOTOK;
1947
1948     switch (i = smatch (cmdp->args[0], sw)) {
1949         case AMBIGSW: 
1950             switch (winX (DISPLAY)) {
1951                 case NOTOK: 
1952                     return NOTOK;
1953
1954                 case OK: 
1955                     ambigsw (cmdp->args[0], sw);
1956                     fflush (stdout);
1957                     fflush (stderr);
1958                     _exit (0);  /* NOTREACHED */
1959
1960                 default: 
1961                     rc2peer (RC_EOF, 0, NULL);
1962                     return NOTOK;
1963             }
1964
1965         case UNKWNSW: 
1966             fmt2peer (RC_ERR,
1967                     "say what: ``%s'' -- type ? (or help) for help",
1968                     cmdp->args[0]);
1969             return NOTOK;
1970
1971         default: 
1972             return i;
1973     }
1974 }
1975
1976
1977 static int
1978 pFIN (void)
1979 {
1980     int status;
1981
1982     switch (setjmp (peerenv)) {
1983         case OK: 
1984             SIGNAL (SIGALRM, alrmser);
1985             alarm (ALARM);
1986
1987             status = peerwait ();
1988
1989             alarm (0);
1990             return status;
1991
1992         default: 
1993             return NOTOK;
1994     }
1995 }
1996
1997
1998 static int
1999 peerwait (void)
2000 {
2001     struct record rcs, *rc;
2002
2003     rc = &rcs;
2004     initrc (rc);
2005
2006     switch (peer2rc (rc)) {
2007         case RC_QRY: 
2008         case RC_CMD: 
2009             rc2peer (RC_FIN, 0, NULL);
2010             return OK;
2011
2012         case RC_XXX: 
2013             advise (NULL, "%s", rc->rc_data);
2014             return NOTOK;
2015
2016         default: 
2017             fmt2peer (RC_FIN, "pLOOP protocol screw-up");
2018             return NOTOK;
2019     }
2020 }
2021
2022
2023 static int
2024 ttyNaux (struct Cmd *cmdp, char *s)
2025 {
2026     struct record rcs, *rc;
2027
2028     rc = &rcs;
2029     initrc (rc);
2030
2031     if (cmdp && init_io (cmdp, vmh) == NOTOK)
2032         return NOTOK;
2033
2034     /* XXX: fseek() too tricky for our own good */
2035     if (!fmsh)
2036         fseek (fp, 0L, SEEK_SET);
2037
2038     vmhtty = NOTOK;
2039     switch (rc2rc (RC_TTY, s ? strlen (s) : 0, s, rc)) {
2040         case RC_ACK: 
2041             vmhtty = OK;        /* fall */
2042         case RC_ERR: 
2043             break;
2044
2045         case RC_XXX: 
2046             padios (NULL, "%s", rc->rc_data);/* NOTREACHED */
2047
2048         default: 
2049             fmt2peer (RC_ERR, "pTTY protocol screw-up");
2050             done (1);           /* NOTREACHED */
2051     }
2052
2053 #ifdef SIGTSTP
2054     SIGNAL (SIGTSTP, tstat);
2055 #endif
2056     return vmhtty;
2057 }
2058
2059
2060 static int
2061 ttyR (struct Cmd *cmdp)
2062 {
2063     struct record rcs, *rc;
2064
2065     rc = &rcs;
2066
2067 #ifdef SIGTSTP
2068     SIGNAL (SIGTSTP, SIG_IGN);
2069 #endif
2070
2071     if (vmhtty != OK)
2072         return NOTOK;
2073
2074     initrc (rc);
2075
2076     if (cmdp)
2077         fin_io (cmdp, 0);
2078
2079     vmhtty = NOTOK;
2080     switch (rc2rc (RC_EOF, 0, NULL, rc)) {
2081         case RC_ACK: 
2082             rc2peer (RC_EOF, 0, NULL);
2083             return OK;
2084
2085         case RC_XXX: 
2086             padios (NULL, "%s", rc->rc_data);/* NOTREACHED */
2087
2088         default: 
2089             fmt2peer (RC_ERR, "pTTY protocol screw-up");
2090             done (1);           /* NOTREACHED */
2091     }
2092
2093     return 1;  /* dead code to satisfy compiler */
2094 }
2095
2096
2097 static int
2098 winN (struct Cmd *cmdp, int n, int eof)
2099 {
2100     int i, pd[2];
2101     char buffer[BUFSIZ];
2102     struct record rcs, *rc;
2103
2104     rc = &rcs;
2105     if (vmhpid == NOTOK)
2106         return OK;
2107
2108     initrc (rc);
2109
2110     /* XXX: fseek() too tricky for our own good */
2111     if (!fmsh)
2112         fseek (fp, 0L, SEEK_SET);
2113
2114     vmhpid = OK;
2115
2116     snprintf (buffer, sizeof(buffer), "%d", n);
2117     switch (str2rc (RC_WIN, buffer, rc)) {
2118         case RC_ACK: 
2119             break;
2120
2121         case RC_ERR: 
2122             return NOTOK;
2123
2124         case RC_XXX: 
2125             padios (NULL, "%s", rc->rc_data);
2126
2127         default: 
2128             fmt2peer (RC_ERR, "pWIN protocol screw-up");
2129             done (1);
2130     }
2131
2132     if (pipe (pd) == NOTOK) {
2133         err2peer (RC_ERR, "pipe", "unable to");
2134         return NOTOK;
2135     }
2136
2137     switch (vmhpid = fork()) {
2138         case NOTOK: 
2139             err2peer (RC_ERR, "fork", "unable to");
2140             close (pd[0]);
2141             close (pd[1]);
2142             return NOTOK;
2143
2144         case OK: 
2145             close (pd[1]);
2146             SIGNAL (SIGPIPE, SIG_IGN);
2147             while ((i = read (pd[0], buffer, sizeof buffer)) > 0)
2148                 switch (rc2rc (RC_DATA, i, buffer, rc)) {
2149                     case RC_ACK: 
2150                         break;
2151
2152                     case RC_ERR: 
2153                         _exit (1);
2154
2155                     case RC_XXX: 
2156                         advise (NULL, "%s", rc->rc_data);
2157                         _exit (2);
2158
2159                     default: 
2160                         fmt2peer (RC_ERR, "pWIN protocol screw-up");
2161                         _exit (2);
2162                 }
2163             if (i == OK)
2164                 switch (rc2rc (RC_EOF, 0, NULL, rc)) {
2165                     case RC_ACK: 
2166                         if (eof)
2167                             rc2peer (RC_EOF, 0, NULL);
2168                         i = 0;
2169                         break;
2170
2171                     case RC_XXX: 
2172                         advise (NULL, "%s", rc->rc_data);
2173                         i = 2;
2174                         break;
2175
2176                     default: 
2177                         fmt2peer (RC_ERR, "pWIN protocol screw-up");
2178                         i = 2;
2179                         break;
2180                 }
2181             if (i == NOTOK)
2182                 err2peer (RC_ERR, "pipe", "error reading from");
2183             close (pd[0]);
2184             _exit (i != NOTOK ? i : 1);
2185
2186         default: 
2187             if ((vmhfd0 = dup (fileno (stdin))) == NOTOK)
2188                 padios ("standard input", "unable to dup");
2189             if ((vmhfd1 = dup (fileno (stdout))) == NOTOK)
2190                 padios ("standard output", "unable to dup");
2191             if ((vmhfd2 = dup (fileno (stderr))) == NOTOK)
2192                 padios ("diagnostic output", "unable to dup");
2193
2194             close (0);
2195             if ((i = open ("/dev/null", O_RDONLY)) != NOTOK && i != fileno (stdin)) {
2196                 dup2 (i, fileno (stdin));
2197                 close (i);
2198             }
2199
2200             fflush (stdout);
2201             if (dup2 (pd[1], fileno (stdout)) == NOTOK)
2202                 padios ("standard output", "unable to dup2");
2203             clearerr (stdout);
2204
2205             fflush (stderr);
2206             if (dup2 (pd[1], fileno (stderr)) == NOTOK)
2207                 padios ("diagnostic output", "unable to dup2");
2208             clearerr (stderr);
2209
2210             if (cmdp && init_io (cmdp, 0) == NOTOK)
2211                 return NOTOK;
2212             pstat = SIGNAL (SIGPIPE, pipeser);
2213             broken_pipe = 1;
2214
2215             close (pd[0]);
2216             close (pd[1]);
2217
2218             return vmhpid;
2219     }
2220 }
2221
2222
2223 static int
2224 winR (struct Cmd *cmdp)
2225 {
2226     int status;
2227
2228     if (vmhpid <= OK)
2229         return NOTOK;
2230
2231     if (cmdp)
2232         fin_io (cmdp, 0);
2233
2234     if (dup2 (vmhfd0, fileno (stdin)) == NOTOK)
2235         padios ("standard input", "unable to dup2");
2236     clearerr (stdin);
2237     close (vmhfd0);
2238
2239     fflush (stdout);
2240     if (dup2 (vmhfd1, fileno (stdout)) == NOTOK)
2241         padios ("standard output", "unable to dup2");
2242     clearerr (stdout);
2243     close (vmhfd1);
2244
2245     fflush (stderr);
2246     if (dup2 (vmhfd2, fileno (stderr)) == NOTOK)
2247         padios ("diagnostic output", "unable to dup2");
2248     clearerr (stderr);
2249     close (vmhfd2);
2250
2251     SIGNAL (SIGPIPE, pstat);
2252
2253     if ((status = pidwait (vmhpid, OK)) == 2)
2254         done (1);
2255
2256     vmhpid = OK;
2257     return (status == 0 ? OK : NOTOK);
2258 }
2259
2260
2261 static int
2262 winX (int n)
2263 {
2264     int i, pid, pd[2];
2265     char buffer[BUFSIZ];
2266     struct record rcs, *rc;
2267
2268     rc = &rcs;
2269     initrc (rc);
2270
2271     /* XXX: fseek() too tricky for our own good */
2272     if (!fmsh)
2273         fseek (fp, 0L, SEEK_SET);
2274
2275     snprintf (buffer, sizeof(buffer), "%d", n);
2276     switch (str2rc (RC_WIN, buffer, rc)) {
2277         case RC_ACK: 
2278             break;
2279
2280         case RC_ERR: 
2281             return NOTOK;
2282
2283         case RC_XXX: 
2284             padios (NULL, "%s", rc->rc_data);
2285
2286         default: 
2287             fmt2peer (RC_ERR, "pWIN protocol screw-up");
2288             done (1);
2289     }
2290
2291     if (pipe (pd) == NOTOK) {
2292         err2peer (RC_ERR, "pipe", "unable to");
2293         return NOTOK;
2294     }
2295
2296     switch (pid = fork ()) {
2297         case NOTOK: 
2298             err2peer (RC_ERR, "fork", "unable to");
2299             close (pd[0]);
2300             close (pd[1]);
2301             return NOTOK;
2302
2303         case OK: 
2304             close (fileno (stdin));
2305             if ((i = open ("/dev/null", O_RDONLY)) != NOTOK && i != fileno (stdin)) {
2306                 dup2 (i, fileno (stdin));
2307                 close (i);
2308             }
2309             dup2 (pd[1], fileno (stdout));
2310             dup2 (pd[1], fileno (stderr));
2311             close (pd[0]);
2312             close (pd[1]);
2313             vmhpid = NOTOK;
2314             return OK;
2315
2316         default: 
2317             close (pd[1]);
2318             while ((i = read (pd[0], buffer, sizeof buffer)) > 0)
2319                 switch (rc2rc (RC_DATA, i, buffer, rc)) {
2320                     case RC_ACK: 
2321                         break;
2322
2323                     case RC_ERR: 
2324                         close (pd[0]);
2325                         pidwait (pid, OK);
2326                         return NOTOK;
2327
2328                     case RC_XXX: 
2329                         padios (NULL, "%s", rc->rc_data);
2330
2331                     default: 
2332                         fmt2peer (RC_ERR, "pWIN protocol screw-up");
2333                         done (1);
2334                 }
2335             if (i == OK)
2336                 switch (rc2rc (RC_EOF, 0, NULL, rc)) {
2337                     case RC_ACK: 
2338                         break;
2339
2340                     case RC_XXX: 
2341                         padios (NULL, "%s", rc->rc_data);
2342
2343                     default: 
2344                         fmt2peer (RC_ERR, "pWIN protocol screw-up");
2345                         done (1);
2346                 }
2347             if (i == NOTOK)
2348                 err2peer (RC_ERR, "pipe", "error reading from");
2349
2350             close (pd[0]);
2351             pidwait (pid, OK);
2352             return (i != NOTOK ? pid : NOTOK);
2353     }
2354 }
2355
2356
2357 void
2358 padios (char *what, char *fmt, ...)
2359 {
2360     va_list ap;
2361
2362     va_start(ap, fmt);
2363     if (vmh) {
2364         verr2peer (RC_FIN, what, fmt, ap);
2365         rcdone ();
2366     } else {
2367         advertise (what, NULL, fmt, ap);
2368     }
2369     va_end(ap);
2370
2371     done (1);
2372 }
2373
2374
2375 void
2376 padvise (char *what, char *fmt, ...)
2377 {
2378     va_list ap;
2379
2380     va_start(ap, fmt);
2381     if (vmh) {
2382         verr2peer (RC_ERR, what, fmt, ap);
2383     } else {
2384         advertise (what, NULL, fmt, ap);
2385     }
2386     va_end(ap);
2387 }