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