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