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