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