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