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