Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / url / url_canon_icu.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // ICU integration functions.
6
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "third_party/icu/source/common/unicode/ucnv.h"
14 #include "third_party/icu/source/common/unicode/ucnv_cb.h"
15 #include "third_party/icu/source/common/unicode/uidna.h"
16 #include "third_party/icu/source/common/unicode/utypes.h"
17 #include "url/url_canon_icu.h"
18 #include "url/url_canon_internal.h"  // for _itoa_s
19
20 namespace url {
21
22 namespace {
23
24 // Called when converting a character that can not be represented, this will
25 // append an escaped version of the numerical character reference for that code
26 // point. It is of the form "&#1234;" and we will escape the non-digits to
27 // "%26%231234%3B". Why? This is what Netscape did back in the olden days.
28 void appendURLEscapedChar(const void* context,
29                           UConverterFromUnicodeArgs* from_args,
30                           const UChar* code_units,
31                           int32_t length,
32                           UChar32 code_point,
33                           UConverterCallbackReason reason,
34                           UErrorCode* err) {
35   if (reason == UCNV_UNASSIGNED) {
36     *err = U_ZERO_ERROR;
37
38     const static int prefix_len = 6;
39     const static char prefix[prefix_len + 1] = "%26%23";  // "&#" percent-escaped
40     ucnv_cbFromUWriteBytes(from_args, prefix, prefix_len, 0, err);
41
42     DCHECK(code_point < 0x110000);
43     char number[8];  // Max Unicode code point is 7 digits.
44     _itoa_s(code_point, number, 10);
45     int number_len = static_cast<int>(strlen(number));
46     ucnv_cbFromUWriteBytes(from_args, number, number_len, 0, err);
47
48     const static int postfix_len = 3;
49     const static char postfix[postfix_len + 1] = "%3B";   // ";" percent-escaped
50     ucnv_cbFromUWriteBytes(from_args, postfix, postfix_len, 0, err);
51   }
52 }
53
54 // A class for scoping the installation of the invalid character callback.
55 class AppendHandlerInstaller {
56  public:
57   // The owner of this object must ensure that the converter is alive for the
58   // duration of this object's lifetime.
59   AppendHandlerInstaller(UConverter* converter) : converter_(converter) {
60     UErrorCode err = U_ZERO_ERROR;
61     ucnv_setFromUCallBack(converter_, appendURLEscapedChar, 0,
62                           &old_callback_, &old_context_, &err);
63   }
64
65   ~AppendHandlerInstaller() {
66     UErrorCode err = U_ZERO_ERROR;
67     ucnv_setFromUCallBack(converter_, old_callback_, old_context_, 0, 0, &err);
68   }
69
70  private:
71   UConverter* converter_;
72
73   UConverterFromUCallback old_callback_;
74   const void* old_context_;
75 };
76
77 // A wrapper to use LazyInstance<>::Leaky with ICU's UIDNA, a C pointer to
78 // a UTS46/IDNA 2008 handling object opened with uidna_openUTS46().
79 //
80 // We use UTS46 with BiDiCheck to migrate from IDNA 2003 (with unassigned
81 // code points allowed) to IDNA 2008 with
82 // the backward compatibility in mind. What it does:
83 //
84 // 1. Use the up-to-date Unicode data.
85 // 2. Define a case folding/mapping with the up-to-date Unicode data as
86 //    in IDNA 2003.
87 // 3. Use transitional mechanism for 4 deviation characters (sharp-s,
88 //    final sigma, ZWJ and ZWNJ) for now.
89 // 4. Continue to allow symbols and punctuations.
90 // 5. Apply new BiDi check rules more permissive than the IDNA 2003 BiDI rules.
91 // 6. Do not apply STD3 rules
92 // 7. Do not allow unassigned code points.
93 //
94 // It also closely matches what IE 10 does except for the BiDi check (
95 // http://goo.gl/3XBhqw ).
96 // See http://http://unicode.org/reports/tr46/ and references therein
97 // for more details.
98 struct UIDNAWrapper {
99   UIDNAWrapper() {
100     UErrorCode err = U_ZERO_ERROR;
101     // TODO(jungshik): Change options as different parties (browsers,
102     // registrars, search engines) converge toward a consensus.
103     value = uidna_openUTS46(UIDNA_CHECK_BIDI, &err);
104     if (U_FAILURE(err)) {
105       CHECK(false) << "failed to open UTS46 data with error: "
106                    << u_errorName(err)
107                    << ". If you see this error message in a test environment "
108                    << "your test environment likely lacks the required data "
109                    << "tables for libicu. See https://crbug.com/778929.";
110       value = NULL;
111     }
112   }
113
114   UIDNA* value;
115 };
116
117 }  // namespace
118
119 ICUCharsetConverter::ICUCharsetConverter(UConverter* converter)
120     : converter_(converter) {
121 }
122
123 ICUCharsetConverter::~ICUCharsetConverter() = default;
124
125 void ICUCharsetConverter::ConvertFromUTF16(const base::char16* input,
126                                            int input_len,
127                                            CanonOutput* output) {
128   // Install our error handler. It will be called for character that can not
129   // be represented in the destination character set.
130   AppendHandlerInstaller handler(converter_);
131
132   int begin_offset = output->length();
133   int dest_capacity = output->capacity() - begin_offset;
134   output->set_length(output->length());
135
136   do {
137     UErrorCode err = U_ZERO_ERROR;
138     char* dest = &output->data()[begin_offset];
139     int required_capacity = ucnv_fromUChars(converter_, dest, dest_capacity,
140                                             input, input_len, &err);
141     if (err != U_BUFFER_OVERFLOW_ERROR) {
142       output->set_length(begin_offset + required_capacity);
143       return;
144     }
145
146     // Output didn't fit, expand
147     dest_capacity = required_capacity;
148     output->Resize(begin_offset + dest_capacity);
149   } while (true);
150 }
151
152 static base::LazyInstance<UIDNAWrapper>::Leaky
153     g_uidna = LAZY_INSTANCE_INITIALIZER;
154
155 // Converts the Unicode input representing a hostname to ASCII using IDN rules.
156 // The output must be ASCII, but is represented as wide characters.
157 //
158 // On success, the output will be filled with the ASCII host name and it will
159 // return true. Unlike most other canonicalization functions, this assumes that
160 // the output is empty. The beginning of the host will be at offset 0, and
161 // the length of the output will be set to the length of the new host name.
162 //
163 // On error, this will return false. The output in this case is undefined.
164 // TODO(jungshik): use UTF-8/ASCII version of nameToASCII.
165 // Change the function signature and callers accordingly to avoid unnecessary
166 // conversions in our code. In addition, consider using icu::IDNA's UTF-8/ASCII
167 // version with StringByteSink. That way, we can avoid C wrappers and additional
168 // string conversion.
169 bool IDNToASCII(const base::char16* src, int src_len, CanonOutputW* output) {
170   DCHECK(output->length() == 0);  // Output buffer is assumed empty.
171
172   UIDNA* uidna = g_uidna.Get().value;
173   DCHECK(uidna != NULL);
174   while (true) {
175     UErrorCode err = U_ZERO_ERROR;
176     UIDNAInfo info = UIDNA_INFO_INITIALIZER;
177     int output_length = uidna_nameToASCII(uidna, src, src_len, output->data(),
178                                           output->capacity(), &info, &err);
179     if (U_SUCCESS(err) && info.errors == 0) {
180       output->set_length(output_length);
181       return true;
182     }
183
184     // TODO(jungshik): Look at info.errors to handle them case-by-case basis
185     // if necessary.
186     if (err != U_BUFFER_OVERFLOW_ERROR || info.errors != 0)
187       return false;  // Unknown error, give up.
188
189     // Not enough room in our buffer, expand.
190     output->Resize(output_length);
191   }
192 }
193
194 }  // namespace url