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("x-uhc", "windows-949");
151 registrar("shift-jis", "Shift_JIS");
152
153 // These aliases are present in modern versions of ICU, but use different codecs, and have no standard names.
154 // They are not present in ICU 3.2.
155 registrar("dos-720", "cp864");
156 registrar("jis7", "ISO-2022-JP");
157
158 // Alternative spelling of ISO encoding names.
159 registrar("ISO8859-1", "ISO-8859-1");
160 registrar("ISO8859-2", "ISO-8859-2");
161 registrar("ISO8859-3", "ISO-8859-3");
162 registrar("ISO8859-4", "ISO-8859-4");
163 registrar("ISO8859-5", "ISO-8859-5");
164 registrar("ISO8859-6", "ISO-8859-6");
165 registrar("ISO8859-7", "ISO-8859-7");
166 registrar("ISO8859-8", "ISO-8859-8");
167 registrar("ISO8859-8-I", "ISO-8859-8-I");
168 registrar("ISO8859-9", "ISO-8859-9");
169 registrar("ISO8859-10", "ISO-8859-10");
170 registrar("ISO8859-13", "ISO-8859-13");
171 registrar("ISO8859-14", "ISO-8859-14");
172 registrar("ISO8859-15", "ISO-8859-15");
173 // Not registering ISO8859-16, because Firefox (as of version 3.6.6) doesn't know this particular alias,
174 // and because older versions of ICU don't support ISO-8859-16 encoding at all.
175 }
176
registerCodecs(TextCodecRegistrar registrar)177 void TextCodecICU::registerCodecs(TextCodecRegistrar registrar)
178 {
179 // See comment above in registerEncodingNames.
180 registrar("ISO-8859-8-I", create, 0);
181
182 int32_t numEncodings = ucnv_countAvailable();
183 for (int32_t i = 0; i < numEncodings; ++i) {
184 const char* name = ucnv_getAvailableName(i);
185 UErrorCode error = U_ZERO_ERROR;
186 const char* standardName = ucnv_getStandardName(name, "MIME", &error);
187 if (!U_SUCCESS(error) || !standardName) {
188 error = U_ZERO_ERROR;
189 standardName = ucnv_getStandardName(name, "IANA", &error);
190 if (!U_SUCCESS(error) || !standardName)
191 continue;
192 }
193 registrar(standardName, create, 0);
194 }
195 }
196
TextCodecICU(const TextEncoding & encoding)197 TextCodecICU::TextCodecICU(const TextEncoding& encoding)
198 : m_encoding(encoding)
199 , m_numBufferedBytes(0)
200 , m_converterICU(0)
201 , m_needsGBKFallbacks(false)
202 {
203 }
204
~TextCodecICU()205 TextCodecICU::~TextCodecICU()
206 {
207 releaseICUConverter();
208 }
209
releaseICUConverter() const210 void TextCodecICU::releaseICUConverter() const
211 {
212 if (m_converterICU) {
213 UConverter*& cachedConverter = cachedConverterICU();
214 if (cachedConverter)
215 ucnv_close(cachedConverter);
216 cachedConverter = m_converterICU;
217 m_converterICU = 0;
218 }
219 }
220
createICUConverter() const221 void TextCodecICU::createICUConverter() const
222 {
223 ASSERT(!m_converterICU);
224
225 const char* name = m_encoding.name();
226 m_needsGBKFallbacks = name[0] == 'G' && name[1] == 'B' && name[2] == 'K' && !name[3];
227
228 UErrorCode err;
229
230 UConverter*& cachedConverter = cachedConverterICU();
231 if (cachedConverter) {
232 err = U_ZERO_ERROR;
233 const char* cachedName = ucnv_getName(cachedConverter, &err);
234 if (U_SUCCESS(err) && m_encoding == cachedName) {
235 m_converterICU = cachedConverter;
236 cachedConverter = 0;
237 return;
238 }
239 }
240
241 err = U_ZERO_ERROR;
242 m_converterICU = ucnv_open(m_encoding.name(), &err);
243 #if !LOG_DISABLED
244 if (err == U_AMBIGUOUS_ALIAS_WARNING)
245 LOG_ERROR("ICU ambiguous alias warning for encoding: %s", m_encoding.name());
246 #endif
247 if (m_converterICU)
248 ucnv_setFallback(m_converterICU, TRUE);
249 }
250
decodeToBuffer(UChar * target,UChar * targetLimit,const char * & source,const char * sourceLimit,int32_t * offsets,bool flush,UErrorCode & err)251 int TextCodecICU::decodeToBuffer(UChar* target, UChar* targetLimit, const char*& source, const char* sourceLimit, int32_t* offsets, bool flush, UErrorCode& err)
252 {
253 UChar* targetStart = target;
254 err = U_ZERO_ERROR;
255 ucnv_toUnicode(m_converterICU, &target, targetLimit, &source, sourceLimit, offsets, flush, &err);
256 return target - targetStart;
257 }
258
259 class ErrorCallbackSetter {
260 public:
ErrorCallbackSetter(UConverter * converter,bool stopOnError)261 ErrorCallbackSetter(UConverter* converter, bool stopOnError)
262 : m_converter(converter)
263 , m_shouldStopOnEncodingErrors(stopOnError)
264 {
265 if (m_shouldStopOnEncodingErrors) {
266 UErrorCode err = U_ZERO_ERROR;
267 ucnv_setToUCallBack(m_converter, UCNV_TO_U_CALLBACK_SUBSTITUTE,
268 UCNV_SUB_STOP_ON_ILLEGAL, &m_savedAction,
269 &m_savedContext, &err);
270 ASSERT(err == U_ZERO_ERROR);
271 }
272 }
~ErrorCallbackSetter()273 ~ErrorCallbackSetter()
274 {
275 if (m_shouldStopOnEncodingErrors) {
276 UErrorCode err = U_ZERO_ERROR;
277 const void* oldContext;
278 UConverterToUCallback oldAction;
279 ucnv_setToUCallBack(m_converter, m_savedAction,
280 m_savedContext, &oldAction,
281 &oldContext, &err);
282 ASSERT(oldAction == UCNV_TO_U_CALLBACK_SUBSTITUTE);
283 ASSERT(!strcmp(static_cast<const char*>(oldContext), UCNV_SUB_STOP_ON_ILLEGAL));
284 ASSERT(err == U_ZERO_ERROR);
285 }
286 }
287
288 private:
289 UConverter* m_converter;
290 bool m_shouldStopOnEncodingErrors;
291 const void* m_savedContext;
292 UConverterToUCallback m_savedAction;
293 };
294
decode(const char * bytes,size_t length,bool flush,bool stopOnError,bool & sawError)295 String TextCodecICU::decode(const char* bytes, size_t length, bool flush, bool stopOnError, bool& sawError)
296 {
297 // Get a converter for the passed-in encoding.
298 if (!m_converterICU) {
299 createICUConverter();
300 ASSERT(m_converterICU);
301 if (!m_converterICU) {
302 LOG_ERROR("error creating ICU encoder even though encoding was in table");
303 return String();
304 }
305 }
306
307 ErrorCallbackSetter callbackSetter(m_converterICU, stopOnError);
308
309 Vector<UChar> result;
310
311 UChar buffer[ConversionBufferSize];
312 UChar* bufferLimit = buffer + ConversionBufferSize;
313 const char* source = reinterpret_cast<const char*>(bytes);
314 const char* sourceLimit = source + length;
315 int32_t* offsets = NULL;
316 UErrorCode err = U_ZERO_ERROR;
317
318 do {
319 int ucharsDecoded = decodeToBuffer(buffer, bufferLimit, source, sourceLimit, offsets, flush, err);
320 result.append(buffer, ucharsDecoded);
321 } while (err == U_BUFFER_OVERFLOW_ERROR);
322
323 if (U_FAILURE(err)) {
324 // flush the converter so it can be reused, and not be bothered by this error.
325 do {
326 decodeToBuffer(buffer, bufferLimit, source, sourceLimit, offsets, true, err);
327 } while (source < sourceLimit);
328 sawError = true;
329 }
330
331 String resultString = String::adopt(result);
332
333 // <http://bugs.webkit.org/show_bug.cgi?id=17014>
334 // Simplified Chinese pages use the code A3A0 to mean "full-width space", but ICU decodes it as U+E5E5.
335 if (strcmp(m_encoding.name(), "GBK") == 0 || strcasecmp(m_encoding.name(), "gb18030") == 0)
336 resultString.replace(0xE5E5, ideographicSpace);
337
338 return resultString;
339 }
340
341 // We need to apply these fallbacks ourselves as they are not currently supported by ICU and
342 // they were provided by the old TEC encoding path. Needed to fix <rdar://problem/4708689>.
fallbackForGBK(UChar32 character)343 static UChar fallbackForGBK(UChar32 character)
344 {
345 switch (character) {
346 case 0x01F9:
347 return 0xE7C8;
348 case 0x1E3F:
349 return 0xE7C7;
350 case 0x22EF:
351 return 0x2026;
352 case 0x301C:
353 return 0xFF5E;
354 }
355 return 0;
356 }
357
358 // Invalid character handler when writing escaped entities for unrepresentable
359 // 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)360 static void urlEscapedEntityCallback(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
361 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
362 {
363 if (reason == UCNV_UNASSIGNED) {
364 *err = U_ZERO_ERROR;
365
366 UnencodableReplacementArray entity;
367 int entityLen = TextCodec::getUnencodableReplacement(codePoint, URLEncodedEntitiesForUnencodables, entity);
368 ucnv_cbFromUWriteBytes(fromUArgs, entity, entityLen, 0, err);
369 } else
370 UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
371 }
372
373 // 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)374 static void gbkCallbackEscape(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
375 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
376 {
377 UChar outChar;
378 if (reason == UCNV_UNASSIGNED && (outChar = fallbackForGBK(codePoint))) {
379 const UChar* source = &outChar;
380 *err = U_ZERO_ERROR;
381 ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
382 return;
383 }
384 UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
385 }
386
387 // 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)388 static void gbkUrlEscapedEntityCallack(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
389 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
390 {
391 if (reason == UCNV_UNASSIGNED) {
392 if (UChar outChar = fallbackForGBK(codePoint)) {
393 const UChar* source = &outChar;
394 *err = U_ZERO_ERROR;
395 ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
396 return;
397 }
398 urlEscapedEntityCallback(context, fromUArgs, codeUnits, length, codePoint, reason, err);
399 return;
400 }
401 UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
402 }
403
gbkCallbackSubstitute(const void * context,UConverterFromUnicodeArgs * fromUArgs,const UChar * codeUnits,int32_t length,UChar32 codePoint,UConverterCallbackReason reason,UErrorCode * err)404 static void gbkCallbackSubstitute(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
405 UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
406 {
407 UChar outChar;
408 if (reason == UCNV_UNASSIGNED && (outChar = fallbackForGBK(codePoint))) {
409 const UChar* source = &outChar;
410 *err = U_ZERO_ERROR;
411 ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
412 return;
413 }
414 UCNV_FROM_U_CALLBACK_SUBSTITUTE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
415 }
416
encode(const UChar * characters,size_t length,UnencodableHandling handling)417 CString TextCodecICU::encode(const UChar* characters, size_t length, UnencodableHandling handling)
418 {
419 if (!length)
420 return "";
421
422 if (!m_converterICU)
423 createICUConverter();
424 if (!m_converterICU)
425 return CString();
426
427 // FIXME: We should see if there is "force ASCII range" mode in ICU;
428 // until then, we change the backslash into a yen sign.
429 // Encoding will change the yen sign back into a backslash.
430 String copy(characters, length);
431 copy = m_encoding.displayString(copy.impl());
432
433 const UChar* source = copy.characters();
434 const UChar* sourceLimit = source + copy.length();
435
436 UErrorCode err = U_ZERO_ERROR;
437
438 switch (handling) {
439 case QuestionMarksForUnencodables:
440 ucnv_setSubstChars(m_converterICU, "?", 1, &err);
441 ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkCallbackSubstitute : UCNV_FROM_U_CALLBACK_SUBSTITUTE, 0, 0, 0, &err);
442 break;
443 case EntitiesForUnencodables:
444 ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkCallbackEscape : UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_XML_DEC, 0, 0, &err);
445 break;
446 case URLEncodedEntitiesForUnencodables:
447 ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkUrlEscapedEntityCallack : urlEscapedEntityCallback, 0, 0, 0, &err);
448 break;
449 }
450
451 ASSERT(U_SUCCESS(err));
452 if (U_FAILURE(err))
453 return CString();
454
455 Vector<char> result;
456 size_t size = 0;
457 do {
458 char buffer[ConversionBufferSize];
459 char* target = buffer;
460 char* targetLimit = target + ConversionBufferSize;
461 err = U_ZERO_ERROR;
462 ucnv_fromUnicode(m_converterICU, &target, targetLimit, &source, sourceLimit, 0, true, &err);
463 size_t count = target - buffer;
464 result.grow(size + count);
465 memcpy(result.data() + size, buffer, count);
466 size += count;
467 } while (err == U_BUFFER_OVERFLOW_ERROR);
468
469 return CString(result.data(), size);
470 }
471
472 } // namespace WebCore
473