Completely removed the backup-prefix (,). We move to +trash instead.
[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
236         /*
237         ** Save the original name of the draft file.  The name of the
238         ** draft file is changed to a temporary file containing the built
239         ** MIME message if there are attachments.  We need the original
240         ** name so that it can be renamed after the message is sent.
241         */
242         original_draft = drft;
243
244         /*
245         ** Convert the draft to a MIME message.
246         ** Use the mhbuild composition file for the draft if there was
247         ** a successful conversion because that now contains the MIME
248         ** message.  A nice side effect of this is that it leaves the
249         ** original draft file untouched so that it can be retrieved
250         ** and modified if desired.
251         */
252         switch (attach(drft)) {
253         case OK:
254                 drft = composition_file_name;
255                 break;
256
257         case NOTOK:
258                 return (NOTOK);
259
260         case DONE:
261                 break;
262         }
263
264         done=armed_done;
265         switch (setjmp(env)) {
266         case OK:
267                 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
268                 if (status == OK) {
269                         /* move original draft to +trash folder */
270                         snprintf(buffer, sizeof buffer,
271                                         "</dev/null refile -file %s +trash",
272                                         original_draft);
273                         if (system(buffer) != 0) {
274                                 advise(NULL, "unable to trash the draft");
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         /* Get rid of temporary files that we created for attachments. */
290         if (drft == composition_file_name) {
291                 clean_up_temporary_files();
292         }
293
294         return status;
295 }
296
297 static int
298 attach(char *draft_file_name)
299 {
300         char buf[MAXPATHLEN + 6];
301         int c;
302         int has_attachment;
303         int has_body;
304         int non_ascii; /* msg body contains non-ASCII chars */
305         int length;  /* length of attachment header field name */
306         char *p;
307
308         if (!(draft_file = fopen(draft_file_name, "r"))) {
309                 adios(NULL, "can't open draft file `%s'.", draft_file_name);
310         }
311
312         /* We'll grow the buffer as needed. */
313         field = (char *)mh_xmalloc(field_size = 256);
314
315         /*
316         ** Scan the draft file for an attachment header field name.
317         */
318         length = strlen(attach_hdr);
319         has_attachment = 0;
320         while (get_line() != EOF && *field != '\0' && *field != '-') {
321                 if (strncasecmp(field, attach_hdr, length)==0 &&
322                                 field[length] == ':') {
323                         has_attachment = 1;
324                 }
325         }
326
327         /*
328         ** Look for at least one non-blank line in the body of the
329         ** message which indicates content in the body.
330         ** Check if body contains at least one non-blank (= not empty)
331         ** and if it contains any non-ASCII chars (= need MIME).
332         */
333         has_body = 0;
334         non_ascii = 0;
335         while (get_line() != EOF) {
336                 for (p = field; *p != '\0'; p++) {
337                         if (*p != ' ' && *p != '\t') {
338                                 has_body = 1;
339                         }
340                         if (*p > 127 || *p < 0) {
341                                 non_ascii = 1;
342                         }
343                 }
344                 if (has_body && non_ascii) {
345                         break;  /* that's been already enough information */
346                 }
347         }
348
349         if (!has_attachment && non_ascii==0) {
350                 /* We don't need to convert it to MIME. */
351                 return DONE;
352         }
353
354         /*
355         ** Else: mimify
356         */
357
358         /* Make names for the temporary files.  */
359         strncpy(body_file_name,
360                         m_mktemp(toabsdir(invo_name), NULL, NULL),
361                         sizeof (body_file_name));
362         strncpy(composition_file_name,
363                         m_mktemp(toabsdir(invo_name), NULL, NULL),
364                         sizeof (composition_file_name));
365
366         if (has_body) {
367                 body_file = fopen(body_file_name, "w");
368         }
369         composition_file = fopen(composition_file_name, "w");
370
371         if ((has_body && !body_file) || !composition_file) {
372                 clean_up_temporary_files();
373                 adios(NULL, "unable to open all of the temporary files.");
374         }
375
376         /* Copy non-attachment header fields to the temp composition file. */
377         rewind(draft_file);
378         while (get_line() != EOF && *field && *field != '-') {
379                 if (strncasecmp(field, attach_hdr, length) != 0 ||
380                                 field[length] != ':') {
381                         fprintf(composition_file, "%s\n", field);
382                 }
383         }
384         fputs("--------\n", composition_file);
385
386         if (has_body) {
387                 /* Copy the message body to the temporary file. */
388                 while ((c = getc(draft_file)) != EOF) {
389                         putc(c, body_file);
390                 }
391                 fclose(body_file);
392
393                 /* Add a mhbuild MIME composition file line for the body */
394                 /* charset will be discovered/guessed by mhbuild */
395                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
396         }
397
398         /*
399         ** Now, go back to the beginning of the draft file and look for
400         ** header fields that specify attachments.  Add a mhbuild MIME
401         ** composition file for each.
402         */
403         rewind(draft_file);
404         while (get_line() != EOF && *field && *field != '-') {
405                 if (strncasecmp(field, attach_hdr, length) == 0 &&
406                                 field[length] == ':') {
407                         for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
408                                 continue;
409                         }
410                         if (*p == '+') {
411                                 /* forwarded message */
412                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
413                         } else {
414                                 /* regular attachment */
415                                 make_mime_composition_file_entry(p);
416                         }
417                 }
418         }
419         fclose(composition_file);
420
421         /* We're ready to roll! */
422         sprintf(buf, "mhbuild %s", composition_file_name);
423         if (system(buf) != 0) {
424                 /* some problem */
425                 clean_up_temporary_files();
426                 return (NOTOK);
427         }
428         /* Remove the automatically created backup of mhbuild. */
429         snprintf(buf, sizeof buf, "%s.orig", composition_file_name);
430         if (unlink(buf) == -1) {
431                 advise(NULL, "unable to remove original composition file.");
432         }
433
434         return (OK);
435 }
436
437 static void
438 clean_up_temporary_files(void)
439 {
440         unlink(body_file_name);
441         unlink(composition_file_name);
442
443         return;
444 }
445
446 static int
447 get_line(void)
448 {
449         int c;  /* current character */
450         int n;  /* number of bytes in buffer */
451         char *p;
452
453         /*
454         ** Get a line from the input file, growing the field buffer as
455         ** needed.  We do this so that we can fit an entire line in the
456         ** buffer making it easy to do a string comparison on both the
457         ** field name and the field body which might be a long path name.
458         */
459         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
460                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
461                         ungetc(c, draft_file);
462                         c = '\n';
463                         break;
464                 }
465                 if (++n >= field_size - 1) {
466                         field = (char *)mh_xrealloc(field, field_size += 256);
467                         p = field + n - 1;
468                 }
469         }
470         *p = '\0';
471
472         return (c);
473 }
474
475 static void
476 make_mime_composition_file_entry(char *file_name)
477 {
478         FILE *fp;
479         struct node *np;
480         char *cp;
481         char content_type[BUFSIZ];
482         char cmdbuf[BUFSIZ];
483         char *cmd = mimetypequeryproc;
484
485         for (np = m_defs; np; np = np->n_next) {
486                 if (strcasecmp(np->n_name, mimetypequery)==0) {
487                         cmd = np->n_field;
488                         break;
489                 }
490         }
491         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
492
493         if (!(fp = popen(cmdbuf, "r"))) {
494                 clean_up_temporary_files();
495                 adios(NULL, "unable to determine content type with `%s'",
496                                 cmdbuf);
497         }
498         if (fgets(content_type, sizeof content_type, fp) &&
499                         (cp = strrchr(content_type, '\n'))) {
500                 *cp = '\0';
501         } else {
502                 strcpy(content_type, "application/octet-stream");
503                 admonish(NULL, "problems with `%s', using fall back type `%s'",
504                                 cmdbuf, content_type);
505         }
506         pclose(fp);
507
508         /* TODO: don't use access(2) because it checks for ruid, not euid */
509         if (access(file_name, R_OK) != 0) {
510                 clean_up_temporary_files();
511                 adios(NULL, "unable to access file `%s'", file_name);
512         }
513
514         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
515         fprintf(composition_file, "#%s; name=\"%s\" <> [%s] {attachment}",
516                         content_type, cp, cp);
517
518         fprintf(composition_file, " %s\n", file_name);
519
520         return;
521 }
522
523 /*
524 ** The back-end of the message sending back-end.
525 ** Annotate original message, and call `spost' to send message.
526 */
527 static int
528 sendaux(char **vec, int vecp, char *drft, struct stat *st)
529 {
530         pid_t child_id;
531         int status;
532         char backup[BUFSIZ];
533
534         vec[vecp++] = drft;
535         if (distfile && distout(drft, distfile, backup) == NOTOK) {
536                 done(1);
537         }
538         vec[vecp] = NULL;
539
540         switch (child_id = fork()) {
541         case -1:
542                 /* oops -- fork error */
543                 adios("fork", "unable to");
544                 break;  /* NOT REACHED */
545
546         case 0:
547                 /* child process -- send it */
548                 execvp(*vec, vec);
549                 fprintf(stderr, "unable to exec ");
550                 perror(*vec);
551                 _exit(-1);
552                 break;  /* NOT REACHED */
553
554         default:
555                 /* parent process -- wait for it */
556                 if ((status = pidwait(child_id, NOTOK)) == OK) {
557                         if (annotext) {
558                                 anno(st);
559                         }
560                 } else {
561                         /* spost failed */
562                         advise(NULL, "message not delivered to anyone");
563                         if (distfile) {
564                                 unlink(drft);
565                                 if (rename(backup, drft) == NOTOK) {
566                                         advise(drft, "unable to rename %s to",
567                                                         backup);
568                                 }
569                         }
570                 }
571                 break;
572         }
573
574         return status;
575 }
576
577
578 static void
579 anno(struct stat *st)
580 {
581         struct stat st2;
582         char *msgs, *folder;
583         char buf[BUFSIZ];
584
585         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
586                         st->st_mtime != st2.st_mtime ||
587                         st->st_dev != st2.st_dev ||
588                         st->st_ino != st2.st_ino)) {
589                 if (debugsw) {
590                         admonish(NULL, "$mhaltmsg mismatch");
591                 }
592                 return;
593         }
594
595         if (!(folder = getenv("mhfolder")) || !*folder) {
596                 if (debugsw) {
597                         admonish(NULL, "$mhfolder not set");
598                 }
599                 return;
600         }
601         if (!(msgs = getenv("mhmessages")) || !*msgs) {
602                 if (debugsw) {
603                         admonish(NULL, "$mhmessages not set");
604                 }
605                 return;
606         }
607         if (debugsw) {
608                 advise(NULL, "annotate as `%s': %s %s", annotext,
609                                 folder, msgs);
610         }
611         snprintf(buf, sizeof buf, "anno -comp '%s' '+%s' %s",
612                         annotext, folder, msgs);
613         if (system(buf) != 0) {
614                 advise(NULL, "unable to annotate");
615         }
616 }
617
618
619 static void
620 armed_done(int status)
621 {
622         longjmp(env, status ? status : NOTOK);
623
624         exit(status);
625 }