06058e86561f7f63074f66796b8e009b7e4118f3
[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 *);
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", 2 },
64 #define WATCSW  4
65         { "watch", 0 },
66 #define NWATCSW  5
67         { "nowatch", 2 },
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)) {
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)
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 (status == OK) {
312                         strncpy(buffer, m_backup(original_draft),
313                                         sizeof(buffer));
314                         if (rename(original_draft, buffer) == NOTOK) {
315                                 advise(buffer, "unable to rename %s to", drft);
316                         }
317                 }
318                 break;
319
320         default:
321                 status = DONE;
322                 break;
323         }
324
325         done=exit;
326         if (distfile) {
327                 unlink(distfile);
328         }
329
330         /*
331         ** Get rid of any temporary files that we created for attachments.
332         ** Also get rid of the renamed composition file that mhbuild
333         ** leaves as a turd.  It looks confusing, but we use the body
334         ** file name to help build the renamed composition file name.
335         */
336         if (drft == composition_file_name) {
337                 clean_up_temporary_files();
338
339                 if (strlen(composition_file_name) >=
340                                 sizeof (composition_file_name) - 6) {
341                         advise(NULL, "unable to remove original composition file.");
342                 } else {
343                         if (!(p = strrchr(composition_file_name, '/'))) {
344                                 p = composition_file_name;
345                         } else {
346                                 p++;
347                         }
348                         strcpy(body_file_name, p);
349                         *p++ = ',';
350                         strcpy(p, body_file_name);
351                         strcat(p, ".orig");
352
353                         unlink(composition_file_name);
354                 }
355         }
356
357         return status;
358 }
359
360 static int
361 attach(char *draft_file_name)
362 {
363         char buf[MAXPATHLEN + 6];
364         int c;
365         int has_attachment;
366         int has_body;
367         int non_ascii; /* msg body contains non-ASCII chars */
368         int length;  /* length of attachment header field name */
369         char *p;
370
371         if (!(draft_file = fopen(draft_file_name, "r"))) {
372                 adios(NULL, "can't open draft file `%s'.", draft_file_name);
373         }
374
375         /* We'll grow the buffer as needed. */
376         field = (char *)mh_xmalloc(field_size = 256);
377
378         /*
379         ** Scan the draft file for an attachment header field name.
380         */
381         length = strlen(attach_hdr);
382         has_attachment = 0;
383         while (get_line() != EOF && *field != '\0' && *field != '-') {
384                 if (strncasecmp(field, attach_hdr, length)==0 &&
385                                 field[length] == ':') {
386                         has_attachment = 1;
387                 }
388         }
389
390         /*
391         ** Look for at least one non-blank line in the body of the
392         ** message which indicates content in the body.
393         ** Check if body contains at least one non-blank (= not empty)
394         ** and if it contains any non-ASCII chars (= need MIME).
395         */
396         has_body = 0;
397         non_ascii = 0;
398         while (get_line() != EOF) {
399                 for (p = field; *p != '\0'; p++) {
400                         if (*p != ' ' && *p != '\t') {
401                                 has_body = 1;
402                         }
403                         if (*p > 127 || *p < 0) {
404                                 non_ascii = 1;
405                         }
406                 }
407                 if (has_body && non_ascii) {
408                         break;  /* that's been already enough information */
409                 }
410         }
411
412         if (!has_attachment && non_ascii==0) {
413                 /* We don't need to convert it to MIME. */
414                 return DONE;
415         }
416
417         /*
418         ** Else: mimify
419         */
420
421         /* Make names for the temporary files.  */
422         strncpy(body_file_name,
423                         m_mktemp(toabsdir(invo_name), NULL, NULL),
424                         sizeof (body_file_name));
425         strncpy(composition_file_name,
426                         m_mktemp(toabsdir(invo_name), NULL, NULL),
427                         sizeof (composition_file_name));
428
429         if (has_body) {
430                 body_file = fopen(body_file_name, "w");
431         }
432         composition_file = fopen(composition_file_name, "w");
433
434         if ((has_body && !body_file) || !composition_file) {
435                 clean_up_temporary_files();
436                 adios(NULL, "unable to open all of the temporary files.");
437         }
438
439         /* Copy non-attachment header fields to the temp composition file. */
440         rewind(draft_file);
441         while (get_line() != EOF && *field && *field != '-') {
442                 if (strncasecmp(field, attach_hdr, length) != 0 ||
443                                 field[length] != ':') {
444                         fprintf(composition_file, "%s\n", field);
445                 }
446         }
447         fputs("--------\n", composition_file);
448
449         if (has_body) {
450                 /* Copy the message body to the temporary file. */
451                 while ((c = getc(draft_file)) != EOF) {
452                         putc(c, body_file);
453                 }
454                 fclose(body_file);
455
456                 /* Add a mhbuild MIME composition file line for the body */
457                 /* charset will be discovered/guessed by mhbuild */
458                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
459         }
460
461         /*
462         ** Now, go back to the beginning of the draft file and look for
463         ** header fields that specify attachments.  Add a mhbuild MIME
464         ** composition file for each.
465         */
466         rewind(draft_file);
467         while (get_line() != EOF && *field && *field != '-') {
468                 if (strncasecmp(field, attach_hdr, length) == 0 &&
469                                 field[length] == ':') {
470                         for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
471                                 continue;
472                         }
473                         if (*p == '+') {
474                                 /* forwarded message */
475                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
476                         } else {
477                                 /* regular attachment */
478                                 make_mime_composition_file_entry(p);
479                         }
480                 }
481         }
482         fclose(composition_file);
483
484         /* We're ready to roll! */
485         sprintf(buf, "mhbuild %s", composition_file_name);
486         if (system(buf) != 0) {
487                 /* some problem */
488                 clean_up_temporary_files();
489                 return (NOTOK);
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 = (char *)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
543         for (np = m_defs; np; np = np->n_next) {
544                 if (strcasecmp(np->n_name, mimetypequery)==0) {
545                         cmd = np->n_field;
546                         break;
547                 }
548         }
549         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
550
551         if (!(fp = popen(cmdbuf, "r"))) {
552                 clean_up_temporary_files();
553                 adios(NULL, "unable to determine content type with `%s'",
554                                 cmdbuf);
555         }
556         if (fgets(content_type, sizeof content_type, fp) &&
557                         (cp = strrchr(content_type, '\n'))) {
558                 *cp = '\0';
559         } else {
560                 strcpy(content_type, "application/octet-stream");
561                 admonish(NULL, "problems with `%s', using fall back type `%s'",
562                                 cmdbuf, content_type);
563         }
564         pclose(fp);
565
566         /* TODO: don't use access(2) because it checks for ruid, not euid */
567         if (access(file_name, R_OK) != 0) {
568                 clean_up_temporary_files();
569                 adios(NULL, "unable to access file `%s'", file_name);
570         }
571
572         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
573         fprintf(composition_file, "#%s; name=\"%s\" <> [%s] {attachment}",
574                         content_type, cp, cp);
575
576         fprintf(composition_file, " %s\n", file_name);
577
578         return;
579 }
580
581 /*
582 ** The back-end of the message sending back-end.
583 ** Annotate original message, and call `spost' to send message.
584 */
585 static int
586 sendaux(char **vec, int vecp, char *drft, struct stat *st)
587 {
588         pid_t child_id;
589         int status;
590         char backup[BUFSIZ];
591
592         vec[vecp++] = drft;
593         if (distfile && distout(drft, distfile, backup) == NOTOK) {
594                 done(1);
595         }
596         vec[vecp] = NULL;
597
598         switch (child_id = fork()) {
599         case -1:
600                 /* oops -- fork error */
601                 adios("fork", "unable to");
602                 break;  /* NOT REACHED */
603
604         case 0:
605                 /* child process -- send it */
606                 execvp(*vec, vec);
607                 fprintf(stderr, "unable to exec ");
608                 perror(*vec);
609                 _exit(-1);
610                 break;  /* NOT REACHED */
611
612         default:
613                 /* parent process -- wait for it */
614                 if ((status = pidwait(child_id, NOTOK)) == OK) {
615                         if (annotext) {
616                                 anno(st);
617                         }
618                 } else {
619                         /* spost failed */
620                         advise(NULL, "message not delivered to anyone");
621                         if (distfile) {
622                                 unlink(drft);
623                                 if (rename(backup, drft) == NOTOK) {
624                                         advise(drft, "unable to rename %s to",
625                                                         backup);
626                                 }
627                         }
628                 }
629                 break;
630         }
631
632         return status;
633 }
634
635
636 static void
637 anno(struct stat *st)
638 {
639         struct stat st2;
640         char *msgs, *folder;
641         char buf[BUFSIZ];
642
643         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
644                         st->st_mtime != st2.st_mtime ||
645                         st->st_dev != st2.st_dev ||
646                         st->st_ino != st2.st_ino)) {
647                 if (debugsw) {
648                         admonish(NULL, "$mhaltmsg mismatch");
649                 }
650                 return;
651         }
652
653         if (!(folder = getenv("mhfolder")) || !*folder) {
654                 if (debugsw) {
655                         admonish(NULL, "$mhfolder not set");
656                 }
657                 return;
658         }
659         if (!(msgs = getenv("mhmessages")) || !*msgs) {
660                 if (debugsw) {
661                         admonish(NULL, "$mhmessages not set");
662                 }
663                 return;
664         }
665         if (debugsw) {
666                 advise(NULL, "annotate as `%s': %s %s", annotext,
667                                 folder, msgs);
668         }
669         snprintf(buf, sizeof buf, "anno -comp '%s' '+%s' %s",
670                         annotext, folder, msgs);
671         if (system(buf) != 0) {
672                 advise(NULL, "unable to annotate");
673         }
674 }
675
676
677 static void
678 armed_done(int status)
679 {
680         longjmp(env, status ? status : NOTOK);
681
682         exit(status);
683 }