]> git.wh0rd.org Git - fontconfig.git/blob - src/fccache.c
Takashi Iwai <tiwai@suse.de>
[fontconfig.git] / src / fccache.c
1 /*
2  * $RCSId: xc/lib/fontconfig/src/fccache.c,v 1.12 2002/08/22 07:36:44 keithp Exp $
3  *
4  * Copyright © 2000 Keith Packard
5  * Copyright © 2005 Patrick Lam
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and its
8  * documentation for any purpose is hereby granted without fee, provided that
9  * the above copyright notice appear in all copies and that both that
10  * copyright notice and this permission notice appear in supporting
11  * documentation, and that the name of Keith Packard not be used in
12  * advertising or publicity pertaining to distribution of the software without
13  * specific, written prior permission.  Keith Packard makes no
14  * representations about the suitability of this software for any purpose.  It
15  * is provided "as is" without express or implied warranty.
16  *
17  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
19  * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
20  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
22  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23  * PERFORMANCE OF THIS SOFTWARE.
24  */
25
26 #include <fcntl.h>
27 #include <dirent.h>
28 #include <string.h>
29 #include <sys/mman.h>
30 #include <sys/utsname.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include "fcint.h"
34 #include <unistd.h>
35
36 #define ENDIAN_TEST 0x12345678
37 #define MACHINE_SIGNATURE_SIZE 9 + 5*20 + 1
38
39 static int
40 FcDirCacheOpen (const FcChar8 * dir);
41
42 static char *
43 FcDirCacheHashName (char * cache_file, int collisions);
44
45 static off_t
46 FcCacheSkipToArch (int fd, const char * arch);
47
48 static FcBool 
49 FcCacheCopyOld (int fd, int fd_orig, off_t start);
50
51 static void *
52 FcDirCacheProduce (FcFontSet *set, FcCache * metadata);
53
54 static FcBool
55 FcDirCacheConsume (int fd, const char * dir, FcFontSet *set, FcConfig *config);
56
57 static int
58 FcCacheNextOffset(off_t w);
59
60 static char *
61 FcCacheMachineSignature (void);
62
63 static FcBool
64 FcCacheHaveBank (int bank);
65
66 static void
67 FcCacheAddBankDir (int bank, const char * dir);
68
69 struct MD5Context {
70         FcChar32 buf[4];
71         FcChar32 bits[2];
72         unsigned char in[64];
73 };
74
75 static void MD5Init(struct MD5Context *ctx);
76 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len);
77 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
78 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
79
80 #define FC_DBG_CACHE_REF    1024
81
82 static char *
83 FcCacheReadString (int fd, char *dest, int len)
84 {
85     FcChar8     c;
86     FcBool      escape;
87     int         size;
88     int         i;
89
90     if (len == 0)
91         return 0;
92     
93     size = len;
94     i = 0;
95     escape = FcFalse;
96     while (read (fd, &c, 1) == 1)
97     {
98         if (!escape)
99         {
100             switch (c) {
101             case '"':
102                 c = '\0';
103                 break;
104             case '\\':
105                 escape = FcTrue;
106                 continue;
107             }
108         }
109         if (i == size)
110         {
111             dest[i++] = 0;
112             return dest;
113         }
114         dest[i++] = c;
115         if (c == '\0')
116             return dest;
117         escape = FcFalse;
118     }
119     return 0;
120 }
121
122 static void
123 FcCacheSkipString (int fd)
124 {
125     FcChar8     c;
126     FcBool      escape;
127
128     escape = FcFalse;
129     while (read (fd, &c, 1) == 1)
130     {
131         if (!escape)
132         {
133             switch (c) {
134             case '"':
135                 c = '\0';
136                 break;
137             case '\\':
138                 escape = FcTrue;
139                 continue;
140             }
141         }
142         if (c == '\0')
143             return;
144         escape = FcFalse;
145     }
146     return;
147 }
148
149 static FcBool
150 FcCacheWriteString (int fd, const char *chars)
151 {
152     if (write (fd, chars, strlen(chars)+1) != strlen(chars)+1)
153         return FcFalse;
154     return FcTrue;
155 }
156
157 static void
158 FcGlobalCacheDirDestroy (FcGlobalCacheDir *d)
159 {
160     FcStrSetDestroy (d->subdirs);
161     FcMemFree (FC_MEM_STRING, strlen (d->name)+1);
162     free (d->name);
163     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheDir));
164     free (d);
165 }
166
167 FcGlobalCache *
168 FcGlobalCacheCreate (void)
169 {
170     FcGlobalCache   *cache;
171
172     cache = malloc (sizeof (FcGlobalCache));
173     if (!cache)
174         return 0;
175     FcMemAlloc (FC_MEM_CACHE, sizeof (FcGlobalCache));
176     cache->dirs = 0;
177     cache->updated = FcFalse;
178     cache->fd = -1;
179     return cache;
180 }
181
182 void
183 FcGlobalCacheDestroy (FcGlobalCache *cache)
184 {
185     FcGlobalCacheDir    *d, *next;
186
187     for (d = cache->dirs; d; d = next)
188     {
189         next = d->next;
190         FcGlobalCacheDirDestroy (d);
191     }
192     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCache));
193     free (cache);
194 }
195
196 void
197 FcGlobalCacheLoad (FcGlobalCache    *cache,
198                    FcStrSet         *staleDirs,
199                    const FcChar8    *cache_file,
200                    FcConfig         *config)
201 {
202     char                name_buf[FC_MAX_FILE_LEN];
203     FcGlobalCacheDir    *d, *next;
204     FcFileTime          config_time = FcConfigModifiedTime (config);
205     char                * current_arch_machine_name;
206     char                candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
207     off_t               current_arch_start;
208
209     struct stat         cache_stat, dir_stat;
210     char                subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
211
212     if (stat ((char *) cache_file, &cache_stat) < 0)
213         return;
214
215     cache->fd = open ((char *) cache_file, O_RDONLY);
216     if (cache->fd == -1)
217         return;
218
219     cache->updated = FcFalse;
220
221     if (!FcCacheReadString (cache->fd, name_buf, sizeof (name_buf)))
222         goto bail_and_destroy;
223     if (strcmp (name_buf, FC_GLOBAL_MAGIC_COOKIE) != 0)
224         goto bail_and_destroy;
225
226     current_arch_machine_name = FcCacheMachineSignature ();
227     current_arch_start = FcCacheSkipToArch(cache->fd, 
228                                            current_arch_machine_name);
229     if (current_arch_start < 0)
230         goto bail_and_destroy;
231
232     lseek (cache->fd, current_arch_start, SEEK_SET);
233     if (!FcCacheReadString (cache->fd, candidate_arch_machine_name, 
234                             sizeof (candidate_arch_machine_name)))
235         goto bail_and_destroy;
236     if (strlen(candidate_arch_machine_name) == 0)
237         goto bail_and_destroy;
238
239     while (1) 
240     {
241         off_t targ;
242
243         if (!FcCacheReadString (cache->fd, name_buf, sizeof (name_buf)) || 
244             !strlen(name_buf))
245             break;
246
247         /* Directory must be older than the global cache file; also
248            cache must be newer than the config file. */
249         if (stat ((char *) name_buf, &dir_stat) < 0 || 
250             dir_stat.st_mtime > cache_stat.st_mtime ||
251             (config_time.set && cache_stat.st_mtime < config_time.time))
252         {
253             FcCache md;
254             off_t off;
255
256             FcStrSetAdd (staleDirs, FcStrCopy ((FcChar8 *)name_buf));
257
258             /* skip subdirs */
259             while (FcCacheReadString (cache->fd, subdirName, 
260                                       sizeof (subdirName)) &&
261                    strlen (subdirName))
262                 ;
263
264             if (read (cache->fd, &md, sizeof (FcCache)) != sizeof(FcCache)) 
265             {
266                 perror ("read metadata");
267                 goto bail1;
268             }
269             off = FcCacheNextOffset (lseek(cache->fd, 0, SEEK_CUR)) + md.count;
270             if (lseek (cache->fd, off, SEEK_SET) != off) 
271             {
272                 perror ("lseek");
273                 goto bail1;
274             }
275             continue;
276         }
277
278         d = malloc (sizeof (FcGlobalCacheDir));
279         if (!d)
280             goto bail1;
281
282         d->next = cache->dirs;
283         cache->dirs = d;
284
285         d->name = (char *)FcStrCopy ((FcChar8 *)name_buf);
286         d->ent = 0;
287         d->state = FcGCDirFileRead;
288
289         d->subdirs = FcStrSetCreate();
290         do
291         {
292             if (!FcCacheReadString (cache->fd, subdirName, 
293                                     sizeof (subdirName)) ||
294                 !strlen (subdirName))
295                 break;
296             FcStrSetAdd (d->subdirs, (FcChar8 *)subdirName);
297         } while (1);
298
299         d->offset = lseek (cache->fd, 0, SEEK_CUR);
300         if (read (cache->fd, &d->metadata, sizeof (FcCache)) != sizeof (FcCache))
301             goto bail1;
302         targ = FcCacheNextOffset (lseek(cache->fd, 0, SEEK_CUR)) + d->metadata.count;
303         if (lseek (cache->fd, targ, SEEK_SET) != targ)
304             goto bail1;
305     }
306     return;
307
308  bail1:
309     for (d = cache->dirs; d; d = next)
310     {
311         next = d->next;
312         free (d);
313     }
314     cache->dirs = 0;
315
316     close (cache->fd);
317     cache->fd = -1;
318     return;
319
320  bail_and_destroy:
321     close (cache->fd);
322     cache->fd = -1;
323
324     if (stat ((char *) cache_file, &cache_stat) == 0)
325         unlink ((char *)cache_file);
326
327     return;
328
329 }
330
331 FcBool
332 FcGlobalCacheReadDir (FcFontSet *set, FcStrSet *dirs, FcGlobalCache * cache, const char *dir, FcConfig *config)
333 {
334     FcGlobalCacheDir    *d;
335     int                 i;
336
337     if (cache->fd == -1)
338         return FcFalse;
339
340     if (!(dir = (char *)FcConfigNormalizeFontDir (config, (FcChar8 *)dir)))
341         return FcFalse; /* non-existing directory */
342
343     for (d = cache->dirs; d; d = d->next)
344     {
345         if (strcmp (d->name, dir) == 0)
346         {
347             if (d->state == FcGCDirDisabled)
348                 return FcFalse;
349
350             if (d->state == FcGCDirFileRead) 
351             {
352                 lseek (cache->fd, d->offset, SEEK_SET);
353                 if (!FcDirCacheConsume (cache->fd, d->name, set, config))
354                     return FcFalse;
355
356                 for (i = 0; i < d->subdirs->num; i++)
357                     FcStrSetAdd (dirs, (FcChar8 *)d->subdirs->strs[i]);
358
359                 d->state = FcGCDirConsumed;
360             }
361             return FcTrue;
362         }
363     }
364
365     return FcFalse;
366 }
367
368 static FcGlobalCacheDir *
369 FcGlobalCacheDirFind (FcGlobalCache *cache, const char *name)
370 {
371     FcGlobalCacheDir * d;
372
373     if (!cache || !name)
374         return NULL;
375
376     for (d = cache->dirs; d; d = d->next)
377         if (strcmp((const char *)d->name, (const char *)name) == 0)
378             return d;
379
380     return NULL;
381  }
382
383 FcBool
384 FcGlobalCacheUpdate (FcGlobalCache  *cache,
385                      FcStrSet       *dirs,
386                      const char     *orig_name,
387                      FcFontSet      *set,
388                      FcConfig       *config)
389 {
390     FcGlobalCacheDir    *d;
391     int                 i;
392     const char *name;
393
394     name = (char *)FcConfigNormalizeFontDir (config, (FcChar8 *)orig_name);
395     if (!name) 
396     {
397         fprintf(stderr, "Invalid directory name %s\n", orig_name);
398         return FcFalse;
399     }
400
401     d = FcGlobalCacheDirFind (cache, name);
402
403     if (!d)
404     {
405         d = malloc (sizeof (FcGlobalCacheDir));
406         if (!d)
407             return FcFalse;
408         d->next = cache->dirs;
409         cache->dirs = d;
410     } else {
411         /* free old resources */
412         FcStrFree ((FcChar8 *)d->name);
413         free (d->ent);
414         FcStrSetDestroy (d->subdirs);
415     }
416
417     cache->updated = FcTrue;
418
419     d->name = (char *)FcStrCopy ((FcChar8 *)name);
420     d->ent = FcDirCacheProduce (set, &d->metadata);
421     d->offset = 0;
422     d->subdirs = FcStrSetCreate();
423     d->state = FcGCDirUpdated;
424     for (i = 0; i < dirs->num; i++)
425         FcStrSetAdd (d->subdirs, dirs->strs[i]);
426     return FcTrue;
427 }
428
429 FcBool
430 FcGlobalCacheSave (FcGlobalCache    *cache,
431                    const FcChar8    *cache_file,
432                    FcConfig         *config)
433 {
434     int                 fd, fd_orig, i;
435     FcGlobalCacheDir    *dir;
436     FcAtomic            *atomic;
437     off_t               current_arch_start = 0, truncate_to;
438     char                * current_arch_machine_name, * header;
439
440     if (!cache->updated)
441         return FcTrue;
442     
443 #if defined (HAVE_GETUID) && defined (HAVE_GETEUID)
444     /* Set-UID programs can't safely update the cache */
445     if (getuid () != geteuid ())
446         return FcFalse;
447 #endif
448     
449     atomic = FcAtomicCreate (cache_file);
450     if (!atomic)
451         return FcFalse;
452
453     if (!FcAtomicLock (atomic))
454         goto bail1;
455     fd = open ((char *) FcAtomicNewFile(atomic), O_RDWR | O_CREAT, 
456                S_IRUSR | S_IWUSR);
457     if (fd == -1)
458         goto bail2;
459     FcCacheWriteString (fd, FC_GLOBAL_MAGIC_COOKIE);
460
461     fd_orig = open ((char *) FcAtomicOrigFile(atomic), O_RDONLY);
462
463     current_arch_machine_name = FcCacheMachineSignature ();
464     if (fd_orig == -1)
465         current_arch_start = 0;
466     else
467         current_arch_start = FcCacheSkipToArch (fd_orig, 
468                                                 current_arch_machine_name);
469
470     if (current_arch_start < 0)
471     {
472         off_t i = lseek(fd_orig, 0, SEEK_END);
473         if (i < strlen (FC_GLOBAL_MAGIC_COOKIE)+1)
474             i = strlen (FC_GLOBAL_MAGIC_COOKIE)+1;
475         current_arch_start = FcCacheNextOffset (i);
476     }
477
478     if (!FcCacheCopyOld(fd, fd_orig, current_arch_start))
479         goto bail3;
480
481     current_arch_start = lseek(fd, 0, SEEK_CUR);
482     if (ftruncate (fd, current_arch_start) == -1)
483         goto bail3;
484
485     header = malloc (10 + strlen (current_arch_machine_name));
486     if (!header)
487         goto bail3;
488
489     truncate_to = current_arch_start + strlen(current_arch_machine_name) + 11;
490     for (dir = cache->dirs; dir; dir = dir->next)
491     {
492         if (dir->state == FcGCDirDisabled)
493             continue;
494         truncate_to += strlen(dir->name) + 1;
495         truncate_to += sizeof (FcCache);
496         truncate_to = FcCacheNextOffset (truncate_to);
497         truncate_to += dir->metadata.count;
498
499         for (i = 0; i < dir->subdirs->size; i++)
500             truncate_to += strlen((char *)dir->subdirs->strs[i]) + 1;
501         truncate_to ++;
502     }
503     truncate_to -= current_arch_start;
504
505     sprintf (header, "%8x ", (int)truncate_to);
506     strcat (header, current_arch_machine_name);
507     if (!FcCacheWriteString (fd, header))
508         goto bail4;
509
510     for (dir = cache->dirs; dir; dir = dir->next)
511     {
512         const char * d;
513         off_t off;
514
515         if (!dir->name || dir->state == FcGCDirDisabled)
516             continue;
517         d = (const char *)FcConfigNormalizeFontDir (config, (const FcChar8 *)dir->name);
518         if (!d) 
519             continue;
520             
521         if (dir->metadata.count && !dir->ent) 
522         {
523             if (dir->state == FcGCDirUpdated || fd_orig < 0) 
524             {
525                 fprintf(stderr, "Invalid metadata entry for %s, skipping...\n", d);
526                 continue;
527             }
528             /* copy the old content */
529             dir->ent = malloc (dir->metadata.count);
530             if (!dir->ent) 
531             {
532                 perror("malloc error");
533                 continue;
534             }
535             off = FcCacheNextOffset (dir->offset + sizeof(FcCache));
536             if (lseek (fd_orig, off, SEEK_SET) != off) 
537             {
538                 perror("lseek");
539                 free(dir->ent);
540                 continue;
541             }
542             if (read (fd_orig, dir->ent, dir->metadata.count)
543                 != dir->metadata.count) 
544             {
545                 perror("read");
546                 free(dir->ent);
547                 continue;
548             }
549         }
550         
551         FcCacheWriteString (fd, d);
552
553         for (i = 0; i < dir->subdirs->size; i++)
554             FcCacheWriteString (fd, (char *)dir->subdirs->strs[i]);
555         FcCacheWriteString (fd, "");
556         
557         if (write (fd, &dir->metadata, sizeof(FcCache)) != sizeof(FcCache))
558         {
559             perror ("write metadata");
560             free (dir->ent);
561             continue;
562         }
563         off = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
564         if (lseek (fd, off, SEEK_SET) != off)
565         {
566             perror ("lseek");
567             free (dir->ent);
568             continue;
569         }
570         if (dir->metadata.count)
571         {
572             if (write (fd, dir->ent, dir->metadata.count) != dir->metadata.count)
573             {
574                 perror ("write dirent");
575                 free (dir->ent);
576                 continue;
577             }
578         }
579         free (dir->ent);
580     }
581     FcCacheWriteString (fd, "");
582
583     if (close (fd) == -1)
584         goto bail25;
585
586     close (fd_orig);
587     fd_orig = -1;
588     
589     if (!FcAtomicReplaceOrig (atomic))
590         goto bail25;
591     
592     FcAtomicUnlock (atomic);
593     FcAtomicDestroy (atomic);
594
595     cache->updated = FcFalse;
596     return FcTrue;
597
598  bail4:
599     free (header);
600  bail3:
601     if (fd_orig != -1)
602         close (fd_orig);
603
604     close (fd);
605  bail25:
606     FcAtomicDeleteNew (atomic);
607  bail2:
608     FcAtomicUnlock (atomic);
609  bail1:
610     FcAtomicDestroy (atomic);
611     return FcFalse;
612 }
613
614 /* 
615  * Find the next presumably-mmapable offset after the supplied file
616  * position.
617  */
618 static int
619 FcCacheNextOffset(off_t w)
620 {
621     static long pagesize = -1;
622     if (pagesize == -1)
623         pagesize = sysconf(_SC_PAGESIZE);
624     if (w % pagesize == 0) 
625         return w;
626     else
627         return ((w / pagesize)+1)*pagesize;
628 }
629
630 /* return the address of the segment for the provided arch,
631  * or -1 if arch not found */
632 static off_t
633 FcCacheSkipToArch (int fd, const char * arch)
634 {
635     char candidate_arch_machine_name_count[MACHINE_SIGNATURE_SIZE + 9];
636     char * candidate_arch;
637     off_t current_arch_start = 0;
638
639     lseek (fd, 0, SEEK_SET);
640     FcCacheSkipString (fd);
641     current_arch_start = lseek (fd, 0, SEEK_CUR);
642
643     /* skip arches that are not the current arch */
644     while (1)
645     {
646         long bs;
647
648         if (lseek (fd, current_arch_start, SEEK_SET) != current_arch_start)
649             return -1;
650
651         if (FcCacheReadString (fd, candidate_arch_machine_name_count, 
652                                 sizeof (candidate_arch_machine_name_count)) == 0)
653             return -1;
654         if (!strlen(candidate_arch_machine_name_count))
655             return -1;
656         bs = strtol(candidate_arch_machine_name_count, &candidate_arch, 16);
657
658         // count = 0 should probably be distinguished from the !bs condition
659         if (!bs || bs < strlen (candidate_arch_machine_name_count))
660             return -1;
661
662         candidate_arch++; /* skip leading space */
663
664         if (strcmp (candidate_arch, arch)==0)
665             return current_arch_start;
666         current_arch_start += bs;
667     }
668
669     return -1;
670 }
671
672 /* Cuts out the segment at the file pointer (moves everything else
673  * down to cover it), and leaves the file pointer at the end of the
674  * file. */
675 static FcBool 
676 FcCacheCopyOld (int fd, int fd_orig, off_t start)
677 {
678     char * buf = malloc (8192);
679     char candidate_arch_machine_name[MACHINE_SIGNATURE_SIZE + 9];
680     long bs;
681     int c, bytes_skipped;
682     off_t loc;
683
684     if (!buf)
685         return FcFalse;
686
687     loc = 0;
688     lseek (fd, 0, SEEK_SET); lseek (fd_orig, 0, SEEK_SET);
689     do
690     {
691         int b = 8192;
692         if (loc + b > start)
693             b = start - loc;
694
695         if ((c = read (fd_orig, buf, b)) <= 0)
696             break;
697         if (write (fd, buf, c) < 0)
698             goto bail;
699
700         loc += c;
701     }
702     while (c > 0);
703
704     lseek (fd, start, SEEK_SET);
705     if (FcCacheReadString (fd, candidate_arch_machine_name, 
706                            sizeof (candidate_arch_machine_name)) == 0)
707         goto done;
708     if (!strlen(candidate_arch_machine_name))
709         goto done;
710
711     bs = strtol(candidate_arch_machine_name, 0, 16);
712     if (bs == 0)
713         goto done;
714
715     bytes_skipped = 0;
716     do
717     {
718         lseek (fd, start+bs+bytes_skipped, SEEK_SET);
719         if ((c = read (fd, buf, 8192)) <= 0)
720             break;
721         lseek (fd, start+bytes_skipped, SEEK_SET);
722         if (write (fd, buf, c) < 0)
723             goto bail;
724         bytes_skipped += c;
725     }
726     while (c > 0);
727     lseek (fd, start+bytes_skipped, SEEK_SET);
728
729  done:
730     free (buf);
731     return FcTrue;
732
733  bail:
734     free (buf);
735     return FcFalse;
736 }
737
738 /* Does not check that the cache has the appropriate arch section. */
739 /* Also, this can be fooled if the original location has a stale
740  * cache, and the hashed location has an up-to-date cache.  Oh well,
741  * sucks to be you in that case! */
742 FcBool
743 FcDirCacheValid (const FcChar8 *dir)
744 {
745     struct stat file_stat, dir_stat;
746     int         fd;
747
748     if (stat ((char *) dir, &dir_stat) < 0)
749         return FcFalse;
750
751     fd = FcDirCacheOpen (dir);
752
753     if (fd < 0)
754         goto bail;
755     if (fstat (fd, &file_stat) < 0)
756         goto bail;
757
758     close (fd);
759
760     /*
761      * If the directory has been modified more recently than
762      * the cache file, the cache is not valid
763      */
764     if (dir_stat.st_mtime > file_stat.st_mtime)
765         return FcFalse;
766
767     return FcTrue;
768
769  bail:
770     close (fd);
771     return FcFalse;
772 }
773
774 /* Assumes that the cache file in 'dir' exists.
775  * Checks that the cache has the appropriate arch section. */
776 FcBool
777 FcDirCacheHasCurrentArch (const FcChar8 *dir)
778 {
779     int         fd;
780     off_t       current_arch_start;
781     char        *current_arch_machine_name;
782
783     fd = FcDirCacheOpen (dir);
784     if (fd < 0)
785         goto bail;
786
787     current_arch_machine_name = FcCacheMachineSignature();
788     current_arch_start = FcCacheSkipToArch(fd, current_arch_machine_name);
789     close (fd);
790
791     if (current_arch_start < 0)
792         return FcFalse;
793     
794     return FcTrue;
795
796  bail:
797     return FcFalse;
798 }
799
800 FcBool
801 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
802 {
803     char        *cache_file;
804     char        *cache_hashed = 0;
805     int         fd, collisions;
806     struct stat cache_stat;
807     char        name_buf[FC_MAX_FILE_LEN];
808
809     dir = FcConfigNormalizeFontDir (config, dir);
810     cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
811     if (!cache_file)
812         return FcFalse;
813
814     /* First remove normal cache file. */
815     if (stat ((char *) cache_file, &cache_stat) == 0 &&
816         unlink ((char *)cache_file) != 0)
817         goto bail;
818
819     /* Next remove any applicable hashed files. */
820     fd = -1; collisions = 0;
821     do
822     {
823         if (cache_hashed)
824             FcStrFree ((FcChar8 *)cache_hashed);
825
826         cache_hashed = FcDirCacheHashName (cache_file, collisions++);
827         if (!cache_hashed)
828             goto bail;
829
830         if (fd > 0)
831             close (fd);
832         fd = open(cache_hashed, O_RDONLY);
833         if (fd == -1)
834         {
835             FcStrFree ((FcChar8 *)cache_file);
836             return FcTrue;
837         }
838
839         if (!FcCacheReadString (fd, name_buf, sizeof (name_buf)) || !strlen(name_buf))
840         {
841             FcStrFree ((FcChar8 *)cache_hashed);
842             goto bail;
843         }
844     } while (strcmp (name_buf, cache_file) != 0);
845
846     close (fd);
847
848     if (stat ((char *) cache_hashed, &cache_stat) == 0 &&
849         unlink ((char *)cache_hashed) != 0)
850     {
851         FcStrFree ((FcChar8 *)cache_hashed);
852         goto bail;
853     }
854
855     FcStrFree ((FcChar8 *)cache_file);
856     FcStrFree ((FcChar8 *)cache_hashed);
857     return FcTrue;
858
859  bail:
860     FcStrFree ((FcChar8 *)cache_file);
861     return FcFalse;
862 }
863
864 static int
865 FcCacheReadDirs (FcConfig * config, FcGlobalCache * cache, 
866                  FcStrList *list, FcFontSet * set, FcStrSet *processed_dirs)
867 {
868     int                 ret = 0;
869     FcChar8             *dir;
870     const FcChar8       *name;
871     FcStrSet            *subdirs;
872     FcStrList           *sublist;
873     struct stat         statb;
874     FcGlobalCacheDir   *d;
875
876     /*
877      * Read in the results from 'list'.
878      */
879     while ((dir = FcStrListNext (list)))
880     {
881         if (!FcConfigAcceptFilename (config, dir))
882             continue;
883
884         /* Skip this directory if already updated
885          * to avoid the looped directories via symlinks
886          */
887         name = FcConfigNormalizeFontDir (config, dir);
888         if (name) 
889         {
890             if (FcStrSetMember (processed_dirs, dir))
891                 continue;
892             FcStrSetAdd (processed_dirs, dir);
893         }
894
895         subdirs = FcStrSetCreate ();
896         if (!subdirs)
897         {
898             fprintf (stderr, "Can't create directory set\n");
899             ret++;
900             continue;
901         }
902         
903         if (access ((char *) dir, X_OK) < 0)
904         {
905             switch (errno) {
906             case ENOENT:
907             case ENOTDIR:
908             case EACCES:
909                 break;
910             default:
911                 fprintf (stderr, "\"%s\": ", dir);
912                 perror ("");
913                 ret++;
914             }
915             FcStrSetDestroy (subdirs);
916             continue;
917         }
918         if (stat ((char *) dir, &statb) == -1)
919         {
920             fprintf (stderr, "\"%s\": ", dir);
921             perror ("");
922             FcStrSetDestroy (subdirs);
923             ret++;
924             continue;
925         }
926         if (!S_ISDIR (statb.st_mode))
927         {
928             fprintf (stderr, "\"%s\": not a directory, skipping\n", dir);
929             FcStrSetDestroy (subdirs);
930             continue;
931         }
932         if (FcDirCacheValid (dir) && FcDirCacheRead (set, subdirs, dir, config))
933         {
934             /* if an old entry is found in the global cache, disable it */
935             if ((d = FcGlobalCacheDirFind (cache, (const char *)name)) != NULL)
936             {
937                 d->state = FcGCDirDisabled;
938                 /* save the updated config later without this entry */
939                 cache->updated = FcTrue;
940             }
941         }
942         else
943         {
944             if (FcDebug () & FC_DBG_FONTSET)
945                 printf ("cache scan dir %s\n", dir);
946
947             FcDirScanConfig (set, subdirs, cache, 
948                              config->blanks, dir, FcFalse, config);
949         }
950         sublist = FcStrListCreate (subdirs);
951         FcStrSetDestroy (subdirs);
952         if (!sublist)
953         {
954             fprintf (stderr, "Can't create subdir list in \"%s\"\n", dir);
955             ret++;
956             continue;
957         }
958         ret += FcCacheReadDirs (config, cache, sublist, set, processed_dirs);
959     }
960     FcStrListDone (list);
961     return ret;
962 }
963
964 FcFontSet *
965 FcCacheRead (FcConfig *config, FcGlobalCache * cache)
966 {
967     FcFontSet   *s = FcFontSetCreate();
968     FcStrSet    *processed_dirs;
969
970     if (!s) 
971         return 0;
972
973     processed_dirs = FcStrSetCreate();
974     if (!processed_dirs)
975         goto bail;
976
977     if (FcCacheReadDirs (config, cache, FcConfigGetConfigDirs (config), s, processed_dirs))
978         goto bail1;
979
980     FcStrSetDestroy (processed_dirs);
981     return s;
982
983  bail1:
984     FcStrSetDestroy (processed_dirs);
985  bail:
986     FcFontSetDestroy (s);
987     return 0;
988 }
989
990 static const char bin2hex[] = { '0', '1', '2', '3',
991                                 '4', '5', '6', '7',
992                                 '8', '9', 'a', 'b',
993                                 'c', 'd', 'e', 'f' };
994
995 static char *
996 FcDirCacheHashName (char * cache_file, int collisions)
997 {
998     unsigned char       hash[16], hex_hash[33];
999     char                *cache_hashed;
1000     unsigned char       uscore = '_';
1001     int                 cnt, i;
1002     FcChar8             *tmp;
1003     struct MD5Context   ctx;
1004
1005     MD5Init (&ctx);
1006     MD5Update (&ctx, (unsigned char *)cache_file, strlen (cache_file));
1007
1008     for (i = 0; i < collisions; i++)
1009         MD5Update (&ctx, &uscore, 1);
1010
1011     MD5Final (hash, &ctx);
1012
1013     for (cnt = 0; cnt < 16; ++cnt)
1014     {
1015         hex_hash[2*cnt] = bin2hex[hash[cnt] >> 4];
1016         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
1017     }
1018     hex_hash[32] = 0;
1019
1020     tmp = FcStrPlus ((FcChar8 *)hex_hash, (FcChar8 *)FC_CACHE_SUFFIX);
1021     if (!tmp)
1022         return 0;
1023
1024     cache_hashed = (char *)FcStrPlus ((FcChar8 *)PKGCACHEDIR"/", tmp);
1025     free (tmp);
1026
1027     return cache_hashed;
1028 }
1029
1030 /* Opens the hashed name for cache_file.
1031  * This would fail in the unlikely event of a collision and subsequent
1032  * removal of the file which originally caused the collision. */
1033 static int
1034 FcDirCacheOpen (const FcChar8 *dir)
1035 {
1036     FcBool      found;
1037     int         fd = -1, collisions = 0;
1038     char        *cache_file, *cache_hashed;
1039     char        name_buf[FC_MAX_FILE_LEN];
1040     struct stat dir_stat;
1041
1042     cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
1043     if (!cache_file)
1044         return -1;
1045
1046     fd = open(cache_file, O_RDONLY);
1047     if (fd != -1)
1048         return fd;
1049
1050     if (stat ((char *)dir, &dir_stat) == -1)
1051         return -1;
1052
1053     found = FcFalse;
1054     do
1055     {
1056         struct stat c;
1057         FcChar8 * name_buf_dir;
1058
1059         cache_hashed = FcDirCacheHashName (cache_file, collisions++);
1060         if (!cache_hashed)
1061         {
1062             FcStrFree ((FcChar8 *)cache_file);
1063             return -1;
1064         }
1065
1066         if (fd > 0)
1067             close (fd);
1068         fd = open(cache_hashed, O_RDONLY);
1069         FcStrFree ((FcChar8 *)cache_hashed);
1070
1071         if (fd == -1)
1072         {
1073             FcStrFree ((FcChar8 *)cache_file);
1074             return -1;
1075         }
1076         if (!FcCacheReadString (fd, name_buf, sizeof (name_buf)) || !strlen(name_buf))
1077             goto bail;
1078
1079         name_buf_dir = FcStrDirname ((FcChar8 *)name_buf);
1080         if (stat ((char *)name_buf_dir, &c) == -1)
1081         {
1082             FcStrFree (name_buf_dir);
1083             continue;
1084         }
1085         FcStrFree (name_buf_dir);
1086         found = (c.st_ino == dir_stat.st_ino) && (c.st_dev == dir_stat.st_dev);
1087     } while (!found);
1088     FcStrFree ((FcChar8 *)cache_file);
1089     return fd;
1090
1091  bail:
1092     FcStrFree ((FcChar8 *)cache_file);
1093     close (fd);
1094     return -1;
1095 }
1096
1097 /* read serialized state from the cache file */
1098 FcBool
1099 FcDirCacheRead (FcFontSet * set, FcStrSet * dirs, const FcChar8 *dir, FcConfig *config)
1100 {
1101     int         fd;
1102     char        *current_arch_machine_name;
1103     char        candidate_arch_machine_name[9+MACHINE_SIGNATURE_SIZE];
1104     off_t       current_arch_start = 0;
1105     char        subdirName[FC_MAX_FILE_LEN + 1 + 12 + 1];
1106
1107     fd = FcDirCacheOpen (dir);
1108     if (fd < 0)
1109         goto bail;
1110
1111     current_arch_machine_name = FcCacheMachineSignature();
1112     current_arch_start = FcCacheSkipToArch(fd, 
1113                                            current_arch_machine_name);
1114     if (current_arch_start < 0)
1115         goto bail1;
1116
1117     lseek (fd, current_arch_start, SEEK_SET);
1118     if (FcCacheReadString (fd, candidate_arch_machine_name, 
1119                            sizeof (candidate_arch_machine_name)) == 0)
1120         goto bail1;
1121
1122     while (FcCacheReadString (fd, subdirName, sizeof (subdirName)) && strlen (subdirName) > 0)
1123         FcStrSetAdd (dirs, (FcChar8 *)subdirName);
1124
1125     if (!FcDirCacheConsume (fd, (const char *)dir, set, config))
1126         goto bail1;
1127         
1128     close(fd);
1129     return FcTrue;
1130
1131  bail1:
1132     close (fd);
1133  bail:
1134     return FcFalse;
1135 }
1136
1137 static FcBool
1138 FcDirCacheConsume (int fd, const char * dir, FcFontSet *set, FcConfig *config)
1139 {
1140     FcCache metadata;
1141     void * current_dir_block;
1142     off_t pos;
1143
1144     if (read(fd, &metadata, sizeof(FcCache)) != sizeof(FcCache))
1145         return FcFalse;
1146     if (metadata.magic != FC_CACHE_MAGIC)
1147         return FcFalse;
1148
1149     if (!metadata.count)
1150     {
1151         pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
1152         lseek (fd, pos, SEEK_SET);
1153         if (config)
1154             FcConfigAddFontDir (config, (FcChar8 *)dir);
1155         return FcTrue;
1156     }
1157
1158     pos = FcCacheNextOffset (lseek(fd, 0, SEEK_CUR));
1159     current_dir_block = mmap (0, metadata.count, 
1160                               PROT_READ, MAP_SHARED, fd, pos);
1161     lseek (fd, pos+metadata.count, SEEK_SET);
1162     if (current_dir_block == MAP_FAILED)
1163         return FcFalse;
1164
1165     FcCacheAddBankDir (metadata.bank, dir);
1166     if (config)
1167         FcConfigAddFontDir (config, (FcChar8 *)dir);
1168
1169     if (!FcFontSetUnserialize (&metadata, set, current_dir_block))
1170         return FcFalse;
1171
1172     return FcTrue;
1173 }
1174
1175 static void *
1176 FcDirCacheProduce (FcFontSet *set, FcCache *metadata)
1177 {
1178     void * current_dir_block, * final_dir_block;
1179     static unsigned int rand_state = 0;
1180     int bank, needed_bytes_no_align;
1181
1182     if (!rand_state) 
1183         rand_state = time(0L);
1184     bank = rand_r(&rand_state);
1185
1186     while (FcCacheHaveBank(bank))
1187         bank = rand_r(&rand_state);
1188
1189     memset (metadata, 0, sizeof(FcCache));
1190     FcFontSetNewBank();
1191     needed_bytes_no_align = FcFontSetNeededBytes (set);
1192     metadata->count = needed_bytes_no_align + 
1193         FcFontSetNeededBytesAlign ();
1194     metadata->magic = FC_CACHE_MAGIC;
1195     metadata->bank = bank;
1196
1197     if (!needed_bytes_no_align) /* not a failure, no fonts to write */
1198     {
1199         /* no, you don't really need to write any bytes at all. */
1200         metadata->count = 0;
1201         return 0;
1202     }
1203
1204     current_dir_block = malloc (metadata->count);
1205     if (!current_dir_block)
1206         goto bail;
1207     // shut up valgrind
1208     memset (current_dir_block, 0, metadata->count);
1209     final_dir_block = FcFontSetDistributeBytes (metadata, current_dir_block);
1210
1211     if ((void *)((char *)current_dir_block+metadata->count) < final_dir_block)
1212         goto bail;
1213                               
1214     if (!FcFontSetSerialize (bank, set))
1215         goto bail;
1216
1217     return current_dir_block;
1218
1219  bail:
1220     free (current_dir_block);
1221     return 0;
1222 }
1223
1224 /* write serialized state to the cache file */
1225 FcBool
1226 FcDirCacheWrite (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
1227 {
1228     char            *cache_file;
1229     char            *cache_hashed;
1230     int             fd, fd_orig, i, dirs_count;
1231     FcAtomic        *atomic;
1232     FcCache         metadata;
1233     off_t           current_arch_start = 0, truncate_to;
1234     char            name_buf[FC_MAX_FILE_LEN];
1235     int             collisions;
1236
1237     char            *current_arch_machine_name, * header;
1238     void            *current_dir_block = 0;
1239
1240     dir = FcConfigNormalizeFontDir (FcConfigGetCurrent(), dir);
1241     if (!dir)
1242         return FcFalse;
1243
1244     cache_file = (char *)FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
1245     if (!cache_file)
1246         goto bail;
1247
1248     /* Ensure that we're not trampling a cache for some other dir. */
1249     /* This is slightly different from FcDirCacheOpen, since it 
1250      * needs the filename, not the file descriptor. */
1251     fd = -1; collisions = 0;
1252     do
1253     {
1254         cache_hashed = FcDirCacheHashName (cache_file, collisions++);
1255         if (!cache_hashed)
1256             goto bail0;
1257
1258         if (fd > 0)
1259             close (fd);
1260         fd = open(cache_hashed, O_RDONLY);
1261         if (fd == -1)
1262             break;
1263         if(!FcCacheReadString (fd, name_buf, sizeof (name_buf)) || !strlen(name_buf))
1264         {
1265             close (fd);
1266             break;
1267         }
1268         close (fd);
1269
1270         if (strcmp (name_buf, cache_file) != 0)
1271             continue;
1272     } while (0);
1273
1274     current_dir_block = FcDirCacheProduce (set, &metadata);
1275
1276     if (metadata.count && !current_dir_block)
1277         goto bail1;
1278
1279     if (FcDebug () & FC_DBG_CACHE)
1280         printf ("FcDirCacheWriteDir cache_file \"%s\"\n", cache_file);
1281
1282     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
1283     if (!atomic)
1284         goto bail1;
1285
1286     if (!FcAtomicLock (atomic))
1287     {
1288         /* Now try rewriting the original version of the file. */
1289         FcAtomicDestroy (atomic);
1290
1291         atomic = FcAtomicCreate ((FcChar8 *)cache_file);
1292         fd_orig = open (cache_file, O_RDONLY);
1293         if (fd_orig == -1)
1294             fd_orig = open((char *)FcAtomicOrigFile (atomic), O_RDONLY);
1295
1296         fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0666);
1297         if (fd == -1)
1298             goto bail2;
1299     }
1300
1301     /* In all cases, try opening the real location of the cache file first. */
1302     /* (even if that's not atomic.) */
1303     fd_orig = open (cache_file, O_RDONLY);
1304     if (fd_orig == -1)
1305         fd_orig = open((char *)FcAtomicOrigFile (atomic), O_RDONLY);
1306
1307     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT, 0666);
1308     if (fd == -1)
1309         goto bail3;
1310
1311     FcCacheWriteString (fd, cache_file);
1312
1313     current_arch_machine_name = FcCacheMachineSignature ();
1314     current_arch_start = 0;
1315
1316     if (fd_orig != -1)
1317         current_arch_start = 
1318             FcCacheSkipToArch(fd_orig, current_arch_machine_name);
1319
1320     if (current_arch_start < 0)
1321     {
1322         off_t i = lseek(fd_orig, 0, SEEK_END);
1323         if (i < strlen (FC_GLOBAL_MAGIC_COOKIE)+1)
1324             i = strlen (FC_GLOBAL_MAGIC_COOKIE)+1;
1325         current_arch_start = FcCacheNextOffset (i);
1326     }
1327
1328     if (fd_orig != -1 && !FcCacheCopyOld(fd, fd_orig, current_arch_start))
1329         goto bail4;
1330
1331     if (fd_orig != -1)
1332         close (fd_orig);
1333
1334     current_arch_start = lseek(fd, 0, SEEK_CUR);
1335     if (ftruncate (fd, current_arch_start) == -1)
1336         goto bail4;
1337
1338     /* allocate space for subdir names in this block */
1339     dirs_count = 0;
1340     for (i = 0; i < dirs->size; i++)
1341         dirs_count += strlen((char *)dirs->strs[i]) + 1;
1342     dirs_count ++;
1343
1344     /* now write the address of the next offset */
1345     truncate_to = FcCacheNextOffset (FcCacheNextOffset (current_arch_start + sizeof (FcCache) + dirs_count) + metadata.count) - current_arch_start;
1346     header = malloc (10 + strlen (current_arch_machine_name));
1347     if (!header)
1348         goto bail4;
1349     sprintf (header, "%8x ", (int)truncate_to);
1350     strcat (header, current_arch_machine_name);
1351     if (!FcCacheWriteString (fd, header))
1352         goto bail5;
1353
1354     for (i = 0; i < dirs->size; i++)
1355         FcCacheWriteString (fd, (char *)dirs->strs[i]);
1356     FcCacheWriteString (fd, "");
1357
1358     if (write (fd, &metadata, sizeof(FcCache)) != sizeof(FcCache)) 
1359     {
1360         perror("write metadata");
1361         goto bail5;
1362     }
1363     if (metadata.count)
1364     {
1365         off_t off = FcCacheNextOffset (lseek(fd, 0, SEEK_END));
1366         if (lseek (fd, off, SEEK_SET) != off)
1367             perror("lseek");
1368         else if (write (fd, current_dir_block, metadata.count) !=
1369                  metadata.count)
1370             perror("write current_dir_block");
1371         free (current_dir_block);
1372     }
1373
1374     /* this actually serves to pad out the cache file, if needed */
1375     if (ftruncate (fd, current_arch_start + truncate_to) == -1)
1376         goto bail5;
1377
1378     free (header);
1379     close(fd);
1380     if (!FcAtomicReplaceOrig(atomic))
1381         goto bail5;
1382     FcStrFree ((FcChar8 *)cache_hashed);
1383     FcStrFree ((FcChar8 *)cache_file);
1384     FcAtomicUnlock (atomic);
1385     FcAtomicDestroy (atomic);
1386     return FcTrue;
1387
1388  bail5:
1389     free (header);
1390  bail4:
1391     close (fd);
1392  bail3:
1393     FcAtomicUnlock (atomic);
1394  bail2:
1395     FcAtomicDestroy (atomic);
1396  bail1:
1397     FcStrFree ((FcChar8 *)cache_hashed);
1398  bail0:
1399     unlink ((char *)cache_file);
1400     FcStrFree ((FcChar8 *)cache_file);
1401     if (current_dir_block)
1402         free (current_dir_block);
1403  bail:
1404     return FcFalse;
1405 }
1406
1407 static char *
1408 FcCacheMachineSignature ()
1409 {
1410     static char buf[MACHINE_SIGNATURE_SIZE];
1411     int32_t magic = ENDIAN_TEST;
1412     char * m = (char *)&magic;
1413
1414     sprintf (buf, "%2x%2x%2x%2x "
1415              "%4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x %4x "
1416              "%4x %4x %4x %4x %4x %4x %4x %4x\n", 
1417              m[0], m[1], m[2], m[3],
1418              (unsigned int)sizeof (char),
1419              (unsigned int)sizeof (char *),
1420              (unsigned int)sizeof (int),
1421              (unsigned int)sizeof (FcPattern),
1422              (unsigned int)sizeof (FcPatternEltPtr),
1423              (unsigned int)sizeof (struct _FcPatternElt *),
1424              (unsigned int)sizeof (FcPatternElt),
1425              (unsigned int)sizeof (FcObjectPtr),
1426              (unsigned int)sizeof (FcValueListPtr),
1427              (unsigned int)sizeof (FcValue),
1428              (unsigned int)sizeof (FcValueBinding),
1429              (unsigned int)sizeof (struct _FcValueList *),
1430              (unsigned int)sizeof (FcCharSet),
1431              (unsigned int)sizeof (FcCharLeaf **),
1432              (unsigned int)sizeof (FcChar16 *),
1433              (unsigned int)sizeof (FcChar16),
1434              (unsigned int)sizeof (FcCharLeaf),
1435              (unsigned int)sizeof (FcChar32),
1436              (unsigned int)sizeof (FcCache),
1437              (unsigned int)sysconf(_SC_PAGESIZE));
1438
1439     return buf;
1440 }
1441
1442 static int banks_ptr = 0, banks_alloc = 0;
1443 int * _fcBankId = 0, * _fcBankIdx = 0;
1444 static const char ** bankDirs = 0;
1445
1446 static FcBool
1447 FcCacheHaveBank (int bank)
1448 {
1449     int i;
1450
1451     if (bank < FC_BANK_FIRST)
1452         return FcTrue;
1453
1454     for (i = 0; i < banks_ptr; i++)
1455         if (_fcBankId[i] == bank)
1456             return FcTrue;
1457
1458     return FcFalse;
1459 }
1460
1461 int
1462 FcCacheBankToIndexMTF (int bank)
1463 {
1464     int i, j;
1465
1466     for (i = 0; i < banks_ptr; i++)
1467         if (_fcBankId[_fcBankIdx[i]] == bank)
1468         {
1469             int t = _fcBankIdx[i];
1470
1471             for (j = i; j > 0; j--)
1472                 _fcBankIdx[j] = _fcBankIdx[j-1];
1473             _fcBankIdx[0] = t;
1474             return t;
1475         }
1476
1477     if (banks_ptr >= banks_alloc)
1478     {
1479         int * b, * bidx;
1480         const char ** bds;
1481
1482         b = realloc (_fcBankId, (banks_alloc + 4) * sizeof(int));
1483         if (!b)
1484             return -1;
1485         _fcBankId = b;
1486
1487         bidx = realloc (_fcBankIdx, (banks_alloc + 4) * sizeof(int));
1488         if (!bidx)
1489             return -1;
1490         _fcBankIdx = bidx;
1491
1492         bds = realloc (bankDirs, (banks_alloc + 4) * sizeof (char *));
1493         if (!bds)
1494             return -1;
1495         bankDirs = bds;
1496
1497         banks_alloc += 4;
1498     }
1499
1500     i = banks_ptr++;
1501     _fcBankId[i] = bank;
1502     _fcBankIdx[i] = i;
1503     return i;
1504 }
1505
1506 static void
1507 FcCacheAddBankDir (int bank, const char * dir)
1508 {
1509     int bi = FcCacheBankToIndexMTF (bank);
1510
1511     if (bi < 0)
1512         return;
1513
1514     bankDirs[bi] = (const char *)FcStrCopy ((FcChar8 *)dir);
1515 }
1516
1517 const char *
1518 FcCacheFindBankDir (int bank)
1519 {
1520     int bi = FcCacheBankToIndex (bank);
1521     return bankDirs[bi];
1522 }
1523
1524 /*
1525  * This code implements the MD5 message-digest algorithm.
1526  * The algorithm is due to Ron Rivest.  This code was
1527  * written by Colin Plumb in 1993, no copyright is claimed.
1528  * This code is in the public domain; do with it what you wish.
1529  *
1530  * Equivalent code is available from RSA Data Security, Inc.
1531  * This code has been tested against that, and is equivalent,
1532  * except that you don't need to include two pages of legalese
1533  * with every copy.
1534  *
1535  * To compute the message digest of a chunk of bytes, declare an
1536  * MD5Context structure, pass it to MD5Init, call MD5Update as
1537  * needed on buffers full of bytes, and then call MD5Final, which
1538  * will fill a supplied 16-byte array with the digest.
1539  */
1540
1541 #ifndef HIGHFIRST
1542 #define byteReverse(buf, len)   /* Nothing */
1543 #else
1544 /*
1545  * Note: this code is harmless on little-endian machines.
1546  */
1547 void byteReverse(unsigned char *buf, unsigned longs)
1548 {
1549     FcChar32 t;
1550     do {
1551         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1552             ((unsigned) buf[1] << 8 | buf[0]);
1553         *(FcChar32 *) buf = t;
1554         buf += 4;
1555     } while (--longs);
1556 }
1557 #endif
1558
1559 /*
1560  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
1561  * initialization constants.
1562  */
1563 static void MD5Init(struct MD5Context *ctx)
1564 {
1565     ctx->buf[0] = 0x67452301;
1566     ctx->buf[1] = 0xefcdab89;
1567     ctx->buf[2] = 0x98badcfe;
1568     ctx->buf[3] = 0x10325476;
1569
1570     ctx->bits[0] = 0;
1571     ctx->bits[1] = 0;
1572 }
1573
1574 /*
1575  * Update context to reflect the concatenation of another buffer full
1576  * of bytes.
1577  */
1578 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len)
1579 {
1580     FcChar32 t;
1581
1582     /* Update bitcount */
1583
1584     t = ctx->bits[0];
1585     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
1586         ctx->bits[1]++;         /* Carry from low to high */
1587     ctx->bits[1] += len >> 29;
1588
1589     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
1590
1591     /* Handle any leading odd-sized chunks */
1592
1593     if (t) {
1594         unsigned char *p = (unsigned char *) ctx->in + t;
1595
1596         t = 64 - t;
1597         if (len < t) {
1598             memcpy(p, buf, len);
1599             return;
1600         }
1601         memcpy(p, buf, t);
1602         byteReverse(ctx->in, 16);
1603         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1604         buf += t;
1605         len -= t;
1606     }
1607     /* Process data in 64-byte chunks */
1608
1609     while (len >= 64) {
1610         memcpy(ctx->in, buf, 64);
1611         byteReverse(ctx->in, 16);
1612         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1613         buf += 64;
1614         len -= 64;
1615     }
1616
1617     /* Handle any remaining bytes of data. */
1618
1619     memcpy(ctx->in, buf, len);
1620 }
1621
1622 /*
1623  * Final wrapup - pad to 64-byte boundary with the bit pattern 
1624  * 1 0* (64-bit count of bits processed, MSB-first)
1625  */
1626 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
1627 {
1628     unsigned count;
1629     unsigned char *p;
1630
1631     /* Compute number of bytes mod 64 */
1632     count = (ctx->bits[0] >> 3) & 0x3F;
1633
1634     /* Set the first char of padding to 0x80.  This is safe since there is
1635        always at least one byte free */
1636     p = ctx->in + count;
1637     *p++ = 0x80;
1638
1639     /* Bytes of padding needed to make 64 bytes */
1640     count = 64 - 1 - count;
1641
1642     /* Pad out to 56 mod 64 */
1643     if (count < 8) {
1644         /* Two lots of padding:  Pad the first block to 64 bytes */
1645         memset(p, 0, count);
1646         byteReverse(ctx->in, 16);
1647         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1648
1649         /* Now fill the next block with 56 bytes */
1650         memset(ctx->in, 0, 56);
1651     } else {
1652         /* Pad block to 56 bytes */
1653         memset(p, 0, count - 8);
1654     }
1655     byteReverse(ctx->in, 14);
1656
1657     /* Append length in bits and transform */
1658     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
1659     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
1660
1661     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
1662     byteReverse((unsigned char *) ctx->buf, 4);
1663     memcpy(digest, ctx->buf, 16);
1664     memset(ctx, 0, sizeof(ctx));        /* In case it's sensitive */
1665 }
1666
1667
1668 /* The four core functions - F1 is optimized somewhat */
1669
1670 /* #define F1(x, y, z) (x & y | ~x & z) */
1671 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1672 #define F2(x, y, z) F1(z, x, y)
1673 #define F3(x, y, z) (x ^ y ^ z)
1674 #define F4(x, y, z) (y ^ (x | ~z))
1675
1676 /* This is the central step in the MD5 algorithm. */
1677 #define MD5STEP(f, w, x, y, z, data, s) \
1678         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1679
1680 /*
1681  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1682  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1683  * the data and converts bytes into longwords for this routine.
1684  */
1685 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
1686 {
1687     register FcChar32 a, b, c, d;
1688
1689     a = buf[0];
1690     b = buf[1];
1691     c = buf[2];
1692     d = buf[3];
1693
1694     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1695     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1696     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1697     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1698     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1699     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1700     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1701     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1702     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1703     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1704     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1705     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1706     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1707     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1708     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1709     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1710
1711     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1712     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1713     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1714     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1715     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1716     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1717     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1718     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1719     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1720     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1721     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1722     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1723     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1724     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1725     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1726     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1727
1728     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1729     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1730     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1731     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1732     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1733     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1734     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1735     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1736     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1737     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1738     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1739     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1740     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1741     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1742     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1743     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1744
1745     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1746     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1747     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1748     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1749     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1750     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1751     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1752     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1753     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1754     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1755     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1756     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1757     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1758     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1759     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1760     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1761
1762     buf[0] += a;
1763     buf[1] += b;
1764     buf[2] += c;
1765     buf[3] += d;
1766 }