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