Debian Codegraph @

c/src/proactor/netaddr-internal.c

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 #ifdef _WIN32
21 #ifndef _WIN32_WINNT
22 #define _WIN32_WINNT 0x0501
23 #endif
24 #if _WIN32_WINNT < 0x0501
25 #error "Proton requires Windows API support for XP or later."
26 #endif
27 #include <winsock2.h>
28 #include <Ws2tcpip.h>
29 #else
30 /* Enable POSIX features beyond c99 for modern pthread and standard strerror_r() */
31 #ifndef _POSIX_C_SOURCE
32 #define _POSIX_C_SOURCE 200809L
33 #endif
34 /* Avoid GNU extensions, in particular the incompatible alternative strerror_r() */
35 #undef _GNU_SOURCE
36 #include <netinet/in.h>
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #endif
40
41 #include "netaddr-internal.h"
42
43 #include <proton/netaddr.h>
44 #include <proton/proactor.h>
45
46 /* Common code for proactors that use the POSIX/Winsock sockaddr library for socket addresses. */
47
48 const struct sockaddr *pn_netaddr_sockaddr(const pn_netaddr_t *na) {
49 return na ? (struct sockaddr*)&na->ss : NULL;
50 }
51
52 size_t pn_netaddr_socklen(const pn_netaddr_t *na) {
53 if (!na) return 0;
54 switch (na->ss.sa.sa_family) {
55 case AF_INET: return sizeof(struct sockaddr_in);
56 case AF_INET6: return sizeof(struct sockaddr_in6);
57 default: return sizeof(na->ss);
58 }
59 }
60
61 const pn_netaddr_t *pn_netaddr_next(const pn_netaddr_t *na) {
62 return na ? na->next : NULL;
63 }
64
65 #ifndef NI_MAXHOST
66 # define NI_MAXHOST 1025
67 #endif
68
69 #ifndef NI_MAXSERV
70 # define NI_MAXSERV 32
71 #endif
72
73 int pn_netaddr_host_port(const pn_netaddr_t* na, char *host, size_t hlen, char *port, size_t plen) {
74 return getnameinfo(pn_netaddr_sockaddr(na), pn_netaddr_socklen(na),
75 host, hlen, port, plen, NI_NUMERICHOST | NI_NUMERICSERV);
76 }
77
78 int pn_netaddr_str(const pn_netaddr_t* na, char *buf, size_t len) {
79 char host[NI_MAXHOST];
80 char port[NI_MAXSERV];
81 int err = pn_netaddr_host_port(na, host, sizeof(host), port, sizeof(port));
82 if (!err) {
83 return pn_proactor_addr(buf, len, host, port);
84 } else {
85 if (buf) *buf = '\0';
86 return 0;
87 }
88 }