SocketCore.h 10 KB

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