1 // Copyright 2011, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // ICU integration functions.
34 #include <unicode/ucnv.h>
35 #include <unicode/ucnv_cb.h>
36 #include <unicode/uidna.h>
38 #include "base/logging.h"
39 #include "url/url_canon_icu.h"
40 #include "url/url_canon_internal.h" // for _itoa_s
46 // Called when converting a character that can not be represented, this will
47 // append an escaped version of the numerical character reference for that code
48 // point. It is of the form "Ӓ" and we will escape the non-digits to
49 // "%26%231234%3B". Why? This is what Netscape did back in the olden days.
50 void appendURLEscapedChar(const void* context
,
51 UConverterFromUnicodeArgs
* from_args
,
52 const UChar
* code_units
,
55 UConverterCallbackReason reason
,
57 if (reason
== UCNV_UNASSIGNED
) {
60 const static int prefix_len
= 6;
61 const static char prefix
[prefix_len
+ 1] = "%26%23"; // "&#" percent-escaped
62 ucnv_cbFromUWriteBytes(from_args
, prefix
, prefix_len
, 0, err
);
64 DCHECK(code_point
< 0x110000);
65 char number
[8]; // Max Unicode code point is 7 digits.
66 _itoa_s(code_point
, number
, 10);
67 int number_len
= static_cast<int>(strlen(number
));
68 ucnv_cbFromUWriteBytes(from_args
, number
, number_len
, 0, err
);
70 const static int postfix_len
= 3;
71 const static char postfix
[postfix_len
+ 1] = "%3B"; // ";" percent-escaped
72 ucnv_cbFromUWriteBytes(from_args
, postfix
, postfix_len
, 0, err
);
76 // A class for scoping the installation of the invalid character callback.
77 class AppendHandlerInstaller
{
79 // The owner of this object must ensure that the converter is alive for the
80 // duration of this object's lifetime.
81 AppendHandlerInstaller(UConverter
* converter
) : converter_(converter
) {
82 UErrorCode err
= U_ZERO_ERROR
;
83 ucnv_setFromUCallBack(converter_
, appendURLEscapedChar
, 0,
84 &old_callback_
, &old_context_
, &err
);
87 ~AppendHandlerInstaller() {
88 UErrorCode err
= U_ZERO_ERROR
;
89 ucnv_setFromUCallBack(converter_
, old_callback_
, old_context_
, 0, 0, &err
);
93 UConverter
* converter_
;
95 UConverterFromUCallback old_callback_
;
96 const void* old_context_
;
101 ICUCharsetConverter::ICUCharsetConverter(UConverter
* converter
)
102 : converter_(converter
) {
105 ICUCharsetConverter::~ICUCharsetConverter() {
108 void ICUCharsetConverter::ConvertFromUTF16(const char16
* input
,
110 CanonOutput
* output
) {
111 // Install our error handler. It will be called for character that can not
112 // be represented in the destination character set.
113 AppendHandlerInstaller
handler(converter_
);
115 int begin_offset
= output
->length();
116 int dest_capacity
= output
->capacity() - begin_offset
;
117 output
->set_length(output
->length());
120 UErrorCode err
= U_ZERO_ERROR
;
121 char* dest
= &output
->data()[begin_offset
];
122 int required_capacity
= ucnv_fromUChars(converter_
, dest
, dest_capacity
,
123 input
, input_len
, &err
);
124 if (err
!= U_BUFFER_OVERFLOW_ERROR
) {
125 output
->set_length(begin_offset
+ required_capacity
);
129 // Output didn't fit, expand
130 dest_capacity
= required_capacity
;
131 output
->Resize(begin_offset
+ dest_capacity
);
135 // Converts the Unicode input representing a hostname to ASCII using IDN rules.
136 // The output must be ASCII, but is represented as wide characters.
138 // On success, the output will be filled with the ASCII host name and it will
139 // return true. Unlike most other canonicalization functions, this assumes that
140 // the output is empty. The beginning of the host will be at offset 0, and
141 // the length of the output will be set to the length of the new host name.
143 // On error, this will return false. The output in this case is undefined.
144 bool IDNToASCII(const char16
* src
, int src_len
, CanonOutputW
* output
) {
145 DCHECK(output
->length() == 0); // Output buffer is assumed empty.
147 // Use ALLOW_UNASSIGNED to be more tolerant of hostnames that violate
148 // the spec (which do exist). This does not present any risk and is a
149 // little more future proof.
150 UErrorCode err
= U_ZERO_ERROR
;
151 int num_converted
= uidna_IDNToASCII(src
, src_len
, output
->data(),
153 UIDNA_ALLOW_UNASSIGNED
, NULL
, &err
);
154 if (err
== U_ZERO_ERROR
) {
155 output
->set_length(num_converted
);
158 if (err
!= U_BUFFER_OVERFLOW_ERROR
)
159 return false; // Unknown error, give up.
161 // Not enough room in our buffer, expand.
162 output
->Resize(output
->capacity() * 2);
166 bool ReadUTFChar(const char* str
, int* begin
, int length
,
167 unsigned* code_point_out
) {
168 int code_point
; // Avoids warning when U8_NEXT writes -1 to it.
169 U8_NEXT(str
, *begin
, length
, code_point
);
170 *code_point_out
= static_cast<unsigned>(code_point
);
172 // The ICU macro above moves to the next char, we want to point to the last
176 // Validate the decoded value.
177 if (U_IS_UNICODE_CHAR(code_point
))
179 *code_point_out
= kUnicodeReplacementCharacter
;
183 bool ReadUTFChar(const char16
* str
, int* begin
, int length
,
184 unsigned* code_point
) {
185 if (U16_IS_SURROGATE(str
[*begin
])) {
186 if (!U16_IS_SURROGATE_LEAD(str
[*begin
]) || *begin
+ 1 >= length
||
187 !U16_IS_TRAIL(str
[*begin
+ 1])) {
188 // Invalid surrogate pair.
189 *code_point
= kUnicodeReplacementCharacter
;
192 // Valid surrogate pair.
193 *code_point
= U16_GET_SUPPLEMENTARY(str
[*begin
], str
[*begin
+ 1]);
197 // Not a surrogate, just one 16-bit word.
198 *code_point
= str
[*begin
];
201 if (U_IS_UNICODE_CHAR(*code_point
))
204 // Invalid code point.
205 *code_point
= kUnicodeReplacementCharacter
;
209 } // namespace url_canon