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