]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd-network/dhcp6-network.c
Merge pull request #1646 from keszybz/man-dnf-install
[thirdparty/systemd.git] / src / libsystemd-network / dhcp6-network.c
1 /***
2 This file is part of systemd.
3
4 Copyright (C) 2014 Intel Corporation. All rights reserved.
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <string.h>
24 #include <linux/if_packet.h>
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <netinet/ip6.h>
28 #include <netinet/in.h>
29
30 #include "socket-util.h"
31
32 #include "dhcp6-internal.h"
33 #include "dhcp6-protocol.h"
34
35 int dhcp6_network_bind_udp_socket(int index, struct in6_addr *local_address) {
36 struct in6_pktinfo pktinfo = {
37 .ipi6_ifindex = index,
38 };
39 union sockaddr_union src = {
40 .in6.sin6_family = AF_INET6,
41 .in6.sin6_port = htobe16(DHCP6_PORT_CLIENT),
42 .in6.sin6_addr = IN6ADDR_ANY_INIT,
43 };
44 _cleanup_close_ int s = -1;
45 int r, off = 0, on = 1;
46
47 if (local_address)
48 memcpy(&src.in6.sin6_addr, local_address,
49 sizeof(src.in6.sin6_addr));
50
51 s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
52 IPPROTO_UDP);
53 if (s < 0)
54 return -errno;
55
56 r = setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO, &pktinfo,
57 sizeof(pktinfo));
58 if (r < 0)
59 return -errno;
60
61 r = setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
62 if (r < 0)
63 return -errno;
64
65 r = setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &off, sizeof(off));
66 if (r < 0)
67 return -errno;
68
69 r = bind(s, &src.sa, sizeof(src.in6));
70 if (r < 0)
71 return -errno;
72
73 r = s;
74 s = -1;
75 return r;
76 }
77
78 int dhcp6_network_send_udp_socket(int s, struct in6_addr *server_address,
79 const void *packet, size_t len) {
80 union sockaddr_union dest = {
81 .in6.sin6_family = AF_INET6,
82 .in6.sin6_port = htobe16(DHCP6_PORT_SERVER),
83 };
84 int r;
85
86 assert(server_address);
87
88 memcpy(&dest.in6.sin6_addr, server_address, sizeof(dest.in6.sin6_addr));
89
90 r = sendto(s, packet, len, 0, &dest.sa, sizeof(dest.in6));
91 if (r < 0)
92 return -errno;
93
94 return 0;
95 }