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