Lots of little code cleanups to prevent warnings - mostly making sure
[mmh] / uip / sendsbr.c
1
2 /*
3  * sendsbr.c -- routines to help WhatNow/Send along
4  *
5  * $Id$
6  */
7
8 #include <h/mh.h>
9 #include <h/signals.h>
10 #include <setjmp.h>
11 #include <signal.h>
12 #include <fcntl.h>
13 #include <h/mime.h>
14
15 #ifdef TIME_WITH_SYS_TIME
16 # include <sys/time.h>
17 # include <time.h>
18 #else
19 # ifdef TM_IN_SYS_TIME
20 #  include <sys/time.h>
21 # else
22 #  include <time.h>
23 # endif
24 #endif
25
26 int debugsw = 0;                /* global */
27 int forwsw  = 1;
28 int inplace = 1;
29 int pushsw  = 0;
30 int splitsw = -1;
31 int unique  = 0;
32 int verbsw  = 0;
33
34 char *altmsg   = NULL;          /*  .. */
35 char *annotext = NULL;
36 char *distfile = NULL;
37
38 static int armed = 0;
39 static jmp_buf env;
40
41 /*
42  * external prototypes
43  */
44 int sendsbr (char **, int, char *, struct stat *, int);
45 int done (int);
46 char *getusername (void);
47
48 /*
49  * static prototypes
50  */
51 static void alert (char *, int);
52 static int tmp_fd (void);
53 static void anno (int, struct stat *);
54 static void annoaux (int);
55 static int splitmsg (char **, int, char *, struct stat *, int);
56 static int sendaux (char **, int, char *, struct stat *);
57
58
59 /*
60  * Entry point into (back-end) routines to send message.
61  */
62
63 int
64 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
65 {
66     int status;
67     char buffer[BUFSIZ], file[BUFSIZ];
68     struct stat sts;
69
70     armed++;
71     switch (setjmp (env)) {
72     case OK: 
73         /*
74          * If given -push and -unique (which is undocumented), then
75          * rename the draft file.  I'm not quite sure why.
76          */
77         if (pushsw && unique) {
78             if (rename (drft, strncpy (file, m_scratch (drft, invo_name), sizeof(file)))
79                     == NOTOK)
80                 adios (file, "unable to rename %s to", drft);
81             drft = file;
82         }
83
84         /*
85          * Check if we need to split the message into
86          * multiple messages of type "message/partial".
87          */
88         if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
89                 && sts.st_size >= CPERMSG) {
90             status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
91         } else {
92             status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
93         }
94
95         /* rename the original draft */
96         if (rename_drft && status == OK &&
97                 rename (drft, strncpy (buffer, m_backup (drft), sizeof(buffer))) == NOTOK)
98             advise (buffer, "unable to rename %s to", drft);
99         break;
100
101     default: 
102         status = DONE;
103         break;
104     }
105
106     armed = 0;
107     if (distfile)
108         unlink (distfile);
109
110     return status;
111 }
112
113
114 /*
115  * Split large message into several messages of
116  * type "message/partial" and send them.
117  */
118
119 static int
120 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
121 {
122     int compnum, nparts, partno, state, status;
123     long pos, start;
124     time_t clock;
125     char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
126     char subject[BUFSIZ];
127     char name[NAMESZ], partnum[BUFSIZ];
128     FILE *in;
129
130     if ((in = fopen (drft, "r")) == NULL)
131         adios (drft, "unable to open for reading");
132
133     cp = dp = NULL;
134     start = 0L;
135
136     /*
137      * Scan through the message and examine the various header fields,
138      * as well as locate the beginning of the message body.
139      */
140     for (compnum = 1, state = FLD;;) {
141         switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
142             case FLD:
143             case FLDPLUS:
144             case FLDEOF:
145                 compnum++;
146
147                 /*
148                  * This header field is discarded.
149                  */
150                 if (!strcasecmp (name, "Message-ID")) {
151                     while (state == FLDPLUS)
152                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
153                 } else if (uprf (name, XXX_FIELD_PRF)
154                         || !strcasecmp (name, VRSN_FIELD)
155                         || !strcasecmp (name, "Subject")
156                         || !strcasecmp (name, "Encrypted")) {
157                     /*
158                      * These header fields are copied to the enclosed
159                      * header of the first message in the collection
160                      * of message/partials.  For the "Subject" header
161                      * field, we also record it, so that a modified
162                      * version of it, can be copied to the header
163                      * of each messsage/partial in the collection.
164                      */
165                     if (!strcasecmp (name, "Subject")) {
166                         size_t sublen;
167
168                         strncpy (subject, buffer, BUFSIZ);
169                         sublen = strlen (subject);
170                         if (sublen > 0 && subject[sublen - 1] == '\n')
171                             subject[sublen - 1] = '\0';
172                     }
173
174                     dp = add (concat (name, ":", buffer, NULL), dp);
175                     while (state == FLDPLUS) {
176                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
177                         dp = add (buffer, dp);
178                     }
179                 } else {
180                     /*
181                      * These header fields are copied to the header of
182                      * each message/partial in the collection.
183                      */
184                     cp = add (concat (name, ":", buffer, NULL), cp);
185                     while (state == FLDPLUS) {
186                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
187                         cp = add (buffer, cp);
188                     }
189                 }
190
191                 if (state != FLDEOF) {
192                     start = ftell (in) + 1;
193                     continue;
194                 }
195                 /* else fall... */
196
197            case BODY:
198            case BODYEOF:
199            case FILEEOF:
200                 break;
201
202            case LENERR:
203            case FMTERR:
204                 adios (NULL, "message format error in component #%d", compnum);
205
206            default:
207                 adios (NULL, "getfld () returned %d", state);
208         }
209
210         break;
211     }
212     if (cp == NULL)
213         adios (NULL, "headers missing from draft");
214
215     nparts = 1;
216     pos = start;
217     while (fgets (buffer, sizeof(buffer) - 1, in)) {
218         long len;
219
220         if ((pos += (len = strlen (buffer))) > CPERMSG) {
221             nparts++;
222             pos = len;
223         }
224     }
225
226     /* Only one part, nothing to split */
227     if (nparts == 1) {
228         free (cp);
229         if (dp)
230             free (dp);
231
232         fclose (in);
233         return sendaux (vec, vecp, drft, st);
234     }
235
236     if (!pushsw) {
237         printf ("Sending as %d Partial Messages\n", nparts);
238         fflush (stdout);
239     }
240     status = OK;
241
242     vec[vecp++] = "-partno";
243     vec[vecp++] = partnum;
244     if (delay == 0)
245         vec[vecp++] = "-queued";
246
247     time (&clock);
248     snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
249                 (int) getpid(), (long) clock, LocalName());
250
251     fseek (in, start, SEEK_SET);
252     for (partno = 1; partno <= nparts; partno++) {
253         char tmpdrf[BUFSIZ];
254         FILE *out;
255
256         strncpy (tmpdrf, m_scratch (drft, invo_name), sizeof(tmpdrf));
257         if ((out = fopen (tmpdrf, "w")) == NULL)
258             adios (tmpdrf, "unable to open for writing");
259         chmod (tmpdrf, 0600);
260
261         /*
262          * Output the header fields
263          */
264         fputs (cp, out);
265         fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
266         fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
267         fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
268         fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
269         fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
270
271         /*
272          * If this is the first in the collection, output the
273          * header fields we are encapsulating at the beginning
274          * of the body of the first message.
275          */
276         if (partno == 1) {
277             if (dp)
278                 fputs (dp, out);
279             fprintf (out, "Message-ID: %s\n", msgid);
280             fprintf (out, "\n");
281         }
282
283         pos = 0;
284         for (;;) {
285             long len;
286
287             if (!fgets (buffer, sizeof(buffer) - 1, in)) {
288                 if (partno == nparts)
289                     break;
290                 adios (NULL, "premature eof");
291             }
292             
293             if ((pos += (len = strlen (buffer))) > CPERMSG) {
294                 fseek (in, -len, SEEK_CUR);
295                 break;
296             }
297
298             fputs (buffer, out);
299         }
300
301         if (fflush (out))
302             adios (tmpdrf, "error writing to");
303
304         fclose (out);
305
306         if (!pushsw && verbsw) {
307             printf ("\n");
308             fflush (stdout);
309         }
310
311         /* Pause here, if a delay is specified */
312         if (delay > 0 && 1 < partno && partno <= nparts) {
313             if (!pushsw) {
314                 printf ("pausing %d seconds before sending part %d...\n",
315                         delay, partno);
316                 fflush (stdout);
317             }
318             sleep ((unsigned int) delay);
319         }
320
321         snprintf (partnum, sizeof(partnum), "%d", partno);
322         status = sendaux (vec, vecp, tmpdrf, st);
323         unlink (tmpdrf);
324         if (status != OK)
325             break;
326
327         /*
328          * This is so sendaux will only annotate
329          * the altmsg the first time it is called.
330          */
331         annotext = NULL;
332     }
333
334     free (cp);
335     if (dp)
336         free (dp);
337
338     fclose (in);        /* close the draft */
339     return status;
340 }
341
342
343 /*
344  * Annotate original message, and
345  * call `postproc' to send message.
346  */
347
348 static int
349 sendaux (char **vec, int vecp, char *drft, struct stat *st)
350 {
351     pid_t child_id;
352     int i, status, fd, fd2;
353     char backup[BUFSIZ], buf[BUFSIZ];
354
355     fd = pushsw ? tmp_fd () : NOTOK;
356     fd2 = NOTOK;
357
358     vec[vecp++] = drft;
359     if (annotext) {
360         if ((fd2 = tmp_fd ()) != NOTOK) {
361             vec[vecp++] = "-idanno";
362             snprintf (buf, sizeof(buf), "%d", fd2);
363             vec[vecp++] = buf;
364         } else {
365             admonish (NULL, "unable to create file for annotation list");
366         }
367     }
368     if (distfile && distout (drft, distfile, backup) == NOTOK)
369         done (1);
370     vec[vecp] = NULL;
371
372     for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
373         sleep (5);
374
375     switch (child_id) {
376     case -1:
377         /* oops -- fork error */
378         adios ("fork", "unable to");
379         break;  /* NOT REACHED */
380
381     case 0:
382         /*
383          * child process -- send it
384          *
385          * If fd is ok, then we are pushing and fd points to temp
386          * file, so capture anything on stdout and stderr there.
387          */
388         if (fd != NOTOK) {
389             dup2 (fd, fileno (stdout));
390             dup2 (fd, fileno (stderr));
391             close (fd);
392         }
393         execvp (postproc, vec);
394         fprintf (stderr, "unable to exec ");
395         perror (postproc);
396         _exit (-1);
397         break;  /* NOT REACHED */
398
399     default:
400         /*
401          * parent process -- wait for it
402          */
403         if ((status = pidwait(child_id, NOTOK)) == OK) {
404             if (annotext && fd2 != NOTOK)
405                 anno (fd2, st);
406         } else {
407             /*
408              * If postproc failed, and we have good fd (which means
409              * we pushed), then mail error message (and possibly the
410              * draft) back to the user.
411              */
412             if (fd != NOTOK) {
413                 alert (drft, fd);
414                 close (fd);
415             } else {
416                 advise (NULL, "message not delivered to anyone");
417             }
418             if (annotext && fd2 != NOTOK)
419                 close (fd2);
420             if (distfile) {
421                 unlink (drft);
422                 if (rename (backup, drft) == NOTOK)
423                     advise (drft, "unable to rename %s to", backup);
424             }
425         }
426         break;
427     }
428
429     return status;
430 }
431
432
433 /*
434  * Mail error notification (and possibly a copy of the
435  * message) back to the user, using the mailproc
436  */
437
438 static void
439 alert (char *file, int out)
440 {
441     pid_t child_id;
442     int i, in;
443     char buf[BUFSIZ];
444
445     for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
446         sleep (5);
447
448     switch (child_id) {
449         case NOTOK:
450             /* oops -- fork error */
451             advise ("fork", "unable to");
452
453         case OK:
454             /* child process -- send it */
455             SIGNAL (SIGHUP, SIG_IGN);
456             SIGNAL (SIGINT, SIG_IGN);
457             SIGNAL (SIGQUIT, SIG_IGN);
458             SIGNAL (SIGTERM, SIG_IGN);
459             if (forwsw) {
460                 if ((in = open (file, O_RDONLY)) == NOTOK) {
461                     admonish (file, "unable to re-open");
462                 } else {
463                     lseek (out, (off_t) 0, SEEK_END);
464                     strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
465                     write (out, buf, strlen (buf));
466                     strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
467                     write (out, buf, strlen (buf));
468                     cpydgst (in, out, file, "temporary file");
469                     close (in);
470                     strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
471                     write (out, buf, strlen (buf));
472                     if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
473                         admonish (buf, "unable to rename %s to", file);
474                 }
475             }
476             lseek (out, (off_t) 0, SEEK_SET);
477             dup2 (out, fileno (stdin));
478             close (out);
479             /* create subject for error notification */
480             snprintf (buf, sizeof(buf), "send failed on %s",
481                         forwsw ? "enclosed draft" : file);
482
483             execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
484                     "-subject", buf, NULL);
485             fprintf (stderr, "unable to exec ");
486             perror (mailproc);
487             _exit (-1);
488
489         default:                /* no waiting... */
490             break;
491     }
492 }
493
494
495 static int
496 tmp_fd (void)
497 {
498     int fd;
499     char tmpfil[BUFSIZ];
500
501     strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
502     if ((fd = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == NOTOK)
503         return NOTOK;
504     if (debugsw)
505         advise (NULL, "temporary file %s selected", tmpfil);
506     else
507         if (unlink (tmpfil) == NOTOK)
508             advise (tmpfil, "unable to remove");
509
510     return fd;
511 }
512
513
514 static void
515 anno (int fd, struct stat *st)
516 {
517     pid_t child_id;
518     sigset_t set, oset;
519     static char *cwd = NULL;
520     struct stat st2;
521
522     if (altmsg &&
523             (stat (altmsg, &st2) == NOTOK
524                 || st->st_mtime != st2.st_mtime
525                 || st->st_dev != st2.st_dev
526                 || st->st_ino != st2.st_ino)) {
527         if (debugsw)
528             admonish (NULL, "$mhaltmsg mismatch");
529         return;
530     }
531
532     child_id = debugsw ? NOTOK : fork ();
533     switch (child_id) {
534         case NOTOK:             /* oops */
535             if (!debugsw)
536                 advise (NULL,
537                             "unable to fork, so doing annotations by hand...");
538             if (cwd == NULL)
539                 cwd = getcpy (pwd ());
540
541         case OK: 
542             /* block a few signals */
543             sigemptyset (&set);
544             sigaddset (&set, SIGHUP);
545             sigaddset (&set, SIGINT);
546             sigaddset (&set, SIGQUIT);
547             sigaddset (&set, SIGTERM);
548             SIGPROCMASK (SIG_BLOCK, &set, &oset);
549
550             annoaux (fd);
551             if (child_id == OK)
552                 _exit (0);
553
554             /* reset the signal mask */
555             SIGPROCMASK (SIG_SETMASK, &oset, &set);
556
557             chdir (cwd);
558             break;
559
560         default:                /* no waiting... */
561             close (fd);
562             break;
563     }
564 }
565
566
567 static void
568 annoaux (int fd)
569 {
570     int fd2, fd3, msgnum;
571     char *cp, *folder, *maildir;
572     char buffer[BUFSIZ], **ap;
573     FILE *fp;
574     struct msgs *mp;
575
576     if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
577         if (debugsw)
578             admonish (NULL, "$mhfolder not set");
579         return;
580     }
581     maildir = m_maildir (folder);
582     if (chdir (maildir) == NOTOK) {
583         if (debugsw)
584             admonish (maildir, "unable to change directory to");
585         return;
586     }
587     if (!(mp = folder_read (folder))) {
588         if (debugsw)
589             admonish (NULL, "unable to read folder %s");
590         return;
591     }
592
593     /* check for empty folder */
594     if (mp->nummsg == 0) {
595         if (debugsw)
596             admonish (NULL, "no messages in %s", folder);
597         goto oops;
598     }
599
600     if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
601         if (debugsw)
602             admonish (NULL, "$mhmessages not set");
603         goto oops;
604     }
605     if (!debugsw                        /* MOBY HACK... */
606             && pushsw
607             && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
608             && (fd2 = dup (fileno (stderr))) != NOTOK) {
609         dup2 (fd3, fileno (stderr));
610         close (fd3);
611     }
612     else
613         fd2 = NOTOK;
614     for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
615         m_convert (mp, *ap);
616     free (cp);
617     if (fd2 != NOTOK)
618         dup2 (fd2, fileno (stderr));
619     if (mp->numsel == 0) {
620         if (debugsw)
621             admonish (NULL, "no messages to annotate");
622         goto oops;
623     }
624
625     lseek (fd, (off_t) 0, SEEK_SET);
626     if ((fp = fdopen (fd, "r")) == NULL) {
627         if (debugsw)
628             admonish (NULL, "unable to fdopen annotation list");
629         goto oops;
630     }
631     cp = NULL;
632     while (fgets (buffer, sizeof(buffer), fp) != NULL)
633         cp = add (buffer, cp);
634     fclose (fp);
635
636     if (debugsw)
637         advise (NULL, "annotate%s with %s: \"%s\"",
638                 inplace ? " inplace" : "", annotext, cp);
639     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
640         if (is_selected(mp, msgnum)) {
641             if (debugsw)
642                 advise (NULL, "annotate message %d", msgnum);
643             annotate (m_name (msgnum), annotext, cp, inplace, 1);
644         }
645     }
646
647     free (cp);
648
649 oops:
650     folder_free (mp);   /* free folder/message structure */
651 }
652
653
654 int
655 done (int status)
656 {
657     if (armed)
658         longjmp (env, status ? status : NOTOK);
659
660     exit (status);
661     return 1;  /* dead code to satisfy the compiler */
662 }