123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158 |
- #ifndef TOOLS_ANDROID_FORWARDER2_SOCKET_H_
- #define TOOLS_ANDROID_FORWARDER2_SOCKET_H_
- #include <fcntl.h>
- #include <netinet/in.h>
- #include <stddef.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include <string>
- #include <vector>
- #include "base/macros.h"
- namespace forwarder2 {
- class Socket {
- public:
- Socket();
- ~Socket();
- bool BindUnix(const std::string& path);
- bool BindTcp(const std::string& host, int port);
- bool ConnectUnix(const std::string& path);
- bool ConnectTcp(const std::string& host, int port);
-
- void Shutdown();
-
- void Close();
- bool IsClosed() const { return socket_ < 0; }
- int fd() const { return socket_; }
- bool Accept(Socket* new_socket);
-
- int GetPort();
-
-
-
- int Read(void* buffer, size_t buffer_size);
-
- int ReadWithTimeout(void* buffer, size_t buffer_size, int timeout_secs);
-
-
-
- int NonBlockingRead(void* buffer, size_t buffer_size);
-
- int Write(const void* buffer, size_t count);
-
- int NonBlockingWrite(const void* buffer, size_t count);
-
-
-
-
- int ReadNumBytes(void* buffer, size_t num_bytes);
-
- int ReadNumBytesWithTimeout(void* buffer, size_t num_bytes, int timeout_secs);
-
-
-
- int WriteNumBytes(const void* buffer, size_t num_bytes);
-
-
- int WriteString(const std::string& buffer);
- bool has_error() const { return socket_error_; }
-
-
-
- void AddEventFd(int event_fd);
-
-
- bool DidReceiveEventOnFd(int fd) const;
- bool DidReceiveEvent() const;
- static pid_t GetUnixDomainSocketProcessOwner(const std::string& path);
- private:
- enum EventType {
- READ,
- WRITE
- };
- union SockAddr {
-
- sockaddr_in addr4;
-
- sockaddr_in6 addr6;
-
- sockaddr_un addr_un;
- };
- struct Event {
- int fd;
- bool was_fired;
- };
- bool SetNonBlocking();
-
- bool InitTcpSocket(const std::string& host, int port);
- bool InitUnixSocket(const std::string& path);
- bool BindAndListen();
- bool Connect();
- bool Resolve(const std::string& host);
- bool InitSocketInternal();
- void SetSocketError();
-
- bool WaitForEvent(EventType type, int timeout_secs);
- int socket_;
- int port_;
- bool socket_error_;
-
- int family_;
- SockAddr addr_;
-
- sockaddr* addr_ptr_;
-
- socklen_t addr_len_;
-
-
- std::vector<Event> events_;
- DISALLOW_COPY_AND_ASSIGN(Socket);
- };
- }
- #endif
|