1 /*
2 * Copyright (C) 2004, 2006, 2007, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 Alexey Proskuryakov <ap@nypop.com>
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 #include "config.h"
28 #include "TextCodecICU.h"
29
30 #include "CharacterNames.h"
31 #include "CString.h"
32 #include "PlatformString.h"
33 #include "ThreadGlobalData.h"
34 #include <unicode/ucnv.h>
35 #include <unicode/ucnv_cb.h>
36 #include <wtf/Assertions.h>
37 #include <wtf/StringExtras.h>
38 #include <wtf/Threading.h>
39
40 using std::auto_ptr;
41 using std::min;
42
43 namespace WebCore {
44
45 const size_t ConversionBufferSize = 16384;
46
~ICUConverterWrapper()47 ICUConverterWrapper::~ICUConverterWrapper()
48 {
49 if (converter)
50 ucnv_close(converter);
51 }
52
cachedConverterICU()53 static UConverter*& cachedConverterICU()
54 {
55 return threadGlobalData().cachedConverterICU().converter;
56 }
57
newTextCodecICU(const TextEncoding & encoding,const void *)58 static auto_ptr<TextCodec> newTextCodecICU(const TextEncoding& encoding, const void*)
59 {
60 return auto_ptr<TextCodec>(new TextCodecICU(encoding));
61 }
62
registerBaseEncodingNames(EncodingNameRegistrar registrar)63 void TextCodecICU::registerBaseEncodingNames(EncodingNameRegistrar registrar)
64 {
65 registrar("UTF-8", "UTF-8");
66 }
67
registerBaseCodecs(TextCodecRegistrar registrar)68 void TextCodecICU::registerBaseCodecs(TextCodecRegistrar registrar)
69 {
70 registrar("UTF-8", newTextCodecICU, 0);
71 }
72
73 // FIXME: Registering all the encodings we get from ucnv_getAvailableName
74 // includes encodings we don't want or need. For example, all
75 // the encodings with commas and version numbers.
76
registerExtendedEncodingNames(EncodingNameRegistrar registrar)77 void TextCodecICU::registerExtendedEncodingNames(EncodingNameRegistrar registrar)
78 {
79 // We register Hebrew with logical ordering using a separate name.
80 // Otherwise, this would share the same canonical name as the
81 // visual ordering case, and then TextEncoding could not tell them
82 // apart; ICU treats these names as synonyms.
83 registrar("ISO-8859-8-I", "ISO-8859-8-I");
84
85 int32_t numEncodings = ucnv_countAvailable();
86 for (int32_t i = 0; i < numEncodings; ++i) {
87 const char* name = ucnv_getAvailableName(i);
88 UErrorCode error = U_ZERO_ERROR;
89 // Try MIME before trying IANA to pick up commonly used names like
90 // 'EUC-JP' instead of horrendeously long names like
91 // 'Extended_UNIX_Code_Packed_Format_for_Japanese'.
92 const char* standardName = ucnv_getStandardName(name, "MIME", &error);
93 if (!U_SUCCESS(error) || !standardName) {
94 error = U_ZERO_ERROR;
95 // Try IANA to pick up 'windows-12xx' and other names
96 // which are not preferred MIME names but are widely used.
97 standardName = ucnv_getStandardName(name, "IANA", &error);
98 if (!U_SUCCESS(error) || !standardName)
99 continue;
100 }
101
102 // 1. Treat GB2312 encoding as GBK (its more modern superset), to match other browsers.
103 // 2. On the Web, GB2312 is encoded as EUC-CN or HZ, while ICU provides a native encoding
104 // for encoding GB_2312-80 and several others. So, we need to override this behavior, too.
105 if (strcmp(standardName, "GB2312") == 0 || strcmp(standardName, "GB_2312-80") == 0)
106 standardName = "GBK";
107 // Similarly, EUC-KR encodings all map to an extended version.
108 else if (strcmp(standardName, "KSC_5601") == 0 || strcmp(standardName, "EUC-KR") == 0 || strcmp(standardName, "cp1363") == 0)
109 standardName = "windows-949";
110 // And so on.
111 else if (strcasecmp(standardName, "iso-8859-9") == 0) // This name is returned in different case by ICU 3.2 and 3.6.
112 standardName = "windows-1254";
113 else if (strcmp(standardName, "TIS-620") == 0)
114 standardName = "windows-874";
115
116 registrar(standardName, standardName);
117
118 uint16_t numAliases = ucnv_countAliases(name, &error);
119 ASSERT(U_SUCCESS(error));
120 if (U_SUCCESS(error))
121 for (uint16_t j = 0; j < numAliases; ++j) {
122 error = U_ZERO_ERROR;
123 const char* alias = ucnv_getAlias(name, j, &error);
124 ASSERT(U_SUCCESS(error));
125 if (U_SUCCESS(error) && alias != standardName)
126 registrar(alias, standardName);
127 }
128 }
129
130 // Additional aliases.
131 // These are present in modern versions of ICU, but not in ICU 3.2 (shipped with Mac OS X 10.4).
132 registrar("macroman", "macintosh");
133 #ifndef ANDROID // Android does not have x-mac-cyrillic in its ICU library
134 registrar("maccyrillic", "x-mac-cyrillic");
135 #endif
136
137 // Additional aliases that historically were present in the encoding
138 // table in WebKit on Macintosh that don't seem to be present in ICU.
139 // Perhaps we can prove these are not used on the web and remove them.
140 // Or perhaps we can get them added to ICU.
141 registrar("xmacroman", "macintosh");
142 #ifndef ANDROID // Android does not have x-mac-cyrillic in its ICU library
143 registrar("xmacukrainian", "x-mac-cyrillic");
144 #endif
145 registrar("cnbig5", "Big5");
146 registrar("xxbig5", "Big5");
147 registrar("cngb", "GBK");
148 registrar("csgb231280", "GBK");
149 registrar("xeuccn", "GBK");
150 registrar("xgbk", "GBK");
151 registrar("csISO88598I", "ISO_8859-8-I");
152 registrar("koi", "KOI8-R");
153 registrar("logical", "ISO-8859-8-I");
154 registrar("unicode11utf8", "UTF-8");
155 registrar("unicode20utf8", "UTF-8");
156 registrar("xunicode20utf8", "UTF-8");
157 registrar("visual", "ISO-8859-8");
158 registrar("winarabic", "windows-1256");
159 registrar("winbaltic", "windows-1257");
160 registrar("wincyrillic", "windows-1251");
161 registrar("iso885911", "windows-874");
162 registrar("dos874", "windows-874");
163 registrar("wingreek", "windows-1253");
164 registrar("winhebrew", "windows-1255");
165 registrar("winlatin2", "windows-1250");
166 registrar("winturkish", "windows-1254");
167 registrar("winvietnamese", "windows-1258");
168 registrar("xcp1250", "windows-1250");
169 registrar("xcp1251", "windows-1251");
170 registrar("xeuc", "EUC-JP");
171 registrar("xwindows949", "windows-949");
172 registrar("xuhc", "windows-949");
173
174 // These aliases are present in modern versions of ICU, but use different codecs, and have no standard names.
175 // They are not present in ICU 3.2.
176 registrar("dos720", "cp864");
177 registrar("jis7", "ISO-2022-JP");
178 }
179
registerExtendedCodecs(TextCodecRegistrar registrar)180 void TextCodecICU::registerExtendedCodecs(TextCodecRegistrar registrar)
181 {
182 // See comment above in registerEncodingNames.
183 registrar("ISO-8859-8-I", newTextCodecICU, 0);
184
185 int32_t numEncodings = ucnv_countAvailable();
186 for (int32_t i = 0; i < numEncodings; ++i) {
187 const char* name = ucnv_getAvailableName(i);
188 UErrorCode error = U_ZERO_ERROR;
189 const char* standardName = ucnv_getStandardName(name, "MIME", &error);
190 if (!U_SUCCESS(error) || !standardName) {
191 error = U_ZERO_ERROR;
192 standardName = ucnv_getStandardName(name, "IANA", &error);
193 if (!U_SUCCESS(error) || !standardName)
194 continue;
195 }
196 registrar(standardName, newTextCodecICU, 0);
197 }
198 }
199
TextCodecICU(const TextEncoding & encoding)200 TextCodecICU::TextCodecICU(const TextEncoding& encoding)
201 : m_encoding(encoding)
202 , m_numBufferedBytes(0)
203 , m_converterICU(0)
204 , m_needsGBKFallbacks(false)
205 {
206 }
207
~TextCodecICU()208 TextCodecICU::~TextCodecICU()
209 {
210 releaseICUConverter();
211 }
212
releaseICUConverter() const213 void TextCodecICU::releaseICUConverter() const
214 {
215 if (m_converterICU) {
216 UConverter*& cachedConverter = cachedConverterICU();
217 if (cachedConverter)
218 ucnv_close(cachedConverter);
219 cachedConverter = m_converterICU;
220 m_converterICU = 0;
221 }
222 }
223
createICUConverter() const224 void TextCodecICU::createICUConverter() const
225 {
226 ASSERT(!m_converterICU);
227
228 const char* name = m_encoding.name();
229 m_needsGBKFallbacks = name[0] == 'G' && name[1] == 'B' && name[2] == 'K' && !name[3];
230
231 UErrorCode err;
232
233 UConverter*& cachedConverter = cachedConverterICU();
234 if (cachedConverter) {
235 err = U_ZERO_ERROR;
236 const char* cachedName = ucnv_getName(cachedConverter, &err);
237 if (U_SUCCESS(err) && m_encoding == cachedName) {
238 m_converterICU = cachedConverter;
239 cachedConverter = 0;
240 return;
241 }
242 }
243
244 err = U_ZERO_ERROR;
245 m_converterICU = ucnv_open(m_encoding.name(), &err);
246 #if !LOG_DISABLED
247 if (err == U_AMBIGUOUS_ALIAS_WARNING)
248 LOG_ERROR("ICU ambiguous alias warning for encoding: %s", m_encoding.name());
249 #endif
250 if (m_converterICU)
251 ucnv_setFallback(m_converterICU, TRUE);
252 }
253
decodeToBuffer(UChar * target,UChar * targetLimit,const char * & source,const char * sourceLimit,int32_t * offsets,bool flush,UErrorCode & err)254 int TextCodecICU::decodeToBuffer(UChar* target, UChar* targetLimit, const char*& source, const char* sourceLimit, int32_t* offsets, bool flush, UErrorCode& err)
255 {
256 UChar* targetStart = target;
257 err = U_ZERO_ERROR;
258 ucnv_toUnicode(m_converterICU, &target, targetLimit, &source, sourceLimit, offsets, flush, &err);
259 return target - targetStart;
260 }
261
262 class ErrorCallbackSetter {
263 public:
ErrorCallbackSetter(UConverter * converter,bool stopOnError)264 ErrorCallbackSetter(UConverter* converter, bool stopOnError)
265 : m_converter(converter)
266 , m_shouldStopOnEncodingErrors(stopOnError)
267 {
268 if (m_shouldStopOnEncodingErrors) {
269 UErrorCode err = U_ZERO_ERROR;
270 ucnv_setToUCallBack(m_converter, UCNV_TO_U_CALLBACK_SUBSTITUTE,
271 UCNV_SUB_STOP_ON_ILLEGAL, &m_savedAction,
272 &m_savedContext, &err);
273 ASSERT(err == U_ZERO_ERROR);
274 }
275 }
~ErrorCallbackSetter()276 ~ErrorCallbackSetter()
277 {
278 if (m_shouldStopOnEncodingErrors) {
279 UErrorCode err = U_ZERO_ERROR;
280 const void* oldContext;
281 UConverterToUCallback oldAction;
282 ucnv_setToUCallBack(m_converter, m_savedAction,
283 m_savedContext, &oldAction,
284 &oldContext, &err);
285 ASSERT(oldAction == UCNV_TO_U_CALLBACK_SUBSTITUTE);
286 ASSERT(!strcmp(static_cast<const char*>(oldContext), UCNV_SUB_STOP_ON_ILLEGAL));
287 ASSERT(err == U_ZERO_ERROR);
288 }
289 }
290 private:
291 UConverter* m_converter;
292 bool m_shouldStopOnEncodingErrors;
293 const void* m_savedContext;
294 UConverterToUCallback m_savedAction;
295 };
296
decode(const char * bytes,size_t length,bool flush,bool stopOnError,bool & sawError)297 String TextCodecICU::decode(const char* bytes, size_t length, bool flush, bool stopOnError, bool& sawError)
298 {
299 // Get a converter for the passed-in encoding.
300 if (!m_converterICU) {
301 createICUConverter();
302 ASSERT(m_converterICU);
303 if (!m_converterICU) {
304 LOG_ERROR("error creating ICU encoder even though encoding was in table");
305 return String();
306 }
307 }
308
309 ErrorCallbackSetter callbackSetter(m_converterICU, stopOnError);
310
311 Vector<UChar> result;
312
313 UChar buffer[ConversionBufferSize];
314 UChar* bufferLimit = buffer + ConversionBufferSize;
315 const char* source = reinterpret_cast<const char*>(bytes);
316 const char* sourceLimit = source + length;
317 int32_t* offsets = NULL;
318 UErrorCode err = U_ZERO_ERROR;
319
320 do {
321 int ucharsDecoded = decodeToBuffer(buffer, bufferLimit, source, sourceLimit, offsets, flush, err);
322 result.append(buffer, ucharsDecoded);
323 } while (err == U_BUFFER_OVERFLOW_ERROR);
324
325 if (U_FAILURE(err)) {
326 // flush the converter so it can be reused, and not be bothered by this error.
327 do {
328 decodeToBuffer(buffer, bufferLimit, source, sourceLimit, offsets, true, err);
329 } while (source < sourceLimit);
330 sawError = true;
331 }
332
333 String resultString = String::adopt(result);
334
335 // <http://bugs.webkit.org/show_bug.cgi?id=17014>
336 // Simplified Chinese pages use the code A3A0 to mean "full-width space", but ICU decodes it as U+E5E5.
337 if (m_encoding == "GBK" || m_encoding == "gb18030")
338 resultString.replace(0xE5E5, ideographicSpace);
339
340 return resultString;
341 }
342
343 // We need to apply these fallbacks ourselves as they are not currently supported by ICU and
344 // they were provided by the old TEC encoding path
345 // Needed to fix <rdar://problem/4708689>
getGbkEscape(UChar32 codePoint)346 static UChar getGbkEscape(UChar32 codePoint)
347 {
348 switch (codePoint) {
349 case 0x01F9:
350 return 0xE7C8;
351 case 0x1E3F:
352 return 0xE7C7;
353 case 0x22EF:
354 return 0x2026;
355 case 0x301C:
356 return 0xFF5E;
357 default:
358 return 0;
359 }
360 }
361
362 // Invalid character handler when writing escaped entities for unrepresentable
363 // characters. See the declaration of TextCodec::encode for more.
urlEscapedEntityCallback(const void * context,UConverterFromUnicodeArgs * fromUArgs,const UChar * codeUnits,int32_t length,UChar32 codePoint,UConverterCallbackReason reason,UErrorCode * err)364 static void urlEscapedEntityCallback(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
365 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
366 {
367 if (reason == UCNV_UNASSIGNED) {
368 *err = U_ZERO_ERROR;
369
370 UnencodableReplacementArray entity;
371 int entityLen = TextCodec::getUnencodableReplacement(codePoint, URLEncodedEntitiesForUnencodables, entity);
372 ucnv_cbFromUWriteBytes(fromUArgs, entity, entityLen, 0, err);
373 } else
374 UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
375 }
376
377 // Substitutes special GBK characters, escaping all other unassigned entities.
gbkCallbackEscape(const void * context,UConverterFromUnicodeArgs * fromUArgs,const UChar * codeUnits,int32_t length,UChar32 codePoint,UConverterCallbackReason reason,UErrorCode * err)378 static void gbkCallbackEscape(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
379 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
380 {
381 UChar outChar;
382 if (reason == UCNV_UNASSIGNED && (outChar = getGbkEscape(codePoint))) {
383 const UChar* source = &outChar;
384 *err = U_ZERO_ERROR;
385 ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
386 return;
387 }
388 UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
389 }
390
391 // Combines both gbkUrlEscapedEntityCallback and GBK character substitution.
gbkUrlEscapedEntityCallack(const void * context,UConverterFromUnicodeArgs * fromUArgs,const UChar * codeUnits,int32_t length,UChar32 codePoint,UConverterCallbackReason reason,UErrorCode * err)392 static void gbkUrlEscapedEntityCallack(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
393 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
394 {
395 if (reason == UCNV_UNASSIGNED) {
396 if (UChar outChar = getGbkEscape(codePoint)) {
397 const UChar* source = &outChar;
398 *err = U_ZERO_ERROR;
399 ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
400 return;
401 }
402 urlEscapedEntityCallback(context, fromUArgs, codeUnits, length, codePoint, reason, err);
403 return;
404 }
405 UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
406 }
407
gbkCallbackSubstitute(const void * context,UConverterFromUnicodeArgs * fromUArgs,const UChar * codeUnits,int32_t length,UChar32 codePoint,UConverterCallbackReason reason,UErrorCode * err)408 static void gbkCallbackSubstitute(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
409 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
410 {
411 UChar outChar;
412 if (reason == UCNV_UNASSIGNED && (outChar = getGbkEscape(codePoint))) {
413 const UChar* source = &outChar;
414 *err = U_ZERO_ERROR;
415 ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
416 return;
417 }
418 UCNV_FROM_U_CALLBACK_SUBSTITUTE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
419 }
420
encode(const UChar * characters,size_t length,UnencodableHandling handling)421 CString TextCodecICU::encode(const UChar* characters, size_t length, UnencodableHandling handling)
422 {
423 if (!length)
424 return "";
425
426 if (!m_converterICU)
427 createICUConverter();
428 if (!m_converterICU)
429 return CString();
430
431 // FIXME: We should see if there is "force ASCII range" mode in ICU;
432 // until then, we change the backslash into a yen sign.
433 // Encoding will change the yen sign back into a backslash.
434 String copy(characters, length);
435 copy = m_encoding.displayString(copy.impl());
436
437 const UChar* source = copy.characters();
438 const UChar* sourceLimit = source + copy.length();
439
440 UErrorCode err = U_ZERO_ERROR;
441
442 switch (handling) {
443 case QuestionMarksForUnencodables:
444 ucnv_setSubstChars(m_converterICU, "?", 1, &err);
445 ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkCallbackSubstitute : UCNV_FROM_U_CALLBACK_SUBSTITUTE, 0, 0, 0, &err);
446 break;
447 case EntitiesForUnencodables:
448 ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkCallbackEscape : UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_XML_DEC, 0, 0, &err);
449 break;
450 case URLEncodedEntitiesForUnencodables:
451 ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkUrlEscapedEntityCallack : urlEscapedEntityCallback, 0, 0, 0, &err);
452 break;
453 }
454
455 ASSERT(U_SUCCESS(err));
456 if (U_FAILURE(err))
457 return CString();
458
459 Vector<char> result;
460 size_t size = 0;
461 do {
462 char buffer[ConversionBufferSize];
463 char* target = buffer;
464 char* targetLimit = target + ConversionBufferSize;
465 err = U_ZERO_ERROR;
466 ucnv_fromUnicode(m_converterICU, &target, targetLimit, &source, sourceLimit, 0, true, &err);
467 size_t count = target - buffer;
468 result.grow(size + count);
469 memcpy(result.data() + size, buffer, count);
470 size += count;
471 } while (err == U_BUFFER_OVERFLOW_ERROR);
472
473 return CString(result.data(), size);
474 }
475
476
477 } // namespace WebCore
478