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