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