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