]> diplodocus.org Git - nmh/blob - uip/whatnowsbr.c
Added context_find_prefix().
[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 #define WHATNOW_SWITCHES \
48 X("draftfolder +folder", 0, DFOLDSW) \
49 X("draftmessage msg", 0, DMSGSW) \
50 X("nodraftfolder", 0, NDFLDSW) \
51 X("editor editor", 0, EDITRSW) \
52 X("noedit", 0, NEDITSW) \
53 X("prompt string", 4, PRMPTSW) \
54 X("version", 0, VERSIONSW) \
55 X("help", 0, HELPSW) \
56 X("attach header-field-name", -6, ATTACHSW) \
57 X("noattach", -8, NOATTACHSW) \
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)) == (char *)0) {
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 case ATTACHSW:
198 advise(NULL, "The -attach switch is deprecated");
199 continue;
200
201 case NOATTACHSW:
202 advise(NULL, "The -noattach switch is deprecated");
203 continue;
204 }
205 }
206 if (drft)
207 adios (NULL, "only one draft at a time!");
208 else
209 drft = cp;
210 }
211
212 if ((drft == NULL && (drft = getenv ("mhdraft")) == NULL) || *drft == 0)
213 drft = getcpy (m_draft (dfolder, dmsg, 1, &isdf));
214
215 msgnam = (cp = getenv ("mhaltmsg")) && *cp ? getcpy (cp) : NULL;
216
217 if ((cp = getenv ("mhatfile")) && *cp)
218 atfile = atoi(cp);
219
220 if ((cp = getenv ("mhuse")) && *cp)
221 use = atoi (cp);
222
223 if (ed == NULL && ((ed = getenv ("mheditor")) == NULL || *ed == 0)) {
224 ed = NULL;
225 nedit++;
226 }
227
228 /* start editing the draft, unless -noedit was given */
229 if (!nedit && editfile (&ed, NULL, drft, use, NULL, msgnam,
230 NULL, 1, atfile) < 0)
231 done (1);
232
233 snprintf (prompt, sizeof(prompt), myprompt, invo_name);
234 for (;;) {
235 #ifdef READLINE_SUPPORT
236 if (!(argp = read_switch_multiword_via_readline (prompt, aleqs))) {
237 #else /* ! READLINE_SUPPORT */
238 if (!(argp = read_switch_multiword (prompt, aleqs))) {
239 #endif /* READLINE_SUPPORT */
240 (void) m_unlink (LINK);
241 done (1);
242 }
243 switch (smatch (*argp, aleqs)) {
244 case DISPSW:
245 /* display the message being replied to, or distributed */
246 if (msgnam)
247 showfile (++argp, msgnam);
248 else
249 advise (NULL, "no alternate message to display");
250 break;
251
252 case BUILDMIMESW:
253 /* Translate MIME composition file */
254 buildfile (++argp, drft);
255 break;
256
257 case EDITSW:
258 /* Call an editor on the draft file */
259 if (*++argp)
260 ed = *argp++;
261 if (editfile (&ed, argp, drft, NOUSE, NULL, msgnam,
262 NULL, 1, atfile) == NOTOK)
263 done (1);
264 break;
265
266 case LISTSW:
267 /* display the draft file */
268 showfile (++argp, drft);
269 break;
270
271 case WHOMSW:
272 /* Check to whom the draft would be sent */
273 whomfile (++argp, drft);
274 break;
275
276 case QUITSW:
277 /* Quit, and possibly delete the draft */
278 if (*++argp && (*argp[0] == 'd' ||
279 ((*argp)[0] == '-' && (*argp)[1] == 'd'))) {
280 removefile (drft);
281 } else {
282 if (stat (drft, &st) != NOTOK)
283 advise (NULL, "draft left on %s", drft);
284 }
285 done (1);
286
287 case DELETESW:
288 /* Delete draft and exit */
289 removefile (drft);
290 done (1);
291
292 case PUSHSW:
293 /* Send draft in background */
294 if (sendfile (++argp, drft, 1))
295 done (1);
296 break;
297
298 case SENDSW:
299 /* Send draft */
300 sendfile (++argp, drft, 0);
301 break;
302
303 case REFILEOPT:
304 /* Refile the draft */
305 if (refile (++argp, drft) == 0)
306 done (0);
307 break;
308
309 case CDCMDSW:
310 /* Change the working directory for attachments
311 *
312 * Run the directory through the user's shell so that
313 * we can take advantage of any syntax that the user
314 * is accustomed to. Read back the absolute path.
315 */
316
317 if (*(argp+1) == (char *)0) {
318 (void)sprintf(buf, "$SHELL -c \"cd&&pwd\"");
319 }
320 else {
321 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
322 }
323 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
324 if (fgets(cwd, sizeof (cwd), f) == NULL) {
325 advise (buf, "fgets");
326 }
327
328 if (strchr(cwd, '\n') != (char *)0)
329 *strchr(cwd, '\n') = '\0';
330
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 printf("%s\n", 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 = (char *)0;
366 n = 0;
367
368 while (*++argp != (char *)0) {
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 advise((char *)0, "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 int verbose = 0;
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 = 1;
409 } else if (*ap[0] != '-') {
410 break;
411 }
412 }
413
414 if (*(argp+1) == (char *)0) {
415 advise(NULL, "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")) != (FILE *)0) {
434 while (fgets(shell, sizeof (shell), f) != (char *)0) {
435 char *ctype;
436
437 *(strchr(shell, '\n')) = '\0';
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 != (char *)0; 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 != (char *)0; arguments++) {
491 if (strcmp(*arguments, "-n") == 0)
492 continue;
493
494 if (**arguments != '\0') {
495 n = atoi(*arguments);
496 annotate(drft, ATTACH_FIELD, (char *)0, 1, 0, n, 1);
497
498 for (argp = arguments + 1; *argp != (char *)0; 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")) != (FILE *)0) {
521 while (fgets(shell, sizeof (shell), f) != (char *)0) {
522 *(strchr(shell, '\n')) = '\0';
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 advise (NULL, "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 adios((char *)0, "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 adios((char *)0, "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 int reedit = 0; /* 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 int slinked = 0;
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 = 1;
697 } else {
698 slinked = 0;
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 m_putenv ("mhfolder", mp->foldpath);
721 m_putenv ("editalt", altpath);
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 advise (NULL, "problems with edit--draft left in %s", cp);
744 } else {
745 advise (NULL, "problems with edit--%s preserved", file);
746 }
747 }
748 status = -2; /* maybe "reedit ? -2 : -1"? */
749 break;
750 }
751
752 reedit++;
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 i, 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 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
832 sleep (5);
833 switch (child_id) {
834 case NOTOK:
835 advise (NULL, "unable to fork, so sending directly...");
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 = (char **) 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", -6, SDRFSW) \
942 X("draftmessage msg", -6, SDRMSW) \
943 X("nodraftfolder", -3, SNDRFSW) \
944 X("sasl", SASLminc(-4), SASLSW) \
945 X("nosasl", SASLminc(-6), NOSASLSW) \
946 X("saslmaxssf", SASLminc(-10), SASLMXSSFSW) \
947 X("saslmech", SASLminc(-5), SASLMECHSW) \
948 X("user", SASLminc(-4), USERSW) \
949 X("attach fieldname", 6, SNDATTACHSW) \
950 X("noattach", 0, SNDNOATTACHSW) \
951 X("attachformat", 7, SNDATTACHFORMAT) \
952 X("port server-port-name/number", 4, PORTSW) \
953 X("tls", TLSminc(-3), TLSSW) \
954 X("initialtls", TLSminc(-10), INITTLSSW) \
955 X("notls", TLSminc(-5), NTLSSW) \
956 X("sendmail program", 0, MTSSM) \
957 X("mts smtp|sendmail/smtp|sendmail/pipe", 2, MTSSW) \
958 X("messageid localname|random", 2, MESSAGEIDSW) \
959
960 #define X(sw, minchars, id) id,
961 DEFINE_SWITCH_ENUM(SEND);
962 #undef X
963
964 #define X(sw, minchars, id) { sw, minchars, id },
965 DEFINE_SWITCH_ARRAY(SEND, sendswitches);
966 #undef X
967
968
969 extern int debugsw; /* from sendsbr.c */
970 extern int forwsw;
971 extern int inplace;
972 extern int pushsw;
973 extern int splitsw;
974 extern int unique;
975 extern int verbsw;
976
977 extern char *altmsg; /* .. */
978 extern char *annotext;
979 extern char *distfile;
980
981
982 static void
983 sendit (char *sp, char **arg, char *file, int pushed)
984 {
985 int vecp, n = 1;
986 char *cp, buf[BUFSIZ], **argp, *program;
987 char **arguments, *savearg[MAXARGS], **vec;
988 struct stat st;
989
990 #ifndef lint
991 int distsw = 0;
992 #endif
993
994 /*
995 * Make sure these are defined. In particular, we need
996 * savearg[1] to be NULL, in case "arg" is NULL below. It
997 * doesn't matter what is the value of savearg[0], but we
998 * set it to NULL, to help catch "off-by-one" errors.
999 */
1000 savearg[0] = NULL;
1001 savearg[1] = NULL;
1002
1003 /*
1004 * Temporarily copy arg to savearg, since the brkstring() call in
1005 * getarguments() will wipe it out before it is merged in.
1006 * Also, we skip the first element of savearg, since getarguments()
1007 * skips it. Then we count the number of arguments
1008 * copied. The value of "n" will be one greater than
1009 * this in order to simulate the standard argc/argv.
1010 */
1011 if (arg) {
1012 char **bp;
1013
1014 copyip (arg, savearg+1, MAXARGS-1);
1015 bp = savearg+1;
1016 while (*bp++)
1017 n++;
1018 }
1019
1020 /*
1021 * Merge any arguments from command line (now in savearg)
1022 * and arguments from profile.
1023 */
1024 arguments = getarguments (sp, n, savearg, 1);
1025 argp = arguments;
1026
1027 debugsw = 0;
1028 forwsw = 1;
1029 inplace = 1;
1030 unique = 0;
1031
1032 altmsg = NULL;
1033 annotext = NULL;
1034 distfile = NULL;
1035
1036 /*
1037 * Get our initial arguments for postproc now
1038 */
1039
1040 vec = argsplit(postproc, &program, &vecp);
1041
1042 vec[vecp++] = "-library";
1043 vec[vecp++] = getcpy (m_maildir (""));
1044
1045 if ((cp = context_find ("fileproc"))) {
1046 vec[vecp++] = "-fileproc";
1047 vec[vecp++] = cp;
1048 }
1049
1050 if ((cp = context_find ("mhlproc"))) {
1051 vec[vecp++] = "-mhlproc";
1052 vec[vecp++] = cp;
1053 }
1054
1055 if ((cp = context_find ("credentials"))) {
1056 /* post doesn't read context so need to pass credentials. */
1057 vec[vecp++] = "-credentials";
1058 vec[vecp++] = cp;
1059 }
1060
1061 while ((cp = *argp++)) {
1062 if (*cp == '-') {
1063 switch (smatch (++cp, sendswitches)) {
1064 case AMBIGSW:
1065 ambigsw (cp, sendswitches);
1066 return;
1067 case UNKWNSW:
1068 advise (NULL, "-%s unknown\n", cp);
1069 return;
1070
1071 case SHELPSW:
1072 snprintf (buf, sizeof(buf), "%s [switches]", sp);
1073 print_help (buf, sendswitches, 1);
1074 return;
1075 case SVERSIONSW:
1076 print_version (invo_name);
1077 return;
1078
1079 case SPSHSW:
1080 pushed++;
1081 continue;
1082 case NSPSHSW:
1083 pushed = 0;
1084 continue;
1085
1086 case SPLITSW:
1087 if (!(cp = *argp++) || sscanf (cp, "%d", &splitsw) != 1) {
1088 advise (NULL, "missing argument to %s", argp[-2]);
1089 return;
1090 }
1091 continue;
1092
1093 case UNIQSW:
1094 unique++;
1095 continue;
1096 case NUNIQSW:
1097 unique = 0;
1098 continue;
1099 case FORWSW:
1100 forwsw++;
1101 continue;
1102 case NFORWSW:
1103 forwsw = 0;
1104 continue;
1105
1106 case VERBSW:
1107 verbsw++;
1108 vec[vecp++] = --cp;
1109 continue;
1110 case NVERBSW:
1111 verbsw = 0;
1112 vec[vecp++] = --cp;
1113 continue;
1114
1115 case DEBUGSW:
1116 debugsw++; /* fall */
1117 case NFILTSW:
1118 case FRMTSW:
1119 case NFRMTSW:
1120 case BITSTUFFSW:
1121 case NBITSTUFFSW:
1122 case MIMESW:
1123 case NMIMESW:
1124 case MSGDSW:
1125 case NMSGDSW:
1126 case WATCSW:
1127 case NWATCSW:
1128 case SNOOPSW:
1129 case SASLSW:
1130 case NOSASLSW:
1131 case TLSSW:
1132 case INITTLSSW:
1133 case NTLSSW:
1134 vec[vecp++] = --cp;
1135 continue;
1136
1137 case ALIASW:
1138 case FILTSW:
1139 case WIDTHSW:
1140 case CLIESW:
1141 case SERVSW:
1142 case SASLMXSSFSW:
1143 case SASLMECHSW:
1144 case USERSW:
1145 case PORTSW:
1146 case MTSSM:
1147 case MTSSW:
1148 case MESSAGEIDSW:
1149 vec[vecp++] = --cp;
1150 if (!(cp = *argp++) || *cp == '-') {
1151 advise (NULL, "missing argument to %s", argp[-2]);
1152 return;
1153 }
1154 vec[vecp++] = cp;
1155 continue;
1156
1157 case SDRFSW:
1158 case SDRMSW:
1159 if (!(cp = *argp++) || *cp == '-') {
1160 advise (NULL, "missing argument to %s", argp[-2]);
1161 return;
1162 }
1163 case SNDRFSW:
1164 continue;
1165
1166 case SNDATTACHSW:
1167 advise(NULL, "The -attach switch is deprecated");
1168 continue;
1169 case SNDNOATTACHSW:
1170 advise(NULL, "The -noattach switch is deprecated");
1171 continue;
1172
1173 case SNDATTACHFORMAT:
1174 advise(NULL, "The -attachformat switch is deprecated");
1175 continue;
1176 }
1177 }
1178 advise (NULL, "usage: %s [switches]", sp);
1179 return;
1180 }
1181
1182 /* allow Aliasfile: profile entry */
1183 if ((cp = context_find ("Aliasfile"))) {
1184 char **ap, *dp;
1185
1186 dp = getcpy (cp);
1187 for (ap = brkstring (dp, " ", "\n"); ap && *ap; ap++) {
1188 vec[vecp++] = "-alias";
1189 vec[vecp++] = *ap;
1190 }
1191 }
1192
1193 if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
1194 if ((cp = context_find ("signature")) && *cp)
1195 m_putenv ("SIGNATURE", cp);
1196
1197 if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
1198 annotext = NULL;
1199 if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
1200 altmsg = NULL;
1201 if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
1202 inplace = atoi (cp);
1203
1204 if ((cp = getenv ("mhdist"))
1205 && *cp
1206 #ifndef lint
1207 && (distsw = atoi (cp))
1208 #endif /* not lint */
1209 && altmsg) {
1210 vec[vecp++] = "-dist";
1211 if ((cp = m_mktemp2(altmsg, invo_name, NULL, NULL)) == NULL) {
1212 adios(NULL, "unable to create temporary file in %s",
1213 get_temp_dir());
1214 }
1215 distfile = getcpy (cp);
1216 (void) m_unlink(distfile);
1217 if (link (altmsg, distfile) == NOTOK)
1218 adios (distfile, "unable to link %s to", altmsg);
1219 } else {
1220 distfile = NULL;
1221 }
1222
1223 if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
1224 st.st_mtime = 0;
1225 st.st_dev = 0;
1226 st.st_ino = 0;
1227 }
1228 if ((pushsw = pushed))
1229 push ();
1230
1231 closefds (3);
1232
1233 if (sendsbr (vec, vecp, program, file, &st, 1) == OK)
1234 done (0);
1235 }
1236
1237 /*
1238 * WHOM
1239 */
1240
1241 static int
1242 whomfile (char **arg, char *file)
1243 {
1244 pid_t pid;
1245 int vecp;
1246 char **vec, *program;
1247
1248 context_save (); /* save the context file */
1249 fflush (stdout);
1250
1251 switch (pid = fork()) {
1252 case NOTOK:
1253 advise ("fork", "unable to");
1254 return 1;
1255
1256 case OK:
1257 vec = argsplit(whomproc, &program, &vecp);
1258 if (arg)
1259 while (*arg)
1260 vec[vecp++] = *arg++;
1261 vec[vecp++] = file;
1262 vec[vecp] = NULL;
1263
1264 execvp (program, vec);
1265 fprintf (stderr, "unable to exec ");
1266 perror (whomproc);
1267 _exit (-1); /* NOTREACHED */
1268
1269 default:
1270 return (pidwait (pid, NOTOK) & 0377 ? 1 : 0);
1271 }
1272 }
1273
1274
1275 /*
1276 * Remove the draft file
1277 */
1278
1279 static int
1280 removefile (char *drft)
1281 {
1282 if (m_unlink (drft) == NOTOK)
1283 adios (drft, "unable to unlink");
1284
1285 return OK;
1286 }
1287
1288
1289 /*
1290 * Return 1 if we already have a MIME-Version header, 0 otherwise.
1291 */
1292
1293 static int
1294 checkmimeheader (char *drft)
1295 {
1296 FILE *f;
1297 m_getfld_state_t gstate = 0;
1298 char buf[BUFSIZ], name[NAMESZ];
1299 int state, retval = 0;
1300
1301 if ((f = fopen(drft, "r")) == NULL) {
1302 admonish(drft, "unable to read draft");
1303 return (0);
1304 }
1305
1306 for (;;) {
1307 int bufsz = sizeof(buf);
1308 switch (state = m_getfld(&gstate, name, buf, &bufsz, f)) {
1309 case FLD:
1310 case FLDPLUS:
1311 if (strcasecmp(name, VRSN_FIELD) == 0) {
1312 advise(NULL, "Cannot use attach commands with already-"
1313 "formatted MIME message \"%s\"", drft);
1314 retval = 1;
1315 break;
1316 }
1317 continue;
1318 default:
1319 break;
1320 }
1321 break;
1322 }
1323
1324 m_getfld_state_destroy(&gstate);
1325 fclose(f);
1326
1327 return retval;
1328 }