Coverage Report

Created: 2026-07-12 14:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/common/format_ip.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/formatIPv6.h
19
// and modified by Doris
20
21
#pragma once
22
23
#include <algorithm>
24
#include <array>
25
#include <bit>
26
#include <cstdint>
27
#include <cstring>
28
#include <utility>
29
30
#include "core/types.h"
31
#include "exec/common/hex.h"
32
#include "exec/common/string_utils/string_utils.h"
33
34
constexpr size_t IPV4_BINARY_LENGTH = 4;
35
constexpr size_t IPV4_MAX_TEXT_LENGTH = 15; /// Does not count tail zero byte.
36
constexpr size_t IPV6_MAX_TEXT_LENGTH = 39;
37
constexpr size_t IPV4_MIN_NUM_VALUE = 0;          //num value of '0.0.0.0'
38
constexpr size_t IPV4_MAX_NUM_VALUE = 4294967295; //num value of '255.255.255.255'
39
constexpr int IPV4_MAX_OCTET_VALUE = 255;         //max value of octet
40
constexpr size_t IPV4_OCTET_BITS = 8;
41
constexpr size_t DECIMAL_BASE = 10;
42
constexpr size_t IPV6_BINARY_LENGTH = 16;
43
44
namespace doris {
45
46
extern const std::array<std::pair<const char*, size_t>, 256> one_byte_to_string_lookup_table;
47
48
/** Format 4-byte binary sequesnce as IPv4 text: 'aaa.bbb.ccc.ddd',
49
  * expects in out to be in BE-format, that is 0x7f000001 => "127.0.0.1".
50
  *
51
  * Any number of the tail bytes can be masked with given mask string.
52
  *
53
  * Assumptions:
54
  *     src is IPV4_BINARY_LENGTH long,
55
  *     dst is IPV4_MAX_TEXT_LENGTH long,
56
  *     mask_tail_octets <= IPV4_BINARY_LENGTH
57
  *     mask_string is NON-NULL, if mask_tail_octets > 0.
58
  *
59
  * Examples:
60
  *     format_ipv4(&0x7f000001, dst, mask_tail_octets = 0, nullptr);
61
  *         > dst == "127.0.0.1"
62
  *     format_ipv4(&0x7f000001, dst, mask_tail_octets = 1, "xxx");
63
  *         > dst == "127.0.0.xxx"
64
  *     format_ipv4(&0x7f000001, dst, mask_tail_octets = 1, "0");
65
  *         > dst == "127.0.0.0"
66
  */
67
inline void format_ipv4(const unsigned char* src, size_t src_size, char*& dst,
68
2.99M
                        uint8_t mask_tail_octets = 0, const char* mask_string = "xxx") {
69
2.99M
    const size_t mask_length = mask_string ? strlen(mask_string) : 0;
70
2.99M
    const size_t limit = std::min(IPV4_BINARY_LENGTH, IPV4_BINARY_LENGTH - mask_tail_octets);
71
2.99M
    const size_t padding = std::min(4 - src_size, limit);
72
2.99M
    for (size_t octet = 0; octet < padding; ++octet) {
73
0
        *dst++ = '0';
74
0
        *dst++ = '.';
75
0
    }
76
77
14.9M
    for (size_t octet = 4 - src_size; octet < limit; ++octet) {
78
11.9M
        uint8_t value = 0;
79
        if constexpr (std::endian::native == std::endian::little)
80
11.9M
            value = static_cast<uint8_t>(src[IPV4_BINARY_LENGTH - octet - 1]);
81
        else
82
            value = static_cast<uint8_t>(src[octet]);
83
11.9M
        const uint8_t len = static_cast<uint8_t>(one_byte_to_string_lookup_table[value].second);
84
11.9M
        const char* str = one_byte_to_string_lookup_table[value].first;
85
86
11.9M
        memcpy(dst, str, len);
87
11.9M
        dst += len;
88
89
11.9M
        *dst++ = '.';
90
11.9M
    }
91
92
2.99M
    for (size_t mask = 0; mask < mask_tail_octets; ++mask) {
93
12
        memcpy(dst, mask_string, mask_length);
94
12
        dst += mask_length;
95
96
12
        *dst++ = '.';
97
12
    }
98
99
2.99M
    dst--;
100
2.99M
}
101
102
inline void format_ipv4(const unsigned char* src, char*& dst, uint8_t mask_tail_octets = 0,
103
2.99M
                        const char* mask_string = "xxx") {
104
2.99M
    format_ipv4(src, 4, dst, mask_tail_octets, mask_string);
105
2.99M
}
106
107
/** Unsafe (no bounds-checking for src nor dst), optimized version of parsing IPv4 string.
108
 *
109
 * Parses the input string `src` and stores binary host-endian value into buffer pointed by `dst`,
110
 * which should be long enough.
111
 * That is "127.0.0.1" becomes 0x7f000001.
112
 *
113
 * In case of failure doesn't modify buffer pointed by `dst`.
114
 *
115
 * WARNING - this function is adapted to work with ReadBuffer, where src is the position reference (ReadBuffer::position())
116
 *           and eof is the ReadBuffer::eof() - therefore algorithm below does not rely on buffer's continuity.
117
 *           To parse strings use overloads below.
118
 *
119
 * @param src         - iterator (reference to pointer) over input string - warning - continuity is not guaranteed.
120
 * @param eof         - function returning true if iterator riched the end - warning - can break iterator's continuity.
121
 * @param dst         - where to put output bytes, expected to be non-null and at IPV4_BINARY_LENGTH-long.
122
 * @param first_octet - preparsed first octet
123
 * @return            - true if parsed successfully, false otherwise.
124
 */
125
template <typename T, typename EOFfunction>
126
    requires(std::is_same<typename std::remove_cv<T>::type, char>::value)
127
169k
inline bool parse_ipv4(T*& src, EOFfunction eof, unsigned char* dst, int32_t first_octet = -1) {
128
169k
    if (src == nullptr || first_octet > IPV4_MAX_OCTET_VALUE) {
129
0
        return false;
130
0
    }
131
132
169k
    UInt32 result = 0;
133
169k
    int offset = (IPV4_BINARY_LENGTH - 1) * IPV4_OCTET_BITS;
134
169k
    if (first_octet >= 0) {
135
156
        result |= first_octet << offset;
136
156
        offset -= IPV4_OCTET_BITS;
137
156
    }
138
139
668k
    for (; true; offset -= IPV4_OCTET_BITS, ++src) {
140
668k
        if (eof()) {
141
122
            return false;
142
122
        }
143
144
668k
        UInt32 value = 0;
145
668k
        size_t len = 0;
146
1.67M
        while (is_numeric_ascii(*src) && len <= 3) {
147
1.16M
            value = value * DECIMAL_BASE + (*src - '0');
148
1.16M
            ++len;
149
1.16M
            ++src;
150
1.16M
            if (eof()) {
151
165k
                break;
152
165k
            }
153
1.16M
        }
154
668k
        if (len == 0 || value > IPV4_MAX_OCTET_VALUE || (offset > 0 && (eof() || *src != '.'))) {
155
3.07k
            return false;
156
3.07k
        }
157
665k
        result |= value << offset;
158
159
665k
        if (offset == 0) {
160
166k
            break;
161
166k
        }
162
665k
    }
163
164
166k
    memcpy(dst, &result, sizeof(result));
165
166k
    return true;
166
169k
}
_ZN5doris10parse_ipv4IKcZNS_10parse_ipv4EPS1_S2_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_i
Line
Count
Source
127
169k
inline bool parse_ipv4(T*& src, EOFfunction eof, unsigned char* dst, int32_t first_octet = -1) {
128
169k
    if (src == nullptr || first_octet > IPV4_MAX_OCTET_VALUE) {
129
0
        return false;
130
0
    }
131
132
169k
    UInt32 result = 0;
133
169k
    int offset = (IPV4_BINARY_LENGTH - 1) * IPV4_OCTET_BITS;
134
169k
    if (first_octet >= 0) {
135
0
        result |= first_octet << offset;
136
0
        offset -= IPV4_OCTET_BITS;
137
0
    }
138
139
667k
    for (; true; offset -= IPV4_OCTET_BITS, ++src) {
140
667k
        if (eof()) {
141
122
            return false;
142
122
        }
143
144
667k
        UInt32 value = 0;
145
667k
        size_t len = 0;
146
1.67M
        while (is_numeric_ascii(*src) && len <= 3) {
147
1.16M
            value = value * DECIMAL_BASE + (*src - '0');
148
1.16M
            ++len;
149
1.16M
            ++src;
150
1.16M
            if (eof()) {
151
165k
                break;
152
165k
            }
153
1.16M
        }
154
667k
        if (len == 0 || value > IPV4_MAX_OCTET_VALUE || (offset > 0 && (eof() || *src != '.'))) {
155
3.06k
            return false;
156
3.06k
        }
157
664k
        result |= value << offset;
158
159
664k
        if (offset == 0) {
160
165k
            break;
161
165k
        }
162
664k
    }
163
164
165k
    memcpy(dst, &result, sizeof(result));
165
165k
    return true;
166
169k
}
_ZN5doris10parse_ipv4IKcZNS_10parse_ipv4EPS1_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_i
Line
Count
Source
127
2
inline bool parse_ipv4(T*& src, EOFfunction eof, unsigned char* dst, int32_t first_octet = -1) {
128
2
    if (src == nullptr || first_octet > IPV4_MAX_OCTET_VALUE) {
129
0
        return false;
130
0
    }
131
132
2
    UInt32 result = 0;
133
2
    int offset = (IPV4_BINARY_LENGTH - 1) * IPV4_OCTET_BITS;
134
2
    if (first_octet >= 0) {
135
0
        result |= first_octet << offset;
136
0
        offset -= IPV4_OCTET_BITS;
137
0
    }
138
139
8
    for (; true; offset -= IPV4_OCTET_BITS, ++src) {
140
8
        if (eof()) {
141
0
            return false;
142
0
        }
143
144
8
        UInt32 value = 0;
145
8
        size_t len = 0;
146
20
        while (is_numeric_ascii(*src) && len <= 3) {
147
12
            value = value * DECIMAL_BASE + (*src - '0');
148
12
            ++len;
149
12
            ++src;
150
12
            if (eof()) {
151
0
                break;
152
0
            }
153
12
        }
154
8
        if (len == 0 || value > IPV4_MAX_OCTET_VALUE || (offset > 0 && (eof() || *src != '.'))) {
155
0
            return false;
156
0
        }
157
8
        result |= value << offset;
158
159
8
        if (offset == 0) {
160
2
            break;
161
2
        }
162
8
    }
163
164
2
    memcpy(dst, &result, sizeof(result));
165
2
    return true;
166
2
}
_ZN5doris10parse_ipv4IKcZNS_10parse_ipv6EPS1_S2_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_i
Line
Count
Source
127
156
inline bool parse_ipv4(T*& src, EOFfunction eof, unsigned char* dst, int32_t first_octet = -1) {
128
156
    if (src == nullptr || first_octet > IPV4_MAX_OCTET_VALUE) {
129
0
        return false;
130
0
    }
131
132
156
    UInt32 result = 0;
133
156
    int offset = (IPV4_BINARY_LENGTH - 1) * IPV4_OCTET_BITS;
134
156
    if (first_octet >= 0) {
135
156
        result |= first_octet << offset;
136
156
        offset -= IPV4_OCTET_BITS;
137
156
    }
138
139
466
    for (; true; offset -= IPV4_OCTET_BITS, ++src) {
140
466
        if (eof()) {
141
0
            return false;
142
0
        }
143
144
466
        UInt32 value = 0;
145
466
        size_t len = 0;
146
1.31k
        while (is_numeric_ascii(*src) && len <= 3) {
147
1.00k
            value = value * DECIMAL_BASE + (*src - '0');
148
1.00k
            ++len;
149
1.00k
            ++src;
150
1.00k
            if (eof()) {
151
154
                break;
152
154
            }
153
1.00k
        }
154
466
        if (len == 0 || value > IPV4_MAX_OCTET_VALUE || (offset > 0 && (eof() || *src != '.'))) {
155
4
            return false;
156
4
        }
157
462
        result |= value << offset;
158
159
462
        if (offset == 0) {
160
152
            break;
161
152
        }
162
462
    }
163
164
152
    memcpy(dst, &result, sizeof(result));
165
152
    return true;
166
156
}
Unexecuted instantiation: _ZN5doris10parse_ipv4IKcZNS_10parse_ipv6EPS1_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_i
167
168
/// returns pointer to the right after parsed sequence or null on failed parsing
169
169k
inline const char* parse_ipv4(const char* src, const char* end, unsigned char* dst) {
170
169k
    if (parse_ipv4(
171
2.33M
                src, [&src, end]() { return src == end; }, dst)) {
172
165k
        return src;
173
165k
    }
174
3.19k
    return nullptr;
175
169k
}
176
177
/// returns true if whole buffer was parsed successfully
178
169k
inline bool parse_ipv4_whole(const char* src, const char* end, unsigned char* dst) {
179
169k
    return parse_ipv4(src, end, dst) == end;
180
169k
}
181
182
/// returns pointer to the right after parsed sequence or null on failed parsing
183
2
inline const char* parse_ipv4(const char* src, unsigned char* dst) {
184
2
    if (parse_ipv4(
185
2
                src, []() { return false; }, dst)) {
186
2
        return src;
187
2
    }
188
0
    return nullptr;
189
2
}
190
191
/// returns true if whole null-terminated string was parsed successfully
192
2
inline bool parse_ipv4_whole(const char* src, unsigned char* dst) {
193
2
    const char* end = parse_ipv4(src, dst);
194
2
    return end != nullptr && *end == '\0';
195
2
}
196
197
/// integer logarithm, return ceil(log(value, base)) (the smallest integer greater or equal than log(value, base)
198
0
inline constexpr UInt32 int_log(const UInt32 value, const UInt32 base, const bool carry) {
199
0
    return value >= base ? 1 + int_log(value / base, base, value % base || carry)
200
0
                         : value % base > 1 || carry;
201
0
}
202
203
/// Print integer in desired base, faster than sprintf.
204
/// NOTE This is not the best way. See https://github.com/miloyip/itoa-benchmark
205
/// But it doesn't matter here.
206
template <UInt32 base, typename T>
207
198k
inline void print_integer(char*& out, T value) {
208
198k
    if (value == 0) {
209
2
        *out++ = '0';
210
198k
    } else {
211
198k
        constexpr size_t buffer_size = sizeof(T) * int_log(256, base, false);
212
213
198k
        char buf[buffer_size];
214
198k
        auto ptr = buf;
215
216
815k
        while (value > 0) {
217
616k
            *ptr = hex_digit_lowercase(value % base);
218
616k
            ++ptr;
219
616k
            value /= base;
220
616k
        }
221
222
        /// Copy to out reversed.
223
815k
        while (ptr != buf) {
224
616k
            --ptr;
225
616k
            *out = *ptr;
226
616k
            ++out;
227
616k
        }
228
198k
    }
229
198k
}
230
231
/** Rewritten inet_ntop6 from http://svn.apache.org/repos/asf/apr/apr/trunk/network_io/unix/inet_pton.c
232
  * performs significantly faster than the reference implementation due to the absence of sprintf calls,
233
  * bounds checking, unnecessary string copying and length calculation.
234
  * @param src         - pointer to IPv6 (16 bytes) stored in little-endian byte order
235
  * @param dst         - where to put format result bytes
236
  * @param zeroed_tail_bytes_count - the parameter is currently not being used
237
  */
238
2.97M
inline void format_ipv6(unsigned char* src, char*& dst, uint8_t zeroed_tail_bytes_count = 0) {
239
2.97M
    struct {
240
2.97M
        Int64 base, len;
241
2.97M
    } best {-1, 0}, cur {-1, 0};
242
2.97M
    std::array<UInt16, IPV6_BINARY_LENGTH / sizeof(UInt16)> words {};
243
244
    // the current function logic is processed in big endian manner
245
    // but ipv6 in doris is stored in little-endian byte order
246
    // so transfer to big-endian byte order first
247
    // compatible with parse_ipv6 function in format_ip.h
248
2.97M
    std::reverse(src, src + IPV6_BINARY_LENGTH);
249
250
    /** Preprocess:
251
        *    Copy the input (bytewise) array into a wordwise array.
252
        *    Find the longest run of 0x00's in src[] for :: shorthanding. */
253
26.7M
    for (size_t i = 0; i < (IPV6_BINARY_LENGTH - zeroed_tail_bytes_count); i += 2) {
254
23.7M
        words[i / 2] = (uint16_t)(src[i] << 8) | src[i + 1];
255
23.7M
    }
256
257
26.7M
    for (size_t i = 0; i < words.size(); i++) {
258
23.7M
        if (words[i] == 0) {
259
23.5M
            if (cur.base == -1) {
260
2.96M
                cur.base = i;
261
2.96M
                cur.len = 1;
262
20.6M
            } else {
263
20.6M
                cur.len++;
264
20.6M
            }
265
23.5M
        } else {
266
198k
            if (cur.base != -1) {
267
55.0k
                if (best.base == -1 || cur.len > best.len) {
268
55.0k
                    best = cur;
269
55.0k
                }
270
55.0k
                cur.base = -1;
271
55.0k
            }
272
198k
        }
273
23.7M
    }
274
275
2.97M
    if (cur.base != -1) {
276
2.91M
        if (best.base == -1 || cur.len > best.len) {
277
2.91M
            best = cur;
278
2.91M
        }
279
2.91M
    }
280
2.97M
    if (best.base != -1 && best.len < 2) {
281
0
        best.base = -1;
282
0
    }
283
284
    /// Format the result.
285
26.7M
    for (size_t i = 0; i < words.size(); i++) {
286
        /// Are we inside the best run of 0x00's?
287
23.7M
        if (best.base != -1) {
288
23.7M
            auto best_base = static_cast<size_t>(best.base);
289
23.7M
            if (i >= best_base && i < (best_base + best.len)) {
290
23.5M
                if (i == best_base) {
291
2.96M
                    *dst++ = ':';
292
2.96M
                }
293
23.5M
                continue;
294
23.5M
            }
295
23.7M
        }
296
        /// Are we following an initial run of 0x00s or any real hex?
297
198k
        if (i != 0) {
298
140k
            *dst++ = ':';
299
140k
        }
300
        /// Is this address an encapsulated IPv4?
301
198k
        if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 5 && words[5] == 0xffffu))) {
302
18
            uint8_t ipv4_buffer[IPV4_BINARY_LENGTH] = {0};
303
18
            memcpy(ipv4_buffer, src + 12, IPV4_BINARY_LENGTH);
304
            // Due to historical reasons format_ipv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format.
305
18
            if constexpr (std::endian::native == std::endian::little) {
306
18
                std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer));
307
18
            }
308
18
            format_ipv4(ipv4_buffer, dst,
309
18
                        std::min(zeroed_tail_bytes_count, static_cast<uint8_t>(IPV4_BINARY_LENGTH)),
310
18
                        "0");
311
            // format_ipv4 has already added a null-terminator for us.
312
18
            return;
313
18
        }
314
198k
        print_integer<16>(dst, words[i]);
315
198k
    }
316
317
    /// Was it a trailing run of 0x00's?
318
2.97M
    if (best.base != -1 &&
319
2.97M
        static_cast<size_t>(best.base) + static_cast<size_t>(best.len) == words.size()) {
320
2.91M
        *dst++ = ':';
321
2.91M
    }
322
2.97M
}
323
324
/** Unsafe (no bounds-checking for src nor dst), optimized version of parsing IPv6 string.
325
*
326
* Parses the input string `src` and stores binary little-endian value into buffer pointed by `dst`,
327
* which should be long enough. In case of failure zeroes IPV6_BINARY_LENGTH bytes of buffer pointed by `dst`.
328
*
329
* WARNING - this function is adapted to work with ReadBuffer, where src is the position reference (ReadBuffer::position())
330
*           and eof is the ReadBuffer::eof() - therefore algorithm below does not rely on buffer's continuity.
331
*           To parse strings use overloads below.
332
*
333
* @param src         - iterator (reference to pointer) over input string - warning - continuity is not guaranteed.
334
* @param eof         - function returning true if iterator riched the end - warning - can break iterator's continuity.
335
* @param dst         - where to put output bytes in little-endian byte order, expected to be non-null and at IPV6_BINARY_LENGTH-long.
336
* @param first_block - preparsed first block
337
* @return            - true if parsed successfully, false otherwise.
338
*/
339
template <typename T, typename EOFfunction>
340
    requires(std::is_same<typename std::remove_cv<T>::type, char>::value)
341
123k
inline bool parse_ipv6(T*& src, EOFfunction eof, unsigned char* dst, int32_t first_block = -1) {
342
123k
    const auto clear_dst = [dst]() {
343
10.8k
        std::memset(dst, '\0', IPV6_BINARY_LENGTH);
344
10.8k
        return false;
345
10.8k
    };
_ZZN5doris10parse_ipv6IKcZNS_10parse_ipv6EPS1_S2_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_iENKUlvE_clEv
Line
Count
Source
342
10.8k
    const auto clear_dst = [dst]() {
343
10.8k
        std::memset(dst, '\0', IPV6_BINARY_LENGTH);
344
10.8k
        return false;
345
10.8k
    };
Unexecuted instantiation: _ZZN5doris10parse_ipv6IKcZNS_10parse_ipv6EPS1_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_iENKUlvE_clEv
346
347
123k
    if (src == nullptr || eof()) return clear_dst();
348
349
123k
    int groups = 0;            /// number of parsed groups
350
123k
    unsigned char* iter = dst; /// iterator over dst buffer
351
123k
    unsigned char* zptr =
352
123k
            nullptr; /// pointer into dst buffer array where all-zeroes block ("::") is started
353
354
123k
    std::memset(dst, '\0', IPV6_BINARY_LENGTH);
355
356
123k
    if (first_block >= 0) {
357
0
        *iter++ = static_cast<unsigned char>((first_block >> 8) & 0xffu);
358
0
        *iter++ = static_cast<unsigned char>(first_block & 0xffu);
359
0
        if (*src == ':') {
360
0
            zptr = iter;
361
0
            ++src;
362
0
        }
363
0
        ++groups;
364
0
    }
365
366
123k
    bool group_start = true;
367
368
1.00M
    while (!eof() && groups < 8) {
369
885k
        if (*src == ':') {
370
755k
            ++src;
371
755k
            if (eof()) /// trailing colon is not allowed
372
62
                return clear_dst();
373
374
755k
            group_start = true;
375
376
755k
            if (*src == ':') {
377
7.21k
                if (zptr != nullptr) /// multiple all-zeroes blocks are not allowed
378
304
                    return clear_dst();
379
6.91k
                zptr = iter;
380
6.91k
                ++src;
381
6.91k
                if (!eof() && *src == ':') {
382
                    /// more than one all-zeroes block is not allowed
383
10
                    return clear_dst();
384
10
                }
385
6.90k
                continue;
386
6.91k
            }
387
748k
            if (groups == 0) /// leading colon is not allowed
388
0
                return clear_dst();
389
748k
        }
390
391
        /// mixed IPv4 parsing
392
878k
        if (*src == '.') {
393
156
            if (groups <= 1 && zptr == nullptr) /// IPv4 block can't be the first
394
0
                return clear_dst();
395
396
156
            if (group_start) /// first octet of IPv4 should be already parsed as an IPv6 group
397
0
                return clear_dst();
398
399
156
            ++src;
400
156
            if (eof()) return clear_dst();
401
402
            /// last parsed group should be reinterpreted as a decimal value - it's the first octet of IPv4
403
156
            --groups;
404
156
            iter -= 2;
405
406
156
            UInt16 num = 0;
407
468
            for (int i = 0; i < 2; ++i) {
408
312
                unsigned char first = (iter[i] >> 4) & 0x0fu;
409
312
                unsigned char second = iter[i] & 0x0fu;
410
312
                if (first > 9 || second > 9) return clear_dst();
411
312
                (num *= 100) += first * 10 + second;
412
312
            }
413
156
            if (num > 255) return clear_dst();
414
415
            /// parse IPv4 with known first octet
416
156
            if (!parse_ipv4(src, eof, iter, num)) return clear_dst();
417
418
            if constexpr (std::endian::native == std::endian::little)
419
152
                std::reverse(iter, iter + IPV4_BINARY_LENGTH);
420
421
152
            iter += 4;
422
152
            groups += 2;
423
152
            break; /// IPv4 block is the last - end of parsing
424
156
        }
425
426
878k
        if (!group_start) /// end of parsing
427
1.63k
            break;
428
876k
        group_start = false;
429
430
876k
        UInt16 val = 0;  /// current decoded group
431
876k
        int xdigits = 0; /// number of decoded hex digits in current group
432
433
2.61M
        for (; !eof() && xdigits < 4; ++src, ++xdigits) {
434
2.24M
            UInt8 num = unhex(*src);
435
2.24M
            if (num == 0xFF) break;
436
1.73M
            (val <<= 4) |= num;
437
1.73M
        }
438
439
876k
        if (xdigits == 0) /// end of parsing
440
1.84k
            break;
441
442
875k
        *iter++ = static_cast<unsigned char>((val >> 8) & 0xffu);
443
875k
        *iter++ = static_cast<unsigned char>(val & 0xffu);
444
875k
        ++groups;
445
875k
    }
446
447
    /// either all 8 groups or all-zeroes block should be present
448
122k
    if (groups < 8 && zptr == nullptr) return clear_dst();
449
450
    /// process all-zeroes block
451
112k
    if (zptr != nullptr) {
452
6.53k
        if (groups == 8) {
453
            /// all-zeroes block at least should be one
454
            /// 2001:0db8:86a3::08d3:1319:8a2e:0370:7344 not valid
455
4
            return clear_dst();
456
4
        }
457
6.52k
        size_t msize = iter - zptr;
458
6.52k
        std::memmove(dst + IPV6_BINARY_LENGTH - msize, zptr, msize);
459
6.52k
        std::memset(zptr, '\0', IPV6_BINARY_LENGTH - (iter - dst));
460
6.52k
    }
461
462
    /// the current function logic is processed in big endian manner
463
    /// but ipv6 in doris is stored in little-endian byte order
464
    /// so transfer to little-endian
465
112k
    std::reverse(dst, dst + IPV6_BINARY_LENGTH);
466
467
112k
    return true;
468
112k
}
_ZN5doris10parse_ipv6IKcZNS_10parse_ipv6EPS1_S2_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_i
Line
Count
Source
341
123k
inline bool parse_ipv6(T*& src, EOFfunction eof, unsigned char* dst, int32_t first_block = -1) {
342
123k
    const auto clear_dst = [dst]() {
343
123k
        std::memset(dst, '\0', IPV6_BINARY_LENGTH);
344
123k
        return false;
345
123k
    };
346
347
123k
    if (src == nullptr || eof()) return clear_dst();
348
349
123k
    int groups = 0;            /// number of parsed groups
350
123k
    unsigned char* iter = dst; /// iterator over dst buffer
351
123k
    unsigned char* zptr =
352
123k
            nullptr; /// pointer into dst buffer array where all-zeroes block ("::") is started
353
354
123k
    std::memset(dst, '\0', IPV6_BINARY_LENGTH);
355
356
123k
    if (first_block >= 0) {
357
0
        *iter++ = static_cast<unsigned char>((first_block >> 8) & 0xffu);
358
0
        *iter++ = static_cast<unsigned char>(first_block & 0xffu);
359
0
        if (*src == ':') {
360
0
            zptr = iter;
361
0
            ++src;
362
0
        }
363
0
        ++groups;
364
0
    }
365
366
123k
    bool group_start = true;
367
368
1.00M
    while (!eof() && groups < 8) {
369
885k
        if (*src == ':') {
370
755k
            ++src;
371
755k
            if (eof()) /// trailing colon is not allowed
372
62
                return clear_dst();
373
374
755k
            group_start = true;
375
376
755k
            if (*src == ':') {
377
7.21k
                if (zptr != nullptr) /// multiple all-zeroes blocks are not allowed
378
304
                    return clear_dst();
379
6.91k
                zptr = iter;
380
6.91k
                ++src;
381
6.91k
                if (!eof() && *src == ':') {
382
                    /// more than one all-zeroes block is not allowed
383
10
                    return clear_dst();
384
10
                }
385
6.90k
                continue;
386
6.91k
            }
387
748k
            if (groups == 0) /// leading colon is not allowed
388
0
                return clear_dst();
389
748k
        }
390
391
        /// mixed IPv4 parsing
392
878k
        if (*src == '.') {
393
156
            if (groups <= 1 && zptr == nullptr) /// IPv4 block can't be the first
394
0
                return clear_dst();
395
396
156
            if (group_start) /// first octet of IPv4 should be already parsed as an IPv6 group
397
0
                return clear_dst();
398
399
156
            ++src;
400
156
            if (eof()) return clear_dst();
401
402
            /// last parsed group should be reinterpreted as a decimal value - it's the first octet of IPv4
403
156
            --groups;
404
156
            iter -= 2;
405
406
156
            UInt16 num = 0;
407
468
            for (int i = 0; i < 2; ++i) {
408
312
                unsigned char first = (iter[i] >> 4) & 0x0fu;
409
312
                unsigned char second = iter[i] & 0x0fu;
410
312
                if (first > 9 || second > 9) return clear_dst();
411
312
                (num *= 100) += first * 10 + second;
412
312
            }
413
156
            if (num > 255) return clear_dst();
414
415
            /// parse IPv4 with known first octet
416
156
            if (!parse_ipv4(src, eof, iter, num)) return clear_dst();
417
418
            if constexpr (std::endian::native == std::endian::little)
419
152
                std::reverse(iter, iter + IPV4_BINARY_LENGTH);
420
421
152
            iter += 4;
422
152
            groups += 2;
423
152
            break; /// IPv4 block is the last - end of parsing
424
156
        }
425
426
878k
        if (!group_start) /// end of parsing
427
1.63k
            break;
428
876k
        group_start = false;
429
430
876k
        UInt16 val = 0;  /// current decoded group
431
876k
        int xdigits = 0; /// number of decoded hex digits in current group
432
433
2.61M
        for (; !eof() && xdigits < 4; ++src, ++xdigits) {
434
2.24M
            UInt8 num = unhex(*src);
435
2.24M
            if (num == 0xFF) break;
436
1.73M
            (val <<= 4) |= num;
437
1.73M
        }
438
439
876k
        if (xdigits == 0) /// end of parsing
440
1.84k
            break;
441
442
875k
        *iter++ = static_cast<unsigned char>((val >> 8) & 0xffu);
443
875k
        *iter++ = static_cast<unsigned char>(val & 0xffu);
444
875k
        ++groups;
445
875k
    }
446
447
    /// either all 8 groups or all-zeroes block should be present
448
122k
    if (groups < 8 && zptr == nullptr) return clear_dst();
449
450
    /// process all-zeroes block
451
112k
    if (zptr != nullptr) {
452
6.53k
        if (groups == 8) {
453
            /// all-zeroes block at least should be one
454
            /// 2001:0db8:86a3::08d3:1319:8a2e:0370:7344 not valid
455
4
            return clear_dst();
456
4
        }
457
6.52k
        size_t msize = iter - zptr;
458
6.52k
        std::memmove(dst + IPV6_BINARY_LENGTH - msize, zptr, msize);
459
6.52k
        std::memset(zptr, '\0', IPV6_BINARY_LENGTH - (iter - dst));
460
6.52k
    }
461
462
    /// the current function logic is processed in big endian manner
463
    /// but ipv6 in doris is stored in little-endian byte order
464
    /// so transfer to little-endian
465
112k
    std::reverse(dst, dst + IPV6_BINARY_LENGTH);
466
467
112k
    return true;
468
112k
}
Unexecuted instantiation: _ZN5doris10parse_ipv6IKcZNS_10parse_ipv6EPS1_PhEUlvE_Qsr3std7is_sameINSt9remove_cvIT_E4typeEcEE5valueEEbRPS6_T0_S3_i
469
470
/// returns pointer to the right after parsed sequence or null on failed parsing
471
123k
inline const char* parse_ipv6(const char* src, const char* end, unsigned char* dst) {
472
123k
    if (parse_ipv6(
473
4.50M
                src, [&src, end]() { return src == end; }, dst))
474
112k
        return src;
475
10.8k
    return nullptr;
476
123k
}
477
478
/// returns true if whole buffer was parsed successfully
479
123k
inline bool parse_ipv6_whole(const char* src, const char* end, unsigned char* dst) {
480
123k
    return parse_ipv6(src, end, dst) == end;
481
123k
}
482
483
/// returns pointer to the right after parsed sequence or null on failed parsing
484
0
inline const char* parse_ipv6(const char* src, unsigned char* dst) {
485
0
    if (parse_ipv6(
486
0
                src, []() { return false; }, dst))
487
0
        return src;
488
0
    return nullptr;
489
0
}
490
491
/// returns true if whole null-terminated string was parsed successfully
492
0
inline bool parse_ipv6_whole(const char* src, unsigned char* dst) {
493
0
    const char* end = parse_ipv6(src, dst);
494
0
    return end != nullptr && *end == '\0';
495
0
}
496
497
} // namespace doris