Shaka Packager SDK
Loading...
Searching...
No Matches
udp_file.cc
1// Copyright 2014 Google LLC. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd
6
7#include <packager/file/udp_file.h>
8
9#include <cstdint>
10#include <limits>
11#include <memory>
12
13#if defined(OS_WIN)
14#include <ws2tcpip.h>
15#define close closesocket
16#define EINTR_CODE WSAEINTR
17#else
18#include <arpa/inet.h>
19#include <errno.h>
20#include <netinet/in.h>
21#include <string.h>
22#include <sys/socket.h>
23#include <sys/time.h>
24#include <unistd.h>
25#define INVALID_SOCKET -1
26#define EINTR_CODE EINTR
27// IP_MULTICAST_ALL has been supported since kernel version 2.6.31 but we may be
28// building on a machine that is older than that.
29#ifndef IP_MULTICAST_ALL
30#define IP_MULTICAST_ALL 49
31#endif
32#endif // defined(OS_WIN)
33
34#include <absl/log/check.h>
35#include <absl/log/log.h>
36
37#include <packager/file.h>
38#include <packager/file/udp_options.h>
39#include <packager/macros/classes.h>
40#include <packager/macros/compiler.h>
41#include <packager/macros/logging.h>
42
43namespace shaka {
44
45namespace {
46
47bool IsIpv4MulticastAddress(const struct in_addr& addr) {
48 return (ntohl(addr.s_addr) & 0xf0000000) == 0xe0000000;
49}
50
51int GetSocketErrorCode() {
52#if defined(OS_WIN)
53 return WSAGetLastError();
54#else
55 return errno;
56#endif
57}
58
59} // anonymous namespace
60
61UdpFile::UdpFile(const char* file_name)
62 : File(file_name), socket_(INVALID_SOCKET) {}
63
64UdpFile::~UdpFile() {}
65
66bool UdpFile::Close() {
67 if (socket_ != INVALID_SOCKET) {
68 close(socket_);
69 socket_ = INVALID_SOCKET;
70 }
71 delete this;
72#if defined(OS_WIN)
73 if (wsa_started_)
74 WSACleanup();
75#endif
76 return true;
77}
78
79int64_t UdpFile::Read(void* buffer, uint64_t length) {
80 DCHECK(buffer);
81 DCHECK_GE(length, 65535u)
82 << "Buffer may be too small to read entire datagram.";
83
84 if (socket_ == INVALID_SOCKET)
85 return -1;
86
87 int64_t result;
88 do {
89 result = recvfrom(socket_, reinterpret_cast<char*>(buffer),
90 static_cast<int>(length), 0, NULL, 0);
91 } while (result == -1 && GetSocketErrorCode() == EINTR_CODE);
92
93 return result;
94}
95
96int64_t UdpFile::Write(const void* buffer, uint64_t length) {
97 UNUSED(buffer);
98 UNUSED(length);
99 NOTIMPLEMENTED() << "UdpFile is unwritable!";
100 return -1;
101}
102
103void UdpFile::CloseForWriting() {
104#if defined(OS_WIN)
105 shutdown(socket_, SD_SEND);
106#else
107 shutdown(socket_, SHUT_WR);
108#endif
109}
110
111int64_t UdpFile::Size() {
112 if (socket_ == INVALID_SOCKET)
113 return -1;
114
115 return std::numeric_limits<int64_t>::max();
116}
117
118bool UdpFile::Flush() {
119 NOTIMPLEMENTED() << "UdpFile is unflushable!";
120 return false;
121}
122
123bool UdpFile::Seek(uint64_t position) {
124 UNUSED(position);
125 NOTIMPLEMENTED() << "UdpFile is unseekable!";
126 return false;
127}
128
129bool UdpFile::Tell(uint64_t* position) {
130 UNUSED(position);
131 NOTIMPLEMENTED() << "UdpFile is unseekable!";
132 return false;
133}
134
135class ScopedSocket {
136 public:
137 explicit ScopedSocket(SOCKET sock_fd) : sock_fd_(sock_fd) {}
138
139 ~ScopedSocket() {
140 if (sock_fd_ != INVALID_SOCKET)
141 close(sock_fd_);
142 }
143
144 SOCKET get() { return sock_fd_; }
145
146 SOCKET release() {
147 SOCKET socket = sock_fd_;
148 sock_fd_ = INVALID_SOCKET;
149 return socket;
150 }
151
152 private:
153 SOCKET sock_fd_;
154
155 DISALLOW_COPY_AND_ASSIGN(ScopedSocket);
156};
157
158bool UdpFile::Open() {
159#if defined(OS_WIN)
160 WSADATA wsa_data;
161 int wsa_error = WSAStartup(MAKEWORD(2, 2), &wsa_data);
162 if (wsa_error != 0) {
163 LOG(ERROR) << "Winsock start up failed with error " << wsa_error;
164 return false;
165 }
166 wsa_started_ = true;
167#endif // defined(OS_WIN)
168
169 DCHECK_EQ(INVALID_SOCKET, socket_);
170
171 std::unique_ptr<UdpOptions> options =
172 UdpOptions::ParseFromString(file_name());
173 if (!options)
174 return false;
175
176 ScopedSocket new_socket(socket(AF_INET, SOCK_DGRAM, 0));
177 if (new_socket.get() == INVALID_SOCKET) {
178 LOG(ERROR) << "Could not allocate socket, error = " << GetSocketErrorCode();
179 return false;
180 }
181
182 struct in_addr local_in_addr = {0};
183 if (inet_pton(AF_INET, options->address().c_str(), &local_in_addr) != 1) {
184 LOG(ERROR) << "Malformed IPv4 address " << options->address();
185 return false;
186 }
187
188 // TODO(kqyang): Support IPv6.
189 struct sockaddr_in local_sock_addr;
190 memset(&local_sock_addr, 0, sizeof(local_sock_addr));
191 local_sock_addr.sin_family = AF_INET;
192 local_sock_addr.sin_port = htons(options->port());
193
194 const bool is_multicast = IsIpv4MulticastAddress(local_in_addr);
195 if (is_multicast) {
196 local_sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
197 } else {
198 local_sock_addr.sin_addr = local_in_addr;
199 }
200
201 if (options->reuse()) {
202 const int optval = 1;
203 if (setsockopt(new_socket.get(), SOL_SOCKET, SO_REUSEADDR,
204 reinterpret_cast<const char*>(&optval),
205 sizeof(optval)) < 0) {
206 LOG(ERROR) << "Could not apply the SO_REUSEADDR property to the UDP "
207 "socket, error = "
208 << GetSocketErrorCode();
209 return false;
210 }
211 }
212
213 if (bind(new_socket.get(),
214 reinterpret_cast<struct sockaddr*>(&local_sock_addr),
215 sizeof(local_sock_addr)) < 0) {
216 LOG(ERROR) << "Could not bind UDP socket, error = " << GetSocketErrorCode();
217 return false;
218 }
219
220 if (is_multicast) {
221 if (options->is_source_specific_multicast()) {
222 struct ip_mreq_source source_multicast_group;
223
224 source_multicast_group.imr_multiaddr = local_in_addr;
225 if (inet_pton(AF_INET, options->interface_address().c_str(),
226 &source_multicast_group.imr_interface) != 1) {
227 LOG(ERROR) << "Malformed IPv4 interface address "
228 << options->interface_address();
229 return false;
230 }
231 if (inet_pton(AF_INET, options->source_address().c_str(),
232 &source_multicast_group.imr_sourceaddr) != 1) {
233 LOG(ERROR) << "Malformed IPv4 source specific multicast address "
234 << options->source_address();
235 return false;
236 }
237
238 if (setsockopt(new_socket.get(), IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP,
239 reinterpret_cast<const char*>(&source_multicast_group),
240 sizeof(source_multicast_group)) < 0) {
241 LOG(ERROR) << "Failed to join multicast group, error = "
242 << GetSocketErrorCode();
243 return false;
244 }
245 } else {
246 // this is a v2 join without a specific source.
247 struct ip_mreq multicast_group;
248
249 multicast_group.imr_multiaddr = local_in_addr;
250
251 if (inet_pton(AF_INET, options->interface_address().c_str(),
252 &multicast_group.imr_interface) != 1) {
253 LOG(ERROR) << "Malformed IPv4 interface address "
254 << options->interface_address();
255 return false;
256 }
257
258 if (setsockopt(new_socket.get(), IPPROTO_IP, IP_ADD_MEMBERSHIP,
259 reinterpret_cast<const char*>(&multicast_group),
260 sizeof(multicast_group)) < 0) {
261 LOG(ERROR) << "Failed to join multicast group, error = "
262 << GetSocketErrorCode();
263 return false;
264 }
265 }
266
267#if defined(__linux__)
268 // Disable IP_MULTICAST_ALL to avoid interference caused when two sockets
269 // are bound to the same port but joined to different multicast groups.
270 const int optval_zero = 0;
271 if (setsockopt(new_socket.get(), IPPROTO_IP, IP_MULTICAST_ALL,
272 reinterpret_cast<const char*>(&optval_zero),
273 sizeof(optval_zero)) < 0 &&
274 GetSocketErrorCode() != ENOPROTOOPT) {
275 LOG(ERROR) << "Failed to disable IP_MULTICAST_ALL option, error = "
276 << GetSocketErrorCode();
277 return false;
278 }
279#endif // #if defined(__linux__)
280 }
281
282 // Set timeout if needed.
283 if (options->timeout_us() != 0) {
284 struct timeval tv;
285 tv.tv_sec = options->timeout_us() / 1000000;
286 tv.tv_usec = options->timeout_us() % 1000000;
287 if (setsockopt(new_socket.get(), SOL_SOCKET, SO_RCVTIMEO,
288 reinterpret_cast<const char*>(&tv), sizeof(tv)) < 0) {
289 LOG(ERROR) << "Failed to set socket timeout, error = "
290 << GetSocketErrorCode();
291 return false;
292 }
293 }
294
295 if (options->buffer_size() > 0) {
296 const int receive_buffer_size = options->buffer_size();
297 if (setsockopt(new_socket.get(), SOL_SOCKET, SO_RCVBUF,
298 reinterpret_cast<const char*>(&receive_buffer_size),
299 sizeof(receive_buffer_size)) < 0) {
300 LOG(ERROR) << "Failed to set the maximum receive buffer size, error = "
301 << GetSocketErrorCode();
302 return false;
303 }
304 }
305
306 socket_ = new_socket.release();
307 return true;
308}
309
310} // namespace shaka
UdpFile(const char *address_and_port)
Definition udp_file.cc:61
static std::unique_ptr< UdpOptions > ParseFromString(std::string_view udp_url)
All the methods that are virtual are virtual for mocking.