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