2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <netinet/in.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
28 #include <android/multinetwork.h>
29 #include <android-base/stringprintf.h>
35 Parameters() : ss({}), port("80"), path("/") {}
37 struct sockaddr_storage ss;
45 bool parseUrl(const struct Arguments& args, struct Parameters* parameters) {
46 if (parameters == nullptr) { return false; }
48 static const char HTTP_PREFIX[] = "http://";
49 if (strncmp(args.arg1, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
50 std::cerr << "Only " << HTTP_PREFIX << " URLs supported." << std::endl;
54 parameters->host = std::string(args.arg1).substr(strlen(HTTP_PREFIX));
55 const auto first_slash = parameters->host.find_first_of("/");
56 if (first_slash != std::string::npos) {
57 parameters->path = parameters->host.substr(first_slash);
58 parameters->host.erase(first_slash);
61 if (parameters->host.size() == 0) {
62 std::cerr << "Host portion cannot be empty." << std::endl;
66 if (parameters->host[0] == '[') {
67 const auto closing_bracket = parameters->host.find_first_of("]");
68 if (closing_bracket == std::string::npos) {
69 std::cerr << "Missing closing bracket." << std::endl;
72 parameters->hostname = parameters->host.substr(1, closing_bracket - 1);
74 const auto colon_port = closing_bracket + 1;
75 if (colon_port < parameters->host.size()) {
76 if (parameters->host[colon_port] != ':') {
77 std::cerr << "Malformed port portion." << std::endl;
80 parameters->port = parameters->host.substr(closing_bracket + 2);
83 const auto first_colon = parameters->host.find_first_of(":");
84 if (first_colon != std::string::npos) {
85 parameters->port = parameters->host.substr(first_colon + 1);
86 parameters->hostname = parameters->host.substr(0, first_colon);
88 parameters->hostname = parameters->host;
92 // TODO: find the request portion to send (before '#...').
94 std::cerr << "Resolving hostname=" << parameters->hostname
95 << ", port=" << parameters->port
98 struct addrinfo hints = {
99 .ai_family = args.family,
100 .ai_socktype = SOCK_STREAM,
102 struct addrinfo *result = nullptr;
105 switch (args.api_mode) {
106 case ApiMode::EXPLICIT:
107 rval = android_getaddrinfofornetwork(args.nethandle,
108 parameters->hostname.c_str(),
109 parameters->port.c_str(),
112 case ApiMode::PROCESS:
113 rval = getaddrinfo(parameters->hostname.c_str(),
114 parameters->port.c_str(),
119 std::cerr << "Unknown api mode." << std::endl;
124 std::cerr << "DNS resolution failure; gaierror=" << rval
125 << " [" << gai_strerror(rval) << "]"
130 memcpy(&(parameters->ss), result[0].ai_addr, result[0].ai_addrlen);
131 std::cerr << "Connecting to: "
132 << inetSockaddrToString(result[0].ai_addr)
135 freeaddrinfo(result);
140 int makeTcpSocket(sa_family_t address_family, net_handle_t nethandle) {
141 int fd = socket(address_family, SOCK_STREAM, IPPROTO_TCP);
143 std::cerr << "failed to create TCP socket" << std::endl;
147 // Don't let reads or writes block indefinitely. We cannot control
148 // connect() timeouts without nonblocking sockets and select/poll/epoll.
149 const struct timeval timeo = { 5, 0 }; // 5 seconds
150 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo));
151 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo));
153 if (nethandle != NETWORK_UNSPECIFIED) {
154 if (android_setsocknetwork(nethandle, fd) != 0) {
156 std::cerr << "android_setsocknetwork() failed;"
157 << " errno: " << errnum << " [" << strerror(errnum) << "]"
167 int doHttpQuery(int fd, const struct Parameters& parameters) {
170 reinterpret_cast<const struct sockaddr *>(&(parameters.ss)),
171 (parameters.ss.ss_family == AF_INET6)
172 ? sizeof(struct sockaddr_in6)
173 : sizeof(struct sockaddr_in)) != 0) {
175 std::cerr << "Failed to connect; errno=" << errnum
176 << " [" << strerror(errnum) << "]"
181 const std::string request(android::base::StringPrintf(
182 "GET %s HTTP/1.1\r\n"
185 "Connection: close\r\n"
186 "User-Agent: httpurl/0.0\r\n"
188 parameters.path.c_str(), parameters.host.c_str()));
189 const ssize_t sent = write(fd, request.c_str(), request.size());
190 if (sent != static_cast<ssize_t>(request.size())) {
191 std::cerr << "Sent only " << sent << "/" << request.size() << " bytes"
198 rval = recv(fd, buf, sizeof(buf), 0);
201 const int saved_errno = errno;
202 std::cerr << "Failed to recv; errno=" << saved_errno
203 << " [" << strerror(saved_errno) << "]"
205 } else if (rval > 0) {
206 std::cout.write(buf, rval);
210 std::cout << std::endl;
216 int main(int argc, const char* argv[]) {
219 struct Arguments args;
220 if (!args.parseArguments(argc, argv)) { return rval; }
222 if (args.api_mode == ApiMode::PROCESS) {
223 rval = android_setprocnetwork(args.nethandle);
226 std::cerr << "android_setprocnetwork(" << args.nethandle << ") failed;"
227 << " errno: " << errnum << " [" << strerror(errnum) << "]"
233 struct Parameters parameters;
234 if (!parseUrl(args, ¶meters)) { return -1; }
236 // TODO: Fall back from IPv6 to IPv4 if ss.ss_family is AF_UNSPEC.
237 // This will involve changes to parseUrl() as well.
238 struct FdAutoCloser closer = makeTcpSocket(
239 parameters.ss.ss_family,
240 (args.api_mode == ApiMode::EXPLICIT) ? args.nethandle
241 : NETWORK_UNSPECIFIED);
242 if (closer.fd < 0) { return closer.fd; }
244 return doHttpQuery(closer.fd, parameters);