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