]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd-network/dhcp6-network.c
Merge pull request #11025 from evverx/clang-asan
[thirdparty/systemd.git] / src / libsystemd-network / dhcp6-network.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright © 2014 Intel Corporation. All rights reserved.
4 ***/
5
6 #include <errno.h>
7 #include <netinet/in.h>
8 #include <netinet/ip6.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include <linux/if_packet.h>
15
16 #include "dhcp6-internal.h"
17 #include "dhcp6-protocol.h"
18 #include "fd-util.h"
19 #include "socket-util.h"
20
21 int dhcp6_network_bind_udp_socket(int index, struct in6_addr *local_address) {
22 union sockaddr_union src = {
23 .in6.sin6_family = AF_INET6,
24 .in6.sin6_port = htobe16(DHCP6_PORT_CLIENT),
25 .in6.sin6_scope_id = index,
26 };
27 _cleanup_close_ int s = -1;
28 int r;
29
30 assert(index > 0);
31 assert(local_address);
32
33 src.in6.sin6_addr = *local_address;
34
35 s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_UDP);
36 if (s < 0)
37 return -errno;
38
39 r = setsockopt_int(s, IPPROTO_IPV6, IPV6_V6ONLY, true);
40 if (r < 0)
41 return r;
42
43 r = setsockopt_int(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, false);
44 if (r < 0)
45 return r;
46
47 r = setsockopt_int(s, SOL_SOCKET, SO_REUSEADDR, true);
48 if (r < 0)
49 return r;
50
51 r = bind(s, &src.sa, sizeof(src.in6));
52 if (r < 0)
53 return -errno;
54
55 return TAKE_FD(s);
56 }
57
58 int dhcp6_network_send_udp_socket(int s, struct in6_addr *server_address,
59 const void *packet, size_t len) {
60 union sockaddr_union dest = {
61 .in6.sin6_family = AF_INET6,
62 .in6.sin6_port = htobe16(DHCP6_PORT_SERVER),
63 };
64 int r;
65
66 assert(server_address);
67
68 memcpy(&dest.in6.sin6_addr, server_address, sizeof(dest.in6.sin6_addr));
69
70 r = sendto(s, packet, len, 0, &dest.sa, sizeof(dest.in6));
71 if (r < 0)
72 return -errno;
73
74 return 0;
75 }