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