Merge 0.10->trunk
[prosody.git] / util-src / encodings.c
1 /* Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- Copyright (C) 1994-2015 Lua.org, PUC-Rio.
5 --
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9 */
10
11 /*
12 * encodings.c
13 * Lua library for base64, stringprep and idna encodings
14 */
15
16 /* Newer MSVC compilers deprecate strcpy as unsafe, but we use it in a safe way */
17 #define _CRT_SECURE_NO_DEPRECATE
18
19 #include <string.h>
20 #include <stdlib.h>
21 #include "lua.h"
22 #include "lauxlib.h"
23
24 #if (LUA_VERSION_NUM == 501)
25 #define luaL_setfuncs(L, R, N) luaL_register(L, NULL, R)
26 #endif
27
28 /***************** BASE64 *****************/
29
30 static const char code[] =
31     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32
33 static void base64_encode(luaL_Buffer* b, unsigned int c1, unsigned int c2, unsigned int c3, int n) {
34         unsigned long tuple = c3 + 256UL * (c2 + 256UL * c1);
35         int i;
36         char s[4];
37
38         for(i = 0; i < 4; i++) {
39                 s[3 - i] = code[tuple % 64];
40                 tuple /= 64;
41         }
42
43         for(i = n + 1; i < 4; i++) {
44                 s[i] = '=';
45         }
46
47         luaL_addlstring(b, s, 4);
48 }
49
50 static int Lbase64_encode(lua_State* L) {       /** encode(s) */
51         size_t l;
52         const unsigned char* s = (const unsigned char*)luaL_checklstring(L, 1, &l);
53         luaL_Buffer b;
54         int n;
55         luaL_buffinit(L, &b);
56
57         for(n = l / 3; n--; s += 3) {
58                 base64_encode(&b, s[0], s[1], s[2], 3);
59         }
60
61         switch(l % 3) {
62                 case 1:
63                         base64_encode(&b, s[0], 0, 0, 1);
64                         break;
65                 case 2:
66                         base64_encode(&b, s[0], s[1], 0, 2);
67                         break;
68         }
69
70         luaL_pushresult(&b);
71         return 1;
72 }
73
74 static void base64_decode(luaL_Buffer* b, int c1, int c2, int c3, int c4, int n) {
75         unsigned long tuple = c4 + 64L * (c3 + 64L * (c2 + 64L * c1));
76         char s[3];
77
78         switch(--n) {
79                 case 3:
80                         s[2] = (char) tuple;
81                 case 2:
82                         s[1] = (char)(tuple >> 8);
83                 case 1:
84                         s[0] = (char)(tuple >> 16);
85         }
86
87         luaL_addlstring(b, s, n);
88 }
89
90 static int Lbase64_decode(lua_State* L) {       /** decode(s) */
91         size_t l;
92         const char* s = luaL_checklstring(L, 1, &l);
93         luaL_Buffer b;
94         int n = 0;
95         char t[4];
96         luaL_buffinit(L, &b);
97
98         for(;;) {
99                 int c = *s++;
100
101                 switch(c) {
102                                 const char* p;
103                         default:
104                                 p = strchr(code, c);
105
106                                 if(p == NULL) {
107                                         return 0;
108                                 }
109
110                                 t[n++] = (char)(p - code);
111
112                                 if(n == 4) {
113                                         base64_decode(&b, t[0], t[1], t[2], t[3], 4);
114                                         n = 0;
115                                 }
116
117                                 break;
118                         case '=':
119
120                                 switch(n) {
121                                         case 1:
122                                                 base64_decode(&b, t[0], 0, 0, 0, 1);
123                                                 break;
124                                         case 2:
125                                                 base64_decode(&b, t[0], t[1], 0, 0, 2);
126                                                 break;
127                                         case 3:
128                                                 base64_decode(&b, t[0], t[1], t[2], 0, 3);
129                                                 break;
130                                 }
131
132                                 n = 0;
133                                 break;
134                         case 0:
135                                 luaL_pushresult(&b);
136                                 return 1;
137                         case '\n':
138                         case '\r':
139                         case '\t':
140                         case ' ':
141                         case '\f':
142                         case '\b':
143                                 break;
144                 }
145         }
146 }
147
148 static const luaL_Reg Reg_base64[] = {
149         { "encode",     Lbase64_encode  },
150         { "decode",     Lbase64_decode  },
151         { NULL,         NULL    }
152 };
153
154 /******************* UTF-8 ********************/
155
156 /*
157  * Adapted from Lua 5.3
158  * Needed because libidn does not validate that input is valid UTF-8
159  */
160
161 #define MAXUNICODE      0x10FFFF
162
163 /*
164  * Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
165  */
166 static const char* utf8_decode(const char* o, int* val) {
167         static unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};
168         const unsigned char* s = (const unsigned char*)o;
169         unsigned int c = s[0];
170         unsigned int res = 0;  /* final result */
171
172         if(c < 0x80) { /* ascii? */
173                 res = c;
174         } else {
175                 int count = 0;  /* to count number of continuation bytes */
176
177                 while(c & 0x40) {   /* still have continuation bytes? */
178                         int cc = s[++count];  /* read next byte */
179
180                         if((cc & 0xC0) != 0x80) { /* not a continuation byte? */
181                                 return NULL;    /* invalid byte sequence */
182                         }
183
184                         res = (res << 6) | (cc & 0x3F);  /* add lower 6 bits from cont. byte */
185                         c <<= 1;  /* to test next bit */
186                 }
187
188                 res |= ((c & 0x7F) << (count * 5));  /* add first byte */
189
190                 if(count > 3 || res > MAXUNICODE || res <= limits[count] || (0xd800 <= res && res <= 0xdfff)) {
191                         return NULL;    /* invalid byte sequence */
192                 }
193
194                 s += count;  /* skip continuation bytes read */
195         }
196
197         if(val) {
198                 *val = res;
199         }
200
201         return (const char*)s + 1;   /* +1 to include first byte */
202 }
203
204 /*
205  * Check that a string is valid UTF-8
206  * Returns NULL if not
207  */
208 const char* check_utf8(lua_State* L, int idx, size_t* l) {
209         size_t pos, len;
210         const char* s = luaL_checklstring(L, 1, &len);
211         pos = 0;
212
213         while(pos <= len) {
214                 const char* s1 = utf8_decode(s + pos, NULL);
215
216                 if(s1 == NULL) {   /* conversion error? */
217                         return NULL;
218                 }
219
220                 pos = s1 - s;
221         }
222
223         if(l != NULL) {
224                 *l = len;
225         }
226
227         return s;
228 }
229
230 static int Lutf8_valid(lua_State* L) {
231         lua_pushboolean(L, check_utf8(L, 1, NULL) != NULL);
232         return 1;
233 }
234
235 static int Lutf8_length(lua_State* L) {
236         size_t len;
237
238         if(!check_utf8(L, 1, &len)) {
239                 lua_pushnil(L);
240                 lua_pushliteral(L, "invalid utf8");
241                 return 2;
242         }
243
244         lua_pushinteger(L, len);
245         return 1;
246 }
247
248 static const luaL_Reg Reg_utf8[] = {
249         { "valid",      Lutf8_valid     },
250         { "length",     Lutf8_length    },
251         { NULL,         NULL    }
252 };
253
254
255 /***************** STRINGPREP *****************/
256 #ifdef USE_STRINGPREP_ICU
257
258 #include <unicode/usprep.h>
259 #include <unicode/ustring.h>
260 #include <unicode/utrace.h>
261
262 static int icu_stringprep_prep(lua_State* L, const UStringPrepProfile* profile) {
263         size_t input_len;
264         int32_t unprepped_len, prepped_len, output_len;
265         const char* input;
266         char output[1024];
267
268         UChar unprepped[1024]; /* Temporary unicode buffer (1024 characters) */
269         UChar prepped[1024];
270
271         UErrorCode err = U_ZERO_ERROR;
272
273         if(!lua_isstring(L, 1)) {
274                 lua_pushnil(L);
275                 return 1;
276         }
277
278         input = lua_tolstring(L, 1, &input_len);
279
280         if(input_len >= 1024) {
281                 lua_pushnil(L);
282                 return 1;
283         }
284
285         u_strFromUTF8(unprepped, 1024, &unprepped_len, input, input_len, &err);
286
287         if(U_FAILURE(err)) {
288                 lua_pushnil(L);
289                 return 1;
290         }
291
292         prepped_len = usprep_prepare(profile, unprepped, unprepped_len, prepped, 1024, 0, NULL, &err);
293
294         if(U_FAILURE(err)) {
295                 lua_pushnil(L);
296                 return 1;
297         } else {
298                 u_strToUTF8(output, 1024, &output_len, prepped, prepped_len, &err);
299
300                 if(U_SUCCESS(err) && output_len < 1024) {
301                         lua_pushlstring(L, output, output_len);
302                 } else {
303                         lua_pushnil(L);
304                 }
305
306                 return 1;
307         }
308 }
309
310 UStringPrepProfile* icu_nameprep;
311 UStringPrepProfile* icu_nodeprep;
312 UStringPrepProfile* icu_resourceprep;
313 UStringPrepProfile* icu_saslprep;
314
315 /* initialize global ICU stringprep profiles */
316 void init_icu() {
317         UErrorCode err = U_ZERO_ERROR;
318         utrace_setLevel(UTRACE_VERBOSE);
319         icu_nameprep = usprep_openByType(USPREP_RFC3491_NAMEPREP, &err);
320         icu_nodeprep = usprep_openByType(USPREP_RFC3920_NODEPREP, &err);
321         icu_resourceprep = usprep_openByType(USPREP_RFC3920_RESOURCEPREP, &err);
322         icu_saslprep = usprep_openByType(USPREP_RFC4013_SASLPREP, &err);
323
324         if(U_FAILURE(err)) {
325                 fprintf(stderr, "[c] util.encodings: error: %s\n", u_errorName((UErrorCode)err));
326         }
327 }
328
329 #define MAKE_PREP_FUNC(myFunc, prep) \
330 static int myFunc(lua_State *L) { return icu_stringprep_prep(L, prep); }
331
332 MAKE_PREP_FUNC(Lstringprep_nameprep, icu_nameprep)              /** stringprep.nameprep(s) */
333 MAKE_PREP_FUNC(Lstringprep_nodeprep, icu_nodeprep)              /** stringprep.nodeprep(s) */
334 MAKE_PREP_FUNC(Lstringprep_resourceprep, icu_resourceprep)              /** stringprep.resourceprep(s) */
335 MAKE_PREP_FUNC(Lstringprep_saslprep, icu_saslprep)              /** stringprep.saslprep(s) */
336
337 static const luaL_Reg Reg_stringprep[] = {
338         { "nameprep",   Lstringprep_nameprep    },
339         { "nodeprep",   Lstringprep_nodeprep    },
340         { "resourceprep",       Lstringprep_resourceprep        },
341         { "saslprep",   Lstringprep_saslprep    },
342         { NULL,         NULL    }
343 };
344 #else /* USE_STRINGPREP_ICU */
345
346 /****************** libidn ********************/
347
348 #include <stringprep.h>
349
350 static int stringprep_prep(lua_State* L, const Stringprep_profile* profile) {
351         size_t len;
352         const char* s;
353         char string[1024];
354         int ret;
355
356         if(!lua_isstring(L, 1)) {
357                 lua_pushnil(L);
358                 return 1;
359         }
360
361         s = check_utf8(L, 1, &len);
362
363         if(s == NULL || len >= 1024 || len != strlen(s)) {
364                 lua_pushnil(L);
365                 return 1; /* TODO return error message */
366         }
367
368         strcpy(string, s);
369         ret = stringprep(string, 1024, (Stringprep_profile_flags)0, profile);
370
371         if(ret == STRINGPREP_OK) {
372                 lua_pushstring(L, string);
373                 return 1;
374         } else {
375                 lua_pushnil(L);
376                 return 1; /* TODO return error message */
377         }
378 }
379
380 #define MAKE_PREP_FUNC(myFunc, prep) \
381 static int myFunc(lua_State *L) { return stringprep_prep(L, prep); }
382
383 MAKE_PREP_FUNC(Lstringprep_nameprep, stringprep_nameprep)               /** stringprep.nameprep(s) */
384 MAKE_PREP_FUNC(Lstringprep_nodeprep, stringprep_xmpp_nodeprep)          /** stringprep.nodeprep(s) */
385 MAKE_PREP_FUNC(Lstringprep_resourceprep, stringprep_xmpp_resourceprep)          /** stringprep.resourceprep(s) */
386 MAKE_PREP_FUNC(Lstringprep_saslprep, stringprep_saslprep)               /** stringprep.saslprep(s) */
387
388 static const luaL_Reg Reg_stringprep[] = {
389         { "nameprep",   Lstringprep_nameprep    },
390         { "nodeprep",   Lstringprep_nodeprep    },
391         { "resourceprep",       Lstringprep_resourceprep        },
392         { "saslprep",   Lstringprep_saslprep    },
393         { NULL,         NULL    }
394 };
395 #endif
396
397 /***************** IDNA *****************/
398 #ifdef USE_STRINGPREP_ICU
399 #include <unicode/ustdio.h>
400 #include <unicode/uidna.h>
401 /* IDNA2003 or IDNA2008 ? ? ? */
402 static int Lidna_to_ascii(lua_State* L) {       /** idna.to_ascii(s) */
403         size_t len;
404         int32_t ulen, dest_len, output_len;
405         const char* s = luaL_checklstring(L, 1, &len);
406         UChar ustr[1024];
407         UErrorCode err = U_ZERO_ERROR;
408         UChar dest[1024];
409         char output[1024];
410
411         u_strFromUTF8(ustr, 1024, &ulen, s, len, &err);
412
413         if(U_FAILURE(err)) {
414                 lua_pushnil(L);
415                 return 1;
416         }
417
418         dest_len = uidna_IDNToASCII(ustr, ulen, dest, 1024, UIDNA_USE_STD3_RULES, NULL, &err);
419
420         if(U_FAILURE(err)) {
421                 lua_pushnil(L);
422                 return 1;
423         } else {
424                 u_strToUTF8(output, 1024, &output_len, dest, dest_len, &err);
425
426                 if(U_SUCCESS(err) && output_len < 1024) {
427                         lua_pushlstring(L, output, output_len);
428                 } else {
429                         lua_pushnil(L);
430                 }
431
432                 return 1;
433         }
434 }
435
436 static int Lidna_to_unicode(lua_State* L) {     /** idna.to_unicode(s) */
437         size_t len;
438         int32_t ulen, dest_len, output_len;
439         const char* s = luaL_checklstring(L, 1, &len);
440         UChar ustr[1024];
441         UErrorCode err = U_ZERO_ERROR;
442         UChar dest[1024];
443         char output[1024];
444
445         u_strFromUTF8(ustr, 1024, &ulen, s, len, &err);
446
447         if(U_FAILURE(err)) {
448                 lua_pushnil(L);
449                 return 1;
450         }
451
452         dest_len = uidna_IDNToUnicode(ustr, ulen, dest, 1024, UIDNA_USE_STD3_RULES, NULL, &err);
453
454         if(U_FAILURE(err)) {
455                 lua_pushnil(L);
456                 return 1;
457         } else {
458                 u_strToUTF8(output, 1024, &output_len, dest, dest_len, &err);
459
460                 if(U_SUCCESS(err) && output_len < 1024) {
461                         lua_pushlstring(L, output, output_len);
462                 } else {
463                         lua_pushnil(L);
464                 }
465
466                 return 1;
467         }
468 }
469
470 #else /* USE_STRINGPREP_ICU */
471 /****************** libidn ********************/
472
473 #include <idna.h>
474 #include <idn-free.h>
475
476 static int Lidna_to_ascii(lua_State* L) {       /** idna.to_ascii(s) */
477         size_t len;
478         const char* s = check_utf8(L, 1, &len);
479         char* output = NULL;
480         int ret;
481
482         if(s == NULL || len != strlen(s)) {
483                 lua_pushnil(L);
484                 return 1; /* TODO return error message */
485         }
486
487         ret = idna_to_ascii_8z(s, &output, IDNA_USE_STD3_ASCII_RULES);
488
489         if(ret == IDNA_SUCCESS) {
490                 lua_pushstring(L, output);
491                 idn_free(output);
492                 return 1;
493         } else {
494                 lua_pushnil(L);
495                 idn_free(output);
496                 return 1; /* TODO return error message */
497         }
498 }
499
500 static int Lidna_to_unicode(lua_State* L) {     /** idna.to_unicode(s) */
501         size_t len;
502         const char* s = luaL_checklstring(L, 1, &len);
503         char* output = NULL;
504         int ret = idna_to_unicode_8z8z(s, &output, 0);
505
506         if(ret == IDNA_SUCCESS) {
507                 lua_pushstring(L, output);
508                 idn_free(output);
509                 return 1;
510         } else {
511                 lua_pushnil(L);
512                 idn_free(output);
513                 return 1; /* TODO return error message */
514         }
515 }
516 #endif
517
518 static const luaL_Reg Reg_idna[] = {
519         { "to_ascii",   Lidna_to_ascii  },
520         { "to_unicode", Lidna_to_unicode        },
521         { NULL,         NULL    }
522 };
523
524 /***************** end *****************/
525
526 LUALIB_API int luaopen_util_encodings(lua_State* L) {
527 #ifdef USE_STRINGPREP_ICU
528         init_icu();
529 #endif
530         lua_newtable(L);
531
532         lua_newtable(L);
533         luaL_setfuncs(L, Reg_base64, 0);
534         lua_setfield(L, -2, "base64");
535
536         lua_newtable(L);
537         luaL_setfuncs(L, Reg_stringprep, 0);
538         lua_setfield(L, -2, "stringprep");
539
540         lua_newtable(L);
541         luaL_setfuncs(L, Reg_idna, 0);
542         lua_setfield(L, -2, "idna");
543
544         lua_newtable(L);
545         luaL_setfuncs(L, Reg_utf8, 0);
546         lua_setfield(L, -2, "utf8");
547
548         lua_pushliteral(L, "-3.14");
549         lua_setfield(L, -2, "version");
550         return 1;
551 }