pkt_filter_inet.cc 8.59 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Copyright (C) 2013 Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <config.h>
#include <dhcp/iface_mgr.h>
#include <dhcp/pkt4.h>
#include <dhcp/pkt_filter_inet.h>
19
20
#include <errno.h>
#include <cstring>
21

22
23
using namespace isc::asiolink;

24
25
26
namespace isc {
namespace dhcp {

27
28
29
30
31
32
PktFilterInet::PktFilterInet()
    : control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
      control_buf_(new char[control_buf_len_])
{
}

33
SocketInfo
34
PktFilterInet::openSocket(Iface& iface,
35
36
37
38
                          const isc::asiolink::IOAddress& addr,
                          const uint16_t port,
                          const bool receive_bcast,
                          const bool send_bcast) {
39

40
41
42
43
44
45
46
    struct sockaddr_in addr4;
    memset(&addr4, 0, sizeof(sockaddr));
    addr4.sin_family = AF_INET;
    addr4.sin_port = htons(port);

    // If we are to receive broadcast messages we have to bind
    // to "ANY" address.
47
    if (receive_bcast && iface.flag_broadcast_) {
48
49
50
51
        addr4.sin_addr.s_addr = INADDR_ANY;
    } else {
        addr4.sin_addr.s_addr = htonl(addr);
    }
52
53
54
55
56
57

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        isc_throw(SocketConfigError, "Failed to create UDP6 socket.");
    }

58
#ifdef SO_BINDTODEVICE
59
    if (receive_bcast && iface.flag_broadcast_) {
60
        // Bind to device so as we receive traffic on a specific interface.
61
62
        if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, iface.getName().c_str(),
                       iface.getName().length() + 1) < 0) {
63
64
            close(sock);
            isc_throw(SocketConfigError, "Failed to set SO_BINDTODEVICE option"
65
                      << " on socket " << sock);
66
67
        }
    }
68
#endif
69

70
    if (send_bcast && iface.flag_broadcast_) {
71
72
73
74
        // Enable sending to broadcast address.
        int flag = 1;
        if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag)) < 0) {
            close(sock);
75
76
            isc_throw(SocketConfigError, "Failed to set SO_BROADCAST option"
                      << " on socket " << sock);
77
78
79
80
81
        }
    }

    if (bind(sock, (struct sockaddr *)&addr4, sizeof(addr4)) < 0) {
        close(sock);
82
83
        isc_throw(SocketConfigError, "Failed to bind socket " << sock
                  << " to " << addr
84
85
86
87
88
89
90
91
92
93
94
95
96
                  << "/port=" << port);
    }

    // if there is no support for IP_PKTINFO, we are really out of luck
    // it will be difficult to undersand, where this packet came from
#if defined(IP_PKTINFO)
    int flag = 1;
    if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag)) != 0) {
        close(sock);
        isc_throw(SocketConfigError, "setsockopt: IP_PKTINFO: failed.");
    }
#endif

97
98
    SocketInfo sock_desc(addr, port, sock);
    return (sock_desc);
99
100
101

}

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
Pkt4Ptr
PktFilterInet::receive(const Iface& iface, const SocketInfo& socket_info) {
    struct sockaddr_in from_addr;
    uint8_t buf[IfaceMgr::RCVBUFSIZE];

    memset(&control_buf_[0], 0, control_buf_len_);
    memset(&from_addr, 0, sizeof(from_addr));

    // Initialize our message header structure.
    struct msghdr m;
    memset(&m, 0, sizeof(m));

    // Point so we can get the from address.
    m.msg_name = &from_addr;
    m.msg_namelen = sizeof(from_addr);

    struct iovec v;
    v.iov_base = static_cast<void*>(buf);
    v.iov_len = IfaceMgr::RCVBUFSIZE;
    m.msg_iov = &v;
    m.msg_iovlen = 1;

    // Getting the interface is a bit more involved.
    //
    // We set up some space for a "control message". We have
    // previously asked the kernel to give us packet
    // information (when we initialized the interface), so we
    // should get the destination address from that.
    m.msg_control = &control_buf_[0];
    m.msg_controllen = control_buf_len_;

    int result = recvmsg(socket_info.sockfd_, &m, 0);
    if (result < 0) {
        isc_throw(SocketReadError, "failed to receive UDP4 data");
    }

    // We have all data let's create Pkt4 object.
    Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(buf, result));

    pkt->updateTimestamp();

    unsigned int ifindex = iface.getIndex();

    IOAddress from(htonl(from_addr.sin_addr.s_addr));
    uint16_t from_port = htons(from_addr.sin_port);

    // Set receiving interface based on information, which socket was used to
    // receive data. OS-specific info (see os_receive4()) may be more reliable,
    // so this value may be overwritten.
    pkt->setIndex(ifindex);
    pkt->setIface(iface.getName());
    pkt->setRemoteAddr(from);
    pkt->setRemotePort(from_port);
    pkt->setLocalPort(socket_info.port_);

157
158
159
160
// In the future the OS-specific code may be abstracted to a different
// file but for now we keep it here because there is no code yet, which
// is specific to non-Linux systems.
#if defined (IP_PKTINFO) && defined (OS_LINUX)
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    struct cmsghdr* cmsg;
    struct in_pktinfo* pktinfo;
    struct in_addr to_addr;

    memset(&to_addr, 0, sizeof(to_addr));

    cmsg = CMSG_FIRSTHDR(&m);
    while (cmsg != NULL) {
        if ((cmsg->cmsg_level == IPPROTO_IP) &&
            (cmsg->cmsg_type == IP_PKTINFO)) {
            pktinfo = (struct in_pktinfo*)CMSG_DATA(cmsg);

            pkt->setIndex(pktinfo->ipi_ifindex);
            pkt->setLocalAddr(IOAddress(htonl(pktinfo->ipi_addr.s_addr)));
            break;

            // This field is useful, when we are bound to unicast
            // address e.g. 192.0.2.1 and the packet was sent to
            // broadcast. This will return broadcast address, not
            // the address we are bound to.

            // XXX: Perhaps we should uncomment this:
            // to_addr = pktinfo->ipi_spec_dst;
        }
        cmsg = CMSG_NXTHDR(&m, cmsg);
    }
187
#endif
188
189
190
191
192

    return (pkt);
}

int
193
194
PktFilterInet::send(const Iface&, uint16_t sockfd,
                    const Pkt4Ptr& pkt) {
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    memset(&control_buf_[0], 0, control_buf_len_);

    // Set the target address we're sending to.
    sockaddr_in to;
    memset(&to, 0, sizeof(to));
    to.sin_family = AF_INET;
    to.sin_port = htons(pkt->getRemotePort());
    to.sin_addr.s_addr = htonl(pkt->getRemoteAddr());

    struct msghdr m;
    // Initialize our message header structure.
    memset(&m, 0, sizeof(m));
    m.msg_name = &to;
    m.msg_namelen = sizeof(to);

    // Set the data buffer we're sending. (Using this wacky
    // "scatter-gather" stuff... we only have a single chunk
    // of data to send, so we declare a single vector entry.)
    struct iovec v;
    memset(&v, 0, sizeof(v));
    // iov_base field is of void * type. We use it for packet
    // transmission, so this buffer will not be modified.
    v.iov_base = const_cast<void *>(pkt->getBuffer().getData());
    v.iov_len = pkt->getBuffer().getLength();
    m.msg_iov = &v;
    m.msg_iovlen = 1;

222
223
224
225
// In the future the OS-specific code may be abstracted to a different
// file but for now we keep it here because there is no code yet, which
// is specific to non-Linux systems.
#if defined (IP_PKTINFO) && defined (OS_LINUX)
226
227
228
    // Setting the interface is a bit more involved.
    //
    // We have to create a "control message", and set that to
229
230
    // define the IPv4 packet information. We set the source address
    // to handle correctly interfaces with multiple addresses.
231
232
233
234
235
236
237
238
239
    m.msg_control = &control_buf_[0];
    m.msg_controllen = control_buf_len_;
    struct cmsghdr* cmsg = CMSG_FIRSTHDR(&m);
    cmsg->cmsg_level = IPPROTO_IP;
    cmsg->cmsg_type = IP_PKTINFO;
    cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
    struct in_pktinfo* pktinfo =(struct in_pktinfo *)CMSG_DATA(cmsg);
    memset(pktinfo, 0, sizeof(struct in_pktinfo));
    pktinfo->ipi_ifindex = pkt->getIndex();
240
	pktinfo->ipi_spec_dst.s_addr = htonl(pkt->getLocalAddr()); // set the source IP address
241
    m.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
242
243
#endif

244
245
246
247
    pkt->updateTimestamp();

    int result = sendmsg(sockfd, &m, 0);
    if (result < 0) {
248
249
        isc_throw(SocketWriteError, "pkt4 send failed: sendmsg() returned "
                  " with an error: " << strerror(errno));
250
251
252
253
254
255
    }

    return (result);
}


256
257
258

} // end of isc::dhcp namespace
} // end of isc namespace