Kea 1.5.0
socketsession.cc
Go to the documentation of this file.
1// Copyright (C) 2011-2016 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8
9#include <unistd.h>
10
11#include <sys/types.h>
12#include <sys/socket.h>
13#include <sys/uio.h>
14#include <sys/un.h>
15
16#include <netinet/in.h>
17
18#include <fcntl.h>
19#include <stdint.h>
20
21#include <cerrno>
22#include <csignal>
23#include <cstddef>
24#include <cstring>
25#include <cassert>
26
27#include <string>
28#include <vector>
29
30#include <boost/noncopyable.hpp>
31
33
34#include <util/buffer.h>
35
36#include <util/io/fd_share.h>
39
40using namespace std;
41
42namespace isc {
43namespace util {
44namespace io {
45
46using namespace internal;
47
48// The expected max size of the session header: 2-byte header length,
49// 6 32-bit fields, and 2 sockaddr structure. (see the SocketSessionUtility
50// overview description in the header file). sizeof sockaddr_storage
51// should be the possible max of any sockaddr structure
52const size_t DEFAULT_HEADER_BUFLEN = sizeof(uint16_t) + sizeof(uint32_t) * 6 +
53 sizeof(struct sockaddr_storage) * 2;
54
55// The allowable maximum size of data passed with the socket FD. For now
56// we use a fixed value of 65535, the largest possible size of valid DNS
57// messages. We may enlarge it or make it configurable as we see the need
58// for more flexibility.
59const int MAX_DATASIZE = 65535;
60
61// The initial buffer size for receiving socket session data in the receiver.
62// This value is the maximum message size of DNS messages carried over UDP
63// (without EDNS). In our expected usage (at the moment) this should be
64// sufficiently large (the expected data is AXFR/IXFR query or an UPDATE
65// requests. The former should be generally quite small. While the latter
66// could be large, it would often be small enough for a single UDP message).
67// If it turns out that there are many exceptions, we may want to extend
68// the class so that this value can be customized. Note that the buffer
69// will be automatically extended for longer data and this is only about
70// efficiency.
71const size_t INITIAL_BUFSIZE = 512;
72
73// The (default) socket buffer size for the forwarder and receiver. This is
74// chosen to be sufficiently large to store two full-size DNS messages. We
75// may want to customize this value in future.
77
80 struct sockaddr_un sock_un_;
81 socklen_t sock_un_len_;
82 int fd_;
84};
85
87 impl_(NULL)
88{
89 // We need to filter SIGPIPE for subsequent push(). See the class
90 // description.
91 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
92 isc_throw(Unexpected, "Failed to filter SIGPIPE: " << strerror(errno));
93 }
94
95 ForwarderImpl impl;
96 if (sizeof(impl.sock_un_.sun_path) - 1 < unix_file.length()) {
98 "File name for a UNIX domain socket is too long: " <<
99 unix_file);
100 }
101 impl.sock_un_.sun_family = AF_UNIX;
102 // the copy should be safe due to the above check, but we'd be rather
103 // paranoid about making it 100% sure even if the check has a bug (with
104 // triggering the assertion in the worse case)
105 strncpy(impl.sock_un_.sun_path, unix_file.c_str(),
106 sizeof(impl.sock_un_.sun_path));
107 assert(impl.sock_un_.sun_path[sizeof(impl.sock_un_.sun_path) - 1] == '\0');
108 impl.sock_un_len_ = offsetof(struct sockaddr_un, sun_path) +
109 unix_file.length();
110#ifdef HAVE_SA_LEN
111 impl.sock_un_.sun_len = impl.sock_un_len_;
112#endif
113 impl.fd_ = -1;
114
115 impl_ = new ForwarderImpl;
116 *impl_ = impl;
117}
118
120 if (impl_->fd_ != -1) {
121 close();
122 }
123 delete impl_;
124}
125
126void
128 if (impl_->fd_ != -1) {
129 isc_throw(BadValue, "Duplicate connect to UNIX domain "
130 "endpoint " << impl_->sock_un_.sun_path);
131 }
132
133 impl_->fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
134 if (impl_->fd_ == -1) {
135 isc_throw(SocketSessionError, "Failed to create a UNIX domain socket: "
136 << strerror(errno));
137 }
138 // Make the socket non blocking
139 int fcntl_flags = fcntl(impl_->fd_, F_GETFL, 0);
140 if (fcntl_flags != -1) {
141 fcntl_flags |= O_NONBLOCK;
142 fcntl_flags = fcntl(impl_->fd_, F_SETFL, fcntl_flags);
143 }
144 if (fcntl_flags == -1) {
145 close(); // note: this is the internal method, not ::close()
147 "Failed to make UNIX domain socket non blocking: " <<
148 strerror(errno));
149 }
150 // Ensure the socket send buffer is large enough. If we can't get the
151 // current size, simply set the sufficient size.
152 int sndbuf_size;
153 socklen_t sndbuf_size_len = sizeof(sndbuf_size);
154 if (getsockopt(impl_->fd_, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
155 &sndbuf_size_len) == -1 ||
156 sndbuf_size < SOCKSESSION_BUFSIZE) {
157 if (setsockopt(impl_->fd_, SOL_SOCKET, SO_SNDBUF, &SOCKSESSION_BUFSIZE,
158 sizeof(SOCKSESSION_BUFSIZE)) == -1) {
159 close();
161 "Failed to set send buffer size to " <<
163 }
164 }
165 if (connect(impl_->fd_, convertSockAddr(&impl_->sock_un_),
166 impl_->sock_un_len_) == -1) {
167 close();
168 isc_throw(SocketSessionError, "Failed to connect to UNIX domain "
169 "endpoint " << impl_->sock_un_.sun_path << ": " <<
170 strerror(errno));
171 }
172}
173
174void
176 if (impl_->fd_ == -1) {
177 isc_throw(BadValue, "Attempt of close before connect");
178 }
179 ::close(impl_->fd_);
180 impl_->fd_ = -1;
181}
182
183void
184SocketSessionForwarder::push(int sock, int family, int type, int protocol,
185 const struct sockaddr& local_end,
186 const struct sockaddr& remote_end,
187 const void* data, size_t data_len)
188{
189 if (impl_->fd_ == -1) {
190 isc_throw(BadValue, "Attempt of push before connect");
191 }
192 if ((local_end.sa_family != AF_INET && local_end.sa_family != AF_INET6) ||
193 (remote_end.sa_family != AF_INET && remote_end.sa_family != AF_INET6))
194 {
195 isc_throw(BadValue, "Invalid address family: must be "
196 "AF_INET or AF_INET6; " <<
197 static_cast<int>(local_end.sa_family) << ", " <<
198 static_cast<int>(remote_end.sa_family) << " given");
199 }
200 if (family != local_end.sa_family || family != remote_end.sa_family) {
201 isc_throw(BadValue, "Inconsistent address family: must be "
202 << static_cast<int>(family) << "; "
203 << static_cast<int>(local_end.sa_family) << ", "
204 << static_cast<int>(remote_end.sa_family) << " given");
205 }
206 if (data_len == 0 || data == NULL) {
207 isc_throw(BadValue, "Data for a socket session must not be empty");
208 }
209 if (data_len > MAX_DATASIZE) {
210 isc_throw(BadValue, "Invalid socket session data size: " <<
211 data_len << ", must not exceed " << MAX_DATASIZE);
212 }
213
214 if (send_fd(impl_->fd_, sock) != 0) {
215 isc_throw(SocketSessionError, "FD passing failed: " <<
216 strerror(errno));
217 }
218
219 impl_->buf_.clear();
220 // Leave the space for the header length
221 impl_->buf_.skip(sizeof(uint16_t));
222 // Socket properties: family, type, protocol
223 impl_->buf_.writeUint32(static_cast<uint32_t>(family));
224 impl_->buf_.writeUint32(static_cast<uint32_t>(type));
225 impl_->buf_.writeUint32(static_cast<uint32_t>(protocol));
226 // Local endpoint
227 impl_->buf_.writeUint32(static_cast<uint32_t>(getSALength(local_end)));
228 impl_->buf_.writeData(&local_end, getSALength(local_end));
229 // Remote endpoint
230 impl_->buf_.writeUint32(static_cast<uint32_t>(getSALength(remote_end)));
231 impl_->buf_.writeData(&remote_end, getSALength(remote_end));
232 // Data length. Must be fit uint32 due to the range check above.
233 const uint32_t data_len32 = static_cast<uint32_t>(data_len);
234 assert(data_len == data_len32); // shouldn't cause overflow.
235 impl_->buf_.writeUint32(data_len32);
236 // Write the resulting header length at the beginning of the buffer
237 impl_->buf_.writeUint16At(impl_->buf_.getLength() - sizeof(uint16_t), 0);
238
239 const struct iovec iov[2] = {
240 { const_cast<void*>(impl_->buf_.getData()), impl_->buf_.getLength() },
241 { const_cast<void*>(data), data_len }
242 };
243 const int cc = writev(impl_->fd_, iov, 2);
244 if (cc != impl_->buf_.getLength() + data_len) {
245 if (cc < 0) {
247 "Write failed in forwarding a socket session: " <<
248 strerror(errno));
249 }
251 "Incomplete write in forwarding a socket session: " << cc <<
252 "/" << (impl_->buf_.getLength() + data_len));
253 }
254}
255
256SocketSession::SocketSession(int sock, int family, int type, int protocol,
257 const sockaddr* local_end,
258 const sockaddr* remote_end,
259 const void* data, size_t data_len) :
260 sock_(sock), family_(family), type_(type), protocol_(protocol),
261 local_end_(local_end), remote_end_(remote_end),
262 data_(data), data_len_(data_len)
263{
264 if (local_end == NULL || remote_end == NULL) {
265 isc_throw(BadValue, "sockaddr must be non NULL for SocketSession");
266 }
267 if (data_len == 0) {
268 isc_throw(BadValue, "data_len must be non 0 for SocketSession");
269 }
270 if (data == NULL) {
271 isc_throw(BadValue, "data must be non NULL for SocketSession");
272 }
273}
274
276 ReceiverImpl(int fd) : fd_(fd),
281 {
282 memset(&ss_local_, 0, sizeof(ss_local_));
283 memset(&ss_remote_, 0, sizeof(ss_remote_));
284
285 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &SOCKSESSION_BUFSIZE,
286 sizeof(SOCKSESSION_BUFSIZE)) == -1) {
288 "Failed to set receive buffer size to " <<
290 }
291 }
292
293 const int fd_;
294 struct sockaddr_storage ss_local_; // placeholder for local endpoint
295 struct sockaddr* const sa_local_;
296 struct sockaddr_storage ss_remote_; // placeholder for remote endpoint
297 struct sockaddr* const sa_remote_;
298
299 // placeholder for session header and data
300 vector<uint8_t> header_buf_;
301 vector<uint8_t> data_buf_;
302};
303
305 impl_(new ReceiverImpl(fd))
306{
307}
308
310 delete impl_;
311}
312
313namespace {
314// A shortcut to throw common exception on failure of recv(2)
315void
316readFail(int actual_len, int expected_len) {
317 if (expected_len < 0) {
318 isc_throw(SocketSessionError, "Failed to receive data from "
319 "SocketSessionForwarder: " << strerror(errno));
320 }
321 isc_throw(SocketSessionError, "Incomplete data from "
322 "SocketSessionForwarder: " << actual_len << "/" <<
323 expected_len);
324}
325
326// A helper container for a (socket) file descriptor used in
327// SocketSessionReceiver::pop that ensures the socket is closed unless it
328// can be safely passed to the caller via release().
329struct ScopedSocket : boost::noncopyable {
330 ScopedSocket(int fd) : fd_(fd) {}
331 ~ScopedSocket() {
332 if (fd_ >= 0) {
333 close(fd_);
334 }
335 }
336 int release() {
337 const int fd = fd_;
338 fd_ = -1;
339 return (fd);
340 }
341 int fd_;
342};
343}
344
345SocketSession
347 ScopedSocket passed_sock(recv_fd(impl_->fd_));
348 if (passed_sock.fd_ == FD_SYSTEM_ERROR) {
349 isc_throw(SocketSessionError, "Receiving a forwarded FD failed: " <<
350 strerror(errno));
351 } else if (passed_sock.fd_ < 0) {
352 isc_throw(SocketSessionError, "No FD forwarded");
353 }
354
355 uint16_t header_len;
356 const int cc_hlen = recv(impl_->fd_, &header_len, sizeof(header_len),
357 MSG_WAITALL);
358 if (cc_hlen < sizeof(header_len)) {
359 readFail(cc_hlen, sizeof(header_len));
360 }
361 header_len = InputBuffer(&header_len, sizeof(header_len)).readUint16();
362 if (header_len > DEFAULT_HEADER_BUFLEN) {
363 isc_throw(SocketSessionError, "Too large header length: " <<
364 header_len);
365 }
366 impl_->header_buf_.clear();
367 impl_->header_buf_.resize(header_len);
368 const int cc_hdr = recv(impl_->fd_, &impl_->header_buf_[0], header_len,
369 MSG_WAITALL);
370 if (cc_hdr < header_len) {
371 readFail(cc_hdr, header_len);
372 }
373
374 InputBuffer ibuffer(&impl_->header_buf_[0], header_len);
375 try {
376 const int family = static_cast<int>(ibuffer.readUint32());
377 if (family != AF_INET && family != AF_INET6) {
379 "Unsupported address family is passed: " << family);
380 }
381 const int type = static_cast<int>(ibuffer.readUint32());
382 const int protocol = static_cast<int>(ibuffer.readUint32());
383 const socklen_t local_end_len = ibuffer.readUint32();
384 const socklen_t endpoint_minlen = (family == AF_INET) ?
385 sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
386 if (local_end_len < endpoint_minlen ||
387 local_end_len > sizeof(impl_->ss_local_)) {
388 isc_throw(SocketSessionError, "Invalid local SA length: " <<
389 local_end_len);
390 }
391 ibuffer.readData(&impl_->ss_local_, local_end_len);
392 const socklen_t remote_end_len = ibuffer.readUint32();
393 if (remote_end_len < endpoint_minlen ||
394 remote_end_len > sizeof(impl_->ss_remote_)) {
395 isc_throw(SocketSessionError, "Invalid remote SA length: " <<
396 remote_end_len);
397 }
398 ibuffer.readData(&impl_->ss_remote_, remote_end_len);
399 if (family != impl_->sa_local_->sa_family ||
400 family != impl_->sa_remote_->sa_family) {
401 isc_throw(SocketSessionError, "SA family inconsistent: " <<
402 static_cast<int>(impl_->sa_local_->sa_family) << ", " <<
403 static_cast<int>(impl_->sa_remote_->sa_family) <<
404 " given, must be " << family);
405 }
406 const size_t data_len = ibuffer.readUint32();
407 if (data_len == 0 || data_len > MAX_DATASIZE) {
409 "Invalid socket session data size: " << data_len <<
410 ", must be > 0 and <= " << MAX_DATASIZE);
411 }
412
413 impl_->data_buf_.clear();
414 impl_->data_buf_.resize(data_len);
415 const int cc_data = recv(impl_->fd_, &impl_->data_buf_[0], data_len,
416 MSG_WAITALL);
417 if (cc_data < data_len) {
418 readFail(cc_data, data_len);
419 }
420
421 return (SocketSession(passed_sock.release(), family, type, protocol,
422 impl_->sa_local_, impl_->sa_remote_,
423 &impl_->data_buf_[0], data_len));
424 } catch (const InvalidBufferPosition& ex) {
425 // We catch the case where the given header is too short and convert
426 // the exception to SocketSessionError.
427 isc_throw(SocketSessionError, "bogus socket session header: " <<
428 ex.what());
429 }
430}
431
432}
433}
434}
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown when an unexpected error condition occurs.
The InputBuffer class is a buffer abstraction for manipulating read-only data.
Definition: buffer.h:81
uint32_t readUint32()
Read an unsigned 32-bit integer in network byte order from the buffer, convert it to host byte order,...
Definition: buffer.h:162
void readData(void *data, size_t len)
Read data of the specified length from the buffer and copy it to the caller supplied buffer.
Definition: buffer.h:186
uint16_t readUint16()
Read an unsigned 16-bit integer in network byte order from the buffer, convert it to host byte order,...
Definition: buffer.h:142
A standard DNS module exception that is thrown if an out-of-range buffer operation is being performed...
Definition: buffer.h:27
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition: buffer.h:294
void writeUint16At(uint16_t data, size_t pos)
Write an unsigned 16-bit integer in host byte order at the specified position of the buffer in networ...
Definition: buffer.h:504
void writeData(const void *data, size_t len)
Copy an arbitrary length of data into the buffer.
Definition: buffer.h:547
void writeUint32(uint32_t data)
Write an unsigned 32-bit integer in host byte order into the buffer in network byte order.
Definition: buffer.h:517
void skip(size_t len)
Insert a specified length of gap at the end of the buffer.
Definition: buffer.h:426
size_t getLength() const
Return the length of data written in the buffer.
Definition: buffer.h:403
void clear()
Clear buffer content.
Definition: buffer.h:448
const void * getData() const
Return a pointer to the head of the data stored in the buffer.
Definition: buffer.h:401
An exception indicating general errors that takes place in the socket session related class objects.
virtual ~SocketSessionForwarder()
The destructor.
virtual void close()
Close the connection to the receiver.
virtual void connectToReceiver()
Establish a connection to the receiver.
SocketSessionForwarder(const std::string &unix_file)
The constructor.
virtual void push(int sock, int family, int type, int protocol, const struct sockaddr &local_end, const struct sockaddr &remote_end, const void *data, size_t data_len)
Forward a socket session to the receiver.
SocketSession pop()
Receive a socket session from the forwarder.
SocketSessionReceiver(int fd)
The constructor.
Socket session object.
SocketSession(int sock, int family, int type, int protocol, const sockaddr *local_end, const sockaddr *remote_end, const void *data, size_t data_len)
The constructor.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
Support to transfer file descriptors between processes.
const struct sockaddr * convertSockAddr(const SAType *sa)
Definition: sockaddr_util.h:41
socklen_t getSALength(const struct sockaddr &sa)
Definition: sockaddr_util.h:26
const size_t INITIAL_BUFSIZE
const int FD_SYSTEM_ERROR
Definition: fd_share.h:20
int recv_fd(const int sock)
Receives a file descriptor.
Definition: fd_share.cc:71
const size_t DEFAULT_HEADER_BUFLEN
int send_fd(const int sock, const int fd)
Sends a file descriptor.
Definition: fd_share.cc:126
const int SOCKSESSION_BUFSIZE
const int MAX_DATASIZE
Defines the logger used by the top-level component of kea-dhcp-ddns.
int fd_