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