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