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