7a65a7fc725cdc868b3860e6905f961b2915c1a0
[mmh] / uip / anno.c
1 /*
2 ** anno.c -- annotate messages
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 **
8 ** Three new options have been added: delete, list, and number. Adding
9 ** features to generalize the anno command seemed to be a better approach
10 ** than the creation of a new command whose features would overlap with
11 ** those of the anno command.
12 */
13
14 #include <h/mh.h>
15 #include <h/utils.h>
16 #include <h/tws.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <utime.h>
20 #include <unistd.h>
21 #include <ctype.h>
22 #include <sys/stat.h>
23 #include <locale.h>
24
25 static enum { MODE_ADD, MODE_DEL, MODE_LIST } mode = MODE_ADD;
26
27 static struct swit switches[] = {
28 #define COMPSW 0
29         { "component field", 0 },
30 #define DATESW 1
31         { "date", 0 },
32 #define NDATESW 2
33         { "nodate", 2 },
34 #define TEXTSW 3
35         { "text body", 0 },
36 #define VERSIONSW 4
37         { "Version", 0 },
38 #define HELPSW 5
39         { "help", 0 },
40 #define LISTSW 6
41         { "list", 0 },
42 #define DELETESW 7
43         { "delete", 0 },
44 #define NUMBERSW 8
45         { "number", 0 },
46 #define APPENDSW 9
47         { "append", 0 },
48 #define PRESERVESW 10
49         { "preserve", 0 },
50 #define NOPRESERVESW 11
51         { "nopreserve", 2 },
52         { NULL, 0 }
53 };
54
55 /*
56 ** static prototypes
57 */
58 static void make_comp(unsigned char **);
59 static int annotate(char *, unsigned char *, char *, int, int, int, int);
60 static void annolist(char *, unsigned char *, int);
61 static void dodel(int, unsigned char *, char *, FILE *, int);
62 static void doadd(int, unsigned char *, char *, FILE *, int, int);
63
64
65 int
66 main(int argc, char **argv)
67 {
68         int datesw = 1;
69         int preserve = 0;
70         int msgnum;
71         char *cp, *maildir;
72         unsigned char *comp = NULL;
73         char *text = NULL, *folder = NULL, buf[BUFSIZ];
74         char *file = NULL;
75         char **argp, **arguments;
76         struct msgs_array msgs = { 0, 0, NULL };
77         struct msgs *mp;
78         int append = 0;  /* append annotations instead of default prepend */
79         int number = 0; /* delete specific number of like elements if set */
80
81         setlocale(LC_ALL, "");
82         invo_name = mhbasename(argv[0]);
83         context_read();
84
85         arguments = getarguments(invo_name, argc, argv, 1);
86         argp = arguments;
87
88         while ((cp = *argp++)) {
89                 if (*cp == '-') {
90                         switch (smatch(++cp, switches)) {
91                         case AMBIGSW:
92                                 ambigsw(cp, switches);
93                                 /* sysexits.h EX_USAGE */
94                                 exit(1);
95                         case UNKWNSW:
96                                 adios(NULL, "-%s unknown", cp);
97
98                         case HELPSW:
99                                 snprintf(buf, sizeof(buf),
100                                         "%s [+folder] [msgs] [switches]",
101                                         invo_name);
102                                 print_help(buf, switches, 1);
103                                 exit(0);
104                         case VERSIONSW:
105                                 print_version(invo_name);
106                                 exit(0);
107
108                         case DELETESW:  /* delete annotations */
109                                 mode = MODE_DEL;
110                                 continue;
111
112                         case LISTSW:  /* produce a listing */
113                                 mode = MODE_LIST;
114                                 continue;
115
116                         case COMPSW:
117                                 if (comp)
118                                         adios(NULL, "only one component at a time!");
119                                 if (!(comp = *argp++) || *comp == '-')
120                                         adios(NULL, "missing argument to %s",
121                                                         argp[-2]);
122                                 continue;
123
124                         case TEXTSW:
125                                 if (text)
126                                         adios(NULL, "only one body at a time!");
127                                 if (!(text = *argp++) || *text == '-')
128                                         adios(NULL, "missing argument to %s",
129                                                         argp[-2]);
130                                 continue;
131
132                         case NUMBERSW: /* number listing or delete by number */
133                                 if (mode == MODE_ADD) {
134                                         adios(NULL, "-number switch must appear after -list or -delete, only.");
135                                 }
136                                 if (mode == MODE_LIST) {
137                                         number = 1;
138                                         continue;
139                                 }
140                                 /* MODE_DEL */
141                                 if (number) {
142                                         adios(NULL, "only one number at a time!");
143                                 }
144                                 if (*argp && strcmp(*argp, "all")==0) {
145                                         number = -1;
146                                         argp++;
147                                         continue;
148                                 }
149                                 if (!*argp || !(number = atoi(*argp))) {
150                                         adios(NULL, "missing argument to %s",
151                                                         argp[-1]);
152                                 }
153                                 if (number < 0) {
154                                         adios(NULL, "invalid number (%d).",
155                                                         number);
156                                 }
157                                 argp++;
158                                 continue;
159
160                         case DATESW:
161                                 datesw++;
162                                 continue;
163                         case NDATESW:
164                                 datesw = 0;
165                                 continue;
166
167                         case APPENDSW:
168                                 append = 1;
169                                 continue;
170
171                         case PRESERVESW:
172                                 preserve = 1;
173                                 continue;
174
175                         case NOPRESERVESW:
176                                 preserve = 0;
177                                 continue;
178                         }
179                 }
180                 if (*cp == '+' || *cp == '@') {
181                         if (folder)
182                                 adios(NULL, "only one folder at a time!");
183                         else
184                                 folder = getcpy(expandfol(cp));
185                 } else if (*cp == '/' || *cp == '.') {
186                         if (file)
187                                 adios(NULL, "only one file at a time!");
188                         file = cp;
189                 } else {
190                         app_msgarg(&msgs, cp);
191                 }
192         }
193
194         if (file && (folder || msgs.size)) {
195                 adios(NULL, "Don't intermix files and messages.");
196         }
197         if (!datesw && !text) {
198                 adios(NULL, "-nodate without -text is a no-op.");
199         }
200         if (number && text) {
201                 adios(NULL, "Don't combine -number with -text.");
202         }
203
204         if (file) {
205                 if (mode == MODE_LIST)
206                         annolist(file, comp, number);
207                 else
208                         annotate(file, comp, text, datesw, number,
209                                         append, preserve);
210                 exit(0);
211         }
212
213         if (!msgs.size)
214                 app_msgarg(&msgs, seq_cur);
215         if (!folder)
216                 folder = getcurfol();
217         maildir = toabsdir(folder);
218
219         if (chdir(maildir) == NOTOK)
220                 adios(maildir, "unable to change directory to");
221
222         /* read folder and create message structure */
223         if (!(mp = folder_read(folder)))
224                 adios(NULL, "unable to read folder %s", folder);
225
226         /* check for empty folder */
227         if (mp->nummsg == 0)
228                 adios(NULL, "no messages in %s", folder);
229
230         /* parse all the message ranges/sequences and set SELECTED */
231         for (msgnum = 0; msgnum < msgs.size; msgnum++) {
232                 if (!m_convert(mp, msgs.msgs[msgnum])) {
233                         /* sysexits.h EX_USAGE */
234                         exit(1);
235                 }
236         }
237
238         /* annotate all the SELECTED messages */
239         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
240                 if (is_selected(mp, msgnum)) {
241                         if (mode == MODE_LIST)
242                                 annolist(m_name(msgnum), comp, number);
243                         else
244                                 annotate(m_name(msgnum), comp, text, datesw,
245                                                 number, append, preserve);
246                 }
247         }
248
249         context_replace(curfolder, folder);
250         seq_setcur(mp, mp->lowsel);
251         seq_save(mp);
252         folder_free(mp);
253         context_save();
254         return 0;
255 }
256
257 static void
258 make_comp(unsigned char **ap)
259 {
260         unsigned char *cp;
261         char buffer[BUFSIZ];
262
263         if (!*ap) {
264                 printf("Enter component name: ");
265                 fflush(stdout);
266
267                 if (!fgets(buffer, sizeof buffer, stdin)) {
268                         /* sysexits.h EX_IOERR */
269                         exit(1);
270                 }
271                 *ap = trimcpy(buffer);
272         }
273
274         if ((cp = *ap + strlen(*ap) - 1) > *ap && *cp == ':')
275                 *cp = '\0';
276         if (strlen(*ap) == 0)
277                 adios(NULL, "null component name");
278         if (**ap == '-')
279                 adios(NULL, "invalid component name %s", *ap);
280         if (strlen(*ap) >= NAMESZ)
281                 adios(NULL, "too large component name %s", *ap);
282
283         for (cp = *ap; *cp; cp++)
284                 if (!isalnum(*cp) && *cp != '-')
285                         adios(NULL, "invalid component name %s", *ap);
286 }
287
288
289 /*
290 **  Produce a listing of all header fields (annotations) whose field
291 **  name matches comp.  Number the listing if number is set.
292 */
293 static void
294 annolist(char *file, unsigned char *comp, int number)
295 {
296         int c;
297         int count = 1;  /* header field (annotation) counter */
298         char *cp;
299         char *field;
300         int field_size;
301         FILE *fp;
302         int length;
303         int n;  /* number of bytes written */
304
305         if ((fp = fopen(file, "r")) == NULL) {
306                 adios(file, "unable to open");
307         }
308
309         /* We'll grow this buffer as needed. */
310         field = (char *)mh_xmalloc(field_size = 256);
311
312         make_comp(&comp);
313         length = strlen(comp); /* Convenience copy. */
314
315         do {
316                 /*
317                 ** Get a line from the input file, growing the field buffer
318                 ** as needed.  We do this so that we can fit an entire line
319                 ** in the buffer making it easy to do a string comparison
320                 ** on both the field name and the field body which might be
321                 ** a long path name.
322                 */
323                 for (n = 0, cp = field; (c = getc(fp)) != EOF; *cp++ = c) {
324                         if (c == '\n' && (c = getc(fp)) != ' ' && c != '\t') {
325                                 ungetc(c, fp);
326                                 c = '\n';
327                                 break;
328                         }
329                         if (++n >= field_size - 1) {
330                                 field = (char *)mh_xrealloc(field,
331                                                 field_size += 256);
332                                 cp = field + n - 1;
333                         }
334                 }
335                 *cp = '\0';
336
337                 if (strncasecmp(field, comp, length)==0 &&
338                                 field[length] == ':') {
339                         cp = trim(field + length + 1);
340                         if (number) {
341                                 printf("%d\t", count++);
342                         }
343                         printf("%s\n", cp);
344                 }
345
346         } while (*field && *field != '-');
347
348         free(field);
349         fclose(fp);
350
351         return;
352 }
353
354
355 static int
356 annotate(char *file, unsigned char *comp, char *text, int datesw,
357                 int number, int append, int preserve)
358 {
359         int fd;
360         struct utimbuf b;
361         int perms, tmpfd;
362         char tmpfil[BUFSIZ];
363         struct stat st;
364         FILE *tmp;
365
366         /* open and lock the file to be annotated */
367         if ((fd = lkopen(file, O_RDWR, 0)) == NOTOK) {
368                 switch (errno) {
369                 case ENOENT:
370                         break;
371                 default:
372                         admonish(file, "unable to lock and open");
373                         break;
374                 }
375                 return 1;
376         }
377
378         if (stat(file, &st) == -1) {
379                 advise("can't get access and modification times for %s", file);
380                 preserve = 0;
381         }
382         b.actime = st.st_atime;
383         b.modtime = st.st_mtime;
384
385         perms = fstat(fd, &st) != NOTOK ?
386                         (int)(st.st_mode & 0777) : m_gmprot();
387
388         strncpy(tmpfil, m_mktemp2(file, "annotate", NULL, &tmp),
389                         sizeof(tmpfil));
390         chmod(tmpfil, perms);
391
392         make_comp(&comp);
393
394         if (mode == MODE_DEL) {
395                 dodel(fd, comp, text, tmp, number);
396         }
397         if (mode == MODE_ADD) {
398                 doadd(fd, comp, text, tmp, datesw, append);
399         }
400
401         cpydata(fd, fileno(tmp), file, tmpfil);
402         fclose(tmp);
403
404         if ((tmpfd = open(tmpfil, O_RDONLY)) == NOTOK) {
405                 adios(tmpfil, "unable to open for re-reading");
406         }
407         lseek(fd, (off_t) 0, SEEK_SET);
408
409         /*
410         **  We're making the file shorter if we're deleting a header field
411         **  so the file has to be truncated or it will contain garbage.
412         */
413         if (mode == MODE_DEL && ftruncate(fd, 0) == -1) {
414                 adios(tmpfil, "unable to truncate.");
415         }
416         cpydata(tmpfd, fd, tmpfil, file);
417         close(tmpfd);
418         unlink(tmpfil);
419
420         if (preserve && utime(file, &b) == -1) {
421                 advise("can't set access and modification times for %s", file);
422         }
423         lkclose(fd, file);
424         return 0;
425 }
426
427 /*
428 ** We're trying to delete a header field (annotation).
429 **
430 ** - If number is greater than zero,
431 **   we're deleting the nth header field that matches
432 **   the field (component) name.
433 ** - If number is zero and text is NULL,
434 **   we're deleting the first field in which the field name
435 **   matches the component name.
436 ** - If number is zero and text is set,
437 **   we're deleting the first field in which both the field name
438 **   matches the component name and the field body matches the text.
439 ** - If number is -1,
440 **   we delete all matching fields.
441 */
442 static void
443 dodel(int fd, unsigned char *comp, char *text, FILE *tmp, int number)
444 {
445         int length = strlen(comp);  /* convenience copy */
446         int count = 1;  /* Number of matching header line. */
447         int c, n;
448         char *cp;
449         char *field = NULL;
450         int field_size = 256;
451         FILE *fp;
452
453         /*
454         ** We're going to need to copy some of the message file to the
455         ** temporary file while examining the contents.  Convert the
456         ** message file descriptor to a file pointer since it's a lot
457         ** easier and more efficient to use stdio for this.  Also allocate
458         ** a buffer to hold the header components as they're read in.
459         ** This buffer is grown as needed later.
460         */
461         if ((fp = fdopen(fd, "r")) == NULL) {
462                 adios(NULL, "unable to fdopen file.");
463         }
464         field = (char *)mh_xmalloc(field_size);
465
466         /*
467         **  Copy lines from the input file to the temporary file
468         **  until we either find the one that we're looking
469         **  for (which we don't copy) or we reach the end of
470         **  the headers.  Both a blank line and a line beginning
471         **  with a - terminate the headers so that we can handle
472         **  both drafts and RFC-2822 format messages.
473         */
474         do {
475                 /*
476                 ** Get a line from the input file, growing the
477                 ** field buffer as needed.  We do this so that
478                 ** we can fit an entire line in the buffer making
479                 ** it easy to do a string comparison on both the
480                 ** field name and the field body which might be
481                 ** a long path name.
482                 */
483                 for (n=0, cp=field; (c=getc(fp)) != EOF; *cp++ = c) {
484                         if (c == '\n' && (c = getc(fp)) != ' ' &&
485                                         c != '\t') {
486                                 ungetc(c, fp);
487                                 c = '\n';
488                                 break;
489                         }
490
491                         if (++n >= field_size - 1) {
492                                 field = (char *) mh_xrealloc(field,
493                                                 field_size *= 2);
494                                 cp = field + n - 1;
495                         }
496                 }
497                 *cp = '\0';
498
499                 if (strncasecmp(field, comp, length)==0 &&
500                                 field[length] == ':') {
501                         /*
502                         ** This component matches and thus is a candidate.
503                         ** We delete the line by not copying it to the
504                         ** temporary file. Thus:
505                         ** - Break if we've found the one to delete.
506                         ** - Continue if this is one to delete, but
507                         **   there'll be further ones.
508                         */
509
510                         if (!number && !text) {
511                                 /* this first one is it */
512                                 break;
513                         }
514
515                         if (number == -1) {
516                                 /* delete all of them */
517                                 continue;
518                         } else if (number == count++) {
519                                 /* delete this specific one */
520                                 break;
521                         }
522
523                         if (text) {
524                                 /* delete the first matching one */
525                                 cp = field+length+1;
526                                 while (*cp==' ' || *cp=='\t') {
527                                         cp++;  /* eat leading whitespace */
528                                 }
529                                 if (*text == '/' && strcmp(text, cp)==0) {
530                                         break;  /* full path matches */
531                                 } else if (strcmp(text, mhbasename(cp))==0) {
532                                         break;  /* basename matches */
533                                 }
534                         }
535                         /*
536                         ** Although the compoment name mached, it
537                         ** wasn't the right one.
538                         */
539                 }
540
541                 /* Copy it. */
542                 if ((n = fputs(field, tmp)) == EOF ||
543                                 (c=='\n' && fputc('\n', tmp)==EOF)) {
544                         adios(NULL, "unable to write temporary file.");
545                 }
546
547         } while (*field && *field != '-');
548
549         free(field);
550
551         fflush(tmp);
552         fflush(fp); /* The underlying fd will be closed by lkclose() */
553
554         /*
555         ** We've been messing with the input file position.  Move the
556         ** input file descriptor to the current place in the file
557         ** because the stock data copying routine uses the descriptor,
558         ** not the pointer.
559         */
560         if (lseek(fd, (off_t)ftell(fp), SEEK_SET) == (off_t)-1) {
561                 adios(NULL, "can't seek.");
562         }
563 }
564
565
566 static void
567 doadd(int fd, unsigned char *comp, char *text, FILE *tmp, int datesw,
568                 int append)
569 {
570         char *cp, *sp;
571         int c;
572         FILE *fp = NULL;
573
574         if (append) {
575                 /*
576                 ** We're going to need to copy some of the message
577                 ** file to the temporary file while examining the
578                 ** contents.  Convert the message file descriptor to
579                 ** a file pointer since it's a lot easier and more
580                 ** efficient to use stdio for this.  Also allocate
581                 ** a buffer to hold the header components as they're
582                 ** read in.  This buffer is grown as needed later.
583                 */
584                 if ((fp = fdopen(fd, "r")) == NULL) {
585                         adios(NULL, "unable to fdopen file.");
586                 }
587                 /* Find the end of the headers. */
588                 if ((c = getc(fp)) == '\n') {
589                         /* Special check for no headers is needed. */
590                         rewind(fp);
591                 } else {
592                         /*
593                         ** Copy lines from the input file to the
594                         ** temporary file until we reach the end
595                         ** of the headers.
596                         */
597                         putc(c, tmp);
598                         while ((c = getc(fp)) != EOF) {
599                                 putc(c, tmp);
600                                 if (c == '\n') {
601                                         ungetc(c = getc(fp), fp);
602                                         if (c == '\n' || c == '-') {
603                                                 break;
604                                         }
605                                 }
606                         }
607                 }
608         }
609
610         if (datesw) {
611                 fprintf(tmp, "%s: %s\n", comp, dtimenow());
612         }
613         if ((cp = text)) {
614                 /* Add body text header */
615                 do {
616                         while (*cp == ' ' || *cp == '\t') {
617                                 cp++;
618                         }
619                         sp = cp;
620                         while (*cp && *cp++ != '\n') {
621                                 continue;
622                         }
623                         if (cp - sp) {
624                                 fprintf(tmp, "%s: %*.*s", comp,
625                                         (int)(cp - sp),
626                                         (int)(cp - sp), sp);
627                         }
628                 } while (*cp);
629                 if (cp[-1] != '\n' && cp != text) {
630                         putc('\n', tmp);
631                 }
632         }
633         fflush(tmp);
634
635         /*
636         ** We've been messing with the input file position.  Move the
637         ** input file descriptor to the current place in the file
638         ** because the stock data copying routine uses the descriptor,
639         ** not the pointer.
640         */
641         if (append) {
642                 if (lseek(fd, (off_t)ftell(fp), SEEK_SET) == (off_t)-1) {
643                         adios(NULL, "can't seek.");
644                 }
645         }
646 }