Code

Yet another md5 fix for 32/64. This time it works on ppc64/gcc
[inkscape.git] / src / pedro / pedroutil.cpp
1 /*
2  * Support classes for the Pedro mini-XMPP client
3  *
4  * Authors:
5  *   Bob Jamison
6  *
7  * Copyright (C) 2005-2007 Bob Jamison
8  *
9  *  This library is free software; you can redistribute it and/or
10  *  modify it under the terms of the GNU Lesser General Public
11  *  License as published by the Free Software Foundation; either
12  *  version 2.1 of the License, or (at your option) any later version.
13  *
14  *  This library 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 GNU
17  *  Lesser General Public License for more details.
18  *
19  *  You should have received a copy of the GNU Lesser General Public
20  *  License along with this library; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22  */
25 #include <stdio.h>
26 #include <stdarg.h>
28 #include <sys/stat.h>
30 #include "pedroutil.h"
34 #ifdef __WIN32__
36 #include <windows.h>
38 #else /* UNIX */
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <netdb.h>
44 #include <unistd.h>
45 #include <sys/ioctl.h>
47 #include <pthread.h>
49 #endif /* UNIX */
51 #ifdef HAVE_SSL
52 RELAYTOOL_SSL
53 #endif
56 namespace Pedro
57 {
63 //########################################################################
64 //########################################################################
65 //# B A S E    6 4
66 //########################################################################
67 //########################################################################
70 //#################
71 //# ENCODER
72 //#################
75 static char *base64encode =
76     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
80 /**
81  * Writes the specified byte to the output buffer
82  */
83 void Base64Encoder::append(int ch)
84 {
85     outBuf   <<=  8;
86     outBuf   |=  (ch & 0xff);
87     bitCount +=  8;
88     if (bitCount >= 24)
89         {
90         int indx  = (int)((outBuf & 0x00fc0000L) >> 18);
91         int obyte = (int)base64encode[indx & 63];
92         buf.push_back(obyte);
94         indx      = (int)((outBuf & 0x0003f000L) >> 12);
95         obyte     = (int)base64encode[indx & 63];
96         buf.push_back(obyte);
98         indx      = (int)((outBuf & 0x00000fc0L) >>  6);
99         obyte     = (int)base64encode[indx & 63];
100         buf.push_back(obyte);
102         indx      = (int)((outBuf & 0x0000003fL)      );
103         obyte     = (int)base64encode[indx & 63];
104         buf.push_back(obyte);
106         bitCount = 0;
107         outBuf   = 0L;
108         }
111 /**
112  * Writes the specified string to the output buffer
113  */
114 void Base64Encoder::append(char *str)
116     while (*str)
117         append((int)*str++);
120 /**
121  * Writes the specified string to the output buffer
122  */
123 void Base64Encoder::append(unsigned char *str, int len)
125     while (len>0)
126         {
127         append((int)*str++);
128         len--;
129         }
132 /**
133  * Writes the specified string to the output buffer
134  */
135 void Base64Encoder::append(const DOMString &str)
137     append((char *)str.c_str());
140 /**
141  * Closes this output stream and releases any system resources
142  * associated with this stream.
143  */
144 DOMString Base64Encoder::finish()
146     //get any last bytes (1 or 2) out of the buffer
147     if (bitCount == 16)
148         {
149         outBuf <<= 2;  //pad to make 18 bits
151         int indx  = (int)((outBuf & 0x0003f000L) >> 12);
152         int obyte = (int)base64encode[indx & 63];
153         buf.push_back(obyte);
155         indx      = (int)((outBuf & 0x00000fc0L) >>  6);
156         obyte     = (int)base64encode[indx & 63];
157         buf.push_back(obyte);
159         indx      = (int)((outBuf & 0x0000003fL)      );
160         obyte     = (int)base64encode[indx & 63];
161         buf.push_back(obyte);
163         buf.push_back('=');
164         }
165     else if (bitCount == 8)
166         {
167         outBuf <<= 4; //pad to make 12 bits
169         int indx  = (int)((outBuf & 0x00000fc0L) >>  6);
170         int obyte = (int)base64encode[indx & 63];
171         buf.push_back(obyte);
173         indx      = (int)((outBuf & 0x0000003fL)      );
174         obyte     = (int)base64encode[indx & 63];
175         buf.push_back(obyte);
177         buf.push_back('=');
178         buf.push_back('=');
179         }
181     DOMString ret = buf;
182     reset();
183     return ret;
187 DOMString Base64Encoder::encode(const DOMString &str)
189     Base64Encoder encoder;
190     encoder.append(str);
191     DOMString ret = encoder.finish();
192     return ret;
197 //#################
198 //# DECODER
199 //#################
201 static int base64decode[] =
203 /*00*/    -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
204 /*08*/    -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
205 /*10*/    -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
206 /*18*/    -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
207 /*20*/    -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
208 /*28*/    -1,   -1,   -1,   62,   -1,   -1,   -1,   63,
209 /*30*/    52,   53,   54,   55,   56,   57,   58,   59,
210 /*38*/    60,   61,   -1,   -1,   -1,   -1,   -1,   -1,
211 /*40*/    -1,    0,    1,    2,    3,    4,    5,    6,
212 /*48*/     7,    8,    9,   10,   11,   12,   13,   14,
213 /*50*/    15,   16,   17,   18,   19,   20,   21,   22,
214 /*58*/    23,   24,   25,   -1,   -1,   -1,   -1,   -1,
215 /*60*/    -1,   26,   27,   28,   29,   30,   31,   32,
216 /*68*/    33,   34,   35,   36,   37,   38,   39,   40,
217 /*70*/    41,   42,   43,   44,   45,   46,   47,   48,
218 /*78*/    49,   50,   51,   -1,   -1,   -1,   -1,   -1
219 };
223 /**
224  * Appends one char to the decoder
225  */
226 void Base64Decoder::append(int ch)
228     if (isspace(ch))
229         return;
230     else if (ch == '=') //padding
231         {
232         inBytes[inCount++] = 0;
233         }
234     else
235         {
236         int byteVal = base64decode[ch & 0x7f];
237         //printf("char:%c %d\n", ch, byteVal);
238         if (byteVal < 0)
239             {
240             //Bad lookup value
241             }
242         inBytes[inCount++] = byteVal;
243         }
245     if (inCount >=4 )
246         {
247         unsigned char b0 = ((inBytes[0]<<2) & 0xfc) | ((inBytes[1]>>4) & 0x03);
248         unsigned char b1 = ((inBytes[1]<<4) & 0xf0) | ((inBytes[2]>>2) & 0x0f);
249         unsigned char b2 = ((inBytes[2]<<6) & 0xc0) | ((inBytes[3]   ) & 0x3f);
250         buf.push_back(b0);
251         buf.push_back(b1);
252         buf.push_back(b2);
253         inCount = 0;
254         }
258 void Base64Decoder::append(char *str)
260     while (*str)
261         append((int)*str++);
264 void Base64Decoder::append(const DOMString &str)
266     append((char *)str.c_str());
269 std::vector<unsigned char> Base64Decoder::finish()
271     std::vector<unsigned char> ret = buf;
272     reset();
273     return ret;
276 std::vector<unsigned char> Base64Decoder::decode(const DOMString &str)
278     Base64Decoder decoder;
279     decoder.append(str);
280     std::vector<unsigned char> ret = decoder.finish();
281     return ret;
284 DOMString Base64Decoder::decodeToString(const DOMString &str)
286     Base64Decoder decoder;
287     decoder.append(str);
288     std::vector<unsigned char> ret = decoder.finish();
289     DOMString buf;
290     for (unsigned int i=0 ; i<ret.size() ; i++)
291         buf.push_back(ret[i]);
292     return buf;
301 //########################################################################
302 //########################################################################
303 //### S H A    1      H A S H I N G
304 //########################################################################
305 //########################################################################
310 void Sha1::hash(unsigned char *dataIn, int len, unsigned char *digest)
312     Sha1 sha1;
313     sha1.append(dataIn, len);
314     sha1.finish(digest);
317 static char *sha1hex = "0123456789abcdef";
319 DOMString Sha1::hashHex(unsigned char *dataIn, int len)
321     unsigned char hashout[20];
322     hash(dataIn, len, hashout);
323     DOMString ret;
324     for (int i=0 ; i<20 ; i++)
325         {
326         unsigned char ch = hashout[i];
327         ret.push_back(sha1hex[ (ch>>4) & 15 ]);
328         ret.push_back(sha1hex[ ch      & 15 ]);
329         }
330     return ret;
334 DOMString Sha1::hashHex(const DOMString &str)
336     return hashHex((unsigned char *)str.c_str(), str.size());
340 void Sha1::init()
343     lenW   = 0;
344     sizeHi = 0;
345     sizeLo = 0;
347     // Initialize H with the magic constants (see FIPS180 for constants)
348     H[0] = 0x67452301L;
349     H[1] = 0xefcdab89L;
350     H[2] = 0x98badcfeL;
351     H[3] = 0x10325476L;
352     H[4] = 0xc3d2e1f0L;
354     for (int i = 0; i < 80; i++)
355         W[i] = 0;
359 void Sha1::append(unsigned char ch)
361     // Read the data into W and process blocks as they get full
362     W[lenW / 4] <<= 8;
363     W[lenW / 4] |= (unsigned long)ch;
364     if ((++lenW) % 64 == 0)
365         {
366         hashblock();
367         lenW = 0;
368         }
369     sizeLo += 8;
370     sizeHi += (sizeLo < 8);
374 void Sha1::append(unsigned char *dataIn, int len)
376     // Read the data into W and process blocks as they get full
377     for (int i = 0; i < len; i++)
378         append(dataIn[i]);
382 void Sha1::append(const DOMString &str)
384     append((unsigned char *)str.c_str(), str.size());
388 void Sha1::finish(unsigned char hashout[20])
390     unsigned char pad0x80 = 0x80;
391     unsigned char pad0x00 = 0x00;
392     unsigned char padlen[8];
394     // Pad with a binary 1 (e.g. 0x80), then zeroes, then length
395     padlen[0] = (unsigned char)((sizeHi >> 24) & 255);
396     padlen[1] = (unsigned char)((sizeHi >> 16) & 255);
397     padlen[2] = (unsigned char)((sizeHi >>  8) & 255);
398     padlen[3] = (unsigned char)((sizeHi >>  0) & 255);
399     padlen[4] = (unsigned char)((sizeLo >> 24) & 255);
400     padlen[5] = (unsigned char)((sizeLo >> 16) & 255);
401     padlen[6] = (unsigned char)((sizeLo >>  8) & 255);
402     padlen[7] = (unsigned char)((sizeLo >>  0) & 255);
404     append(&pad0x80, 1);
406     while (lenW != 56)
407         append(&pad0x00, 1);
408     append(padlen, 8);
410     // Output hash
411     for (int i = 0; i < 20; i++)
412         {
413         hashout[i] = (unsigned char)(H[i / 4] >> 24);
414         H[i / 4] <<= 8;
415         }
417     // Re-initialize the context (also zeroizes contents)
418     init();
422 #define SHA_ROTL(X,n) ((((X) << (n)) | ((X) >> (32-(n)))) & 0xffffffffL)
424 void Sha1::hashblock()
427     for (int t = 16; t <= 79; t++)
428         W[t] = SHA_ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
430     unsigned long A = H[0];
431     unsigned long B = H[1];
432     unsigned long C = H[2];
433     unsigned long D = H[3];
434     unsigned long E = H[4];
436     unsigned long TEMP;
438     for (int t = 0; t <= 19; t++)
439         {
440         TEMP = (SHA_ROTL(A,5) + (((C^D)&B)^D) +
441                 E + W[t] + 0x5a827999L) & 0xffffffffL;
442         E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
443         }
444     for (int t = 20; t <= 39; t++)
445         {
446         TEMP = (SHA_ROTL(A,5) + (B^C^D) +
447                 E + W[t] + 0x6ed9eba1L) & 0xffffffffL;
448         E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
449         }
450     for (int t = 40; t <= 59; t++)
451         {
452         TEMP = (SHA_ROTL(A,5) + ((B&C)|(D&(B|C))) +
453                 E + W[t] + 0x8f1bbcdcL) & 0xffffffffL;
454         E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
455         }
456     for (int t = 60; t <= 79; t++)
457         {
458         TEMP = (SHA_ROTL(A,5) + (B^C^D) +
459                 E + W[t] + 0xca62c1d6L) & 0xffffffffL;
460         E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
461         }
463     H[0] += A;
464     H[1] += B;
465     H[2] += C;
466     H[3] += D;
467     H[4] += E;
475 //########################################################################
476 //########################################################################
477 //### M D 5      H A S H I N G
478 //########################################################################
479 //########################################################################
485 void Md5::hash(unsigned char *dataIn, unsigned long len, unsigned char *digest)
487     Md5 md5;
488     md5.append(dataIn, len);
489     md5.finish(digest);
492 DOMString Md5::hashHex(unsigned char *dataIn, unsigned long len)
494     Md5 md5;
495     md5.append(dataIn, len);
496     DOMString ret = md5.finishHex();
497     return ret;
500 DOMString Md5::hashHex(const DOMString &str)
502     Md5 md5;
503     md5.append(str);
504     DOMString ret = md5.finishHex();
505     return ret;
509 /**
510  * Initialize MD5 polynomials and storage
511  */
512 void Md5::init()
514     hashBuf[0]  = 0x67452301;
515     hashBuf[1]  = 0xefcdab89;
516     hashBuf[2]  = 0x98badcfe;
517     hashBuf[3]  = 0x10325476;
519     nrBytesHi = 0;
520     nrBytesLo = 0;
521     byteNr    = 0;
522     longNr    = 0;
528 /*
529  * Update with one character
530  */
531 void Md5::append(unsigned char ch)
533     if (nrBytesLo == 0xffffffff)
534         {
535         nrBytesLo = 0;
536         nrBytesHi++;
537         }
538     else
539         nrBytesLo++;
541     //pack 64 bytes into 16 longs
542     inb[byteNr++] = (unsigned long)ch;
543     if (byteNr >= 4)
544         {
545         unsigned long val =
546              inb[3] << 24 | inb[2] << 16 | inb[1] << 8 | inb[0];
547         inBuf[longNr++] = val;
548         byteNr = 0;
549         }
550     if (longNr >= 16)
551         {
552         transform();
553         longNr = 0;
554         }
558 /*
559  * Update context to reflect the concatenation of another buffer full
560  * of bytes.
561  */
562 void Md5::append(unsigned char *source, unsigned long len)
564     while (len--)
565         append(*source++);
569 /*
570  * Update context to reflect the concatenation of another string
571  */
572 void Md5::append(const DOMString &str)
574     append((unsigned char *)str.c_str(), str.size());
578 /*
579  * Final wrapup - pad to 64-byte boundary with the bit pattern
580  * 1 0* (64-bit count of bits processed, MSB-first)
581  */
582 void Md5::finish(unsigned char *digest)
584     //snapshot the bit count now before padding
585     unsigned long nrBitsLo = nrBytesLo << 3;
586     unsigned long nrBitsHi = (nrBytesHi << 3) | ((nrBytesLo >> 29) & 7);
588     //Append terminal char
589     append(0x80);
591     //pad until we have a 56 of 64 bits, allowing for 8 bytes at the end
592     while (true)
593         {
594         int remain = (int)(nrBytesLo & 63);
595         if (remain == 56)
596             break;
597         append(0);
598         }
600     //##### Append length in bits
601     int shift;
602     shift = 0;
603     for (int i=0 ; i<4 ; i++)
604         {
605         unsigned char ch = (unsigned char)((nrBitsLo>>shift) & 0xff);
606         append(ch);
607         shift += 8;
608         }
610     shift = 0;
611     for (int i=0 ; i<4 ; i++)
612         {
613         unsigned char ch = (unsigned char)((nrBitsHi>>shift) & 0xff);
614         append(ch);
615         shift += 8;
616         }
618     //copy out answer
619     int indx = 0;
620     for (int i=0 ; i<4 ; i++)
621         {
622         digest[indx++] = (unsigned char)((hashBuf[i]      ) & 0xff);
623         digest[indx++] = (unsigned char)((hashBuf[i] >>  8) & 0xff);
624         digest[indx++] = (unsigned char)((hashBuf[i] >> 16) & 0xff);
625         digest[indx++] = (unsigned char)((hashBuf[i] >> 24) & 0xff);
626         }
628     init();  // Security!  ;-)
633 static const char *md5hex = "0123456789abcdef";
635 DOMString Md5::finishHex()
637     unsigned char hashout[16];
638     finish(hashout);
639     DOMString ret;
640     for (int i=0 ; i<16 ; i++)
641         {
642         unsigned char ch = hashout[i];
643         ret.push_back(md5hex[ (ch>>4) & 15 ]);
644         ret.push_back(md5hex[ ch      & 15 ]);
645         }
646     return ret;
651 //#  The four core functions - F1 is optimized somewhat
653 // #define F1(x, y, z) (x & y | ~x & z)
654 #define M(x) ((x) &= 0xffffffff)
655 #define F1(x, y, z) (z ^ (x & (y ^ z)))
656 #define F2(x, y, z) F1(z, x, y)
657 #define F3(x, y, z) (x ^ y ^ z)
658 #define F4(x, y, z) (y ^ (x | ~z))
660 // ## This is the central step in the MD5 algorithm.
661 #define MD5STEP(f, w, x, y, z, data, s) \
662         ( w += (f(x, y, z) + data), M(w), w = w<<s | w>>(32-s), w += x, M(w) )
664 /*
665  * The core of the MD5 algorithm, this alters an existing MD5 hash to
666  * reflect the addition of 16 longwords of new data.  MD5Update blocks
667  * the data and converts bytes into longwords for this routine.
668  * @parm buf points to an array of 4 unsigned longs
669  * @parm in points to an array of 16 unsigned longs
670  */
671 void Md5::transform()
673     unsigned long *i = inBuf;
674     unsigned long a  = hashBuf[0];
675     unsigned long b  = hashBuf[1];
676     unsigned long c  = hashBuf[2];
677     unsigned long d  = hashBuf[3];
679     MD5STEP(F1, a, b, c, d, i[ 0] + 0xd76aa478,  7);
680     MD5STEP(F1, d, a, b, c, i[ 1] + 0xe8c7b756, 12);
681     MD5STEP(F1, c, d, a, b, i[ 2] + 0x242070db, 17);
682     MD5STEP(F1, b, c, d, a, i[ 3] + 0xc1bdceee, 22);
683     MD5STEP(F1, a, b, c, d, i[ 4] + 0xf57c0faf,  7);
684     MD5STEP(F1, d, a, b, c, i[ 5] + 0x4787c62a, 12);
685     MD5STEP(F1, c, d, a, b, i[ 6] + 0xa8304613, 17);
686     MD5STEP(F1, b, c, d, a, i[ 7] + 0xfd469501, 22);
687     MD5STEP(F1, a, b, c, d, i[ 8] + 0x698098d8,  7);
688     MD5STEP(F1, d, a, b, c, i[ 9] + 0x8b44f7af, 12);
689     MD5STEP(F1, c, d, a, b, i[10] + 0xffff5bb1, 17);
690     MD5STEP(F1, b, c, d, a, i[11] + 0x895cd7be, 22);
691     MD5STEP(F1, a, b, c, d, i[12] + 0x6b901122,  7);
692     MD5STEP(F1, d, a, b, c, i[13] + 0xfd987193, 12);
693     MD5STEP(F1, c, d, a, b, i[14] + 0xa679438e, 17);
694     MD5STEP(F1, b, c, d, a, i[15] + 0x49b40821, 22);
696     MD5STEP(F2, a, b, c, d, i[ 1] + 0xf61e2562,  5);
697     MD5STEP(F2, d, a, b, c, i[ 6] + 0xc040b340,  9);
698     MD5STEP(F2, c, d, a, b, i[11] + 0x265e5a51, 14);
699     MD5STEP(F2, b, c, d, a, i[ 0] + 0xe9b6c7aa, 20);
700     MD5STEP(F2, a, b, c, d, i[ 5] + 0xd62f105d,  5);
701     MD5STEP(F2, d, a, b, c, i[10] + 0x02441453,  9);
702     MD5STEP(F2, c, d, a, b, i[15] + 0xd8a1e681, 14);
703     MD5STEP(F2, b, c, d, a, i[ 4] + 0xe7d3fbc8, 20);
704     MD5STEP(F2, a, b, c, d, i[ 9] + 0x21e1cde6,  5);
705     MD5STEP(F2, d, a, b, c, i[14] + 0xc33707d6,  9);
706     MD5STEP(F2, c, d, a, b, i[ 3] + 0xf4d50d87, 14);
707     MD5STEP(F2, b, c, d, a, i[ 8] + 0x455a14ed, 20);
708     MD5STEP(F2, a, b, c, d, i[13] + 0xa9e3e905,  5);
709     MD5STEP(F2, d, a, b, c, i[ 2] + 0xfcefa3f8,  9);
710     MD5STEP(F2, c, d, a, b, i[ 7] + 0x676f02d9, 14);
711     MD5STEP(F2, b, c, d, a, i[12] + 0x8d2a4c8a, 20);
713     MD5STEP(F3, a, b, c, d, i[ 5] + 0xfffa3942,  4);
714     MD5STEP(F3, d, a, b, c, i[ 8] + 0x8771f681, 11);
715     MD5STEP(F3, c, d, a, b, i[11] + 0x6d9d6122, 16);
716     MD5STEP(F3, b, c, d, a, i[14] + 0xfde5380c, 23);
717     MD5STEP(F3, a, b, c, d, i[ 1] + 0xa4beea44,  4);
718     MD5STEP(F3, d, a, b, c, i[ 4] + 0x4bdecfa9, 11);
719     MD5STEP(F3, c, d, a, b, i[ 7] + 0xf6bb4b60, 16);
720     MD5STEP(F3, b, c, d, a, i[10] + 0xbebfbc70, 23);
721     MD5STEP(F3, a, b, c, d, i[13] + 0x289b7ec6,  4);
722     MD5STEP(F3, d, a, b, c, i[ 0] + 0xeaa127fa, 11);
723     MD5STEP(F3, c, d, a, b, i[ 3] + 0xd4ef3085, 16);
724     MD5STEP(F3, b, c, d, a, i[ 6] + 0x04881d05, 23);
725     MD5STEP(F3, a, b, c, d, i[ 9] + 0xd9d4d039,  4);
726     MD5STEP(F3, d, a, b, c, i[12] + 0xe6db99e5, 11);
727     MD5STEP(F3, c, d, a, b, i[15] + 0x1fa27cf8, 16);
728     MD5STEP(F3, b, c, d, a, i[ 2] + 0xc4ac5665, 23);
730     MD5STEP(F4, a, b, c, d, i[ 0] + 0xf4292244,  6);
731     MD5STEP(F4, d, a, b, c, i[ 7] + 0x432aff97, 10);
732     MD5STEP(F4, c, d, a, b, i[14] + 0xab9423a7, 15);
733     MD5STEP(F4, b, c, d, a, i[ 5] + 0xfc93a039, 21);
734     MD5STEP(F4, a, b, c, d, i[12] + 0x655b59c3,  6);
735     MD5STEP(F4, d, a, b, c, i[ 3] + 0x8f0ccc92, 10);
736     MD5STEP(F4, c, d, a, b, i[10] + 0xffeff47d, 15);
737     MD5STEP(F4, b, c, d, a, i[ 1] + 0x85845dd1, 21);
738     MD5STEP(F4, a, b, c, d, i[ 8] + 0x6fa87e4f,  6);
739     MD5STEP(F4, d, a, b, c, i[15] + 0xfe2ce6e0, 10);
740     MD5STEP(F4, c, d, a, b, i[ 6] + 0xa3014314, 15);
741     MD5STEP(F4, b, c, d, a, i[13] + 0x4e0811a1, 21);
742     MD5STEP(F4, a, b, c, d, i[ 4] + 0xf7537e82,  6);
743     MD5STEP(F4, d, a, b, c, i[11] + 0xbd3af235, 10);
744     MD5STEP(F4, c, d, a, b, i[ 2] + 0x2ad7d2bb, 15);
745     MD5STEP(F4, b, c, d, a, i[ 9] + 0xeb86d391, 21);
747     hashBuf[0] += a;
748     hashBuf[1] += b;
749     hashBuf[2] += c;
750     hashBuf[3] += d;
759 //########################################################################
760 //########################################################################
761 //### T H R E A D
762 //########################################################################
763 //########################################################################
769 #ifdef __WIN32__
772 static DWORD WINAPI WinThreadFunction(LPVOID context)
774     Thread *thread = (Thread *)context;
775     thread->execute();
776     return 0;
780 void Thread::start()
782     DWORD dwThreadId;
783     HANDLE hThread = CreateThread(NULL, 0, WinThreadFunction,
784                (LPVOID)this,  0,  &dwThreadId);
785     //Make sure the thread is started before 'this' is deallocated
786     while (!started)
787         sleep(10);
788     CloseHandle(hThread);
791 void Thread::sleep(unsigned long millis)
793     Sleep(millis);
796 #else /* UNIX */
799 void *PthreadThreadFunction(void *context)
801     Thread *thread = (Thread *)context;
802     thread->execute();
803     return NULL;
807 void Thread::start()
809     pthread_t thread;
811     int ret = pthread_create(&thread, NULL,
812             PthreadThreadFunction, (void *)this);
813     if (ret != 0)
814         printf("Thread::start: thread creation failed: %s\n", strerror(ret));
816     //Make sure the thread is started before 'this' is deallocated
817     while (!started)
818         sleep(10);
822 void Thread::sleep(unsigned long millis)
824     timespec requested;
825     requested.tv_sec = millis / 1000;
826     requested.tv_nsec = (millis % 1000 ) * 1000000L;
827     nanosleep(&requested, NULL);
830 #endif
839 //########################################################################
840 //########################################################################
841 //### S O C K E T
842 //########################################################################
843 //########################################################################
849 //#########################################################################
850 //# U T I L I T Y
851 //#########################################################################
853 static void mybzero(void *s, size_t n)
855     unsigned char *p = (unsigned char *)s;
856     while (n > 0)
857         {
858         *p++ = (unsigned char)0;
859         n--;
860         }
863 static void mybcopy(void *src, void *dest, size_t n)
865     unsigned char *p = (unsigned char *)dest;
866     unsigned char *q = (unsigned char *)src;
867     while (n > 0)
868         {
869         *p++ = *q++;
870         n--;
871         }
876 //#########################################################################
877 //# T C P    C O N N E C T I O N
878 //#########################################################################
880 TcpSocket::TcpSocket()
882     init();
886 TcpSocket::TcpSocket(const std::string &hostnameArg, int port)
888     init();
889     hostname  = hostnameArg;
890     portno    = port;
896 #ifdef HAVE_SSL
898 static void cryptoLockCallback(int mode, int type, const char *file, int line)
900     //printf("########### LOCK\n");
901     static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */
902     const char *errstr = NULL;
904     int rw = mode & (CRYPTO_READ|CRYPTO_WRITE);
905     if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE)))
906         {
907         errstr = "invalid mode";
908         goto err;
909         }
911     if (type < 0 || type >= CRYPTO_NUM_LOCKS)
912         {
913         errstr = "type out of bounds";
914         goto err;
915         }
917     if (mode & CRYPTO_LOCK)
918         {
919         if (modes[type])
920             {
921             errstr = "already locked";
922             /* must not happen in a single-threaded program
923              * (would deadlock)
924              */
925             goto err;
926             }
928         modes[type] = rw;
929         }
930     else if (mode & CRYPTO_UNLOCK)
931         {
932         if (!modes[type])
933             {
934              errstr = "not locked";
935              goto err;
936              }
938         if (modes[type] != rw)
939             {
940             errstr = (rw == CRYPTO_READ) ?
941                   "CRYPTO_r_unlock on write lock" :
942                   "CRYPTO_w_unlock on read lock";
943             }
945         modes[type] = 0;
946         }
947     else
948         {
949         errstr = "invalid mode";
950         goto err;
951         }
953     err:
954     if (errstr)
955         {
956         //how do we pass a context pointer here?
957         //error("openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d",
958         //        errstr, mode, type, file, line);
959         }
962 static unsigned long cryptoIdCallback()
964 #ifdef __WIN32__
965     unsigned long ret = (unsigned long) GetCurrentThreadId();
966 #else
967     unsigned long ret = (unsigned long) pthread_self();
968 #endif
969     return ret;
972 #endif
975 TcpSocket::TcpSocket(const TcpSocket &other)
977     init();
978     sock      = other.sock;
979     hostname  = other.hostname;
980     portno    = other.portno;
984 void TcpSocket::error(char *fmt, ...)
986     static char buf[256];
987     lastError = "TcpSocket err: ";
988     va_list args;
989     va_start(args, fmt);
990     vsnprintf(buf, 255, fmt, args);
991     va_end(args);
992     lastError.append(buf);
993     fprintf(stderr, "%s\n", lastError.c_str());
997 DOMString &TcpSocket::getLastError()
999     return lastError;
1004 static bool tcp_socket_inited = false;
1006 void TcpSocket::init()
1008     if (!tcp_socket_inited)
1009         {
1010 #ifdef __WIN32__
1011         WORD wVersionRequested = MAKEWORD( 2, 2 );
1012         WSADATA wsaData;
1013         WSAStartup( wVersionRequested, &wsaData );
1014 #endif
1015 #ifdef HAVE_SSL
1016         if (libssl_is_present)
1017         {
1018         sslStream  = NULL;
1019         sslContext = NULL;
1020             CRYPTO_set_locking_callback(cryptoLockCallback);
1021         CRYPTO_set_id_callback(cryptoIdCallback);
1022         SSL_library_init();
1023         SSL_load_error_strings();
1024         }
1025 #endif
1026         tcp_socket_inited = true;
1027         }
1028     sock           = -1;
1029     connected      = false;
1030     hostname       = "";
1031     portno         = -1;
1032     sslEnabled     = false;
1033     receiveTimeout = 0;
1036 TcpSocket::~TcpSocket()
1038     disconnect();
1041 bool TcpSocket::isConnected()
1043     if (!connected || sock < 0)
1044         return false;
1045     return true;
1048 bool TcpSocket::getHaveSSL()
1050 #ifdef HAVE_SSL
1051     if (libssl_is_present)
1052     {
1053         return true;
1054     } else {
1055         return false;
1056     }
1057 #else
1058     return false;
1059 #endif
1062 void TcpSocket::enableSSL(bool val)
1064     sslEnabled = val;
1067 bool TcpSocket::getEnableSSL()
1069     return sslEnabled;
1074 bool TcpSocket::connect(const std::string &hostnameArg, int portnoArg)
1076     hostname = hostnameArg;
1077     portno   = portnoArg;
1078     return connect();
1083 #ifdef HAVE_SSL
1084 /*
1085 static int password_cb(char *buf, int bufLen, int rwflag, void *userdata)
1087     char *password = "password";
1088     if (bufLen < (int)(strlen(password)+1))
1089         return 0;
1091     strcpy(buf,password);
1092     int ret = strlen(password);
1093     return ret;
1096 static void infoCallback(const SSL *ssl, int where, int ret)
1098     switch (where)
1099         {
1100         case SSL_CB_ALERT:
1101             {
1102             printf("## %d SSL ALERT: %s\n",  where, SSL_alert_desc_string_long(ret));
1103             break;
1104             }
1105         default:
1106             {
1107             printf("## %d SSL: %s\n",  where, SSL_state_string_long(ssl));
1108             break;
1109             }
1110         }
1112 */
1113 #endif
1116 bool TcpSocket::startTls()
1118 #ifndef HAVE_SSL
1119     error("SSL starttls() error:  client not compiled with SSL enabled");
1120     return false;
1121 #else /*HAVE_SSL*/
1122     if (!libssl_is_present)
1123         {
1124         error("SSL starttls() error:  the correct version of libssl was not found");
1125         return false;
1126         }
1128     sslStream  = NULL;
1129     sslContext = NULL;
1131     //SSL_METHOD *meth = SSLv23_method();
1132     //SSL_METHOD *meth = SSLv3_client_method();
1133     SSL_METHOD *meth = TLSv1_client_method();
1134     sslContext = SSL_CTX_new(meth);
1135     //SSL_CTX_set_info_callback(sslContext, infoCallback);
1137     /**
1138      * For now, let's accept all connections.  Ignore this
1139      * block of code     
1140      *       
1141     char *keyFile  = "client.pem";
1142     char *caList   = "root.pem";
1143     //#  Load our keys and certificates
1144     if (!(SSL_CTX_use_certificate_chain_file(sslContext, keyFile)))
1145         {
1146         fprintf(stderr, "Can't read certificate file\n");
1147         disconnect();
1148         return false;
1149         }
1151     SSL_CTX_set_default_passwd_cb(sslContext, password_cb);
1153     if (!(SSL_CTX_use_PrivateKey_file(sslContext, keyFile, SSL_FILETYPE_PEM)))
1154         {
1155         fprintf(stderr, "Can't read key file\n");
1156         disconnect();
1157         return false;
1158         }
1160     //## Load the CAs we trust
1161     if (!(SSL_CTX_load_verify_locations(sslContext, caList, 0)))
1162         {
1163         fprintf(stderr, "Can't read CA list\n");
1164         disconnect();
1165         return false;
1166         }
1167     */
1169     /* Connect the SSL socket */
1170     sslStream  = SSL_new(sslContext);
1171     SSL_set_fd(sslStream, sock);
1173     int ret = SSL_connect(sslStream);
1174     if (ret == 0)
1175         {
1176         error("SSL connection not successful");
1177         disconnect();
1178         return false;
1179         }
1180     else if (ret < 0)
1181         {
1182         int err = SSL_get_error(sslStream, ret);
1183         error("SSL connect error %d", err);
1184         disconnect();
1185         return false;
1186         }
1188     sslEnabled = true;
1189     return true;
1190 #endif /* HAVE_SSL */
1194 bool TcpSocket::connect()
1196     if (hostname.size()<1)
1197         {
1198         error("open: null hostname");
1199         return false;
1200         }
1202     if (portno<1)
1203         {
1204         error("open: bad port number");
1205         return false;
1206         }
1208     sock = socket(PF_INET, SOCK_STREAM, 0);
1209     if (sock < 0)
1210         {
1211         error("open: error creating socket");
1212         return false;
1213         }
1215     char *c_hostname = (char *)hostname.c_str();
1216     struct hostent *server = gethostbyname(c_hostname);
1217     if (!server)
1218         {
1219         error("open: could not locate host '%s'", c_hostname);
1220         return false;
1221         }
1223     struct sockaddr_in serv_addr;
1224     mybzero((char *) &serv_addr, sizeof(serv_addr));
1225     serv_addr.sin_family = AF_INET;
1226     mybcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,
1227          server->h_length);
1228     serv_addr.sin_port = htons(portno);
1230     int ret = ::connect(sock, (const sockaddr *)&serv_addr, sizeof(serv_addr));
1231     if (ret < 0)
1232         {
1233         error("open: could not connect to host '%s'", c_hostname);
1234         return false;
1235         }
1237      if (sslEnabled)
1238         {
1239         if (!startTls())
1240             return false;
1241         }
1242     connected = true;
1243     return true;
1246 bool TcpSocket::disconnect()
1248     bool ret  = true;
1249     connected = false;
1250 #ifdef HAVE_SSL
1251     if (libssl_is_present)
1252     {
1253     if (sslEnabled)
1254         {
1255         if (sslStream)
1256             {
1257             int r = SSL_shutdown(sslStream);
1258             switch(r)
1259                 {
1260                 case 1:
1261                     break; /* Success */
1262                 case 0:
1263                 case -1:
1264                 default:
1265                     error("Shutdown failed");
1266                     ret = false;
1267                 }
1268             SSL_free(sslStream);
1269             }
1270         if (sslContext)
1271             SSL_CTX_free(sslContext);
1272         }
1273     sslStream  = NULL;
1274     sslContext = NULL;
1275     }
1276 #endif /*HAVE_SSL*/
1278 #ifdef __WIN32__
1279     closesocket(sock);
1280 #else
1281     ::close(sock);
1282 #endif
1283     sock = -1;
1284     sslEnabled = false;
1286     return ret;
1291 bool TcpSocket::setReceiveTimeout(unsigned long millis)
1293     receiveTimeout = millis;
1294     return true;
1297 /**
1298  * For normal sockets, return the number of bytes waiting to be received.
1299  * For SSL, just return >0 when something is ready to be read.
1300  */
1301 long TcpSocket::available()
1303     if (!isConnected())
1304         return -1;
1306     long count = 0;
1307 #ifdef __WIN32__
1308     if (ioctlsocket(sock, FIONREAD, (unsigned long *)&count) != 0)
1309         return -1;
1310 #else
1311     if (ioctl(sock, FIONREAD, &count) != 0)
1312         return -1;
1313 #endif
1314     if (count<=0 && sslEnabled)
1315         {
1316 #ifdef HAVE_SSL
1317             if (libssl_is_present)
1318                 {
1319             return SSL_pending(sslStream);
1320                 }
1321 #endif
1322         }
1323     return count;
1328 bool TcpSocket::write(int ch)
1330     if (!isConnected())
1331         {
1332         error("write: socket closed");
1333         return false;
1334         }
1335     unsigned char c = (unsigned char)ch;
1337     if (sslEnabled)
1338         {
1339 #ifdef HAVE_SSL
1340         if (libssl_is_present)
1341         {
1342         int r = SSL_write(sslStream, &c, 1);
1343         if (r<=0)
1344             {
1345             switch(SSL_get_error(sslStream, r))
1346                 {
1347                 default:
1348                     error("SSL write problem");
1349                     return -1;
1350                 }
1351             }
1352         }
1353 #endif
1354         }
1355     else
1356         {
1357         if (send(sock, (const char *)&c, 1, 0) < 0)
1358         //if (send(sock, &c, 1, 0) < 0)
1359             {
1360             error("write: could not send data");
1361             return false;
1362             }
1363         }
1364     return true;
1367 bool TcpSocket::write(char *str)
1369    if (!isConnected())
1370         {
1371         error("write(str): socket closed");
1372         return false;
1373         }
1374     int len = strlen(str);
1376     if (sslEnabled)
1377         {
1378 #ifdef HAVE_SSL
1379         if (libssl_is_present)
1380         {
1381         int r = SSL_write(sslStream, (unsigned char *)str, len);
1382         if (r<=0)
1383             {
1384             switch(SSL_get_error(sslStream, r))
1385                 {
1386                 default:
1387                     error("SSL write problem");
1388                     return -1;
1389                 }
1390             }
1391         }
1392 #endif
1393         }
1394     else
1395         {
1396         if (send(sock, str, len, 0) < 0)
1397         //if (send(sock, &c, 1, 0) < 0)
1398             {
1399             error("write: could not send data");
1400             return false;
1401             }
1402         }
1403     return true;
1406 bool TcpSocket::write(const std::string &str)
1408     return write((char *)str.c_str());
1411 int TcpSocket::read()
1413     if (!isConnected())
1414         return -1;
1416     //We'll use this loop for timeouts, so that SSL and plain sockets
1417     //will behave the same way
1418     if (receiveTimeout > 0)
1419         {
1420         unsigned long tim = 0;
1421         while (true)
1422             {
1423             int avail = available();
1424             if (avail > 0)
1425                 break;
1426             if (tim >= receiveTimeout)
1427                 return -2;
1428             Thread::sleep(20);
1429             tim += 20;
1430             }
1431         }
1433     //check again
1434     if (!isConnected())
1435         return -1;
1437     unsigned char ch;
1438     if (sslEnabled)
1439         {
1440 #ifdef HAVE_SSL
1441         if (libssl_is_present)
1442         {
1443         if (!sslStream)
1444             return -1;
1445         int r = SSL_read(sslStream, &ch, 1);
1446         unsigned long err = SSL_get_error(sslStream, r);
1447         switch (err)
1448             {
1449             case SSL_ERROR_NONE:
1450                  break;
1451             case SSL_ERROR_ZERO_RETURN:
1452                 return -1;
1453             case SSL_ERROR_SYSCALL:
1454                 error("SSL read problem(syscall) %s",
1455                      ERR_error_string(ERR_get_error(), NULL));
1456                 return -1;
1457             default:
1458                 error("SSL read problem %s",
1459                      ERR_error_string(ERR_get_error(), NULL));
1460                 return -1;
1461             }
1462         }
1463 #endif
1464         }
1465     else
1466         {
1467         if (recv(sock, (char *)&ch, 1, 0) <= 0)
1468             {
1469             error("read: could not receive data");
1470             disconnect();
1471             return -1;
1472             }
1473         }
1474     return (int)ch;
1477 std::string TcpSocket::readLine()
1479     std::string ret;
1481     while (isConnected())
1482         {
1483         int ch = read();
1484         if (ch<0)
1485             return ret;
1486         if (ch=='\r' || ch=='\n')
1487             return ret;
1488         ret.push_back((char)ch);
1489         }
1491     return ret;
1502 } //namespace Pedro
1503 //########################################################################
1504 //# E N D    O F     F I L E
1505 //########################################################################