Merge 0.9->0.10
[prosody.git] / util-src / encodings.c
1 /* Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8 */
9
10 /*
11 * encodings.c
12 * Lua library for base64, stringprep and idna encodings
13 */
14
15 /* Newer MSVC compilers deprecate strcpy as unsafe, but we use it in a safe way */
16 #define _CRT_SECURE_NO_DEPRECATE
17
18 #include <string.h>
19 #include <stdlib.h>
20 #include "lua.h"
21 #include "lauxlib.h"
22
23 #if (LUA_VERSION_NUM == 502)
24 #define luaL_register(L, N, R) luaL_setfuncs(L, R, 0)
25 #endif
26
27 /***************** BASE64 *****************/
28
29 static const char code[]=
30 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
31
32 static void base64_encode(luaL_Buffer *b, unsigned int c1, unsigned int c2, unsigned int c3, int n)
33 {
34         unsigned long tuple=c3+256UL*(c2+256UL*c1);
35         int i;
36         char s[4];
37         for (i=0; i<4; i++) {
38                 s[3-i] = code[tuple % 64];
39                 tuple /= 64;
40         }
41         for (i=n+1; i<4; i++) s[i]='=';
42         luaL_addlstring(b,s,4);
43 }
44
45 static int Lbase64_encode(lua_State *L)         /** encode(s) */
46 {
47         size_t l;
48         const unsigned char *s=(const unsigned char*)luaL_checklstring(L,1,&l);
49         luaL_Buffer b;
50         int n;
51         luaL_buffinit(L,&b);
52         for (n=l/3; n--; s+=3) base64_encode(&b,s[0],s[1],s[2],3);
53         switch (l%3)
54         {
55                 case 1: base64_encode(&b,s[0],0,0,1);           break;
56                 case 2: base64_encode(&b,s[0],s[1],0,2);                break;
57         }
58         luaL_pushresult(&b);
59         return 1;
60 }
61
62 static void base64_decode(luaL_Buffer *b, int c1, int c2, int c3, int c4, int n)
63 {
64         unsigned long tuple=c4+64L*(c3+64L*(c2+64L*c1));
65         char s[3];
66         switch (--n)
67         {
68                 case 3: s[2]=(char) tuple;
69                 case 2: s[1]=(char) (tuple >> 8);
70                 case 1: s[0]=(char) (tuple >> 16);
71         }
72         luaL_addlstring(b,s,n);
73 }
74
75 static int Lbase64_decode(lua_State *L)         /** decode(s) */
76 {
77         size_t l;
78         const char *s=luaL_checklstring(L,1,&l);
79         luaL_Buffer b;
80         int n=0;
81         char t[4];
82         luaL_buffinit(L,&b);
83         for (;;)
84         {
85                 int c=*s++;
86                 switch (c)
87                 {
88                         const char *p;
89                         default:
90                                 p=strchr(code,c); if (p==NULL) return 0;
91                                 t[n++]= (char) (p-code);
92                                 if (n==4)
93                                 {
94                                         base64_decode(&b,t[0],t[1],t[2],t[3],4);
95                                         n=0;
96                                 }
97                                 break;
98                         case '=':
99                                 switch (n)
100                                 {
101                                         case 1: base64_decode(&b,t[0],0,0,0,1);         break;
102                                         case 2: base64_decode(&b,t[0],t[1],0,0,2);      break;
103                                         case 3: base64_decode(&b,t[0],t[1],t[2],0,3);   break;
104                                 }
105                                 n=0;
106                                 break;
107                         case 0:
108                                 luaL_pushresult(&b);
109                                 return 1;
110                         case '\n': case '\r': case '\t': case ' ': case '\f': case '\b':
111                                 break;
112                 }
113         }
114 }
115
116 static const luaL_Reg Reg_base64[] =
117 {
118         { "encode",     Lbase64_encode  },
119         { "decode",     Lbase64_decode  },
120         { NULL,         NULL    }
121 };
122
123 /***************** STRINGPREP *****************/
124 #ifdef USE_STRINGPREP_ICU
125
126 #include <unicode/usprep.h>
127 #include <unicode/ustring.h>
128 #include <unicode/utrace.h>
129
130 static int icu_stringprep_prep(lua_State *L, const UStringPrepProfile *profile)
131 {
132         size_t input_len;
133         int32_t unprepped_len, prepped_len, output_len;
134         const char *input;
135         char output[1024];
136
137         UChar unprepped[1024]; /* Temporary unicode buffer (1024 characters) */
138         UChar prepped[1024];
139         
140         UErrorCode err = U_ZERO_ERROR;
141
142         if(!lua_isstring(L, 1)) {
143                 lua_pushnil(L);
144                 return 1;
145         }
146         input = lua_tolstring(L, 1, &input_len);
147         if (input_len >= 1024) {
148                 lua_pushnil(L);
149                 return 1;
150         }
151         u_strFromUTF8(unprepped, 1024, &unprepped_len, input, input_len, &err);
152         if (U_FAILURE(err)) {
153                 lua_pushnil(L);
154                 return 1;
155         }
156         prepped_len = usprep_prepare(profile, unprepped, unprepped_len, prepped, 1024, 0, NULL, &err);
157         if (U_FAILURE(err)) {
158                 lua_pushnil(L);
159                 return 1;
160         } else {
161                 u_strToUTF8(output, 1024, &output_len, prepped, prepped_len, &err);
162                 if (U_SUCCESS(err) && output_len < 1024)
163                         lua_pushlstring(L, output, output_len);
164                 else
165                         lua_pushnil(L);
166                 return 1;
167         }
168 }
169
170 UStringPrepProfile *icu_nameprep;
171 UStringPrepProfile *icu_nodeprep;
172 UStringPrepProfile *icu_resourceprep; 
173 UStringPrepProfile *icu_saslprep;
174
175 /* initialize global ICU stringprep profiles */
176 void init_icu()
177 {
178         UErrorCode err = U_ZERO_ERROR;
179         utrace_setLevel(UTRACE_VERBOSE);
180         icu_nameprep = usprep_openByType(USPREP_RFC3491_NAMEPREP, &err);
181         icu_nodeprep = usprep_openByType(USPREP_RFC3920_NODEPREP, &err);
182         icu_resourceprep = usprep_openByType(USPREP_RFC3920_RESOURCEPREP, &err);
183         icu_saslprep = usprep_openByType(USPREP_RFC4013_SASLPREP, &err);
184         if (U_FAILURE(err)) fprintf(stderr, "[c] util.encodings: error: %s\n", u_errorName((UErrorCode)err));
185 }
186
187 #define MAKE_PREP_FUNC(myFunc, prep) \
188 static int myFunc(lua_State *L) { return icu_stringprep_prep(L, prep); }
189
190 MAKE_PREP_FUNC(Lstringprep_nameprep, icu_nameprep)              /** stringprep.nameprep(s) */
191 MAKE_PREP_FUNC(Lstringprep_nodeprep, icu_nodeprep)              /** stringprep.nodeprep(s) */
192 MAKE_PREP_FUNC(Lstringprep_resourceprep, icu_resourceprep)              /** stringprep.resourceprep(s) */
193 MAKE_PREP_FUNC(Lstringprep_saslprep, icu_saslprep)              /** stringprep.saslprep(s) */
194
195 static const luaL_Reg Reg_stringprep[] =
196 {
197         { "nameprep",   Lstringprep_nameprep    },
198         { "nodeprep",   Lstringprep_nodeprep    },
199         { "resourceprep",       Lstringprep_resourceprep        },
200         { "saslprep",   Lstringprep_saslprep    },
201         { NULL,         NULL    }
202 };
203 #else /* USE_STRINGPREP_ICU */
204
205 /****************** libidn ********************/
206
207 #include <stringprep.h>
208
209 static int stringprep_prep(lua_State *L, const Stringprep_profile *profile)
210 {
211         size_t len;
212         const char *s;
213         char string[1024];
214         int ret;
215         if(!lua_isstring(L, 1)) {
216                 lua_pushnil(L);
217                 return 1;
218         }
219         s = lua_tolstring(L, 1, &len);
220         if (len >= 1024) {
221                 lua_pushnil(L);
222                 return 1; /* TODO return error message */
223         }
224         strcpy(string, s);
225         ret = stringprep(string, 1024, (Stringprep_profile_flags)0, profile);
226         if (ret == STRINGPREP_OK) {
227                 lua_pushstring(L, string);
228                 return 1;
229         } else {
230                 lua_pushnil(L);
231                 return 1; /* TODO return error message */
232         }
233 }
234
235 #define MAKE_PREP_FUNC(myFunc, prep) \
236 static int myFunc(lua_State *L) { return stringprep_prep(L, prep); }
237
238 MAKE_PREP_FUNC(Lstringprep_nameprep, stringprep_nameprep)               /** stringprep.nameprep(s) */
239 MAKE_PREP_FUNC(Lstringprep_nodeprep, stringprep_xmpp_nodeprep)          /** stringprep.nodeprep(s) */
240 MAKE_PREP_FUNC(Lstringprep_resourceprep, stringprep_xmpp_resourceprep)          /** stringprep.resourceprep(s) */
241 MAKE_PREP_FUNC(Lstringprep_saslprep, stringprep_saslprep)               /** stringprep.saslprep(s) */
242
243 static const luaL_Reg Reg_stringprep[] =
244 {
245         { "nameprep",   Lstringprep_nameprep    },
246         { "nodeprep",   Lstringprep_nodeprep    },
247         { "resourceprep",       Lstringprep_resourceprep        },
248         { "saslprep",   Lstringprep_saslprep    },
249         { NULL,         NULL    }
250 };
251 #endif
252
253 /***************** IDNA *****************/
254 #ifdef USE_STRINGPREP_ICU
255 #include <unicode/ustdio.h>
256 #include <unicode/uidna.h>
257 /* IDNA2003 or IDNA2008 ? ? ? */
258 static int Lidna_to_ascii(lua_State *L)         /** idna.to_ascii(s) */
259 {
260         size_t len;
261         int32_t ulen, dest_len, output_len;
262         const char *s = luaL_checklstring(L, 1, &len);
263         UChar ustr[1024];
264         UErrorCode err = U_ZERO_ERROR;
265         UChar dest[1024];
266         char output[1024];
267
268         u_strFromUTF8(ustr, 1024, &ulen, s, len, &err);
269         if (U_FAILURE(err)) {
270                 lua_pushnil(L);
271                 return 1;
272         }
273
274         dest_len = uidna_IDNToASCII(ustr, ulen, dest, 1024, UIDNA_USE_STD3_RULES, NULL, &err);
275         if (U_FAILURE(err)) {
276                 lua_pushnil(L);
277                 return 1;
278         } else {
279                 u_strToUTF8(output, 1024, &output_len, dest, dest_len, &err);
280                 if (U_SUCCESS(err) && output_len < 1024)
281                         lua_pushlstring(L, output, output_len);
282                 else
283                         lua_pushnil(L);
284                 return 1;
285         }
286 }
287
288 static int Lidna_to_unicode(lua_State *L)               /** idna.to_unicode(s) */
289 {
290         size_t len;
291         int32_t ulen, dest_len, output_len;
292         const char *s = luaL_checklstring(L, 1, &len);
293         UChar ustr[1024];
294         UErrorCode err = U_ZERO_ERROR;
295         UChar dest[1024];
296         char output[1024];
297
298         u_strFromUTF8(ustr, 1024, &ulen, s, len, &err);
299         if (U_FAILURE(err)) {
300                 lua_pushnil(L);
301                 return 1;
302         }
303
304         dest_len = uidna_IDNToUnicode(ustr, ulen, dest, 1024, UIDNA_USE_STD3_RULES, NULL, &err);
305         if (U_FAILURE(err)) {
306                 lua_pushnil(L);
307                 return 1;
308         } else {
309                 u_strToUTF8(output, 1024, &output_len, dest, dest_len, &err);
310                 if (U_SUCCESS(err) && output_len < 1024)
311                         lua_pushlstring(L, output, output_len);
312                 else
313                         lua_pushnil(L);
314                 return 1;
315         }
316 }
317
318 #else /* USE_STRINGPREP_ICU */
319 /****************** libidn ********************/
320
321 #include <idna.h>
322 #include <idn-free.h>
323
324 static int Lidna_to_ascii(lua_State *L)         /** idna.to_ascii(s) */
325 {
326         size_t len;
327         const char *s = luaL_checklstring(L, 1, &len);
328         char* output = NULL;
329         int ret = idna_to_ascii_8z(s, &output, IDNA_USE_STD3_ASCII_RULES);
330         if (ret == IDNA_SUCCESS) {
331                 lua_pushstring(L, output);
332                 idn_free(output);
333                 return 1;
334         } else {
335                 lua_pushnil(L);
336                 idn_free(output);
337                 return 1; /* TODO return error message */
338         }
339 }
340
341 static int Lidna_to_unicode(lua_State *L)               /** idna.to_unicode(s) */
342 {
343         size_t len;
344         const char *s = luaL_checklstring(L, 1, &len);
345         char* output = NULL;
346         int ret = idna_to_unicode_8z8z(s, &output, 0);
347         if (ret == IDNA_SUCCESS) {
348                 lua_pushstring(L, output);
349                 idn_free(output);
350                 return 1;
351         } else {
352                 lua_pushnil(L);
353                 idn_free(output);
354                 return 1; /* TODO return error message */
355         }
356 }
357 #endif
358
359 static const luaL_Reg Reg_idna[] =
360 {
361         { "to_ascii",   Lidna_to_ascii  },
362         { "to_unicode", Lidna_to_unicode        },
363         { NULL,         NULL    }
364 };
365
366 /***************** end *****************/
367
368 LUALIB_API int luaopen_util_encodings(lua_State *L)
369 {
370 #ifdef USE_STRINGPREP_ICU
371         init_icu();
372 #endif
373         lua_newtable(L);
374
375         lua_newtable(L);
376         luaL_register(L, NULL, Reg_base64);
377         lua_setfield(L, -2, "base64");
378
379         lua_newtable(L);
380         luaL_register(L, NULL, Reg_stringprep);
381         lua_setfield(L, -2, "stringprep");
382
383         lua_newtable(L);
384         luaL_register(L, NULL, Reg_idna);
385         lua_setfield(L, -2, "idna");
386
387         lua_pushliteral(L, "-3.14");
388         lua_setfield(L, -2, "version");
389         return 1;
390 }