0dfc3d72194e4eaa8a70eee9f9cfa6ba9f505f13
[mmh] / uip / whatnowsbr.c
1 /*
2 ** whatnowsbr.c -- the WhatNow shell
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 **
8 **  Several options have been added to ease the inclusion of attachments
9 **  using the header field name mechanism added to anno and send.  The
10 **  -attach option is used to specify the header field name for attachments.
11 **
12 **  Several commands have been added at the whatnow prompt:
13 **
14 **        cd [ directory ]        This option works just like the shell's
15 **                                cd command and lets the user change the
16 **                                directory from which attachments are
17 **                                taken so that long path names are not
18 **                                needed with every file.
19 **
20 **        ls [ ls-options ]       This option works just like the normal
21 **                                ls command and exists to allow the user
22 **                                to verify file names in the directory.
23 **
24 **        pwd                     This option works just like the normal
25 **                                pwd command and exists to allow the user
26 **                                to verify the directory.
27 **
28 **        attach files            This option attaches the named files to
29 **                                the draft.
30 **
31 **        alist [-ln]             This option lists the attachments on the
32 **                                draft.  -l gets long listings, -n gets
33 **                                numbered listings.
34 **
35 **        detach files            This option removes attachments from the
36 **        detach -n numbers       draft.  This can be done by file name or
37 **                                by attachment number.
38 */
39
40 #include <h/mh.h>
41 #include <fcntl.h>
42 #include <signal.h>
43 #include <h/mime.h>
44 #include <h/utils.h>
45
46 static struct swit whatnowswitches[] = {
47 #define EDITRSW  0
48         { "editor editor", 0 },
49 #define NEDITSW  1
50         { "noedit", 0 },
51 #define PRMPTSW  2
52         { "prompt string", 4 },
53 #define VERSIONSW  3
54         { "version", 0 },
55 #define HELPSW  4
56         { "help", 0 },
57 #define ATTACHSW  5
58         { "attach header-field-name", 0 },
59         { NULL, 0 }
60 };
61
62 /*
63 ** Options at the "whatnow" prompt
64 */
65 static struct swit aleqs[] = {
66 #define EDITSW  0
67         { "edit [<editor> <switches>]", 0 },
68 #define REFILEOPT  1
69         { "refile [<switches>] +folder", 0 },
70 #define BUILDMIMESW  2
71         { "mime [<switches>]", 0 },
72 #define DISPSW  3
73         { "display [<switches>]", 0 },
74 #define LISTSW  4
75         { "list [<switches>]", 0 },
76 #define SENDSW  5
77         { "send [<switches>]", 0 },
78 #define PUSHSW  6
79         { "push [<switches>]", 0 },
80 #define QUITSW  7
81         { "quit [-delete]", 0 },
82 #define DELETESW  8
83         { "delete", 0 },
84 #define CDCMDSW  9
85         { "cd [directory]", 0 },
86 #define PWDCMDSW  10
87         { "pwd", 0 },
88 #define LSCMDSW  11
89         { "ls", 0 },
90 #define ATTACHCMDSW  12
91         { "attach", 0 },
92 #define DETACHCMDSW  13
93         { "detach [-n]", 2 },
94 #define ALISTCMDSW  14
95         { "alist [-ln] ", 2 },
96         { NULL, 0 }
97 };
98
99 static char *myprompt = "\nWhat now? ";
100
101 /*
102 ** static prototypes
103 */
104 static int editfile (char **, char **, char *, int, struct msgs *,
105         char *, char *, int);
106 static int sendfile (char **, char *, int);
107 static void sendit (char *, char **, char *, int);
108 static int buildfile (char **, char *);
109 static int check_draft (char *);
110 static int removefile (char *);
111 static void writelscmd(char *, int, char **);
112 static void writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp);
113 static FILE* popen_in_dir(const char *dir, const char *cmd, const char *type);
114 static int system_in_dir(const char *dir, const char *cmd);
115
116
117 #ifdef HAVE_LSTAT
118 static int copyf (char *, char *);
119 #endif
120
121
122 int
123 WhatNow (int argc, char **argv)
124 {
125         int nedit = 0, use = 0;
126         char *cp;
127         char *ed = NULL, *drft = NULL, *msgnam = NULL;
128         char buf[BUFSIZ], prompt[BUFSIZ];
129         char **argp, **arguments;
130         struct stat st;
131         char *attach = (char *)0;  /* attachment header field name */
132         char cwd[MAXPATHLEN + 1];  /* current working directory */
133         char file[MAXPATHLEN + 1];  /* file name buffer */
134         char shell[MAXPATHLEN + 1];  /* shell response buffer */
135         FILE *f;  /* read pointer for bgnd proc */
136         char *l;  /* set on -l to alist  command */
137         int n;  /* set on -n to alist command */
138
139         invo_name = r1bindex (argv[0], '/');
140
141         /* read user profile/context */
142         context_read();
143
144         arguments = getarguments (invo_name, argc, argv, 1);
145         argp = arguments;
146
147         /*
148         ** Get the initial current working directory.
149         */
150
151         if (getcwd(cwd, sizeof (cwd)) == (char *)0) {
152                 adios("getcwd", "could not get working directory");
153         }
154
155         while ((cp = *argp++)) {
156                 if (*cp == '-') {
157                         switch (smatch (++cp, whatnowswitches)) {
158                         case AMBIGSW:
159                                 ambigsw (cp, whatnowswitches);
160                                 done (1);
161                         case UNKWNSW:
162                                 adios (NULL, "-%s unknown", cp);
163
164                         case HELPSW:
165                                 snprintf (buf, sizeof(buf),
166                                                 "%s [switches] [file]",
167                                                 invo_name);
168                                 print_help (buf, whatnowswitches, 1);
169                                 done (1);
170                         case VERSIONSW:
171                                 print_version(invo_name);
172                                 done (1);
173
174                         case EDITRSW:
175                                 if (!(ed = *argp++) || *ed == '-')
176                                         adios (NULL, "missing argument to %s",
177                                                         argp[-2]);
178                                 nedit = 0;
179                                 continue;
180                         case NEDITSW:
181                                 nedit++;
182                                 continue;
183
184                         case PRMPTSW:
185                                 if (!(myprompt = *argp++) || *myprompt == '-')
186                                         adios (NULL, "missing argument to %s",
187                                                         argp[-2]);
188                                 continue;
189
190                         case ATTACHSW:
191                                 if (attach != (char *)0)
192                                         adios(NULL, "only one attachment header field name at a time!");
193                                 if (!(attach = *argp++) || *attach == '-')
194                                         adios (NULL, "missing argument to %s",
195                                                         argp[-2]);
196                                 continue;
197                         }
198                 }
199                 if (drft)
200                         adios (NULL, "only one draft at a time!");
201                 else
202                         drft = cp;
203         }
204
205         if ((drft == NULL && (drft = getenv("mhdraft")) == NULL) || *drft == 0)
206                 drft = getcpy (m_draft("cur"));
207
208         msgnam = (cp = getenv ("mhaltmsg")) && *cp ? getcpy (cp) : NULL;
209
210         if ((cp = getenv ("mhuse")) && *cp)
211                 use = atoi (cp);
212
213         if (ed == NULL && ((ed = getenv ("mheditor")) == NULL || *ed == 0)) {
214                 ed = NULL;
215                 nedit++;
216         }
217
218         /* start editing the draft, unless -noedit was given */
219         if (!nedit && editfile(&ed, NULL, drft, use, NULL, msgnam, NULL, 1)
220                         < 0)
221                 done (1);
222
223         snprintf (prompt, sizeof(prompt), myprompt, invo_name);
224         for (;;) {
225                 if (!(argp = getans (prompt, aleqs))) {
226                         unlink (altmsglink);
227                         done (1);
228                 }
229                 switch (smatch (*argp, aleqs)) {
230                 case DISPSW:
231                         /*
232                         ** display the message being replied to,
233                         ** or distributed
234                         */
235                         if (msgnam)
236                                 showfile (++argp, msgnam);
237                         else
238                                 advise (NULL, "no alternate message to display");
239                         break;
240
241                 case BUILDMIMESW:
242                         /* Translate MIME composition file */
243                         buildfile (++argp, drft);
244                         break;
245
246                 case EDITSW:
247                         /* Call an editor on the draft file */
248                         if (*++argp)
249                                 ed = *argp++;
250                         if (editfile (&ed, argp, drft, NOUSE, NULL,
251                                         msgnam, NULL, 1) == NOTOK)
252                                 done (1);
253                         break;
254
255                 case LISTSW:
256                         /* display the draft file */
257                         showfile (++argp, drft);
258                         break;
259
260                 case QUITSW:
261                         /* Quit, and possibly delete the draft */
262                         if (*++argp && (*argp[0] == 'd' ||
263                                 ((*argp)[0] == '-' && (*argp)[1] == 'd'))) {
264                                 removefile (drft);
265                         } else {
266                                 if (stat (drft, &st) != NOTOK)
267                                         advise(NULL, "draft left on %s", drft);
268                         }
269                         done (1);
270
271                 case DELETESW:
272                         /* Delete draft and exit */
273                         removefile (drft);
274                         done (1);
275
276                 case PUSHSW:
277                         /* Send draft in background */
278                         if (sendfile (++argp, drft, 1))
279                                 done (1);
280                         break;
281
282                 case SENDSW:
283                         /* Send draft */
284                         sendfile (++argp, drft, 0);
285                         break;
286
287                 case REFILEOPT:
288                         /* Refile the draft */
289                         if (refile (++argp, drft) == 0)
290                                 done (0);
291                         break;
292
293                 case CDCMDSW:
294                         /*
295                         ** Change the working directory for attachments
296                         **
297                         ** Run the directory through the user's shell
298                         ** so that we can take advantage of any syntax
299                         ** that the user is accustomed to.  Read back
300                         ** the absolute path.
301                         */
302
303                         if (*(argp+1) == (char *)0) {
304                                 (void)sprintf(buf, "$SHELL -c \"cd;pwd\"");
305                         } else {
306                                 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
307                         }
308                         if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
309                                 fgets(cwd, sizeof (cwd), f);
310
311                                 if (strchr(cwd, '\n') != (char *)0)
312                                                 *strchr(cwd, '\n') = '\0';
313
314                                 pclose(f);
315                         } else {
316                                 advise("popen", "could not get directory");
317                         }
318
319                         break;
320
321                 case PWDCMDSW:
322                         /* Print the working directory for attachments */
323                         printf("%s\n", cwd);
324                         break;
325
326                 case LSCMDSW:
327                         /*
328                         ** List files in the current attachment working
329                         ** directory
330                         **
331                         ** Use the user's shell so that we can take
332                         ** advantage of any syntax that the user is
333                         ** accustomed to.
334                         */
335                         writelscmd(buf, sizeof(buf), argp);
336                         (void)system_in_dir(cwd, buf);
337                         break;
338
339                 case ALISTCMDSW:
340                         /*
341                         ** List attachments on current draft.  Options are:
342                         **
343                         ** -l    long listing (full path names)
344                         ** -n    numbers listing
345                         */
346
347                         if (attach == (char *)0) {
348                                 advise((char *)0, "can't list because no header field name was given.");
349                                 break;
350                         }
351
352                         l = (char *)0;
353                         n = 0;
354
355                         while (*++argp != (char *)0) {
356                                 if (strcmp(*argp, "-l") == 0)
357                                         l = "/";
358
359                                 else if (strcmp(*argp, "-n") == 0)
360                                         n = 1;
361
362                                 else if (strcmp(*argp, "-ln") == 0 ||
363                                                 strcmp(*argp, "-nl") == 0) {
364                                         l = "/";
365                                         n = 1;
366                                 } else {
367                                         n = -1;
368                                         break;
369                                 }
370                         }
371
372                         if (n == -1)
373                                 advise((char *)0, "usage is alist [-ln].");
374
375                         else
376                                 annolist(drft, attach, l, n);
377
378                         break;
379
380                 case ATTACHCMDSW:
381                         /*
382                         ** Attach files to current draft.
383                         */
384
385                         if (attach == (char *)0) {
386                                 advise((char *)0, "can't attach because no header field name was given.");
387                                 break;
388                         }
389
390                         if (*(argp+1) == (char *)0) {
391                                 advise((char *)0, "attach command requires file argument(s).");
392                                 break;
393                         }
394
395                         /*
396                         ** Build a command line that causes the user's
397                         ** shell to list the file name arguments.
398                         ** This handles and wildcard expansion, tilde
399                         ** expansion, etc.
400                         */
401                         writelscmd(buf, sizeof(buf), argp);
402
403                         /*
404                         ** Read back the response from the shell,
405                         ** which contains a number of lines with one
406                         ** file name per line.  Remove off the newline.
407                         ** Determine whether we have an absolute or
408                         ** relative path name.  Prepend the current
409                         ** working directory to relative path names.
410                         ** Add the attachment annotation to the draft.
411                         */
412
413                         if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
414                                 while (fgets(shell, sizeof (shell), f)
415                                                 != (char *)0) {
416                                         *(strchr(shell, '\n')) = '\0';
417
418                                         if (*shell == '/')
419                                                 annotate(drft, attach, shell,
420                                                                 1, 0, -2, 1);
421                                         else {
422                                                 sprintf(file, "%s/%s", cwd,
423                                                                 shell);
424                                                 annotate(drft, attach, file,
425                                                                 1, 0, -2, 1);
426                                         }
427                                 }
428
429                                 pclose(f);
430                         } else {
431                                 advise("popen", "could not get file from shell");
432                         }
433
434                         break;
435
436                 case DETACHCMDSW:
437                         /*
438                         ** Detach files from current draft.
439                         */
440
441                         if (attach == (char *)0) {
442                                 advise((char *)0, "can't detach because no header field name was given.");
443                                 break;
444                         }
445
446                         /*
447                         ** Scan the arguments for a -n.  Mixed file
448                         ** names and numbers aren't allowed, so this
449                         ** catches a -n anywhere in the argument list.
450                         */
451
452                         for (n = 0, arguments = argp + 1;
453                                         *arguments != (char *)0;
454                                         arguments++) {
455                                 if (strcmp(*arguments, "-n") == 0) {
456                                                 n = 1;
457                                                 break;
458                                 }
459                         }
460
461                         /*
462                         ** A -n was found so interpret the arguments as
463                         ** attachment numbers.  Decrement any remaining
464                         ** argument number that is greater than the one
465                         ** just processed after processing each one so
466                         ** that the numbering stays correct.
467                         */
468
469                         if (n == 1) {
470                                 for (arguments = argp + 1;
471                                                 *arguments != (char *)0;
472                                                 arguments++) {
473                                         if (strcmp(*arguments, "-n") == 0)
474                                                 continue;
475
476                                         if (**arguments != '\0') {
477                                                 n = atoi(*arguments);
478                                                 annotate(drft, attach, NULL,
479                                                                 1, 0, n, 1);
480
481                                                 for (argp = arguments + 1; *argp != (char *)0; argp++) {
482                                                         if (atoi(*argp) > n) {
483                                                                 if (atoi(*argp) == 1)
484                                                                         *argp = "";
485                                                                 else
486                                                                         (void)sprintf(*argp, "%d", atoi(*argp) - 1);
487                                                         }
488                                                 }
489                                         }
490                                 }
491                         }
492
493                         /*
494                         ** The arguments are interpreted as file names.
495                         ** Run them through the user's shell for wildcard
496                         ** expansion and other goodies.  Do this from
497                         ** the current working directory if the argument
498                         ** is not an absolute path name (does not begin
499                         ** with a /).
500                         **
501                         ** We feed all the file names to the shell at
502                         ** once, otherwise you can't provide a file name
503                         ** with a space in it.
504                         */
505                         writelscmd(buf, sizeof(buf), argp);
506                         if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
507                                 while (fgets(shell, sizeof (shell), f)
508                                                 != NULL) {
509                                         *(strchr(shell, '\n')) = '\0';
510                                         annotate(drft, attach, shell,
511                                                         1, 0, 0, 1);
512                                 }
513                                 pclose(f);
514                         } else {
515                                 advise("popen", "could not get file from shell");
516                         }
517
518                         break;
519
520                 default:
521                         /* Unknown command */
522                         advise (NULL, "say what?");
523                         break;
524                 }
525         }
526         /*NOTREACHED*/
527 }
528
529
530
531 /*
532 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
533 ** trailcmd".
534 */
535 static void
536 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
537 {
538         char *cp;
539         /*
540         ** Note that we do not quote -- the argp from the user
541         ** is assumed to be quoted as they desire. (We can't treat
542         ** it as pure literal as that would prevent them using ~,
543         ** wildcards, etc.) The buffer produced by this function
544         ** should be given to popen_in_dir() or system_in_dir() so
545         ** that the current working directory is set correctly.
546         */
547         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
548         /*
549         ** NB that some snprintf() return -1 on overflow rather than the
550         ** new C99 mandated 'number of chars that would have been written'
551         */
552         /*
553         ** length checks here and inside the loop allow for the
554         ** trailing ';', trailcmd, '"' and NUL
555         */
556         int trailln = strlen(trailcmd) + 3;
557         if (ln < 0 || ln + trailln > bufsz)
558                 adios((char *)0, "arguments too long");
559
560         cp = buf + ln;
561
562         while (*++argp != (char *)0) {
563                 ln = strlen(*argp);
564                 /* +1 for leading space */
565                 if (ln + trailln + 1 > bufsz - (cp-buf))
566                         adios((char *)0, "arguments too long");
567                 *cp++ = ' ';
568                 memcpy(cp, *argp, ln+1);
569                 cp += ln;
570         }
571         if (*trailcmd) {
572                 *cp++ = ';';
573                 strcpy(cp, trailcmd);
574                 cp += trailln - 3;
575         }
576         *cp++ = '"';
577         *cp = 0;
578 }
579
580 /*
581 ** Build a command line that causes the user's shell to list the file name
582 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
583 */
584 static void
585 writelscmd(char *buf, int bufsz, char **argp)
586 {
587         writesomecmd(buf, bufsz, "ls", "", argp);
588 }
589
590 /*
591 ** Like system(), but run the command in directory dir.
592 ** This assumes the program is single-threaded!
593 */
594 static int
595 system_in_dir(const char *dir, const char *cmd)
596 {
597         char olddir[BUFSIZ];
598         int r;
599         if (getcwd(olddir, sizeof(olddir)) == 0)
600                 adios("getcwd", "could not get working directory");
601         if (chdir(dir) != 0)
602                 adios("chdir", "could not change working directory");
603         r = system(cmd);
604         if (chdir(olddir) != 0)
605                 adios("chdir", "could not change working directory");
606         return r;
607 }
608
609 /* ditto for popen() */
610 static FILE*
611 popen_in_dir(const char *dir, const char *cmd, const char *type)
612 {
613         char olddir[BUFSIZ];
614         FILE *f;
615         if (getcwd(olddir, sizeof(olddir)) == 0)
616                 adios("getcwd", "could not get working directory");
617         if (chdir(dir) != 0)
618                 adios("chdir", "could not change working directory");
619         f = popen(cmd, type);
620         if (chdir(olddir) != 0)
621                 adios("chdir", "could not change working directory");
622         return f;
623 }
624
625
626 /*
627 ** EDIT
628 */
629
630 static int  reedit = 0;  /* have we been here before? */
631 static char *edsave = NULL;  /* the editor we used previously */
632
633
634 static int
635 editfile (char **ed, char **arg, char *file, int use, struct msgs *mp,
636         char *altmsg, char *cwd, int save_editor)
637 {
638         int pid, status, vecp;
639         char altpath[BUFSIZ], linkpath[BUFSIZ];
640         char *cp, *vec[MAXARGS];
641         struct stat st;
642
643 #ifdef HAVE_LSTAT
644         int slinked = 0;
645 #if 0
646         int oumask;  /* PJS: for setting permissions on symlinks. */
647 #endif
648 #endif /* HAVE_LSTAT */
649
650         /* Was there a previous edit session? */
651         if (reedit) {
652                 if (!*ed) {  /* no explicit editor */
653                         *ed = edsave;  /* so use the previous one */
654                         if ((cp = r1bindex (*ed, '/')) == NULL)
655                                 cp = *ed;
656
657                         /* unless we've specified it via "editor-next" */
658                         cp = concat (cp, "-next", NULL);
659                         if ((cp = context_find (cp)) != NULL)
660                                 *ed = cp;
661                 }
662         } else {
663                 /* set initial editor */
664                 if (*ed == NULL && (*ed = context_find ("editor")) == NULL)
665                         *ed = defaulteditor;
666         }
667
668         if (altmsg) {
669                 if (mp == NULL || *altmsg == '/' || cwd == NULL)
670                         strncpy (altpath, altmsg, sizeof(altpath));
671                 else
672                         snprintf (altpath, sizeof(altpath), "%s/%s",
673                                         mp->foldpath, altmsg);
674                 if (cwd == NULL)
675                         strncpy (linkpath, altmsglink, sizeof(linkpath));
676                 else
677                         snprintf (linkpath, sizeof(linkpath), "%s/%s",
678                                         cwd, altmsglink);
679         }
680
681         if (altmsg) {
682                 unlink (linkpath);
683 #ifdef HAVE_LSTAT
684                 if (link (altpath, linkpath) == NOTOK) {
685 #if 0
686                         /* I don't think permission on symlinks matters /JLR */
687                         /* PJS: else symlinks are world 'r' */
688                         oumask = umask(0044);
689 #endif
690                         symlink (altpath, linkpath);
691 #if 0
692                         umask(oumask);  /* PJS: else symlinks are world 'r' */
693 #endif
694                         slinked = 1;
695                 } else {
696                         slinked = 0;
697                 }
698 #else /* not HAVE_LSTAT */
699                 link (altpath, linkpath);
700 #endif /* not HAVE_LSTAT */
701         }
702
703         context_save ();  /* save the context file */
704         fflush (stdout);
705
706         switch (pid = vfork ()) {
707                 case NOTOK:
708                         advise ("fork", "unable to");
709                         status = NOTOK;
710                         break;
711
712                 case OK:
713                         if (cwd)
714                                 chdir (cwd);
715                         if (altmsg) {
716                                 if (mp)
717                                         m_putenv ("mhfolder", mp->foldpath);
718                                 m_putenv ("editalt", altpath);
719                         }
720
721                         vecp = 0;
722                         vec[vecp++] = r1bindex (*ed, '/');
723                         if (arg)
724                                 while (*arg)
725                                         vec[vecp++] = *arg++;
726                         vec[vecp++] = file;
727                         vec[vecp] = NULL;
728
729                         execvp (*ed, vec);
730                         fprintf (stderr, "unable to exec ");
731                         perror (*ed);
732                         _exit (-1);
733
734                 default:
735                         if ((status = pidwait (pid, NOTOK))) {
736 #ifdef ATTVIBUG
737                                 if ((cp = r1bindex (*ed, '/'))
738                                                 && strcmp (cp, "vi") == 0
739                                                 && (status & 0x00ff) == 0)
740                                         status = 0;
741                                 else {
742 #endif
743                                 if (((status & 0xff00) != 0xff00)
744                                         && (!reedit || (status & 0x00ff))) {
745                                         if (!use && (status & 0xff00) &&
746                                                         (rename (file, cp = m_backup (file)) != NOTOK)) {
747                                                 advise (NULL, "problems with edit--draft left in %s", cp);
748                                         } else {
749                                                 advise (NULL, "problems with edit--%s preserved", file);
750                                         }
751                                 }
752                                 status = -2;  /* maybe "reedit ? -2 : -1"? */
753                                 break;
754 #ifdef ATTVIBUG
755                                 }
756 #endif
757                         }
758
759                         reedit++;
760 #ifdef HAVE_LSTAT
761                         if (altmsg
762                                         && mp
763                                         && !is_readonly(mp)
764                                         && (slinked
765                                                    ? lstat (linkpath, &st) != NOTOK
766                                                                 && S_ISREG(st.st_mode)
767                                                                 && copyf (linkpath, altpath) == NOTOK
768                                                    : stat (linkpath, &st) != NOTOK
769                                                                 && st.st_nlink == 1
770                                                                 && (unlink (altpath) == NOTOK
771                                                                                 || link (linkpath, altpath) == NOTOK)))
772                                 advise (linkpath, "unable to update %s from", altmsg);
773 #else /* HAVE_LSTAT */
774                         if (altmsg && mp && !is_readonly(mp)
775                                         && stat (linkpath, &st) != NOTOK
776                                         && st.st_nlink == 1
777                                         && (unlink (altpath) == NOTOK
778                                         || link (linkpath, altpath) == NOTOK))
779                                 advise (linkpath, "unable to update %s from",
780                                                 altmsg);
781 #endif /* HAVE_LSTAT */
782         }
783
784         /* normally, we remember which editor we used */
785         if (save_editor)
786                 edsave = getcpy (*ed);
787
788         *ed = NULL;
789         if (altmsg)
790                 unlink (linkpath);
791
792         return status;
793 }
794
795
796 #ifdef HAVE_LSTAT
797 static int
798 copyf (char *ifile, char *ofile)
799 {
800         int i, in, out;
801         char buffer[BUFSIZ];
802
803         if ((in = open (ifile, O_RDONLY)) == NOTOK)
804                 return NOTOK;
805         if ((out = open (ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
806                 admonish (ofile, "unable to open and truncate");
807                 close (in);
808                 return NOTOK;
809         }
810
811         while ((i = read (in, buffer, sizeof(buffer))) > OK)
812                 if (write (out, buffer, i) != i) {
813                         advise (ofile, "may have damaged");
814                         i = NOTOK;
815                         break;
816                 }
817
818         close (in);
819         close (out);
820         return i;
821 }
822 #endif /* HAVE_LSTAT */
823
824
825 /*
826 ** SEND
827 */
828
829 static int
830 sendfile (char **arg, char *file, int pushsw)
831 {
832         pid_t child_id;
833         int i, vecp;
834         char *cp, *sp, *vec[MAXARGS];
835
836         /* Translate MIME composition file, if necessary */
837         if ((cp = context_find ("automimeproc")) && (!strcmp (cp, "1"))
838                         && !getenv ("NOMHNPROC") && check_draft (file)
839                         && (buildfile (NULL, file) == NOTOK))
840                 return 0;
841
842         /* For backwards compatibility */
843         if ((cp = context_find ("automhnproc")) && !getenv ("NOMHNPROC")
844                         && check_draft (file) && (i = editfile (&cp, NULL,
845                         file, NOUSE, NULL, NULL, NULL, 0)))
846                 return 0;
847
848         /*
849         ** If the sendproc is the nmh command `send', then we call
850         ** those routines directly rather than exec'ing the command.
851         */
852         if (strcmp (sp = r1bindex (sendproc, '/'), "send") == 0) {
853                 cp = invo_name;
854                 sendit (invo_name = sp, arg, file, pushsw);
855                 invo_name = cp;
856                 return 1;
857         }
858
859         context_save ();  /* save the context file */
860         fflush (stdout);
861
862         for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
863                 sleep (5);
864         switch (child_id) {
865                 case NOTOK:
866                         advise (NULL, "unable to fork, so sending directly...");
867                 case OK:
868                         vecp = 0;
869                         vec[vecp++] = invo_name;
870                         if (pushsw)
871                                 vec[vecp++] = "-push";
872                         if (arg)
873                                 while (*arg)
874                                         vec[vecp++] = *arg++;
875                         vec[vecp++] = file;
876                         vec[vecp] = NULL;
877
878                         execvp (sendproc, vec);
879                         fprintf (stderr, "unable to exec ");
880                         perror (sendproc);
881                         _exit (-1);
882
883                 default:
884                         if (pidwait(child_id, OK) == 0)
885                                 done (0);
886                         return 1;
887         }
888 }
889
890
891 /*
892 ** Translate MIME composition file (call buildmimeproc)
893 */
894
895 static int
896 buildfile (char **argp, char *file)
897 {
898         int i;
899         char **args, *ed;
900
901         ed = buildmimeproc;
902
903         /* allocate space for arguments */
904         i = 0;
905         if (argp) {
906                 while (argp[i])
907                         i++;
908         }
909         args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
910
911         /*
912         ** For backward compatibility, we need to add -build
913         ** if we are using mhn as buildmimeproc
914         */
915         i = 0;
916         if (strcmp (r1bindex (ed, '/'), "mhn") == 0)
917                 args[i++] = "-build";
918
919         /* copy any other arguments */
920         while (argp && *argp)
921                 args[i++] = *argp++;
922         args[i] = NULL;
923
924         i = editfile (&ed, args, file, NOUSE, NULL, NULL, NULL, 0);
925         free (args);
926
927         return (i ? NOTOK : OK);
928 }
929
930
931 /*
932 **  Check if draft is a mhbuild composition file
933 */
934
935 static int
936 check_draft (char *msgnam)
937 {
938         int state;
939         char buf[BUFSIZ], name[NAMESZ];
940         FILE *fp;
941
942         if ((fp = fopen (msgnam, "r")) == NULL)
943                 return 0;
944         for (state = FLD;;)
945                 switch (state = m_getfld (state, name, buf, sizeof(buf), fp)) {
946                         case FLD:
947                         case FLDPLUS:
948                         case FLDEOF:
949                                 /*
950                                 ** If draft already contains any of the
951                                 ** Content-XXX fields, then assume it already
952                                 ** been converted.
953                                 */
954                                 if (uprf (name, XXX_FIELD_PRF)) {
955                                         fclose (fp);
956                                         return 0;
957                                 }
958                                 while (state == FLDPLUS)
959                                         state = m_getfld (state, name, buf,
960                                                         sizeof(buf), fp);
961                                 break;
962
963                         case BODY:
964                                 do {
965                                         char *bp;
966
967                                         for (bp = buf; *bp; bp++)
968                                                 if (*bp != ' ' && *bp != '\t' && *bp != '\n') {
969                                                         fclose (fp);
970                                                         return 1;
971                                                 }
972
973                                         state = m_getfld (state, name, buf,
974                                                         sizeof(buf), fp);
975                                 } while (state == BODY);
976                                 /* and fall... */
977
978                         default:
979                                 fclose (fp);
980                                 return 0;
981                 }
982 }
983
984
985 static struct swit  sendswitches[] = {
986 #define ALIASW  0
987         { "alias aliasfile", 0 },
988 #define DEBUGSW  1
989         { "debug", -5 },
990 #define FILTSW  2
991         { "filter filterfile", 0 },
992 #define NFILTSW  3
993         { "nofilter", 0 },
994 #define FRMTSW  4
995         { "format", 0 },
996 #define NFRMTSW  5
997         { "noformat", 0 },
998 #define FORWSW  6
999         { "forward", 0 },
1000 #define NFORWSW  7
1001         { "noforward", 0 },
1002 #define MIMESW  8
1003         { "mime", 0 },
1004 #define NMIMESW  9
1005         { "nomime", 0 },
1006 #define MSGDSW  10
1007         { "msgid", 0 },
1008 #define NMSGDSW  11
1009         { "nomsgid", 0 },
1010 #define SPSHSW  12
1011         { "push", 0 },
1012 #define NSPSHSW  13
1013         { "nopush", 0 },
1014 #define UNIQSW  14
1015         { "unique", -6 },
1016 #define NUNIQSW  15
1017         { "nounique", -8 },
1018 #define VERBSW  16
1019         { "verbose", 0 },
1020 #define NVERBSW  17
1021         { "noverbose", 0 },
1022 #define WATCSW  18
1023         { "watch", 0 },
1024 #define NWATCSW  19
1025         { "nowatch", 0 },
1026 #define WIDTHSW  20
1027         { "width columns", 0 },
1028 #define SVERSIONSW  21
1029         { "version", 0 },
1030 #define SHELPSW  22
1031         { "help", 0 },
1032 #define BITSTUFFSW  23
1033         { "dashstuffing", -12 },
1034 #define NBITSTUFFSW  24
1035         { "nodashstuffing", -14 },
1036 #define MAILSW  25
1037         { "mail", -4 },
1038 #define SAMLSW  26
1039         { "saml", -4 },
1040 #define SSNDSW  27
1041         { "send", -4 },
1042 #define SOMLSW  28
1043         { "soml", -4 },
1044 #define CLIESW  29
1045         { "client host", -6 },
1046 #define SERVSW  30
1047         { "server host", 6 },
1048 #define SNOOPSW  31
1049         { "snoop", -5 },
1050 #define SNDATTACHSW  32
1051         { "attach file", 6 },
1052 #define SNDATTACHFORMAT   33
1053         { "attachformat", 7 },
1054 #define PORTSW  34
1055         { "port server-port-name/number", 4 },
1056         { NULL, 0 }
1057 };
1058
1059
1060 extern int debugsw;  /* from sendsbr.c */
1061 extern int forwsw;
1062 extern int inplace;
1063 extern int pushsw;
1064 extern int unique;
1065 extern int verbsw;
1066
1067 extern char *altmsg;  /*  .. */
1068 extern char *annotext;
1069 extern char *distfile;
1070
1071
1072 static void
1073 sendit (char *sp, char **arg, char *file, int pushed)
1074 {
1075         int vecp, n = 1;
1076         char *cp, buf[BUFSIZ], **argp;
1077         char **arguments, *vec[MAXARGS];
1078         struct stat st;
1079         char *attach = (char *)0;  /* attachment header field name */
1080         int attachformat = 0;  /* mhbuild format specifier for attachments */
1081
1082 #ifndef lint
1083         int distsw = 0;
1084 #endif
1085 #ifdef UCI
1086         FILE *fp;
1087 #endif
1088
1089         /*
1090         ** Make sure these are defined.  In particular, we need
1091         ** vec[1] to be NULL, in case "arg" is NULL below.  It
1092         ** doesn't matter what is the value of vec[0], but we
1093         ** set it to NULL, to help catch "off-by-one" errors.
1094         */
1095         vec[0] = NULL;
1096         vec[1] = NULL;
1097
1098         /*
1099         ** Temporarily copy arg to vec, since the brkstring() call in
1100         ** getarguments() will wipe it out before it is merged in.
1101         ** Also, we skip the first element of vec, since getarguments()
1102         ** skips it.  Then we count the number of arguments
1103         ** copied.  The value of "n" will be one greater than
1104         ** this in order to simulate the standard argc/argv.
1105         */
1106         if (arg) {
1107                 char **bp;
1108
1109                 copyip (arg, vec+1, MAXARGS-1);
1110                 bp = vec+1;
1111                 while (*bp++)
1112                         n++;
1113         }
1114
1115         /*
1116         ** Merge any arguments from command line (now in vec)
1117         ** and arguments from profile.
1118         */
1119         arguments = getarguments (sp, n, vec, 1);
1120         argp = arguments;
1121
1122         debugsw = 0;
1123         forwsw = 1;
1124         inplace = 1;
1125         unique = 0;
1126
1127         altmsg = NULL;
1128         annotext = NULL;
1129         distfile = NULL;
1130
1131         vecp = 1;  /* we'll get the zero'th element later */
1132         vec[vecp++] = "-library";
1133         vec[vecp++] = getcpy (m_maildir (""));
1134
1135         while ((cp = *argp++)) {
1136                 if (*cp == '-') {
1137                         switch (smatch (++cp, sendswitches)) {
1138                                 case AMBIGSW:
1139                                         ambigsw (cp, sendswitches);
1140                                         return;
1141                                 case UNKWNSW:
1142                                         advise (NULL, "-%s unknown\n", cp);
1143                                         return;
1144
1145                                 case SHELPSW:
1146                                         snprintf (buf, sizeof(buf),
1147                                                         "%s [switches]", sp);
1148                                         print_help (buf, sendswitches, 1);
1149                                         return;
1150                                 case SVERSIONSW:
1151                                         print_version (invo_name);
1152                                         return;
1153
1154                                 case SPSHSW:
1155                                         pushed++;
1156                                         continue;
1157                                 case NSPSHSW:
1158                                         pushed = 0;
1159                                         continue;
1160
1161                                 case UNIQSW:
1162                                         unique++;
1163                                         continue;
1164                                 case NUNIQSW:
1165                                         unique = 0;
1166                                         continue;
1167                                 case FORWSW:
1168                                         forwsw++;
1169                                         continue;
1170                                 case NFORWSW:
1171                                         forwsw = 0;
1172                                         continue;
1173
1174                                 case VERBSW:
1175                                         verbsw++;
1176                                         vec[vecp++] = --cp;
1177                                         continue;
1178                                 case NVERBSW:
1179                                         verbsw = 0;
1180                                         vec[vecp++] = --cp;
1181                                         continue;
1182
1183                                 case DEBUGSW:
1184                                         debugsw++;  /* fall */
1185                                 case NFILTSW:
1186                                 case FRMTSW:
1187                                 case NFRMTSW:
1188                                 case BITSTUFFSW:
1189                                 case NBITSTUFFSW:
1190                                 case MIMESW:
1191                                 case NMIMESW:
1192                                 case MSGDSW:
1193                                 case NMSGDSW:
1194                                 case WATCSW:
1195                                 case NWATCSW:
1196                                 case MAILSW:
1197                                 case SAMLSW:
1198                                 case SSNDSW:
1199                                 case SOMLSW:
1200                                 case SNOOPSW:
1201                                         vec[vecp++] = --cp;
1202                                         continue;
1203
1204                                 case ALIASW:
1205                                 case FILTSW:
1206                                 case WIDTHSW:
1207                                 case CLIESW:
1208                                 case SERVSW:
1209                                 case PORTSW:
1210                                         vec[vecp++] = --cp;
1211                                         if (!(cp = *argp++) || *cp == '-') {
1212                                                 advise (NULL, "missing argument to %s", argp[-2]);
1213                                                 return;
1214                                         }
1215                                         vec[vecp++] = cp;
1216                                         continue;
1217
1218                                 case SNDATTACHSW:
1219                                         if (!(attach = *argp++) ||
1220                                                         *attach == '-') {
1221                                                 advise (NULL, "missing argument to %s", argp[-2]);
1222                                                 return;
1223                                         }
1224                                         continue;
1225
1226                                 case SNDATTACHFORMAT:
1227                                         if (! *argp || **argp == '-')
1228                                                 adios (NULL, "missing argument to %s", argp[-1]);
1229                                         else {
1230                                                 attachformat = atoi (*argp);
1231                                                 if (attachformat < 0 || attachformat > ATTACHFORMATS - 1) {
1232                                                         advise (NULL, "unsupported attachformat %d", attachformat);
1233                                                         continue;
1234                                                 }
1235                                         }
1236                                         ++argp;
1237                                         continue;
1238                         }
1239                 }
1240                 advise (NULL, "usage: %s [switches]", sp);
1241                 return;
1242         }
1243
1244         /* allow Aliasfile: profile entry */
1245         if ((cp = context_find ("Aliasfile"))) {
1246                 char **ap, *dp;
1247
1248                 dp = getcpy (cp);
1249                 for (ap = brkstring (dp, " ", "\n"); ap && *ap; ap++) {
1250                         vec[vecp++] = "-alias";
1251                         vec[vecp++] = *ap;
1252                 }
1253         }
1254
1255         if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
1256                 if ((cp = context_find ("signature")) && *cp)
1257                         m_putenv ("SIGNATURE", cp);
1258 #ifdef UCI
1259                 else {
1260                         snprintf (buf, sizeof(buf), "%s/.signature", mypath);
1261                         if ((fp = fopen (buf, "r")) != NULL
1262                                 && fgets (buf, sizeof(buf), fp) != NULL) {
1263                                         fclose (fp);
1264                                         if (cp = strchr (buf, '\n'))
1265                                                 *cp = 0;
1266                                         m_putenv ("SIGNATURE", buf);
1267                         }
1268                 }
1269 #endif /* UCI */
1270
1271         if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
1272                 annotext = NULL;
1273         if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
1274                 altmsg = NULL;
1275         if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
1276                 inplace = atoi (cp);
1277
1278         if ((cp = getenv ("mhdist"))
1279                         && *cp
1280 #ifndef lint
1281                         && (distsw = atoi (cp))
1282 #endif /* not lint */
1283                         && altmsg) {
1284                 vec[vecp++] = "-dist";
1285                 distfile = getcpy (m_mktemp2(altmsg, invo_name, NULL, NULL));
1286                 if (link (altmsg, distfile) == NOTOK)
1287                         adios (distfile, "unable to link %s to", altmsg);
1288         } else {
1289                 distfile = NULL;
1290         }
1291
1292         if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
1293                 st.st_mtime = 0;
1294                 st.st_dev = 0;
1295                 st.st_ino = 0;
1296         }
1297         if ((pushsw = pushed))
1298                 push ();
1299
1300         vec[0] = r1bindex (postproc, '/');
1301         closefds (3);
1302
1303         if (sendsbr (vec, vecp, file, &st, 1, attach, attachformat) == OK)
1304                 done (0);
1305 }
1306
1307
1308 /*
1309 ** Remove the draft file
1310 */
1311
1312 static int
1313 removefile (char *drft)
1314 {
1315         if (unlink (drft) == NOTOK)
1316                 adios (drft, "unable to unlink");
1317
1318         return OK;
1319 }