Added an improved user interface for sending messages with attachments.
[mmh] / uip / annosbr.c
1
2 /*
3  * annosbr.c -- prepend annotation to messages
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <h/tws.h>
14 #include <fcntl.h>
15 #include <errno.h>
16
17 extern int  errno;
18
19 /*
20  * static prototypes
21  */
22 static int annosbr (int, char *, char *, char *, int, int, int, int);
23
24
25 int
26 annotate (char *file, char *comp, char *text, int inplace, int datesw, int delete, int append)
27 {
28     int i, fd;
29
30     /* open and lock the file to be annotated */
31     if ((fd = lkopen (file, O_RDWR, 0)) == NOTOK) {
32         switch (errno) {
33             case ENOENT:
34                 break;
35
36             default:
37                 admonish (file, "unable to lock and open");
38                 break;
39         }
40         return 1;
41     }
42
43     i = annosbr (fd, file, comp, text, inplace, datesw, delete, append);
44     lkclose (fd, file);
45     return i;
46 }
47
48 /*
49  *  Produce a listing of all header fields (annotations) whose field name matches
50  *  comp.  Number the listing if number is set.  Treate the field bodies as path
51  *  names and just output the last component unless text is non-NULL.  We don't
52  *  care what text is set to.
53  */
54
55 void
56 annolist(char *file, char *comp, char *text, int number)
57 {
58     int         c;              /* current character */
59     int         count;          /* header field (annotation) counter */
60     char        *cp;            /* miscellaneous character pointer */
61     char        *field;         /* buffer for header field */
62     int         field_size;     /* size of field buffer */
63     FILE        *fp;            /* file pointer made from locked file descriptor */
64     int         length;         /* length of field name */
65     int         n;              /* number of bytes written */
66     char        *sp;            /* another miscellaneous character pointer */
67
68     if ((fp = fopen(file, "r")) == (FILE *)0)
69         adios(file, "unable to open");
70
71     /*
72      *  Allocate a buffer to hold the header components as they're read in.
73      *  This buffer might need to be quite large, so we grow it as needed.
74      */
75
76     if ((field = (char *)malloc(field_size = 256)) == (char *)0)
77         adios(NULL, "can't allocate field buffer.");
78
79     /*
80      *  Get the length of the field name since we use it often.
81      */
82
83     length = strlen(comp);
84
85     count = 0;
86
87     do {
88         /*
89          *      Get a line from the input file, growing the field buffer as needed.  We do this
90          *      so that we can fit an entire line in the buffer making it easy to do a string
91          *      comparison on both the field name and the field body which might be a long path
92          *      name.
93          */
94
95         for (n = 0, cp = field; (c = getc(fp)) != EOF; *cp++ = c) {
96             if (c == '\n' && (c = getc(fp)) != ' ' && c != '\t') {
97                 (void)ungetc(c, fp);
98                 c = '\n';
99                 break;
100             }
101
102             if (++n >= field_size - 1) {
103                 if ((field = (char *)realloc((void *)field, field_size += 256)) == (char *)0)
104                     adios(NULL, "can't grow field buffer.");
105                 
106                 cp = field + n - 1;
107             }
108         }
109
110         /*
111          *      NUL-terminate the field..
112          */
113
114         *cp = '\0';
115
116         if (strncasecmp(field, comp, length) == 0 && field[length] == ':') {
117             for (cp = field + length + 1; *cp == ' ' || *cp == '\t'; cp++)
118                 ;
119
120             if (number)
121                 (void)printf("%d\t", ++count);
122
123             if (text == (char *)0 && (sp = strrchr(cp, '/')) != (char *)0)
124                 cp = sp + 1;
125
126             (void)printf("%s\n", cp);
127         }
128
129     } while (*field != '\0' && *field != '-');
130
131     /*
132      *  Clean up.
133      */
134
135     free(field);
136
137     (void)fclose(fp);
138
139     return;
140 }
141
142
143 static int
144 annosbr (int fd, char *file, char *comp, char *text, int inplace, int datesw, int delete, int append)
145 {
146     int mode, tmpfd;
147     char *cp, *sp;
148     char buffer[BUFSIZ], tmpfil[BUFSIZ];
149     struct stat st;
150     FILE        *tmp;
151     int         c;              /* current character */
152     int         count;          /* header field (annotation) counter */
153     char        *field;         /* buffer for header field */
154     int         field_size;     /* size of field buffer */
155     FILE        *fp;            /* file pointer made from locked file descriptor */
156     int         length;         /* length of field name */
157     int         n;              /* number of bytes written */
158
159     mode = fstat (fd, &st) != NOTOK ? (st.st_mode & 0777) : m_gmprot ();
160
161     strncpy (tmpfil, m_scratch (file, "annotate"), sizeof(tmpfil));
162
163     if ((tmp = fopen (tmpfil, "w")) == NULL) {
164         admonish (tmpfil, "unable to create");
165         return 1;
166     }
167     chmod (tmpfil, mode);
168
169     /*
170      *  We're going to need to copy some of the message file to the temporary
171      *  file while examining the contents.  Convert the message file descriptor
172      *  to a file pointer since it's a lot easier and more efficient to use
173      *  stdio for this.  Also allocate a buffer to hold the header components
174      *  as they're read in.  This buffer is grown as needed later.
175      */
176
177     if (delete >= 0 || append != 0) {
178         if ((fp = fdopen(fd, "r")) == (FILE *)0)
179             adios(NULL, "unable to fdopen file.");
180
181         if ((field = (char *)malloc(field_size = 256)) == (char *)0)
182             adios(NULL, "can't allocate field buffer.");
183     }
184
185     /*
186      *  We're trying to delete a header field (annotation )if the delete flag is
187      *  non-negative.  A  value greater than zero means that we're deleting the
188      *  nth header field that matches the field (component) name.  A value of
189      *  zero means that we're deleting the first field in which both the field
190      *  name matches the component name and the field body matches the text.
191      *  The text is matched in its entirety if it begins with a slash; otherwise
192      *  the text is matched against whatever portion of the field body follows
193      *  the last slash.  This allows matching of both absolute and relative path
194      *  names.  This is because this functionality was added to support attachments.
195      *  It might be worth having a separate flag to indicate path name matching to
196      *  make it more general.
197      */
198
199     if (delete >= 0) {
200         /*
201          *  Get the length of the field name since we use it often.
202          */
203
204         length = strlen(comp);
205
206         /*
207          *  Initialize the field counter.  This is only used if we're deleting by
208          *  number.
209          */
210
211         count = 0;
212
213         /*
214          *  Copy lines from the input file to the temporary file until we either find the one
215          *  that we're looking for (which we don't copy) or we reach the end of the headers.
216          *  Both a blank line and a line beginning with a - terminate the headers so that we
217          *  can handle both drafts and RFC-2822 format messages.
218          */
219
220         do {
221             /*
222              *  Get a line from the input file, growing the field buffer as needed.  We do this
223              *  so that we can fit an entire line in the buffer making it easy to do a string
224              *  comparison on both the field name and the field body which might be a long path
225              *  name.
226              */
227
228             for (n = 0, cp = field; (c = getc(fp)) != EOF; *cp++ = c) {
229                 if (c == '\n' && (c = getc(fp)) != ' ' && c != '\t') {
230                     (void)ungetc(c, fp);
231                     c = '\n';
232                     break;
233                 }
234
235                 if (++n >= field_size - 1) {
236                     if ((field = (char *)realloc((void *)field, field_size *= 2)) == (char *)0)
237                         adios(NULL, "can't grow field buffer.");
238                     
239                     cp = field + n - 1;
240                 }
241             }
242
243             /*
244              *  NUL-terminate the field..
245              */
246
247             *cp = '\0';
248
249             /*
250              *  Check for a match on the field name.  We delete the line by not copying it to the
251              *  temporary file if
252              *
253              *   o  The delete flag is 0, meaning that we're going to delete the first matching
254              *      field, and the text is NULL meaning that we don't care about the field body.
255              *
256              *   o  The delete flag is 0, meaning that we're going to delete the first matching
257              *      field, and the text begins with a / meaning that we're looking for a full
258              *      path name, and the text matches the field body.
259              *
260              *   o  The delete flag is 0, meaning that we're going to delete the first matching
261              *      field, the text does not begin with a / meaning that we're looking for the
262              *      last path name component, and the last path name component matches the text.
263              *
264              *   o  The delete flag is non-zero meaning that we're going to delete the nth field
265              *      with a matching field name, and this is the nth matching field name.
266              */
267
268             if (strncasecmp(field, comp, length) == 0 && field[length] == ':') {
269                 if (delete == 0) {
270                     if (text == (char *)0)
271                         break;
272
273                     for (cp = field + length + 1; *cp == ' ' || *cp == '\t'; cp++)
274                         ;
275
276                     if (*text == '/') {
277                         if (strcmp(cp, text) == 0)
278                                 break;
279                     }
280                     else {
281                         if ((sp = strrchr(cp, '/')) != (char *)0)
282                             cp = sp + 1;
283
284                         if (strcmp(cp, text) == 0)
285                             break;
286                     }
287                 }
288
289                 else if (++count == delete)
290                     break;
291             }
292
293             /*
294              *  This line wasn't a match so copy it to the temporary file.
295              */
296
297             if ((n = fputs(field, tmp)) == EOF || (c == '\n' && fputc('\n', tmp) == EOF))
298                 adios(NULL, "unable to write temporary file.");
299
300         } while (*field != '\0' && *field != '-');
301
302         /*
303          *  Get rid of the field buffer because we're done with it.
304          */
305
306         free((void *)field);
307     }
308
309     else {
310         /*
311          *  Find the end of the headers before adding the annotations if we're
312          *  appending instead of the default prepending.
313          */
314
315         if (append) {
316             /*
317              *  Copy lines from the input file to the temporary file until we
318              *  reach the end of the headers.
319              */
320
321             while ((c = getc(fp)) != EOF) {
322                 (void)putc(c, tmp);
323
324                 if (c == '\n') {
325                     (void)ungetc(c = getc(fp), fp);
326
327                     if (c == '\n' || c == '-')
328                         break;
329                 }
330             }
331         }
332
333         if (datesw)
334             fprintf (tmp, "%s: %s\n", comp, dtimenow (0));
335         if ((cp = text)) {
336             do {
337                 while (*cp == ' ' || *cp == '\t')
338                     cp++;
339                 sp = cp;
340                 while (*cp && *cp++ != '\n')
341                     continue;
342                 if (cp - sp)
343                     fprintf (tmp, "%s: %*.*s", comp, cp - sp, cp - sp, sp);
344             } while (*cp);
345             if (cp[-1] != '\n' && cp != text)
346                 putc ('\n', tmp);
347         }
348     }
349
350     fflush (tmp);
351
352     /*
353      *  We've been messing with the input file position.  Move the input file
354      *  descriptor to the current place in the file because the stock data
355      *  copying routine uses the descriptor, not the pointer.
356      */
357
358     if (append || delete >= 0) {
359         if (lseek(fd, (off_t)ftell(fp), SEEK_SET) == (off_t)-1)
360             adios(NULL, "can't seek.");
361     }
362
363     cpydata (fd, fileno (tmp), file, tmpfil);
364     fclose (tmp);
365
366     if (inplace) {
367         if ((tmpfd = open (tmpfil, O_RDONLY)) == NOTOK)
368             adios (tmpfil, "unable to open for re-reading");
369
370         lseek (fd, (off_t) 0, SEEK_SET);
371
372         /*
373          *  We're making the file shorter if we're deleting a header field
374          *  so the file has to be truncated or it will contain garbage.
375          */
376
377         if (delete >= 0 && ftruncate(fd, 0) == -1)
378             adios(tmpfil, "unable to truncate.");
379
380         cpydata (tmpfd, fd, tmpfil, file);
381         close (tmpfd);
382         unlink (tmpfil);
383     } else {
384         strncpy (buffer, m_backup (file), sizeof(buffer));
385         if (rename (file, buffer) == NOTOK) {
386             switch (errno) {
387                 case ENOENT:    /* unlinked early - no annotations */
388                     unlink (tmpfil);
389                     break;
390
391                 default:
392                     admonish (buffer, "unable to rename %s to", file);
393                     break;
394             }
395             return 1;
396         }
397         if (rename (tmpfil, file) == NOTOK) {
398             admonish (file, "unable to rename %s to", tmpfil);
399             return 1;
400         }
401     }
402
403     /*
404      *  Close the delete file so that we don't run out of file pointers if
405      *  we're doing piles of files.  Note that this will make the close() in
406      *  lkclose() fail, but that failure is ignored so it's not a problem.
407      */
408
409     if (delete >= 0)
410         (void)fclose(fp);
411
412     return 0;
413 }