Coverage Report

Created: 2026-10-15 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541_15/arch/posix/eventloop_posix_udp.c
Line
Count
Source
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
 *
5
 *    Copyright 2021-2022 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
6
 *    Copyright 2021 (c) Fraunhofer IOSB (Author: Jan Hermes)
7
 */
8
9
#include "eventloop_posix.h"
10
11
#if defined(UA_ARCHITECTURE_POSIX) && !defined(UA_ARCHITECTURE_LWIP) || defined(UA_ARCHITECTURE_WIN32)
12
13
472
#define IPV4_PREFIX_MASK 0xF0
14
472
#define IPV4_MULTICAST_PREFIX 0xE0
15
#if UA_IPV6
16
0
# define IPV6_PREFIX_MASK 0xFF
17
0
# define IPV6_MULTICAST_PREFIX 0xFF
18
#endif
19
20
/* Configuration parameters */
21
22
9.39k
#define UDP_MANAGERPARAMS 2
23
24
static UA_KeyValueRestriction udpManagerParams[UDP_MANAGERPARAMS] = {
25
    {{0, UA_STRING_STATIC("recv-bufsize")}, &UA_TYPES[UA_TYPES_UINT32], false, true, false},
26
    {{0, UA_STRING_STATIC("send-bufsize")}, &UA_TYPES[UA_TYPES_UINT32], false, true, false}
27
};
28
29
472
#define UDP_PARAMETERSSIZE 9
30
472
#define UDP_PARAMINDEX_LISTEN 0
31
472
#define UDP_PARAMINDEX_ADDR 1
32
472
#define UDP_PARAMINDEX_PORT 2
33
472
#define UDP_PARAMINDEX_INTERFACE 3
34
472
#define UDP_PARAMINDEX_TTL 4
35
472
#define UDP_PARAMINDEX_LOOPBACK 5
36
472
#define UDP_PARAMINDEX_REUSE 6
37
472
#define UDP_PARAMINDEX_SOCKPRIO 7
38
472
#define UDP_PARAMINDEX_VALIDATE 8
39
40
static UA_KeyValueRestriction udpConnectionParams[UDP_PARAMETERSSIZE] = {
41
    {{0, UA_STRING_STATIC("listen")}, &UA_TYPES[UA_TYPES_BOOLEAN], false, true, false},
42
    {{0, UA_STRING_STATIC("address")}, &UA_TYPES[UA_TYPES_STRING], false, true, true},
43
    {{0, UA_STRING_STATIC("port")}, &UA_TYPES[UA_TYPES_UINT16], true, true, false},
44
    {{0, UA_STRING_STATIC("interface")}, &UA_TYPES[UA_TYPES_STRING], false, true, false},
45
    {{0, UA_STRING_STATIC("ttl")}, &UA_TYPES[UA_TYPES_UINT32], false, true, false},
46
    {{0, UA_STRING_STATIC("loopback")}, &UA_TYPES[UA_TYPES_BOOLEAN], false, true, false},
47
    {{0, UA_STRING_STATIC("reuse")}, &UA_TYPES[UA_TYPES_BOOLEAN], false, true, false},
48
    {{0, UA_STRING_STATIC("sockpriority")}, &UA_TYPES[UA_TYPES_UINT32], false, true, false},
49
    {{0, UA_STRING_STATIC("validate")}, &UA_TYPES[UA_TYPES_BOOLEAN], false, true, false}
50
};
51
52
/* A registered file descriptor with an additional method pointer */
53
typedef struct {
54
    UA_RegisteredFD rfd;
55
56
    UA_ConnectionManager_connectionCallback applicationCB;
57
    void *application;
58
    void *context;
59
60
    struct sockaddr_storage sendAddr;
61
#ifdef UA_ARCHITECTURE_WIN32
62
    size_t sendAddrLength;
63
#else
64
    socklen_t sendAddrLength;
65
#endif
66
} UDP_FD;
67
68
typedef enum {
69
    MULTICASTTYPE_NONE = 0,
70
    MULTICASTTYPE_IPV4,
71
    MULTICASTTYPE_IPV6
72
} MultiCastType;
73
74
typedef union {
75
#if !defined(__linux__)
76
    struct ip_mreq ipv4;
77
#else
78
    struct ip_mreqn ipv4;
79
#endif
80
#if UA_IPV6
81
    struct ipv6_mreq ipv6;
82
#endif
83
} MulticastRequest;
84
85
static UA_Boolean
86
472
isMulticastAddress(const UA_Byte *address, UA_Byte mask, UA_Byte prefix) {
87
472
    return (address[0] & mask) == prefix;
88
472
}
89
90
static MultiCastType
91
472
multiCastType(struct addrinfo *info) {
92
472
    const UA_Byte *address;
93
472
    if(info->ai_family == AF_INET) {
94
472
        address = (UA_Byte *)&((struct sockaddr_in *)info->ai_addr)->sin_addr;
95
472
        if(isMulticastAddress(address, IPV4_PREFIX_MASK, IPV4_MULTICAST_PREFIX))
96
472
            return MULTICASTTYPE_IPV4;
97
472
#if UA_IPV6
98
472
    } else if(info->ai_family == AF_INET6) {
99
0
        address = (UA_Byte *)&((struct sockaddr_in6 *)info->ai_addr)->sin6_addr;
100
0
        if(isMulticastAddress(address, IPV6_PREFIX_MASK, IPV6_MULTICAST_PREFIX))
101
0
            return MULTICASTTYPE_IPV6;
102
0
#endif
103
0
    }
104
0
    return MULTICASTTYPE_NONE;
105
472
}
106
107
#ifdef UA_ARCHITECTURE_WIN32
108
109
#define ADDR_BUFFER_SIZE 15000 /* recommended size in the MSVC docs */
110
111
static UA_StatusCode
112
setMulticastInterface(const char *netif, struct addrinfo *info,
113
                      MulticastRequest *req, const UA_Logger *logger) {
114
    ULONG outBufLen = ADDR_BUFFER_SIZE;
115
    UA_STACKARRAY(char, addrBuf, ADDR_BUFFER_SIZE);
116
117
    /* Get the network interface descriptions */
118
    ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
119
        GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME;
120
    PIP_ADAPTER_ADDRESSES ifaddr = (IP_ADAPTER_ADDRESSES *)addrBuf;
121
    DWORD ret = GetAdaptersAddresses(info->ai_family, flags, NULL, ifaddr, &outBufLen);
122
    if(ret != NO_ERROR) {
123
        UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
124
                     "UDP\t| Interface configuration preparation failed");
125
        return UA_STATUSCODE_BADINTERNALERROR;
126
    }
127
128
    /* Iterate through linked list of network interfaces */
129
    char sourceAddr[64];
130
    unsigned int idx = 0;
131
    for(PIP_ADAPTER_ADDRESSES ifa = ifaddr; ifa != NULL; ifa = ifa->Next) {
132
        idx = (info->ai_family == AF_INET) ? ifa->IfIndex : ifa->Ipv6IfIndex;
133
134
        /* Check if network interface name matches */
135
        if(strcmp(ifa->AdapterName, netif) == 0)
136
            goto done;
137
138
        /* Check if ip address matches */
139
        for(PIP_ADAPTER_UNICAST_ADDRESS u = ifa->FirstUnicastAddress; u; u = u->Next) {
140
            LPSOCKADDR addr = u->Address.lpSockaddr;
141
            if(addr->sa_family == AF_INET) {
142
                inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr,
143
                          sourceAddr, sizeof(sourceAddr));
144
            } else if(addr->sa_family == AF_INET6) {
145
                inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr,
146
                          sourceAddr, sizeof(sourceAddr));
147
            } else {
148
                continue;
149
            }
150
            if(strcmp(sourceAddr, netif) == 0)
151
                goto done;
152
        }
153
    }
154
155
    /* Not matching interface found */
156
    UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
157
                 "UDP\t| Interface configuration preparation failed "
158
                 "(interface %s not found)", netif);
159
    return UA_STATUSCODE_BADINTERNALERROR;
160
161
 done:
162
    /* Write the interface index */
163
    if(info->ai_family == AF_INET)
164
        /* MSVC documentation of struct ip_mreq: To use an interface index of 1
165
         * would be the same as an IP address of 0.0.0.1. */
166
        req->ipv4.imr_interface.s_addr = htonl(idx);
167
#if UA_IPV6
168
    else /* if(info->ai_family == AF_INET6) */
169
        req->ipv6.ipv6mr_interface = idx;
170
#endif
171
    return UA_STATUSCODE_GOOD;
172
}
173
174
#else
175
176
static UA_StatusCode
177
setMulticastInterface(const char *netif, struct addrinfo *info,
178
0
                      MulticastRequest *req, const UA_Logger *logger) {
179
0
    UA_RESET_ERRNO;
180
0
    struct ifaddrs *ifaddr;
181
0
    int ret = getifaddrs(&ifaddr);
182
0
    if(ret == -1) {
183
0
        UA_LOG_SOCKET_ERRNO_WRAP(
184
0
           UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
185
0
                        "UDP\t| Interface configuration preparation failed "
186
0
                        "(getifaddrs error: %s)", errno_str));
187
0
        return UA_STATUSCODE_BADINTERNALERROR;
188
0
    }
189
190
    /* Iterate over the interfaces */
191
0
    unsigned int idx = 0;
192
0
    struct ifaddrs *ifa = NULL;
193
0
    for(ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
194
0
        if(!ifa->ifa_addr)
195
0
            continue;
196
197
        /* Does the protocol family match? */
198
0
        if(ifa->ifa_addr->sa_family != info->ai_family)
199
0
            continue;
200
201
0
#if defined(UA_ARCHITECTURE_WIN32) || defined(__linux__)
202
0
        idx = UA_if_nametoindex(ifa->ifa_name);
203
0
        if(idx == 0)
204
0
            continue;
205
0
#endif
206
207
        /* Found network interface by name */
208
0
        if(strcmp(ifa->ifa_name, netif) == 0)
209
0
            break;
210
211
        /* Check if the interface name is an IP address that matches */
212
0
        UA_RESET_ERRNO;
213
0
        char host[NI_MAXHOST];
214
0
        ret = getnameinfo(ifa->ifa_addr,
215
0
                          (info->ai_family == AF_INET) ?
216
0
                          sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
217
0
                          host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
218
0
        if(ret != 0) {
219
0
            UA_LOG_SOCKET_ERRNO_WRAP(
220
0
               UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
221
0
                            "UDP\t| Interface configuration preparation "
222
0
                            "failed (Error: %s).", errno_str));
223
0
            freeifaddrs(ifaddr);
224
0
            return UA_STATUSCODE_BADINTERNALERROR;
225
0
        }
226
0
        if(strcmp(host, netif) == 0)
227
0
            break;
228
0
    }
229
230
0
    if(!ifa) {
231
0
        freeifaddrs(ifaddr);
232
0
        return UA_STATUSCODE_BADINTERNALERROR;
233
0
    }
234
235
    /* Write the interface index */
236
0
    if(info->ai_family == AF_INET) {
237
0
#if defined(__linux__)
238
0
        req->ipv4.imr_ifindex = idx;
239
#elif defined(__APPLE__)
240
        struct sockaddr_in *sin = (struct sockaddr_in*)ifa->ifa_addr;
241
        req->ipv4.imr_interface = sin->sin_addr;
242
#endif
243
0
#if UA_IPV6
244
0
    } else { /* if(info->ai_family == AF_INET6) */
245
0
        req->ipv6.ipv6mr_interface = idx;
246
0
#endif
247
0
    }
248
249
0
    freeifaddrs(ifaddr);
250
0
    return UA_STATUSCODE_GOOD;
251
0
}
252
253
#endif /* UA_ARCHITECTURE_WIN32 */
254
255
static UA_StatusCode
256
setupMulticastRequest(UA_FD socket, MulticastRequest *req, const UA_KeyValueMap *params,
257
472
                      struct addrinfo *info, const UA_Logger *logger) {
258
    /* Initialize the address information */
259
472
    if(info->ai_family == AF_INET) {
260
472
        struct sockaddr_in *sin = (struct sockaddr_in *)info->ai_addr;
261
472
        req->ipv4.imr_multiaddr = sin->sin_addr;
262
#if !defined(__linux__)
263
        req->ipv4.imr_interface.s_addr = htonl(INADDR_ANY); /* default ANY */
264
#else
265
472
        req->ipv4.imr_address.s_addr = htonl(INADDR_ANY); /* default ANY */
266
472
        req->ipv4.imr_ifindex = 0;
267
472
#endif
268
472
#if UA_IPV6
269
472
    } else if(info->ai_family == AF_INET6) {
270
0
        struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)info->ai_addr;
271
0
        req->ipv6.ipv6mr_multiaddr = sin6->sin6_addr;
272
0
        req->ipv6.ipv6mr_interface = 0; /* default ANY interface */
273
0
#endif
274
0
    } else {
275
0
        UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
276
0
                     "UDP\t| Multicast configuration failed: Unknown protocol family");
277
0
        return UA_STATUSCODE_BADINTERNALERROR;
278
0
    }
279
280
    /* Was an interface (or local IP address) defined? */
281
472
    const UA_String *netif = (const UA_String*)
282
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_INTERFACE].name,
283
472
                                 &UA_TYPES[UA_TYPES_STRING]);
284
472
    if(!netif) {
285
472
        UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
286
472
                    "UDP %u\t| No network interface defined for multicast. "
287
472
                    "The first suitable network interface is used.",
288
472
                    (unsigned)socket);
289
472
        return UA_STATUSCODE_GOOD;
290
472
    }
291
292
    /* Set the interface index */
293
0
    if(netif->length >= UA_MAXHOSTNAME_LENGTH) {
294
0
        UA_LOG_ERROR(logger, UA_LOGCATEGORY_NETWORK,
295
0
                     "UDP %u\t| Network interface name too long",
296
0
                     (unsigned)socket);
297
0
        return UA_STATUSCODE_BADINTERNALERROR;
298
0
    }
299
0
    char interfaceAsChar[UA_MAXHOSTNAME_LENGTH];
300
0
    memcpy(interfaceAsChar, netif->data, netif->length);
301
0
    interfaceAsChar[netif->length] = 0;
302
0
    return setMulticastInterface(interfaceAsChar, info, req, logger);
303
0
}
304
305
/* Retrieves hostname and port from given key value parameters.
306
 *
307
 * @param[in] params the parameter map to retrieve from
308
 * @param[out] hostname the retrieved hostname when present, NULL otherwise
309
 * @param[out] portStr the retrieved port when present, NULL otherwise
310
 * @param[in] logger the logger to log information
311
 * @return -1 upon error, 0 if there was no host or port parameter, 1 if
312
 *         host and port are present */
313
static int
314
getHostAndPortFromParams(const UA_KeyValueMap *params, char *hostname,
315
236
                         char *portStr, const UA_Logger *logger) {
316
    /* Prepare the port parameter as a string */
317
236
    const UA_UInt16 *port = (const UA_UInt16*)
318
236
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_PORT].name,
319
236
                                 &UA_TYPES[UA_TYPES_UINT16]);
320
236
    UA_assert(port); /* checked before */
321
236
    mp_snprintf(portStr, UA_MAXPORTSTR_LENGTH, "%d", *port);
322
323
    /* Prepare the hostname string */
324
236
    const UA_String *host = (const UA_String*)
325
236
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_ADDR].name,
326
236
                                 &UA_TYPES[UA_TYPES_STRING]);
327
236
    if(!host) {
328
0
        UA_LOG_DEBUG(logger, UA_LOGCATEGORY_NETWORK,
329
0
                     "UDP\t| No address configured");
330
0
        return -1;
331
0
    }
332
236
    if(host->length >= UA_MAXHOSTNAME_LENGTH) {
333
0
        UA_LOG_ERROR(logger, UA_LOGCATEGORY_EVENTLOOP,
334
0
                     "UDP\t| Open UDP Connection: Hostname too long, aborting");
335
0
        return -1;
336
0
    }
337
236
    strncpy(hostname, (const char*)host->data, host->length);
338
236
    hostname[host->length] = 0;
339
236
    return 1;
340
236
}
341
342
static int
343
getConnectionInfoFromParams(const UA_KeyValueMap *params,
344
                            char *hostname, char *portStr,
345
236
                            struct addrinfo **info, const UA_Logger *logger) {
346
236
    int foundParams = getHostAndPortFromParams(params, hostname, portStr, logger);
347
236
    if(foundParams < 0)
348
0
        return -1;
349
350
    /* Create the socket description from the connectString
351
     * TODO: Make this non-blocking */
352
236
    UA_RESET_ERRNO;
353
236
    struct addrinfo hints;
354
236
    memset(&hints, 0, sizeof(struct addrinfo));
355
236
    hints.ai_family = AF_UNSPEC;
356
236
    hints.ai_socktype = SOCK_DGRAM;
357
236
    int error = UA_getaddrinfo(hostname, portStr, &hints, info);
358
236
    if(error != 0) {
359
#ifdef UA_ARCHITECTURE_WIN32
360
        UA_LOG_SOCKET_ERRNO_GAI_WRAP(
361
            UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
362
                           "UDP\t| Lookup of %s failed with error %d - %s",
363
                           hostname, error, errno_str));
364
#else
365
0
        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
366
0
                       "UDP\t| Lookup of %s failed with error %s",
367
0
                       hostname, gai_strerror(error));
368
0
#endif
369
0
        return -1;
370
0
    }
371
236
    return 1;
372
236
}
373
374
/* Set loop back data to your host */
375
static UA_StatusCode
376
setLoopBackData(UA_SOCKET sockfd, UA_Boolean enableLoopback,
377
0
                int ai_family, const UA_Logger *logger) {
378
0
    UA_RESET_ERRNO;
379
    /* The loopback option has a different integer size between IPv4 and IPv6.
380
     * Some operating systems (e.g. OpenBSD) handle this very strict. Hence the
381
     * different "enable" variables below are required. */
382
0
    int retcode;
383
0
#if UA_IPV6
384
0
    if(ai_family == AF_INET6) {
385
0
        unsigned int enable6 = enableLoopback;
386
0
        retcode = UA_setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
387
0
                                &enable6, sizeof(enable6));
388
0
    } else
389
0
#endif
390
0
    {
391
0
        unsigned char enable = enableLoopback;
392
0
        retcode = UA_setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_LOOP,
393
0
                                &enable, sizeof (enable));
394
0
    }
395
0
    if(retcode < 0) {
396
0
        UA_LOG_SOCKET_ERRNO_WRAP(
397
0
            UA_LOG_ERROR(logger, UA_LOGCATEGORY_NETWORK,
398
0
                         "UDP %u\t| Loopback setup failed: "
399
0
                         "Cannot set socket option IP_MULTICAST_LOOP. Error: %s",
400
0
                         (unsigned)sockfd, errno_str));
401
0
        return UA_STATUSCODE_BADINTERNALERROR;
402
0
    }
403
0
    return UA_STATUSCODE_GOOD;
404
0
}
405
406
static UA_StatusCode
407
setTimeToLive(UA_SOCKET sockfd, UA_UInt32 messageTTL,
408
472
              int ai_family, const UA_Logger *logger) {
409
472
    UA_RESET_ERRNO;
410
    /* Set Time to live (TTL). Value of 1 prevent forward beyond the local network. */
411
472
#if UA_IPV6
412
472
    if(UA_setsockopt(sockfd,
413
472
                     ai_family == PF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP,
414
472
                     ai_family == PF_INET6 ? IPV6_MULTICAST_HOPS : IP_MULTICAST_TTL,
415
472
                     (const char *)&messageTTL,
416
472
                     sizeof(messageTTL)) < 0)
417
#else
418
    if(UA_setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL,
419
                     (const char *)&messageTTL,
420
                     sizeof(messageTTL)) < 0)
421
#endif
422
0
    {
423
0
        UA_LOG_SOCKET_ERRNO_WRAP(
424
0
            UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
425
0
                           "UDP %u\t| Time to live setup failed: "
426
0
                           "Cannot set socket option IP_MULTICAST_TTL. Error: %s",
427
0
                           (unsigned)sockfd, errno_str));
428
0
        return UA_STATUSCODE_BADINTERNALERROR;
429
0
    }
430
472
    return UA_STATUSCODE_GOOD;
431
472
}
432
433
static UA_StatusCode
434
472
setReuseAddress(UA_SOCKET sockfd, UA_Boolean enableReuse, const UA_Logger *logger) {
435
    /* Set reuse address -> enables sharing of the same listening address on
436
     * different sockets */
437
472
    UA_RESET_ERRNO;
438
472
    int enableReuseVal = (enableReuse) ? 1 : 0;
439
472
    if(UA_setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
440
472
                     (const char*)&enableReuseVal, sizeof(enableReuseVal)) < 0) {
441
0
        UA_LOG_SOCKET_ERRNO_WRAP(
442
0
            UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
443
0
                           "UDP %u\t| Reuse address setup failed: "
444
0
                           "Cannot set socket option SO_REUSEADDR. Error: %s",
445
0
                           (unsigned)sockfd, errno_str));
446
0
        return UA_STATUSCODE_BADINTERNALERROR;
447
0
    }
448
472
    return UA_STATUSCODE_GOOD;
449
472
}
450
451
#ifdef __linux__
452
static UA_StatusCode
453
setSocketPriority(UA_SOCKET sockfd, UA_UInt32 socketPriority,
454
0
                  const UA_Logger *logger) {
455
0
    UA_RESET_ERRNO;
456
0
    int prio = (int)socketPriority;
457
0
    if(UA_setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &prio, sizeof(int)) < 0) {
458
0
        UA_LOG_SOCKET_ERRNO_WRAP(
459
0
            UA_LOG_ERROR(logger, UA_LOGCATEGORY_NETWORK,
460
0
                         "UDP %u\t| Socket priority setup failed: "
461
0
                         "Cannot set socket option SO_PRIORITY. Error: %s",
462
0
                         (unsigned)sockfd, errno_str));
463
0
        return UA_STATUSCODE_BADINTERNALERROR;
464
0
    }
465
0
    return UA_STATUSCODE_GOOD;
466
0
}
467
#endif
468
469
static UA_StatusCode
470
setConnectionConfig(UA_FD socket, const UA_KeyValueMap *params,
471
472
                    int ai_family, const UA_Logger *logger) {
472
    /* Set socket config that is always set */
473
472
    UA_StatusCode res = UA_STATUSCODE_GOOD;
474
472
    res |= UA_EventLoopPOSIX_setNonBlocking(socket);
475
472
    res |= UA_EventLoopPOSIX_setNoSigPipe(socket);
476
472
    if(res != UA_STATUSCODE_GOOD)
477
0
        return res;
478
479
    /* Some Linux distributions have net.ipv6.bindv6only not activated. So
480
     * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
481
     * AF_INET6 sockets only for IPv6. */
482
472
#if UA_IPV6
483
472
    int optval = 1;
484
472
    if(ai_family == AF_INET6 &&
485
0
       UA_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY,
486
0
                     (const char*)&optval, sizeof(optval)) == -1) {
487
0
        UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
488
0
                       "UDP %u\t| Could not set an IPv6 socket to IPv6 only, closing",
489
0
                       (unsigned)socket);
490
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
491
0
    }
492
472
#endif
493
494
472
    UA_RESET_ERRNO;
495
496
    /* Set socket settings from the parameters */
497
472
    const UA_UInt32 *messageTTL = (const UA_UInt32*)
498
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_TTL].name,
499
472
                                 &UA_TYPES[UA_TYPES_UINT32]);
500
472
    if(messageTTL)
501
472
        res |= setTimeToLive(socket, *messageTTL, ai_family, logger);
502
503
472
    const UA_Boolean *enableLoopback = (const UA_Boolean*)
504
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_LOOPBACK].name,
505
472
                                 &UA_TYPES[UA_TYPES_BOOLEAN]);
506
472
    if(enableLoopback)
507
0
        res |= setLoopBackData(socket, *enableLoopback, ai_family, logger);
508
509
472
    const UA_Boolean *enableReuse = (const UA_Boolean*)
510
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_REUSE].name,
511
472
                                 &UA_TYPES[UA_TYPES_BOOLEAN]);
512
472
    if(enableReuse)
513
472
        res |= setReuseAddress(socket, *enableReuse, logger);
514
515
472
#ifdef __linux__
516
472
    const UA_UInt32 *socketPriority = (const UA_UInt32*)
517
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_SOCKPRIO].name,
518
472
                                 &UA_TYPES[UA_TYPES_UINT32]);
519
472
    if(socketPriority)
520
0
        res |= setSocketPriority(socket, *socketPriority, logger);
521
472
#endif
522
523
472
    if(res != UA_STATUSCODE_GOOD) {
524
0
        UA_LOG_SOCKET_ERRNO_WRAP(
525
0
            UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
526
0
                           "UDP\t| Could not set socket options: %s", errno_str));
527
0
    }
528
472
    return res;
529
472
}
530
531
static UA_StatusCode
532
setupListenMultiCast(UA_FD fd, struct addrinfo *info, const UA_KeyValueMap *params,
533
236
                     MultiCastType multiCastType, const UA_Logger *logger) {
534
236
    MulticastRequest req;
535
236
    UA_StatusCode res = setupMulticastRequest(fd, &req, params, info, logger);
536
236
    if(res != UA_STATUSCODE_GOOD)
537
0
        return res;
538
539
236
    UA_RESET_ERRNO;
540
236
    int result = -1;
541
236
    if(info->ai_family == AF_INET && multiCastType == MULTICASTTYPE_IPV4) {
542
236
        result = UA_setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
543
236
                               &req.ipv4, sizeof(req.ipv4));
544
236
#if UA_IPV6
545
236
    } else if(info->ai_family == AF_INET6 && multiCastType == MULTICASTTYPE_IPV6) {
546
0
        result = UA_setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
547
0
                               &req.ipv6, sizeof(req.ipv6));
548
0
#endif
549
0
    }
550
551
236
    if(result < 0) {
552
0
        UA_LOG_SOCKET_ERRNO_WRAP(
553
0
            UA_LOG_ERROR(logger, UA_LOGCATEGORY_NETWORK,
554
0
                         "UDP %u\t| Cannot set socket for multicast receiving. Error: %s",
555
0
                         (unsigned)fd, errno_str));
556
0
        return UA_STATUSCODE_BADINTERNALERROR;
557
0
    }
558
236
    return UA_STATUSCODE_GOOD;
559
236
}
560
561
static UA_StatusCode
562
setupSendMultiCast(UA_FD fd, struct addrinfo *info, const UA_KeyValueMap *params,
563
236
                   MultiCastType multiCastType, const UA_Logger *logger) {
564
236
    MulticastRequest req;
565
236
    UA_StatusCode res = setupMulticastRequest(fd, &req, params, info, logger);
566
236
    if(res != UA_STATUSCODE_GOOD)
567
0
        return res;
568
569
236
    UA_RESET_ERRNO;
570
236
    int result = -1;
571
236
    if(info->ai_family == AF_INET && multiCastType == MULTICASTTYPE_IPV4) {
572
#ifdef UA_ARCHITECTURE_WIN32
573
        result = UA_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
574
                            (const char *)&req.ipv4.imr_interface,
575
                            sizeof(struct in_addr));
576
#elif defined(__APPLE__)
577
        result = UA_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
578
                            &req.ipv4.imr_interface, sizeof(struct in_addr));
579
#else
580
236
        result = UA_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
581
236
                            &req.ipv4, sizeof(req.ipv4));
582
236
#endif
583
236
#if UA_IPV6
584
236
    } else if(info->ai_family == AF_INET6 && multiCastType == MULTICASTTYPE_IPV6) {
585
0
        result = UA_setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
586
0
                            (const char *)
587
0
                            &req.ipv6.ipv6mr_interface, sizeof(req.ipv6.ipv6mr_interface));
588
0
#endif
589
0
    }
590
591
236
    if(result < 0) {
592
0
        UA_LOG_SOCKET_ERRNO_WRAP(
593
0
            UA_LOG_ERROR(logger, UA_LOGCATEGORY_NETWORK,
594
0
                         "UDP %u\t| Cannot set socket for multicast sending. Error: %s",
595
0
                         (unsigned)fd, errno_str));
596
0
        return UA_STATUSCODE_BADINTERNALERROR;
597
0
    }
598
236
    return UA_STATUSCODE_GOOD;
599
236
}
600
601
/* Test if the ConnectionManager can be stopped */
602
static void
603
9.87k
UDP_checkStopped(UA_POSIXConnectionManager *pcm) {
604
9.87k
    UA_LOCK_ASSERT(&((UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop)->elMutex);
605
606
9.87k
    if(pcm->fdsSize == 0 &&
607
9.63k
       pcm->cm.eventSource.state == UA_EVENTSOURCESTATE_STOPPING) {
608
9.39k
        UA_LOG_DEBUG(pcm->cm.eventSource.eventLoop->logger, UA_LOGCATEGORY_NETWORK,
609
9.39k
                     "UDP\t| All sockets closed, the EventLoop has stopped");
610
9.39k
        pcm->cm.eventSource.state = UA_EVENTSOURCESTATE_STOPPED;
611
9.39k
    }
612
9.87k
}
613
614
/* This method must not be called from the application directly, but from within
615
 * the EventLoop. Otherwise we cannot be sure whether the file descriptor is
616
 * still used after calling close. */
617
static void
618
472
UDP_close(UA_POSIXConnectionManager *pcm, UDP_FD *conn) {
619
472
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop;
620
472
    UA_LOCK_ASSERT(&el->elMutex);
621
622
472
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
623
472
                 "UDP %u\t| Closing connection",
624
472
                 (unsigned)conn->rfd.fd);
625
626
    /* Deregister from the EventLoop */
627
472
    UA_EventLoopPOSIX_deregisterFD(el, &conn->rfd);
628
629
    /* Deregister internally */
630
472
    ZIP_REMOVE(UA_FDTree, &pcm->fds, &conn->rfd);
631
472
    UA_assert(pcm->fdsSize > 0);
632
472
    pcm->fdsSize--;
633
634
    /* Signal closing to the application */
635
472
    conn->applicationCB(&pcm->cm, (uintptr_t)conn->rfd.fd,
636
472
                        conn->application, &conn->context,
637
472
                        UA_CONNECTIONSTATE_CLOSING,
638
472
                        &UA_KEYVALUEMAP_NULL, UA_BYTESTRING_NULL);
639
640
    /* Close the socket */
641
472
    UA_RESET_ERRNO;
642
472
    int ret = UA_close(conn->rfd.fd);
643
472
    if(ret == 0) {
644
472
        UA_LOG_INFO(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
645
472
                    "UDP %u\t| Socket closed", (unsigned)conn->rfd.fd);
646
472
    } else {
647
0
        UA_LOG_SOCKET_ERRNO_WRAP(
648
0
           UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
649
0
                          "UDP %u\t| Could not close the socket (%s)",
650
0
                          (unsigned)conn->rfd.fd, errno_str));
651
0
    }
652
653
472
    UA_free(conn);
654
655
    /* Stop if the ucm is stopping and this was the last open socket */
656
472
    UDP_checkStopped(pcm);
657
472
}
658
659
static void
660
472
UDP_delayedClose(void *application, void *context) {
661
472
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)application;
662
472
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop;
663
472
    UDP_FD *conn = (UDP_FD*)context;
664
472
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_EVENTLOOP,
665
472
                 "UDP %u\t| Delayed closing of the connection",
666
472
                 (unsigned)conn->rfd.fd);
667
472
    UA_LOCK(&el->elMutex);
668
472
    UDP_close(pcm, conn);
669
472
    UA_UNLOCK(&el->elMutex);
670
472
}
671
672
/* Gets called when a socket receives data or closes */
673
static void
674
UDP_connectionSocketCallback(UA_POSIXConnectionManager *pcm, UDP_FD *conn,
675
0
                             short event) {
676
0
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop;
677
0
    UA_LOCK_ASSERT(&el->elMutex);
678
679
0
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
680
0
                 "UDP %u\t| Activity on the socket",
681
0
                 (unsigned)conn->rfd.fd);
682
683
0
    if(event == UA_FDEVENT_ERR) {
684
0
        UA_LOG_SOCKET_ERRNO_WRAP(
685
0
           UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
686
0
                        "UDP %u\t| recv signaled the socket was shutdown (%s)",
687
0
                        (unsigned)conn->rfd.fd, errno_str));
688
0
        UDP_close(pcm, conn);
689
0
        return;
690
0
    }
691
692
0
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
693
0
                 "UDP %u\t| Allocate receive buffer", (unsigned)conn->rfd.fd);
694
695
    /* Use the already allocated receive-buffer */
696
0
    UA_ByteString response = pcm->rxBuffer;
697
698
    /* Receive */
699
0
    UA_RESET_ERRNO;
700
0
    struct sockaddr_storage source;
701
0
#ifndef UA_ARCHITECTURE_WIN32
702
0
    socklen_t sourceSize = (socklen_t)sizeof(struct sockaddr_storage);
703
0
    ssize_t ret = UA_recvfrom(conn->rfd.fd, (char*)response.data, response.length,
704
0
                           MSG_DONTWAIT, (struct sockaddr*)&source, &sourceSize);
705
#else
706
    int sourceSize = (int)sizeof(struct sockaddr_storage);
707
    int ret = UA_recvfrom(conn->rfd.fd, (char*)response.data, (int)response.length,
708
                       MSG_DONTWAIT, (struct sockaddr*)&source, &sourceSize);
709
#endif
710
711
    /* Receive has failed */
712
0
    if(ret <= 0) {
713
0
        if(ret < 0 && UA_ERRNO == UA_INTERRUPTED)
714
0
            return;
715
716
        /* Orderly shutdown of the socket. We can immediately close as no method
717
         * "below" in the call stack will use the socket in this iteration of
718
         * the EventLoop. */
719
0
        UA_LOG_SOCKET_ERRNO_WRAP(
720
0
           UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
721
0
                        "UDP %u\t| recv signaled the socket was shutdown (%s)",
722
0
                        (unsigned)conn->rfd.fd, errno_str));
723
0
        UDP_close(pcm, conn);
724
0
        return;
725
0
    }
726
727
0
    response.length = (size_t)ret; /* Set the length of the received buffer */
728
729
    /* Extract message source and port */
730
0
    char sourceAddr[64];
731
0
    UA_UInt16 sourcePort;
732
0
    switch(source.ss_family) {
733
0
        case AF_INET:
734
0
            UA_inet_ntop(AF_INET, &((struct sockaddr_in *)&source)->sin_addr,
735
0
                    sourceAddr, 64);
736
0
            sourcePort = htons(((struct sockaddr_in *)&source)->sin_port);
737
0
            break;
738
0
        case AF_INET6:
739
0
            UA_inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)&source)->sin6_addr),
740
0
                    sourceAddr, 64);
741
0
            sourcePort = htons(((struct sockaddr_in6 *)&source)->sin6_port);
742
0
            break;
743
0
        default:
744
0
            sourceAddr[0] = 0;
745
0
            sourcePort = 0;
746
0
    }
747
748
0
    UA_String sourceAddrStr = UA_STRING(sourceAddr);
749
0
    UA_KeyValuePair kvp[2];
750
0
    kvp[0].key = UA_QUALIFIEDNAME(0, "remote-address");
751
0
    UA_Variant_setScalar(&kvp[0].value, &sourceAddrStr, &UA_TYPES[UA_TYPES_STRING]);
752
0
    kvp[1].key = UA_QUALIFIEDNAME(0, "remote-port");
753
0
    UA_Variant_setScalar(&kvp[1].value, &sourcePort, &UA_TYPES[UA_TYPES_UINT16]);
754
0
    UA_KeyValueMap kvm = {2, kvp};
755
756
0
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
757
0
                 "UDP %u\t| Received message of size %u from %s on port %u",
758
0
                 (unsigned)conn->rfd.fd, (unsigned)ret,
759
0
                 sourceAddr, sourcePort);
760
761
    /* Callback to the application layer */
762
0
    conn->applicationCB(&pcm->cm, (uintptr_t)conn->rfd.fd,
763
0
                        conn->application, &conn->context,
764
0
                        UA_CONNECTIONSTATE_ESTABLISHED,
765
0
                        &kvm, response);
766
0
}
767
768
static UA_StatusCode
769
UDP_registerListenSocket(UA_POSIXConnectionManager *pcm, UA_UInt16 port,
770
                         struct addrinfo *info, const UA_KeyValueMap *params,
771
                         void *application, void *context,
772
                         UA_ConnectionManager_connectionCallback connectionCallback,
773
236
                         UA_Boolean validate) {
774
236
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop;
775
236
    UA_LOCK_ASSERT(&el->elMutex);
776
777
    /* Get logging information */
778
236
    UA_RESET_ERRNO;
779
236
    char hoststr[UA_MAXHOSTNAME_LENGTH];
780
236
    int get_res = UA_getnameinfo(info->ai_addr, info->ai_addrlen,
781
236
                                 hoststr, sizeof(hoststr),
782
236
                                 NULL, 0, NI_NUMERICHOST);
783
236
    if(get_res != 0) {
784
0
        hoststr[0] = 0;
785
0
        UA_LOG_SOCKET_ERRNO_WRAP(
786
0
           UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
787
0
                          "UDP\t| Could not resolve the hostname (Error: %s)", errno_str));
788
0
        if(validate)
789
0
            return UA_STATUSCODE_BADCONNECTIONREJECTED;
790
0
    }
791
792
    /* Create the listen socket */
793
236
    UA_RESET_ERRNO;
794
236
    UA_FD listenSocket = UA_socket(info->ai_family, info->ai_socktype, info->ai_protocol);
795
236
    if(listenSocket == UA_INVALID_FD) {
796
0
        UA_LOG_SOCKET_ERRNO_WRAP(
797
0
           UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
798
0
                          "UDP\t| Error opening the listen socket for "
799
0
                          "\"%s\" on port %u (Error: %s)",
800
0
                          (unsigned)listenSocket, hoststr, port, errno_str));
801
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
802
0
    }
803
804
    /* Set the socket configuration per the parameters */
805
236
    UA_StatusCode res =
806
236
        setConnectionConfig(listenSocket, params,
807
236
                            info->ai_family, el->eventLoop.logger);
808
236
    if(res != UA_STATUSCODE_GOOD) {
809
0
        UA_close(listenSocket);
810
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
811
0
    }
812
813
    /* Are we going to prepare a socket for multicast? */
814
236
    MultiCastType mc = multiCastType(info);
815
816
    /* Bind socket to the address */
817
236
    UA_RESET_ERRNO;
818
#ifdef UA_ARCHITECTURE_WIN32
819
    /* On windows we need to bind the socket to INADDR_ANY before registering
820
     * for the multicast group */
821
    int ret = -1;
822
    if(mc != MULTICASTTYPE_NONE) {
823
        if(info->ai_family == AF_INET) {
824
            struct sockaddr_in *orig = (struct sockaddr_in *)info->ai_addr;
825
            struct sockaddr_in sin;
826
            memset(&sin, 0, sizeof(sin));
827
            sin.sin_family = AF_INET;
828
            sin.sin_addr.s_addr = htonl(INADDR_ANY);
829
            sin.sin_port = orig->sin_port;
830
            ret = bind(listenSocket, (struct sockaddr*)&sin, sizeof(sin));
831
        } else if(info->ai_family == AF_INET6) {
832
            struct sockaddr_in6 *orig = (struct sockaddr_in6 *)info->ai_addr;
833
            struct sockaddr_in6 sin6;
834
            memset(&sin6, 0, sizeof(sin6));
835
            sin6.sin6_family = AF_INET6;
836
            sin6.sin6_addr = in6addr_any;
837
            sin6.sin6_port = orig->sin6_port;
838
            ret = bind(listenSocket, (struct sockaddr*)&sin6, sizeof(sin6));
839
        }
840
    } else {
841
        ret = UA_bind(listenSocket, info->ai_addr, (socklen_t)info->ai_addrlen);
842
    }
843
#else
844
236
    int ret = UA_bind(listenSocket, info->ai_addr, (socklen_t)info->ai_addrlen);
845
236
#endif
846
847
    /* Get the port being used if dynamic porting was used */
848
236
    if(port == 0) {
849
0
        struct sockaddr_in sin;
850
0
        memset(&sin, 0, sizeof(sin));
851
0
        socklen_t len = sizeof(sin);
852
0
        if(getsockname(listenSocket, (struct sockaddr *)&sin, &len) != 0) {
853
0
            UA_LOG_SOCKET_ERRNO_WRAP(
854
0
                UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
855
0
                            "UDP %u\t| getsockname failed (%s)",
856
0
                            (unsigned)listenSocket, errno_str));
857
0
            UA_close(listenSocket);
858
0
            return UA_STATUSCODE_BADCONNECTIONREJECTED;
859
0
        }
860
0
        port = ntohs(sin.sin_port);
861
0
    }
862
863
236
    if(ret < 0) {
864
0
        UA_LOG_SOCKET_ERRNO_WRAP(
865
0
            UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
866
0
                           "UDP\t| Failed to bind listen socket for \"%s\" on port %u "
867
0
                           "(Error: %s)", hoststr, port, errno_str));
868
0
        UA_close(listenSocket);
869
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
870
0
    }
871
872
    /* Enable multicast if this is a multicast address */
873
236
    if(mc != MULTICASTTYPE_NONE) {
874
236
        UA_RESET_ERRNO;
875
236
        res = setupListenMultiCast(listenSocket, info, params, mc,
876
236
                                   (validate) ? NULL : el->eventLoop.logger);
877
236
        if(res != UA_STATUSCODE_GOOD) {
878
0
            if(!validate) {
879
0
                UA_LOG_SOCKET_ERRNO_GAI_WRAP(
880
0
                   UA_LOG_WARNING(pcm->cm.eventSource.eventLoop->logger,
881
0
                                  UA_LOGCATEGORY_NETWORK,
882
0
                                  "UDP\t| Failed to set up multicast for \"%s\" on port %u (%s)",
883
0
                                  hoststr, port, errno_str));
884
0
            } else {
885
0
                UA_LOG_SOCKET_ERRNO_GAI_WRAP(
886
0
                   UA_LOG_WARNING(pcm->cm.eventSource.eventLoop->logger, UA_LOGCATEGORY_NETWORK,
887
0
                                  "UDP\t| Failed to validate multicast for \"%s\" on port %u (%s)",
888
0
                                  hoststr, port, errno_str));
889
0
            }
890
0
            UA_close(listenSocket);
891
0
            return res;
892
0
        }
893
236
    }
894
895
    /* Validation is complete - close and return */
896
236
    if(validate) {
897
0
        UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
898
0
                    "UDP\t| Listen socket for \"%s\" on port %u validated", hoststr, port);
899
0
        UA_close(listenSocket);
900
0
        return UA_STATUSCODE_GOOD;
901
0
    }
902
903
236
    UA_LOG_INFO(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
904
236
                "UDP %u\t| New listen socket for \"%s\" on port %u",
905
236
                (unsigned)listenSocket, hoststr, port);
906
907
    /* Allocate the UA_RegisteredFD */
908
236
    UDP_FD *newudpfd = (UDP_FD*)UA_calloc(1, sizeof(UDP_FD));
909
236
    if(!newudpfd) {
910
0
        UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
911
0
                       "UDP %u\t| Error allocating memory for the socket, closing",
912
0
                       (unsigned)listenSocket);
913
0
        UA_close(listenSocket);
914
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
915
0
    }
916
917
236
    newudpfd->rfd.fd = listenSocket;
918
236
    newudpfd->rfd.es = &pcm->cm.eventSource;
919
236
    newudpfd->rfd.listenEvents = UA_FDEVENT_IN;
920
236
    newudpfd->rfd.eventSourceCB = (UA_FDCallback)UDP_connectionSocketCallback;
921
236
    newudpfd->applicationCB = connectionCallback;
922
236
    newudpfd->application = application;
923
236
    newudpfd->context = context;
924
925
    /* Register in the EventLoop */
926
236
    res = UA_EventLoopPOSIX_registerFD(el, &newudpfd->rfd);
927
236
    if(res != UA_STATUSCODE_GOOD) {
928
0
        UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
929
0
                       "UDP %u\t| Error registering the socket, closing",
930
0
                       (unsigned)listenSocket);
931
0
        UA_free(newudpfd);
932
0
        UA_close(listenSocket);
933
0
        return res;
934
0
    }
935
936
    /* Register internally in the EventSource */
937
236
    ZIP_INSERT(UA_FDTree, &pcm->fds, &newudpfd->rfd);
938
236
    pcm->fdsSize++;
939
940
    /* Register the listen socket in the application */
941
236
    connectionCallback(&pcm->cm, (uintptr_t)newudpfd->rfd.fd,
942
236
                       application, &newudpfd->context,
943
236
                       UA_CONNECTIONSTATE_ESTABLISHED,
944
236
                       &UA_KEYVALUEMAP_NULL, UA_BYTESTRING_NULL);
945
236
    return UA_STATUSCODE_GOOD;
946
236
}
947
948
static UA_StatusCode
949
UDP_registerListenSockets(UA_POSIXConnectionManager *pcm, const char *hostname,
950
                          UA_UInt16 port, const UA_KeyValueMap *params,
951
                          void *application, void *context,
952
                          UA_ConnectionManager_connectionCallback connectionCallback,
953
236
                          UA_Boolean validate) {
954
236
    UA_LOCK_ASSERT(&((UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop)->elMutex);
955
956
    /* Get all the interface and IPv4/6 combinations for the configured hostname */
957
236
    struct addrinfo hints, *res;
958
236
    memset(&hints, 0, sizeof hints);
959
236
#if UA_IPV6
960
236
    hints.ai_family = AF_UNSPEC; /* Allow IPv4 and IPv6 */
961
#else
962
    hints.ai_family = AF_INET;   /* IPv4 only */
963
#endif
964
236
    hints.ai_socktype = SOCK_DGRAM;
965
236
    hints.ai_protocol = IPPROTO_UDP;
966
236
    hints.ai_flags = AI_PASSIVE;
967
968
    /* Set up the port string */
969
236
    char portstr[6];
970
236
    mp_snprintf(portstr, 6, "%d", port);
971
972
236
    UA_RESET_ERRNO;
973
236
    int retcode = UA_getaddrinfo(hostname, portstr, &hints, &res);
974
236
    if(retcode != 0) {
975
#ifdef UA_ARCHITECTURE_WIN32
976
        UA_LOG_SOCKET_ERRNO_GAI_WRAP(
977
           UA_LOG_WARNING(pcm->cm.eventSource.eventLoop->logger,
978
                          UA_LOGCATEGORY_NETWORK,
979
                          "UDP\t| getaddrinfo lookup for \"%s\" on port %u failed (%s)",
980
                          hostname, port, errno_str));
981
#else
982
0
        UA_LOG_WARNING(pcm->cm.eventSource.eventLoop->logger, UA_LOGCATEGORY_NETWORK,
983
0
                       "UDP\t| getaddrinfo lookup for \"%s\" on port %u failed (%s)",
984
0
                       hostname, port, gai_strerror(retcode));
985
0
#endif
986
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
987
0
    }
988
989
    /* Add listen sockets */
990
236
    struct addrinfo *ai = res;
991
236
    UA_StatusCode rv = UA_STATUSCODE_GOOD;
992
472
    while(ai) {
993
236
        rv = UDP_registerListenSocket(pcm, port, ai, params, application,
994
236
                                      context, connectionCallback, validate);
995
236
        if(rv != UA_STATUSCODE_GOOD)
996
0
            break;
997
236
        ai = ai->ai_next;
998
236
    }
999
236
    UA_freeaddrinfo(res);
1000
236
    return rv;
1001
236
}
1002
1003
/* Close the connection via a delayed callback */
1004
static void
1005
472
UDP_shutdown(UA_ConnectionManager *cm, UA_RegisteredFD *rfd) {
1006
472
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX *)cm->eventSource.eventLoop;
1007
472
    UA_LOCK_ASSERT(&el->elMutex);
1008
1009
472
    if(rfd->dc.callback) {
1010
0
        UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1011
0
                     "UDP %u\t| Cannot close - already closing",
1012
0
                     (unsigned)rfd->fd);
1013
0
        return;
1014
0
    }
1015
1016
    /* Shutdown the socket to cancel the current select/epoll */
1017
472
    UA_shutdown(rfd->fd, UA_SHUT_RDWR);
1018
1019
472
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1020
472
                 "UDP %u\t| Shutdown called", (unsigned)rfd->fd);
1021
1022
472
    UA_DelayedCallback *dc = &rfd->dc;
1023
472
    dc->callback = UDP_delayedClose;
1024
472
    dc->application = cm;
1025
472
    dc->context = rfd;
1026
1027
    /* Adding a delayed callback does not take a lock */
1028
472
    UA_EventLoopPOSIX_addDelayedCallback((UA_EventLoop*)el, dc);
1029
472
}
1030
1031
static UA_StatusCode
1032
472
UDP_shutdownConnection(UA_ConnectionManager *cm, uintptr_t connectionId) {
1033
472
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)cm;
1034
472
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX *)cm->eventSource.eventLoop;
1035
472
    UA_FD fd = (UA_FD)connectionId;
1036
1037
472
    UA_LOCK(&el->elMutex);
1038
472
    UA_RegisteredFD *rfd = ZIP_FIND(UA_FDTree, &pcm->fds, &fd);
1039
472
    if(!rfd) {
1040
0
        UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1041
0
                       "UDP\t| Cannot close UDP connection %u - not found",
1042
0
                       (unsigned)connectionId);
1043
0
        UA_UNLOCK(&el->elMutex);
1044
0
        return UA_STATUSCODE_BADNOTFOUND;
1045
0
    }
1046
472
    UDP_shutdown(cm, rfd);
1047
472
    UA_UNLOCK(&el->elMutex);
1048
472
    return UA_STATUSCODE_GOOD;
1049
472
}
1050
1051
static UA_StatusCode
1052
UDP_sendWithConnection(UA_ConnectionManager *cm, uintptr_t connectionId,
1053
                       const UA_KeyValueMap *params,
1054
0
                       UA_ByteString *buf) {
1055
0
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)cm;
1056
0
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)cm->eventSource.eventLoop;
1057
1058
0
    UA_LOCK(&el->elMutex);
1059
1060
    /* Look up the registered UDP socket */
1061
0
    UA_FD fd = (UA_FD)connectionId;
1062
0
    UDP_FD *conn = (UDP_FD*)ZIP_FIND(UA_FDTree, &pcm->fds, &fd);
1063
0
    if(!conn) {
1064
0
        UA_UNLOCK(&el->elMutex);
1065
0
        UA_EventLoopPOSIX_freeNetworkBuffer(cm, connectionId, buf);
1066
0
        return UA_STATUSCODE_BADINTERNALERROR;
1067
0
    }
1068
1069
    /* Send the full buffer. This may require several calls to send */
1070
0
    size_t nWritten = 0;
1071
0
    do {
1072
0
        ssize_t n = 0;
1073
0
        do {
1074
0
            UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1075
0
                         "UDP %u\t| Attempting to send", (unsigned)connectionId);
1076
1077
            /* Prevent OS signals when sending to a closed socket */
1078
0
            UA_RESET_ERRNO;
1079
0
            int flags = MSG_NOSIGNAL;
1080
0
            size_t bytes_to_send = buf->length - nWritten;
1081
0
            n = UA_sendto((UA_FD)connectionId, (const char*)buf->data + nWritten,
1082
0
                          bytes_to_send, flags, (struct sockaddr*)&conn->sendAddr,
1083
0
                          conn->sendAddrLength);
1084
0
            if(n < 0) {
1085
                /* An error we cannot recover from? */
1086
0
                if(UA_ERRNO != UA_INTERRUPTED &&
1087
0
                   UA_ERRNO != UA_WOULDBLOCK &&
1088
0
                   UA_ERRNO != UA_AGAIN) {
1089
0
                    UA_LOG_SOCKET_ERRNO_WRAP(
1090
0
                       UA_LOG_ERROR(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1091
0
                                    "UDP %u\t| Send failed with error %s",
1092
0
                                    (unsigned)connectionId, errno_str));
1093
0
                    UA_UNLOCK(&el->elMutex);
1094
0
                    UDP_shutdownConnection(cm, connectionId);
1095
0
                    UA_EventLoopPOSIX_freeNetworkBuffer(cm, connectionId, buf);
1096
0
                    return UA_STATUSCODE_BADCONNECTIONCLOSED;
1097
0
                }
1098
1099
                /* Poll for the socket resources to become available and retry
1100
                 * (blocking) */
1101
0
                int poll_ret;
1102
0
                struct pollfd tmp_poll_fd;
1103
0
                tmp_poll_fd.fd = (UA_FD)connectionId;
1104
0
                tmp_poll_fd.events = UA_POLLOUT;
1105
0
                do {
1106
0
                    UA_RESET_ERRNO;
1107
0
                    poll_ret = UA_poll(&tmp_poll_fd, 1, 100);
1108
0
                    if(poll_ret < 0 && UA_ERRNO != UA_INTERRUPTED) {
1109
0
                        UA_LOG_SOCKET_ERRNO_WRAP(
1110
0
                           UA_LOG_ERROR(el->eventLoop.logger,
1111
0
                                        UA_LOGCATEGORY_NETWORK,
1112
0
                                        "UDP %u\t| Send failed with error %s",
1113
0
                                        (unsigned)connectionId, errno_str));
1114
0
                        UA_EventLoopPOSIX_freeNetworkBuffer(cm, connectionId, buf);
1115
0
                        UDP_shutdown(cm, &conn->rfd);
1116
0
                        UA_UNLOCK(&el->elMutex);
1117
0
                        return UA_STATUSCODE_BADCONNECTIONCLOSED;
1118
0
                    }
1119
0
                } while(poll_ret <= 0);
1120
0
            }
1121
0
        } while(n < 0);
1122
0
        nWritten += (size_t)n;
1123
0
    } while(nWritten < buf->length);
1124
1125
    /* Free the buffer */
1126
0
    UA_UNLOCK(&el->elMutex);
1127
0
    UA_EventLoopPOSIX_freeNetworkBuffer(cm, connectionId, buf);
1128
0
    return UA_STATUSCODE_GOOD;
1129
0
}
1130
1131
static UA_StatusCode
1132
registerSocketAndDestinationForSend(const UA_KeyValueMap *params,
1133
                                    const char *hostname, struct addrinfo *info,
1134
                                    int error, UDP_FD *ufd, UA_FD *sock,
1135
236
                                    const UA_Logger *logger, UA_Boolean validate) {
1136
236
    UA_RESET_ERRNO;
1137
236
    UA_FD newSock = UA_socket(info->ai_family, info->ai_socktype, info->ai_protocol);
1138
236
    *sock = newSock;
1139
236
    if(newSock == UA_INVALID_FD) {
1140
0
        UA_LOG_SOCKET_ERRNO_WRAP(
1141
0
            UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
1142
0
                           "UDP\t| Could not create socket to connect to %s (%s)",
1143
0
                           hostname, errno_str));
1144
0
        return UA_STATUSCODE_BADDISCONNECT;
1145
0
    }
1146
236
    UA_StatusCode res = setConnectionConfig(newSock, params, info->ai_family, logger);
1147
236
    if(res != UA_STATUSCODE_GOOD) {
1148
0
        UA_close(newSock);
1149
0
        return res;
1150
0
    }
1151
1152
    /* Prepare socket for multicast */
1153
236
    MultiCastType mc = multiCastType(info);
1154
236
    if(mc != MULTICASTTYPE_NONE) {
1155
236
        res = setupSendMultiCast(newSock, info, params, mc, (validate) ? NULL : logger);
1156
236
        if(res != UA_STATUSCODE_GOOD) {
1157
0
            UA_close(newSock);
1158
0
            return res;
1159
0
        }
1160
236
    }
1161
1162
236
    memcpy(&ufd->sendAddr, info->ai_addr, info->ai_addrlen);
1163
236
    ufd->sendAddrLength = info->ai_addrlen;
1164
236
    return UA_STATUSCODE_GOOD;
1165
236
}
1166
1167
static UA_StatusCode
1168
UDP_openSendConnection(UA_POSIXConnectionManager *pcm, const UA_KeyValueMap *params,
1169
                       void *application, void *context,
1170
                       UA_ConnectionManager_connectionCallback connectionCallback,
1171
236
                       UA_Boolean validate) {
1172
236
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX *)pcm->cm.eventSource.eventLoop;
1173
236
    UA_LOCK_ASSERT(&el->elMutex);
1174
1175
    /* Get the connection parameters */
1176
236
    char hostname[UA_MAXHOSTNAME_LENGTH];
1177
236
    char portStr[UA_MAXPORTSTR_LENGTH];
1178
236
    struct addrinfo *info = NULL;
1179
1180
236
    int error = getConnectionInfoFromParams(params, hostname,
1181
236
                                            portStr, &info, el->eventLoop.logger);
1182
236
    if(error < 0 || info == NULL) {
1183
0
        if(info != NULL) {
1184
0
            UA_freeaddrinfo(info);
1185
0
        }
1186
0
        UA_LOG_ERROR(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1187
0
                     "UDP\t| Opening a connection failed");
1188
0
        return UA_STATUSCODE_BADCONNECTIONREJECTED;
1189
0
    }
1190
1191
236
    UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1192
236
                 "UDP\t| Open a connection to \"%s\" on port %s", hostname, portStr);
1193
1194
    /* Allocate the UA_RegisteredFD */
1195
236
    UDP_FD *conn = (UDP_FD*)UA_calloc(1, sizeof(UDP_FD));
1196
236
    if(!conn) {
1197
0
        UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1198
0
                       "UDP\t| Error allocating memory for the socket, closing");
1199
0
        UA_freeaddrinfo(info);
1200
0
        return UA_STATUSCODE_BADOUTOFMEMORY;
1201
0
    }
1202
1203
    /* Create a socket and register the destination address from the provided parameters */
1204
236
    UA_RESET_ERRNO;
1205
236
    UA_FD newSock = UA_INVALID_FD;
1206
236
    UA_StatusCode res =
1207
236
        registerSocketAndDestinationForSend(params, hostname, info,
1208
236
                                            error, conn, &newSock,
1209
236
                                            el->eventLoop.logger, validate);
1210
236
    UA_freeaddrinfo(info);
1211
236
    if(validate && res == UA_STATUSCODE_GOOD) {
1212
0
        UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1213
0
                     "UDP\t| Connection parameters to \"%s\" on port %s have been validated",
1214
0
                     hostname, portStr);
1215
0
        UA_close(newSock);
1216
0
        UA_free(conn);
1217
0
        return UA_STATUSCODE_GOOD;
1218
0
    }
1219
236
    if(res != UA_STATUSCODE_GOOD) {
1220
0
        if(!validate) {
1221
0
            UA_LOG_SOCKET_ERRNO_WRAP(
1222
0
                UA_LOG_ERROR(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1223
0
                             "UDP\t| Connection to \"%s\" on port %s could not be opened "
1224
0
                             "with error: %s", hostname, portStr, errno_str));
1225
0
        } else {
1226
0
            UA_LOG_SOCKET_ERRNO_WRAP(
1227
0
                UA_LOG_ERROR(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1228
0
                             "UDP\t| Invalid connection parameters to \"%s\" on "
1229
0
                             "port %s (Error: %s)", hostname, portStr, errno_str));
1230
0
        }
1231
0
        UA_free(conn);
1232
0
        return res;
1233
0
    }
1234
1235
236
    conn->rfd.fd = newSock;
1236
236
    conn->rfd.listenEvents = 0;
1237
236
    conn->rfd.es = &pcm->cm.eventSource;
1238
236
    conn->rfd.eventSourceCB = (UA_FDCallback)UDP_connectionSocketCallback;
1239
236
    conn->applicationCB = connectionCallback;
1240
236
    conn->application = application;
1241
236
    conn->context = context;
1242
1243
    /* Register the fd to trigger when output is possible (the connection is open) */
1244
236
    res = UA_EventLoopPOSIX_registerFD(el, &conn->rfd);
1245
236
    if(res != UA_STATUSCODE_GOOD) {
1246
0
        UA_LOG_WARNING(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1247
0
                       "UDP\t| Registering the socket for %s failed", hostname);
1248
0
        UA_close(newSock);
1249
0
        UA_free(conn);
1250
0
        return res;
1251
0
    }
1252
1253
    /* Register internally in the EventSource */
1254
236
    ZIP_INSERT(UA_FDTree, &pcm->fds, &conn->rfd);
1255
236
    pcm->fdsSize++;
1256
1257
236
    UA_LOG_INFO(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1258
236
                "UDP %u\t| New connection to \"%s\" on port %s",
1259
236
                (unsigned)newSock, hostname, portStr);
1260
1261
    /* Signal the connection as opening. The connection fully opens in the next
1262
     * iteration of the EventLoop */
1263
236
    connectionCallback(&pcm->cm, (uintptr_t)newSock, application,
1264
236
                       &conn->context, UA_CONNECTIONSTATE_ESTABLISHED,
1265
236
                       &UA_KEYVALUEMAP_NULL, UA_BYTESTRING_NULL);
1266
1267
236
    return UA_STATUSCODE_GOOD;
1268
236
}
1269
1270
static UA_StatusCode
1271
UDP_openReceiveConnection(UA_POSIXConnectionManager *pcm, const UA_KeyValueMap *params,
1272
                          void *application, void *context,
1273
                          UA_ConnectionManager_connectionCallback connectionCallback,
1274
236
                          UA_Boolean validate) {
1275
236
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)pcm->cm.eventSource.eventLoop;
1276
236
    UA_LOCK_ASSERT(&el->elMutex);
1277
1278
    /* Get the port */
1279
236
    const UA_UInt16 *port = (const UA_UInt16*)
1280
236
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_PORT].name,
1281
236
                                 &UA_TYPES[UA_TYPES_UINT16]);
1282
236
    UA_assert(port); /* checked before */
1283
1284
    /* Get the hostname configuration */
1285
236
    const UA_Variant *addrs =
1286
236
        UA_KeyValueMap_get(params, udpConnectionParams[UDP_PARAMINDEX_ADDR].name);
1287
236
    size_t addrsSize = 0;
1288
236
    if(addrs) {
1289
236
        UA_assert(addrs->type == &UA_TYPES[UA_TYPES_STRING]);
1290
236
        if(UA_Variant_isScalar(addrs))
1291
236
            addrsSize = 1;
1292
0
        else
1293
0
            addrsSize = addrs->arrayLength;
1294
236
    }
1295
1296
    /* No hostname configured -> listen on all interfaces */
1297
236
    if(addrsSize == 0) {
1298
0
        UA_LOG_DEBUG(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1299
0
                     "UDP\t| Listening on all interfaces");
1300
0
        return UDP_registerListenSockets(pcm, NULL, *port, params, application,
1301
0
                                         context, connectionCallback, validate);
1302
0
    }
1303
1304
    /* Iterate over the configured hostnames */
1305
236
    UA_String *hostStrings = (UA_String*)addrs->data;
1306
472
    for(size_t i = 0; i < addrsSize; i++) {
1307
236
        char hn[UA_MAXHOSTNAME_LENGTH];
1308
236
        if(hostStrings[i].length >= sizeof(hn))
1309
0
            continue;
1310
236
        memcpy(hn, hostStrings[i].data, hostStrings[i].length);
1311
236
        hn[hostStrings[i].length] = '\0';
1312
236
        UA_StatusCode rv =
1313
236
            UDP_registerListenSockets(pcm, hn, *port, params, application,
1314
236
                                      context, connectionCallback, validate);
1315
236
        if(rv != UA_STATUSCODE_GOOD)
1316
0
            return rv;
1317
236
    }
1318
1319
236
    return UA_STATUSCODE_GOOD;
1320
236
}
1321
1322
static UA_StatusCode
1323
UDP_openConnection(UA_ConnectionManager *cm, const UA_KeyValueMap *params,
1324
                   void *application, void *context,
1325
472
                   UA_ConnectionManager_connectionCallback connectionCallback) {
1326
472
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)cm;
1327
472
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)cm->eventSource.eventLoop;
1328
472
    UA_LOCK(&el->elMutex);
1329
1330
472
    if(cm->eventSource.state != UA_EVENTSOURCESTATE_STARTED) {
1331
0
        UA_LOG_ERROR(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1332
0
                     "UDP\t| Cannot open a connection for a "
1333
0
                     "ConnectionManager that is not started");
1334
0
        UA_UNLOCK(&el->elMutex);
1335
0
        return UA_STATUSCODE_BADINTERNALERROR;
1336
0
    }
1337
1338
    /* Check the parameters */
1339
472
    UA_StatusCode res =
1340
472
        UA_KeyValueRestriction_validate(el->eventLoop.logger, "UDP",
1341
472
                                        udpConnectionParams,
1342
472
                                        UDP_PARAMETERSSIZE, params);
1343
472
    if(res != UA_STATUSCODE_GOOD) {
1344
0
        UA_UNLOCK(&el->elMutex);
1345
0
        return res;
1346
0
    }
1347
1348
472
    UA_Boolean validate = false;
1349
472
    const UA_Boolean *validationValue = (const UA_Boolean*)
1350
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_VALIDATE].name,
1351
472
                                 &UA_TYPES[UA_TYPES_BOOLEAN]);
1352
472
    if(validationValue)
1353
0
        validate = *validationValue;
1354
1355
472
    UA_Boolean listen = false;
1356
472
    const UA_Boolean *listenValue = (const UA_Boolean*)
1357
472
        UA_KeyValueMap_getScalar(params, udpConnectionParams[UDP_PARAMINDEX_LISTEN].name,
1358
472
                                 &UA_TYPES[UA_TYPES_BOOLEAN]);
1359
472
    if(listenValue)
1360
472
        listen = *listenValue;
1361
1362
472
    if(listen) {
1363
236
        res = UDP_openReceiveConnection(pcm, params, application, context,
1364
236
                                        connectionCallback, validate);
1365
236
    } else {
1366
236
        res = UDP_openSendConnection(pcm, params, application, context,
1367
236
                                     connectionCallback, validate);
1368
236
    }
1369
472
    UA_UNLOCK(&el->elMutex);
1370
472
    return res;
1371
472
}
1372
1373
static UA_StatusCode
1374
9.39k
UDP_eventSourceStart(UA_ConnectionManager *cm) {
1375
9.39k
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)cm;
1376
9.39k
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)cm->eventSource.eventLoop;
1377
9.39k
    if(!el)
1378
0
        return UA_STATUSCODE_BADINTERNALERROR;
1379
1380
9.39k
    UA_LOCK(&el->elMutex);
1381
1382
    /* Check the state */
1383
9.39k
    if(cm->eventSource.state != UA_EVENTSOURCESTATE_STOPPED) {
1384
0
        UA_LOG_ERROR(el->eventLoop.logger, UA_LOGCATEGORY_NETWORK,
1385
0
                     "UDP\t| To start the ConnectionManager, "
1386
0
                     "it has to be registered in an EventLoop and not started");
1387
0
        UA_UNLOCK(&el->elMutex);
1388
0
        return UA_STATUSCODE_BADINTERNALERROR;
1389
0
    }
1390
1391
    /* Check the parameters */
1392
9.39k
    UA_StatusCode res =
1393
9.39k
        UA_KeyValueRestriction_validate(el->eventLoop.logger, "UDP",
1394
9.39k
                                        udpManagerParams, UDP_MANAGERPARAMS,
1395
9.39k
                                        &cm->eventSource.params);
1396
9.39k
    if(res != UA_STATUSCODE_GOOD)
1397
0
        goto finish;
1398
1399
    /* Allocate the rx buffer */
1400
9.39k
    res = UA_EventLoopPOSIX_allocateStaticBuffers(pcm);
1401
9.39k
    if(res != UA_STATUSCODE_GOOD)
1402
0
        goto finish;
1403
1404
    /* Set the EventSource to the started state */
1405
9.39k
    cm->eventSource.state = UA_EVENTSOURCESTATE_STARTED;
1406
1407
9.39k
 finish:
1408
9.39k
    UA_UNLOCK(&el->elMutex);
1409
9.39k
    return res;
1410
9.39k
}
1411
1412
static void *
1413
0
UDP_shutdownCB(void *application, UA_RegisteredFD *rfd) {
1414
0
    UA_ConnectionManager *cm = (UA_ConnectionManager*)application;
1415
0
    UDP_shutdown(cm, rfd);
1416
0
    return NULL;
1417
0
}
1418
1419
static void
1420
9.39k
UDP_eventSourceStop(UA_ConnectionManager *cm) {
1421
9.39k
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)cm;
1422
9.39k
    UA_EventLoopPOSIX *el = (UA_EventLoopPOSIX*)cm->eventSource.eventLoop;
1423
9.39k
    (void)el;
1424
9.39k
    UA_LOCK(&el->elMutex);
1425
1426
9.39k
    UA_LOG_DEBUG(cm->eventSource.eventLoop->logger, UA_LOGCATEGORY_NETWORK,
1427
9.39k
                 "UDP\t| Shutting down the ConnectionManager");
1428
1429
    /* Prevent new connections to open */
1430
9.39k
    cm->eventSource.state = UA_EVENTSOURCESTATE_STOPPING;
1431
1432
    /* Shutdown all existing connection */
1433
9.39k
    ZIP_ITER(UA_FDTree, &pcm->fds, UDP_shutdownCB, cm);
1434
1435
    /* Check if stopped once more (also checking inside UDP_close, but there we
1436
     * don't check if there is no rfd at all) */
1437
9.39k
    UDP_checkStopped(pcm);
1438
1439
9.39k
    UA_UNLOCK(&el->elMutex);
1440
9.39k
}
1441
1442
static UA_StatusCode
1443
18.7k
UDP_eventSourceDelete(UA_ConnectionManager *cm) {
1444
18.7k
    UA_POSIXConnectionManager *pcm = (UA_POSIXConnectionManager*)cm;
1445
18.7k
    if(cm->eventSource.state >= UA_EVENTSOURCESTATE_STARTING) {
1446
0
        UA_LOG_ERROR(cm->eventSource.eventLoop->logger, UA_LOGCATEGORY_EVENTLOOP,
1447
0
                     "UDP\t| The EventSource must be stopped before it can be deleted");
1448
0
        return UA_STATUSCODE_BADINTERNALERROR;
1449
0
    }
1450
1451
18.7k
    UA_ByteString_clear(&pcm->rxBuffer);
1452
18.7k
    UA_ByteString_clear(&pcm->txBuffer);
1453
18.7k
    UA_KeyValueMap_clear(&cm->eventSource.params);
1454
18.7k
    UA_String_clear(&cm->eventSource.name);
1455
18.7k
    UA_free(cm);
1456
1457
18.7k
    return UA_STATUSCODE_GOOD;
1458
18.7k
}
1459
1460
static const char *udpName = "udp";
1461
1462
UA_ConnectionManager *
1463
18.7k
UA_ConnectionManager_new_POSIX_UDP(const UA_String eventSourceName) {
1464
18.7k
    UA_POSIXConnectionManager *cm = (UA_POSIXConnectionManager*)
1465
18.7k
        UA_calloc(1, sizeof(UA_POSIXConnectionManager));
1466
18.7k
    if(!cm)
1467
0
        return NULL;
1468
1469
18.7k
    cm->cm.eventSource.eventSourceType = UA_EVENTSOURCETYPE_CONNECTIONMANAGER;
1470
18.7k
    UA_String_copy(&eventSourceName, &cm->cm.eventSource.name);
1471
18.7k
    cm->cm.eventSource.start = (UA_StatusCode (*)(UA_EventSource *))UDP_eventSourceStart;
1472
18.7k
    cm->cm.eventSource.stop = (void (*)(UA_EventSource *))UDP_eventSourceStop;
1473
18.7k
    cm->cm.eventSource.free = (UA_StatusCode (*)(UA_EventSource *))UDP_eventSourceDelete;
1474
18.7k
    cm->cm.protocol = UA_STRING((char*)(uintptr_t)udpName);
1475
18.7k
    cm->cm.openConnection = UDP_openConnection;
1476
18.7k
    cm->cm.allocNetworkBuffer = UA_EventLoopPOSIX_allocNetworkBuffer;
1477
18.7k
    cm->cm.freeNetworkBuffer = UA_EventLoopPOSIX_freeNetworkBuffer;
1478
18.7k
    cm->cm.sendWithConnection = UDP_sendWithConnection;
1479
18.7k
    cm->cm.closeConnection = UDP_shutdownConnection;
1480
18.7k
    return &cm->cm;
1481
18.7k
}
1482
1483
#endif