You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

361 lines
9.6 KiB

  1. /*
  2. * This file is part of PowerDNS or dnsdist.
  3. * Copyright -- PowerDNS.COM B.V. and its contributors
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of version 2 of the GNU General Public License as
  7. * published by the Free Software Foundation.
  8. *
  9. * In addition, for the avoidance of any doubt, permission is granted to
  10. * link this program with OpenSSL and to (re)distribute the binaries
  11. * produced as the result of such linking.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #pragma once
  23. #include <string>
  24. #include <sstream>
  25. #include <iostream>
  26. #include "iputils.hh"
  27. #include <errno.h>
  28. #include <sys/types.h>
  29. #include <unistd.h>
  30. #include <sys/socket.h>
  31. #include <netinet/in.h>
  32. #include <arpa/inet.h>
  33. #include <sys/select.h>
  34. #include <fcntl.h>
  35. #include <stdexcept>
  36. #include <boost/utility.hpp>
  37. #include <csignal>
  38. #include "namespaces.hh"
  39. #include "namespaces.hh"
  40. typedef int ProtocolType; //!< Supported protocol types
  41. //! Representation of a Socket and many of the Berkeley functions available
  42. class Socket : public boost::noncopyable
  43. {
  44. Socket(int fd): d_socket(fd)
  45. {
  46. }
  47. public:
  48. //! Construct a socket of specified address family and socket type.
  49. Socket(int af, int st, ProtocolType pt=0)
  50. {
  51. if((d_socket=socket(af, st, pt))<0)
  52. throw NetworkError(stringerror());
  53. setCloseOnExec(d_socket);
  54. }
  55. Socket(Socket&& rhs): d_buffer(std::move(rhs.d_buffer)), d_socket(rhs.d_socket)
  56. {
  57. rhs.d_socket = -1;
  58. }
  59. ~Socket()
  60. {
  61. try {
  62. if (d_socket != -1) {
  63. closesocket(d_socket);
  64. }
  65. }
  66. catch(const PDNSException& e) {
  67. }
  68. }
  69. //! If the socket is capable of doing so, this function will wait for a connection
  70. std::unique_ptr<Socket> accept()
  71. {
  72. struct sockaddr_in remote;
  73. socklen_t remlen=sizeof(remote);
  74. memset(&remote, 0, sizeof(remote));
  75. int s=::accept(d_socket, reinterpret_cast<sockaddr *>(&remote), &remlen);
  76. if(s<0) {
  77. if(errno==EAGAIN)
  78. return nullptr;
  79. throw NetworkError("Accepting a connection: "+stringerror());
  80. }
  81. return std::unique_ptr<Socket>(new Socket(s));
  82. }
  83. //! Get remote address
  84. bool getRemote(ComboAddress &remote) {
  85. socklen_t remotelen=sizeof(remote);
  86. return (getpeername(d_socket, reinterpret_cast<struct sockaddr *>(&remote), &remotelen) >= 0);
  87. }
  88. //! Check remote address against netmaskgroup ng
  89. bool acl(const NetmaskGroup &ng)
  90. {
  91. ComboAddress remote;
  92. if (getRemote(remote))
  93. return ng.match(remote);
  94. return false;
  95. }
  96. //! Set the socket to non-blocking
  97. void setNonBlocking()
  98. {
  99. ::setNonBlocking(d_socket);
  100. }
  101. //! Set the socket to blocking
  102. void setBlocking()
  103. {
  104. ::setBlocking(d_socket);
  105. }
  106. void setReuseAddr()
  107. {
  108. try {
  109. ::setReuseAddr(d_socket);
  110. } catch (const PDNSException &e) {
  111. throw NetworkError(e.reason);
  112. }
  113. }
  114. //! Bind the socket to a specified endpoint
  115. void bind(const ComboAddress &local, bool reuseaddr=true)
  116. {
  117. int tmp=1;
  118. if(reuseaddr && setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&tmp), sizeof tmp)<0)
  119. throw NetworkError("Setsockopt failed: "+stringerror());
  120. if(::bind(d_socket, reinterpret_cast<const struct sockaddr *>(&local), local.getSocklen())<0)
  121. throw NetworkError("While binding: "+stringerror());
  122. }
  123. //! Connect the socket to a specified endpoint
  124. void connect(const ComboAddress &ep, int timeout=0)
  125. {
  126. SConnectWithTimeout(d_socket, ep, timeout);
  127. }
  128. //! For datagram sockets, receive a datagram and learn where it came from
  129. /** For datagram sockets, receive a datagram and learn where it came from
  130. \param dgram Will be filled with the datagram
  131. \param ep Will be filled with the origin of the datagram */
  132. void recvFrom(string &dgram, ComboAddress &ep)
  133. {
  134. socklen_t remlen = sizeof(ep);
  135. ssize_t bytes;
  136. d_buffer.resize(s_buflen);
  137. if((bytes=recvfrom(d_socket, &d_buffer[0], s_buflen, 0, reinterpret_cast<sockaddr *>(&ep) , &remlen)) <0)
  138. throw NetworkError("After recvfrom: "+stringerror());
  139. dgram.assign(d_buffer, 0, static_cast<size_t>(bytes));
  140. }
  141. bool recvFromAsync(string &dgram, ComboAddress &ep)
  142. {
  143. struct sockaddr_in remote;
  144. socklen_t remlen = sizeof(remote);
  145. ssize_t bytes;
  146. d_buffer.resize(s_buflen);
  147. if((bytes=recvfrom(d_socket, &d_buffer[0], s_buflen, 0, reinterpret_cast<sockaddr *>(&remote), &remlen))<0) {
  148. if(errno!=EAGAIN) {
  149. throw NetworkError("After async recvfrom: "+stringerror());
  150. }
  151. else {
  152. return false;
  153. }
  154. }
  155. dgram.assign(d_buffer, 0, static_cast<size_t>(bytes));
  156. return true;
  157. }
  158. //! For datagram sockets, send a datagram to a destination
  159. void sendTo(const char* msg, size_t len, const ComboAddress &ep)
  160. {
  161. if(sendto(d_socket, msg, len, 0, reinterpret_cast<const sockaddr *>(&ep), ep.getSocklen())<0)
  162. throw NetworkError("After sendto: "+stringerror());
  163. }
  164. //! For connected datagram sockets, send a datagram
  165. void send(const std::string& msg)
  166. {
  167. if(::send(d_socket, msg.c_str(), msg.size(), 0)<0)
  168. throw NetworkError("After send: "+stringerror());
  169. }
  170. /** For datagram sockets, send a datagram to a destination
  171. \param dgram The datagram
  172. \param ep The intended destination of the datagram */
  173. void sendTo(const string &dgram, const ComboAddress &ep)
  174. {
  175. sendTo(dgram.c_str(), dgram.length(), ep);
  176. }
  177. //! Write this data to the socket, taking care that all bytes are written out
  178. void writen(const string &data)
  179. {
  180. if(data.empty())
  181. return;
  182. size_t toWrite=data.length();
  183. ssize_t res;
  184. const char *ptr=data.c_str();
  185. do {
  186. res=::send(d_socket, ptr, toWrite, 0);
  187. if(res<0)
  188. throw NetworkError("Writing to a socket: "+stringerror());
  189. if(!res)
  190. throw NetworkError("EOF on socket");
  191. toWrite -= static_cast<size_t>(res);
  192. ptr += static_cast<size_t>(res);
  193. } while(toWrite);
  194. }
  195. //! tries to write toWrite bytes from ptr to the socket
  196. /** tries to write toWrite bytes from ptr to the socket, but does not make sure they al get written out
  197. \param ptr Location to write from
  198. \param toWrite number of bytes to try
  199. */
  200. size_t tryWrite(const char *ptr, size_t toWrite)
  201. {
  202. ssize_t res;
  203. res=::send(d_socket,ptr,toWrite,0);
  204. if(res==0)
  205. throw NetworkError("EOF on writing to a socket");
  206. if(res>0)
  207. return res;
  208. if(errno==EAGAIN)
  209. return 0;
  210. throw NetworkError("Writing to a socket: "+stringerror());
  211. }
  212. //! Writes toWrite bytes from ptr to the socket
  213. /** Writes toWrite bytes from ptr to the socket. Returns how many bytes were written */
  214. size_t write(const char *ptr, size_t toWrite)
  215. {
  216. ssize_t res;
  217. res=::send(d_socket,ptr,toWrite,0);
  218. if(res<0) {
  219. throw NetworkError("Writing to a socket: "+stringerror());
  220. }
  221. return res;
  222. }
  223. void writenWithTimeout(const void *buffer, size_t n, int timeout)
  224. {
  225. size_t bytes=n;
  226. const char *ptr = reinterpret_cast<const char*>(buffer);
  227. ssize_t ret;
  228. while(bytes) {
  229. ret=::write(d_socket, ptr, bytes);
  230. if(ret < 0) {
  231. if(errno==EAGAIN) {
  232. ret=waitForRWData(d_socket, false, timeout, 0);
  233. if(ret < 0)
  234. throw NetworkError("Waiting for data write");
  235. if(!ret)
  236. throw NetworkError("Timeout writing data");
  237. continue;
  238. }
  239. else
  240. throw NetworkError("Writing data: "+stringerror());
  241. }
  242. if(!ret) {
  243. throw NetworkError("Did not fulfill TCP write due to EOF");
  244. }
  245. ptr += static_cast<size_t>(ret);
  246. bytes -= static_cast<size_t>(ret);
  247. }
  248. }
  249. //! reads one character from the socket
  250. int getChar()
  251. {
  252. char c;
  253. ssize_t res=::recv(d_socket,&c,1,0);
  254. if(res)
  255. return c;
  256. return -1;
  257. }
  258. void getline(string &data)
  259. {
  260. data="";
  261. int c;
  262. while((c=getChar())!=-1) {
  263. data+=(char)c;
  264. if(c=='\n')
  265. break;
  266. }
  267. }
  268. //! Reads a block of data from the socket to a string
  269. void read(string &data)
  270. {
  271. d_buffer.resize(s_buflen);
  272. ssize_t res=::recv(d_socket, &d_buffer[0], s_buflen, 0);
  273. if(res<0)
  274. throw NetworkError("Reading from a socket: "+stringerror());
  275. data.assign(d_buffer, 0, static_cast<size_t>(res));
  276. }
  277. //! Reads a block of data from the socket to a block of memory
  278. size_t read(char *buffer, size_t bytes)
  279. {
  280. ssize_t res=::recv(d_socket, buffer, bytes, 0);
  281. if(res<0)
  282. throw NetworkError("Reading from a socket: "+stringerror());
  283. return static_cast<size_t>(res);
  284. }
  285. ssize_t readWithTimeout(char* buffer, size_t n, int timeout)
  286. {
  287. int err = waitForRWData(d_socket, true, timeout, 0);
  288. if(err == 0)
  289. throw NetworkError("timeout reading");
  290. if(err < 0)
  291. throw NetworkError("nonblocking read failed: "+stringerror());
  292. return read(buffer, n);
  293. }
  294. //! Sets the socket to listen with a default listen backlog of 10 pending connections
  295. void listen(unsigned int length=10)
  296. {
  297. if(::listen(d_socket,length)<0)
  298. throw NetworkError("Setting socket to listen: "+stringerror());
  299. }
  300. //! Returns the internal file descriptor of the socket
  301. int getHandle() const
  302. {
  303. return d_socket;
  304. }
  305. private:
  306. static const size_t s_buflen{4096};
  307. std::string d_buffer;
  308. int d_socket;
  309. };