SocketCore.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. #ifdef HAVE_EPOLL
  39. # include <sys/epoll.h>
  40. #endif // HAVE_EPOLL
  41. #include <string>
  42. #include <cstdlib>
  43. #include <utility>
  44. #include <vector>
  45. #ifdef HAVE_LIBSSL
  46. // for SSL
  47. # include <openssl/ssl.h>
  48. # include <openssl/err.h>
  49. #endif // HAVE_LIBSSL
  50. #ifdef HAVE_LIBGNUTLS
  51. # include <gnutls/gnutls.h>
  52. #endif // HAVE_LIBGNUTLS
  53. #include "SharedHandle.h"
  54. #include "a2io.h"
  55. #include "a2netcompat.h"
  56. #include "a2time.h"
  57. namespace aria2 {
  58. #ifdef ENABLE_SSL
  59. class TLSContext;
  60. #endif // ENABLE_SSL
  61. class SocketCore {
  62. friend bool operator==(const SocketCore& s1, const SocketCore& s2);
  63. friend bool operator!=(const SocketCore& s1, const SocketCore& s2);
  64. friend bool operator<(const SocketCore& s1, const SocketCore& s2);
  65. private:
  66. // socket type defined in <sys/socket.h>
  67. int _sockType;
  68. // socket endpoint descriptor
  69. sock_t sockfd;
  70. #ifdef HAVE_EPOLL
  71. // file descriptor used for epoll
  72. int _epfd;
  73. struct epoll_event _epEvent;
  74. #endif // HAVE_EPOLL
  75. enum PollMethod {
  76. POLL_METHOD_EPOLL, POLL_METHOD_SELECT
  77. };
  78. static PollMethod _pollMethod;
  79. static int _protocolFamily;
  80. static std::vector<std::pair<struct sockaddr_storage, socklen_t> > _bindAddrs;
  81. bool blocking;
  82. int secure;
  83. bool _wantRead;
  84. bool _wantWrite;
  85. #if ENABLE_SSL
  86. static SharedHandle<TLSContext> _tlsContext;
  87. #endif // ENABLE_SSL
  88. #ifdef HAVE_LIBSSL
  89. // for SSL
  90. SSL* ssl;
  91. int sslHandleEAGAIN(int ret);
  92. #endif // HAVE_LIBSSL
  93. #ifdef HAVE_LIBGNUTLS
  94. gnutls_session_t sslSession;
  95. char* peekBuf;
  96. size_t peekBufLength;
  97. size_t peekBufMax;
  98. size_t shiftPeekData(char* data, size_t len);
  99. void addPeekData(char* data, size_t len);
  100. ssize_t gnutlsRecv(char* data, size_t len);
  101. ssize_t gnutlsPeek(char* data, size_t len);
  102. void gnutlsRecordCheckDirection();
  103. #endif // HAVE_LIBGNUTLS
  104. void init();
  105. void bind(const struct sockaddr* addr, socklen_t addrlen);
  106. #ifdef HAVE_EPOLL
  107. void initEPOLL();
  108. #endif // HAVE_EPOLL
  109. void setSockOpt(int level, int optname, void* optval, socklen_t optlen);
  110. SocketCore(sock_t sockfd, int sockType);
  111. public:
  112. SocketCore(int sockType = SOCK_STREAM);
  113. ~SocketCore();
  114. sock_t getSockfd() const { return sockfd; }
  115. bool isOpen() const { return sockfd != (sock_t) -1; }
  116. void setMulticastTtl(unsigned char ttl);
  117. void joinMulticastGroup(const std::string& ipaddr, uint16_t port);
  118. void bindWithFamily(uint16_t port, int family, int flags = AI_PASSIVE);
  119. /**
  120. * Creates a socket and bind it with locahost's address and port.
  121. * flags is set to struct addrinfo's ai_flags.
  122. * @param port port to listen. If 0 is specified, os automaticaly
  123. * choose avaiable port.
  124. */
  125. void bind(uint16_t port, int flags = AI_PASSIVE);
  126. /**
  127. * Listens form connection on it.
  128. * Call bind(uint16_t) before calling this function.
  129. */
  130. void beginListen();
  131. /**
  132. * Stores host address and port of this socket to addrinfo.
  133. * @param addrinfo placeholder to store host address and port.
  134. */
  135. void getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const;
  136. /**
  137. * Stores peer's address and port to peerinfo.
  138. * @param peerinfo placeholder to store peer's address and port.
  139. */
  140. void getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const;
  141. /**
  142. * Accepts incoming connection on this socket.
  143. * You must call beginListen() before calling this method.
  144. * @return accepted socket. The caller must delete it after using it.
  145. */
  146. SocketCore* acceptConnection() const;
  147. /**
  148. * Connects to the server named host and the destination port is port.
  149. * This method makes socket non-blocking mode.
  150. * To make the socket blocking mode again, call setBlockingMode() after
  151. * the connection is established.
  152. * @param host hostname or ip address to connect to
  153. * @param port service port number to connect to
  154. */
  155. void establishConnection(const std::string& host, uint16_t port);
  156. void setNonBlockingMode();
  157. /**
  158. * Makes this socket blocking mode.
  159. */
  160. void setBlockingMode();
  161. /**
  162. * Closes the connection of this socket.
  163. */
  164. void closeConnection();
  165. /**
  166. * Checks whether this socket is available for writing.
  167. * @param timeout the amount of time elapsed before the checking are timed
  168. * out.
  169. * @return true if the socket is available for writing,
  170. * otherwise returns false.
  171. */
  172. bool isWritable(time_t timeout);
  173. /**
  174. * Checks whether this socket is available for reading.
  175. * @param timeout the amount of time elapsed before the checking are timed
  176. * out.
  177. * @return true if the socket is available for reading,
  178. * otherwise returns false.
  179. */
  180. bool isReadable(time_t timeout);
  181. /**
  182. * Writes data into this socket. data is a pointer pointing the first
  183. * byte of the data and len is the length of data.
  184. * If the underlying socket is in blocking mode, this method may block until
  185. * all data is sent.
  186. * If the underlying socket is in non-blocking mode, this method may return
  187. * even if all data is sent. The size of written data is returned. If
  188. * underlying socket gets EAGAIN, _wantRead or _wantWrite is set accordingly.
  189. * This method sets _wantRead and _wantWrite to false before do anything else.
  190. * @param data data to write
  191. * @param len length of data
  192. */
  193. ssize_t writeData(const char* data, size_t len);
  194. ssize_t writeData(const std::string& msg)
  195. {
  196. return writeData(msg.c_str(), msg.size());
  197. }
  198. ssize_t writeData(const unsigned char* data, size_t len)
  199. {
  200. return writeData(reinterpret_cast<const char*>(data), len);
  201. }
  202. ssize_t writeData(const char* data, size_t len,
  203. const std::string& host, uint16_t port);
  204. ssize_t writeData(const unsigned char* data, size_t len,
  205. const std::string& host,
  206. uint16_t port)
  207. {
  208. return writeData(reinterpret_cast<const char*>(data), len, host, port);
  209. }
  210. /**
  211. * Reads up to len bytes from this socket.
  212. * data is a pointer pointing the first
  213. * byte of the data, which must be allocated before this method is called.
  214. * len is the size of the allocated memory. When this method returns
  215. * successfully, len is replaced by the size of the read data.
  216. * If the underlying socket is in blocking mode, this method may block until
  217. * at least 1byte is received.
  218. * If the underlying socket is in non-blocking mode, this method may return
  219. * even if no single byte is received. If the underlying socket gets EAGAIN,
  220. * _wantRead or _wantWrite is set accordingly.
  221. * This method sets _wantRead and _wantWrite to false before do anything else.
  222. * @param data holder to store data.
  223. * @param len the maximum size data can store. This method assigns
  224. * the number of bytes read to len.
  225. */
  226. void readData(char* data, size_t& len);
  227. void readData(unsigned char* data, size_t& len)
  228. {
  229. readData(reinterpret_cast<char*>(data), len);
  230. }
  231. ssize_t readDataFrom(char* data, size_t len,
  232. std::pair<std::string /* numerichost */,
  233. uint16_t /* port */>& sender);
  234. ssize_t readDataFrom(unsigned char* data, size_t len,
  235. std::pair<std::string /* numerichost */,
  236. uint16_t /* port */>& sender)
  237. {
  238. return readDataFrom(reinterpret_cast<char*>(data), len, sender);
  239. }
  240. /**
  241. * Reads up to len bytes from this socket, but bytes are not removed from
  242. * this socket.
  243. * This method internally calls isReadable(). The parameter timeout is used
  244. * for this method call.
  245. * @param data holder to store data.
  246. * @param len the maximum size data can store. This method assigns
  247. * the number of bytes read to len.
  248. */
  249. void peekData(char* data, size_t& len);
  250. void peekData(unsigned char* data, size_t& len)
  251. {
  252. peekData(reinterpret_cast<char*>(data), len);
  253. }
  254. /**
  255. * Makes this socket secure.
  256. * If the system has not OpenSSL, then this method do nothing.
  257. * connection must be established before calling this method.
  258. *
  259. * If you are going to verify peer's certificate, hostname must be supplied.
  260. */
  261. bool initiateSecureConnection(const std::string& hostname="");
  262. void prepareSecureConnection();
  263. bool operator==(const SocketCore& s) {
  264. return sockfd == s.sockfd;
  265. }
  266. bool operator!=(const SocketCore& s) {
  267. return !(*this == s);
  268. }
  269. bool operator<(const SocketCore& s) {
  270. return sockfd < s.sockfd;
  271. }
  272. std::string getSocketError() const;
  273. /**
  274. * Returns true if the underlying socket gets EAGAIN in the previous
  275. * readData() or writeData() and the socket needs more incoming data to
  276. * continue the operation.
  277. */
  278. bool wantRead() const;
  279. /**
  280. * Returns true if the underlying socket gets EAGAIN in the previous
  281. * readData() or writeData() and the socket needs to write more data.
  282. */
  283. bool wantWrite() const;
  284. #ifdef HAVE_EPOLL
  285. static void useEpoll();
  286. #endif // HAVE_EPOLL
  287. static void useSelect();
  288. #ifdef ENABLE_SSL
  289. static void setTLSContext(const SharedHandle<TLSContext>& tlsContext);
  290. #endif // ENABLE_SSL
  291. static void setProtocolFamily(int protocolFamily)
  292. {
  293. _protocolFamily = protocolFamily;
  294. }
  295. // Bind socket to interface. interface may be specified as a
  296. // hostname, IP address or interface name like eth0. If the given
  297. // interface is not found or binding socket is failed, exception
  298. // will be thrown. Set _protocolFamily before calling this function
  299. // if you limit protocol family.
  300. //
  301. // We cannot use interface as an argument because it is a reserved
  302. // keyword in MSVC.
  303. static void bindAddress(const std::string& iface);
  304. friend void getInterfaceAddress
  305. (std::vector<std::pair<struct sockaddr_storage, socklen_t> >& ifAddrs,
  306. const std::string& iface, int family);
  307. };
  308. // Set default ai_flags. hints.ai_flags is initialized with this
  309. // value.
  310. void setDefaultAIFlags(int flags);
  311. // Wrapper function for getaddrinfo(). The value
  312. // flags|DEFAULT_AI_FLAGS is used as ai_flags. You can override
  313. // DEFAULT_AI_FLAGS value by calling setDefaultAIFlags() with new
  314. // flags.
  315. int callGetaddrinfo
  316. (struct addrinfo** resPtr, const char* host, const char* service, int family,
  317. int sockType, int flags, int protocol);
  318. // Collects IP addresses of given inteface iface and stores in
  319. // ifAddres. iface may be specified as a hostname, IP address or
  320. // interface name like eth0. You can limit the family of IP addresses
  321. // to collect using family argument.
  322. void getInterfaceAddress
  323. (std::vector<std::pair<struct sockaddr_storage, socklen_t> >& ifAddrs,
  324. const std::string& iface, int family = AF_UNSPEC);
  325. } // namespace aria2
  326. #endif // _D_SOCKET_CORE_H_