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