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