]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/iputils.cc
Merge pull request #7830 from rgacogne/dnsdist-missing-completions
[thirdparty/pdns.git] / pdns / iputils.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25 #include "iputils.hh"
26 #include <sys/socket.h>
27
28 /** these functions provide a very lightweight wrapper to the Berkeley sockets API. Errors -> exceptions! */
29
30 static void RuntimeError(const boost::format& fmt)
31 {
32 throw runtime_error(fmt.str());
33 }
34
35 static void NetworkErr(const boost::format& fmt)
36 {
37 throw NetworkError(fmt.str());
38 }
39
40 int SSocket(int family, int type, int flags)
41 {
42 int ret = socket(family, type, flags);
43 if(ret < 0)
44 RuntimeError(boost::format("creating socket of type %d: %s") % family % strerror(errno));
45 return ret;
46 }
47
48 int SConnect(int sockfd, const ComboAddress& remote)
49 {
50 int ret = connect(sockfd, reinterpret_cast<const struct sockaddr*>(&remote), remote.getSocklen());
51 if(ret < 0) {
52 int savederrno = errno;
53 RuntimeError(boost::format("connecting socket to %s: %s") % remote.toStringWithPort() % strerror(savederrno));
54 }
55 return ret;
56 }
57
58 int SConnectWithTimeout(int sockfd, const ComboAddress& remote, int timeout)
59 {
60 int ret = connect(sockfd, reinterpret_cast<const struct sockaddr*>(&remote), remote.getSocklen());
61 if(ret < 0) {
62 int savederrno = errno;
63 if (savederrno == EINPROGRESS) {
64 if (timeout <= 0) {
65 return savederrno;
66 }
67
68 /* we wait until the connection has been established */
69 bool error = false;
70 bool disconnected = false;
71 int res = waitForRWData(sockfd, false, timeout, 0, &error, &disconnected);
72 if (res == 1) {
73 if (error) {
74 savederrno = 0;
75 socklen_t errlen = sizeof(savederrno);
76 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&savederrno, &errlen) == 0) {
77 NetworkErr(boost::format("connecting to %s failed: %s") % remote.toStringWithPort() % string(strerror(savederrno)));
78 }
79 else {
80 NetworkErr(boost::format("connecting to %s failed") % remote.toStringWithPort());
81 }
82 }
83 if (disconnected) {
84 NetworkErr(boost::format("%s closed the connection") % remote.toStringWithPort());
85 }
86 return 0;
87 }
88 else if (res == 0) {
89 NetworkErr(boost::format("timeout while connecting to %s") % remote.toStringWithPort());
90 } else if (res < 0) {
91 savederrno = errno;
92 NetworkErr(boost::format("waiting to connect to %s: %s") % remote.toStringWithPort() % string(strerror(savederrno)));
93 }
94 }
95 else {
96 NetworkErr(boost::format("connecting to %s: %s") % remote.toStringWithPort() % string(strerror(savederrno)));
97 }
98 }
99
100 return 0;
101 }
102
103 int SBind(int sockfd, const ComboAddress& local)
104 {
105 int ret = bind(sockfd, (struct sockaddr*)&local, local.getSocklen());
106 if(ret < 0) {
107 int savederrno = errno;
108 RuntimeError(boost::format("binding socket to %s: %s") % local.toStringWithPort() % strerror(savederrno));
109 }
110 return ret;
111 }
112
113 int SAccept(int sockfd, ComboAddress& remote)
114 {
115 socklen_t remlen = remote.getSocklen();
116
117 int ret = accept(sockfd, (struct sockaddr*)&remote, &remlen);
118 if(ret < 0)
119 RuntimeError(boost::format("accepting new connection on socket: %s") % strerror(errno));
120 return ret;
121 }
122
123 int SListen(int sockfd, int limit)
124 {
125 int ret = listen(sockfd, limit);
126 if(ret < 0)
127 RuntimeError(boost::format("setting socket to listen: %s") % strerror(errno));
128 return ret;
129 }
130
131 int SSetsockopt(int sockfd, int level, int opname, int value)
132 {
133 int ret = setsockopt(sockfd, level, opname, &value, sizeof(value));
134 if(ret < 0)
135 RuntimeError(boost::format("setsockopt for level %d and opname %d to %d failed: %s") % level % opname % value % strerror(errno));
136 return ret;
137 }
138
139 void setSocketIgnorePMTU(int sockfd)
140 {
141 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
142 #ifdef IP_PMTUDISC_OMIT
143 /* Linux 3.15+ has IP_PMTUDISC_OMIT, which discards PMTU information to prevent
144 poisoning, but still allows fragmentation if the packet size exceeds the
145 outgoing interface MTU, which is good.
146 */
147 try {
148 SSetsockopt(sockfd, IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_OMIT);
149 return;
150 }
151 catch(const std::exception& e) {
152 /* failed, let's try IP_PMTUDISC_DONT instead */
153 }
154 #endif /* IP_PMTUDISC_OMIT */
155
156 /* IP_PMTUDISC_DONT disables Path MTU discovery */
157 SSetsockopt(sockfd, IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DONT);
158 #endif /* defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT) */
159 }
160
161 bool HarvestTimestamp(struct msghdr* msgh, struct timeval* tv)
162 {
163 #ifdef SO_TIMESTAMP
164 struct cmsghdr *cmsg;
165 for (cmsg = CMSG_FIRSTHDR(msgh); cmsg != NULL; cmsg = CMSG_NXTHDR(msgh,cmsg)) {
166 if ((cmsg->cmsg_level == SOL_SOCKET) && (cmsg->cmsg_type == SO_TIMESTAMP || cmsg->cmsg_type == SCM_TIMESTAMP) &&
167 CMSG_LEN(sizeof(*tv)) == cmsg->cmsg_len) {
168 memcpy(tv, CMSG_DATA(cmsg), sizeof(*tv));
169 return true;
170 }
171 }
172 #endif
173 return false;
174 }
175 bool HarvestDestinationAddress(const struct msghdr* msgh, ComboAddress* destination)
176 {
177 destination->reset();
178 #ifdef __NetBSD__
179 struct cmsghdr* cmsg;
180 #else
181 const struct cmsghdr* cmsg;
182 #endif
183 for (cmsg = CMSG_FIRSTHDR(msgh); cmsg != NULL; cmsg = CMSG_NXTHDR(const_cast<struct msghdr*>(msgh), const_cast<struct cmsghdr*>(cmsg))) {
184 #if defined(IP_PKTINFO)
185 if ((cmsg->cmsg_level == IPPROTO_IP) && (cmsg->cmsg_type == IP_PKTINFO)) {
186 struct in_pktinfo *i = (struct in_pktinfo *) CMSG_DATA(cmsg);
187 destination->sin4.sin_addr = i->ipi_addr;
188 destination->sin4.sin_family = AF_INET;
189 return true;
190 }
191 #elif defined(IP_RECVDSTADDR)
192 if ((cmsg->cmsg_level == IPPROTO_IP) && (cmsg->cmsg_type == IP_RECVDSTADDR)) {
193 struct in_addr *i = (struct in_addr *) CMSG_DATA(cmsg);
194 destination->sin4.sin_addr = *i;
195 destination->sin4.sin_family = AF_INET;
196 return true;
197 }
198 #endif
199
200 if ((cmsg->cmsg_level == IPPROTO_IPV6) && (cmsg->cmsg_type == IPV6_PKTINFO)) {
201 struct in6_pktinfo *i = (struct in6_pktinfo *) CMSG_DATA(cmsg);
202 destination->sin6.sin6_addr = i->ipi6_addr;
203 destination->sin4.sin_family = AF_INET6;
204 return true;
205 }
206 }
207 return false;
208 }
209
210 bool IsAnyAddress(const ComboAddress& addr)
211 {
212 if(addr.sin4.sin_family == AF_INET)
213 return addr.sin4.sin_addr.s_addr == 0;
214 else if(addr.sin4.sin_family == AF_INET6)
215 return !memcmp(&addr.sin6.sin6_addr, &in6addr_any, sizeof(addr.sin6.sin6_addr));
216
217 return false;
218 }
219
220 ssize_t sendfromto(int sock, const char* data, size_t len, int flags, const ComboAddress& from, const ComboAddress& to)
221 {
222 struct msghdr msgh;
223 struct iovec iov;
224 char cbuf[256];
225
226 /* Set up iov and msgh structures. */
227 memset(&msgh, 0, sizeof(struct msghdr));
228 iov.iov_base = (void*)data;
229 iov.iov_len = len;
230 msgh.msg_iov = &iov;
231 msgh.msg_iovlen = 1;
232 msgh.msg_name = (struct sockaddr*)&to;
233 msgh.msg_namelen = to.getSocklen();
234
235 if(from.sin4.sin_family) {
236 addCMsgSrcAddr(&msgh, cbuf, &from, 0);
237 }
238 else {
239 msgh.msg_control=NULL;
240 }
241 return sendmsg(sock, &msgh, flags);
242 }
243
244 // be careful: when using this for receive purposes, make sure addr->sin4.sin_family is set appropriately so getSocklen works!
245 // be careful: when using this function for *send* purposes, be sure to set cbufsize to 0!
246 // be careful: if you don't call addCMsgSrcAddr after fillMSGHdr, make sure to set msg_control to NULL
247 void fillMSGHdr(struct msghdr* msgh, struct iovec* iov, char* cbuf, size_t cbufsize, char* data, size_t datalen, ComboAddress* addr)
248 {
249 iov->iov_base = data;
250 iov->iov_len = datalen;
251
252 memset(msgh, 0, sizeof(struct msghdr));
253
254 msgh->msg_control = cbuf;
255 msgh->msg_controllen = cbufsize;
256 msgh->msg_name = addr;
257 msgh->msg_namelen = addr->getSocklen();
258 msgh->msg_iov = iov;
259 msgh->msg_iovlen = 1;
260 msgh->msg_flags = 0;
261 }
262
263 // warning: various parts of PowerDNS assume 'truncate' will never throw
264 void ComboAddress::truncate(unsigned int bits) noexcept
265 {
266 uint8_t* start;
267 int len=4;
268 if(sin4.sin_family==AF_INET) {
269 if(bits >= 32)
270 return;
271 start = (uint8_t*)&sin4.sin_addr.s_addr;
272 len=4;
273 }
274 else {
275 if(bits >= 128)
276 return;
277 start = (uint8_t*)&sin6.sin6_addr.s6_addr;
278 len=16;
279 }
280
281 auto tozero= len*8 - bits; // if set to 22, this will clear 1 byte, as it should
282
283 memset(start + len - tozero/8, 0, tozero/8); // blot out the whole bytes on the right
284
285 auto bitsleft=tozero % 8; // 2 bits left to clear
286
287 // a b c d, to truncate to 22 bits, we just zeroed 'd' and need to zero 2 bits from c
288 // so and by '11111100', which is ~((1<<2)-1) = ~3
289 uint8_t* place = start + len - 1 - tozero/8;
290 *place &= (~((1<<bitsleft)-1));
291 }
292
293 size_t sendMsgWithOptions(int fd, const char* buffer, size_t len, const ComboAddress* dest, const ComboAddress* local, unsigned int localItf, int flags)
294 {
295 struct msghdr msgh;
296 struct iovec iov;
297 char cbuf[256];
298
299 /* Set up iov and msgh structures. */
300 memset(&msgh, 0, sizeof(struct msghdr));
301 msgh.msg_control = nullptr;
302 msgh.msg_controllen = 0;
303 if (dest) {
304 msgh.msg_name = reinterpret_cast<void*>(const_cast<ComboAddress*>(dest));
305 msgh.msg_namelen = dest->getSocklen();
306 }
307 else {
308 msgh.msg_name = nullptr;
309 msgh.msg_namelen = 0;
310 }
311
312 msgh.msg_flags = 0;
313
314 if (localItf != 0 && local) {
315 addCMsgSrcAddr(&msgh, cbuf, local, localItf);
316 }
317
318 iov.iov_base = reinterpret_cast<void*>(const_cast<char*>(buffer));
319 iov.iov_len = len;
320 msgh.msg_iov = &iov;
321 msgh.msg_iovlen = 1;
322 msgh.msg_flags = 0;
323
324 size_t sent = 0;
325 bool firstTry = true;
326
327 do {
328
329 #ifdef MSG_FASTOPEN
330 if (flags & MSG_FASTOPEN && firstTry == false) {
331 flags &= ~MSG_FASTOPEN;
332 }
333 #endif /* MSG_FASTOPEN */
334
335 ssize_t res = sendmsg(fd, &msgh, flags);
336
337 if (res > 0) {
338 size_t written = static_cast<size_t>(res);
339 sent += written;
340
341 if (sent == len) {
342 return sent;
343 }
344
345 /* partial write */
346 firstTry = false;
347 iov.iov_len -= written;
348 iov.iov_base = reinterpret_cast<void*>(reinterpret_cast<char*>(iov.iov_base) + written);
349 written = 0;
350 }
351 else if (res == 0) {
352 return res;
353 }
354 else if (res == -1) {
355 if (errno == EINTR) {
356 continue;
357 }
358 else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINPROGRESS || errno == ENOTCONN) {
359 /* EINPROGRESS might happen with non blocking socket,
360 especially with TCP Fast Open */
361 return sent;
362 }
363 else {
364 unixDie("failed in sendMsgWithTimeout");
365 }
366 }
367 }
368 while (true);
369
370 return 0;
371 }
372
373 template class NetmaskTree<bool>;
374
375 /* requires a non-blocking socket.
376 On Linux, we could use MSG_DONTWAIT on a blocking socket
377 but this is not portable.
378 */
379 bool isTCPSocketUsable(int sock)
380 {
381 int err = 0;
382 char buf = '\0';
383 size_t buf_size = sizeof(buf);
384
385 do {
386 ssize_t got = recv(sock, &buf, buf_size, MSG_PEEK);
387
388 if (got > 0) {
389 /* socket is usable, some data is even waiting to be read */
390 return true;
391 }
392 else if (got == 0) {
393 /* other end has closed the socket */
394 return false;
395 }
396 else {
397 err = errno;
398
399 if (err == EAGAIN || err == EWOULDBLOCK) {
400 /* socket is usable, no data waiting */
401 return true;
402 }
403 else {
404 if (err != EINTR) {
405 /* something is wrong, could be ECONNRESET,
406 ENOTCONN, EPIPE, but anyway this socket is
407 not usable. */
408 return false;
409 }
410 }
411 }
412 } while (err == EINTR);
413
414 return false;
415 }