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