1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "tools/android/common/adb_connection.h"
11 #include <sys/socket.h>
12 #include <sys/types.h>
15 #include "base/logging.h"
16 #include "base/posix/eintr_wrapper.h"
17 #include "tools/android/common/net.h"
22 void CloseSocket(int fd
) {
24 int old_errno
= errno
;
25 (void) HANDLE_EINTR(close(fd
));
32 int ConnectAdbHostSocket(const char* forward_to
) {
33 // ADB port forward request format: HHHHtcp:port:address.
34 // HHHH is the hexidecimal length of the "tcp:port:address" part.
35 const size_t kBufferMaxLength
= 30;
36 const size_t kLengthOfLength
= 4;
37 const size_t kAddressMaxLength
= kBufferMaxLength
- kLengthOfLength
;
39 const char kAddressPrefix
[] = { 't', 'c', 'p', ':' };
40 size_t address_length
= arraysize(kAddressPrefix
) + strlen(forward_to
);
41 if (address_length
> kBufferMaxLength
- kLengthOfLength
) {
42 LOG(ERROR
) << "Forward to address is too long: " << forward_to
;
46 char request
[kBufferMaxLength
];
47 memcpy(request
+ kLengthOfLength
, kAddressPrefix
, arraysize(kAddressPrefix
));
48 memcpy(request
+ kLengthOfLength
+ arraysize(kAddressPrefix
),
49 forward_to
, strlen(forward_to
));
51 char length_buffer
[kLengthOfLength
+ 1];
52 snprintf(length_buffer
, arraysize(length_buffer
), "%04X",
53 static_cast<int>(address_length
));
54 memcpy(request
, length_buffer
, kLengthOfLength
);
56 int host_socket
= socket(AF_INET
, SOCK_STREAM
, 0);
57 if (host_socket
< 0) {
58 LOG(ERROR
) << "Failed to create adb socket: " << strerror(errno
);
62 DisableNagle(host_socket
);
64 const int kAdbPort
= 5037;
66 memset(&addr
, 0, sizeof(addr
));
67 addr
.sin_family
= AF_INET
;
68 addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
69 addr
.sin_port
= htons(kAdbPort
);
70 if (HANDLE_EINTR(connect(host_socket
, reinterpret_cast<sockaddr
*>(&addr
),
72 LOG(ERROR
) << "Failed to connect adb socket: " << strerror(errno
);
73 CloseSocket(host_socket
);
77 size_t bytes_remaining
= address_length
+ kLengthOfLength
;
78 size_t bytes_sent
= 0;
79 while (bytes_remaining
> 0) {
80 int ret
= HANDLE_EINTR(send(host_socket
, request
+ bytes_sent
,
83 LOG(ERROR
) << "Failed to send request: " << strerror(errno
);
84 CloseSocket(host_socket
);
89 bytes_remaining
-= ret
;
92 const size_t kAdbStatusLength
= 4;
93 char response
[kBufferMaxLength
];
94 int response_length
= HANDLE_EINTR(recv(host_socket
, response
,
95 kBufferMaxLength
, 0));
96 if (response_length
< kAdbStatusLength
||
97 strncmp("OKAY", response
, kAdbStatusLength
) != 0) {
98 LOG(ERROR
) << "Bad response from ADB: length: " << response_length
99 << " data: " << DumpBinary(response
, response_length
);
100 CloseSocket(host_socket
);