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