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