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