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