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