ed5647efecc34ad55b5b3f491ae1c7a8c52c5bcb
[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 = NULL;  /* 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 = mhbasename(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)) == NULL) {
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 != NULL)
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) == NULL) {
304                                 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') != NULL)
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                         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 == NULL) {
348                                 advise(NULL, "can't list because no header field name was given.");
349                                 break;
350                         }
351
352                         l = NULL;
353                         n = 0;
354
355                         while (*++argp != NULL) {
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(NULL, "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 == NULL) {
386                                 advise(NULL, "can't attach because no header field name was given.");
387                                 break;
388                         }
389
390                         if (*(argp+1) == NULL) {
391                                 advise(NULL, "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                                                 != NULL) {
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 == NULL) {
442                                 advise(NULL, "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 != NULL;
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 != NULL;
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 != NULL; argp++) {
482                                                         if (atoi(*argp) > n) {
483                                                                 if (atoi(*argp) == 1)
484                                                                         *argp = "";
485                                                                 else
486                                                                         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(NULL, "arguments too long");
559
560         cp = buf + ln;
561
562         while (*++argp != NULL) {
563                 ln = strlen(*argp);
564                 /* +1 for leading space */
565                 if (ln + trailln + 1 > bufsz - (cp-buf))
566                         adios(NULL, "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 = mhbasename(*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 = fork()) {
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++] = mhbasename(*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 = mhbasename(*ed)) && strcmp(cp, "vi") == 0 &&
738                                         (status & 0x00ff) == 0)
739                                 status = 0;
740                         else {
741 #endif
742                         if (((status & 0xff00) != 0xff00)
743                                 && (!reedit || (status & 0x00ff))) {
744                                 if (!use && (status & 0xff00) && (rename(file, cp = m_backup (file)) != NOTOK)) {
745                                         advise(NULL, "problems with edit--draft left in %s", cp);
746                                 } else {
747                                         advise(NULL, "problems with edit--%s preserved", file);
748                                 }
749                         }
750                         status = -2;  /* maybe "reedit ? -2 : -1"? */
751                         break;
752 #ifdef ATTVIBUG
753                         }
754 #endif
755                 }
756
757                 reedit++;
758 #ifdef HAVE_LSTAT
759                 if (altmsg && mp && !is_readonly(mp) && (slinked ?
760                                 lstat (linkpath, &st) != NOTOK &&
761                                 S_ISREG(st.st_mode) &&
762                                 copyf(linkpath, altpath) == NOTOK :
763                                 stat(linkpath, &st) != NOTOK &&
764                                 st.st_nlink == 1 &&
765                                 (unlink(altpath) == NOTOK ||
766                                 link(linkpath, altpath) == NOTOK)))
767                         advise(linkpath, "unable to update %s from", altmsg);
768 #else /* HAVE_LSTAT */
769                 if (altmsg && mp && !is_readonly(mp) &&
770                                 stat(linkpath, &st) != NOTOK &&
771                                 st.st_nlink == 1 &&
772                                 (unlink(altpath) == NOTOK ||
773                                 link(linkpath, altpath) == NOTOK))
774                         advise(linkpath, "unable to update %s from", altmsg);
775 #endif /* HAVE_LSTAT */
776         }
777
778         /* normally, we remember which editor we used */
779         if (save_editor)
780                 edsave = getcpy(*ed);
781
782         *ed = NULL;
783         if (altmsg)
784                 unlink(linkpath);
785
786         return status;
787 }
788
789
790 #ifdef HAVE_LSTAT
791 static int
792 copyf(char *ifile, char *ofile)
793 {
794         int i, in, out;
795         char buffer[BUFSIZ];
796
797         if ((in = open(ifile, O_RDONLY)) == NOTOK)
798                 return NOTOK;
799         if ((out = open(ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
800                 admonish(ofile, "unable to open and truncate");
801                 close(in);
802                 return NOTOK;
803         }
804
805         while ((i = read(in, buffer, sizeof(buffer))) > OK)
806                 if (write(out, buffer, i) != i) {
807                         advise(ofile, "may have damaged");
808                         i = NOTOK;
809                         break;
810                 }
811
812         close(in);
813         close(out);
814         return i;
815 }
816 #endif /* HAVE_LSTAT */
817
818
819 /*
820 ** SEND
821 */
822
823 static int
824 sendfile(char **arg, char *file, int pushsw)
825 {
826         pid_t child_id;
827         int i, vecp;
828         char *cp, *sp, *vec[MAXARGS];
829
830         /* Translate MIME composition file, if necessary */
831         if ((cp = context_find("automimeproc")) && (!strcmp(cp, "1")) &&
832                         !getenv("NOMHNPROC") && check_draft(file) &&
833                         (buildfile(NULL, file) == NOTOK))
834                 return 0;
835
836         /* For backwards compatibility */
837         if ((cp = context_find("automhnproc")) && !getenv("NOMHNPROC")
838                         && check_draft(file) && (i = editfile(&cp, NULL,
839                         file, NOUSE, NULL, NULL, NULL, 0)))
840                 return 0;
841
842         /*
843         ** If the sendproc is the nmh command `send', then we call
844         ** those routines directly rather than exec'ing the command.
845         */
846         if (strcmp(sp = mhbasename(sendproc), "send") == 0) {
847                 cp = invo_name;
848                 sendit(invo_name = sp, arg, file, pushsw);
849                 invo_name = cp;
850                 return 1;
851         }
852
853         context_save();  /* save the context file */
854         fflush(stdout);
855
856         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
857                 sleep(5);
858         switch (child_id) {
859         case NOTOK:
860                 advise(NULL, "unable to fork, so sending directly...");
861         case OK:
862                 vecp = 0;
863                 vec[vecp++] = invo_name;
864                 if (pushsw)
865                         vec[vecp++] = "-push";
866                 if (arg)
867                         while (*arg)
868                                 vec[vecp++] = *arg++;
869                 vec[vecp++] = file;
870                 vec[vecp] = NULL;
871
872                 execvp(sendproc, vec);
873                 fprintf(stderr, "unable to exec ");
874                 perror(sendproc);
875                 _exit(-1);
876
877         default:
878                 if (pidwait(child_id, OK) == 0)
879                         done(0);
880                 return 1;
881         }
882 }
883
884
885 /*
886 ** Translate MIME composition file (call buildmimeproc)
887 */
888
889 static int
890 buildfile(char **argp, char *file)
891 {
892         int i;
893         char **args, *ed;
894
895         ed = buildmimeproc;
896
897         /* allocate space for arguments */
898         i = 0;
899         if (argp) {
900                 while (argp[i])
901                         i++;
902         }
903         args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
904
905         /*
906         ** For backward compatibility, we need to add -build
907         ** if we are using mhn as buildmimeproc
908         */
909         i = 0;
910         if (strcmp(mhbasename(ed), "mhn") == 0)
911                 args[i++] = "-build";
912
913         /* copy any other arguments */
914         while (argp && *argp)
915                 args[i++] = *argp++;
916         args[i] = NULL;
917
918         i = editfile(&ed, args, file, NOUSE, NULL, NULL, NULL, 0);
919         free(args);
920
921         return (i ? NOTOK : OK);
922 }
923
924
925 /*
926 **  Check if draft is a mhbuild composition file
927 */
928
929 static int
930 check_draft(char *msgnam)
931 {
932         int state;
933         char buf[BUFSIZ], name[NAMESZ];
934         FILE *fp;
935
936         if ((fp = fopen(msgnam, "r")) == NULL)
937                 return 0;
938         for (state = FLD;;)
939                 switch (state = m_getfld(state, name, buf, sizeof(buf), fp)) {
940                 case FLD:
941                 case FLDPLUS:
942                 case FLDEOF:
943                         /*
944                         ** If draft already contains any of the
945                         ** Content-XXX fields, then assume it already
946                         ** been converted.
947                         */
948                         if (uprf(name, XXX_FIELD_PRF)) {
949                                 fclose(fp);
950                                 return 0;
951                         }
952                         while (state == FLDPLUS)
953                                 state = m_getfld(state, name, buf,
954                                                 sizeof(buf), fp);
955                         break;
956
957                 case BODY:
958                         do {
959                                 char *bp;
960
961                                 for (bp = buf; *bp; bp++)
962                                         if (*bp != ' ' && *bp != '\t' &&
963                                                         *bp != '\n') {
964                                                 fclose(fp);
965                                                 return 1;
966                                         }
967
968                                 state = m_getfld(state, name, buf,
969                                                 sizeof(buf), fp);
970                         } while (state == BODY);
971                         /* and fall... */
972
973                 default:
974                         fclose(fp);
975                         return 0;
976                 }
977 }
978
979
980 static struct swit  sendswitches[] = {
981 #define ALIASW  0
982         { "alias aliasfile", 0 },
983 #define DEBUGSW  1
984         { "debug", -5 },
985 #define FILTSW  2
986         { "filter filterfile", 0 },
987 #define NFILTSW  3
988         { "nofilter", 0 },
989 #define FRMTSW  4
990         { "format", 0 },
991 #define NFRMTSW  5
992         { "noformat", 0 },
993 #define FORWSW  6
994         { "forward", 0 },
995 #define NFORWSW  7
996         { "noforward", 0 },
997 #define MIMESW  8
998         { "mime", 0 },
999 #define NMIMESW  9
1000         { "nomime", 0 },
1001 #define MSGDSW  10
1002         { "msgid", 0 },
1003 #define NMSGDSW  11
1004         { "nomsgid", 0 },
1005 #define SPSHSW  12
1006         { "push", 0 },
1007 #define NSPSHSW  13
1008         { "nopush", 0 },
1009 #define UNIQSW  14
1010         { "unique", -6 },
1011 #define NUNIQSW  15
1012         { "nounique", -8 },
1013 #define VERBSW  16
1014         { "verbose", 0 },
1015 #define NVERBSW  17
1016         { "noverbose", 0 },
1017 #define WATCSW  18
1018         { "watch", 0 },
1019 #define NWATCSW  19
1020         { "nowatch", 0 },
1021 #define WIDTHSW  20
1022         { "width columns", 0 },
1023 #define SVERSIONSW  21
1024         { "version", 0 },
1025 #define SHELPSW  22
1026         { "help", 0 },
1027 #define BITSTUFFSW  23
1028         { "dashstuffing", -12 },
1029 #define NBITSTUFFSW  24
1030         { "nodashstuffing", -14 },
1031 #define MAILSW  25
1032         { "mail", -4 },
1033 #define SAMLSW  26
1034         { "saml", -4 },
1035 #define SSNDSW  27
1036         { "send", -4 },
1037 #define SOMLSW  28
1038         { "soml", -4 },
1039 #define CLIESW  29
1040         { "client host", -6 },
1041 #define SERVSW  30
1042         { "server host", 6 },
1043 #define SNOOPSW  31
1044         { "snoop", -5 },
1045 #define SNDATTACHSW  32
1046         { "attach file", 6 },
1047 #define SNDATTACHFORMAT   33
1048         { "attachformat", 7 },
1049 #define PORTSW  34
1050         { "port server-port-name/number", 4 },
1051         { NULL, 0 }
1052 };
1053
1054
1055 extern int debugsw;  /* from sendsbr.c */
1056 extern int forwsw;
1057 extern int inplace;
1058 extern int pushsw;
1059 extern int unique;
1060 extern int verbsw;
1061
1062 extern char *altmsg;  /*  .. */
1063 extern char *annotext;
1064 extern char *distfile;
1065
1066
1067 static void
1068 sendit(char *sp, char **arg, char *file, int pushed)
1069 {
1070         int vecp, n = 1;
1071         char *cp, buf[BUFSIZ], **argp;
1072         char **arguments, *vec[MAXARGS];
1073         struct stat st;
1074         char *attach = NULL;  /* attachment header field name */
1075         int attachformat = 0;  /* mhbuild format specifier for attachments */
1076
1077 #ifndef lint
1078         int distsw = 0;
1079 #endif
1080 #ifdef UCI
1081         FILE *fp;
1082 #endif
1083
1084         /*
1085         ** Make sure these are defined.  In particular, we need
1086         ** vec[1] to be NULL, in case "arg" is NULL below.  It
1087         ** doesn't matter what is the value of vec[0], but we
1088         ** set it to NULL, to help catch "off-by-one" errors.
1089         */
1090         vec[0] = NULL;
1091         vec[1] = NULL;
1092
1093         /*
1094         ** Temporarily copy arg to vec, since the brkstring() call in
1095         ** getarguments() will wipe it out before it is merged in.
1096         ** Also, we skip the first element of vec, since getarguments()
1097         ** skips it.  Then we count the number of arguments
1098         ** copied.  The value of "n" will be one greater than
1099         ** this in order to simulate the standard argc/argv.
1100         */
1101         if (arg) {
1102                 char **bp;
1103
1104                 copyip(arg, vec+1, MAXARGS-1);
1105                 bp = vec+1;
1106                 while (*bp++)
1107                         n++;
1108         }
1109
1110         /*
1111         ** Merge any arguments from command line (now in vec)
1112         ** and arguments from profile.
1113         */
1114         arguments = getarguments (sp, n, vec, 1);
1115         argp = arguments;
1116
1117         debugsw = 0;
1118         forwsw = 1;
1119         inplace = 1;
1120         unique = 0;
1121
1122         altmsg = NULL;
1123         annotext = NULL;
1124         distfile = NULL;
1125
1126         vecp = 1;  /* we'll get the zero'th element later */
1127         vec[vecp++] = "-library";
1128         vec[vecp++] = getcpy(toabsdir("+"));
1129
1130         while ((cp = *argp++)) {
1131                 if (*cp == '-') {
1132                         switch (smatch(++cp, sendswitches)) {
1133                         case AMBIGSW:
1134                                 ambigsw(cp, sendswitches);
1135                                 return;
1136                         case UNKWNSW:
1137                                 advise(NULL, "-%s unknown\n", cp);
1138                                 return;
1139
1140                         case SHELPSW:
1141                                 snprintf(buf, sizeof(buf),
1142                                                 "%s [switches]", sp);
1143                                 print_help(buf, sendswitches, 1);
1144                                 return;
1145                         case SVERSIONSW:
1146                                 print_version(invo_name);
1147                                 return;
1148
1149                         case SPSHSW:
1150                                 pushed++;
1151                                 continue;
1152                         case NSPSHSW:
1153                                 pushed = 0;
1154                                 continue;
1155
1156                         case UNIQSW:
1157                                 unique++;
1158                                 continue;
1159                         case NUNIQSW:
1160                                 unique = 0;
1161                                 continue;
1162                         case FORWSW:
1163                                 forwsw++;
1164                                 continue;
1165                         case NFORWSW:
1166                                 forwsw = 0;
1167                                 continue;
1168
1169                         case VERBSW:
1170                                 verbsw++;
1171                                 vec[vecp++] = --cp;
1172                                 continue;
1173                         case NVERBSW:
1174                                 verbsw = 0;
1175                                 vec[vecp++] = --cp;
1176                                 continue;
1177
1178                         case DEBUGSW:
1179                                 debugsw++;  /* fall */
1180                         case NFILTSW:
1181                         case FRMTSW:
1182                         case NFRMTSW:
1183                         case BITSTUFFSW:
1184                         case NBITSTUFFSW:
1185                         case MIMESW:
1186                         case NMIMESW:
1187                         case MSGDSW:
1188                         case NMSGDSW:
1189                         case WATCSW:
1190                         case NWATCSW:
1191                         case MAILSW:
1192                         case SAMLSW:
1193                         case SSNDSW:
1194                         case SOMLSW:
1195                         case SNOOPSW:
1196                                 vec[vecp++] = --cp;
1197                                 continue;
1198
1199                         case ALIASW:
1200                         case FILTSW:
1201                         case WIDTHSW:
1202                         case CLIESW:
1203                         case SERVSW:
1204                         case PORTSW:
1205                                 vec[vecp++] = --cp;
1206                                 if (!(cp = *argp++) || *cp == '-') {
1207                                         advise(NULL, "missing argument to %s",
1208                                                         argp[-2]);
1209                                         return;
1210                                 }
1211                                 vec[vecp++] = cp;
1212                                 continue;
1213
1214                         case SNDATTACHSW:
1215                                 if (!(attach = *argp++) || *attach == '-') {
1216                                         advise(NULL, "missing argument to %s",
1217                                                         argp[-2]);
1218                                         return;
1219                                 }
1220                                 continue;
1221
1222                         case SNDATTACHFORMAT:
1223                                 if (! *argp || **argp == '-')
1224                                         adios(NULL, "missing argument to %s",
1225                                                         argp[-1]);
1226                                 else {
1227                                         attachformat = atoi(*argp);
1228                                         if (attachformat < 0 || attachformat > ATTACHFORMATS - 1) {
1229                                                 advise(NULL, "unsupported attachformat %d", attachformat);
1230                                                 continue;
1231                                         }
1232                                 }
1233                                 ++argp;
1234                                 continue;
1235                         }
1236                 }
1237                 advise(NULL, "usage: %s [switches]", sp);
1238                 return;
1239         }
1240
1241         /* allow Aliasfile: profile entry */
1242         if ((cp = context_find("Aliasfile"))) {
1243                 char **ap, *dp;
1244
1245                 dp = getcpy(cp);
1246                 for (ap = brkstring(dp, " ", "\n"); ap && *ap; ap++) {
1247                         vec[vecp++] = "-alias";
1248                         vec[vecp++] = *ap;
1249                 }
1250         }
1251
1252         if ((cp = getenv("SIGNATURE")) == NULL || *cp == 0)
1253                 if ((cp = context_find("signature")) && *cp)
1254                         m_putenv("SIGNATURE", cp);
1255 #ifdef UCI
1256                 else {
1257                         snprintf(buf, sizeof(buf), "%s/.signature", mypath);
1258                         if ((fp = fopen(buf, "r")) != NULL &&
1259                                         fgets(buf, sizeof(buf), fp) != NULL) {
1260                                 fclose(fp);
1261                                 if (cp = strchr(buf, '\n'))
1262                                         *cp = 0;
1263                                 m_putenv("SIGNATURE", buf);
1264                         }
1265                 }
1266 #endif /* UCI */
1267
1268         if ((annotext = getenv("mhannotate")) == NULL || *annotext == 0)
1269                 annotext = NULL;
1270         if ((altmsg = getenv("mhaltmsg")) == NULL || *altmsg == 0)
1271                 altmsg = NULL;
1272         if (annotext && ((cp = getenv("mhinplace")) != NULL && *cp != 0))
1273                 inplace = atoi(cp);
1274
1275         if ((cp = getenv("mhdist")) && *cp
1276 #ifndef lint
1277                         && (distsw = atoi (cp))
1278 #endif /* not lint */
1279                         && altmsg) {
1280                 vec[vecp++] = "-dist";
1281                 distfile = getcpy(m_mktemp2(altmsg, invo_name, NULL, NULL));
1282                 if (link(altmsg, distfile) == NOTOK)
1283                         adios(distfile, "unable to link %s to", altmsg);
1284         } else {
1285                 distfile = NULL;
1286         }
1287
1288         if (altmsg == NULL || stat(altmsg, &st) == NOTOK) {
1289                 st.st_mtime = 0;
1290                 st.st_dev = 0;
1291                 st.st_ino = 0;
1292         }
1293         if ((pushsw = pushed))
1294                 push();
1295
1296         vec[0] = mhbasename(postproc);
1297         closefds(3);
1298
1299         if (sendsbr(vec, vecp, file, &st, 1, attach, attachformat) == OK)
1300                 done(0);
1301 }
1302
1303
1304 /*
1305 ** Remove the draft file
1306 */
1307
1308 static int
1309 removefile(char *drft)
1310 {
1311         if (unlink(drft) == NOTOK)
1312                 adios(drft, "unable to unlink");
1313
1314         return OK;
1315 }