aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/netliba/v6/udp_address.cpp
blob: be823e2dfa35b8f4de5caa6120bb7f6ce94b3175 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#include "stdafx.h"
#include "udp_address.h"

#include <util/system/mutex.h>
#include <util/system/spinlock.h>

#ifdef _win_
#include <iphlpapi.h>
#pragma comment(lib, "Iphlpapi.lib")
#else
#include <errno.h>
#include <ifaddrs.h>
#endif

namespace NNetliba {
    static bool IsValidIPv6(const char* sz) {
        enum {
            S1,
            SEMICOLON,
            SCOPE
        };
        int state = S1, scCount = 0, digitCount = 0, hasDoubleSemicolon = false;
        while (*sz) {
            if (state == S1) {
                switch (*sz) {
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                    case 'A':
                    case 'B':
                    case 'C':
                    case 'D':
                    case 'E':
                    case 'F':
                    case 'a':
                    case 'b':
                    case 'c':
                    case 'd':
                    case 'e':
                    case 'f':
                        ++digitCount;
                        if (digitCount > 4)
                            return false;
                        break;
                    case ':':
                        state = SEMICOLON;
                        ++scCount;
                        break;
                    case '%':
                        state = SCOPE;
                        break;
                    default:
                        return false;
                }
                ++sz;
            } else if (state == SEMICOLON) {
                if (*sz == ':') {
                    if (hasDoubleSemicolon)
                        return false;
                    hasDoubleSemicolon = true;
                    ++scCount;
                    digitCount = 0;
                    state = S1;
                    ++sz;
                } else {
                    digitCount = 0;
                    state = S1;
                }
            } else if (state == SCOPE) {
                // arbitrary string is allowed as scope id
                ++sz;
            }
        }
        if (!hasDoubleSemicolon && scCount != 7)
            return false;
        return scCount <= 7;
    }

    static bool ParseInetName(TUdpAddress* pRes, const char* name, int nDefaultPort, EUdpAddressType addressType) {
        int nPort = nDefaultPort;

        TString host;
        if (name[0] == '[') {
            ++name;
            const char* nameFin = name;
            for (; *nameFin; ++nameFin) {
                if (nameFin[0] == ']')
                    break;
            }
            host.assign(name, nameFin);
            Y_ASSERT(IsValidIPv6(host.c_str()));
            name = *nameFin ? nameFin + 1 : nameFin;
            if (name[0] == ':') {
                char* endPtr = nullptr;
                nPort = strtol(name + 1, &endPtr, 10);
                if (!endPtr || *endPtr != '\0')
                    return false;
            }
        } else {
            host = name;
            if (!IsValidIPv6(name)) {
                size_t nIdx = host.find(':');
                if (nIdx != (size_t)TString::npos) {
                    const char* pszPort = host.c_str() + nIdx + 1;
                    char* endPtr = nullptr;
                    nPort = strtol(pszPort, &endPtr, 10);
                    if (!endPtr || *endPtr != '\0')
                        return false;
                    host.resize(nIdx);
                }
            }
        }

        addrinfo aiHints;
        Zero(aiHints);
        aiHints.ai_family = AF_UNSPEC;
        aiHints.ai_socktype = SOCK_DGRAM;
        aiHints.ai_protocol = IPPROTO_UDP;

        // Do not use TMutex here: it has a non-trivial destructor which will be called before
        // destruction of current thread, if its TThread declared as global/static variable.
        static TAdaptiveLock cs;
        TGuard lock(cs);

        addrinfo* aiList = nullptr;
        for (int attempt = 0; attempt < 1000; ++attempt) {
            int rv = getaddrinfo(host.c_str(), "1313", &aiHints, &aiList);
            if (rv == 0)
                break;
            if (aiList) {
                freeaddrinfo(aiList);
            }
            if (rv != EAI_AGAIN) {
                return false;
            }
            usleep(100 * 1000);
        }
        for (addrinfo* ptr = aiList; ptr; ptr = ptr->ai_next) {
            sockaddr* addr = ptr->ai_addr;
            if (addr == nullptr)
                continue;
            switch (addressType) {
                case UAT_ANY: {
                    if (addr->sa_family != AF_INET && addr->sa_family != AF_INET6)
                        continue;
                    break;
                }
                case UAT_IPV4: {
                    if (addr->sa_family != AF_INET)
                        continue;
                    break;
                }
                case UAT_IPV6: {
                    if (addr->sa_family != AF_INET6)
                        continue;
                    break;
                }
            }

            GetUdpAddress(pRes, *(sockaddr_in6*)addr);
            pRes->Port = nPort;
            freeaddrinfo(aiList);
            return true;
        }
        freeaddrinfo(aiList);
        return false;
    }

    bool GetLocalAddresses(TVector<TUdpAddress>* addrs) {
#ifdef _win_
        TVector<char> buf;
        buf.resize(1000000);
        PIP_ADAPTER_ADDRESSES adapterBuf = (PIP_ADAPTER_ADDRESSES)&buf[0];
        ULONG bufSize = buf.ysize();

        ULONG rv = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapterBuf, &bufSize);
        if (rv != ERROR_SUCCESS)
            return false;
        for (PIP_ADAPTER_ADDRESSES ptr = adapterBuf; ptr; ptr = ptr->Next) {
            if ((ptr->Flags & (IP_ADAPTER_IPV4_ENABLED | IP_ADAPTER_IPV6_ENABLED)) == 0) {
                continue;
            }
            if (ptr->IfType == IF_TYPE_TUNNEL) {
                // ignore tunnels
                continue;
            }
            if (ptr->OperStatus != IfOperStatusUp) {
                // ignore disable adapters
                continue;
            }
            if (ptr->Mtu < 1280) {
                fprintf(stderr, "WARNING: MTU %lu is less then ipv6 minimum", ptr->Mtu);
            }
            for (IP_ADAPTER_UNICAST_ADDRESS* addr = ptr->FirstUnicastAddress; addr; addr = addr->Next) {
                sockaddr* x = (sockaddr*)addr->Address.lpSockaddr;
                if (x == 0)
                    continue;
                if (x->sa_family == AF_INET || x->sa_family == AF_INET6) {
                    TUdpAddress address;
                    sockaddr_in6* xx = (sockaddr_in6*)x;
                    GetUdpAddress(&address, *xx);
                    addrs->push_back(address);
                }
            }
        }
        return true;
#else
        ifaddrs* ifap;
        if (getifaddrs(&ifap) != -1) {
            for (ifaddrs* ifa = ifap; ifa; ifa = ifa->ifa_next) {
                sockaddr* sa = (sockaddr*)ifa->ifa_addr;
                if (sa == nullptr)
                    continue;
                if (sa->sa_family == AF_INET || sa->sa_family == AF_INET6) {
                    TUdpAddress address;
                    sockaddr_in6* xx = (sockaddr_in6*)sa;
                    GetUdpAddress(&address, *xx);
                    addrs->push_back(address);
                }
            }
            freeifaddrs(ifap);
            return true;
        }
        return false;
#endif
    }

    void GetUdpAddress(TUdpAddress* res, const sockaddr_in6& addr) {
        if (addr.sin6_family == AF_INET) {
            const sockaddr_in& addr4 = *(const sockaddr_in*)&addr;
            res->Network = 0;
            res->Interface = 0xffff0000ll + (((ui64)(ui32)addr4.sin_addr.s_addr) << 32);
            res->Scope = 0;
            res->Port = ntohs(addr4.sin_port);
        } else if (addr.sin6_family == AF_INET6) {
            res->Network = *BreakAliasing<ui64>(addr.sin6_addr.s6_addr + 0);
            res->Interface = *BreakAliasing<ui64>(addr.sin6_addr.s6_addr + 8);
            res->Scope = addr.sin6_scope_id;
            res->Port = ntohs(addr.sin6_port);
        }
    }

    void GetWinsockAddr(sockaddr_in6* res, const TUdpAddress& addr) {
        if (0) { //addr.IsIPv4()) {
            // use ipv4 to ipv6 mapping
            //// ipv4
            //sockaddr_in &toAddress = *(sockaddr_in*)res;
            //Zero(toAddress);
            //toAddress.sin_family = AF_INET;
            //toAddress.sin_addr.s_addr = addr.GetIPv4();
            //toAddress.sin_port = htons((u_short)addr.Port);
        } else {
            // ipv6
            sockaddr_in6& toAddress = *(sockaddr_in6*)res;
            Zero(toAddress);
            toAddress.sin6_family = AF_INET6;
            *BreakAliasing<ui64>(toAddress.sin6_addr.s6_addr + 0) = addr.Network;
            *BreakAliasing<ui64>(toAddress.sin6_addr.s6_addr + 8) = addr.Interface;
            toAddress.sin6_scope_id = addr.Scope;
            toAddress.sin6_port = htons((u_short)addr.Port);
        }
    }

    TUdpAddress CreateAddress(const TString& server, int defaultPort, EUdpAddressType addressType) {
        TUdpAddress res;
        ParseInetName(&res, server.c_str(), defaultPort, addressType);
        return res;
    }

    TString GetAddressAsString(const TUdpAddress& addr) {
        char buf[1000];
        if (addr.IsIPv4()) {
            int ip = addr.GetIPv4();
            snprintf(buf, sizeof(buf), "%d.%d.%d.%d:%d",
                    (ip >> 0) & 0xff, (ip >> 8) & 0xff,
                    (ip >> 16) & 0xff, (ip >> 24) & 0xff,
                    addr.Port);
        } else {
            ui16 ipv6[8];
            *BreakAliasing<ui64>(ipv6) = addr.Network;
            *BreakAliasing<ui64>(ipv6 + 4) = addr.Interface;
            char suffix[100] = "";
            if (addr.Scope != 0) {
                snprintf(suffix, sizeof(suffix), "%%%d", addr.Scope);
            }
            snprintf(buf, sizeof(buf), "[%x:%x:%x:%x:%x:%x:%x:%x%s]:%d",
                    ntohs(ipv6[0]), ntohs(ipv6[1]), ntohs(ipv6[2]), ntohs(ipv6[3]),
                    ntohs(ipv6[4]), ntohs(ipv6[5]), ntohs(ipv6[6]), ntohs(ipv6[7]),
                    suffix, addr.Port);
        }
        return buf;
    }
}