redesign version string
[mmh] / uip / send.c
1 /*
2 ** send.c -- send a composed message
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <fcntl.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <h/signals.h>
14 #include <h/mime.h>
15 #include <h/tws.h>
16 #include <h/utils.h>
17 #include <sysexits.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20 #include <ctype.h>
21 #include <sys/stat.h>
22 #include <locale.h>
23
24 #ifdef HAVE_SYS_TIME_H
25 # include <sys/time.h>
26 #endif
27 #include <time.h>
28
29 #ifdef HAVE_SYS_PARAM_H
30 # include <sys/param.h>
31 #endif
32
33 int debugsw = 0;  /* global */
34 char *altmsg = NULL;
35 char *annotext = NULL;
36 char *distfile = NULL;
37
38 /* name of temp file for body content */
39 static char body_file_name[MAXPATHLEN + 1];
40 /* name of mhbuild composition temporary file */
41 static char composition_file_name[MAXPATHLEN + 1]; 
42 static int field_size;  /* size of header field buffer */
43 static char *field;  /* header field buffer */
44 static FILE *draft_file;  /* draft file pointer */
45 static FILE *body_file;  /* body file pointer */
46 static FILE *composition_file;  /* composition file pointer */
47
48 /*
49 ** static prototypes
50 */
51 static int sendsbr(char **, int, char *, struct stat *);
52 static void anno(struct stat *);
53 static int sendaux(char **, int, char *, struct stat *);
54 static int attach(char *);
55 static int signandenc(char *);
56 static void clean_up_temporary_files(void);
57 static int get_line(void);
58 static void make_mime_composition_file_entry(char *);
59 static char* strexit(int status);
60
61
62 static struct swit switches[] = {
63 #define DEBUGSW  0
64         { "debug", -5 },
65 #define VERBSW  1
66         { "verbose", 0 },
67 #define NVERBSW  2
68         { "noverbose", 2 },
69 #define VERSIONSW  3
70         { "Version", 0 },
71 #define HELPSW  4
72         { "help", 0 },
73         { NULL, 0 }
74 };
75
76 char *version=VERSION;
77
78 int
79 main(int argc, char **argv)
80 {
81         int nmsgs = 0, nfiles = 0, distsw = 0, vecp = 1;
82         int msgnum, status;
83         int in, out;
84         int n;
85         char *cp, *maildir = NULL, *folder = NULL;
86         char buf[BUFSIZ], **argp, **arguments;
87         char *msgs[MAXARGS], *vec[MAXARGS];
88         char *files[MAXARGS];
89         struct msgs *mp;
90         struct stat st;
91         struct stat st2;
92
93         setlocale(LC_ALL, "");
94         invo_name = mhbasename(argv[0]);
95
96         /* read user profile/context */
97         context_read();
98
99         arguments = getarguments(invo_name, argc, argv, 1);
100         argp = arguments;
101
102         while ((cp = *argp++)) {
103                 if (*cp == '-') {
104                         switch (smatch(++cp, switches)) {
105                         case AMBIGSW:
106                                 ambigsw(cp, switches);
107                                 exit(EX_USAGE);
108                         case UNKWNSW:
109                                 adios(EX_USAGE, NULL, "-%s unknown\n", cp);
110
111                         case HELPSW:
112                                 snprintf(buf, sizeof(buf),
113                                                 "%s [file] [switches]",
114                                                 invo_name);
115                                 print_help(buf, switches, 1);
116                                 exit(argc == 2 ? EX_OK : EX_USAGE);
117                         case VERSIONSW:
118                                 print_version(invo_name);
119                                 exit(argc == 2 ? EX_OK : EX_USAGE);
120
121                         case DEBUGSW:
122                                 debugsw++;
123                                 /* fall */
124                         case VERBSW:
125                         case NVERBSW:
126                                 vec[vecp++] = --cp;
127                                 continue;
128                         }
129                 } else if (*cp == '+' || *cp == '@') {
130                         if (folder) {
131                                 adios(EX_USAGE, NULL, "only one folder at a time!");
132                         } else {
133                                 folder = mh_xstrdup(expandfol(cp));
134                         }
135                 } else {
136                         if (*cp == '/') {
137                                 files[nfiles++] = cp;
138                         } else {
139                                 msgs[nmsgs++] = cp;
140                         }
141                 }
142         }
143
144         if (!nmsgs && !nfiles) {
145                 msgs[nmsgs++] = seq_cur;
146         }
147
148         if (nmsgs) {
149                 folder = folder ? folder : draftfolder;
150                 maildir = toabsdir(folder);
151                 if (chdir(maildir) == NOTOK) {
152                         adios(EX_OSERR, maildir, "unable to change directory to");
153                 }
154                 if (!(mp = folder_read(folder))) {
155                         adios(EX_IOERR, NULL, "unable to read folder %s",
156                                         folder);
157                 }
158                 if (mp->nummsg == 0) {
159                         adios(EX_DATAERR, NULL, "no messages in folder %s",
160                                         folder);
161                 }
162                 /* parse all the msgranges/sequences and set SELECTED */
163                 for (msgnum = 0; msgnum < nmsgs; msgnum++) {
164                         if (!m_convert(mp, msgs[msgnum])) {
165                                 exit(EX_USAGE);
166                         }
167                 }
168                 seq_setprev(mp);
169
170                 for (nmsgs = 0, msgnum = mp->lowsel;
171                                 msgnum <= mp->hghsel; msgnum++) {
172                         if (is_selected(mp, msgnum)) {
173                                 files[nfiles++] = mh_xstrdup(m_name(msgnum));
174                                 unset_exists(mp, msgnum);
175                         }
176                 }
177
178                 mp->msgflags |= SEQMOD;
179                 seq_save(mp);
180         }
181
182         if (!(cp = getenv("SIGNATURE")) || !*cp) {
183                 if ((cp = context_find("signature")) && *cp) {
184                         m_putenv("SIGNATURE", cp);
185                 }
186         }
187
188         for (n = 0; n < nfiles; n++) {
189                 if (stat(files[n], &st) == NOTOK) {
190                         adios(EX_IOERR, files[n], "unable to stat draft file");
191                 }
192         }
193
194         if (!(annotext = getenv("mhannotate")) || !*annotext) {
195                 annotext = NULL;
196         }
197         if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
198                 altmsg = NULL;  /* used by dist interface - see below */
199         }
200
201         if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
202                 vec[vecp++] = "-dist";
203                 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
204                         adios(EX_IOERR, altmsg, "unable to open for reading");
205                 }
206                 fstat(in, &st2);
207                 distfile = mh_xstrdup(m_mktemp2(NULL, invo_name, NULL, NULL));
208                 if ((out = creat(distfile, (int)st2.st_mode & 0777))==NOTOK) {
209                         adios(EX_IOERR, distfile, "unable to open for writing");
210                 }
211                 cpydata(in, out, altmsg, distfile);
212                 close(in);
213                 close(out);
214         } else {
215                 distfile = NULL;
216         }
217
218         if (!altmsg || stat(altmsg, &st) == NOTOK) {
219                 st.st_mtime = 0;
220                 st.st_dev = 0;
221                 st.st_ino = 0;
222         }
223         status = 0;
224         vec[0] = "spost";
225         for (n=3; n<OPEN_MAX; n++) {
226                 close(n);
227         }
228
229         for (n = 0; n < nfiles; n++) {
230                 switch (sendsbr(vec, vecp, files[n], &st)) {
231                 case DONE:
232                         exit(++status);
233                 case NOTOK:
234                         status++;  /* fall */
235                 case OK:
236                         break;
237                 }
238         }
239
240         context_save();
241         return status;
242 }
243
244
245 /*
246 ** message sending back-end
247 */
248 static int
249 sendsbr(char **vec, int vecp, char *drft, struct stat *st)
250 {
251         int status, dupfd;
252         char *original_draft;
253
254         /*
255         ** Save the original name of the draft file.  The name of the
256         ** draft file is changed to a temporary file containing the built
257         ** MIME message if there are attachments.  We need the original
258         ** name so that it can be renamed after the message is sent.
259         */
260         original_draft = drft;
261
262         /*
263         ** Convert the draft to a MIME message.
264         ** Use the mhbuild composition file for the draft if there was
265         ** a successful conversion because that now contains the MIME
266         ** message.  A nice side effect of this is that it leaves the
267         ** original draft file untouched so that it can be retrieved
268         ** and modified if desired.
269         */
270         switch (attach(drft)) {
271         case OK:
272                 /* successfully MIMEified: use generate draft */
273                 drft = composition_file_name;
274                 break;
275
276         case NOTOK:
277                 return (NOTOK);
278
279         case DONE:
280                 /* already in MIME format: keep original draft */
281                 break;
282         }
283
284         /*
285         ** Sign and encrypt the message as needed.
286         ** Use the mhbuild composition file for the draft if there was
287         ** a successful conversion because that now contains the MIME
288         ** message.  A nice side effect of this is that it leaves the
289         ** original draft file untouched so that it can be retrieved
290         ** and modified if desired.
291         */
292         switch (signandenc(drft)) {
293         case OK:
294                 drft = composition_file_name;
295                 break;
296
297         case NOTOK:
298                 return (NOTOK);
299
300         case DONE:
301                 break;
302         }
303
304         if ((status = sendaux(vec, vecp, drft, st)) == OK) {
305                 /* move original draft to +trash folder */
306                 /* temporary close stdin, for refile not to ask */
307                 dupfd = dup(0);
308                 close(0);
309                 if (execprogl("refile", "refile", "-file",
310                                 original_draft, "+trash",
311                                 (char *)NULL) != 0) {
312                         advise(NULL, "unable to trash the draft");
313                 }
314                 dup2(dupfd, 0);
315                 close(dupfd);
316         } else {
317                 status = DONE;
318         }
319
320         if (distfile) {
321                 unlink(distfile);
322         }
323
324         /* Get rid of temporary files that we created for attachments. */
325         if (drft == composition_file_name) {
326                 clean_up_temporary_files();
327         }
328
329         return status;
330 }
331
332 static int
333 attach(char *draft_file_name)
334 {
335         char buf[MAXPATHLEN + 6];
336         int c;
337         int length = strlen(attach_hdr);
338         char *p;
339
340         if(distfile) {
341                 return DONE;
342         }
343
344         if (!(draft_file = fopen(draft_file_name, "r"))) {
345                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
346         }
347
348         /* We'll grow the buffer as needed. */
349         field = mh_xcalloc(field_size = 256, sizeof(char));
350
351         /*
352         ** MIMEify
353         */
354
355         /* Make names for the temporary files.  */
356         strncpy(body_file_name,
357                         m_mktemp(toabsdir(invo_name), NULL, NULL),
358                         sizeof (body_file_name));
359         strncpy(composition_file_name,
360                         m_mktemp(toabsdir(invo_name), NULL, NULL),
361                         sizeof (composition_file_name));
362
363         body_file = fopen(body_file_name, "w");
364         composition_file = fopen(composition_file_name, "w");
365
366         if (!body_file || !composition_file) {
367                 clean_up_temporary_files();
368                 adios(EX_IOERR, NULL, "unable to open all of the temporary files.");
369         }
370
371         /* Copy non-attachment header fields to the temp composition file. */
372         rewind(draft_file);
373         while (get_line() != EOF && *field && *field != '-') {
374                 if (strncasecmp(field, VRSN_FIELD, strlen(VRSN_FIELD))==0 &&
375                                 field[strlen(VRSN_FIELD)] == ':') {
376                         /*
377                         ** The draft is already in MIME format, thus
378                         ** back out and use the original draft file.
379                         */
380                         clean_up_temporary_files();
381                         return DONE;
382                 }
383
384                 if (strncasecmp(field, attach_hdr, length) != 0 ||
385                                 field[length] != ':') {
386                         fprintf(composition_file, "%s\n", field);
387                 }
388         }
389         fputs("--------\n", composition_file);
390
391         /* Copy the message body to the temporary file. */
392         while ((c = getc(draft_file)) != EOF) {
393                 putc(c, body_file);
394         }
395         fclose(body_file);
396
397         /* Add a mhbuild MIME composition file line for the body */
398         /* charset will be discovered/guessed by mhbuild */
399         fprintf(composition_file, "#text/plain %s\n", body_file_name);
400
401         /*
402         ** Now, go back to the beginning of the draft file and look for
403         ** header fields that specify attachments.  Add a mhbuild MIME
404         ** composition file for each.
405         */
406         rewind(draft_file);
407         while (get_line() != EOF && *field && *field != '-') {
408                 if (strncasecmp(field, attach_hdr, length) == 0 &&
409                                 field[length] == ':') {
410                         p = trim(field+length+1);
411                         if (*p == '+') {
412                                 /* forwarded message */
413                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
414                         } else {
415                                 /* regular attachment */
416                                 make_mime_composition_file_entry(p);
417                         }
418                 }
419         }
420         fclose(composition_file);
421
422         /* We're ready to roll! */
423         if (execprogl("mhbuild", "mhbuild", composition_file_name,
424                         (char *)NULL) != 0) {
425                 /* some problem */
426                 clean_up_temporary_files();
427                 return (NOTOK);
428         }
429         /* Remove the automatically created backup of mhbuild. */
430         snprintf(buf, sizeof buf, "%s.orig", composition_file_name);
431         if (unlink(buf) == -1) {
432                 advise(NULL, "unable to remove original composition file.");
433         }
434
435         return (OK);
436 }
437
438 static int
439 signandenc(char *draft_file_name)
440 {
441         char buf[BUFSIZ];
442         int dosign = 0;
443         int doenc = 0;
444         int ret;
445
446         if(distfile) {
447                 return DONE;
448         }
449
450         if (!(draft_file = fopen(draft_file_name, "r"))) {
451                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
452         }
453
454         /* We'll grow the buffer as needed. */
455         field = mh_xcalloc(field_size = 256, sizeof(char));
456
457         /* Scan the draft file for an attachment header field name. */
458         while (get_line() != EOF && *field != '\0' && *field != '-') {
459                 if (strncasecmp(field, sign_hdr, strlen(sign_hdr))==0 &&
460                                 field[strlen(sign_hdr)] == ':') {
461                         dosign = 1;
462                 }
463                 if (strncasecmp(field, enc_hdr, strlen(enc_hdr))==0 &&
464                                 field[strlen(enc_hdr)] == ':') {
465                         doenc = 1;
466                 }
467         }
468         if (!dosign && !doenc) {
469                 return DONE;
470         }
471
472         strcpy(composition_file_name, draft_file_name);
473
474         /* We're ready to roll! */
475         if (doenc) {
476                 ret = execprogl("mhsign", "mhsign", "-m", "-e",
477                                 draft_file_name, (char *)NULL);
478         } else {
479                 ret = execprogl("mhsign", "mhsign", "-m",
480                                 draft_file_name, (char *)NULL);
481         }
482         if (ret != 0) {
483                 /* some problem */
484                 return (NOTOK);
485         }
486         /* Remove the automatically created backup of mhsign. */
487         snprintf(buf, sizeof buf, "%s.orig", draft_file_name);
488         if (unlink(buf) == -1) {
489                 advise(NULL, "unable to remove original draft file.");
490         }
491
492         return (OK);
493 }
494
495 static void
496 clean_up_temporary_files(void)
497 {
498         unlink(body_file_name);
499         unlink(composition_file_name);
500
501         return;
502 }
503
504 static int
505 get_line(void)
506 {
507         int c;  /* current character */
508         int n;  /* number of bytes in buffer */
509         char *p;
510
511         /*
512         ** Get a line from the input file, growing the field buffer as
513         ** needed.  We do this so that we can fit an entire line in the
514         ** buffer making it easy to do a string comparison on both the
515         ** field name and the field body which might be a long path name.
516         */
517         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
518                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
519                         ungetc(c, draft_file);
520                         c = '\n';
521                         break;
522                 }
523                 if (++n >= field_size - 1) {
524                         field = mh_xrealloc(field, field_size += 256);
525                         p = field + n - 1;
526                 }
527         }
528         *p = '\0';
529
530         return (c);
531 }
532
533 static void
534 make_mime_composition_file_entry(char *file_name)
535 {
536         FILE *fp;
537         struct node *np;
538         char *cp;
539         char content_type[BUFSIZ];
540         char cmdbuf[BUFSIZ];
541         char *cmd = mimetypequeryproc;
542         int semicolon = 0;
543
544         for (np = m_defs; np; np = np->n_next) {
545                 if (strcasecmp(np->n_name, mimetypequery)==0) {
546                         cmd = np->n_field;
547                         break;
548                 }
549         }
550         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
551
552         if (!(fp = popen(cmdbuf, "r"))) {
553                 clean_up_temporary_files();
554                 adios(EX_IOERR, NULL, "unable to determine content type with `%s'",
555                                 cmdbuf);
556         }
557         if (fgets(content_type, sizeof content_type, fp) &&
558                         (cp = strrchr(content_type, '\n'))) {
559                 *cp = '\0';
560         } else {
561                 strcpy(content_type, "application/octet-stream");
562                 admonish(NULL, "problems with `%s', using fall back type `%s'",
563                                 cmdbuf, content_type);
564         }
565         pclose(fp);
566
567         /* TODO: don't use access(2) because it checks for ruid, not euid */
568         if (access(file_name, R_OK) != 0) {
569                 clean_up_temporary_files();
570                 adios(EX_IOERR, NULL, "unable to access file `%s'", file_name);
571         }
572
573         /* Check for broken file(1). See man page mh-profile(5). */
574         for (cp=content_type; *cp; cp++) {
575                 if (isspace(*cp)) {
576                         if (!semicolon) {
577                                 adios(EX_SOFTWARE, NULL, "Sorry, your Mime-Type-Query command (%s) is broken.\n\tThe output misses a semicolon before the whitespace.\n\tOutput was: %s", cmd, content_type);
578                         }
579                 } else if (*cp == ';') {
580                         semicolon = 1;
581                 } else {
582                         semicolon = 0;
583                 }
584         }
585
586         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
587         fprintf(composition_file,
588                         "#%s; name=\"%s\" <> [%s] {attachment} %s\n",
589                         content_type, cp, cp, file_name);
590
591         return;
592 }
593
594 /*
595 ** The back-end of the message sending back-end.
596 ** Annotate original message, and call `spost' to send message.
597 */
598 static int
599 sendaux(char **vec, int vecp, char *drft, struct stat *st)
600 {
601         pid_t child_id;
602         int status;
603         char backup[BUFSIZ];
604
605         vec[vecp++] = drft;
606         if (distfile && distout(drft, distfile, backup) == NOTOK) {
607                 return DONE;
608         }
609         vec[vecp] = NULL;
610
611         switch (child_id = fork()) {
612         case -1:
613                 /* oops -- fork error */
614                 advise("fork", "unable to");
615                 return DONE;
616
617         case 0:
618                 /* child process -- send it */
619                 execvp(*vec, vec);
620                 fprintf(stderr, "unable to exec ");
621                 perror(*vec);
622                 _exit(EX_OSERR);
623                 break;  /* NOT REACHED */
624
625         default:
626                 /* parent process -- wait for it */
627                 status = pidwait(child_id, NOTOK);
628                 if (WIFEXITED(status) && WEXITSTATUS(status) == EX_OK) {
629                         if (annotext) {
630                                 anno(st);
631                         }
632                 } else {
633                         /* spost failed */
634                         advise(NULL, "%s", strexit(status));
635                         if (distfile) {
636                                 unlink(drft);
637                                 if (rename(backup, drft) == NOTOK) {
638                                         advise(drft, "unable to rename %s to",
639                                                         backup);
640                                 }
641                         }
642                 }
643         }
644
645         return status ? NOTOK : status;
646 }
647
648
649 static void
650 anno(struct stat *st)
651 {
652         struct stat st2;
653         char *msgs, *folder;
654         char buf[BUFSIZ];
655         char *vec[MAXARGS];
656         int vecp = 0;
657         char *cp, *dp;
658
659         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
660                         st->st_mtime != st2.st_mtime ||
661                         st->st_dev != st2.st_dev ||
662                         st->st_ino != st2.st_ino)) {
663                 if (debugsw) {
664                         admonish(NULL, "$mhaltmsg mismatch");
665                 }
666                 return;
667         }
668
669         if (!(folder = getenv("mhfolder")) || !*folder) {
670                 if (debugsw) {
671                         admonish(NULL, "$mhfolder not set");
672                 }
673                 return;
674         }
675         if (!(msgs = getenv("mhmessages")) || !*msgs) {
676                 if (debugsw) {
677                         admonish(NULL, "$mhmessages not set");
678                 }
679                 return;
680         }
681         if (debugsw) {
682                 advise(NULL, "annotate as `%s': %s %s", annotext,
683                                 folder, msgs);
684         }
685         vec[vecp++] = "anno";
686         vec[vecp++] = "-comp";
687         vec[vecp++] = annotext;
688         snprintf(buf, sizeof buf, "+%s", folder);
689         vec[vecp++] = buf;
690
691         while (isspace(*msgs)) {
692                 msgs++;
693         }
694         for (cp=dp=msgs; *cp; cp++) {
695                 if (isspace(*cp)) {
696                         while (isspace(*cp)) {
697                                 *cp++ = '\0';
698                         }
699                         vec[vecp++] = dp;
700                         dp = cp;
701                 }
702         }
703         vec[vecp++] = dp;
704         vec[vecp] = NULL;
705         if (execprog(*vec, vec) != 0) {
706                 advise(NULL, "unable to annotate");
707         }
708 }
709
710
711 char*
712 strexit(int status)
713 {
714         if (WIFSIGNALED(status)) {
715                 return "spost or sendmail killed by signal";
716         }
717         if (!WIFEXITED(status)) {
718                 return "message not delivered to anyone";
719         }
720         switch (WEXITSTATUS(status)) {
721         case EX_TEMPFAIL:
722                 return "Temporary error, maybe the MTA has queued the message";
723         default:
724                 return "message not delivered to anyone";
725         }
726 }