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