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