* man/mhbuild.man: wrapped one appearance of "Content-Disposition"
[mmh] / uip / folder.c
1
2 /*
3  * folder(s).c -- set/list the current message and/or folder
4  *             -- push/pop a folder onto/from the folder stack
5  *             -- list the folder stack
6  *
7  * $Id$
8  *
9  * This code is Copyright (c) 2002, by the authors of nmh.  See the
10  * COPYRIGHT file in the root directory of the nmh distribution for
11  * complete copyright information.
12  */
13
14 #include <h/mh.h>
15 #include <h/utils.h>
16 #include <errno.h>
17
18 static struct swit switches[] = {
19 #define ALLSW           0
20     { "all", 0 },
21 #define NALLSW          1
22     { "noall", 0 },
23 #define CREATSW         2
24     { "create", 0 },
25 #define NCREATSW        3
26     { "nocreate", 0 },
27 #define FASTSW          4
28     { "fast", 0 },
29 #define NFASTSW         5
30     { "nofast", 0 },
31 #define HDRSW           6
32     { "header", 0 },
33 #define NHDRSW          7
34     { "noheader", 0 },
35 #define PACKSW          8
36     { "pack", 0 },
37 #define NPACKSW         9
38     { "nopack", 0 },
39 #define VERBSW         10
40     { "verbose", 0 },
41 #define NVERBSW        11
42     { "noverbose", 0 },
43 #define RECURSW        12
44     { "recurse", 0 },
45 #define NRECRSW        13
46     { "norecurse", 0 },
47 #define TOTALSW        14
48     { "total", 0 },
49 #define NTOTLSW        15
50     { "nototal", 0 },
51 #define LISTSW         16
52     { "list", 0 },
53 #define NLISTSW        17
54     { "nolist", 0 },
55 #define PRNTSW         18
56     { "print", 0 },
57 #define NPRNTSW        19
58     { "noprint", -4 },
59 #define PUSHSW         20
60     { "push", 0 },
61 #define POPSW          21
62     { "pop", 0 },
63 #define VERSIONSW      22
64     { "version", 0 },
65 #define HELPSW         23
66     { "help", 0 },
67     { NULL, 0 }
68 };
69
70 static int fshort   = 0;        /* output only folder names                 */
71 static int fcreat   = 0;        /* should we ask to create new folders?     */
72 static int fpack    = 0;        /* are we packing the folder?               */
73 static int fverb    = 0;        /* print actions taken while packing folder */
74 static int fheader  = 0;        /* should we output a header?               */
75 static int frecurse = 0;        /* recurse through subfolders               */
76 static int ftotal   = 0;        /* should we output the totals?             */
77 static int all      = 0;        /* should we output all folders             */
78
79 static int total_folders = 0;   /* total number of folders                  */
80
81 static int start = 0;
82 static int foldp = 0;
83
84 static char *nmhdir;
85 static char *stack = "Folder-Stack";
86 static char folder[BUFSIZ];
87
88 #define NUMFOLDERS 100
89
90 /*
91  * This is how many folders we currently can hold in the array
92  * `folds'.  We increase this amount by NUMFOLDERS at a time.
93  */
94 static int maxfolders;
95 static char **folds;
96
97 /*
98  * Structure to hold information about
99  * folders as we scan them.
100  */
101 struct FolderInfo {
102     char *name;
103     int nummsg;
104     int curmsg;
105     int lowmsg;
106     int hghmsg;
107     int others;         /* others == 1 if other files in folder */
108     int error;          /* error == 1 for unreadable folder     */
109 };
110
111 /*
112  * Dynamically allocated space to hold
113  * all the folder information.
114  */
115 static struct FolderInfo *fi;
116 static int maxFolderInfo;
117
118 /*
119  * static prototypes
120  */
121 static void dodir (char *);
122 static int get_folder_info (char *, char *);
123 static void print_folders (void);
124 static int sfold (struct msgs *, char *);
125 static void addir (char *);
126 static void addfold (char *);
127 static int compare (char *, char *);
128 static void readonly_folders (void);
129
130
131 int
132 main (int argc, char **argv)
133 {
134     int printsw = 0, listsw = 0;
135     int pushsw = 0, popsw = 0;
136     char *cp, *dp, *msg = NULL, *argfolder = NULL;
137     char **ap, **argp, buf[BUFSIZ], **arguments;
138     struct stat st;
139
140 #ifdef LOCALE
141     setlocale(LC_ALL, "");
142 #endif
143     invo_name = r1bindex (argv[0], '/');
144
145     /* read user profile/context */
146     context_read();
147
148     /*
149      * If program was invoked with name ending
150      * in `s', then add switch `-all'.
151      */
152     if (argv[0][strlen (argv[0]) - 1] == 's')
153         all = 1;
154
155     arguments = getarguments (invo_name, argc, argv, 1);
156     argp = arguments;
157
158     while ((cp = *argp++)) {
159         if (*cp == '-') {
160             switch (smatch (++cp, switches)) {
161                 case AMBIGSW: 
162                     ambigsw (cp, switches);
163                     done (1);
164                 case UNKWNSW: 
165                     adios (NULL, "-%s unknown", cp);
166
167                 case HELPSW: 
168                     snprintf (buf, sizeof(buf), "%s [+folder] [msg] [switches]",
169                         invo_name);
170                     print_help (buf, switches, 1);
171                     done (1);
172                 case VERSIONSW:
173                     print_version(invo_name);
174                     done (1);
175
176                 case ALLSW: 
177                     all = 1;
178                     continue;
179
180                 case NALLSW:
181                     all = 0;
182                     continue;
183
184                 case CREATSW: 
185                     fcreat = 1;
186                     continue;
187                 case NCREATSW: 
188                     fcreat = -1;
189                     continue;
190
191                 case FASTSW: 
192                     fshort++;
193                     continue;
194                 case NFASTSW: 
195                     fshort = 0;
196                     continue;
197
198                 case HDRSW: 
199                     fheader = 1;
200                     continue;
201                 case NHDRSW: 
202                     fheader = -1;
203                     continue;
204
205                 case PACKSW: 
206                     fpack++;
207                     continue;
208                 case NPACKSW: 
209                     fpack = 0;
210                     continue;
211
212                 case VERBSW:
213                     fverb++;
214                     continue;
215                 case NVERBSW:
216                     fverb = 0;
217                     continue;
218
219                 case RECURSW: 
220                     frecurse++;
221                     continue;
222                 case NRECRSW: 
223                     frecurse = 0;
224                     continue;
225
226                 case TOTALSW: 
227                     ftotal = 1;
228                     continue;
229                 case NTOTLSW: 
230                     ftotal = -1;
231                     continue;
232
233                 case PRNTSW: 
234                     printsw = 1;
235                     continue;
236                 case NPRNTSW: 
237                     printsw = 0;
238                     continue;
239
240                 case LISTSW: 
241                     listsw = 1;
242                     continue;
243                 case NLISTSW: 
244                     listsw = 0;
245                     continue;
246
247                 case PUSHSW: 
248                     pushsw = 1;
249                     listsw = 1;
250                     popsw  = 0;
251                     continue;
252                 case POPSW: 
253                     popsw  = 1;
254                     listsw = 1;
255                     pushsw = 0;
256                     continue;
257             }
258         }
259         if (*cp == '+' || *cp == '@') {
260             if (argfolder)
261                 adios (NULL, "only one folder at a time!");
262             else
263                 argfolder = path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
264         } else {
265             if (msg)
266                 adios (NULL, "only one (current) message at a time!");
267             else
268                 msg = cp;
269         }
270     }
271
272     if (!context_find ("path"))
273         free (path ("./", TFOLDER));
274     nmhdir = concat (m_maildir (""), "/", NULL);
275
276     /*
277      * If we aren't working with the folder stack
278      * (-push, -pop, -list) then the default is to print.
279      */
280     if (pushsw == 0 && popsw == 0 && listsw == 0)
281         printsw++;
282
283     /* Pushing a folder onto the folder stack */
284     if (pushsw) {
285         if (!argfolder) {
286             /* If no folder is given, the current folder and */
287             /* the top of the folder stack are swapped.      */
288             if ((cp = context_find (stack))) {
289                 dp = getcpy (cp);
290                 ap = brkstring (dp, " ", "\n");
291                 argfolder = getcpy(*ap++);
292             } else {
293                 adios (NULL, "no other folder");
294             }
295             for (cp = getcpy (getfolder (1)); *ap; ap++)
296                 cp = add (*ap, add (" ", cp));
297             free (dp);
298             context_replace (stack, cp);        /* update folder stack */
299         } else {
300             /* update folder stack */
301             context_replace (stack,
302                     (cp = context_find (stack))
303                     ? concat (getfolder (1), " ", cp, NULL)
304                     : getcpy (getfolder (1)));
305         }
306     }
307
308     /* Popping a folder off of the folder stack */
309     if (popsw) {
310         if (argfolder)
311             adios (NULL, "sorry, no folders allowed with -pop");
312         if ((cp = context_find (stack))) {
313             dp = getcpy (cp);
314             ap = brkstring (dp, " ", "\n");
315             argfolder = getcpy(*ap++);
316         } else {
317             adios (NULL, "folder stack empty");
318         }
319         if (*ap) {
320             /* if there's anything left in the stack */
321             cp = getcpy (*ap++);
322             for (; *ap; ap++)
323                 cp = add (*ap, add (" ", cp));
324             context_replace (stack, cp);        /* update folder stack */
325         } else {
326             context_del (stack);        /* delete folder stack entry from context */
327         }
328         free (dp);
329     }
330     if (pushsw || popsw) {
331         cp = m_maildir(argfolder);
332         if (access (cp, F_OK) == NOTOK)
333             adios (cp, "unable to find folder");
334         context_replace (pfolder, argfolder);   /* update current folder   */
335         context_save ();                /* save the context file   */
336         argfolder = NULL;
337     }
338
339     /* Listing the folder stack */
340     if (listsw) {
341         printf ("%s", argfolder ? argfolder : getfolder (1));
342         if ((cp = context_find (stack))) {
343             dp = getcpy (cp);
344             for (ap = brkstring (dp, " ", "\n"); *ap; ap++)
345                 printf (" %s", *ap);
346             free (dp);
347         }
348         printf ("\n");
349
350         if (!printsw)
351             done (0);
352     }
353
354     /* Allocate initial space to record folder names */
355     maxfolders = NUMFOLDERS;
356     folds = mh_xmalloc (maxfolders * sizeof(char *));
357
358     /* Allocate initial space to record folder information */
359     maxFolderInfo = NUMFOLDERS;
360     fi = mh_xmalloc (maxFolderInfo * sizeof(*fi));
361
362     /*
363      * Scan the folders
364      */
365     if (all || ftotal > 0) {
366         /*
367          * If no folder is given, do them all
368          */
369         if (!argfolder) {
370             if (msg)
371                 admonish (NULL, "no folder given for message %s", msg);
372             readonly_folders (); /* do any readonly folders */
373             strncpy (folder, (cp = context_find (pfolder)) ? cp : "", sizeof(folder));
374             dodir (".");
375         } else {
376             strncpy (folder, argfolder, sizeof(folder));
377             if (get_folder_info (argfolder, msg)) {
378                 context_replace (pfolder, argfolder);/* update current folder */
379                 context_save ();                     /* save the context file */
380             }
381             /*
382              * Since recurse wasn't done in get_folder_info(),
383              * we still need to list all level-1 sub-folders.
384              */
385             if (!frecurse)
386                 dodir (folder);
387         }
388     } else {
389         strncpy (folder, argfolder ? argfolder : getfolder (1), sizeof(folder));
390
391         /*
392          * Check if folder exists.  If not, then see if
393          * we should create it, or just exit.
394          */
395         create_folder (m_maildir (folder), fcreat, done);
396
397         if (get_folder_info (folder, msg) && argfolder) {
398             /* update current folder */
399             context_replace (pfolder, argfolder);
400             }
401     }
402
403     /*
404      * Print out folder information
405      */
406     print_folders();
407
408     context_save ();    /* save the context file */
409     return done (0);
410 }
411
412 /*
413  * Base routine for scanning a folder
414  */
415
416 static void
417 dodir (char *dir)
418 {
419     int i;
420     int os = start;
421     int of = foldp;
422     char buffer[BUFSIZ];
423
424     start = foldp;
425
426     /* change directory to base of nmh directory */
427     if (chdir (nmhdir) == NOTOK)
428         adios (nmhdir, "unable to change directory to");
429
430     addir (strncpy (buffer, dir, sizeof(buffer)));
431
432     for (i = start; i < foldp; i++) {
433         get_folder_info (folds[i], NULL);
434         fflush (stdout);
435     }
436
437     start = os;
438     foldp = of;
439 }
440
441 static int
442 get_folder_info (char *fold, char *msg)
443 {
444     int i, retval = 1;
445     char *mailfile;
446     struct msgs *mp = NULL;
447
448     i = total_folders++;
449
450     /*
451      * if necessary, reallocate the space
452      * for folder information
453      */
454     if (total_folders >= maxFolderInfo) {
455         maxFolderInfo += NUMFOLDERS;
456         fi = mh_xrealloc (fi, maxFolderInfo * sizeof(*fi));
457     }
458
459     fi[i].name   = fold;
460     fi[i].nummsg = 0;
461     fi[i].curmsg = 0;
462     fi[i].lowmsg = 0;
463     fi[i].hghmsg = 0;
464     fi[i].others = 0;
465     fi[i].error  = 0;
466
467     mailfile = m_maildir (fold);
468
469     if (!chdir (mailfile)) {
470         if ((ftotal > 0) || !fshort || msg || fpack) {
471             /*
472              * create message structure and get folder info
473              */
474             if (!(mp = folder_read (fold))) {
475                 admonish (NULL, "unable to read folder %s", fold);
476                 return 0;
477             }
478
479             /* set the current message */
480             if (msg && !sfold (mp, msg))
481                 retval = 0;
482
483             if (fpack) {
484                 if (folder_pack (&mp, fverb) == -1)
485                     done (1);
486                 seq_save (mp);          /* synchronize the sequences */
487                 context_save ();        /* save the context file     */
488             }
489
490             /* record info for this folder */
491             if ((ftotal > 0) || !fshort) {
492                 fi[i].nummsg = mp->nummsg;
493                 fi[i].curmsg = mp->curmsg;
494                 fi[i].lowmsg = mp->lowmsg;
495                 fi[i].hghmsg = mp->hghmsg;
496                 fi[i].others = other_files (mp);
497             }
498
499             folder_free (mp); /* free folder/message structure */
500         }
501     } else {
502         fi[i].error = 1;
503     }
504
505     if (frecurse && (fshort || fi[i].others) && (fi[i].error == 0))
506         dodir (fold);
507     return retval;
508 }
509
510 /*
511  * Print folder information
512  */
513
514 static void
515 print_folders (void)
516 {
517     int i, len, hasempty = 0, curprinted;
518     int maxlen = 0, maxnummsg = 0, maxlowmsg = 0;
519     int maxhghmsg = 0, maxcurmsg = 0, total_msgs = 0;
520     int nummsgdigits, lowmsgdigits;
521     int hghmsgdigits, curmsgdigits;
522     char tmpname[BUFSIZ];
523
524     /*
525      * compute a few values needed to for
526      * printing various fields
527      */
528     for (i = 0; i < total_folders; i++) {
529         /* length of folder name */
530         len = strlen (fi[i].name);
531         if (len > maxlen)
532             maxlen = len;
533
534         /* If folder has error, skip the rest */
535         if (fi[i].error)
536             continue;
537
538         /* calculate total number of messages */
539         total_msgs += fi[i].nummsg;
540
541         /* maximum number of messages */
542         if (fi[i].nummsg > maxnummsg)
543             maxnummsg = fi[i].nummsg;
544
545         /* maximum low message */
546         if (fi[i].lowmsg > maxlowmsg)
547             maxlowmsg = fi[i].lowmsg;
548
549         /* maximum high message */
550         if (fi[i].hghmsg > maxhghmsg)
551             maxhghmsg = fi[i].hghmsg;
552
553         /* maximum current message */
554         if (fi[i].curmsg >= fi[i].lowmsg &&
555             fi[i].curmsg <= fi[i].hghmsg &&
556             fi[i].curmsg > maxcurmsg)
557             maxcurmsg = fi[i].curmsg;
558
559         /* check for empty folders */
560         if (fi[i].nummsg == 0)
561             hasempty = 1;
562     }
563     nummsgdigits = num_digits (maxnummsg);
564     lowmsgdigits = num_digits (maxlowmsg);
565     hghmsgdigits = num_digits (maxhghmsg);
566     curmsgdigits = num_digits (maxcurmsg);
567
568     if (hasempty && nummsgdigits < 2)
569         nummsgdigits = 2;
570
571     /*
572      * Print the header
573      */
574     if (fheader > 0 || (all && !fshort && fheader >= 0))
575         printf ("%-*s %*s %-*s; %-*s %*s\n",
576                 maxlen+1, "FOLDER",
577                 nummsgdigits + 13, "# MESSAGES",
578                 lowmsgdigits + hghmsgdigits + 4, " RANGE",
579                 curmsgdigits + 4, "CUR",
580                 9, "(OTHERS)");
581
582     /*
583      * Print folder information
584      */
585     if (all || fshort || ftotal < 1) {
586         for (i = 0; i < total_folders; i++) {
587             if (fshort) {
588                 printf ("%s\n", fi[i].name);
589                 continue;
590             }
591
592             /* Add `+' to end of name, if folder is current */
593             if (strcmp (folder, fi[i].name))
594                 snprintf (tmpname, sizeof(tmpname), "%s", fi[i].name);
595             else
596                 snprintf (tmpname, sizeof(tmpname), "%s+", fi[i].name);
597
598             if (fi[i].error) {
599                 printf ("%-*s is unreadable\n", maxlen+1, tmpname);
600                 continue;
601             }
602
603             printf ("%-*s ", maxlen+1, tmpname);
604
605             curprinted = 0; /* remember if we print cur */
606             if (fi[i].nummsg == 0) {
607                 printf ("has %*s messages%*s",
608                         nummsgdigits, "no",
609                         fi[i].others ? lowmsgdigits + hghmsgdigits + 5 : 0, "");
610             } else {
611                 printf ("has %*d message%s  (%*d-%*d)",
612                         nummsgdigits, fi[i].nummsg,
613                         (fi[i].nummsg == 1) ? " " : "s",
614                         lowmsgdigits, fi[i].lowmsg,
615                         hghmsgdigits, fi[i].hghmsg);
616                 if (fi[i].curmsg >= fi[i].lowmsg && fi[i].curmsg <= fi[i].hghmsg) {
617                     curprinted = 1;
618                     printf ("; cur=%*d", curmsgdigits, fi[i].curmsg);
619                 }
620             }
621
622             if (fi[i].others)
623                 printf (";%*s (others)", curprinted ? 0 : curmsgdigits + 6, "");
624             printf (".\n");
625         }
626     }
627
628     /*
629      * Print folder/message totals
630      */
631     if (ftotal > 0 || (all && !fshort && ftotal >= 0)) {
632         if (all)
633             printf ("\n");
634         printf ("TOTAL = %d message%c in %d folder%s.\n",
635                 total_msgs, total_msgs != 1 ? 's' : ' ',
636                 total_folders, total_folders != 1 ? "s" : "");
637     }
638
639     fflush (stdout);
640 }
641
642 /*
643  * Set the current message and sychronize sequences
644  */
645
646 static int
647 sfold (struct msgs *mp, char *msg)
648 {
649     /* parse the message range/sequence/name and set SELECTED */
650     if (!m_convert (mp, msg))
651         return 0;
652
653     if (mp->numsel > 1) {
654         admonish (NULL, "only one message at a time!");
655         return 0;
656     }
657     seq_setprev (mp);           /* set the previous-sequence     */
658     seq_setcur (mp, mp->lowsel);/* set current message           */
659     seq_save (mp);              /* synchronize message sequences */
660     context_save ();            /* save the context file         */
661
662     return 1;
663 }
664
665
666 static void
667 addir (char *name)
668 {
669     int nlink;
670     char *base, *cp;
671     struct stat st;
672     struct dirent *dp;
673     DIR * dd;
674
675     cp = name + strlen (name);
676     *cp++ = '/';
677     *cp = '\0';
678
679     /*
680      * A hack to skip over a leading
681      * "./" in folder names.
682      */
683     base = strcmp (name, "./") ? name : name + 2;
684
685    /* short-cut to see if directory has any sub-directories */
686     if (stat (name, &st) != -1 && st.st_nlink == 2)
687         return;
688  
689     if (!(dd = opendir (name))) {
690         admonish (name, "unable to read directory ");
691         return;
692     }
693
694     /*
695      * Keep track of the number of directories we've seen
696      * so we can quit stat'ing early, if we've seen them all.
697      */
698     nlink = st.st_nlink;
699
700     while (nlink && (dp = readdir (dd))) {
701         if (!strcmp (dp->d_name, ".") || !strcmp (dp->d_name, "..")) {
702             nlink--;
703             continue;
704         }
705         if (cp + NLENGTH(dp) + 2 >= name + BUFSIZ)
706             continue;
707         strcpy (cp, dp->d_name);
708         if (stat (name, &st) != -1 && S_ISDIR(st.st_mode)) {
709             /*
710              * Check if this was really a symbolic link pointing at
711              * a directory.  If not, then decrement link count.
712              */
713             if (lstat (name, &st) == -1)
714                 nlink--;
715             addfold (base);
716         }
717     }
718
719     closedir (dd);
720     *--cp = '\0';
721 }
722
723 /*
724  * Add the folder name into the
725  * list in a sorted fashion.
726  */
727
728 static void
729 addfold (char *fold)
730 {
731     register int i, j;
732     register char *cp;
733
734     /* if necessary, reallocate the space for folder names */
735     if (foldp >= maxfolders) {
736         maxfolders += NUMFOLDERS;
737         folds = mh_xrealloc (folds, maxfolders * sizeof(char *));
738     }
739
740     cp = getcpy (fold);
741     for (i = start; i < foldp; i++)
742         if (compare (cp, folds[i]) < 0) {
743             for (j = foldp - 1; j >= i; j--)
744                 folds[j + 1] = folds[j];
745             foldp++;
746             folds[i] = cp;
747             return;
748         }
749
750     folds[foldp++] = cp;
751 }
752
753
754 static int
755 compare (char *s1, char *s2)
756 {
757     register int i;
758
759     while (*s1 || *s2)
760         if ((i = *s1++ - *s2++))
761             return i;
762
763     return 0;
764 }
765
766 /*
767  * Do the read only folders
768  */
769
770 static void
771 readonly_folders (void)
772 {
773     int atrlen;
774     char atrcur[BUFSIZ];
775     register struct node *np;
776
777     snprintf (atrcur, sizeof(atrcur), "atr-%s-", current);
778     atrlen = strlen (atrcur);
779
780     for (np = m_defs; np; np = np->n_next)
781         if (ssequal (atrcur, np->n_name)
782                 && !ssequal (nmhdir, np->n_name + atrlen))
783             get_folder_info (np->n_name + atrlen, NULL);
784 }