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