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