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