-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathutils.hpp
86 lines (66 loc) · 2.25 KB
/
utils.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#pragma once
#include <fmt/ostream.h>
#include <cstdint>
#include <cstdio>
namespace mstack {
namespace utils {
template <typename... A>
inline std::string format(std::string format, A&&... a) {
std::ostringstream os;
fmt::print(os, format, std::forward<A>(a)...);
return os.str();
}
template <typename... A>
inline static int run_cmd(std::string fmt, A&&... a) {
std::string cmd = format(fmt, std::forward<A>(a)...);
DLOG(INFO) << "[EXEC COMMAND]: " << cmd;
return system(cmd.c_str());
}
static int set_interface_route(std::string dev, std::string cidr) {
return run_cmd("ip route add dev {} {}", dev, cidr);
}
static int set_interface_address(std::string dev, std::string cidr) {
return run_cmd("ip address add dev {} local {}", dev, cidr);
}
static int set_interface_up(std::string dev) { return run_cmd("ip link set dev {} up", dev); }
uint32_t ntoh(uint32_t value) {
return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}
uint16_t ntoh(uint16_t value) { return (value & 0x00FF) << 8 | (value & 0xFF00) >> 8; }
uint8_t ntoh(uint8_t value) { return value; }
template <typename T>
inline T consume(uint8_t*& ptr) {
T ret = *(reinterpret_cast<T*>(ptr));
ptr += sizeof(T);
return ntoh(ret);
}
template <typename T>
inline void produce(uint8_t*& p, T t) {
T* ptr_ = reinterpret_cast<T*>(p);
*ptr_ = ntoh(t);
p += sizeof(T);
}
uint32_t sum_every_16bits(uint8_t* addr, int count) {
uint32_t sum = 0;
uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
while (count > 1) {
/* This is the inner loop */
sum += *ptr++;
count -= 2;
}
/* Add left-over byte, if any */
if (count > 0) sum += *(uint8_t*)ptr;
return sum;
}
uint16_t checksum(uint8_t* addr, int count, int start_sum) {
uint32_t sum = start_sum;
sum += sum_every_16bits(addr, count);
/* Fold 32-bit sum to 16 bits */
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
uint16_t ret = ~sum;
return ntoh(ret);
}
}; // namespace utils
}; // namespace mstack