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