3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
27 #include "translation.h"
33 #include <unordered_map>
38 #define _WIN32_WINNT 0x0501
44 static bool convert(const char *to, const char *from, char *outbuf,
45 size_t *outbuf_size, char *inbuf, size_t inbuf_size)
47 iconv_t cd = iconv_open(to, from);
49 char *inbuf_ptr = inbuf;
50 char *outbuf_ptr = outbuf;
52 size_t *inbuf_left_ptr = &inbuf_size;
54 const size_t old_outbuf_size = *outbuf_size;
55 size_t old_size = inbuf_size;
56 while (inbuf_size > 0) {
57 iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_size);
58 if (inbuf_size == old_size) {
62 old_size = inbuf_size;
66 *outbuf_size = old_outbuf_size - *outbuf_size;
71 // On Android iconv disagrees how big a wchar_t is for whatever reason
72 const char *DEFAULT_ENCODING = "UTF-32LE";
73 #elif defined(__NetBSD__) || defined(__OpenBSD__)
74 // NetBSD does not allow "WCHAR_T" as a charset input to iconv.
75 #include <sys/endian.h>
76 #if BYTE_ORDER == BIG_ENDIAN
77 const char *DEFAULT_ENCODING = "UTF-32BE";
79 const char *DEFAULT_ENCODING = "UTF-32LE";
82 const char *DEFAULT_ENCODING = "WCHAR_T";
85 std::wstring utf8_to_wide(const std::string &input)
87 const size_t inbuf_size = input.length();
88 // maximum possible size, every character is sizeof(wchar_t) bytes
89 size_t outbuf_size = input.length() * sizeof(wchar_t);
91 char *inbuf = new char[inbuf_size]; // intentionally NOT null-terminated
92 memcpy(inbuf, input.c_str(), inbuf_size);
94 out.resize(outbuf_size / sizeof(wchar_t));
96 #if defined(__ANDROID__) || defined(__NetBSD__) || defined(__OpenBSD__)
97 static_assert(sizeof(wchar_t) == 4, "Unexpected wide char size");
100 char *outbuf = reinterpret_cast<char*>(&out[0]);
101 if (!convert(DEFAULT_ENCODING, "UTF-8", outbuf, &outbuf_size, inbuf, inbuf_size)) {
102 infostream << "Couldn't convert UTF-8 string 0x" << hex_encode(input)
103 << " into wstring" << std::endl;
105 return L"<invalid UTF-8 string>";
109 out.resize(outbuf_size / sizeof(wchar_t));
113 std::string wide_to_utf8(const std::wstring &input)
115 const size_t inbuf_size = input.length() * sizeof(wchar_t);
116 // maximum possible size: utf-8 encodes codepoints using 1 up to 4 bytes
117 size_t outbuf_size = input.length() * 4;
119 char *inbuf = new char[inbuf_size]; // intentionally NOT null-terminated
120 memcpy(inbuf, input.c_str(), inbuf_size);
122 out.resize(outbuf_size);
124 if (!convert("UTF-8", DEFAULT_ENCODING, &out[0], &outbuf_size, inbuf, inbuf_size)) {
125 infostream << "Couldn't convert wstring 0x" << hex_encode(inbuf, inbuf_size)
126 << " into UTF-8 string" << std::endl;
128 return "<invalid wide string>";
132 out.resize(outbuf_size);
138 std::wstring utf8_to_wide(const std::string &input)
140 size_t outbuf_size = input.size() + 1;
141 wchar_t *outbuf = new wchar_t[outbuf_size];
142 memset(outbuf, 0, outbuf_size * sizeof(wchar_t));
143 MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(),
144 outbuf, outbuf_size);
145 std::wstring out(outbuf);
150 std::string wide_to_utf8(const std::wstring &input)
152 size_t outbuf_size = (input.size() + 1) * 6;
153 char *outbuf = new char[outbuf_size];
154 memset(outbuf, 0, outbuf_size);
155 WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(),
156 outbuf, outbuf_size, NULL, NULL);
157 std::string out(outbuf);
164 wchar_t *utf8_to_wide_c(const char *str)
166 std::wstring ret = utf8_to_wide(std::string(str));
167 size_t len = ret.length();
168 wchar_t *ret_c = new wchar_t[len + 1];
169 memcpy(ret_c, ret.c_str(), (len + 1) * sizeof(wchar_t));
174 std::string urlencode(const std::string &str)
176 // Encodes non-unreserved URI characters by a percent sign
177 // followed by two hex digits. See RFC 3986, section 2.3.
178 static const char url_hex_chars[] = "0123456789ABCDEF";
179 std::ostringstream oss(std::ios::binary);
180 for (unsigned char c : str) {
181 if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
185 << url_hex_chars[(c & 0xf0) >> 4]
186 << url_hex_chars[c & 0x0f];
192 std::string urldecode(const std::string &str)
194 // Inverse of urlencode
195 std::ostringstream oss(std::ios::binary);
196 for (u32 i = 0; i < str.size(); i++) {
197 unsigned char highvalue, lowvalue;
199 hex_digit_decode(str[i+1], highvalue) &&
200 hex_digit_decode(str[i+2], lowvalue)) {
201 oss << (char) ((highvalue << 4) | lowvalue);
210 u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask)
216 char *strpos = nullptr;
218 while ((flagstr = strtok_r(s, ",", &strpos))) {
221 while (*flagstr == ' ' || *flagstr == '\t')
225 if (!strncasecmp(flagstr, "no", 2)) {
230 for (int i = 0; flagdesc[i].name; i++) {
231 if (!strcasecmp(flagstr, flagdesc[i].name)) {
232 mask |= flagdesc[i].flag;
234 result |= flagdesc[i].flag;
246 std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask)
250 for (int i = 0; flagdesc[i].name; i++) {
251 if (flagmask & flagdesc[i].flag) {
252 if (!(flags & flagdesc[i].flag))
255 result += flagdesc[i].name;
260 size_t len = result.length();
262 result.erase(len - 2, 2);
267 size_t mystrlcpy(char *dst, const char *src, size_t size)
269 size_t srclen = strlen(src) + 1;
270 size_t copylen = MYMIN(srclen, size);
273 memcpy(dst, src, copylen);
274 dst[copylen - 1] = '\0';
280 char *mystrtok_r(char *s, const char *sep, char **lasts)
287 while (*s && strchr(sep, *s))
295 if (strchr(sep, *t)) {
306 u64 read_seed(const char *str)
311 if (str[0] == '0' && str[1] == 'x')
312 num = strtoull(str, &endptr, 16);
314 num = strtoull(str, &endptr, 10);
317 num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337);
322 static bool parseHexColorString(const std::string &value, video::SColor &color,
323 unsigned char default_alpha)
325 u8 components[] = {0x00, 0x00, 0x00, default_alpha}; // R,G,B,A
327 size_t len = value.size();
330 if (len == 9 || len == 7) // #RRGGBBAA or #RRGGBB
332 else if (len == 5 || len == 4) // #RGBA or #RGB
337 for (size_t pos = 1, cc = 0; pos < len; pos++, cc++) {
340 if (!hex_digit_decode(value[pos], d))
343 components[cc] = (d & 0xf) << 4 | (d & 0xf);
346 if (!hex_digit_decode(value[pos], d1) ||
347 !hex_digit_decode(value[pos+1], d2))
350 components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf);
351 pos++; // skip the second digit -- it's already used
355 color.setRed(components[0]);
356 color.setGreen(components[1]);
357 color.setBlue(components[2]);
358 color.setAlpha(components[3]);
363 const static std::unordered_map<std::string, u32> s_named_colors = {
364 {"aliceblue", 0xf0f8ff},
365 {"antiquewhite", 0xfaebd7},
367 {"aquamarine", 0x7fffd4},
370 {"bisque", 0xffe4c4},
372 {"blanchedalmond", 0xffebcd},
374 {"blueviolet", 0x8a2be2},
376 {"burlywood", 0xdeb887},
377 {"cadetblue", 0x5f9ea0},
378 {"chartreuse", 0x7fff00},
379 {"chocolate", 0xd2691e},
381 {"cornflowerblue", 0x6495ed},
382 {"cornsilk", 0xfff8dc},
383 {"crimson", 0xdc143c},
385 {"darkblue", 0x00008b},
386 {"darkcyan", 0x008b8b},
387 {"darkgoldenrod", 0xb8860b},
388 {"darkgray", 0xa9a9a9},
389 {"darkgreen", 0x006400},
390 {"darkgrey", 0xa9a9a9},
391 {"darkkhaki", 0xbdb76b},
392 {"darkmagenta", 0x8b008b},
393 {"darkolivegreen", 0x556b2f},
394 {"darkorange", 0xff8c00},
395 {"darkorchid", 0x9932cc},
396 {"darkred", 0x8b0000},
397 {"darksalmon", 0xe9967a},
398 {"darkseagreen", 0x8fbc8f},
399 {"darkslateblue", 0x483d8b},
400 {"darkslategray", 0x2f4f4f},
401 {"darkslategrey", 0x2f4f4f},
402 {"darkturquoise", 0x00ced1},
403 {"darkviolet", 0x9400d3},
404 {"deeppink", 0xff1493},
405 {"deepskyblue", 0x00bfff},
406 {"dimgray", 0x696969},
407 {"dimgrey", 0x696969},
408 {"dodgerblue", 0x1e90ff},
409 {"firebrick", 0xb22222},
410 {"floralwhite", 0xfffaf0},
411 {"forestgreen", 0x228b22},
412 {"fuchsia", 0xff00ff},
413 {"gainsboro", 0xdcdcdc},
414 {"ghostwhite", 0xf8f8ff},
416 {"goldenrod", 0xdaa520},
419 {"greenyellow", 0xadff2f},
421 {"honeydew", 0xf0fff0},
422 {"hotpink", 0xff69b4},
423 {"indianred", 0xcd5c5c},
424 {"indigo", 0x4b0082},
427 {"lavender", 0xe6e6fa},
428 {"lavenderblush", 0xfff0f5},
429 {"lawngreen", 0x7cfc00},
430 {"lemonchiffon", 0xfffacd},
431 {"lightblue", 0xadd8e6},
432 {"lightcoral", 0xf08080},
433 {"lightcyan", 0xe0ffff},
434 {"lightgoldenrodyellow", 0xfafad2},
435 {"lightgray", 0xd3d3d3},
436 {"lightgreen", 0x90ee90},
437 {"lightgrey", 0xd3d3d3},
438 {"lightpink", 0xffb6c1},
439 {"lightsalmon", 0xffa07a},
440 {"lightseagreen", 0x20b2aa},
441 {"lightskyblue", 0x87cefa},
442 {"lightslategray", 0x778899},
443 {"lightslategrey", 0x778899},
444 {"lightsteelblue", 0xb0c4de},
445 {"lightyellow", 0xffffe0},
447 {"limegreen", 0x32cd32},
449 {"magenta", 0xff00ff},
450 {"maroon", 0x800000},
451 {"mediumaquamarine", 0x66cdaa},
452 {"mediumblue", 0x0000cd},
453 {"mediumorchid", 0xba55d3},
454 {"mediumpurple", 0x9370db},
455 {"mediumseagreen", 0x3cb371},
456 {"mediumslateblue", 0x7b68ee},
457 {"mediumspringgreen", 0x00fa9a},
458 {"mediumturquoise", 0x48d1cc},
459 {"mediumvioletred", 0xc71585},
460 {"midnightblue", 0x191970},
461 {"mintcream", 0xf5fffa},
462 {"mistyrose", 0xffe4e1},
463 {"moccasin", 0xffe4b5},
464 {"navajowhite", 0xffdead},
466 {"oldlace", 0xfdf5e6},
468 {"olivedrab", 0x6b8e23},
469 {"orange", 0xffa500},
470 {"orangered", 0xff4500},
471 {"orchid", 0xda70d6},
472 {"palegoldenrod", 0xeee8aa},
473 {"palegreen", 0x98fb98},
474 {"paleturquoise", 0xafeeee},
475 {"palevioletred", 0xdb7093},
476 {"papayawhip", 0xffefd5},
477 {"peachpuff", 0xffdab9},
481 {"powderblue", 0xb0e0e6},
482 {"purple", 0x800080},
483 {"rebeccapurple", 0x663399},
485 {"rosybrown", 0xbc8f8f},
486 {"royalblue", 0x4169e1},
487 {"saddlebrown", 0x8b4513},
488 {"salmon", 0xfa8072},
489 {"sandybrown", 0xf4a460},
490 {"seagreen", 0x2e8b57},
491 {"seashell", 0xfff5ee},
492 {"sienna", 0xa0522d},
493 {"silver", 0xc0c0c0},
494 {"skyblue", 0x87ceeb},
495 {"slateblue", 0x6a5acd},
496 {"slategray", 0x708090},
497 {"slategrey", 0x708090},
499 {"springgreen", 0x00ff7f},
500 {"steelblue", 0x4682b4},
503 {"thistle", 0xd8bfd8},
504 {"tomato", 0xff6347},
505 {"turquoise", 0x40e0d0},
506 {"violet", 0xee82ee},
509 {"whitesmoke", 0xf5f5f5},
510 {"yellow", 0xffff00},
511 {"yellowgreen", 0x9acd32}
514 static bool parseNamedColorString(const std::string &value, video::SColor &color)
516 std::string color_name;
517 std::string alpha_string;
519 /* If the string has a # in it, assume this is the start of a specified
520 * alpha value (if it isn't the string is invalid and the error will be
521 * caught later on, either because the color name won't be found or the
522 * alpha value will fail conversion)
524 size_t alpha_pos = value.find('#');
525 if (alpha_pos != std::string::npos) {
526 color_name = value.substr(0, alpha_pos);
527 alpha_string = value.substr(alpha_pos + 1);
532 color_name = lowercase(color_name);
534 auto it = s_named_colors.find(color_name);
535 if (it == s_named_colors.end())
538 u32 color_temp = it->second;
540 /* An empty string for alpha is ok (none of the color table entries
541 * have an alpha value either). Color strings without an alpha specified
542 * are interpreted as fully opaque
544 if (!alpha_string.empty()) {
545 if (alpha_string.size() == 1) {
547 if (!hex_digit_decode(alpha_string[0], d))
550 color_temp |= ((d & 0xf) << 4 | (d & 0xf)) << 24;
551 } else if (alpha_string.size() == 2) {
553 if (!hex_digit_decode(alpha_string[0], d1)
554 || !hex_digit_decode(alpha_string[1], d2))
557 color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24;
562 color_temp |= 0xff << 24; // Fully opaque
565 color = video::SColor(color_temp);
570 bool parseColorString(const std::string &value, video::SColor &color, bool quiet,
571 unsigned char default_alpha)
576 success = parseHexColorString(value, color, default_alpha);
578 success = parseNamedColorString(value, color);
580 if (!success && !quiet)
581 errorstream << "Invalid color: \"" << value << "\"" << std::endl;
586 void str_replace(std::string &str, char from, char to)
588 std::replace(str.begin(), str.end(), from, to);
591 /* Translated strings have the following format:
592 * \x1bT marks the beginning of a translated string
593 * \x1bE marks its end
595 * \x1bF marks the beginning of an argument, and \x1bE its end.
597 * Arguments are *not* translated, as they may contain escape codes.
598 * Thus, if you want a translated argument, it should be inside \x1bT/\x1bE tags as well.
600 * This representation is chosen so that clients ignoring escape codes will
601 * see untranslated strings.
603 * For instance, suppose we have a string such as "@1 Wool" with the argument "White"
604 * The string will be sent as "\x1bT\x1bF\x1bTWhite\x1bE\x1bE Wool\x1bE"
605 * To translate this string, we extract what is inside \x1bT/\x1bE tags.
606 * When we notice the \x1bF tag, we recursively extract what is there up to the \x1bE end tag,
607 * translating it as well.
608 * We get the argument "White", translated, and create a template string with "@1" instead of it.
609 * We finally get the template "@1 Wool" that was used in the beginning, which we translate
610 * before filling it again.
613 void translate_all(const std::wstring &s, size_t &i,
614 Translations *translations, std::wstring &res);
616 void translate_string(const std::wstring &s, Translations *translations,
617 const std::wstring &textdomain, size_t &i, std::wstring &res)
619 std::wostringstream output;
620 std::vector<std::wstring> args;
622 while (i < s.length()) {
623 // Not an escape sequence: just add the character.
624 if (s[i] != '\x1b') {
626 // The character is a literal '@'; add it twice
627 // so that it is not mistaken for an argument.
634 // We have an escape sequence: locate it and its data
635 // It is either a single character, or it begins with '('
636 // and extends up to the following ')', with '\' as an escape character.
638 size_t start_index = i;
640 if (i == s.length()) {
642 } else if (s[i] == L'(') {
645 while (i < s.length() && s[i] != L')') {
650 length = i - start_index;
658 std::wstring escape_sequence(s, start_index, length);
660 // The escape sequence is now reconstructed.
661 std::vector<std::wstring> parts = split(escape_sequence, L'@');
662 if (parts[0] == L"E") {
663 // "End of translation" escape sequence. We are done locating the string to translate.
665 } else if (parts[0] == L"F") {
666 // "Start of argument" escape sequence.
667 // Recursively translate the argument, and add it to the argument list.
668 // Add an "@n" instead of the argument to the template to translate.
669 if (arg_number >= 10) {
670 errorstream << "Ignoring too many arguments to translation" << std::endl;
672 translate_all(s, i, translations, arg);
677 output << arg_number;
680 translate_all(s, i, translations, arg);
683 // This is an escape sequence *inside* the template string to translate itself.
684 // This should not happen, show an error message.
685 errorstream << "Ignoring escape sequence '"
686 << wide_to_utf8(escape_sequence) << "' in translation" << std::endl;
690 std::wstring toutput;
691 // Translate the template.
692 if (translations != nullptr)
693 toutput = translations->getTranslation(
694 textdomain, output.str());
696 toutput = output.str();
698 // Put back the arguments in the translated template.
699 std::wostringstream result;
701 while (j < toutput.length()) {
702 // Normal character, add it to output and continue.
703 if (toutput[j] != L'@' || j == toutput.length() - 1) {
704 result.put(toutput[j]);
710 // Literal escape for '@'.
711 if (toutput[j] == L'@') {
717 // Here we have an argument; get its index and add the translated argument to the output.
718 int arg_index = toutput[j] - L'1';
720 if (0 <= arg_index && (size_t)arg_index < args.size()) {
721 result << args[arg_index];
723 // This is not allowed: show an error message
724 errorstream << "Ignoring out-of-bounds argument escape sequence in translation" << std::endl;
730 void translate_all(const std::wstring &s, size_t &i,
731 Translations *translations, std::wstring &res)
733 std::wostringstream output;
734 while (i < s.length()) {
735 // Not an escape sequence: just add the character.
736 if (s[i] != '\x1b') {
742 // We have an escape sequence: locate it and its data
743 // It is either a single character, or it begins with '('
744 // and extends up to the following ')', with '\' as an escape character.
745 size_t escape_start = i;
747 size_t start_index = i;
749 if (i == s.length()) {
751 } else if (s[i] == L'(') {
754 while (i < s.length() && s[i] != L')') {
760 length = i - start_index;
768 std::wstring escape_sequence(s, start_index, length);
770 // The escape sequence is now reconstructed.
771 std::vector<std::wstring> parts = split(escape_sequence, L'@');
772 if (parts[0] == L"E") {
773 // "End of argument" escape sequence. Exit.
775 } else if (parts[0] == L"T") {
776 // Beginning of translated string.
777 std::wstring textdomain;
778 if (parts.size() > 1)
779 textdomain = parts[1];
780 std::wstring translated;
781 translate_string(s, translations, textdomain, i, translated);
782 output << translated;
784 // Another escape sequence, such as colors. Preserve it.
785 output << std::wstring(s, escape_start, i - escape_start);
792 // Translate string server side
793 std::wstring translate_string(const std::wstring &s, Translations *translations)
797 translate_all(s, i, translations, res);
801 // Translate string client side
802 std::wstring translate_string(const std::wstring &s)
805 return translate_string(s, nullptr);
807 return translate_string(s, g_client_translations);
811 static const std::array<std::wstring, 30> disallowed_dir_names = {
812 // Problematic filenames from here:
813 // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#file-and-directory-names
814 // Plus undocumented values from here:
815 // https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html
849 * List of characters that are blacklisted from created directories
851 static const std::wstring disallowed_path_chars = L"<>:\"/\\|?*.";
854 std::string sanitizeDirName(const std::string &str, const std::string &optional_prefix)
856 std::wstring safe_name = utf8_to_wide(str);
858 for (std::wstring disallowed_name : disallowed_dir_names) {
859 if (str_equal(safe_name, disallowed_name, true)) {
860 safe_name = utf8_to_wide(optional_prefix) + safe_name;
865 // Replace leading and trailing spaces with underscores.
866 size_t start = safe_name.find_first_not_of(L' ');
867 size_t end = safe_name.find_last_not_of(L' ');
868 if (start == std::wstring::npos || end == std::wstring::npos)
869 start = end = safe_name.size();
870 for (size_t i = 0; i < start; i++)
872 for (size_t i = end + 1; i < safe_name.size(); i++)
875 // Replace other disallowed characters with underscores
876 for (size_t i = 0; i < safe_name.length(); i++) {
877 bool is_valid = true;
879 // Unlikely, but control characters should always be blacklisted
880 if (safe_name[i] < 32) {
882 } else if (safe_name[i] < 128) {
883 is_valid = disallowed_path_chars.find_first_of(safe_name[i])
884 == std::wstring::npos;
891 return wide_to_utf8(safe_name);
895 void safe_print_string(std::ostream &os, const std::string &str)
897 std::ostream::fmtflags flags = os.flags();
899 for (const char c : str) {
900 if (IS_ASCII_PRINTABLE_CHAR(c) || IS_UTF8_MULTB_START(c) ||
901 IS_UTF8_MULTB_INNER(c) || c == '\n' || c == '\t') {
904 os << '<' << std::setw(2) << (int)c << '>';