httpurl.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. #include <errno.h>
  17. #include <fcntl.h>
  18. #include <netdb.h>
  19. #include <netinet/in.h>
  20. #include <sys/socket.h>
  21. #include <sys/types.h>
  22. #include <sys/uio.h>
  23. #include <iostream>
  24. #include <string>
  25. #include <android/multinetwork.h>
  26. #include <android-base/stringprintf.h>
  27. #include "common.h"
  28. struct Parameters {
  29. Parameters() : ss({}), port("80"), path("/") {}
  30. struct sockaddr_storage ss;
  31. std::string host;
  32. std::string hostname;
  33. std::string port;
  34. std::string path;
  35. };
  36. bool parseUrl(const struct Arguments& args, struct Parameters* parameters) {
  37. if (parameters == nullptr) { return false; }
  38. static const char HTTP_PREFIX[] = "http://";
  39. if (strncmp(args.arg1, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
  40. std::cerr << "Only " << HTTP_PREFIX << " URLs supported." << std::endl;
  41. return false;
  42. }
  43. parameters->host = std::string(args.arg1).substr(strlen(HTTP_PREFIX));
  44. const auto first_slash = parameters->host.find_first_of('/');
  45. if (first_slash != std::string::npos) {
  46. parameters->path = parameters->host.substr(first_slash);
  47. parameters->host.erase(first_slash);
  48. }
  49. if (parameters->host.size() == 0) {
  50. std::cerr << "Host portion cannot be empty." << std::endl;
  51. return false;
  52. }
  53. if (parameters->host[0] == '[') {
  54. const auto closing_bracket = parameters->host.find_first_of(']');
  55. if (closing_bracket == std::string::npos) {
  56. std::cerr << "Missing closing bracket." << std::endl;
  57. return false;
  58. }
  59. parameters->hostname = parameters->host.substr(1, closing_bracket - 1);
  60. const auto colon_port = closing_bracket + 1;
  61. if (colon_port < parameters->host.size()) {
  62. if (parameters->host[colon_port] != ':') {
  63. std::cerr << "Malformed port portion." << std::endl;
  64. return false;
  65. }
  66. parameters->port = parameters->host.substr(closing_bracket + 2);
  67. }
  68. } else {
  69. const auto first_colon = parameters->host.find_first_of(':');
  70. if (first_colon != std::string::npos) {
  71. parameters->port = parameters->host.substr(first_colon + 1);
  72. parameters->hostname = parameters->host.substr(0, first_colon);
  73. } else {
  74. parameters->hostname = parameters->host;
  75. }
  76. }
  77. // TODO: find the request portion to send (before '#...').
  78. std::cerr << "Resolving hostname=" << parameters->hostname
  79. << ", port=" << parameters->port
  80. << std::endl;
  81. struct addrinfo hints = {
  82. .ai_family = args.family,
  83. .ai_socktype = SOCK_STREAM,
  84. };
  85. struct addrinfo *result = nullptr;
  86. int rval = -1;
  87. switch (args.api_mode) {
  88. case ApiMode::EXPLICIT:
  89. rval = android_getaddrinfofornetwork(args.nethandle,
  90. parameters->hostname.c_str(),
  91. parameters->port.c_str(),
  92. &hints, &result);
  93. break;
  94. case ApiMode::PROCESS:
  95. rval = getaddrinfo(parameters->hostname.c_str(),
  96. parameters->port.c_str(),
  97. &hints, &result);
  98. break;
  99. default:
  100. // Unreachable.
  101. std::cerr << "Unknown api mode." << std::endl;
  102. return false;
  103. }
  104. if (rval != 0) {
  105. std::cerr << "DNS resolution failure; gaierror=" << rval
  106. << " [" << gai_strerror(rval) << "]"
  107. << std::endl;
  108. return rval;
  109. }
  110. memcpy(&(parameters->ss), result[0].ai_addr, result[0].ai_addrlen);
  111. std::cerr << "Connecting to: "
  112. << inetSockaddrToString(result[0].ai_addr)
  113. << std::endl;
  114. freeaddrinfo(result);
  115. return true;
  116. }
  117. int makeTcpSocket(sa_family_t address_family, net_handle_t nethandle) {
  118. int fd = socket(address_family, SOCK_STREAM, IPPROTO_TCP);
  119. if (fd < 0) {
  120. std::cerr << "failed to create TCP socket" << std::endl;
  121. return -1;
  122. }
  123. // Don't let reads or writes block indefinitely. We cannot control
  124. // connect() timeouts without nonblocking sockets and select/poll/epoll.
  125. const struct timeval timeo = { 5, 0 }; // 5 seconds
  126. setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo));
  127. setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo));
  128. if (nethandle != NETWORK_UNSPECIFIED) {
  129. if (android_setsocknetwork(nethandle, fd) != 0) {
  130. int errnum = errno;
  131. std::cerr << "android_setsocknetwork() failed;"
  132. << " errno: " << errnum << " [" << strerror(errnum) << "]"
  133. << std::endl;
  134. close(fd);
  135. return -1;
  136. }
  137. }
  138. return fd;
  139. }
  140. int doHttpQuery(int fd, const struct Parameters& parameters) {
  141. int rval = -1;
  142. if (connect(fd,
  143. reinterpret_cast<const struct sockaddr *>(&(parameters.ss)),
  144. (parameters.ss.ss_family == AF_INET6)
  145. ? sizeof(struct sockaddr_in6)
  146. : sizeof(struct sockaddr_in)) != 0) {
  147. int errnum = errno;
  148. std::cerr << "Failed to connect; errno=" << errnum
  149. << " [" << strerror(errnum) << "]"
  150. << std::endl;
  151. return -1;
  152. }
  153. const std::string request(android::base::StringPrintf(
  154. "GET %s HTTP/1.1\r\n"
  155. "Host: %s\r\n"
  156. "Accept: */*\r\n"
  157. "Connection: close\r\n"
  158. "User-Agent: httpurl/0.0\r\n"
  159. "\r\n",
  160. parameters.path.c_str(), parameters.host.c_str()));
  161. const ssize_t sent = write(fd, request.c_str(), request.size());
  162. if (sent != static_cast<ssize_t>(request.size())) {
  163. std::cerr << "Sent only " << sent << "/" << request.size() << " bytes"
  164. << std::endl;
  165. return -1;
  166. }
  167. char buf[4*1024];
  168. do {
  169. rval = recv(fd, buf, sizeof(buf), 0);
  170. if (rval < 0) {
  171. const int saved_errno = errno;
  172. std::cerr << "Failed to recv; errno=" << saved_errno
  173. << " [" << strerror(saved_errno) << "]"
  174. << std::endl;
  175. } else if (rval > 0) {
  176. std::cout.write(buf, rval);
  177. std::cout.flush();
  178. }
  179. } while (rval > 0);
  180. std::cout << std::endl;
  181. return 0;
  182. }
  183. int main(int argc, const char* argv[]) {
  184. int rval = -1;
  185. struct Arguments args;
  186. if (!args.parseArguments(argc, argv)) { return rval; }
  187. if (args.api_mode == ApiMode::PROCESS) {
  188. rval = android_setprocnetwork(args.nethandle);
  189. if (rval != 0) {
  190. int errnum = errno;
  191. std::cerr << "android_setprocnetwork(" << args.nethandle << ") failed;"
  192. << " errno: " << errnum << " [" << strerror(errnum) << "]"
  193. << std::endl;
  194. return rval;
  195. }
  196. }
  197. struct Parameters parameters;
  198. if (!parseUrl(args, &parameters)) { return -1; }
  199. // TODO: Fall back from IPv6 to IPv4 if ss.ss_family is AF_UNSPEC.
  200. // This will involve changes to parseUrl() as well.
  201. struct FdAutoCloser closer = makeTcpSocket(
  202. parameters.ss.ss_family,
  203. (args.api_mode == ApiMode::EXPLICIT) ? args.nethandle
  204. : NETWORK_UNSPECIFIED);
  205. if (closer.fd < 0) { return closer.fd; }
  206. return doHttpQuery(closer.fd, parameters);
  207. }