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