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