2 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "internal/cryptlib.h"
12 #include "internal/unicode.h"
13 #include <openssl/asn1.h>
18 * This parses a UTF8 string one character at a time. It is passed a pointer
19 * to the string and the length of the string. It sets 'value' to the value of
20 * the current character. It returns the number of characters read or a
21 * negative error code:
22 * -1 = string too short
23 * -2 = illegal character
24 * -3 = subsequent characters not of the form 10xxxxxx
25 * -4 = character encoded incorrectly (not minimal length).
28 int UTF8_getc(const unsigned char *str, int len, unsigned long *val)
30 const unsigned char *p;
37 /* Check syntax and work out the encoded value (if correct) */
38 if ((*p & 0x80) == 0) {
41 } else if ((*p & 0xe0) == 0xc0) {
44 if ((p[1] & 0xc0) != 0x80)
46 value = (*p++ & 0x1f) << 6;
51 } else if ((*p & 0xf0) == 0xe0) {
54 if (((p[1] & 0xc0) != 0x80)
55 || ((p[2] & 0xc0) != 0x80))
57 value = (*p++ & 0xf) << 12;
58 value |= (*p++ & 0x3f) << 6;
62 if (is_unicode_surrogate(value))
65 } else if ((*p & 0xf8) == 0xf0) {
68 if (((p[1] & 0xc0) != 0x80)
69 || ((p[2] & 0xc0) != 0x80)
70 || ((p[3] & 0xc0) != 0x80))
72 value = ((unsigned long)(*p++ & 0x7)) << 18;
73 value |= (*p++ & 0x3f) << 12;
74 value |= (*p++ & 0x3f) << 6;
86 * This takes a character 'value' and writes the UTF8 encoded value in 'str'
87 * where 'str' is a buffer containing 'len' characters. Returns the number of
88 * characters written, -1 if 'len' is too small or -2 if 'value' is out of
89 * range. 'str' can be set to NULL in which case it just returns the number of
90 * characters. It will need at most 4 characters.
93 int UTF8_putc(unsigned char *str, int len, unsigned long value)
96 len = 4; /* Maximum we will need */
101 *str = (unsigned char)value;
108 *str++ = (unsigned char)(((value >> 6) & 0x1f) | 0xc0);
109 *str = (unsigned char)((value & 0x3f) | 0x80);
113 if (value < 0x10000) {
114 if (is_unicode_surrogate(value))
119 *str++ = (unsigned char)(((value >> 12) & 0xf) | 0xe0);
120 *str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
121 *str = (unsigned char)((value & 0x3f) | 0x80);
125 if (value < UNICODE_LIMIT) {
129 *str++ = (unsigned char)(((value >> 18) & 0x7) | 0xf0);
130 *str++ = (unsigned char)(((value >> 12) & 0x3f) | 0x80);
131 *str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
132 *str = (unsigned char)((value & 0x3f) | 0x80);