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