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