OpenVPN 3 Core Library
Loading...
Searching...
No Matches
binprefix.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#ifndef OPENVPN_COMMON_BINPREFIX_H
13#define OPENVPN_COMMON_BINPREFIX_H
14
15#include <algorithm> // for std::min, std::max
16#include <cstring> // for std::memset, std::memcpy
17#include <cstdint> // for std::uint32_t, uint64_t
18
19#include <openvpn/common/socktypes.hpp> // for ntohl
20
21namespace openvpn {
22
23// Return the binary prefix of a big-endian data buffer
24// as a 32 bit type.
25template <typename T>
26inline typename std::enable_if<4 == sizeof(T), T>::type
27bin_prefix(const unsigned char *data)
28{
29 static_assert(sizeof(T) == 4, "size inconsistency");
30 return T(ntohl(*(uint32_t *)&data[0]));
31}
32
33// Return the binary prefix of a big-endian data buffer
34// as a 64 bit type.
35template <typename T>
36inline typename std::enable_if<8 == sizeof(T), T>::type
37bin_prefix(const unsigned char *data)
38{
39 static_assert(sizeof(T) == 8, "size inconsistency");
40 return (T(ntohl(*(uint32_t *)&data[0])) << 32) | T(ntohl(*(uint32_t *)&data[4]));
41}
42
43template <typename T>
44inline T bin_prefix(const unsigned char *data, const size_t len)
45{
46 unsigned char d[sizeof(T)]
47#ifndef _MSC_VER
48 __attribute__((aligned(sizeof(T))))
49#endif
50 ;
51 const size_t l = std::min(len, sizeof(d));
52 std::memset(d, 0, sizeof(d));
53 std::memcpy(d + sizeof(d) - l, data, l);
54 return bin_prefix<T>(d);
55}
56
57template <typename T>
58inline T bin_prefix_floor(const unsigned char *data, const size_t len, const T floor)
59{
60 return std::max(bin_prefix<T>(data, len), floor);
61}
62
63} // namespace openvpn
64#endif
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
T bin_prefix_floor(const unsigned char *data, const size_t len, const T floor)
Definition binprefix.hpp:58
std::enable_if< 4==sizeof(T), T >::type bin_prefix(const unsigned char *data)
Definition binprefix.hpp:27