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