b685f0557d0b10613f984d09ffcb6a928030fccb
[silc.git] / lib / silcutil / silcstrutil.c
1 /*
2
3   silcstrutil.c 
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2002 Pekka Riikonen
8
9   This program 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; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /* $Id$ */
20
21 #include "silcincludes.h"
22 #include "silcstrutil.h"
23
24 static unsigned char pem_enc[64] =
25 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
26
27 /* Encodes data into PEM encoding. Returns NULL terminated PEM encoded
28    data string. Note: This is originally public domain code and is
29    still PD. */
30
31 char *silc_pem_encode(unsigned char *data, SilcUInt32 len)
32 {
33   int i, j;
34   SilcUInt32 bits, c, char_count;
35   char *pem;
36
37   char_count = 0;
38   bits = 0;
39   j = 0;
40
41   pem = silc_calloc(((len * 8 + 5) / 6) + 5, sizeof(*pem));
42
43   for (i = 0; i < len; i++) {
44     c = data[i];
45     bits += c;
46     char_count++;
47
48     if (char_count == 3) {
49       pem[j++] = pem_enc[bits  >> 18];
50       pem[j++] = pem_enc[(bits >> 12) & 0x3f];
51       pem[j++] = pem_enc[(bits >> 6)  & 0x3f];
52       pem[j++] = pem_enc[bits & 0x3f];
53       bits = 0;
54       char_count = 0;
55     } else {
56       bits <<= 8;
57     }
58   }
59
60   if (char_count != 0) {
61     bits <<= 16 - (8 * char_count);
62     pem[j++] = pem_enc[bits >> 18];
63     pem[j++] = pem_enc[(bits >> 12) & 0x3f];
64
65     if (char_count == 1) {
66       pem[j++] = '=';
67       pem[j] = '=';
68     } else {
69       pem[j++] = pem_enc[(bits >> 6) & 0x3f];
70       pem[j] = '=';
71     }
72   }
73
74   return pem;
75 }
76
77 /* Same as above but puts newline ('\n') every 72 characters. */
78
79 char *silc_pem_encode_file(unsigned char *data, SilcUInt32 data_len)
80 {
81   int i, j;
82   SilcUInt32 len, cols;
83   char *pem, *pem2;
84
85   pem = silc_pem_encode(data, data_len);
86   len = strlen(pem);
87
88   pem2 = silc_calloc(len + (len / 72) + 1, sizeof(*pem2));
89
90   for (i = 0, j = 0, cols = 1; i < len; i++, cols++) {
91     if (cols == 72) {
92       pem2[i] = '\n';
93       cols = 0;
94       len++;
95       continue;
96     }
97
98     pem2[i] = pem[j++];
99   }
100
101   silc_free(pem);
102   return pem2;
103 }
104
105 /* Decodes PEM into data. Returns the decoded data. Note: This is
106    originally public domain code and is still PD. */
107
108 unsigned char *silc_pem_decode(unsigned char *pem, SilcUInt32 pem_len,
109                                SilcUInt32 *ret_len)
110 {
111   int i, j;
112   SilcUInt32 len, c, char_count, bits;
113   unsigned char *data;
114   static char ialpha[256], decoder[256];
115
116   for (i = 64 - 1; i >= 0; i--) {
117     ialpha[pem_enc[i]] = 1;
118     decoder[pem_enc[i]] = i;
119   }
120
121   char_count = 0;
122   bits = 0;
123   j = 0;
124
125   if (!pem_len)
126     len = strlen(pem);
127   else
128     len = pem_len;
129
130   data = silc_calloc(((len * 6) / 8), sizeof(*data));
131
132   for (i = 0; i < len; i++) {
133     c = pem[i];
134
135     if (c == '=')
136       break;
137
138     if (c > 127 || !ialpha[c])
139       continue;
140
141     bits += decoder[c];
142     char_count++;
143
144     if (char_count == 4) {
145       data[j++] = bits >> 16;
146       data[j++] = (bits >> 8) & 0xff;
147       data[j++] = bits & 0xff;
148       bits = 0;
149       char_count = 0;
150     } else {
151       bits <<= 6;
152     }
153   }
154
155   switch(char_count) {
156   case 1:
157     silc_free(data);
158     return NULL;
159     break;
160   case 2:
161     data[j++] = bits >> 10;
162     break;
163   case 3:
164     data[j++] = bits >> 16;
165     data[j++] = (bits >> 8) & 0xff;
166     break;
167   }
168
169   if (ret_len)
170     *ret_len = j;
171
172   return data;
173 }
174
175 /* Encodes the string `bin' of which encoding is `bin_encoding' to the
176    UTF-8 encoding into the buffer `utf8' which is of size of `utf8_size'.
177    Returns the length of the UTF-8 encoded string, or zero (0) on error.
178    By default `bin_encoding' is ASCII, and the caller needs to know the
179    encoding of the input string if it is anything else. */
180
181 SilcUInt32 silc_utf8_encode(const unsigned char *bin, SilcUInt32 bin_len,
182                             SilcStringEncoding bin_encoding,
183                             unsigned char *utf8, SilcUInt32 utf8_size)
184 {
185   SilcUInt32 enclen = 0, i, charval = 0;
186
187   if (!bin || !bin_len)
188     return 0;
189
190   if (silc_utf8_valid(bin, bin_len) && bin_len <= utf8_size) {
191     memcpy(utf8, bin, bin_len);
192     return bin_len;
193   }
194
195   if (bin_encoding == SILC_STRING_LANGUAGE) {
196 #if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) && defined(CODESET)
197     char *fromconv, *icp, *ocp;
198     iconv_t icd;
199     size_t inlen, outlen;
200
201     setlocale(LC_CTYPE, "");
202     fromconv = nl_langinfo(CODESET);
203     if (fromconv && strlen(fromconv)) {
204       icd = iconv_open("UTF-8", fromconv);
205       icp = (char *)bin;
206       ocp = (char *)utf8;
207       inlen = bin_len;
208       outlen = utf8_size;
209       if (icp && ocp && icd != (iconv_t)-1) {
210         if (iconv(icd, &icp, &inlen, &ocp, &outlen) != -1) {
211           utf8_size -= outlen;
212           iconv_close(icd);
213           return utf8_size;
214         }
215       }
216       if (icd != (iconv_t)-1)
217         iconv_close(icd);
218     }
219 #endif
220
221     /* Fallback to 8-bit ASCII */
222     bin_encoding = SILC_STRING_ASCII;
223   }
224
225   for (i = 0; i < bin_len; i++) {
226     switch (bin_encoding) {
227     case SILC_STRING_ASCII:
228       charval = bin[i];
229       break;
230     case SILC_STRING_ASCII_ESC:
231       SILC_NOT_IMPLEMENTED("SILC_STRING_ASCII_ESC");
232       return 0;
233       break;
234     case SILC_STRING_BMP:
235       SILC_GET16_MSB(charval, bin + i);
236       i += 1;
237       break;
238     case SILC_STRING_BMP_LSB:
239       SILC_GET16_LSB(charval, bin + i);
240       i += 1;
241       break;
242     case SILC_STRING_UNIVERSAL:
243       SILC_GET32_MSB(charval, bin + i);
244       i += 3;
245       break;
246     case SILC_STRING_UNIVERSAL_LSB:
247       SILC_GET32_LSB(charval, bin + i);
248       i += 3;
249       break;
250     case SILC_STRING_LANGUAGE:
251       break;
252     }
253
254     if (charval < 0x80) {
255       if (utf8) {
256         if (enclen > utf8_size)
257           return 0;
258
259         utf8[enclen] = (unsigned char)charval;
260       }
261       enclen++;
262     } else if (charval < 0x800) {
263       if (utf8) {
264         if (enclen + 2 > utf8_size)
265           return 0;
266
267         utf8[enclen    ] = (unsigned char )(((charval >> 6)  & 0x1f) | 0xc0);
268         utf8[enclen + 1] = (unsigned char )((charval & 0x3f) | 0x80);
269       }
270       enclen += 2;
271     } else if (charval < 0x10000) {
272       if (utf8) {
273         if (enclen + 3 > utf8_size)
274           return 0;
275
276         utf8[enclen    ] = (unsigned char )(((charval >> 12) & 0xf)  | 0xe0);
277         utf8[enclen + 1] = (unsigned char )(((charval >> 6)  & 0x3f) | 0x80);
278         utf8[enclen + 2] = (unsigned char )((charval & 0x3f) | 0x80);
279       }
280       enclen += 3;
281     } else if (charval < 0x200000) {
282       if (utf8) {
283         if (enclen + 4 > utf8_size)
284           return 0;
285
286         utf8[enclen    ] = (unsigned char )(((charval >> 18) & 0x7)  | 0xf0);
287         utf8[enclen + 1] = (unsigned char )(((charval >> 12) & 0x3f) | 0x80);
288         utf8[enclen + 2] = (unsigned char )(((charval >> 6)  & 0x3f) | 0x80);
289         utf8[enclen + 3] = (unsigned char )((charval & 0x3f) | 0x80);
290       }
291       enclen += 4;
292     } else if (charval < 0x4000000) {
293       if (utf8) {
294         if (enclen + 5 > utf8_size)
295           return 0;
296
297         utf8[enclen    ] = (unsigned char )(((charval >> 24) & 0x3)  | 0xf8);
298         utf8[enclen + 1] = (unsigned char )(((charval >> 18) & 0x3f) | 0x80);
299         utf8[enclen + 2] = (unsigned char )(((charval >> 12) & 0x3f) | 0x80);
300         utf8[enclen + 3] = (unsigned char )(((charval >> 6)  & 0x3f) | 0x80);
301         utf8[enclen + 4] = (unsigned char )((charval & 0x3f) | 0x80);
302       }
303       enclen += 5;
304     } else {
305       if (utf8) {
306         if (enclen + 6 > utf8_size)
307           return 0;
308
309         utf8[enclen    ] = (unsigned char )(((charval >> 30) & 0x1)  | 0xfc);
310         utf8[enclen + 1] = (unsigned char )(((charval >> 24) & 0x3f) | 0x80);
311         utf8[enclen + 2] = (unsigned char )(((charval >> 18) & 0x3f) | 0x80);
312         utf8[enclen + 3] = (unsigned char )(((charval >> 12) & 0x3f) | 0x80);
313         utf8[enclen + 4] = (unsigned char )(((charval >> 6)  & 0x3f) | 0x80);
314         utf8[enclen + 5] = (unsigned char )((charval & 0x3f) | 0x80);
315       }
316       enclen += 6;
317     }
318   }
319
320   return enclen;
321 }
322
323 /* Decodes UTF-8 encoded string `utf8' to string of which encoding is
324    to be `bin_encoding', into the `bin' buffer of size of `bin_size'.
325    Returns the length of the decoded buffer, or zero (0) on error.
326    By default `bin_encoding' is ASCII, and the caller needs to know to
327    which encoding the output string is to be encoded if ASCII is not
328    desired. */
329
330 SilcUInt32 silc_utf8_decode(const unsigned char *utf8, SilcUInt32 utf8_len,
331                             SilcStringEncoding bin_encoding,
332                             unsigned char *bin, SilcUInt32 bin_size)
333 {
334   SilcUInt32 enclen = 0, i, charval;
335
336   if (!utf8 || !utf8_len)
337     return 0;
338
339   if (bin_encoding == SILC_STRING_LANGUAGE) {
340 #if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) && defined(CODESET)
341     char *toconv, *icp, *ocp;
342     iconv_t icd;
343     size_t inlen, outlen;
344
345     setlocale(LC_CTYPE, "");
346     toconv = nl_langinfo(CODESET);
347     if (toconv && strlen(toconv)) {
348       icd = iconv_open(toconv, "UTF-8");
349       icp = (char *)utf8;
350       ocp = (char *)bin;
351       inlen = utf8_len;
352       outlen = bin_size;
353       if (icp && ocp && icd != (iconv_t)-1) {
354         if (iconv(icd, &icp, &inlen, &ocp, &outlen) != -1) {
355           bin_size -= outlen;
356           iconv_close(icd);
357           return bin_size;
358         }
359       }
360       if (icd != (iconv_t)-1)
361         iconv_close(icd);
362     }
363 #endif
364
365     /* Fallback to 8-bit ASCII */
366     bin_encoding = SILC_STRING_ASCII;
367   }
368
369   for (i = 0; i < utf8_len; i++) {
370     if ((utf8[i] & 0x80) == 0x00) {
371       charval = utf8[i] & 0x7f;
372     } else if ((utf8[i] & 0xe0) == 0xc0) {
373       if (utf8_len < 2)
374         return 0;
375
376       if ((utf8[i + 1] & 0xc0) != 0x80)
377         return 0;
378
379       charval = (utf8[i++] & 0x1f) << 6;
380       charval |= utf8[i] & 0x3f;
381       if (charval < 0x80)
382         return 0;
383     } else if ((utf8[i] & 0xf0) == 0xe0) {
384       if (utf8_len < 3)
385         return 0;
386
387       if (((utf8[i + 1] & 0xc0) != 0x80) || 
388           ((utf8[i + 2] & 0xc0) != 0x80))
389         return 0;
390
391       charval = (utf8[i++]  & 0xf)  << 12;
392       charval |= (utf8[i++] & 0x3f) << 6;
393       charval |= utf8[i] & 0x3f;
394       if (charval < 0x800)
395         return 0;
396     } else if ((utf8[i] & 0xf8) == 0xf0) {
397       if (utf8_len < 4)
398         return 0;
399
400       if (((utf8[i + 1] & 0xc0) != 0x80) || 
401           ((utf8[i + 2] & 0xc0) != 0x80) ||
402           ((utf8[i + 3] & 0xc0) != 0x80))
403         return 0;
404
405       charval = ((SilcUInt32)(utf8[i++] & 0x7)) << 18;
406       charval |= (utf8[i++] & 0x3f) << 12;
407       charval |= (utf8[i++] & 0x3f) << 6;
408       charval |= utf8[i] & 0x3f;
409       if (charval < 0x10000)
410         return 0;
411     } else if ((utf8[i] & 0xfc) == 0xf8) {
412       if (utf8_len < 5)
413         return 0;
414
415       if (((utf8[i + 1] & 0xc0) != 0x80) || 
416           ((utf8[i + 2] & 0xc0) != 0x80) ||
417           ((utf8[i + 3] & 0xc0) != 0x80) ||
418           ((utf8[i + 4] & 0xc0) != 0x80))
419         return 0;
420
421       charval = ((SilcUInt32)(utf8[i++]  & 0x3))  << 24;
422       charval |= ((SilcUInt32)(utf8[i++] & 0x3f)) << 18;
423       charval |= ((SilcUInt32)(utf8[i++] & 0x3f)) << 12;
424       charval |= (utf8[i++] & 0x3f) << 6;
425       charval |= utf8[i] & 0x3f;
426       if (charval < 0x200000)
427         return 0;
428     } else if ((utf8[i] & 0xfe) == 0xfc) {
429       if (utf8_len < 6)
430         return 0;
431
432       if (((utf8[i + 1] & 0xc0) != 0x80) || 
433           ((utf8[i + 2] & 0xc0) != 0x80) ||
434           ((utf8[i + 3] & 0xc0) != 0x80) ||
435           ((utf8[i + 4] & 0xc0) != 0x80) ||
436           ((utf8[i + 5] & 0xc0) != 0x80))
437         return 0;
438
439       charval = ((SilcUInt32)(utf8[i++]  & 0x1))  << 30;
440       charval |= ((SilcUInt32)(utf8[i++] & 0x3f)) << 24;
441       charval |= ((SilcUInt32)(utf8[i++] & 0x3f)) << 18;
442       charval |= ((SilcUInt32)(utf8[i++] & 0x3f)) << 12;
443       charval |= (utf8[i++] & 0x3f) << 6;
444       charval |= utf8[i] & 0x3f;
445       if (charval < 0x4000000)
446         return 0;
447     } else {
448       return 0;
449     }
450
451     switch (bin_encoding) {
452     case SILC_STRING_ASCII:
453       if (bin) {
454         if (enclen + 1 > bin_size)
455           return 0;
456
457         bin[enclen] = (unsigned char)charval;
458       }
459       enclen++;
460       break;
461     case SILC_STRING_ASCII_ESC:
462       SILC_NOT_IMPLEMENTED("SILC_STRING_ASCII_ESC");
463       return 0;
464       break;
465     case SILC_STRING_BMP:
466       SILC_PUT16_MSB(charval, bin + enclen);
467       enclen += 2;
468       break;
469     case SILC_STRING_BMP_LSB:
470       SILC_PUT16_LSB(charval, bin + enclen);
471       enclen += 2;
472       break;
473     case SILC_STRING_UNIVERSAL:
474       SILC_PUT32_MSB(charval, bin + enclen);
475       enclen += 4;
476       break;
477     case SILC_STRING_UNIVERSAL_LSB:
478       SILC_PUT32_LSB(charval, bin + enclen);
479       enclen += 4;
480       break;
481     case SILC_STRING_LANGUAGE:
482       break;
483     }
484   }
485
486   return enclen;
487 }
488
489 /* Returns the length of UTF-8 encoded string if the `bin' of
490    encoding of `bin_encoding' is encoded with silc_utf8_encode. */
491
492 SilcUInt32 silc_utf8_encoded_len(const unsigned char *bin, SilcUInt32 bin_len,
493                                  SilcStringEncoding bin_encoding)
494 {
495   return silc_utf8_encode(bin, bin_len, bin_encoding, NULL, 0);
496 }
497
498 /* Returns TRUE if the `utf8' string of length of `utf8_len' is valid
499    UTF-8 encoded string, FALSE if it is not UTF-8 encoded string. */
500
501 bool silc_utf8_valid(const unsigned char *utf8, SilcUInt32 utf8_len)
502 {
503   return silc_utf8_decode(utf8, utf8_len, 0, NULL, 0) != 0;
504 }
505
506 /* Mime constants and macros */
507 #define MIME_VERSION "MIME-Version: "
508 #define MIME_VERSION_LEN 14
509 #define MIME_CONTENT_TYPE "Content-Type: "
510 #define MIME_CONTENT_TYPE_LEN 14
511 #define MIME_TRANSFER_ENCODING "Content-Transfer-Encoding: "
512 #define MIME_TRANSFER_ENCODING_LEN 27
513
514 #define MIME_GET_FIELD(header, mime, mime_len, field, field_len,        \
515                        dest, dest_size)                                 \
516 do {                                                                    \
517   if (dest) {                                                           \
518     char *f = strstr(header, field);                                    \
519     if (f) {                                                            \
520       f = (char *)mime + (f - header) + field_len;                      \
521       for (i = 0; i < (mime_len - (f - (char *)mime)); i++) {           \
522         if (f[i] == '\r' || f[i] == '\n' || i == dest_size)             \
523           break;                                                        \
524         dest[i] = f[i];                                                 \
525       }                                                                 \
526     }                                                                   \
527   }                                                                     \
528 } while(0)
529
530 /* Parses MIME object and MIME header in it. */
531
532 bool 
533 silc_mime_parse(const unsigned char *mime, SilcUInt32 mime_len,
534                 char *version, SilcUInt32 version_size,
535                 char *content_type, SilcUInt32 content_type_size,
536                 char *transfer_encoding, SilcUInt32 transfer_encoding_size,
537                 unsigned char **mime_data_ptr, SilcUInt32 *mime_data_len)
538
539   int i;
540   char header[256];
541    
542   memcpy(header, mime, 256 > mime_len ? mime_len : 256);
543   header[sizeof(header) - 1] = '\0';
544
545   /* Check for mandatory Content-Type field */
546   if (!strstr(header, MIME_CONTENT_TYPE))
547     return FALSE;
548   
549   /* Get the pointer to the data area in the object */
550   for (i = 0; i < mime_len; i++) {
551     if (mime_len >= i + 4 &&
552         mime[i    ] == '\r' && mime[i + 1] == '\n' &&
553         mime[i + 2] == '\r' && mime[i + 3] == '\n')
554       break;
555   }
556   if (i >= mime_len)
557     return FALSE;
558
559   if (mime_data_ptr)
560     *mime_data_ptr = (unsigned char *)mime + i + 4;
561   if (mime_data_len)
562     *mime_data_len = mime_len - ((mime + i + 4) - mime);
563   
564   /* Get MIME version, Content-Type and Transfer Encoding fields */
565   MIME_GET_FIELD(header, mime, mime_len,
566                  MIME_VERSION, MIME_VERSION_LEN,
567                  version, version_size);
568   MIME_GET_FIELD(header, mime, mime_len,
569                  MIME_CONTENT_TYPE, MIME_CONTENT_TYPE_LEN,
570                  content_type, content_type_size);
571   MIME_GET_FIELD(header, mime, mime_len,
572                  MIME_TRANSFER_ENCODING, MIME_TRANSFER_ENCODING_LEN,
573                  transfer_encoding, transfer_encoding_size);
574
575   return TRUE;
576 }
577
578 /* Concatenates the `src' into `dest'.  If `src_len' is more than the
579    size of the `dest' (minus NULL at the end) the `src' will be
580    truncated to fit. */
581
582 char *silc_strncat(char *dest, SilcUInt32 dest_size,
583                    const char *src, SilcUInt32 src_len)
584 {
585   int len;
586
587   dest[dest_size - 1] = '\0';
588
589   len = dest_size - 1 - strlen(dest);
590   if (len < src_len) {
591     if (len > 0)
592       strncat(dest, src, len);
593   } else {
594     strncat(dest, src, src_len);
595   }
596
597   return dest;
598 }