• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "ErrorCode.h"
20 #include "JNIHelp.h"
21 #include "JniConstants.h"
22 #include "ScopedJavaUnicodeString.h"
23 #include "unicode/uidna.h"
24 
isLabelSeparator(const UChar ch)25 static bool isLabelSeparator(const UChar ch) {
26     switch (ch) {
27     case 0x3002: // ideographic full stop
28     case 0xff0e: // fullwidth full stop
29     case 0xff61: // halfwidth ideographic full stop
30         return true;
31     default:
32         return false;
33     }
34 }
35 
NativeIDN_convertImpl(JNIEnv * env,jclass,jstring s,jint flags,jboolean toAscii)36 static jstring NativeIDN_convertImpl(JNIEnv* env, jclass, jstring s, jint flags, jboolean toAscii) {
37     ScopedJavaUnicodeString sus(env, s);
38     const UChar* src = sus.unicodeString().getBuffer();
39     const size_t srcLength = sus.unicodeString().length();
40     UChar dst[256];
41     UErrorCode status = U_ZERO_ERROR;
42     size_t resultLength = toAscii
43             ? uidna_IDNToASCII(src, srcLength, &dst[0], sizeof(dst), flags, NULL, &status)
44             : uidna_IDNToUnicode(src, srcLength, &dst[0], sizeof(dst), flags, NULL, &status);
45     if (U_FAILURE(status)) {
46         jniThrowException(env, "java/lang/IllegalArgumentException", u_errorName(status));
47         return NULL;
48     }
49     if (!toAscii) {
50         // ICU only translates separators to ASCII for toASCII.
51         // Java expects the translation for toUnicode too.
52         // We may as well do this here, while the string is still mutable.
53         for (size_t i = 0; i < resultLength; ++i) {
54             if (isLabelSeparator(dst[i])) {
55                 dst[i] = '.';
56             }
57         }
58     }
59     return env->NewString(&dst[0], resultLength);
60 }
61 
62 static JNINativeMethod gMethods[] = {
63     NATIVE_METHOD(NativeIDN, convertImpl, "(Ljava/lang/String;IZ)Ljava/lang/String;"),
64 };
register_libcore_icu_NativeIDN(JNIEnv * env)65 int register_libcore_icu_NativeIDN(JNIEnv* env) {
66     return jniRegisterNativeMethods(env, "libcore/icu/NativeIDN", gMethods, NELEM(gMethods));
67 }
68