Automatically remove invalid cache files.
[platform/upstream/fontconfig.git] / src / fccache.c
1 /*
2  * Copyright © 2000 Keith Packard
3  * Copyright © 2005 Patrick Lam
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and its
6  * documentation for any purpose is hereby granted without fee, provided that
7  * the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation, and that the name of Keith Packard not be used in
10  * advertising or publicity pertaining to distribution of the software without
11  * specific, written prior permission.  Keith Packard makes no
12  * representations about the suitability of this software for any purpose.  It
13  * is provided "as is" without express or implied warranty.
14  *
15  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
16  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
17  * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
18  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
19  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
20  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21  * PERFORMANCE OF THIS SOFTWARE.
22  */
23
24 #include "fcint.h"
25 #include "../fc-arch/fcarch.h"
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <dirent.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
32 #  include <unistd.h>
33 #  include <sys/mman.h>
34 #elif defined(_WIN32)
35 #  include <windows.h>
36 #endif
37
38 #ifndef O_BINARY
39 #define O_BINARY 0
40 #endif
41
42 struct MD5Context {
43         FcChar32 buf[4];
44         FcChar32 bits[2];
45         unsigned char in[64];
46 };
47
48 static void MD5Init(struct MD5Context *ctx);
49 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len);
50 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx);
51 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16]);
52
53 #define CACHEBASE_LEN (1 + 32 + 1 + sizeof (FC_ARCHITECTURE) + sizeof (FC_CACHE_SUFFIX))
54
55 static const char bin2hex[] = { '0', '1', '2', '3',
56                                 '4', '5', '6', '7',
57                                 '8', '9', 'a', 'b',
58                                 'c', 'd', 'e', 'f' };
59
60 static FcChar8 *
61 FcDirCacheBasename (const FcChar8 * dir, FcChar8 cache_base[CACHEBASE_LEN])
62 {
63     unsigned char       hash[16];
64     FcChar8             *hex_hash;
65     int                 cnt;
66     struct MD5Context   ctx;
67
68     MD5Init (&ctx);
69     MD5Update (&ctx, (unsigned char *)dir, strlen ((char *) dir));
70
71     MD5Final (hash, &ctx);
72
73     cache_base[0] = '/';
74     hex_hash = cache_base + 1;
75     for (cnt = 0; cnt < 16; ++cnt)
76     {
77         hex_hash[2*cnt  ] = bin2hex[hash[cnt] >> 4];
78         hex_hash[2*cnt+1] = bin2hex[hash[cnt] & 0xf];
79     }
80     hex_hash[2*cnt] = 0;
81     strcat ((char *) cache_base, "-" FC_ARCHITECTURE FC_CACHE_SUFFIX);
82
83     return cache_base;
84 }
85
86 FcBool
87 FcDirCacheUnlink (const FcChar8 *dir, FcConfig *config)
88 {
89     FcChar8     *cache_hashed = NULL;
90     FcChar8     cache_base[CACHEBASE_LEN];
91     FcStrList   *list;
92     FcChar8     *cache_dir;
93
94     FcDirCacheBasename (dir, cache_base);
95
96     list = FcStrListCreate (config->cacheDirs);
97     if (!list)
98         return FcFalse;
99         
100     while ((cache_dir = FcStrListNext (list)))
101     {
102         cache_hashed = FcStrPlus (cache_dir, cache_base);
103         if (!cache_hashed)
104             break;
105         (void) unlink ((char *) cache_hashed);
106     }
107     FcStrListDone (list);
108     /* return FcFalse if something went wrong */
109     if (cache_dir)
110         return FcFalse;
111     return FcTrue;
112 }
113
114 static int
115 FcCacheReadDirs (FcConfig * config,
116                  FcStrList *list, FcFontSet * set, FcStrSet *processed_dirs)
117 {
118     int                 ret = 0;
119     FcChar8             *dir;
120     FcStrSet            *subdirs;
121     FcStrList           *sublist;
122
123     /*
124      * Read in the results from 'list'.
125      */
126     while ((dir = FcStrListNext (list)))
127     {
128         if (!FcConfigAcceptFilename (config, dir))
129             continue;
130
131         /* Skip this directory if already updated
132          * to avoid the looped directories via symlinks
133          * Clearly a dir not in fonts.conf shouldn't be globally cached.
134          */
135
136         if (FcStrSetMember (processed_dirs, dir))
137             continue;
138         if (!FcStrSetAdd (processed_dirs, dir))
139             continue;
140
141         subdirs = FcStrSetCreate ();
142         if (!subdirs)
143         {
144             fprintf (stderr, "Can't create directory set\n");
145             ret++;
146             continue;
147         }
148         
149         FcDirScanConfig (set, subdirs,
150                          config->blanks, dir, FcFalse, config);
151         
152         sublist = FcStrListCreate (subdirs);
153         FcStrSetDestroy (subdirs);
154         if (!sublist)
155         {
156             fprintf (stderr, "Can't create subdir list in \"%s\"\n", dir);
157             ret++;
158             continue;
159         }
160         ret += FcCacheReadDirs (config, sublist, set, processed_dirs);
161     }
162     FcStrListDone (list);
163     return ret;
164 }
165
166 FcFontSet *
167 FcCacheRead (FcConfig *config)
168 {
169     FcFontSet   *s = FcFontSetCreate();
170     FcStrSet    *processed_dirs;
171
172     if (!s) 
173         return 0;
174
175     processed_dirs = FcStrSetCreate();
176     if (!processed_dirs)
177         goto bail;
178
179     if (FcCacheReadDirs (config, FcConfigGetConfigDirs (config), s, processed_dirs))
180         goto bail1;
181
182     FcStrSetDestroy (processed_dirs);
183     return s;
184
185  bail1:
186     FcStrSetDestroy (processed_dirs);
187  bail:
188     FcFontSetDestroy (s);
189     return 0;
190 }
191
192 /* 
193  * Look for a cache file for the specified dir. Attempt
194  * to use each one we find, stopping when the callback
195  * indicates success
196  */
197 static FcBool
198 FcDirCacheProcess (FcConfig *config, const FcChar8 *dir, 
199                    FcBool (*callback) (int fd, off_t size, void *closure),
200                    void *closure)
201 {
202     int         fd = -1;
203     FcChar8     cache_base[CACHEBASE_LEN];
204     FcStrList   *list;
205     FcChar8     *cache_dir;
206     struct stat file_stat, dir_stat;
207     FcBool      ret = FcFalse;
208
209     if (stat ((char *) dir, &dir_stat) < 0)
210         return FcFalse;
211
212     FcDirCacheBasename (dir, cache_base);
213
214     list = FcStrListCreate (config->cacheDirs);
215     if (!list)
216         return FcFalse;
217         
218     while ((cache_dir = FcStrListNext (list)))
219     {
220         FcChar8 *cache_hashed = FcStrPlus (cache_dir, cache_base);
221         if (!cache_hashed)
222             break;
223         fd = open((char *) cache_hashed, O_RDONLY | O_BINARY);
224         FcStrFree (cache_hashed);
225         if (fd >= 0) {
226             if (fstat (fd, &file_stat) >= 0 &&
227                 dir_stat.st_mtime <= file_stat.st_mtime)
228             {
229                 ret = (*callback) (fd, file_stat.st_size, closure);
230                 if (ret)
231                 {
232                     close (fd);
233                     break;
234                 }
235             }
236             close (fd);
237         }
238     }
239     FcStrListDone (list);
240     
241     return ret;
242 }
243
244 FcBool
245 FcDirCacheLoad (int fd, off_t size, void *closure)
246 {
247     FcCache     *cache;
248     FcBool      allocated = FcFalse;
249
250     if (size < sizeof (FcCache))
251         return FcFalse;
252 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
253     cache = mmap (0, size, PROT_READ, MAP_SHARED, fd, 0);
254 #elif defined(_WIN32)
255     {
256         HANDLE hFileMap;
257
258         cache = NULL;
259         hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
260                                      PAGE_READONLY, 0, 0, NULL);
261         if (hFileMap != NULL)
262         {
263             cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0, size);
264             CloseHandle (hFileMap);
265         }
266     }
267 #endif
268     if (!cache)
269     {
270         cache = malloc (size);
271         if (!cache)
272             return FcFalse;
273
274         if (read (fd, cache, size) != size)
275         {
276             free (cache);
277             return FcFalse;
278         }
279         allocated = FcTrue;
280     } 
281     if (cache->magic != FC_CACHE_MAGIC ||
282         cache->size != size)
283     {
284         if (allocated)
285             free (cache);
286         else
287         {
288 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
289             munmap (cache, size);
290 #elif defined(_WIN32)
291             UnmapViewOfFile (cache);
292 #endif
293         }
294         return FcFalse;
295     }
296
297     /* Mark allocated caches so they're freed rather than unmapped */
298     if (allocated)
299         cache->magic = FC_CACHE_MAGIC_COPY;
300         
301     *((FcCache **) closure) = cache;
302     return FcTrue;
303 }
304
305 FcCache *
306 FcDirCacheMap (const FcChar8 *dir, FcConfig *config)
307 {
308     FcCache *cache = NULL;
309
310     if (!FcDirCacheProcess (config, dir,
311                             FcDirCacheLoad,
312                             &cache))
313         return NULL;
314     return cache;
315 }
316
317 FcBool
318 FcDirCacheRead (FcFontSet * set, FcStrSet * dirs, 
319                 const FcChar8 *dir, FcConfig *config)
320 {
321     FcCache     *cache;
322     int         i;
323     FcFontSet   *cache_set;
324     intptr_t    *cache_dirs;
325     FcPattern   **cache_fonts;
326
327     cache = FcDirCacheMap (dir, config);
328     if (!cache)
329         return FcFalse;
330     
331     cache_set = FcCacheSet (cache);
332     cache_fonts = FcFontSetFonts(cache_set);
333     if (FcDebug() & FC_DBG_CACHE)
334         printf ("FcDirCacheRead mapped cache for %s (%d fonts %d subdirs)\n",
335                 dir, cache_set->nfont, cache->dirs_count);
336     for (i = 0; i < cache_set->nfont; i++)
337     {
338         FcPattern   *font = FcEncodedOffsetToPtr (cache_set,
339                                                   cache_fonts[i],
340                                                   FcPattern);
341         if (FcDebug() & FC_DBG_CACHEV) {
342             printf ("Mapped font %d\n", i);
343             FcPatternPrint (font);
344         }
345         FcFontSetAdd (set, font);
346     }
347     
348     cache_dirs = FcCacheDirs (cache);
349     for (i = 0; i < cache->dirs_count; i++) 
350         FcStrSetAdd (dirs, FcOffsetToPtr (cache_dirs,
351                                           cache_dirs[i],
352                                           FcChar8));
353          
354     if (config)
355         FcConfigAddFontDir (config, (FcChar8 *)dir);
356     
357     return FcTrue;
358 }
359     
360 static FcBool
361 FcDirCacheValidate (int fd, off_t size, void *closure)
362 {
363     FcBool  ret = FcTrue;
364     FcCache     c;
365     struct stat file_stat;
366     
367     if (read (fd, &c, sizeof (FcCache)) != sizeof (FcCache))
368         ret = FcFalse;
369     else if (fstat (fd, &file_stat) < 0)
370         ret = FcFalse;
371     else if (c.magic != FC_CACHE_MAGIC)
372         ret = FcFalse;
373     else if (file_stat.st_size != c.size)
374         ret = FcFalse;
375     return ret;
376 }
377
378 FcBool
379 FcDirCacheValid (const FcChar8 *dir, FcConfig *config)
380 {
381     return FcDirCacheProcess (config, dir, FcDirCacheValidate, NULL);
382 }
383
384 void
385 FcDirCacheUnmap (FcCache *cache)
386 {
387     if (cache->magic == FC_CACHE_MAGIC_COPY)
388     {
389         free (cache);
390         return;
391     }
392 #if defined(HAVE_MMAP) || defined(__CYGWIN__)
393     munmap (cache, cache->size);
394 #elif defined(_WIN32)
395     UnmapViewOfFile (cache);
396 #endif
397 }
398
399 /*
400  * Cache file is:
401  *
402  * FcCache
403  * dir name
404  * subdirs
405  * FcFontSet
406  */
407
408 static FcCache *
409 FcDirCacheProduce (FcFontSet *set, const FcChar8 *dir, FcStrSet *dirs)
410 {
411     FcSerialize *serialize = FcSerializeCreate ();
412     FcCache *cache;
413     int i;
414     intptr_t    cache_offset;
415     intptr_t    dirs_offset;
416     FcChar8     *dir_serialize;
417     intptr_t    *dirs_serialize;
418     FcFontSet   *set_serialize;
419     
420     if (!serialize)
421         return NULL;
422     /*
423      * Space for cache structure
424      */
425     cache_offset = FcSerializeReserve (serialize, sizeof (FcCache));
426     /*
427      * Directory name
428      */
429     if (!FcStrSerializeAlloc (serialize, dir))
430         goto bail1;
431     /*
432      * Subdirs
433      */
434     dirs_offset = FcSerializeAlloc (serialize, dirs, dirs->num * sizeof (FcChar8 *));
435     for (i = 0; i < dirs->num; i++)
436         if (!FcStrSerializeAlloc (serialize, dirs->strs[i]))
437             goto bail1;
438
439     /*
440      * Patterns
441      */
442     if (!FcFontSetSerializeAlloc (serialize, set))
443         goto bail1;
444     
445     /* Serialize layout complete. Now allocate space and fill it */
446     cache = malloc (serialize->size);
447     if (!cache)
448         goto bail1;
449     /* shut up valgrind */
450     memset (cache, 0, serialize->size);
451
452     serialize->linear = cache;
453
454     cache->magic = FC_CACHE_MAGIC;
455     cache->size = serialize->size;
456
457     /*
458      * Serialize directory name
459      */
460     dir_serialize = FcStrSerialize (serialize, dir);
461     if (!dir_serialize)
462         goto bail2;
463     cache->dir = FcPtrToOffset (cache, dir_serialize);
464     
465     /*
466      * Serialize sub dirs
467      */
468     dirs_serialize = FcSerializePtr (serialize, dirs);
469     if (!dirs_serialize)
470         goto bail2;
471     cache->dirs = FcPtrToOffset (cache, dirs_serialize);
472     cache->dirs_count = dirs->num;
473     for (i = 0; i < dirs->num; i++) 
474     {
475         FcChar8 *d_serialize = FcStrSerialize (serialize, dirs->strs[i]);
476         if (!d_serialize)
477             goto bail2;
478         dirs_serialize[i] = FcPtrToOffset (dirs_serialize, d_serialize);
479     }
480     
481     /*
482      * Serialize font set
483      */
484     set_serialize = FcFontSetSerialize (serialize, set);
485     if (!set_serialize)
486         goto bail2;
487     cache->set = FcPtrToOffset (cache, set_serialize);
488
489     FcSerializeDestroy (serialize);
490     
491     return cache;
492
493 bail2:
494     free (cache);
495 bail1:
496     FcSerializeDestroy (serialize);
497     return NULL;
498 }
499
500 static FcBool
501 FcMakeDirectory (const FcChar8 *dir)
502 {
503     FcChar8 *parent;
504     FcBool  ret;
505     
506     if (strlen ((char *) dir) == 0)
507         return FcFalse;
508     
509     parent = FcStrDirname (dir);
510     if (!parent)
511         return FcFalse;
512     if (access ((char *) parent, W_OK|X_OK) == 0)
513         ret = mkdir ((char *) dir, 0777) == 0;
514     else if (access ((char *) parent, F_OK) == -1)
515         ret = FcMakeDirectory (parent) && (mkdir ((char *) dir, 0777) == 0);
516     else
517         ret = FcFalse;
518     FcStrFree (parent);
519     return ret;
520 }
521
522 /* write serialized state to the cache file */
523 FcBool
524 FcDirCacheWrite (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir, FcConfig *config)
525 {
526     FcChar8         cache_base[CACHEBASE_LEN];
527     FcChar8         *cache_hashed;
528     int             fd;
529     FcAtomic        *atomic;
530     FcCache         *cache;
531     FcStrList       *list;
532     FcChar8         *cache_dir = NULL;
533     FcChar8         *test_dir;
534
535     /*
536      * Write it to the first directory in the list which is writable
537      */
538     
539     list = FcStrListCreate (config->cacheDirs);
540     if (!list)
541         return FcFalse;
542     while ((test_dir = FcStrListNext (list))) {
543         if (access ((char *) test_dir, W_OK|X_OK) == 0)
544         {
545             cache_dir = test_dir;
546             break;
547         }
548         else
549         {
550             /*
551              * If the directory doesn't exist, try to create it
552              */
553             if (access ((char *) test_dir, F_OK) == -1) {
554                 if (FcMakeDirectory (test_dir))
555                 {
556                     cache_dir = test_dir;
557                     break;
558                 }
559             }
560         }
561     }
562     FcStrListDone (list);
563     if (!cache_dir)
564         return FcFalse;
565
566     FcDirCacheBasename (dir, cache_base);
567     cache_hashed = FcStrPlus (cache_dir, cache_base);
568     if (!cache_hashed)
569         return FcFalse;
570
571     cache = FcDirCacheProduce (set, dir, dirs);
572
573     if (!cache)
574         goto bail1;
575
576     if (FcDebug () & FC_DBG_CACHE)
577         printf ("FcDirCacheWriteDir dir \"%s\" file \"%s\"\n",
578                 dir, cache_hashed);
579
580     atomic = FcAtomicCreate ((FcChar8 *)cache_hashed);
581     if (!atomic)
582         goto bail2;
583
584     if (!FcAtomicLock (atomic))
585         goto bail3;
586
587     fd = open((char *)FcAtomicNewFile (atomic), O_RDWR | O_CREAT | O_BINARY, 0666);
588     if (fd == -1)
589         goto bail4;
590     
591     if (write (fd, cache, cache->size) != cache->size)
592     {
593         perror ("write cache");
594         goto bail5;
595     }
596
597     close(fd);
598     if (!FcAtomicReplaceOrig(atomic))
599         goto bail4;
600     FcStrFree ((FcChar8 *)cache_hashed);
601     FcAtomicUnlock (atomic);
602     FcAtomicDestroy (atomic);
603     return FcTrue;
604
605  bail5:
606     close (fd);
607  bail4:
608     FcAtomicUnlock (atomic);
609  bail3:
610     FcAtomicDestroy (atomic);
611  bail2:
612     free (cache);
613  bail1:
614     FcStrFree ((FcChar8 *)cache_hashed);
615     return FcFalse;
616 }
617
618 /*
619  * This code implements the MD5 message-digest algorithm.
620  * The algorithm is due to Ron Rivest.  This code was
621  * written by Colin Plumb in 1993, no copyright is claimed.
622  * This code is in the public domain; do with it what you wish.
623  *
624  * Equivalent code is available from RSA Data Security, Inc.
625  * This code has been tested against that, and is equivalent,
626  * except that you don't need to include two pages of legalese
627  * with every copy.
628  *
629  * To compute the message digest of a chunk of bytes, declare an
630  * MD5Context structure, pass it to MD5Init, call MD5Update as
631  * needed on buffers full of bytes, and then call MD5Final, which
632  * will fill a supplied 16-byte array with the digest.
633  */
634
635 #ifndef HIGHFIRST
636 #define byteReverse(buf, len)   /* Nothing */
637 #else
638 /*
639  * Note: this code is harmless on little-endian machines.
640  */
641 void byteReverse(unsigned char *buf, unsigned longs)
642 {
643     FcChar32 t;
644     do {
645         t = (FcChar32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
646             ((unsigned) buf[1] << 8 | buf[0]);
647         *(FcChar32 *) buf = t;
648         buf += 4;
649     } while (--longs);
650 }
651 #endif
652
653 /*
654  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
655  * initialization constants.
656  */
657 static void MD5Init(struct MD5Context *ctx)
658 {
659     ctx->buf[0] = 0x67452301;
660     ctx->buf[1] = 0xefcdab89;
661     ctx->buf[2] = 0x98badcfe;
662     ctx->buf[3] = 0x10325476;
663
664     ctx->bits[0] = 0;
665     ctx->bits[1] = 0;
666 }
667
668 /*
669  * Update context to reflect the concatenation of another buffer full
670  * of bytes.
671  */
672 static void MD5Update(struct MD5Context *ctx, unsigned char *buf, unsigned len)
673 {
674     FcChar32 t;
675
676     /* Update bitcount */
677
678     t = ctx->bits[0];
679     if ((ctx->bits[0] = t + ((FcChar32) len << 3)) < t)
680         ctx->bits[1]++;         /* Carry from low to high */
681     ctx->bits[1] += len >> 29;
682
683     t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */
684
685     /* Handle any leading odd-sized chunks */
686
687     if (t) {
688         unsigned char *p = (unsigned char *) ctx->in + t;
689
690         t = 64 - t;
691         if (len < t) {
692             memcpy(p, buf, len);
693             return;
694         }
695         memcpy(p, buf, t);
696         byteReverse(ctx->in, 16);
697         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
698         buf += t;
699         len -= t;
700     }
701     /* Process data in 64-byte chunks */
702
703     while (len >= 64) {
704         memcpy(ctx->in, buf, 64);
705         byteReverse(ctx->in, 16);
706         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
707         buf += 64;
708         len -= 64;
709     }
710
711     /* Handle any remaining bytes of data. */
712
713     memcpy(ctx->in, buf, len);
714 }
715
716 /*
717  * Final wrapup - pad to 64-byte boundary with the bit pattern 
718  * 1 0* (64-bit count of bits processed, MSB-first)
719  */
720 static void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
721 {
722     unsigned count;
723     unsigned char *p;
724
725     /* Compute number of bytes mod 64 */
726     count = (ctx->bits[0] >> 3) & 0x3F;
727
728     /* Set the first char of padding to 0x80.  This is safe since there is
729        always at least one byte free */
730     p = ctx->in + count;
731     *p++ = 0x80;
732
733     /* Bytes of padding needed to make 64 bytes */
734     count = 64 - 1 - count;
735
736     /* Pad out to 56 mod 64 */
737     if (count < 8) {
738         /* Two lots of padding:  Pad the first block to 64 bytes */
739         memset(p, 0, count);
740         byteReverse(ctx->in, 16);
741         MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
742
743         /* Now fill the next block with 56 bytes */
744         memset(ctx->in, 0, 56);
745     } else {
746         /* Pad block to 56 bytes */
747         memset(p, 0, count - 8);
748     }
749     byteReverse(ctx->in, 14);
750
751     /* Append length in bits and transform */
752     ((FcChar32 *) ctx->in)[14] = ctx->bits[0];
753     ((FcChar32 *) ctx->in)[15] = ctx->bits[1];
754
755     MD5Transform(ctx->buf, (FcChar32 *) ctx->in);
756     byteReverse((unsigned char *) ctx->buf, 4);
757     memcpy(digest, ctx->buf, 16);
758     memset(ctx, 0, sizeof(ctx));        /* In case it's sensitive */
759 }
760
761
762 /* The four core functions - F1 is optimized somewhat */
763
764 /* #define F1(x, y, z) (x & y | ~x & z) */
765 #define F1(x, y, z) (z ^ (x & (y ^ z)))
766 #define F2(x, y, z) F1(z, x, y)
767 #define F3(x, y, z) (x ^ y ^ z)
768 #define F4(x, y, z) (y ^ (x | ~z))
769
770 /* This is the central step in the MD5 algorithm. */
771 #define MD5STEP(f, w, x, y, z, data, s) \
772         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
773
774 /*
775  * The core of the MD5 algorithm, this alters an existing MD5 hash to
776  * reflect the addition of 16 longwords of new data.  MD5Update blocks
777  * the data and converts bytes into longwords for this routine.
778  */
779 static void MD5Transform(FcChar32 buf[4], FcChar32 in[16])
780 {
781     register FcChar32 a, b, c, d;
782
783     a = buf[0];
784     b = buf[1];
785     c = buf[2];
786     d = buf[3];
787
788     MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
789     MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
790     MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
791     MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
792     MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
793     MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
794     MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
795     MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
796     MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
797     MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
798     MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
799     MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
800     MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
801     MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
802     MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
803     MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
804
805     MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
806     MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
807     MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
808     MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
809     MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
810     MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
811     MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
812     MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
813     MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
814     MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
815     MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
816     MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
817     MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
818     MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
819     MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
820     MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
821
822     MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
823     MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
824     MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
825     MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
826     MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
827     MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
828     MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
829     MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
830     MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
831     MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
832     MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
833     MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
834     MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
835     MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
836     MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
837     MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
838
839     MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
840     MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
841     MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
842     MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
843     MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
844     MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
845     MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
846     MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
847     MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
848     MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
849     MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
850     MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
851     MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
852     MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
853     MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
854     MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
855
856     buf[0] += a;
857     buf[1] += b;
858     buf[2] += c;
859     buf[3] += d;
860 }