OpenVPN 3 Core Library
Loading...
Searching...
No Matches
udp.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// Define the UDP header
13
14#ifndef OPENVPN_IP_UDP_H
15#define OPENVPN_IP_UDP_H
16
18
19namespace openvpn {
20
21#pragma pack(push)
22#pragma pack(1)
23
25{
26 std::uint16_t source;
27 std::uint16_t dest;
28 std::uint16_t len;
29 std::uint16_t check;
30};
31
32#pragma pack(pop)
33
34inline std::uint16_t udp_checksum(const std::uint8_t *buf,
35 const unsigned int len_udp,
36 const std::uint8_t *src_addr,
37 const std::uint8_t *dest_addr)
38{
39 std::uint32_t sum = 0;
40
41 /* make 16 bit words out of every two adjacent 8 bit words and */
42 /* calculate the sum of all 16 bit words */
43 for (unsigned int i = 0; i < len_udp; i += 2)
44 {
45 std::uint16_t word16 = static_cast<uint16_t>(((buf[i] << 8) & 0xFF00) + ((i + 1 < len_udp) ? (buf[i + 1] & 0xFF) : 0));
46 sum += word16;
47 }
48
49 /* add the UDP pseudo header which contains the IP source and destination addresses */
50 for (unsigned int i = 0; i < 4; i += 2)
51 {
52 std::uint16_t word16 = static_cast<uint16_t>(((src_addr[i] << 8) & 0xFF00) + (src_addr[i + 1] & 0xFF));
53 sum += word16;
54 }
55 for (unsigned int i = 0; i < 4; i += 2)
56 {
57 std::uint16_t word16 = static_cast<uint16_t>(((dest_addr[i] << 8) & 0xFF00) + (dest_addr[i + 1] & 0xFF));
58 sum += word16;
59 }
60
61 /* the protocol number and the length of the UDP packet */
62 sum += (std::uint16_t)IPCommon::UDP + (std::uint16_t)len_udp;
63
64 /* keep only the last 16 bits of the 32 bit calculated sum and add the carries */
65 while (sum >> 16)
66 sum = (sum & 0xFFFF) + (sum >> 16);
67
68 /* take the one's complement of sum */
69 return std::uint16_t(~sum);
70}
71
72} // namespace openvpn
73
74#endif
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
std::uint16_t udp_checksum(const std::uint8_t *buf, const unsigned int len_udp, const std::uint8_t *src_addr, const std::uint8_t *dest_addr)
Definition udp.hpp:34
std::uint16_t source
Definition udp.hpp:26
std::uint16_t dest
Definition udp.hpp:27
std::uint16_t len
Definition udp.hpp:28
std::uint16_t check
Definition udp.hpp:29