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