SocketCore.h 9.8 KB

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