Renamed all standard sequences (e.g. cur->c) and made them globally changeable
[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 no sequences specified, we use the `unseen' sequence(s)
246         ** We check to make sure that the Unseen-Sequence entry doesn't
247         ** contain too many sequences.
248         */
249         if (numsequences == 0) {
250                 char **ap, *dp;
251
252                 if ((cp = context_find(usequence))) {
253                         if (!*cp) {
254                                 adios(NULL, "profile entry %s set, but empty, and no sequence given", usequence);
255                         }
256                 } else {
257                         cp = seq_unseen;  /* use default */
258                 }
259                 dp = getcpy(cp);
260                 ap = brkstring(dp, " ", "\n");
261                 for (; ap && *ap; ap++) {
262                         if (numsequences >= NUMATTRS) {
263                                 adios(NULL, "too many sequences (more than %d) in %s profile entry", NUMATTRS, usequence);
264                         } else {
265                                 sequencesToDo[numsequences++] = *ap;
266                         }
267                 }
268         }
269
270         GetFolderOrder();
271         ScanFolders();
272         qsort(folders, nFolders, sizeof(struct Folder),
273                         (qsort_comp) CompareFolders);
274         PrintFolders();
275         done(0);
276         return 1;
277 }
278
279 /*
280 ** Read the Flist-Order profile entry to determine
281 ** how to sort folders for output.
282 */
283
284 void
285 GetFolderOrder(void)
286 {
287         unsigned char *p, *s;
288         int priority = 1;
289         struct Folder *o;
290
291         if (!(p = context_find("Flist-Order")))
292                 return;
293         for (;;) {
294                 while (isspace(*p))
295                         ++p;
296                 s = p;
297                 while (*p && !isspace(*p))
298                         ++p;
299                 if (p != s) {
300                         /* Found one. */
301                         AllocFolders(&orders, &nOrdersAlloced, nOrders + 1);
302                         o = &orders[nOrders++];
303                         o->priority = priority++;
304                         o->name = (char *) mh_xmalloc(p - s + 1);
305                         strncpy(o->name, s, p - s);
306                         o->name[p - s] = 0;
307                 } else
308                         break;
309         }
310 }
311
312 /*
313 ** Scan all the necessary folders
314 */
315
316 void
317 ScanFolders(void)
318 {
319         int i;
320
321         /*
322          * change directory to base of nmh directory
323          */
324         if (chdir(nmhdir) == NOTOK)
325                 adios(nmhdir, "unable to change directory to");
326
327         if (numfolders > 0) {
328                 /* Update context */
329                 strncpy(curfol, foldersToDo[numfolders - 1], sizeof(curfol));
330                 context_replace(curfolder, curfol); /* update current folder */
331                 context_save();  /* save the context file */
332
333                 /*
334                 ** Scan each given folder.  If -all is given,
335                 ** then also scan the 1st level subfolders under
336                 ** each given folder.
337                 */
338                 for (i = 0; i < numfolders; ++i)
339                         BuildFolderList(foldersToDo[i], all ? 1 : 0);
340         } else {
341                 if (all) {
342                         /* Do the readonly folders */
343                         do_readonly_folders();
344
345                         /* Now scan the entire nmh directory for folders */
346                         BuildFolderList(".", 0);
347                 } else {
348                         /* Else scan current folder */
349                         BuildFolderList(curfol, 0);
350                 }
351         }
352 }
353
354 /*
355 ** Initial building of folder list for
356 ** the top of our search tree.
357 */
358
359 void
360 BuildFolderList(char *dirName, int searchdepth)
361 {
362         struct stat st;
363
364         /* Make sure we have a directory */
365         if ((stat(dirName, &st) == -1) || !S_ISDIR(st.st_mode))
366                 return;
367
368         /*
369         ** If base directory, don't add it to the
370         ** folder list. We just recurse into it.
371         */
372         if (!strcmp(dirName, ".")) {
373                 BuildFolderListRecurse(".", &st, 0);
374                 return;
375         }
376
377         /*
378         ** Add this folder to the list.
379         ** If recursing and directory has subfolders,
380         ** then build folder list for subfolders.
381         */
382         if (AddFolder(dirName, showzero) && (recurse || searchdepth) &&
383                         st.st_nlink > 2)
384                 BuildFolderListRecurse(dirName, &st, searchdepth - 1);
385 }
386
387 /*
388 ** Recursive building of folder list
389 */
390
391 void
392 BuildFolderListRecurse(char *dirName, struct stat *s, int searchdepth)
393 {
394         char *base, name[PATH_MAX];
395         unsigned char *n;
396         int nlinks;
397         DIR *dir;
398         struct dirent *dp;
399         struct stat st;
400
401         /*
402         ** Keep track of number of directories we've seen so we can
403         ** stop stat'ing entries in this directory once we've seen
404         ** them all.  This optimization will fail if you have extra
405         ** directories beginning with ".", since we don't bother to
406         ** stat them.  But that shouldn't generally be a problem.
407         */
408         nlinks = s->st_nlink;
409
410         if (!(dir = opendir(dirName)))
411                 adios(dirName, "can't open directory");
412
413         /*
414         ** A hack so that we don't see a
415         ** leading "./" in folder names.
416         */
417         base = strcmp(dirName, ".") ? dirName : dirName + 1;
418
419         while (nlinks && (dp = readdir(dir))) {
420                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
421                         nlinks--;
422                         continue;
423                 }
424                 if (dp->d_name[0] == '.')
425                         continue;
426                 /* Check to see if the name of the file is a number
427                 ** if it is, we assume it's a mail file and skip it
428                 */
429                 for (n = dp->d_name; *n && isdigit(*n); n++);
430                 if (!*n)
431                         continue;
432                 strncpy(name, base, sizeof(name) - 2);
433                 if (*base)
434                         strcat(name, "/");
435                 strncat(name, dp->d_name, sizeof(name) - strlen(name) - 1);
436                 if ((stat(name, &st) != -1) && S_ISDIR(st.st_mode)) {
437                         /*
438                         ** Check if this was really a symbolic link pointing
439                         ** to a directory.  If not, then decrement link count.
440                         */
441                         if (lstat(name, &st) == -1)
442                                 nlinks--;
443                         /* Add this folder to the list */
444                         if (AddFolder(name, showzero) &&
445                                         (recurse || searchdepth) &&
446                                         st.st_nlink > 2)
447                                 BuildFolderListRecurse(name, &st,
448                                                 searchdepth - 1);
449                 }
450         }
451         closedir(dir);
452 }
453
454 /*
455 ** Add this folder to our list, counting the total number of
456 ** messages and the number of messages in each sequence.
457 */
458
459 int
460 AddFolder(char *name, int force)
461 {
462         int i, msgnum, nonzero;
463         int seqnum[NUMATTRS], nSeq[NUMATTRS];
464         struct Folder *f;
465         struct msgs *mp;
466
467         /* Read folder and create message structure */
468         if (!(mp = folder_read(name))) {
469                 /* Oops, error occurred.  Record it and continue. */
470                 AllocFolders(&folders, &nFoldersAlloced, nFolders + 1);
471                 f = &folders[nFolders++];
472                 f->name = getcpy(name);
473                 f->error = 1;
474                 f->priority = AssignPriority(f->name);
475                 return 0;
476         }
477
478         for (i = 0; i < numsequences; i++) {
479                 /* Convert sequences to their sequence numbers */
480                 if (sequencesToDo[i])
481                         seqnum[i] = seq_getnum(mp, sequencesToDo[i]);
482                 else
483                         seqnum[i] = -1;
484
485                 /* Now count messages in this sequence */
486                 nSeq[i] = 0;
487                 if (mp->nummsg > 0 && seqnum[i] != -1) {
488                         for (msgnum = mp->lowmsg; msgnum <= mp->hghmsg;
489                                         msgnum++) {
490                                 if (in_sequence(mp, seqnum[i], msgnum))
491                                         nSeq[i]++;
492                         }
493                 }
494         }
495
496         /* Check if any of the sequence checks were nonzero */
497         nonzero = 0;
498         for (i = 0; i < numsequences; i++) {
499                 if (nSeq[i] > 0) {
500                         nonzero = 1;
501                         break;
502                 }
503         }
504
505         if (nonzero || force) {
506                 /* save general folder information */
507                 AllocFolders(&folders, &nFoldersAlloced, nFolders + 1);
508                 f = &folders[nFolders++];
509                 f->name = getcpy(name);
510                 f->nMsgs = mp->nummsg;
511                 f->error = 0;
512                 f->priority = AssignPriority(f->name);
513
514                 /* record the sequence information */
515                 for (i = 0; i < numsequences; i++) {
516                         f->nSeq[i] = nSeq[i];
517                         f->private[i] = (seqnum[i] != -1) ?
518                                         is_seq_private(mp, seqnum[i]) : 0;
519                 }
520         }
521
522         folder_free(mp);  /* free folder/message structure */
523         return 1;
524 }
525
526 /*
527 ** Print the folder/sequence information
528 */
529
530 void
531 PrintFolders(void)
532 {
533         char tmpname[BUFSIZ];
534         int i, j, len, has_private = 0;
535         int maxfolderlen = 0, maxseqlen = 0;
536         int maxnum = 0, maxseq = 0;
537
538         if (!Total) {
539                 for (i = 0; i < nFolders; i++)
540                         printf("%s\n", folders[i].name);
541                 return;
542         }
543
544         /*
545         ** Find the width we need for various fields
546         */
547         for (i = 0; i < nFolders; ++i) {
548                 /* find the length of longest folder name */
549                 len = strlen(folders[i].name);
550                 if (len > maxfolderlen)
551                         maxfolderlen = len;
552
553                 /* If folder had error, skip the rest */
554                 if (folders[i].error)
555                         continue;
556
557                 /* find the maximum total messages */
558                 if (folders[i].nMsgs > maxnum)
559                         maxnum = folders[i].nMsgs;
560
561                 for (j = 0; j < numsequences; j++) {
562                         /* find maximum width of sequence name */
563                         len = strlen(sequencesToDo[j]);
564                         if ((folders[i].nSeq[j] > 0 || showzero) &&
565                                         (len > maxseqlen))
566                                 maxseqlen = len;
567
568                         /* find the maximum number of messages in sequence */
569                         if (folders[i].nSeq[j] > maxseq)
570                                 maxseq = folders[i].nSeq[j];
571
572                         /*
573                         ** check if this sequence is private in any of
574                         ** the folders
575                         */
576                         if (folders[i].private[j])
577                                 has_private = 1;
578                 }
579         }
580
581         /* Now print all the folder/sequence information */
582         for (i = 0; i < nFolders; i++) {
583                 for (j = 0; j < numsequences; j++) {
584                         if (folders[i].nSeq[j] > 0 || showzero) {
585                                 /* Add `+' to end of name of current folder */
586                                 if (strcmp(curfol, folders[i].name))
587                                         snprintf(tmpname, sizeof(tmpname),
588                                                         "%s", folders[i].name);
589                                 else
590                                         snprintf(tmpname, sizeof(tmpname),
591                                                         "%s+",
592                                                         folders[i].name);
593
594                                 if (folders[i].error) {
595                                         printf("%-*s is unreadable\n",
596                                                         maxfolderlen+1,
597                                                         tmpname);
598                                         continue;
599                                 }
600
601                                 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);
602                         }
603                 }
604         }
605 }
606
607 /*
608 ** Put them in priority order.
609 */
610
611 int
612 CompareFolders(struct Folder *f1, struct Folder *f2)
613 {
614         if (!alphaOrder && f1->priority != f2->priority)
615                 return f1->priority - f2->priority;
616         else
617                 return strcmp(f1->name, f2->name);
618 }
619
620 /*
621 ** Make sure we have at least n folders allocated.
622 */
623
624 void
625 AllocFolders(struct Folder **f, int *nfa, int n)
626 {
627         if (n <= *nfa)
628                 return;
629         if (*f == NULL) {
630                 *nfa = 10;
631                 *f = (struct Folder *) mh_xmalloc(
632                                 *nfa * (sizeof(struct Folder)));
633         } else {
634                 *nfa *= 2;
635                 *f = (struct Folder *) mh_xrealloc(
636                                 *f, *nfa * (sizeof(struct Folder)));
637         }
638 }
639
640 /*
641 ** Return the priority for a name.  The highest comes from an exact match.
642 ** After that, the longest match (then first) assigns the priority.
643 */
644 int
645 AssignPriority(char *name)
646 {
647         int i, ol, nl;
648         int best = nOrders;
649         int bestLen = 0;
650         struct Folder *o;
651
652         nl = strlen(name);
653         for (i = 0; i < nOrders; ++i) {
654                 o = &orders[i];
655                 if (!strcmp(name, o->name))
656                         return o->priority;
657                 ol = strlen(o->name);
658                 if (nl < ol - 1)
659                         continue;
660                 if (ol < bestLen)
661                         continue;
662                 if (o->name[0] == '*' && !strcmp(o->name + 1,
663                                 name + (nl - ol + 1))) {
664                         best = o->priority;
665                         bestLen = ol;
666                 } else if (o->name[ol - 1] == '*' &&
667                                 strncmp(o->name, name, ol - 1) == 0) {
668                         best = o->priority;
669                         bestLen = ol;
670                 }
671         }
672         return best;
673 }
674
675 /*
676 ** Do the read only folders
677 */
678
679 static void
680 do_readonly_folders(void)
681 {
682         int atrlen;
683         char atrcur[BUFSIZ];
684         register struct node *np;
685
686         snprintf(atrcur, sizeof(atrcur), "atr-%s-", seq_cur);
687         atrlen = strlen(atrcur);
688
689         for (np = m_defs; np; np = np->n_next)
690                 if (isprefix(atrcur, np->n_name)
691                                 && !isprefix(nmhdir, np->n_name + atrlen))
692                         BuildFolderList(np->n_name + atrlen, 0);
693 }