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