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