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