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