Better bounds checking on DNS
[network-sink.git] / include / network.hpp
blobff28694b6e5d8380e2fc452f99faa727ba5b6e56
1 #ifndef NETWORK_H
2 #define NETWORK_H
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <sys/un.h>
7 #include <sys/socket.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
11 namespace Sinkhole
13 /** Retrieve a pointer to the network buffer for recv() etc to read into.
14 * @param The pointer and the size it points to
16 extern std::pair<char *, size_t> NetBuffer();
18 /** A sockaddr union used to combine IPv4 and IPv6 sockaddrs
20 union sockaddrs
22 sockaddr sa;
23 sockaddr_in sa4;
24 sockaddr_in6 sa6;
25 sockaddr_un un;
27 /** Construct the object, sets everything to 0
29 sockaddrs();
31 /** Memset the object to 0
33 void clear();
35 /** Get the size of the sockaddr we represent
36 * @return The size
38 size_t size() const;
40 /** Get the port represented by this addr
41 * @return The port, or -1 on fail
43 int port() const;
45 /** Get the address represented by this addr
46 * @return The address
48 std::string addr() const;
50 /** Check if this sockaddr has data in it
52 bool operator()() const;
54 /** Compares this sockaddr with another. Compares address type, port, and address
55 * @return true if they are the same
57 bool operator==(const sockaddrs &other) const;
58 /* The same as above but not */
59 inline bool operator!=(const sockaddrs &other) const { return !(*this == other); }
61 /** Compares this sockaddr with another.
62 * @return true if this is less than the other
64 bool operator<(const sockaddrs &other) const;
66 /** The equivalent of inet_pton
67 * @param type AF_INET or AF_INET6
68 * @param address The address to place in the sockaddr structures
69 * @param pport An option port to include in the sockaddr structures
70 * @throws A socket exception if given invalid IPs
72 void pton(int type, const std::string &address, int pport = 0);
74 /** The equivalent of inet_ntop
75 * @param type AF_INET or AF_INET6
76 * @param address The in_addr or in_addr6 structure
77 * @throws A socket exception if given an invalid structure
79 void ntop(int type, const void *src);
82 class cidr
84 static const unsigned char AF_INET_LEN;
85 static const unsigned char AF_INET6_LEN;
86 sockaddrs addr;
87 std::string cidr_ip;
88 unsigned char cidr_len;
89 public:
90 cidr(const std::string &ip);
91 cidr(const std::string &ip, unsigned char len);
92 std::string mask() const;
93 bool match(sockaddrs &other);
94 bool operator==(const cidr &other) const;
95 /* The same as above but not */
96 inline bool operator!=(const cidr &other) const { return !(*this == other); }
97 bool operator<(const cidr &other) const;
101 #endif