Added -nocontentid (and -contentid, for symmetry) switch to mhbuild. This allows...
[mmh] / uip / flist.c
1 /*
2  * flist.c -- list nmh folders containing messages
3  *         -- in a given sequence
4  *
5  * originally by
6  * David Nichols, Xerox-PARC, November, 1992
7  *
8  * Copyright (c) 1994 Xerox Corporation.
9  * Use and copying of this software and preparation of derivative works based
10  * upon this software are permitted. Any distribution of this software or
11  * derivative works must comply with all applicable United States export
12  * control laws. This software is made available AS IS, and Xerox Corporation
13  * makes no warranty about the software, its performance or its conformity to
14  * any specification.
15  *
16  *  $Id$
17  */
18
19 #include <h/mh.h>
20 #include <h/utils.h>
21
22 #define FALSE   0
23 #define TRUE    1
24
25 /*
26  * We allocate space to record the names of folders
27  * (foldersToDo array), this number of elements at a time.
28  */
29 #define MAXFOLDERS  100
30
31
32 static struct swit switches[] = {
33 #define SEQSW           0
34     { "sequence name", 0 },
35 #define ALLSW           1
36     { "all", 0 },
37 #define NOALLSW         2
38     { "noall", 0 },
39 #define RECURSE         3
40     { "recurse", 0 },
41 #define NORECURSE       4
42     { "norecurse", 0 },
43 #define SHOWZERO        5
44     { "showzero", 0 },
45 #define NOSHOWZERO      6
46     { "noshowzero", 0 },
47 #define ALPHASW         7
48     { "alpha", 0 },
49 #define NOALPHASW       8
50     { "noalpha", 0 },
51 #define FASTSW          9
52     { "fast", 0 },
53 #define NOFASTSW        10
54     { "nofast", 0 },
55 #define TOTALSW         11
56     { "total", -5 },
57 #define NOTOTALSW       12
58     { "nototal", -7 },
59 #define VERSIONSW       13
60     { "version", 0 },
61 #define HELPSW          14
62     { "help", 0 },
63     { NULL, 0 }
64 };
65
66 struct Folder {
67     char *name;                 /* name of folder */
68     int priority;
69     int error;                  /* error == 1 for unreadable folder     */
70     int nMsgs;                  /* number of messages in folder         */
71     int nSeq[NUMATTRS];         /* number of messages in each sequence  */
72     int private[NUMATTRS];      /* is given sequence, public or private */
73 };
74
75 static struct Folder *orders = NULL;
76 static int nOrders = 0;
77 static int nOrdersAlloced = 0;
78 static struct Folder *folders = NULL;
79 static int nFolders = 0;
80 static int nFoldersAlloced = 0;
81
82 /* info on folders to search */
83 static char **foldersToDo;
84 static int numfolders;
85 static int maxfolders;
86
87 /* info on sequences to search for */
88 static char *sequencesToDo[NUMATTRS];
89 static int numsequences;
90
91 static int all        = FALSE;  /* scan all folders in top level?           */
92 static int alphaOrder = FALSE;  /* want alphabetical order only             */
93 static int recurse    = FALSE;  /* show nested folders?                     */
94 static int showzero   = TRUE;   /* show folders even if no messages in seq? */
95 static int Total      = TRUE;   /* display info on number of messages in    *
96                                  * sequence found, and total num messages   */
97
98 static char curfolder[BUFSIZ];  /* name of the current folder */
99 static char *nmhdir;            /* base nmh mail directory    */
100
101 /*
102  * Type for a compare function for qsort.  This keeps
103  * the compiler happy.
104  */
105 typedef int (*qsort_comp) (const void *, const void *);
106
107 /*
108  * prototypes
109  */
110 int CompareFolders(struct Folder *, struct Folder *);
111 void GetFolderOrder(void);
112 void ScanFolders(void);
113 int AddFolder(char *, int);
114 void BuildFolderList(char *, int);
115 void BuildFolderListRecurse(char *, struct stat *, int);
116 void PrintFolders(void);
117 static int num_digits (int);
118 void AllocFolders(struct Folder **, int *, int);
119 int AssignPriority(char *);
120 static void do_readonly_folders(void);
121
122
123
124 int
125 main(int argc, char **argv)
126 {
127     char *cp, **argp;
128     char **arguments;
129     char buf[BUFSIZ];
130
131 #ifdef LOCALE
132     setlocale(LC_ALL, "");
133 #endif
134     invo_name = r1bindex(argv[0], '/');
135
136     /* read user profile/context */
137     context_read();
138
139     /*
140      * If program was invoked with name ending
141      * in `s', then add switch `-all'.
142      */
143     if (argv[0][strlen (argv[0]) - 1] == 's')
144         all = TRUE;
145
146     arguments = getarguments (invo_name, argc, argv, 1);
147     argp = arguments;
148
149     /* allocate the initial space to record the folder names */
150     numfolders = 0;
151     maxfolders = MAXFOLDERS;
152     foldersToDo = (char **) mh_xmalloc ((size_t) (maxfolders * sizeof(*foldersToDo)));
153
154     /* no sequences yet */
155     numsequences = 0;
156
157     /* parse arguments */
158     while ((cp = *argp++)) {
159         if (*cp == '-') {
160             switch (smatch(++cp, switches)) {
161             case AMBIGSW:
162                 ambigsw(cp, switches);
163                 done(1);
164             case UNKWNSW:
165                 adios(NULL, "-%s unknown", cp);
166
167             case HELPSW:
168                 snprintf(buf, sizeof(buf), "%s [+folder1 [+folder2 ...]][switches]",
169                         invo_name);
170                 print_help(buf, switches, 1);
171                 done(1);
172             case VERSIONSW:
173                 print_version(invo_name);
174                 done (1);
175
176             case SEQSW:
177                 if (!(cp = *argp++) || *cp == '-')
178                     adios (NULL, "missing argument to %s", argp[-2]);
179
180                 /* check if too many sequences specified */
181                 if (numsequences >= NUMATTRS)
182                     adios (NULL, "too many sequences (more than %d) specified", NUMATTRS);
183                 sequencesToDo[numsequences++] = cp;
184                 break;
185
186             case ALLSW:
187                 all = TRUE;
188                 break;
189             case NOALLSW:
190                 all = FALSE;
191                 break;
192
193             case SHOWZERO:
194                 showzero = TRUE;
195                 break;
196             case NOSHOWZERO:
197                 showzero = FALSE;
198                 break;
199
200             case ALPHASW:
201                 alphaOrder = TRUE;
202                 break;
203             case NOALPHASW:
204                 alphaOrder = FALSE;
205                 break;
206
207             case NOFASTSW:
208             case TOTALSW:
209                 Total = TRUE;
210                 break;
211
212             case FASTSW:
213             case NOTOTALSW:
214                 Total = FALSE;
215                 break;
216
217             case RECURSE:
218                 recurse = TRUE;
219                 break;
220             case NORECURSE:
221                 recurse = FALSE;
222                 break;
223             }
224         } else {
225             /*
226              * Check if we need to allocate more space
227              * for folder names.
228              */
229             if (numfolders >= maxfolders) {
230                 maxfolders += MAXFOLDERS;
231                 foldersToDo = (char **) mh_xrealloc (foldersToDo,
232                     (size_t) (maxfolders * sizeof(*foldersToDo)));
233             }
234             if (*cp == '+' || *cp == '@') {
235                 foldersToDo[numfolders++] =
236                     path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
237             } else
238                 foldersToDo[numfolders++] = cp;
239         }
240     }
241
242     if (!context_find ("path"))
243         free (path ("./", TFOLDER));
244
245     /* get current folder */
246     strncpy (curfolder, getfolder(1), sizeof(curfolder));
247
248     /* get nmh base directory */
249     nmhdir = m_maildir ("");
250
251     /*
252      * If we didn't specify any sequences, we search
253      * for the "Unseen-Sequence" profile entry and use
254      * all the sequences defined there.  We check to
255      * make sure that the Unseen-Sequence entry doesn't
256      * contain more than NUMATTRS sequences.
257      */
258     if (numsequences == 0) {
259         if ((cp = context_find(usequence)) && *cp) {
260             char **ap, *dp;
261
262             dp = getcpy(cp);
263             ap = brkstring (dp, " ", "\n");
264             for (; ap && *ap; ap++) {
265                 if (numsequences >= NUMATTRS)
266                     adios (NULL, "too many sequences (more than %d) in %s profile entry",
267                            NUMATTRS, usequence);
268                 else
269                     sequencesToDo[numsequences++] = *ap;
270             }
271         } else {
272             adios (NULL, "no sequence specified or %s profile entry found", usequence);
273         }
274     }
275
276     GetFolderOrder();
277     ScanFolders();
278     qsort(folders, nFolders, sizeof(struct Folder), (qsort_comp) CompareFolders);
279     PrintFolders();
280     return done (0);
281 }
282
283 /*
284  * Read the Flist-Order profile entry to determine
285  * how to sort folders for output.
286  */
287
288 void
289 GetFolderOrder(void)
290 {
291     char *p, *s;
292     int priority = 1;
293     struct Folder *o;
294
295     if (!(p = context_find("Flist-Order")))
296         return;
297     for (;;) {
298         while (isspace(*p))
299             ++p;
300         s = p;
301         while (*p && !isspace(*p))
302             ++p;
303         if (p != s) {
304             /* Found one. */
305             AllocFolders(&orders, &nOrdersAlloced, nOrders + 1);
306             o = &orders[nOrders++];
307             o->priority = priority++;
308             o->name = (char *) mh_xmalloc(p - s + 1);
309             strncpy(o->name, s, p - s);
310             o->name[p - s] = 0;
311         } else
312             break;
313     }
314 }
315
316 /*
317  * Scan all the necessary folders
318  */
319
320 void
321 ScanFolders(void)
322 {
323     int i;
324
325     /*
326      * change directory to base of nmh directory
327      */
328     if (chdir (nmhdir) == NOTOK)
329         adios (nmhdir, "unable to change directory to");
330
331     if (numfolders > 0) {
332         /* Update context */
333         strncpy (curfolder, foldersToDo[numfolders - 1], sizeof(curfolder));
334         context_replace (pfolder, curfolder);/* update current folder */
335         context_save ();                     /* save the context file */
336
337         /*
338          * Scan each given folder.  If -all is given,
339          * then also scan the 1st level subfolders under
340          * each given folder.
341          */
342         for (i = 0; i < numfolders; ++i)
343             BuildFolderList(foldersToDo[i], all ? 1 : 0);
344     } else {
345         if (all) {
346             /*
347              * Do the readonly folders
348              */
349             do_readonly_folders();
350
351             /*
352              * Now scan the entire nmh directory for folders
353              */
354             BuildFolderList(".", 0);
355         } else {
356             /*
357              * Else scan current folder
358              */
359             BuildFolderList(curfolder, 0);
360         }
361     }
362 }
363
364 /*
365  * Initial building of folder list for
366  * the top of our search tree.
367  */
368
369 void
370 BuildFolderList(char *dirName, int searchdepth)
371 {
372     struct stat st;
373
374     /* Make sure we have a directory */
375     if ((stat(dirName, &st) == -1) || !S_ISDIR(st.st_mode))
376         return;
377
378     /*
379      * If base directory, don't add it to the
380      * folder list. We just recurse into it.
381      */
382     if (!strcmp (dirName, ".")) {
383         BuildFolderListRecurse (".", &st, 0);
384         return;
385     }
386
387     /*
388      * Add this folder to the list.
389      * If recursing and directory has subfolders,
390      * then build folder list for subfolders.
391      */
392     if (AddFolder(dirName, showzero) && (recurse || searchdepth) && st.st_nlink > 2)
393         BuildFolderListRecurse(dirName, &st, searchdepth - 1);
394 }
395
396 /*
397  * Recursive building of folder list
398  */
399
400 void
401 BuildFolderListRecurse(char *dirName, struct stat *s, int searchdepth)
402 {
403     char *base, *n, name[PATH_MAX];
404     int nlinks;
405     DIR *dir;
406     struct dirent *dp;
407     struct stat st;
408
409     /*
410      * Keep track of number of directories we've seen so we can
411      * stop stat'ing entries in this directory once we've seen
412      * them all.  This optimization will fail if you have extra
413      * directories beginning with ".", since we don't bother to
414      * stat them.  But that shouldn't generally be a problem.
415      */
416     nlinks = s->st_nlink;
417
418     if (!(dir = opendir(dirName)))
419         adios(dirName, "can't open directory");
420
421     /*
422      * A hack so that we don't see a
423      * leading "./" in folder names.
424      */
425     base = strcmp (dirName, ".") ? dirName : dirName + 1;
426
427     while (nlinks && (dp = readdir(dir))) {
428         if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
429             nlinks--;
430             continue;
431         }
432         if (dp->d_name[0] == '.')
433             continue;
434         /* Check to see if the name of the file is a number
435          * if it is, we assume it's a mail file and skip it
436          */
437         for (n = dp->d_name; *n && isdigit(*n); n++);
438         if (!*n)
439             continue;
440         strncpy (name, base, sizeof(name) - 2);
441         if (*base)
442             strcat(name, "/");
443         strncat(name, dp->d_name, sizeof(name) - strlen(name) - 1);
444         if ((stat(name, &st) != -1) && S_ISDIR(st.st_mode)) {
445             /*
446              * Check if this was really a symbolic link pointing
447              * to a directory.  If not, then decrement link count.
448              */
449             if (lstat (name, &st) == -1)
450                 nlinks--;
451             /* Add this folder to the list */
452             if (AddFolder(name, showzero) &&
453                         (recurse || searchdepth) && st.st_nlink > 2)
454                 BuildFolderListRecurse(name, &st, searchdepth - 1);
455         }
456     }
457     closedir(dir);
458 }
459
460 /*
461  * Add this folder to our list, counting the total number of
462  * messages and the number of messages in each sequence.
463  */
464
465 int
466 AddFolder(char *name, int force)
467 {
468     int i, msgnum, nonzero;
469     int seqnum[NUMATTRS], nSeq[NUMATTRS];
470     struct Folder *f;
471     struct msgs *mp;
472
473     /* Read folder and create message structure */
474     if (!(mp = folder_read (name))) {
475         /* Oops, error occurred.  Record it and continue. */
476         AllocFolders(&folders, &nFoldersAlloced, nFolders + 1);
477         f = &folders[nFolders++];
478         f->name = getcpy(name);
479         f->error = 1;
480         f->priority = AssignPriority(f->name);
481         return 0;
482     }
483
484     for (i = 0; i < numsequences; i++) {
485         /* Convert sequences to their sequence numbers */
486         if (sequencesToDo[i])
487             seqnum[i] = seq_getnum(mp, sequencesToDo[i]);
488         else
489             seqnum[i] = -1;
490
491         /* Now count messages in this sequence */
492         nSeq[i] = 0;
493         if (mp->nummsg > 0 && seqnum[i] != -1) {
494             for (msgnum = mp->lowmsg; msgnum <= mp->hghmsg; msgnum++) {
495                 if (in_sequence(mp, seqnum[i], msgnum))
496                     nSeq[i]++;
497             }
498         }
499     }
500
501     /* Check if any of the sequence checks were nonzero */
502     nonzero = 0;
503     for (i = 0; i < numsequences; i++) {
504         if (nSeq[i] > 0) {
505             nonzero = 1;
506             break;
507         }
508     }
509
510     if (nonzero || force) {
511         /* save general folder information */
512         AllocFolders(&folders, &nFoldersAlloced, nFolders + 1);
513         f = &folders[nFolders++];
514         f->name = getcpy(name);
515         f->nMsgs = mp->nummsg;
516         f->error = 0;
517         f->priority = AssignPriority(f->name);
518
519         /* record the sequence information */
520         for (i = 0; i < numsequences; i++) {
521             f->nSeq[i] = nSeq[i];
522             f->private[i] = (seqnum[i] != -1) ? is_seq_private(mp, seqnum[i]) : 0;
523         }
524     }
525
526     folder_free (mp);   /* free folder/message structure */
527     return 1;
528 }
529
530 /*
531  * Print the folder/sequence information
532  */
533
534 void
535 PrintFolders(void)
536 {
537     char tmpname[BUFSIZ];
538     int i, j, len, has_private = 0;
539     int maxfolderlen = 0, maxseqlen = 0;
540     int maxnum = 0, maxseq = 0;
541
542     if (!Total) {
543         for (i = 0; i < nFolders; i++)
544             printf("%s\n", folders[i].name);
545         return;
546     }
547
548     /*
549      * Find the width we need for various fields
550      */
551     for (i = 0; i < nFolders; ++i) {
552         /* find the length of longest folder name */
553         len = strlen(folders[i].name);
554         if (len > maxfolderlen)
555             maxfolderlen = len;
556
557         /* If folder had error, skip the rest */
558         if (folders[i].error)
559             continue;
560
561         /* find the maximum total messages */
562         if (folders[i].nMsgs > maxnum)
563             maxnum = folders[i].nMsgs;
564
565         for (j = 0; j < numsequences; j++) {
566             /* find maximum width of sequence name */
567             len = strlen (sequencesToDo[j]);
568             if ((folders[i].nSeq[j] > 0 || showzero) && (len > maxseqlen))
569                 maxseqlen = len;
570
571             /* find the maximum number of messages in sequence */
572             if (folders[i].nSeq[j] > maxseq)
573                 maxseq = folders[i].nSeq[j];
574
575             /* check if this sequence is private in any of the folders */
576             if (folders[i].private[j])
577                 has_private = 1;
578         }
579     }
580
581     /* Now print all the folder/sequence information */
582     for (i = 0; i < nFolders; i++) {
583         for (j = 0; j < numsequences; j++) {
584             if (folders[i].nSeq[j] > 0 || showzero) {
585                 /* Add `+' to end of name of current folder */
586                 if (strcmp(curfolder, folders[i].name))
587                     snprintf(tmpname, sizeof(tmpname), "%s", folders[i].name);
588                 else
589                     snprintf(tmpname, sizeof(tmpname), "%s+", folders[i].name);
590
591                 if (folders[i].error) {
592                     printf("%-*s is unreadable\n", maxfolderlen+1, tmpname);
593                     continue;
594                 }
595
596                 printf("%-*s has %*d in sequence %-*s%s; out of %*d\n",
597                        maxfolderlen+1, tmpname,
598                        num_digits(maxseq), folders[i].nSeq[j],
599                        maxseqlen, sequencesToDo[j],
600                        !has_private ? "" : folders[i].private[j] ? " (private)" : "          ",
601                        num_digits(maxnum), folders[i].nMsgs);
602             }
603         }
604     }
605 }
606
607 /*
608  * Calculate the number of digits in a nonnegative integer
609  */
610 static int
611 num_digits (int n)
612 {
613     int ndigits = 0;
614
615     /* Sanity check */
616     if (n < 0)
617         adios (NULL, "oops, num_digits called with negative value");
618
619     if (n == 0)
620         return 1;
621
622     while (n) {
623         n /= 10;
624         ndigits++;
625     }
626
627     return ndigits;
628 }
629
630 /*
631  * Put them in priority order.
632  */
633
634 int
635 CompareFolders(struct Folder *f1, struct Folder *f2)
636 {
637     if (!alphaOrder && f1->priority != f2->priority)
638         return f1->priority - f2->priority;
639     else
640         return strcmp(f1->name, f2->name);
641 }
642
643 /*
644  * Make sure we have at least n folders allocated.
645  */
646
647 void
648 AllocFolders(struct Folder **f, int *nfa, int n)
649 {
650     if (n <= *nfa)
651         return;
652     if (*f == NULL) {
653         *nfa = 10;
654         *f = (struct Folder *) mh_xmalloc (*nfa * (sizeof(struct Folder)));
655     } else {
656         *nfa *= 2;
657         *f = (struct Folder *) mh_xrealloc (*f, *nfa * (sizeof(struct Folder)));
658     }
659 }
660
661 /*
662  * Return the priority for a name.  The highest comes from an exact match.
663  * After that, the longest match (then first) assigns the priority.
664  */
665 int
666 AssignPriority(char *name)
667 {
668     int i, ol, nl;
669     int best = nOrders;
670     int bestLen = 0;
671     struct Folder *o;
672
673     nl = strlen(name);
674     for (i = 0; i < nOrders; ++i) {
675         o = &orders[i];
676         if (!strcmp(name, o->name))
677             return o->priority;
678         ol = strlen(o->name);
679         if (nl < ol - 1)
680             continue;
681         if (ol < bestLen)
682             continue;
683         if (o->name[0] == '*' && !strcmp(o->name + 1, name + (nl - ol + 1))) {
684             best = o->priority;
685             bestLen = ol;
686         } else if (o->name[ol - 1] == '*' && strncmp(o->name, name, ol - 1) == 0) {
687             best = o->priority;
688             bestLen = ol;
689         }
690     }
691     return best;
692 }
693
694 /*
695  * Do the read only folders
696  */
697
698 static void
699 do_readonly_folders (void)
700 {
701     int atrlen;
702     char atrcur[BUFSIZ];
703     register struct node *np;
704
705     snprintf (atrcur, sizeof(atrcur), "atr-%s-", current);
706     atrlen = strlen (atrcur);
707
708     for (np = m_defs; np; np = np->n_next)
709         if (ssequal (atrcur, np->n_name)
710                 && !ssequal (nmhdir, np->n_name + atrlen))
711             BuildFolderList (np->n_name + atrlen, 0);
712 }