SocketCore.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 <memory>
  43. #include "a2netcompat.h"
  44. #include "a2io.h"
  45. #include "a2netcompat.h"
  46. #include "a2time.h"
  47. namespace aria2 {
  48. #ifdef ENABLE_SSL
  49. class TLSContext;
  50. class TLSSession;
  51. #endif // ENABLE_SSL
  52. #ifdef HAVE_LIBSSH2
  53. class SSHSession;
  54. #endif // HAVE_LIBSSH2
  55. class SocketCore {
  56. friend bool operator==(const SocketCore& s1, const SocketCore& s2);
  57. friend bool operator!=(const SocketCore& s1, const SocketCore& s2);
  58. friend bool operator<(const SocketCore& s1, const SocketCore& s2);
  59. private:
  60. // socket type defined in <sys/socket.h>
  61. int sockType_;
  62. // socket endpoint descriptor
  63. sock_t sockfd_;
  64. static int protocolFamily_;
  65. static int ipDscp_;
  66. static std::vector<SockAddr> bindAddrs_;
  67. static std::vector<std::vector<SockAddr>> bindAddrsList_;
  68. static std::vector<std::vector<SockAddr>>::iterator bindAddrsListIt_;
  69. static int socketRecvBufferSize_;
  70. bool blocking_;
  71. int secure_;
  72. bool wantRead_;
  73. bool wantWrite_;
  74. #if ENABLE_SSL
  75. // TLS context for client side
  76. static std::shared_ptr<TLSContext> clTlsContext_;
  77. // TLS context for server side
  78. static std::shared_ptr<TLSContext> svTlsContext_;
  79. std::shared_ptr<TLSSession> tlsSession_;
  80. /**
  81. * Makes this socket secure. The connection must be established
  82. * before calling this method.
  83. *
  84. * If you are going to verify peer's certificate, hostname must be supplied.
  85. */
  86. bool tlsHandshake(TLSContext* tlsctx, const std::string& hostname);
  87. #endif // ENABLE_SSL
  88. #ifdef HAVE_LIBSSH2
  89. std::unique_ptr<SSHSession> sshSession_;
  90. void sshCheckDirection();
  91. #endif // HAVE_LIBSSH2
  92. void init();
  93. void bind(const struct sockaddr* addr, socklen_t addrlen);
  94. void setSockOpt(int level, int optname, void* optval, socklen_t optlen);
  95. public:
  96. SocketCore(int sockType = SOCK_STREAM);
  97. // Formally, private constructor, but made public to use with
  98. // std::make_shared.
  99. SocketCore(sock_t sockfd, int sockType);
  100. ~SocketCore();
  101. sock_t getSockfd() const { return sockfd_; }
  102. bool isOpen() const { return sockfd_ != (sock_t)-1; }
  103. void setMulticastInterface(const std::string& localAddr);
  104. void setMulticastTtl(unsigned char ttl);
  105. void setMulticastLoop(unsigned char loop);
  106. void joinMulticastGroup(const std::string& multicastAddr,
  107. uint16_t multicastPort, const std::string& localAddr);
  108. // Enables TCP_NODELAY socket option if f == true.
  109. void setTcpNodelay(bool f);
  110. // Set DSCP byte
  111. void applyIpDscp();
  112. static void setIpDscp(int ipDscp)
  113. {
  114. // Here we prepare DSCP value for IPTOS option, which sets whole DS field
  115. ipDscp_ = ipDscp << 2;
  116. }
  117. void create(int family, int protocol = 0);
  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. void bind(const char* addrp, uint16_t port, int family,
  127. int flags = AI_PASSIVE);
  128. /**
  129. * Listens form connection on it.
  130. * Call bind(uint16_t) before calling this function.
  131. */
  132. void beginListen();
  133. /**
  134. * Returns host address, family and port of this socket.
  135. */
  136. Endpoint getAddrInfo() const;
  137. /**
  138. * Stores address of this socket to sockaddr. len must be
  139. * initialized to the size of sockaddr. On success, address data is
  140. * stored in sockaddr and actual size of address structure is stored
  141. * in len.
  142. */
  143. void getAddrInfo(sockaddr_union& sockaddr, socklen_t& len) const;
  144. /**
  145. * Returns address family of this socket.
  146. * The socket must be connected or bounded to address.
  147. */
  148. int getAddressFamily() const;
  149. /**
  150. * Returns peer's address, family and port.
  151. */
  152. Endpoint getPeerInfo() const;
  153. /**
  154. * Accepts incoming connection on this socket.
  155. * You must call beginListen() before calling this method.
  156. * @return accepted socket.
  157. */
  158. std::shared_ptr<SocketCore> acceptConnection() const;
  159. /**
  160. * Connects to the server named host and the destination port is port.
  161. * This method makes socket non-blocking mode.
  162. * To make the socket blocking mode again, call setBlockingMode() after
  163. * the connection is established.
  164. * @param host hostname or ip address to connect to
  165. * @param port service port number to connect to
  166. * @param tcpNodelay true to disable Nagle algorithm
  167. */
  168. void establishConnection(const std::string& host, uint16_t port,
  169. bool tcpNodelay = true);
  170. void setNonBlockingMode();
  171. /**
  172. * Makes this socket blocking mode.
  173. */
  174. void setBlockingMode();
  175. /**
  176. * Closes the connection of this socket.
  177. */
  178. void closeConnection();
  179. /**
  180. * Checks whether this socket is available for writing.
  181. * @param timeout the amount of time elapsed before the checking are timed
  182. * out.
  183. * @return true if the socket is available for writing,
  184. * otherwise returns false.
  185. */
  186. bool isWritable(time_t timeout);
  187. /**
  188. * Checks whether this socket is available for reading.
  189. * @param timeout the amount of time elapsed before the checking are timed
  190. * out.
  191. * @return true if the socket is available for reading,
  192. * otherwise returns false.
  193. */
  194. bool isReadable(time_t timeout);
  195. /**
  196. * Writes data into this socket. data is a pointer pointing the first
  197. * byte of the data and len is the length of data.
  198. * If the underlying socket is in blocking mode, this method may block until
  199. * all data is sent.
  200. * If the underlying socket is in non-blocking mode, this method may return
  201. * even if all data is sent. The size of written data is returned. If
  202. * underlying socket gets EAGAIN, wantRead_ or wantWrite_ is set accordingly.
  203. * This method sets wantRead_ and wantWrite_ to false before do anything else.
  204. * @param data data to write
  205. * @param len length of data
  206. */
  207. ssize_t writeData(const void* data, size_t len);
  208. ssize_t writeData(const std::string& msg)
  209. {
  210. return writeData(msg.c_str(), msg.size());
  211. }
  212. ssize_t writeData(const void* data, size_t len, const std::string& host,
  213. uint16_t port);
  214. ssize_t writeVector(a2iovec* iov, size_t iovcnt);
  215. /**
  216. * Reads up to len bytes from this socket.
  217. * data is a pointer pointing the first
  218. * byte of the data, which must be allocated before this method is called.
  219. * len is the size of the allocated memory. When this method returns
  220. * successfully, len is replaced by the size of the read data.
  221. * If the underlying socket is in blocking mode, this method may block until
  222. * at least 1byte is received.
  223. * If the underlying socket is in non-blocking mode, this method may return
  224. * even if no single byte is received. If the underlying socket gets EAGAIN,
  225. * wantRead_ or wantWrite_ is set accordingly.
  226. * This method sets wantRead_ and wantWrite_ to false before do anything else.
  227. * @param data holder to store data.
  228. * @param len the maximum size data can store. This method assigns
  229. * the number of bytes read to len.
  230. */
  231. void readData(void* data, size_t& len);
  232. // sender.addr will be numerihost assigned.
  233. ssize_t readDataFrom(void* data, size_t len, Endpoint& sender);
  234. #ifdef ENABLE_SSL
  235. // Performs TLS server side handshake. If handshake is completed,
  236. // returns true. If handshake has not been done yet, returns false.
  237. bool tlsAccept();
  238. // Performs TLS client side handshake. If handshake is completed,
  239. // returns true. If handshake has not been done yet, returns false.
  240. //
  241. // If you are going to verify peer's certificate, hostname must be
  242. // supplied.
  243. bool tlsConnect(const std::string& hostname);
  244. #endif // ENABLE_SSL
  245. #ifdef HAVE_LIBSSH2
  246. // Performs SSH handshake
  247. bool sshHandshake(const std::string& hashType, const std::string& digest);
  248. // Performs SSH authentication using username and password.
  249. bool sshAuthPassword(const std::string& user, const std::string& password);
  250. // Starts sftp session and open remote file |path|.
  251. bool sshSFTPOpen(const std::string& path);
  252. // Closes sftp remote file gracefully
  253. bool sshSFTPClose();
  254. // Gets total length and modified time for remote file currently
  255. // opened. |path| is used for logging.
  256. bool sshSFTPStat(int64_t& totalLength, time_t& mtime,
  257. const std::string& path);
  258. // Seeks file position to |pos|.
  259. void sshSFTPSeek(int64_t pos);
  260. bool sshGracefulShutdown();
  261. #endif // HAVE_LIBSSH2
  262. bool operator==(const SocketCore& s) { return sockfd_ == s.sockfd_; }
  263. bool operator!=(const SocketCore& s) { return !(*this == s); }
  264. bool operator<(const SocketCore& s) { return sockfd_ < s.sockfd_; }
  265. std::string getSocketError() const;
  266. /**
  267. * Returns true if the underlying socket gets EAGAIN in the previous
  268. * readData() or writeData() and the socket needs more incoming data to
  269. * continue the operation.
  270. */
  271. bool wantRead() const;
  272. /**
  273. * Returns true if the underlying socket gets EAGAIN in the previous
  274. * readData() or writeData() and the socket needs to write more data.
  275. */
  276. bool wantWrite() const;
  277. // Returns buffered data which are already received. This data was
  278. // already read from socket, and ready to read without reading
  279. // socket.
  280. size_t getRecvBufferedLength() const;
  281. #ifdef ENABLE_SSL
  282. static void
  283. setClientTLSContext(const std::shared_ptr<TLSContext>& tlsContext);
  284. static void
  285. setServerTLSContext(const std::shared_ptr<TLSContext>& tlsContext);
  286. #endif // ENABLE_SSL
  287. static void setProtocolFamily(int protocolFamily)
  288. {
  289. protocolFamily_ = protocolFamily;
  290. }
  291. static void setSocketRecvBufferSize(int size);
  292. static int getSocketRecvBufferSize();
  293. // Bind socket to interface. interface may be specified as a
  294. // hostname, IP address or interface name like eth0. If the given
  295. // interface is not found or binding socket is failed, exception
  296. // will be thrown. Set protocolFamily_ before calling this function
  297. // if you limit protocol family.
  298. //
  299. // We cannot use interface as an argument because it is a reserved
  300. // keyword in MSVC.
  301. static void bindAddress(const std::string& iface);
  302. static void bindAllAddress(const std::string& ifaces);
  303. // Collects IP addresses of given interface iface and stores in
  304. // ifAddres. iface may be specified as a hostname, IP address or
  305. // interface name like eth0. You can limit the family of IP
  306. // addresses to collect using family argument. aiFlags is passed to
  307. // getaddrinfo() as hints.ai_flags. No throw.
  308. static std::vector<SockAddr> getInterfaceAddress(const std::string& iface,
  309. int family = AF_UNSPEC,
  310. int aiFlags = 0);
  311. };
  312. // Set default ai_flags. hints.ai_flags is initialized with this
  313. // value.
  314. void setDefaultAIFlags(int flags);
  315. // Wrapper function for getaddrinfo(). The value
  316. // flags|DEFAULT_AI_FLAGS is used as ai_flags. You can override
  317. // DEFAULT_AI_FLAGS value by calling setDefaultAIFlags() with new
  318. // flags.
  319. int callGetaddrinfo(struct addrinfo** resPtr, const char* host,
  320. const char* service, int family, int sockType, int flags,
  321. int protocol);
  322. // Provides functionality of inet_ntop using getnameinfo. The return
  323. // value is the exact value of getnameinfo returns. You can get error
  324. // message using gai_strerror(3).
  325. int inetNtop(int af, const void* src, char* dst, socklen_t size);
  326. // Provides functionality of inet_pton using getBinAddr. If af is
  327. // AF_INET, dst is assumed to be the pointer to struct in_addr. If af
  328. // is AF_INET6, dst is assumed to be the pointer to struct in6_addr.
  329. //
  330. // This function returns 0 if it succeeds, or -1.
  331. int inetPton(int af, const char* src, void* dst);
  332. namespace net {
  333. // Stores binary representation of IP address ip which is represented
  334. // in text. ip must be numeric IPv4 or IPv6 address. dest must be
  335. // allocated by caller before the call. For IPv4 address, dest must be
  336. // at least 4. For IPv6 address, dest must be at least 16. Returns the
  337. // number of bytes written in dest, that is 4 for IPv4 and 16 for
  338. // IPv6. Return 0 if error occurred.
  339. size_t getBinAddr(void* dest, const std::string& ip);
  340. // Verifies hostname against presented identifiers in the certificate.
  341. // The implementation is based on the procedure described in RFC 6125.
  342. bool verifyHostname(const std::string& hostname,
  343. const std::vector<std::string>& dnsNames,
  344. const std::vector<std::string>& ipAddrs,
  345. const std::string& commonName);
  346. // Checks public IP address are configured for each family: IPv4 and
  347. // IPv6. The result can be obtained using getIpv4AddrConfigured() and
  348. // getIpv6AddrConfigured() respectively.
  349. void checkAddrconfig();
  350. bool getIPv4AddrConfigured();
  351. bool getIPv6AddrConfigured();
  352. } // namespace net
  353. } // namespace aria2
  354. #endif // D_SOCKET_CORE_H