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