1 /*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "NativeIDN"
18
19 #include "JNIHelp.h"
20 #include "JniConstants.h"
21 #include "ScopedStringChars.h"
22 #include "unicode/uidna.h"
23
isLabelSeparator(const UChar ch)24 static bool isLabelSeparator(const UChar ch) {
25 switch (ch) {
26 case 0x3002: // ideographic full stop
27 case 0xff0e: // fullwidth full stop
28 case 0xff61: // halfwidth ideographic full stop
29 return true;
30 default:
31 return false;
32 }
33 }
34
NativeIDN_convertImpl(JNIEnv * env,jclass,jstring javaSrc,jint flags,jboolean toAscii)35 static jstring NativeIDN_convertImpl(JNIEnv* env, jclass, jstring javaSrc, jint flags, jboolean toAscii) {
36 ScopedStringChars src(env, javaSrc);
37 if (src.get() == NULL) {
38 return NULL;
39 }
40 UChar dst[256];
41 UErrorCode status = U_ZERO_ERROR;
42
43 // We're stuck implementing IDNA-2003 for now since that's what we specify.
44 //
45 // TODO: Change our spec to IDNA-2008 + UTS-46 compatibility processing if
46 // it's safe enough.
47 #pragma GCC diagnostic push
48 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
49 size_t resultLength = toAscii
50 ? uidna_IDNToASCII(src.get(), src.size(), &dst[0], sizeof(dst), flags, NULL, &status)
51 : uidna_IDNToUnicode(src.get(), src.size(), &dst[0], sizeof(dst), flags, NULL, &status);
52 #pragma GCC diagnostic pop
53
54 if (U_FAILURE(status)) {
55 jniThrowException(env, "java/lang/IllegalArgumentException", u_errorName(status));
56 return NULL;
57 }
58 if (!toAscii) {
59 // ICU only translates separators to ASCII for toASCII.
60 // Java expects the translation for toUnicode too.
61 // We may as well do this here, while the string is still mutable.
62 for (size_t i = 0; i < resultLength; ++i) {
63 if (isLabelSeparator(dst[i])) {
64 dst[i] = '.';
65 }
66 }
67 }
68 return env->NewString(&dst[0], resultLength);
69 }
70
71 static JNINativeMethod gMethods[] = {
72 NATIVE_METHOD(NativeIDN, convertImpl, "(Ljava/lang/String;IZ)Ljava/lang/String;"),
73 };
register_libcore_icu_NativeIDN(JNIEnv * env)74 void register_libcore_icu_NativeIDN(JNIEnv* env) {
75 jniRegisterNativeMethods(env, "libcore/icu/NativeIDN", gMethods, NELEM(gMethods));
76 }
77