1d95606081220c0df8daee9770f1d26ddc84aa22
[oweals/minetest.git] / src / util / string.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "string.h"
21 #include "pointer.h"
22 #include "numeric.h"
23 #include "log.h"
24
25 #include "../sha1.h"
26 #include "../base64.h"
27 #include "../hex.h"
28 #include "../porting.h"
29
30 #include <algorithm>
31 #include <sstream>
32 #include <iomanip>
33 #include <map>
34
35 static bool parseHexColorString(const std::string &value, video::SColor &color);
36 static bool parseNamedColorString(const std::string &value, video::SColor &color);
37
38 #ifdef __ANDROID__
39 const wchar_t* wide_chars =
40         L" !\"#$%&'()*+,-./0123456789:;<=>?@"
41         L"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
42         L"abcdefghijklmnopqrstuvwxyz{|}~";
43
44 int wctomb(char *s, wchar_t wc)
45 {
46         for (unsigned int j = 0; j < (sizeof(wide_chars)/sizeof(wchar_t));j++) {
47                 if (wc == wide_chars[j]) {
48                         *s = (char) (j+32);
49                         return 1;
50                 }
51                 else if (wc == L'\n') {
52                         *s = '\n';
53                         return 1;
54                 }
55         }
56         return -1;
57 }
58
59 int mbtowc(wchar_t *pwc, const char *s, size_t n)
60 {
61         std::wstring intermediate = narrow_to_wide(s);
62
63         if (intermediate.length() > 0) {
64                 *pwc = intermediate[0];
65                 return 1;
66         }
67         else {
68                 return -1;
69         }
70 }
71
72 std::wstring narrow_to_wide(const std::string& mbs) {
73         size_t wcl = mbs.size();
74
75         std::wstring retval = L"";
76
77         for (unsigned int i = 0; i < wcl; i++) {
78                 if (((unsigned char) mbs[i] >31) &&
79                  ((unsigned char) mbs[i] < 127)) {
80
81                         retval += wide_chars[(unsigned char) mbs[i] -32];
82                 }
83                 //handle newline
84                 else if (mbs[i] == '\n') {
85                         retval += L'\n';
86                 }
87         }
88
89         return retval;
90 }
91 #else
92
93 std::wstring narrow_to_wide(const std::string& mbs)
94 {
95         size_t wcl = mbs.size();
96         Buffer<wchar_t> wcs(wcl+1);
97         size_t l = mbstowcs(*wcs, mbs.c_str(), wcl);
98         if(l == (size_t)(-1))
99                 return L"<invalid multibyte string>";
100         wcs[l] = 0;
101         return *wcs;
102 }
103
104 #endif
105
106 #ifdef __ANDROID__
107 std::string wide_to_narrow(const std::wstring& wcs) {
108         size_t mbl = wcs.size()*4;
109
110         std::string retval = "";
111         for (unsigned int i = 0; i < wcs.size(); i++) {
112                 wchar_t char1 = (wchar_t) wcs[i];
113
114                 if (char1 == L'\n') {
115                         retval += '\n';
116                         continue;
117                 }
118
119                 for (unsigned int j = 0; j < wcslen(wide_chars);j++) {
120                         wchar_t char2 = (wchar_t) wide_chars[j];
121
122                         if (char1 == char2) {
123                                 char toadd = (j+32);
124                                 retval += toadd;
125                                 break;
126                         }
127                 }
128         }
129
130         return retval;
131 }
132 #else
133 std::string wide_to_narrow(const std::wstring& wcs)
134 {
135         size_t mbl = wcs.size()*4;
136         SharedBuffer<char> mbs(mbl+1);
137         size_t l = wcstombs(*mbs, wcs.c_str(), mbl);
138         if(l == (size_t)(-1)) {
139                 return "Character conversion failed!";
140         }
141         else
142                 mbs[l] = 0;
143         return *mbs;
144 }
145
146 #endif
147
148 // Get an sha-1 hash of the player's name combined with
149 // the password entered. That's what the server uses as
150 // their password. (Exception : if the password field is
151 // blank, we send a blank password - this is for backwards
152 // compatibility with password-less players).
153 std::string translatePassword(std::string playername, std::wstring password)
154 {
155         if(password.length() == 0)
156                 return "";
157
158         std::string slt = playername + wide_to_narrow(password);
159         SHA1 sha1;
160         sha1.addBytes(slt.c_str(), slt.length());
161         unsigned char *digest = sha1.getDigest();
162         std::string pwd = base64_encode(digest, 20);
163         free(digest);
164         return pwd;
165 }
166
167 std::string urlencode(std::string str)
168 {
169         // Encodes non-unreserved URI characters by a percent sign
170         // followed by two hex digits. See RFC 3986, section 2.3.
171         static const char url_hex_chars[] = "0123456789ABCDEF";
172         std::ostringstream oss(std::ios::binary);
173         for (u32 i = 0; i < str.size(); i++) {
174                 unsigned char c = str[i];
175                 if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~')
176                         oss << c;
177                 else
178                         oss << "%"
179                                 << url_hex_chars[(c & 0xf0) >> 4]
180                                 << url_hex_chars[c & 0x0f];
181         }
182         return oss.str();
183 }
184
185 std::string urldecode(std::string str)
186 {
187         // Inverse of urlencode
188         std::ostringstream oss(std::ios::binary);
189         for (u32 i = 0; i < str.size(); i++) {
190                 unsigned char highvalue, lowvalue;
191                 if (str[i] == '%' &&
192                                 hex_digit_decode(str[i+1], highvalue) &&
193                                 hex_digit_decode(str[i+2], lowvalue)) {
194                         oss << (char) ((highvalue << 4) | lowvalue);
195                         i += 2;
196                 }
197                 else
198                         oss << str[i];
199         }
200         return oss.str();
201 }
202
203 u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask)
204 {
205         u32 result = 0, mask = 0;
206         char *s = &str[0];
207         char *flagstr, *strpos = NULL;
208
209         while ((flagstr = strtok_r(s, ",", &strpos))) {
210                 s = NULL;
211
212                 while (*flagstr == ' ' || *flagstr == '\t')
213                         flagstr++;
214
215                 bool flagset = true;
216                 if (!strncasecmp(flagstr, "no", 2)) {
217                         flagset = false;
218                         flagstr += 2;
219                 }
220
221                 for (int i = 0; flagdesc[i].name; i++) {
222                         if (!strcasecmp(flagstr, flagdesc[i].name)) {
223                                 mask |= flagdesc[i].flag;
224                                 if (flagset)
225                                         result |= flagdesc[i].flag;
226                                 break;
227                         }
228                 }
229         }
230
231         if (flagmask)
232                 *flagmask = mask;
233
234         return result;
235 }
236
237 std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask)
238 {
239         std::string result;
240
241         for (int i = 0; flagdesc[i].name; i++) {
242                 if (flagmask & flagdesc[i].flag) {
243                         if (!(flags & flagdesc[i].flag))
244                                 result += "no";
245
246                         result += flagdesc[i].name;
247                         result += ", ";
248                 }
249         }
250
251         size_t len = result.length();
252         if (len >= 2)
253                 result.erase(len - 2, 2);
254
255         return result;
256 }
257
258 size_t mystrlcpy(char *dst, const char *src, size_t size)
259 {
260         size_t srclen  = strlen(src) + 1;
261         size_t copylen = MYMIN(srclen, size);
262
263         if (copylen > 0) {
264                 memcpy(dst, src, copylen);
265                 dst[copylen - 1] = '\0';
266         }
267
268         return srclen;
269 }
270
271 char *mystrtok_r(char *s, const char *sep, char **lasts)
272 {
273         char *t;
274
275         if (!s)
276                 s = *lasts;
277
278         while (*s && strchr(sep, *s))
279                 s++;
280
281         if (!*s)
282                 return NULL;
283
284         t = s;
285         while (*t) {
286                 if (strchr(sep, *t)) {
287                         *t++ = '\0';
288                         break;
289                 }
290                 t++;
291         }
292         
293         *lasts = t;
294         return s;
295 }
296
297 u64 read_seed(const char *str)
298 {
299         char *endptr;
300         u64 num;
301         
302         if (str[0] == '0' && str[1] == 'x')
303                 num = strtoull(str, &endptr, 16);
304         else
305                 num = strtoull(str, &endptr, 10);
306                 
307         if (*endptr)
308                 num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337);
309                 
310         return num;
311 }
312
313 bool parseColorString(const std::string &value, video::SColor &color, bool quiet)
314 {
315         bool success;
316
317         if (value[0] == '#')
318                 success = parseHexColorString(value, color);
319         else
320                 success = parseNamedColorString(value, color);
321
322         if (!success && !quiet)
323                 errorstream << "Invalid color: \"" << value << "\"" << std::endl;
324
325         return success;
326 }
327
328 static bool parseHexColorString(const std::string &value, video::SColor &color)
329 {
330         unsigned char components[] = { 0x00, 0x00, 0x00, 0xff }; // R,G,B,A
331
332         if (value[0] != '#')
333                 return false;
334
335         size_t len = value.size();
336         bool short_form;
337
338         if (len == 9 || len == 7) // #RRGGBBAA or #RRGGBB
339                 short_form = false;
340         else if (len == 5 || len == 4) // #RGBA or #RGB
341                 short_form = true;
342         else
343                 return false;
344
345         bool success = true;
346
347         for (size_t pos = 1, cc = 0; pos < len; pos++, cc++) {
348                 assert(cc < sizeof components / sizeof components[0]);
349                 if (short_form) {
350                         unsigned char d;
351                         if (!hex_digit_decode(value[pos], d)) {
352                                 success = false;
353                                 break;
354                         }
355                         components[cc] = (d & 0xf) << 4 | (d & 0xf);
356                 } else {
357                         unsigned char d1, d2;
358                         if (!hex_digit_decode(value[pos], d1) ||
359                                         !hex_digit_decode(value[pos+1], d2)) {
360                                 success = false;
361                                 break;
362                         }
363                         components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf);
364                         pos++;  // skip the second digit -- it's already used
365                 }
366         }
367
368         if (success) {
369                 color.setRed(components[0]);
370                 color.setGreen(components[1]);
371                 color.setBlue(components[2]);
372                 color.setAlpha(components[3]);
373         }
374
375         return success;
376 }
377
378 struct ColorContainer {
379         ColorContainer();
380         std::map<const std::string, u32> colors;
381 };
382
383 ColorContainer::ColorContainer()
384 {
385         colors["aliceblue"]              = 0xf0f8ff;
386         colors["antiquewhite"]           = 0xfaebd7;
387         colors["aqua"]                   = 0x00ffff;
388         colors["aquamarine"]             = 0x7fffd4;
389         colors["azure"]                  = 0xf0ffff;
390         colors["beige"]                  = 0xf5f5dc;
391         colors["bisque"]                 = 0xffe4c4;
392         colors["black"]                  = 00000000;
393         colors["blanchedalmond"]         = 0xffebcd;
394         colors["blue"]                   = 0x0000ff;
395         colors["blueviolet"]             = 0x8a2be2;
396         colors["brown"]                  = 0xa52a2a;
397         colors["burlywood"]              = 0xdeb887;
398         colors["cadetblue"]              = 0x5f9ea0;
399         colors["chartreuse"]             = 0x7fff00;
400         colors["chocolate"]              = 0xd2691e;
401         colors["coral"]                  = 0xff7f50;
402         colors["cornflowerblue"]         = 0x6495ed;
403         colors["cornsilk"]               = 0xfff8dc;
404         colors["crimson"]                = 0xdc143c;
405         colors["cyan"]                   = 0x00ffff;
406         colors["darkblue"]               = 0x00008b;
407         colors["darkcyan"]               = 0x008b8b;
408         colors["darkgoldenrod"]          = 0xb8860b;
409         colors["darkgray"]               = 0xa9a9a9;
410         colors["darkgreen"]              = 0x006400;
411         colors["darkkhaki"]              = 0xbdb76b;
412         colors["darkmagenta"]            = 0x8b008b;
413         colors["darkolivegreen"]         = 0x556b2f;
414         colors["darkorange"]             = 0xff8c00;
415         colors["darkorchid"]             = 0x9932cc;
416         colors["darkred"]                = 0x8b0000;
417         colors["darksalmon"]             = 0xe9967a;
418         colors["darkseagreen"]           = 0x8fbc8f;
419         colors["darkslateblue"]          = 0x483d8b;
420         colors["darkslategray"]          = 0x2f4f4f;
421         colors["darkturquoise"]          = 0x00ced1;
422         colors["darkviolet"]             = 0x9400d3;
423         colors["deeppink"]               = 0xff1493;
424         colors["deepskyblue"]            = 0x00bfff;
425         colors["dimgray"]                = 0x696969;
426         colors["dodgerblue"]             = 0x1e90ff;
427         colors["firebrick"]              = 0xb22222;
428         colors["floralwhite"]            = 0xfffaf0;
429         colors["forestgreen"]            = 0x228b22;
430         colors["fuchsia"]                = 0xff00ff;
431         colors["gainsboro"]              = 0xdcdcdc;
432         colors["ghostwhite"]             = 0xf8f8ff;
433         colors["gold"]                   = 0xffd700;
434         colors["goldenrod"]              = 0xdaa520;
435         colors["gray"]                   = 0x808080;
436         colors["green"]                  = 0x008000;
437         colors["greenyellow"]            = 0xadff2f;
438         colors["honeydew"]               = 0xf0fff0;
439         colors["hotpink"]                = 0xff69b4;
440         colors["indianred "]             = 0xcd5c5c;
441         colors["indigo "]                = 0x4b0082;
442         colors["ivory"]                  = 0xfffff0;
443         colors["khaki"]                  = 0xf0e68c;
444         colors["lavender"]               = 0xe6e6fa;
445         colors["lavenderblush"]          = 0xfff0f5;
446         colors["lawngreen"]              = 0x7cfc00;
447         colors["lemonchiffon"]           = 0xfffacd;
448         colors["lightblue"]              = 0xadd8e6;
449         colors["lightcoral"]             = 0xf08080;
450         colors["lightcyan"]              = 0xe0ffff;
451         colors["lightgoldenrodyellow"]   = 0xfafad2;
452         colors["lightgray"]              = 0xd3d3d3;
453         colors["lightgreen"]             = 0x90ee90;
454         colors["lightpink"]              = 0xffb6c1;
455         colors["lightsalmon"]            = 0xffa07a;
456         colors["lightseagreen"]          = 0x20b2aa;
457         colors["lightskyblue"]           = 0x87cefa;
458         colors["lightslategray"]         = 0x778899;
459         colors["lightsteelblue"]         = 0xb0c4de;
460         colors["lightyellow"]            = 0xffffe0;
461         colors["lime"]                   = 0x00ff00;
462         colors["limegreen"]              = 0x32cd32;
463         colors["linen"]                  = 0xfaf0e6;
464         colors["magenta"]                = 0xff00ff;
465         colors["maroon"]                 = 0x800000;
466         colors["mediumaquamarine"]       = 0x66cdaa;
467         colors["mediumblue"]             = 0x0000cd;
468         colors["mediumorchid"]           = 0xba55d3;
469         colors["mediumpurple"]           = 0x9370db;
470         colors["mediumseagreen"]         = 0x3cb371;
471         colors["mediumslateblue"]        = 0x7b68ee;
472         colors["mediumspringgreen"]      = 0x00fa9a;
473         colors["mediumturquoise"]        = 0x48d1cc;
474         colors["mediumvioletred"]        = 0xc71585;
475         colors["midnightblue"]           = 0x191970;
476         colors["mintcream"]              = 0xf5fffa;
477         colors["mistyrose"]              = 0xffe4e1;
478         colors["moccasin"]               = 0xffe4b5;
479         colors["navajowhite"]            = 0xffdead;
480         colors["navy"]                   = 0x000080;
481         colors["oldlace"]                = 0xfdf5e6;
482         colors["olive"]                  = 0x808000;
483         colors["olivedrab"]              = 0x6b8e23;
484         colors["orange"]                 = 0xffa500;
485         colors["orangered"]              = 0xff4500;
486         colors["orchid"]                 = 0xda70d6;
487         colors["palegoldenrod"]          = 0xeee8aa;
488         colors["palegreen"]              = 0x98fb98;
489         colors["paleturquoise"]          = 0xafeeee;
490         colors["palevioletred"]          = 0xdb7093;
491         colors["papayawhip"]             = 0xffefd5;
492         colors["peachpuff"]              = 0xffdab9;
493         colors["peru"]                   = 0xcd853f;
494         colors["pink"]                   = 0xffc0cb;
495         colors["plum"]                   = 0xdda0dd;
496         colors["powderblue"]             = 0xb0e0e6;
497         colors["purple"]                 = 0x800080;
498         colors["red"]                    = 0xff0000;
499         colors["rosybrown"]              = 0xbc8f8f;
500         colors["royalblue"]              = 0x4169e1;
501         colors["saddlebrown"]            = 0x8b4513;
502         colors["salmon"]                 = 0xfa8072;
503         colors["sandybrown"]             = 0xf4a460;
504         colors["seagreen"]               = 0x2e8b57;
505         colors["seashell"]               = 0xfff5ee;
506         colors["sienna"]                 = 0xa0522d;
507         colors["silver"]                 = 0xc0c0c0;
508         colors["skyblue"]                = 0x87ceeb;
509         colors["slateblue"]              = 0x6a5acd;
510         colors["slategray"]              = 0x708090;
511         colors["snow"]                   = 0xfffafa;
512         colors["springgreen"]            = 0x00ff7f;
513         colors["steelblue"]              = 0x4682b4;
514         colors["tan"]                    = 0xd2b48c;
515         colors["teal"]                   = 0x008080;
516         colors["thistle"]                = 0xd8bfd8;
517         colors["tomato"]                 = 0xff6347;
518         colors["turquoise"]              = 0x40e0d0;
519         colors["violet"]                 = 0xee82ee;
520         colors["wheat"]                  = 0xf5deb3;
521         colors["white"]                  = 0xffffff;
522         colors["whitesmoke"]             = 0xf5f5f5;
523         colors["yellow"]                 = 0xffff00;
524         colors["yellowgreen"]            = 0x9acd32;
525
526 }
527
528 static const ColorContainer named_colors;
529
530 static bool parseNamedColorString(const std::string &value, video::SColor &color)
531 {
532         std::string color_name;
533         std::string alpha_string;
534
535         /* If the string has a # in it, assume this is the start of a specified
536          * alpha value (if it isn't the string is invalid and the error will be
537          * caught later on, either because the color name won't be found or the
538          * alpha value will fail conversion)
539          */
540         size_t alpha_pos = value.find('#');
541         if (alpha_pos != std::string::npos) {
542                 color_name = value.substr(0, alpha_pos);
543                 alpha_string = value.substr(alpha_pos + 1);
544         } else {
545                 color_name = value;
546         }
547
548         color_name = lowercase(value);
549
550         std::map<const std::string, unsigned>::const_iterator it;
551         it = named_colors.colors.find(color_name);
552         if (it == named_colors.colors.end())
553                 return false;
554
555         u32 color_temp = it->second;
556
557         /* An empty string for alpha is ok (none of the color table entries
558          * have an alpha value either). Color strings without an alpha specified
559          * are interpreted as fully opaque
560          *
561          * For named colors the supplied alpha string (representing a hex value)
562          * must be exactly two digits. For example:  colorname#08
563          */
564         if (!alpha_string.empty()) {
565                 if (alpha_string.length() != 2)
566                         return false;
567
568                 unsigned char d1, d2;
569                 if (!hex_digit_decode(alpha_string.at(0), d1)
570                                 || !hex_digit_decode(alpha_string.at(1), d2))
571                         return false;
572                 color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24;
573         } else {
574                 color_temp |= 0xff << 24;  // Fully opaque
575         }
576
577         color = video::SColor(color_temp);
578
579         return true;
580 }
581
582 void str_replace(std::string &str, char from, char to)
583 {
584         std::replace(str.begin(), str.end(), from, to);
585 }
586