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