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