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