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