Debian Codegraph @

Source/Core/Common/Network.cpp

raw symbols SCIP
1 // Copyright 2014 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "Common/Network.h"
5
6 #include <algorithm>
7 #include <bit>
8 #include <string_view>
9 #include <vector>
10
11 #ifndef _WIN32
12 #include <cstring>
13 #include <netinet/in.h>
14 #include <sys/socket.h>
15 #else
16 #include <WinSock2.h>
17 #endif
18
19 #include <fmt/format.h>
20 #include <fmt/ranges.h>
21
22 #include "Common/BitUtils.h"
23 #include "Common/CommonFuncs.h"
24 #include "Common/Logging/Log.h"
25 #include "Common/Random.h"
26 #include "Common/StringUtil.h"
27 #include "Common/Swap.h"
28
29 namespace Common
30 {
31
32 static constexpr auto GetMaskFromNetworkPrefixLength(u32 network_prefix_length)
33 {
34 return (network_prefix_length == 0) ?
35 u32(0) :
36 u32(BigEndianValue(u32(-1) >> (32 - network_prefix_length)));
37 }
38
39 u32 IPv4Port::GetIPAddressValue() const
40 {
41 return std::bit_cast<Common::BigEndianValue<u32>>(ip_address);
42 }
43
44 u16 IPv4Port::GetPortValue() const
45 {
46 return std::bit_cast<Common::BigEndianValue<u16>>(port);
47 }
48
49 bool IPv4PortRange::IsMatch(IPv4Port subject) const
50 {
51 const u32 ip_u32 = subject.GetIPAddressValue();
52 const u16 port_u16 = subject.GetPortValue();
53
54 return ip_u32 >= first.GetIPAddressValue() && ip_u32 <= last.GetIPAddressValue() &&
55 port_u16 >= first.GetPortValue() && port_u16 <= last.GetPortValue();
56 }
57
58 std::string IPv4PortRange::ToString() const
59 {
60 const u32 first_ip_value = first.GetIPAddressValue();
61 const u32 last_ip_value = last.GetIPAddressValue();
62 const u32 different_bits = first_ip_value ^ last_ip_value;
63 const u32 common_high_bits = std::countl_zero(different_bits);
64
65 std::string ip_range = Common::IPAddressToString(first.ip_address);
66 if (common_high_bits == 32)
67 {
68 // Identical first and last IP.
69 }
70 else if ((last_ip_value - first_ip_value + 1) << common_high_bits == 0)
71 {
72 // An exact network range can use CIDR notation.
73 ip_range = fmt::format("{}/{}", ip_range, common_high_bits);
74 }
75 else if (common_high_bits >= 24)
76 {
77 // Only the last octet is different.
78 ip_range = fmt::format("{}-{}", ip_range, last.ip_address.back());
79 }
80 else
81 {
82 // Plainly specified range.
83 ip_range = fmt::format("{}-{}", ip_range, Common::IPAddressToString(last.ip_address));
84 }
85
86 if (first.port == 0)
87 return ip_range;
88
89 if (first.port == last.port)
90 return fmt::format("{}:{}", ip_range, first.GetPortValue());
91
92 return fmt::format("{}:{}-{}", ip_range, first.GetPortValue(), last.GetPortValue());
93 }
94
95 std::string IPAddressToString(IPAddress ip_address)
96 {
97 return fmt::format("{}", fmt::join(ip_address, "."));
98 }
99
100 std::optional<IPv4PortRange> StringToIPv4PortRange(std::string_view subject)
101 {
102 // TODO: This could be optimized and improved a lot.
103
104 auto read_pos = std::ranges::find_first_of(subject, std::string_view{"-/:"});
105
106 const auto first_ip_octets = SplitStringIntoArray<4>({subject.begin(), read_pos}, '.');
107
108 if (!first_ip_octets.has_value())
109 return std::nullopt; // Wrong number of octets.
110
111 std::optional<IPv4PortRange> result;
112 result.emplace();
113
114 for (u32 i = 0; i != result->first.ip_address.size(); ++i)
115 {
116 if (!TryParse(std::string((*first_ip_octets)[i]), &result->first.ip_address[i]))
117 return std::nullopt; // Bad octet.
118 }
119
120 if (read_pos == subject.end())
121 {
122 // Last IP and ports not specified.
123 result->last.ip_address = result->first.ip_address;
124 result->first.port = 0;
125 result->last.port = u16(-1);
126 return result;
127 }
128
129 if (*read_pos == '-')
130 {
131 // Read last IP.
132 ++read_pos;
133
134 const auto last_ip_end = std::ranges::find(read_pos, subject.end(), ':');
135 const auto last_ip_octets = SplitString({read_pos, last_ip_end}, '.');
136
137 // Copy octets from first_ip when less than 4 are specified.
138 // FYI: This currently allows for syntax like: 10.0.0.1-7.255
139 // I don't know if it's desirable or not to allow 2 or 3 octets on the last IP.
140 const std::size_t octet_share_count = 4 - last_ip_octets.size();
141
142 if (octet_share_count >= 4)
143 return std::nullopt; // Too many octets.
144
145 std::copy_n(result->first.ip_address.begin(), octet_share_count,
146 result->last.ip_address.begin());
147
148 std::size_t i = octet_share_count;
149 for (auto&& octet_str : last_ip_octets)
150 {
151 if (!TryParse(octet_str, &result->last.ip_address[i]))
152 return std::nullopt; // Bad octet.
153 ++i;
154 }
155
156 if (result->first.ip_address > result->last.ip_address)
157 return std::nullopt; // Reversed range.
158
159 read_pos = last_ip_end;
160 }
161 else if (*read_pos == '/')
162 {
163 // Read network prefix length.
164 ++read_pos;
165
166 u32 network_prefix_length{};
167 const auto [parse_end, ec] = FromChars({read_pos, subject.end()}, network_prefix_length);
168
169 if (ec != std::errc{} || network_prefix_length > 32)
170 return std::nullopt; // Bad network prefix.
171
172 read_pos += parse_end - std::to_address(read_pos); // Working around MSVC iterators..
173
174 const auto net_mask = GetMaskFromNetworkPrefixLength(network_prefix_length);
175 const auto first_ip_address_u32 = std::bit_cast<u32>(result->first.ip_address) & net_mask;
176 result->first.ip_address = std::bit_cast<IPAddress>(first_ip_address_u32);
177 result->last.ip_address = std::bit_cast<IPAddress>(first_ip_address_u32 | ~net_mask);
178 }
179 else
180 {
181 // Last IP not specified.
182 result->last.ip_address = result->first.ip_address;
183 }
184
185 if (read_pos == subject.end())
186 {
187 // Ports not specified.
188 result->first.port = 0;
189 result->last.port = u16(-1);
190 return result;
191 }
192
193 if (*read_pos != ':')
194 return std::nullopt; // Unexpected character.
195
196 u16 first_port_u16{};
197 {
198 // Read first port.
199 ++read_pos;
200
201 const auto [parse_end, ec] = FromChars({read_pos, subject.end()}, first_port_u16);
202 if (ec != std::errc{})
203 return std::nullopt; // Bad first port.
204
205 result->first.port = std::bit_cast<u16>(Common::BigEndianValue(first_port_u16));
206
207 read_pos += parse_end - std::to_address(read_pos); // Working around MSVC iterators..
208 }
209
210 if (read_pos == subject.end())
211 {
212 // Last port not specified.
213 result->last.port = result->first.port;
214 return result;
215 }
216
217 if (*read_pos != '-')
218 return std::nullopt; // Unexpected character.
219
220 u16 first_last_u16{};
221 {
222 // Read last port.
223 ++read_pos;
224
225 const auto [parse_end, ec] = FromChars({read_pos, subject.end()}, first_last_u16);
226 if (ec != std::errc{} || first_last_u16 < first_port_u16)
227 return std::nullopt; // Bad last port.
228
229 result->last.port = std::bit_cast<u16>(Common::BigEndianValue(first_last_u16));
230
231 read_pos += parse_end - std::to_address(read_pos); // Working around MSVC iterators..
232 }
233
234 if (read_pos != subject.end())
235 return std::nullopt;
236
237 return result;
238 }
239
240 MACAddress GenerateMacAddress(const MACConsumer type)
241 {
242 constexpr std::array<u8, 3> oui_bba{{0x00, 0x09, 0xbf}};
243 constexpr std::array<u8, 3> oui_ios{{0x00, 0x17, 0xab}};
244
245 MACAddress mac{};
246
247 switch (type)
248 {
249 case MACConsumer::BBA:
250 std::ranges::copy(oui_bba, mac.begin());
251 break;
252 case MACConsumer::IOS:
253 std::ranges::copy(oui_ios, mac.begin());
254 break;
255 }
256
257 // Generate the 24-bit NIC-specific portion of the MAC address.
258 Random::Generate(&mac[3], 3);
259 return mac;
260 }
261
262 std::string MacAddressToString(const MACAddress& mac)
263 {
264 return fmt::format("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", mac[0], mac[1], mac[2], mac[3],
265 mac[4], mac[5]);
266 }
267
268 std::optional<MACAddress> StringToMacAddress(std::string_view mac_string)
269 {
270 if (mac_string.empty())
271 return std::nullopt;
272
273 int x = 0;
274 MACAddress mac{};
275
276 for (size_t i = 0; i < mac_string.size() && x < (MAC_ADDRESS_SIZE * 2); ++i)
277 {
278 char c = Common::ToLower(mac_string.at(i));
279 if (c >= '0' && c <= '9')
280 {
281 mac[x / 2] |= (c - '0') << ((x & 1) ? 0 : 4);
282 ++x;
283 }
284 else if (c >= 'a' && c <= 'f')
285 {
286 mac[x / 2] |= (c - 'a' + 10) << ((x & 1) ? 0 : 4);
287 ++x;
288 }
289 }
290
291 // A valid 48-bit MAC address consists of 6 octets, where each
292 // nibble is a character in the MAC address, making 12 characters
293 // in total.
294 if (x / 2 != MAC_ADDRESS_SIZE)
295 return std::nullopt;
296
297 return std::make_optional(mac);
298 }
299
300 std::string BluetoothAddressToString(BluetoothAddress bdaddr)
301 {
302 std::ranges::reverse(bdaddr);
303 return MacAddressToString(std::bit_cast<MACAddress>(bdaddr));
304 }
305
306 std::optional<BluetoothAddress> StringToBluetoothAddress(std::string_view str)
307 {
308 auto result = StringToMacAddress(str);
309 if (!result)
310 return std::nullopt;
311 std::ranges::reverse(*result);
312 return std::bit_cast<BluetoothAddress>(*result);
313 }
314
315 EthernetHeader::EthernetHeader() = default;
316
317 EthernetHeader::EthernetHeader(u16 ether_type) : ethertype(htons(ether_type))
318 {
319 }
320
321 EthernetHeader::EthernetHeader(const MACAddress& dest, const MACAddress& src, u16 ether_type)
322 : destination(dest), source(src), ethertype(htons(ether_type))
323 {
324 }
325
326 u16 EthernetHeader::Size() const
327 {
328 return static_cast<u16>(SIZE);
329 }
330
331 IPv4Header::IPv4Header() = default;
332
333 IPv4Header::IPv4Header(u16 data_size, u8 ip_proto, const sockaddr_in& from, const sockaddr_in& to)
334 {
335 version_ihl = 0x45;
336 total_len = htons(Size() + data_size);
337 flags_fragment_offset = htons(0x4000);
338 ttl = 0x40;
339 protocol = ip_proto;
340 std::memcpy(source_addr.data(), &from.sin_addr, IPV4_ADDR_LEN);
341 std::memcpy(destination_addr.data(), &to.sin_addr, IPV4_ADDR_LEN);
342
343 header_checksum = htons(ComputeNetworkChecksum(this, Size()));
344 }
345
346 u16 IPv4Header::Size() const
347 {
348 return static_cast<u16>(SIZE);
349 }
350
351 u8 IPv4Header::DefinedSize() const
352 {
353 return (version_ihl & 0xf) * 4;
354 }
355
356 TCPHeader::TCPHeader() = default;
357
358 TCPHeader::TCPHeader(const sockaddr_in& from, const sockaddr_in& to, u32 seq, const u8* data,
359 u16 length)
360 {
361 std::memcpy(&source_port, &from.sin_port, 2);
362 std::memcpy(&destination_port, &to.sin_port, 2);
363 sequence_number = htonl(seq);
364
365 // TODO: Write flags
366 // Write data offset
367 std::memset(&properties, 0x50, 1);
368
369 window_size = 0xFFFF;
370
371 // Compute the TCP checksum with its pseudo header
372 const u32 source_addr = ntohl(from.sin_addr.s_addr);
373 const u32 destination_addr = ntohl(to.sin_addr.s_addr);
374 const u32 initial_value = (source_addr >> 16) + (source_addr & 0xFFFF) +
375 (destination_addr >> 16) + (destination_addr & 0xFFFF) + IPProto() +
376 Size() + length;
377 u32 tcp_checksum = ComputeNetworkChecksum(this, Size(), initial_value);
378 tcp_checksum += ComputeNetworkChecksum(data, length);
379 while (tcp_checksum > 0xFFFF)
380 tcp_checksum = (tcp_checksum >> 16) + (tcp_checksum & 0xFFFF);
381 checksum = htons(static_cast<u16>(tcp_checksum));
382 }
383
384 TCPHeader::TCPHeader(const sockaddr_in& from, const sockaddr_in& to, u32 seq, u32 ack, u16 flags)
385 {
386 source_port = from.sin_port;
387 destination_port = to.sin_port;
388 sequence_number = htonl(seq);
389 acknowledgement_number = htonl(ack);
390 properties = htons(flags);
391
392 window_size = 0x7c;
393 checksum = 0;
394 }
395
396 u8 TCPHeader::GetHeaderSize() const
397 {
398 return (ntohs(properties) & 0xf000) >> 10;
399 }
400
401 u16 TCPHeader::Size() const
402 {
403 return static_cast<u16>(SIZE);
404 }
405
406 u8 TCPHeader::IPProto() const
407 {
408 return static_cast<u8>(IPPROTO_TCP);
409 }
410
411 UDPHeader::UDPHeader() = default;
412
413 UDPHeader::UDPHeader(const sockaddr_in& from, const sockaddr_in& to, u16 data_length)
414 {
415 std::memcpy(&source_port, &from.sin_port, 2);
416 std::memcpy(&destination_port, &to.sin_port, 2);
417 length = htons(Size() + data_length);
418 }
419
420 u16 UDPHeader::Size() const
421 {
422 return static_cast<u16>(SIZE);
423 }
424
425 u8 UDPHeader::IPProto() const
426 {
427 return static_cast<u8>(IPPROTO_UDP);
428 }
429
430 ARPHeader::ARPHeader() = default;
431
432 ARPHeader::ARPHeader(u32 from_ip, const MACAddress& from_mac, u32 to_ip, const MACAddress& to_mac)
433 {
434 hardware_type = htons(BBA_HARDWARE_TYPE);
435 protocol_type = IPV4_HEADER_TYPE;
436 hardware_size = MAC_ADDRESS_SIZE;
437 protocol_size = IPV4_ADDR_LEN;
438 opcode = 0x200;
439 sender_ip = from_ip;
440 target_ip = to_ip;
441 targer_address = to_mac;
442 sender_address = from_mac;
443 }
444
445 u16 ARPHeader::Size() const
446 {
447 return static_cast<u16>(SIZE);
448 }
449
450 DHCPBody::DHCPBody() = default;
451
452 DHCPBody::DHCPBody(u32 transaction, const MACAddress& client_address, u32 new_ip, u32 serv_ip)
453 {
454 transaction_id = transaction;
455 message_type = DHCPConst::MESSAGE_REPLY;
456 hardware_type = BBA_HARDWARE_TYPE;
457 hardware_addr = MAC_ADDRESS_SIZE;
458 client_mac = client_address;
459 your_ip = new_ip;
460 server_ip = serv_ip;
461 }
462
463 DHCPPacket::DHCPPacket() = default;
464
465 DHCPPacket::DHCPPacket(std::span<const u8> data)
466 {
467 if (data.size() < DHCPBody::SIZE)
468 return;
469 body = Common::BitCastPtr<DHCPBody>(data.data());
470 std::size_t offset = DHCPBody::SIZE;
471
472 while (offset < data.size() - 1)
473 {
474 const u8 fnc = data[offset];
475 if (fnc == 0)
476 {
477 ++offset;
478 continue;
479 }
480 if (fnc == 255)
481 break;
482 const u8 len = data[offset + 1];
483 const auto opt_begin = data.begin() + offset;
484 offset += 2 + len;
485 if (offset > data.size())
486 break;
487 const auto opt_end = data.begin() + offset;
488 options.emplace_back(opt_begin, opt_end);
489 }
490 }
491
492 void DHCPPacket::AddOption(u8 fnc, std::span<const u8> params)
493 {
494 if (params.size() > 255)
495 return;
496 std::vector<u8> opt = {fnc, u8(params.size())};
497 opt.insert(opt.end(), params.begin(), params.end());
498 options.emplace_back(std::move(opt));
499 }
500
501 std::vector<u8> DHCPPacket::Build() const
502 {
503 const u8* body_ptr = reinterpret_cast<const u8*>(&body);
504 std::vector<u8> result(body_ptr, body_ptr + DHCPBody::SIZE);
505
506 for (auto& opt : options)
507 {
508 result.insert(result.end(), opt.begin(), opt.end());
509 }
510 constexpr auto no_option = std::to_array<u8>({255, 0, 0, 0});
511 result.insert(result.end(), no_option.begin(), no_option.end());
512
513 return result;
514 }
515
516 // Compute the network checksum with a 32-bit accumulator using the
517 // "Normal" order, see RFC 1071 for more details.
518 u16 ComputeNetworkChecksum(const void* data, u16 length, u32 initial_value)
519 {
520 u32 checksum = initial_value;
521 std::size_t index = 0;
522 const std::string_view data_view{static_cast<const char*>(data), length};
523 for (u8 b : data_view)
524 {
525 const bool is_hi = index++ % 2 == 0;
526 checksum += is_hi ? b << 8 : b;
527 }
528 while (checksum > 0xFFFF)
529 checksum = (checksum >> 16) + (checksum & 0xFFFF);
530 return ~static_cast<u16>(checksum);
531 }
532
533 // Compute the TCP checksum with its pseudo header
534 u16 ComputeTCPNetworkChecksum(const IPAddress& from, const IPAddress& to, const void* data,
535 u16 length, u8 protocol)
536 {
537 const u32 source_addr = ntohl(std::bit_cast<u32>(from));
538 const u32 destination_addr = ntohl(std::bit_cast<u32>(to));
539 const u32 initial_value = (source_addr >> 16) + (source_addr & 0xFFFF) +
540 (destination_addr >> 16) + (destination_addr & 0xFFFF) + protocol +
541 length;
542 const u32 tcp_checksum = ComputeNetworkChecksum(data, length, initial_value);
543 return htons(static_cast<u16>(tcp_checksum));
544 }
545
546 template <typename Container, typename T>
547 static inline void InsertObj(Container* container, const T& obj)
548 {
549 static_assert(std::is_trivially_copyable_v<T>);
550 const u8* const ptr = reinterpret_cast<const u8*>(&obj);
551 container->insert(container->end(), ptr, ptr + sizeof(obj));
552 }
553
554 ARPPacket::ARPPacket() = default;
555
556 u16 ARPPacket::Size() const
557 {
558 return static_cast<u16>(SIZE);
559 }
560
561 ARPPacket::ARPPacket(const MACAddress& destination, const MACAddress& source)
562 {
563 eth_header.destination = destination;
564 eth_header.source = source;
565 eth_header.ethertype = htons(ARP_ETHERTYPE);
566 }
567
568 std::vector<u8> ARPPacket::Build() const
569 {
570 std::vector<u8> result;
571 result.reserve(EthernetHeader::SIZE + ARPHeader::SIZE);
572 InsertObj(&result, eth_header);
573 InsertObj(&result, arp_header);
574 return result;
575 }
576
577 TCPPacket::TCPPacket() = default;
578
579 TCPPacket::TCPPacket(const MACAddress& destination, const MACAddress& source,
580 const sockaddr_in& from, const sockaddr_in& to, u32 seq, u32 ack, u16 flags)
581 : eth_header(destination, source, IPV4_ETHERTYPE),
582 ip_header(Common::TCPHeader::SIZE, IPPROTO_TCP, from, to),
583 tcp_header(from, to, seq, ack, flags)
584 {
585 }
586
587 std::vector<u8> TCPPacket::Build() const
588 {
589 std::vector<u8> result;
590 result.reserve(Size()); // Useful not to invalidate .data() pointers
591
592 // Copy data
593 InsertObj(&result, eth_header);
594 u8* const ip_ptr = result.data() + result.size();
595 InsertObj(&result, ip_header);
596 result.insert(result.end(), ipv4_options.begin(), ipv4_options.end());
597 u8* const tcp_ptr = result.data() + result.size();
598 InsertObj(&result, tcp_header);
599 result.insert(result.end(), tcp_options.begin(), tcp_options.end());
600 result.insert(result.end(), data.begin(), data.end());
601
602 // Adjust size and checksum fields
603 const u16 tcp_length = static_cast<u16>(TCPHeader::SIZE + tcp_options.size() + data.size());
604 const u16 tcp_properties =
605 (ntohs(tcp_header.properties) & 0xfff) |
606 (static_cast<u16>((tcp_options.size() + TCPHeader::SIZE) & 0x3c) << 10);
607 Common::BitCastPtr<u16>(tcp_ptr + offsetof(TCPHeader, properties)) = htons(tcp_properties);
608
609 const u16 ip_header_size = static_cast<u16>(IPv4Header::SIZE + ipv4_options.size());
610 const u16 ip_total_len = ip_header_size + tcp_length;
611 Common::BitCastPtr<u16>(ip_ptr + offsetof(IPv4Header, total_len)) = htons(ip_total_len);
612
613 auto ip_checksum_bitcast_ptr =
614 Common::BitCastPtr<u16>(ip_ptr + offsetof(IPv4Header, header_checksum));
615 ip_checksum_bitcast_ptr = u16(0);
616 ip_checksum_bitcast_ptr = htons(Common::ComputeNetworkChecksum(ip_ptr, ip_header_size));
617
618 auto checksum_bitcast_ptr = Common::BitCastPtr<u16>(tcp_ptr + offsetof(TCPHeader, checksum));
619 checksum_bitcast_ptr = u16(0);
620 checksum_bitcast_ptr = ComputeTCPNetworkChecksum(
621 ip_header.source_addr, ip_header.destination_addr, tcp_ptr, tcp_length, IPPROTO_TCP);
622
623 return result;
624 }
625
626 u16 TCPPacket::Size() const
627 {
628 return static_cast<u16>(MIN_SIZE + data.size() + ipv4_options.size() + tcp_options.size());
629 }
630
631 UDPPacket::UDPPacket() = default;
632
633 UDPPacket::UDPPacket(const MACAddress& destination, const MACAddress& source,
634 const sockaddr_in& from, const sockaddr_in& to, const std::vector<u8>& payload)
635 : eth_header(destination, source, IPV4_ETHERTYPE),
636 ip_header(static_cast<u16>(payload.size() + Common::UDPHeader::SIZE), IPPROTO_UDP, from, to),
637 udp_header(from, to, static_cast<u16>(payload.size())), data(payload)
638 {
639 }
640
641 std::vector<u8> UDPPacket::Build() const
642 {
643 std::vector<u8> result;
644 result.reserve(Size()); // Useful not to invalidate .data() pointers
645
646 // Copy data
647 InsertObj(&result, eth_header);
648 u8* const ip_ptr = result.data() + result.size();
649 InsertObj(&result, ip_header);
650 result.insert(result.end(), ipv4_options.begin(), ipv4_options.end());
651 u8* const udp_ptr = result.data() + result.size();
652 InsertObj(&result, udp_header);
653 result.insert(result.end(), data.begin(), data.end());
654
655 // Adjust size and checksum fields
656 const u16 udp_length = static_cast<u16>(UDPHeader::SIZE + data.size());
657 Common::BitCastPtr<u16>(udp_ptr + offsetof(UDPHeader, length)) = htons(udp_length);
658
659 const u16 ip_header_size = static_cast<u16>(IPv4Header::SIZE + ipv4_options.size());
660 const u16 ip_total_len = ip_header_size + udp_length;
661 Common::BitCastPtr<u16>(ip_ptr + offsetof(IPv4Header, total_len)) = htons(ip_total_len);
662
663 auto ip_checksum_bitcast_ptr =
664 Common::BitCastPtr<u16>(ip_ptr + offsetof(IPv4Header, header_checksum));
665 ip_checksum_bitcast_ptr = u16(0);
666 ip_checksum_bitcast_ptr = htons(Common::ComputeNetworkChecksum(ip_ptr, ip_header_size));
667
668 auto checksum_bitcast_ptr = Common::BitCastPtr<u16>(udp_ptr + offsetof(UDPHeader, checksum));
669 checksum_bitcast_ptr = u16(0);
670 checksum_bitcast_ptr = ComputeTCPNetworkChecksum(
671 ip_header.source_addr, ip_header.destination_addr, udp_ptr, udp_length, IPPROTO_UDP);
672
673 return result;
674 }
675
676 u16 UDPPacket::Size() const
677 {
678 return static_cast<u16>(MIN_SIZE + data.size() + ipv4_options.size());
679 }
680
681 PacketView::PacketView(const u8* ptr, std::size_t size) : m_ptr(ptr), m_size(size)
682 {
683 }
684
685 std::optional<u16> PacketView::GetEtherType() const
686 {
687 if (m_size < EthernetHeader::SIZE)
688 return std::nullopt;
689 const std::size_t offset = offsetof(EthernetHeader, ethertype);
690 return ntohs(Common::BitCastPtr<u16>(m_ptr + offset));
691 }
692
693 std::optional<ARPPacket> PacketView::GetARPPacket() const
694 {
695 if (m_size < ARPPacket::SIZE)
696 return std::nullopt;
697 return Common::BitCastPtr<ARPPacket>(m_ptr);
698 }
699
700 std::optional<u8> PacketView::GetIPProto() const
701 {
702 if (m_size < EthernetHeader::SIZE + IPv4Header::SIZE)
703 return std::nullopt;
704 return m_ptr[EthernetHeader::SIZE + offsetof(IPv4Header, protocol)];
705 }
706
707 std::optional<TCPPacket> PacketView::GetTCPPacket() const
708 {
709 if (m_size < TCPPacket::MIN_SIZE)
710 return std::nullopt;
711 TCPPacket result;
712 result.eth_header = Common::BitCastPtr<EthernetHeader>(m_ptr);
713 result.ip_header = Common::BitCastPtr<IPv4Header>(m_ptr + EthernetHeader::SIZE);
714 const u16 offset = result.ip_header.DefinedSize() + EthernetHeader::SIZE;
715 if (m_size < offset + TCPHeader::SIZE)
716 return std::nullopt;
717 result.ipv4_options =
718 std::vector<u8>(m_ptr + EthernetHeader::SIZE + IPv4Header::SIZE, m_ptr + offset);
719 result.tcp_header = Common::BitCastPtr<TCPHeader>(m_ptr + offset);
720 const u16 data_offset = result.tcp_header.GetHeaderSize() + offset;
721
722 const u16 total_len = ntohs(result.ip_header.total_len);
723 const std::size_t end = EthernetHeader::SIZE + total_len;
724
725 if (m_size < end || end < data_offset)
726 return std::nullopt;
727
728 result.tcp_options = std::vector<u8>(m_ptr + offset + TCPHeader::SIZE, m_ptr + data_offset);
729 result.data = std::vector<u8>(m_ptr + data_offset, m_ptr + end);
730
731 return result;
732 }
733
734 std::optional<UDPPacket> PacketView::GetUDPPacket() const
735 {
736 if (m_size < UDPPacket::MIN_SIZE)
737 return std::nullopt;
738 UDPPacket result;
739 result.eth_header = Common::BitCastPtr<EthernetHeader>(m_ptr);
740 result.ip_header = Common::BitCastPtr<IPv4Header>(m_ptr + EthernetHeader::SIZE);
741 const u16 offset = result.ip_header.DefinedSize() + EthernetHeader::SIZE;
742 if (m_size < offset + UDPHeader::SIZE)
743 return std::nullopt;
744 result.ipv4_options =
745 std::vector<u8>(m_ptr + EthernetHeader::SIZE + IPv4Header::SIZE, m_ptr + offset);
746 result.udp_header = Common::BitCastPtr<UDPHeader>(m_ptr + offset);
747 const u16 data_offset = UDPHeader::SIZE + offset;
748
749 const u16 total_len = ntohs(result.udp_header.length);
750 const std::size_t end = offset + total_len;
751
752 if (m_size < end || end < data_offset)
753 return std::nullopt;
754
755 result.data = std::vector<u8>(m_ptr + data_offset, m_ptr + end);
756
757 return result;
758 }
759
760 NetworkErrorState SaveNetworkErrorState()
761 {
762 return {
763 errno,
764 #ifdef _WIN32
765 WSAGetLastError(),
766 #endif
767 };
768 }
769
770 void RestoreNetworkErrorState(const NetworkErrorState& state)
771 {
772 errno = state.error;
773 #ifdef _WIN32
774 WSASetLastError(state.wsa_error);
775 #endif
776 }
777
778 const char* DecodeNetworkError(s32 error_code)
779 {
780 thread_local char buffer[1024];
781
782 #ifdef _WIN32
783 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
784 FORMAT_MESSAGE_MAX_WIDTH_MASK,
785 nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer,
786 sizeof(buffer), nullptr);
787 return buffer;
788 #else
789 return Common::StrErrorWrapper(error_code, buffer, sizeof(buffer));
790 #endif
791 }
792
793 const char* StrNetworkError()
794 {
795 #ifdef _WIN32
796 const s32 error_code = WSAGetLastError();
797 #else
798 const s32 error_code = errno;
799 #endif
800 return DecodeNetworkError(error_code);
801 }
802
803 bool SetPlatformSocketOptions(int fd [[maybe_unused]])
804 {
805 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
806 int opt_no_sigpipe = 1;
807 if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &opt_no_sigpipe, sizeof(opt_no_sigpipe)) < 0)
808 {
809 ERROR_LOG_FMT(COMMON, "Failed to set SO_NOSIGPIPE on socket: {}", StrNetworkError());
810 return false;
811 }
812 #endif
813 return true;
814 }
815
816 } // namespace Common