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