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