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