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