SocketCore.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #ifndef D_SOCKET_CORE_H
  36. #define D_SOCKET_CORE_H
  37. #include "common.h"
  38. #include <string>
  39. #include <cstdlib>
  40. #include <utility>
  41. #include <vector>
  42. #include "a2netcompat.h"
  43. #ifdef HAVE_LIBSSL
  44. // for SSL
  45. # include <openssl/ssl.h>
  46. # include <openssl/err.h>
  47. #endif // HAVE_LIBSSL
  48. #ifdef HAVE_LIBGNUTLS
  49. # include <gnutls/gnutls.h>
  50. #endif // HAVE_LIBGNUTLS
  51. #include "SharedHandle.h"
  52. #include "a2io.h"
  53. #include "a2netcompat.h"
  54. #include "a2time.h"
  55. namespace aria2 {
  56. #ifdef ENABLE_SSL
  57. class TLSContext;
  58. #endif // ENABLE_SSL
  59. class SocketCore {
  60. friend bool operator==(const SocketCore& s1, const SocketCore& s2);
  61. friend bool operator!=(const SocketCore& s1, const SocketCore& s2);
  62. friend bool operator<(const SocketCore& s1, const SocketCore& s2);
  63. private:
  64. // socket type defined in <sys/socket.h>
  65. int sockType_;
  66. // socket endpoint descriptor
  67. sock_t sockfd_;
  68. static int protocolFamily_;
  69. static std::vector<std::pair<struct sockaddr_storage, socklen_t> > bindAddrs_;
  70. bool blocking_;
  71. int secure_;
  72. bool wantRead_;
  73. bool wantWrite_;
  74. #if ENABLE_SSL
  75. static SharedHandle<TLSContext> tlsContext_;
  76. #endif // ENABLE_SSL
  77. #ifdef HAVE_LIBSSL
  78. // for SSL
  79. SSL* ssl;
  80. int sslHandleEAGAIN(int ret);
  81. #endif // HAVE_LIBSSL
  82. #ifdef HAVE_LIBGNUTLS
  83. gnutls_session_t sslSession_;
  84. char* peekBuf_;
  85. size_t peekBufLength_;
  86. size_t peekBufMax_;
  87. size_t shiftPeekData(char* data, size_t len);
  88. void addPeekData(char* data, size_t len);
  89. ssize_t gnutlsRecv(char* data, size_t len);
  90. ssize_t gnutlsPeek(char* data, size_t len);
  91. void gnutlsRecordCheckDirection();
  92. #endif // HAVE_LIBGNUTLS
  93. void init();
  94. void bind(const struct sockaddr* addr, socklen_t addrlen);
  95. void setSockOpt(int level, int optname, void* optval, socklen_t optlen);
  96. SocketCore(sock_t sockfd, int sockType);
  97. public:
  98. SocketCore(int sockType = SOCK_STREAM);
  99. ~SocketCore();
  100. sock_t getSockfd() const { return sockfd_; }
  101. bool isOpen() const { return sockfd_ != (sock_t) -1; }
  102. void setMulticastInterface(const std::string& localAddr);
  103. void setMulticastTtl(unsigned char ttl);
  104. void setMulticastLoop(unsigned char loop);
  105. void joinMulticastGroup
  106. (const std::string& multicastAddr, uint16_t multicastPort,
  107. const std::string& localAddr);
  108. void create(int family, int protocol = 0);
  109. void bindWithFamily(uint16_t port, int family, int flags = AI_PASSIVE);
  110. /**
  111. * Creates a socket and bind it with locahost's address and port.
  112. * flags is set to struct addrinfo's ai_flags.
  113. * @param port port to listen. If 0 is specified, os automaticaly
  114. * choose avaiable port.
  115. */
  116. void bind(uint16_t port, int flags = AI_PASSIVE);
  117. void bind
  118. (const std::string& addr, uint16_t port, int family, int flags = AI_PASSIVE);
  119. /**
  120. * Listens form connection on it.
  121. * Call bind(uint16_t) before calling this function.
  122. */
  123. void beginListen();
  124. /**
  125. * Stores host address and port of this socket to addrinfo.
  126. * @param addrinfo placeholder to store host address and port.
  127. */
  128. void getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const;
  129. /**
  130. * Stores address of this socket to sockaddr. len must be
  131. * initialized to the size of sockaddr. On success, address data is
  132. * stored in sockaddr and actual size of address structure is stored
  133. * in len.
  134. */
  135. void getAddrInfo
  136. (struct sockaddr_storage& sockaddr, socklen_t& len) const;
  137. /**
  138. * Returns address family of this socket.
  139. * The socket must be connected or bounded to address.
  140. */
  141. int getAddressFamily() const;
  142. /**
  143. * Stores peer's address and port to peerinfo.
  144. * @param peerinfo placeholder to store peer's address and port.
  145. */
  146. void getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const;
  147. /**
  148. * Accepts incoming connection on this socket.
  149. * You must call beginListen() before calling this method.
  150. * @return accepted socket. The caller must delete it after using it.
  151. */
  152. SocketCore* acceptConnection() const;
  153. /**
  154. * Connects to the server named host and the destination port is port.
  155. * This method makes socket non-blocking mode.
  156. * To make the socket blocking mode again, call setBlockingMode() after
  157. * the connection is established.
  158. * @param host hostname or ip address to connect to
  159. * @param port service port number to connect to
  160. */
  161. void establishConnection(const std::string& host, uint16_t port);
  162. void setNonBlockingMode();
  163. /**
  164. * Makes this socket blocking mode.
  165. */
  166. void setBlockingMode();
  167. /**
  168. * Closes the connection of this socket.
  169. */
  170. void closeConnection();
  171. /**
  172. * Checks whether this socket is available for writing.
  173. * @param timeout the amount of time elapsed before the checking are timed
  174. * out.
  175. * @return true if the socket is available for writing,
  176. * otherwise returns false.
  177. */
  178. bool isWritable(time_t timeout);
  179. /**
  180. * Checks whether this socket is available for reading.
  181. * @param timeout the amount of time elapsed before the checking are timed
  182. * out.
  183. * @return true if the socket is available for reading,
  184. * otherwise returns false.
  185. */
  186. bool isReadable(time_t timeout);
  187. /**
  188. * Writes data into this socket. data is a pointer pointing the first
  189. * byte of the data and len is the length of data.
  190. * If the underlying socket is in blocking mode, this method may block until
  191. * all data is sent.
  192. * If the underlying socket is in non-blocking mode, this method may return
  193. * even if all data is sent. The size of written data is returned. If
  194. * underlying socket gets EAGAIN, wantRead_ or wantWrite_ is set accordingly.
  195. * This method sets wantRead_ and wantWrite_ to false before do anything else.
  196. * @param data data to write
  197. * @param len length of data
  198. */
  199. ssize_t writeData(const char* data, size_t len);
  200. ssize_t writeData(const std::string& msg)
  201. {
  202. return writeData(msg.c_str(), msg.size());
  203. }
  204. ssize_t writeData(const unsigned char* data, size_t len)
  205. {
  206. return writeData(reinterpret_cast<const char*>(data), len);
  207. }
  208. ssize_t writeData(const char* data, size_t len,
  209. const std::string& host, uint16_t port);
  210. ssize_t writeData(const unsigned char* data, size_t len,
  211. const std::string& host,
  212. uint16_t port)
  213. {
  214. return writeData(reinterpret_cast<const char*>(data), len, host, port);
  215. }
  216. /**
  217. * Reads up to len bytes from this socket.
  218. * data is a pointer pointing the first
  219. * byte of the data, which must be allocated before this method is called.
  220. * len is the size of the allocated memory. When this method returns
  221. * successfully, len is replaced by the size of the read data.
  222. * If the underlying socket is in blocking mode, this method may block until
  223. * at least 1byte is received.
  224. * If the underlying socket is in non-blocking mode, this method may return
  225. * even if no single byte is received. If the underlying socket gets EAGAIN,
  226. * wantRead_ or wantWrite_ is set accordingly.
  227. * This method sets wantRead_ and wantWrite_ to false before do anything else.
  228. * @param data holder to store data.
  229. * @param len the maximum size data can store. This method assigns
  230. * the number of bytes read to len.
  231. */
  232. void readData(char* data, size_t& len);
  233. void readData(unsigned char* data, size_t& len)
  234. {
  235. readData(reinterpret_cast<char*>(data), len);
  236. }
  237. ssize_t readDataFrom(char* data, size_t len,
  238. std::pair<std::string /* numerichost */,
  239. uint16_t /* port */>& sender);
  240. ssize_t readDataFrom(unsigned char* data, size_t len,
  241. std::pair<std::string /* numerichost */,
  242. uint16_t /* port */>& sender)
  243. {
  244. return readDataFrom(reinterpret_cast<char*>(data), len, sender);
  245. }
  246. /**
  247. * Reads up to len bytes from this socket, but bytes are not removed from
  248. * this socket.
  249. * This method internally calls isReadable(). The parameter timeout is used
  250. * for this method call.
  251. * @param data holder to store data.
  252. * @param len the maximum size data can store. This method assigns
  253. * the number of bytes read to len.
  254. */
  255. void peekData(char* data, size_t& len);
  256. void peekData(unsigned char* data, size_t& len)
  257. {
  258. peekData(reinterpret_cast<char*>(data), len);
  259. }
  260. /**
  261. * Makes this socket secure.
  262. * If the system has not OpenSSL, then this method do nothing.
  263. * connection must be established before calling this method.
  264. *
  265. * If you are going to verify peer's certificate, hostname must be supplied.
  266. */
  267. bool initiateSecureConnection(const std::string& hostname="");
  268. void prepareSecureConnection();
  269. bool operator==(const SocketCore& s) {
  270. return sockfd_ == s.sockfd_;
  271. }
  272. bool operator!=(const SocketCore& s) {
  273. return !(*this == s);
  274. }
  275. bool operator<(const SocketCore& s) {
  276. return sockfd_ < s.sockfd_;
  277. }
  278. std::string getSocketError() const;
  279. /**
  280. * Returns true if the underlying socket gets EAGAIN in the previous
  281. * readData() or writeData() and the socket needs more incoming data to
  282. * continue the operation.
  283. */
  284. bool wantRead() const;
  285. /**
  286. * Returns true if the underlying socket gets EAGAIN in the previous
  287. * readData() or writeData() and the socket needs to write more data.
  288. */
  289. bool wantWrite() const;
  290. #ifdef ENABLE_SSL
  291. static void setTLSContext(const SharedHandle<TLSContext>& tlsContext);
  292. #endif // ENABLE_SSL
  293. static void setProtocolFamily(int protocolFamily)
  294. {
  295. protocolFamily_ = protocolFamily;
  296. }
  297. // Bind socket to interface. interface may be specified as a
  298. // hostname, IP address or interface name like eth0. If the given
  299. // interface is not found or binding socket is failed, exception
  300. // will be thrown. Set protocolFamily_ before calling this function
  301. // if you limit protocol family.
  302. //
  303. // We cannot use interface as an argument because it is a reserved
  304. // keyword in MSVC.
  305. static void bindAddress(const std::string& iface);
  306. friend void getInterfaceAddress
  307. (std::vector<std::pair<struct sockaddr_storage, socklen_t> >& ifAddrs,
  308. const std::string& iface, int family, int aiFlags);
  309. };
  310. // Set default ai_flags. hints.ai_flags is initialized with this
  311. // value.
  312. void setDefaultAIFlags(int flags);
  313. // Wrapper function for getaddrinfo(). The value
  314. // flags|DEFAULT_AI_FLAGS is used as ai_flags. You can override
  315. // DEFAULT_AI_FLAGS value by calling setDefaultAIFlags() with new
  316. // flags.
  317. int callGetaddrinfo
  318. (struct addrinfo** resPtr, const char* host, const char* service, int family,
  319. int sockType, int flags, int protocol);
  320. // Collects IP addresses of given inteface iface and stores in
  321. // ifAddres. iface may be specified as a hostname, IP address or
  322. // interface name like eth0. You can limit the family of IP addresses
  323. // to collect using family argument. aiFlags is passed to
  324. // getaddrinfo() as hints.ai_flags. No throw.
  325. void getInterfaceAddress
  326. (std::vector<std::pair<struct sockaddr_storage, socklen_t> >& ifAddrs,
  327. const std::string& iface, int family = AF_UNSPEC, int aiFlags = 0);
  328. } // namespace aria2
  329. #endif // D_SOCKET_CORE_H