XEmacs 21.2.28 "Hermes".
[chise/xemacs-chise.git.1] / src / md5.c
1 /* md5.c - Functions to compute MD5 message digest of files or memory blocks
2    according to the definition of MD5 in RFC 1321 from April 1992.
3    Copyright (C) 1995, 1996 Free Software Foundation, Inc.
4    NOTE: The canonical source of this file is maintained with the GNU C
5    Library.  Bugs can be reported to bug-glibc@prep.ai.mit.edu.
6
7    This program is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by the
9    Free Software Foundation; either version 2, or (at your option) any
10    later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software Foundation,
19    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.  */
22
23 /* XEmacs frontend written by Ben Wing, Jareth Hein and Hrvoje Niksic.  */
24
25 #ifdef HAVE_CONFIG_H
26 # include <config.h>
27 #endif
28
29 #include <sys/types.h>
30 #include <string.h>
31 #include <stdio.h>
32
33 #if defined HAVE_LIMITS_H || _LIBC
34 # include <limits.h>
35 #endif
36
37 /* The following contortions are an attempt to use the C preprocessor
38    to determine an unsigned integral type that is 32 bits wide.  An
39    alternative approach is to use autoconf's AC_CHECK_SIZEOF macro, but
40    doing that would require that the configure script compile and *run*
41    the resulting executable.  Locally running cross-compiled executables
42    is usually not possible.  */
43
44 #ifdef _LIBC
45 # include <sys/types.h>
46 typedef u_int32_t md5_uint32;
47 #else
48 # if defined __STDC__ && __STDC__
49 #  define UINT_MAX_32_BITS 4294967295U
50 # else
51 #  define UINT_MAX_32_BITS 0xFFFFFFFF
52 # endif
53
54 /* If UINT_MAX isn't defined, assume it's a 32-bit type.
55    This should be valid for all systems GNU cares about because
56    that doesn't include 16-bit systems, and only modern systems
57    (that certainly have <limits.h>) have 64+-bit integral types.  */
58
59 # ifndef UINT_MAX
60 #  define UINT_MAX UINT_MAX_32_BITS
61 # endif
62
63 # if UINT_MAX == UINT_MAX_32_BITS
64    typedef unsigned int md5_uint32;
65 # else
66 #  if USHRT_MAX == UINT_MAX_32_BITS
67     typedef unsigned short md5_uint32;
68 #  else
69 #   if ULONG_MAX == UINT_MAX_32_BITS
70      typedef unsigned long md5_uint32;
71 #   else
72      /* The following line is intended to evoke an error.
73         Using #error is not portable enough.  */
74      "Cannot determine unsigned 32-bit data type."
75 #   endif
76 #  endif
77 # endif
78 #endif
79
80 #include "lisp.h"
81 #include "buffer.h"
82 #include "lstream.h"
83 #ifdef FILE_CODING
84 # include "file-coding.h"
85 #endif
86
87 /* Structure to save state of computation between the single steps.  */
88 struct md5_ctx
89 {
90   md5_uint32 A;
91   md5_uint32 B;
92   md5_uint32 C;
93   md5_uint32 D;
94
95   md5_uint32 total[2];
96   md5_uint32 buflen;
97   char buffer[128];
98 };
99
100 #ifdef WORDS_BIGENDIAN
101 # define SWAP(n)                                                        \
102     (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
103 #else
104 # define SWAP(n) (n)
105 #endif
106
107
108 /* This array contains the bytes used to pad the buffer to the next
109    64-byte boundary.  (RFC 1321, 3.1: Step 1)  */
110 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */ };
111
112
113 static void md5_process_block (CONST void *, size_t, struct md5_ctx *);
114
115
116 /* Initialize structure containing state of computation.
117    (RFC 1321, 3.3: Step 3)  */
118 static void
119 md5_init_ctx (struct md5_ctx *ctx)
120 {
121   ctx->A = 0x67452301;
122   ctx->B = 0xefcdab89;
123   ctx->C = 0x98badcfe;
124   ctx->D = 0x10325476;
125
126   ctx->total[0] = ctx->total[1] = 0;
127   ctx->buflen = 0;
128 }
129
130 /* Put result from CTX in first 16 bytes following RESBUF.  The result
131    must be in little endian byte order.
132
133    IMPORTANT: On some systems it is required that RESBUF is correctly
134    aligned for a 32 bits value.  */
135 static void *
136 md5_read_ctx (CONST struct md5_ctx *ctx, void *resbuf)
137 {
138   ((md5_uint32 *) resbuf)[0] = SWAP (ctx->A);
139   ((md5_uint32 *) resbuf)[1] = SWAP (ctx->B);
140   ((md5_uint32 *) resbuf)[2] = SWAP (ctx->C);
141   ((md5_uint32 *) resbuf)[3] = SWAP (ctx->D);
142
143   return resbuf;
144 }
145
146 /* Process the remaining bytes in the internal buffer and the usual
147    prolog according to the standard and write the result to RESBUF.
148
149    IMPORTANT: On some systems it is required that RESBUF is correctly
150    aligned for a 32 bits value.  */
151 static void *
152 md5_finish_ctx (struct md5_ctx *ctx, void *resbuf)
153 {
154   /* Take yet unprocessed bytes into account.  */
155   md5_uint32 bytes = ctx->buflen;
156   size_t pad;
157
158   /* Now count remaining bytes.  */
159   ctx->total[0] += bytes;
160   if (ctx->total[0] < bytes)
161     ++ctx->total[1];
162
163   pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
164   memcpy (&ctx->buffer[bytes], fillbuf, pad);
165
166   /* Put the 64-bit file length in *bits* at the end of the buffer.  */
167   *(md5_uint32 *) &ctx->buffer[bytes + pad] = SWAP (ctx->total[0] << 3);
168   *(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = SWAP ((ctx->total[1] << 3) |
169                                                         (ctx->total[0] >> 29));
170
171   /* Process last bytes.  */
172   md5_process_block (ctx->buffer, bytes + pad + 8, ctx);
173
174   return md5_read_ctx (ctx, resbuf);
175 }
176
177 #ifndef emacs                   /* unused in Emacs */
178 /* Compute MD5 message digest for bytes read from STREAM.  The
179    resulting message digest number will be written into the 16 bytes
180    beginning at RESBLOCK.  */
181 int
182 md5_stream (FILE *stream, void *resblock)
183 {
184   /* Important: BLOCKSIZE must be a multiple of 64.  */
185 #define BLOCKSIZE 4096
186   struct md5_ctx ctx;
187   char buffer[BLOCKSIZE + 72];
188   size_t sum;
189
190   /* Initialize the computation context.  */
191   md5_init_ctx (&ctx);
192
193   /* Iterate over full file contents.  */
194   while (1)
195     {
196       /* We read the file in blocks of BLOCKSIZE bytes.  One call of the
197          computation function processes the whole buffer so that with the
198          next round of the loop another block can be read.  */
199       size_t n;
200       sum = 0;
201
202       /* Read block.  Take care for partial reads.  */
203       do
204         {
205           n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
206
207           sum += n;
208         }
209       while (sum < BLOCKSIZE && n != 0);
210       if (n == 0 && ferror (stream))
211         return 1;
212
213       /* If end of file is reached, end the loop.  */
214       if (n == 0)
215         break;
216
217       /* Process buffer with BLOCKSIZE bytes.  Note that
218                         BLOCKSIZE % 64 == 0
219        */
220       md5_process_block (buffer, BLOCKSIZE, &ctx);
221     }
222
223   /* Add the last bytes if necessary.  */
224   if (sum > 0)
225     md5_process_bytes (buffer, sum, &ctx);
226
227   /* Construct result in desired memory.  */
228   md5_finish_ctx (&ctx, resblock);
229   return 0;
230 }
231
232 /* Compute MD5 message digest for LEN bytes beginning at BUFFER.  The
233    result is always in little endian byte order, so that a byte-wise
234    output yields to the wanted ASCII representation of the message
235    digest.  */
236 void *
237 md5_buffer (const char *buffer, size_t len, void *resblock)
238 {
239   struct md5_ctx ctx;
240
241   /* Initialize the computation context.  */
242   md5_init_ctx (&ctx);
243
244   /* Process whole buffer but last len % 64 bytes.  */
245   md5_process_bytes (buffer, len, &ctx);
246
247   /* Put result in desired memory area.  */
248   return md5_finish_ctx (&ctx, resblock);
249 }
250 #endif /* not emacs */
251
252
253 static void
254 md5_process_bytes (CONST void *buffer, size_t len, struct md5_ctx *ctx)
255 {
256   /* When we already have some bits in our internal buffer concatenate
257      both inputs first.  */
258   if (ctx->buflen != 0)
259     {
260       size_t left_over = ctx->buflen;
261       size_t add = 128 - left_over > len ? len : 128 - left_over;
262
263       memcpy (&ctx->buffer[left_over], buffer, add);
264       ctx->buflen += add;
265
266       if (left_over + add > 64)
267         {
268           md5_process_block (ctx->buffer, (left_over + add) & ~63, ctx);
269           /* The regions in the following copy operation cannot overlap.  */
270           memcpy (ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
271                   (left_over + add) & 63);
272           ctx->buflen = (left_over + add) & 63;
273         }
274
275       buffer = (const char *) buffer + add;
276       len -= add;
277     }
278
279   /* Process available complete blocks.  */
280   if (len > 64)
281     {
282       md5_process_block (buffer, len & ~63, ctx);
283       buffer = (const char *) buffer + (len & ~63);
284       len &= 63;
285     }
286
287   /* Move remaining bytes in internal buffer.  */
288   if (len > 0)
289     {
290       memcpy (ctx->buffer, buffer, len);
291       ctx->buflen = len;
292     }
293 }
294
295
296 /* These are the four functions used in the four steps of the MD5 algorithm
297    and defined in the RFC 1321.  The first function is a little bit optimized
298    (as found in Colin Plumbs public domain implementation).  */
299 /* #define FF(b, c, d) ((b & c) | (~b & d)) */
300 #define FF(b, c, d) (d ^ (b & (c ^ d)))
301 #define FG(b, c, d) FF (d, b, c)
302 #define FH(b, c, d) (b ^ c ^ d)
303 #define FI(b, c, d) (c ^ (b | ~d))
304
305 /* Process LEN bytes of BUFFER, accumulating context into CTX.
306    It is assumed that LEN % 64 == 0.  */
307
308 static void
309 md5_process_block (CONST void *buffer, size_t len, struct md5_ctx *ctx)
310 {
311   md5_uint32 correct_words[16];
312   const md5_uint32 *words = (const md5_uint32 *) buffer;
313   size_t nwords = len / sizeof (md5_uint32);
314   const md5_uint32 *endp = words + nwords;
315   md5_uint32 A = ctx->A;
316   md5_uint32 B = ctx->B;
317   md5_uint32 C = ctx->C;
318   md5_uint32 D = ctx->D;
319
320   /* First increment the byte count.  RFC 1321 specifies the possible
321      length of the file up to 2^64 bits.  Here we only compute the
322      number of bytes.  Do a double word increment.  */
323   ctx->total[0] += len;
324   if (ctx->total[0] < len)
325     ++ctx->total[1];
326
327   /* Process all bytes in the buffer with 64 bytes in each round of
328      the loop.  */
329   while (words < endp)
330     {
331       md5_uint32 *cwp = correct_words;
332       md5_uint32 A_save = A;
333       md5_uint32 B_save = B;
334       md5_uint32 C_save = C;
335       md5_uint32 D_save = D;
336
337       /* First round: using the given function, the context and a constant
338          the next context is computed.  Because the algorithms processing
339          unit is a 32-bit word and it is determined to work on words in
340          little endian byte order we perhaps have to change the byte order
341          before the computation.  To reduce the work for the next steps
342          we store the swapped words in the array CORRECT_WORDS.  */
343
344 #define OP(a, b, c, d, s, T)                                            \
345       do                                                                \
346         {                                                               \
347           a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T;             \
348           ++words;                                                      \
349           CYCLIC (a, s);                                                \
350           a += b;                                                       \
351         }                                                               \
352       while (0)
353
354       /* It is unfortunate that C does not provide an operator for
355          cyclic rotation.  Hope the C compiler is smart enough.  */
356 #define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s)))
357
358       /* Before we start, one word to the strange constants.
359          They are defined in RFC 1321 as
360
361          T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64
362        */
363
364       /* Round 1.  */
365       OP (A, B, C, D,  7, 0xd76aa478);
366       OP (D, A, B, C, 12, 0xe8c7b756);
367       OP (C, D, A, B, 17, 0x242070db);
368       OP (B, C, D, A, 22, 0xc1bdceee);
369       OP (A, B, C, D,  7, 0xf57c0faf);
370       OP (D, A, B, C, 12, 0x4787c62a);
371       OP (C, D, A, B, 17, 0xa8304613);
372       OP (B, C, D, A, 22, 0xfd469501);
373       OP (A, B, C, D,  7, 0x698098d8);
374       OP (D, A, B, C, 12, 0x8b44f7af);
375       OP (C, D, A, B, 17, 0xffff5bb1);
376       OP (B, C, D, A, 22, 0x895cd7be);
377       OP (A, B, C, D,  7, 0x6b901122);
378       OP (D, A, B, C, 12, 0xfd987193);
379       OP (C, D, A, B, 17, 0xa679438e);
380       OP (B, C, D, A, 22, 0x49b40821);
381
382       /* For the second to fourth round we have the possibly swapped words
383          in CORRECT_WORDS.  Redefine the macro to take an additional first
384          argument specifying the function to use.  */
385 #undef OP
386 #define OP(f, a, b, c, d, k, s, T)                                      \
387       do                                                                \
388         {                                                               \
389           a += f (b, c, d) + correct_words[k] + T;                      \
390           CYCLIC (a, s);                                                \
391           a += b;                                                       \
392         }                                                               \
393       while (0)
394
395       /* Round 2.  */
396       OP (FG, A, B, C, D,  1,  5, 0xf61e2562);
397       OP (FG, D, A, B, C,  6,  9, 0xc040b340);
398       OP (FG, C, D, A, B, 11, 14, 0x265e5a51);
399       OP (FG, B, C, D, A,  0, 20, 0xe9b6c7aa);
400       OP (FG, A, B, C, D,  5,  5, 0xd62f105d);
401       OP (FG, D, A, B, C, 10,  9, 0x02441453);
402       OP (FG, C, D, A, B, 15, 14, 0xd8a1e681);
403       OP (FG, B, C, D, A,  4, 20, 0xe7d3fbc8);
404       OP (FG, A, B, C, D,  9,  5, 0x21e1cde6);
405       OP (FG, D, A, B, C, 14,  9, 0xc33707d6);
406       OP (FG, C, D, A, B,  3, 14, 0xf4d50d87);
407       OP (FG, B, C, D, A,  8, 20, 0x455a14ed);
408       OP (FG, A, B, C, D, 13,  5, 0xa9e3e905);
409       OP (FG, D, A, B, C,  2,  9, 0xfcefa3f8);
410       OP (FG, C, D, A, B,  7, 14, 0x676f02d9);
411       OP (FG, B, C, D, A, 12, 20, 0x8d2a4c8a);
412
413       /* Round 3.  */
414       OP (FH, A, B, C, D,  5,  4, 0xfffa3942);
415       OP (FH, D, A, B, C,  8, 11, 0x8771f681);
416       OP (FH, C, D, A, B, 11, 16, 0x6d9d6122);
417       OP (FH, B, C, D, A, 14, 23, 0xfde5380c);
418       OP (FH, A, B, C, D,  1,  4, 0xa4beea44);
419       OP (FH, D, A, B, C,  4, 11, 0x4bdecfa9);
420       OP (FH, C, D, A, B,  7, 16, 0xf6bb4b60);
421       OP (FH, B, C, D, A, 10, 23, 0xbebfbc70);
422       OP (FH, A, B, C, D, 13,  4, 0x289b7ec6);
423       OP (FH, D, A, B, C,  0, 11, 0xeaa127fa);
424       OP (FH, C, D, A, B,  3, 16, 0xd4ef3085);
425       OP (FH, B, C, D, A,  6, 23, 0x04881d05);
426       OP (FH, A, B, C, D,  9,  4, 0xd9d4d039);
427       OP (FH, D, A, B, C, 12, 11, 0xe6db99e5);
428       OP (FH, C, D, A, B, 15, 16, 0x1fa27cf8);
429       OP (FH, B, C, D, A,  2, 23, 0xc4ac5665);
430
431       /* Round 4.  */
432       OP (FI, A, B, C, D,  0,  6, 0xf4292244);
433       OP (FI, D, A, B, C,  7, 10, 0x432aff97);
434       OP (FI, C, D, A, B, 14, 15, 0xab9423a7);
435       OP (FI, B, C, D, A,  5, 21, 0xfc93a039);
436       OP (FI, A, B, C, D, 12,  6, 0x655b59c3);
437       OP (FI, D, A, B, C,  3, 10, 0x8f0ccc92);
438       OP (FI, C, D, A, B, 10, 15, 0xffeff47d);
439       OP (FI, B, C, D, A,  1, 21, 0x85845dd1);
440       OP (FI, A, B, C, D,  8,  6, 0x6fa87e4f);
441       OP (FI, D, A, B, C, 15, 10, 0xfe2ce6e0);
442       OP (FI, C, D, A, B,  6, 15, 0xa3014314);
443       OP (FI, B, C, D, A, 13, 21, 0x4e0811a1);
444       OP (FI, A, B, C, D,  4,  6, 0xf7537e82);
445       OP (FI, D, A, B, C, 11, 10, 0xbd3af235);
446       OP (FI, C, D, A, B,  2, 15, 0x2ad7d2bb);
447       OP (FI, B, C, D, A,  9, 21, 0xeb86d391);
448
449       /* Add the starting values of the context.  */
450       A += A_save;
451       B += B_save;
452       C += C_save;
453       D += D_save;
454     }
455
456   /* Put checksum in context given as argument.  */
457   ctx->A = A;
458   ctx->B = B;
459   ctx->C = C;
460   ctx->D = D;
461 }
462
463 \f
464 #ifdef emacs
465 #ifdef FILE_CODING
466 /* Find out what format the buffer will be saved in, so we can make
467    the digest based on what it will look like on disk.  */
468 static Lisp_Object
469 md5_coding_system (Lisp_Object object, Lisp_Object coding, Lisp_Object istream,
470                    int error_me_not)
471 {
472   Lisp_Object coding_system;
473
474   if (NILP (coding))
475     {
476       if (BUFFERP (object))
477         {
478           /* Use the file coding for this buffer by default.  */
479           coding_system = XBUFFER (object)->buffer_file_coding_system;
480         }
481       else
482         {
483           /* Attempt to autodetect the coding of the string.  This is
484              VERY hit-and-miss.  */
485           eol_type_t eol = EOL_AUTODETECT;
486           coding_system = Fget_coding_system (Qundecided);
487           determine_real_coding_system (XLSTREAM (istream),
488                                         &coding_system, &eol);
489         }
490       if (NILP (coding_system)) 
491         coding_system = Fget_coding_system (Qbinary);
492       else
493         {
494           coding_system = Ffind_coding_system (coding_system);
495           if (NILP (coding_system))
496             coding_system = Fget_coding_system (Qbinary);
497         }
498     }
499   else
500     {
501       coding_system = Ffind_coding_system (coding);
502       if (NILP (coding_system))
503         {
504           if (error_me_not)
505             /* Default to binary.  */
506             coding_system = Fget_coding_system (Qbinary);
507           else
508             signal_simple_error ("No such coding system", coding);
509         }
510     }
511   return coding_system;
512 }
513 #endif /* FILE_CODING */
514
515
516 DEFUN ("md5", Fmd5, 1, 5, 0, /*
517 Return the MD5 message digest of OBJECT, a buffer or string.
518
519 Optional arguments START and END denote positions for computing the
520 digest of a portion of OBJECT.
521
522 The optional CODING argument specifies the coding system the text is to be
523 represented in while computing the digest.  If unspecified, it defaults
524 to the current format of the data, or is guessed.
525
526 If NOERROR is non-nil, silently assume binary coding if the guesswork
527 fails.  Normally, an error is signaled in such case.
528
529 CODING and NOERROR arguments are meaningful only in XEmacsen with
530 file-coding or Mule support.  Otherwise, they are ignored.
531 */
532        (object, start, end, coding, noerror))
533 {
534   /* This function can GC */
535   /* Can this really GC?  How?  */
536   struct md5_ctx ctx;
537   unsigned char digest[16];
538   unsigned char thehash[33];
539   int i;
540
541   Lisp_Object instream;
542   struct gcpro gcpro1;
543 #ifdef FILE_CODING
544   Lisp_Object raw_instream;
545   struct gcpro ngcpro1;
546 #endif
547
548   /* Set up the input stream.  */
549   if (BUFFERP (object))
550     {
551       struct buffer *b;
552       Bufpos begv, endv;
553       CHECK_LIVE_BUFFER (object);
554       b = XBUFFER (object);
555       /* Figure out where we need to get info from */
556       get_buffer_range_char (b, start, end, &begv, &endv, GB_ALLOW_NIL);
557
558       instream = make_lisp_buffer_input_stream (b, begv, endv, 0);
559     }
560   else
561     {
562       Bytecount bstart, bend;
563       CHECK_STRING (object);
564       get_string_range_byte (object, start, end, &bstart, &bend,
565                              GB_HISTORICAL_STRING_BEHAVIOR);
566       instream = make_lisp_string_input_stream (object, bstart, bend - bstart);
567     }
568   GCPRO1 (instream);
569
570 #ifdef FILE_CODING
571   /* Determine the coding and set up the conversion stream.  */
572   coding = md5_coding_system (object, coding, instream, !NILP (noerror));
573   raw_instream = instream;
574   instream = make_encoding_input_stream (XLSTREAM (instream), coding);
575   NGCPRO1 (raw_instream);
576 #endif
577
578   /* Initialize MD5 context.  */
579   md5_init_ctx (&ctx);
580
581   /* Get the data while doing the conversion.  */
582   while (1)
583     {
584       Bufbyte tempbuf[1024];    /* some random amount */
585       ssize_t size_in_bytes =
586         Lstream_read (XLSTREAM (instream), tempbuf, sizeof (tempbuf));
587       if (!size_in_bytes)
588         break;
589
590       /* Process the bytes.  */
591       md5_process_bytes (tempbuf, size_in_bytes, &ctx);
592     }
593   Lstream_delete (XLSTREAM (instream));
594 #ifdef FILE_CODING
595   Lstream_delete (XLSTREAM (raw_instream));
596   NUNGCPRO;
597 #endif
598   UNGCPRO;
599
600   md5_finish_ctx (&ctx, digest);
601   for (i = 0; i < 16; i++)
602     sprintf ((char *) (thehash + (i * 2)), "%02x", digest[i]);
603
604   return make_string (thehash, 32);
605 }
606
607 void
608 syms_of_md5 (void)
609 {
610   DEFSUBR (Fmd5);
611 }
612
613 void
614 vars_of_md5 (void)
615 {
616   Fprovide (intern ("md5"));
617 }
618 #endif /* emacs */