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