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