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