1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <netdb.h>
21 #include <netinet/in.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
24 #include <sys/uio.h>
25 #include <iostream>
26 #include <string>
27
28 #include <android/multinetwork.h>
29 #include <android-base/stringprintf.h>
30 #include "common.h"
31
32 using android::base::StringPrintf;
33
34 struct Parameters {
ParametersParameters35 Parameters() : ss({}), port("80"), path("/") {}
36
37 struct sockaddr_storage ss;
38 std::string host;
39 std::string hostname;
40 std::string port;
41 std::string path;
42 };
43
44 bool resolveHostname(const struct Arguments& args, struct Parameters* parameters);
45
parseUrl(const struct Arguments & args,struct Parameters * parameters)46 bool parseUrl(const struct Arguments& args, struct Parameters* parameters) {
47 if (parameters == nullptr) { return false; }
48
49 if (args.random_name) {
50 parameters->host = StringPrintf("%d-%d-ipv6test.ds.metric.gstatic.com", rand(), rand());
51 parameters->hostname = parameters->host;
52 parameters->path = "/ip.js?fmt=text";
53 return resolveHostname(args, parameters);
54 }
55
56 static const char HTTP_PREFIX[] = "http://";
57 if (strncmp(args.arg1, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
58 std::cerr << "Only " << HTTP_PREFIX << " URLs supported." << std::endl;
59 return false;
60 }
61
62 parameters->host = std::string(args.arg1).substr(strlen(HTTP_PREFIX));
63 const auto first_slash = parameters->host.find_first_of('/');
64 if (first_slash != std::string::npos) {
65 parameters->path = parameters->host.substr(first_slash);
66 parameters->host.erase(first_slash);
67 }
68
69 if (parameters->host.size() == 0) {
70 std::cerr << "Host portion cannot be empty." << std::endl;
71 return false;
72 }
73
74 if (parameters->host[0] == '[') {
75 const auto closing_bracket = parameters->host.find_first_of(']');
76 if (closing_bracket == std::string::npos) {
77 std::cerr << "Missing closing bracket." << std::endl;
78 return false;
79 }
80 parameters->hostname = parameters->host.substr(1, closing_bracket - 1);
81
82 const auto colon_port = closing_bracket + 1;
83 if (colon_port < parameters->host.size()) {
84 if (parameters->host[colon_port] != ':') {
85 std::cerr << "Malformed port portion." << std::endl;
86 return false;
87 }
88 parameters->port = parameters->host.substr(closing_bracket + 2);
89 }
90 } else {
91 const auto first_colon = parameters->host.find_first_of(':');
92 if (first_colon != std::string::npos) {
93 parameters->port = parameters->host.substr(first_colon + 1);
94 parameters->hostname = parameters->host.substr(0, first_colon);
95 } else {
96 parameters->hostname = parameters->host;
97 }
98 }
99
100 // TODO: find the request portion to send (before '#...').
101
102 return resolveHostname(args, parameters);
103 }
104
resolveHostname(const struct Arguments & args,struct Parameters * parameters)105 bool resolveHostname(const struct Arguments& args, struct Parameters* parameters) {
106 std::cerr << "Resolving hostname=" << parameters->hostname
107 << ", port=" << parameters->port
108 << std::endl;
109
110 struct addrinfo hints = {
111 .ai_family = args.family,
112 .ai_socktype = SOCK_STREAM,
113 };
114 struct addrinfo *result = nullptr;
115
116 int rval = -1;
117 switch (args.api_mode) {
118 case ApiMode::EXPLICIT:
119 rval = android_getaddrinfofornetwork(args.nethandle,
120 parameters->hostname.c_str(),
121 parameters->port.c_str(),
122 &hints, &result);
123 break;
124 case ApiMode::PROCESS:
125 rval = getaddrinfo(parameters->hostname.c_str(),
126 parameters->port.c_str(),
127 &hints, &result);
128 break;
129 default:
130 // Unreachable.
131 std::cerr << "Unknown api mode." << std::endl;
132 return false;
133 }
134
135 if (rval != 0) {
136 std::cerr << "DNS resolution failure; gaierror=" << rval
137 << " [" << gai_strerror(rval) << "]"
138 << std::endl;
139 return rval;
140 }
141
142 memcpy(&(parameters->ss), result[0].ai_addr, result[0].ai_addrlen);
143 std::cerr << "Connecting to: "
144 << inetSockaddrToString(result[0].ai_addr)
145 << std::endl;
146
147 freeaddrinfo(result);
148 return true;
149 }
150
makeTcpSocket(sa_family_t address_family,net_handle_t nethandle)151 int makeTcpSocket(sa_family_t address_family, net_handle_t nethandle) {
152 int fd = socket(address_family, SOCK_STREAM, IPPROTO_TCP);
153 if (fd < 0) {
154 std::cerr << "failed to create TCP socket" << std::endl;
155 return -1;
156 }
157
158 // Don't let reads or writes block indefinitely. We cannot control
159 // connect() timeouts without nonblocking sockets and select/poll/epoll.
160 const struct timeval timeo = { 5, 0 }; // 5 seconds
161 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo));
162 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo));
163
164 if (nethandle != NETWORK_UNSPECIFIED) {
165 if (android_setsocknetwork(nethandle, fd) != 0) {
166 int errnum = errno;
167 std::cerr << "android_setsocknetwork() failed;"
168 << " errno: " << errnum << " [" << strerror(errnum) << "]"
169 << std::endl;
170 close(fd);
171 return -1;
172 }
173 }
174 return fd;
175 }
176
177
doHttpQuery(int fd,const struct Parameters & parameters)178 int doHttpQuery(int fd, const struct Parameters& parameters) {
179 int rval = -1;
180 if (connect(fd,
181 reinterpret_cast<const struct sockaddr *>(&(parameters.ss)),
182 (parameters.ss.ss_family == AF_INET6)
183 ? sizeof(struct sockaddr_in6)
184 : sizeof(struct sockaddr_in)) != 0) {
185 int errnum = errno;
186 std::cerr << "Failed to connect; errno=" << errnum
187 << " [" << strerror(errnum) << "]"
188 << std::endl;
189 return -1;
190 }
191
192 const std::string request(android::base::StringPrintf(
193 "GET %s HTTP/1.1\r\n"
194 "Host: %s\r\n"
195 "Accept: */*\r\n"
196 "Connection: close\r\n"
197 "User-Agent: httpurl/0.0\r\n"
198 "\r\n",
199 parameters.path.c_str(), parameters.host.c_str()));
200 const ssize_t sent = write(fd, request.c_str(), request.size());
201 if (sent != static_cast<ssize_t>(request.size())) {
202 std::cerr << "Sent only " << sent << "/" << request.size() << " bytes"
203 << std::endl;
204 return -1;
205 }
206
207 char buf[4*1024];
208 do {
209 rval = recv(fd, buf, sizeof(buf), 0);
210
211 if (rval < 0) {
212 const int saved_errno = errno;
213 std::cerr << "Failed to recv; errno=" << saved_errno
214 << " [" << strerror(saved_errno) << "]"
215 << std::endl;
216 } else if (rval > 0) {
217 std::cout.write(buf, rval);
218 std::cout.flush();
219 }
220 } while (rval > 0);
221 std::cout << std::endl;
222
223 return 0;
224 }
225
226
main(int argc,const char * argv[])227 int main(int argc, const char* argv[]) {
228 int rval = -1;
229
230 struct Arguments args;
231 if (!args.parseArguments(argc, argv)) { return rval; }
232
233 if (args.api_mode == ApiMode::PROCESS) {
234 rval = android_setprocnetwork(args.nethandle);
235 if (rval != 0) {
236 int errnum = errno;
237 std::cerr << "android_setprocnetwork(" << args.nethandle << ") failed;"
238 << " errno: " << errnum << " [" << strerror(errnum) << "]"
239 << std::endl;
240 return rval;
241 }
242 }
243
244 struct Parameters parameters;
245 if (!parseUrl(args, ¶meters)) { return -1; }
246
247 int ret = 0;
248
249 for (int i = 0; i < args.attempts; i++) {
250 // TODO: Fall back from IPv6 to IPv4 if ss.ss_family is AF_UNSPEC.
251 // This will involve changes to parseUrl() as well.
252 struct FdAutoCloser closer = makeTcpSocket(
253 parameters.ss.ss_family,
254 (args.api_mode == ApiMode::EXPLICIT) ? args.nethandle : NETWORK_UNSPECIFIED);
255 if (closer.fd < 0) {
256 return closer.fd;
257 }
258
259 ret |= doHttpQuery(closer.fd, parameters);
260 }
261
262 return ret;
263 }
264