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