Replace mh_xmalloc() with mh_xcalloc()
[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_xcalloc((size_t) 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                                 exit(EX_USAGE);
158                         case UNKWNSW:
159                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
160
161                         case HELPSW:
162                                 snprintf(buf, sizeof(buf), "%s [+folder1 [+folder2 ...]][switches]", invo_name);
163                                 print_help(buf, switches, 1);
164                                 exit(argc == 2 ? EX_OK : EX_USAGE);
165
166                         case VERSIONSW:
167                                 print_version(invo_name);
168                                 exit(argc == 2 ? EX_OK : EX_USAGE);
169
170                         case SEQSW:
171                                 if (!(cp = *argp++) || *cp == '-')
172                                         adios(EX_USAGE, NULL, "missing argument to %s",
173                                                         argp[-2]);
174
175                                 /* check if too many sequences specified */
176                                 if (numsequences >= NUMATTRS)
177                                         adios(EX_USAGE, 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(EX_CONFIG, 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(EX_USAGE, 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 EX_OK;
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_xcalloc(p - s + 1, sizeof(char));
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(EX_OSERR, 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(EX_IOERR, 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_xcalloc(*nfa, sizeof(struct Folder));
627         } else {
628                 *nfa *= 2;
629                 *f = (struct Folder *) mh_xrealloc(
630                                 *f, *nfa * (sizeof(struct Folder)));
631         }
632 }
633
634 /*
635 ** Return the priority for a name.  The highest comes from an exact match.
636 ** After that, the longest match (then first) assigns the priority.
637 */
638 int
639 AssignPriority(char *name)
640 {
641         int i, ol, nl;
642         int best = nOrders;
643         int bestLen = 0;
644         struct Folder *o;
645
646         nl = strlen(name);
647         for (i = 0; i < nOrders; ++i) {
648                 o = &orders[i];
649                 if (strcmp(name, o->name)==0)
650                         return o->priority;
651                 ol = strlen(o->name);
652                 if (nl < ol - 1)
653                         continue;
654                 if (ol < bestLen)
655                         continue;
656                 if (o->name[0] == '*' &&
657                                 strcmp(o->name + 1, name + (nl - ol + 1))==0) {
658                         best = o->priority;
659                         bestLen = ol;
660                 } else if (o->name[ol - 1] == '*' &&
661                                 strncmp(o->name, name, ol - 1) == 0) {
662                         best = o->priority;
663                         bestLen = ol;
664                 }
665         }
666         return best;
667 }
668
669 /*
670 ** Do the read only folders
671 */
672
673 static void
674 do_readonly_folders(void)
675 {
676         int atrlen;
677         char atrcur[BUFSIZ];
678         struct node *np;
679
680         snprintf(atrcur, sizeof(atrcur), "atr-%s-", seq_cur);
681         atrlen = strlen(atrcur);
682
683         for (np = m_defs; np; np = np->n_next)
684                 if (strncmp(np->n_name, atrcur, atrlen)==0
685                                 && strncmp(np->n_name+atrlen, nmhdir, strlen(nmhdir))!=0)
686                         /* Why do we exclude absolute path names? --meillo */
687                         BuildFolderList(np->n_name + atrlen, 0);
688 }