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