Make the simple QUIC client able to resolve hosts.
[chromium-blink-merge.git] / net / tools / quic / quic_simple_client_bin.cc
blob396009290943db575988b4d270cd3ec1687bdb22
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 // A binary wrapper for QuicClient.
6 // Connects to a host using QUIC, sends a request to the provided URL, and
7 // displays the response.
8 //
9 // Some usage examples:
11 // TODO(rtenneti): make --host optional by getting IP Address of URL's host.
13 // Get IP address of the www.google.com
14 // IP=`dig www.google.com +short | head -1`
16 // Standard request/response:
17 // quic_client http://www.google.com --host=${IP}
18 // quic_client http://www.google.com --quiet --host=${IP}
19 // quic_client https://www.google.com --port=443 --host=${IP}
21 // Use a specific version:
22 // quic_client http://www.google.com --version=23 --host=${IP}
24 // Send a POST instead of a GET:
25 // quic_client http://www.google.com --body="this is a POST body" --host=${IP}
27 // Append additional headers to the request:
28 // quic_client http://www.google.com --host=${IP}
29 // --headers="Header-A: 1234; Header-B: 5678"
31 // Connect to a host different to the URL being requested:
32 // Get IP address of the www.google.com
33 // IP=`dig www.google.com +short | head -1`
34 // quic_client mail.google.com --host=${IP}
36 // Try to connect to a host which does not speak QUIC:
37 // Get IP address of the www.example.com
38 // IP=`dig www.example.com +short | head -1`
39 // quic_client http://www.example.com --host=${IP}
41 #include <iostream>
43 #include "base/at_exit.h"
44 #include "base/command_line.h"
45 #include "base/logging.h"
46 #include "base/strings/string_number_conversions.h"
47 #include "base/strings/string_split.h"
48 #include "base/strings/string_util.h"
49 #include "net/base/ip_endpoint.h"
50 #include "net/base/net_errors.h"
51 #include "net/base/net_log.h"
52 #include "net/base/privacy_mode.h"
53 #include "net/cert/cert_verifier.h"
54 #include "net/http/http_request_info.h"
55 #include "net/http/transport_security_state.h"
56 #include "net/quic/crypto/proof_verifier_chromium.h"
57 #include "net/quic/quic_protocol.h"
58 #include "net/quic/quic_server_id.h"
59 #include "net/quic/quic_utils.h"
60 #include "net/spdy/spdy_http_utils.h"
61 #include "net/tools/quic/quic_simple_client.h"
62 #include "net/tools/quic/synchronous_host_resolver.h"
63 #include "url/gurl.h"
65 using base::StringPiece;
66 using net::CertVerifier;
67 using net::ProofVerifierChromium;
68 using net::TransportSecurityState;
69 using std::cout;
70 using std::cerr;
71 using std::map;
72 using std::string;
73 using std::vector;
74 using std::endl;
76 // The IP or hostname the quic client will connect to.
77 string FLAGS_host = "";
78 // The port to connect to.
79 int32 FLAGS_port = 80;
80 // If set, send a POST with this body.
81 string FLAGS_body = "";
82 // A semicolon separated list of key:value pairs to add to request headers.
83 string FLAGS_headers = "";
84 // Set to true for a quieter output experience.
85 bool FLAGS_quiet = false;
86 // QUIC version to speak, e.g. 21. If not set, then all available versions are
87 // offered in the handshake.
88 int32 FLAGS_quic_version = -1;
89 // If true, a version mismatch in the handshake is not considered a failure.
90 // Useful for probing a server to determine if it speaks any version of QUIC.
91 bool FLAGS_version_mismatch_ok = false;
92 // If true, an HTTP response code of 3xx is considered to be a successful
93 // response, otherwise a failure.
94 bool FLAGS_redirect_is_success = true;
96 int main(int argc, char *argv[]) {
97 base::CommandLine::Init(argc, argv);
98 base::CommandLine* line = base::CommandLine::ForCurrentProcess();
99 const base::CommandLine::StringVector& urls = line->GetArgs();
101 logging::LoggingSettings settings;
102 settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
103 CHECK(logging::InitLogging(settings));
105 if (line->HasSwitch("h") || line->HasSwitch("help") || urls.empty()) {
106 const char* help_str =
107 "Usage: quic_client [options] <url>\n"
108 "\n"
109 "<url> with scheme must be provided (e.g. http://www.google.com)\n\n"
110 "Options:\n"
111 "-h, --help show this help message and exit\n"
112 "--host=<host> specify the IP address of the hostname to "
113 "connect to\n"
114 "--port=<port> specify the port to connect to\n"
115 "--body=<body> specify the body to post\n"
116 "--headers=<headers> specify a semicolon separated list of "
117 "key:value pairs to add to request headers\n"
118 "--quiet specify for a quieter output experience\n"
119 "--quic-version=<quic version> specify QUIC version to speak\n"
120 "--version_mismatch_ok if specified a version mismatch in the "
121 "handshake is not considered a failure\n"
122 "--redirect_is_success if specified an HTTP response code of 3xx "
123 "is considered to be a successful response, otherwise a failure\n";
124 cout << help_str;
125 exit(0);
127 if (line->HasSwitch("host")) {
128 FLAGS_host = line->GetSwitchValueASCII("host");
130 if (line->HasSwitch("port")) {
131 if (!base::StringToInt(line->GetSwitchValueASCII("port"), &FLAGS_port)) {
132 std::cerr << "--port must be an integer\n";
133 return 1;
136 if (line->HasSwitch("body")) {
137 FLAGS_body = line->GetSwitchValueASCII("body");
139 if (line->HasSwitch("headers")) {
140 FLAGS_headers = line->GetSwitchValueASCII("headers");
142 if (line->HasSwitch("quiet")) {
143 FLAGS_quiet = true;
145 if (line->HasSwitch("quic-version")) {
146 int quic_version;
147 if (base::StringToInt(line->GetSwitchValueASCII("quic-version"),
148 &quic_version)) {
149 FLAGS_quic_version = quic_version;
152 if (line->HasSwitch("version_mismatch_ok")) {
153 FLAGS_version_mismatch_ok = true;
155 if (line->HasSwitch("redirect_is_success")) {
156 FLAGS_redirect_is_success = true;
159 VLOG(1) << "server host: " << FLAGS_host << " port: " << FLAGS_port
160 << " body: " << FLAGS_body << " headers: " << FLAGS_headers
161 << " quiet: " << FLAGS_quiet
162 << " quic-version: " << FLAGS_quic_version
163 << " version_mismatch_ok: " << FLAGS_version_mismatch_ok
164 << " redirect_is_success: " << FLAGS_redirect_is_success;
166 base::AtExitManager exit_manager;
167 base::MessageLoopForIO message_loop;
169 // Determine IP address to connect to from supplied hostname.
170 net::IPAddressNumber ip_addr;
172 // TODO(rtenneti): GURL's doesn't support default_protocol argument, thus
173 // protocol is required in the URL.
174 GURL url(urls[0]);
175 string host = FLAGS_host;
176 if (host.empty()) {
177 host = url.host();
179 if (!net::ParseIPLiteralToNumber(host, &ip_addr)) {
180 net::AddressList addresses;
181 int rv = net::tools::SynchronousHostResolver::Resolve(host, &addresses);
182 if (rv != net::OK) {
183 LOG(ERROR) << "Unable to resolve '" << host << "' : "
184 << net::ErrorToString(rv);
185 return 1;
187 ip_addr = addresses[0].address();
190 string host_port = net::IPAddressToStringWithPort(ip_addr, FLAGS_port);
191 VLOG(1) << "Resolved " << host << " to " << host_port << endl;
193 // Build the client, and try to connect.
194 bool is_https = (FLAGS_port == 443);
195 net::QuicServerId server_id(host, FLAGS_port, is_https,
196 net::PRIVACY_MODE_DISABLED);
197 net::QuicVersionVector versions = net::QuicSupportedVersions();
198 if (FLAGS_quic_version != -1) {
199 versions.clear();
200 versions.push_back(static_cast<net::QuicVersion>(FLAGS_quic_version));
202 net::tools::QuicSimpleClient client(net::IPEndPoint(ip_addr, FLAGS_port),
203 server_id, versions);
204 scoped_ptr<CertVerifier> cert_verifier;
205 scoped_ptr<TransportSecurityState> transport_security_state;
206 if (is_https) {
207 // For secure QUIC we need to verify the cert chain.a
208 cert_verifier.reset(CertVerifier::CreateDefault());
209 transport_security_state.reset(new TransportSecurityState);
210 // TODO(rtenneti): Fix "Proof invalid: Missing context" error.
211 client.SetProofVerifier(new ProofVerifierChromium(
212 cert_verifier.get(), transport_security_state.get()));
214 if (!client.Initialize()) {
215 cerr << "Failed to initialize client." << endl;
216 return 1;
218 if (!client.Connect()) {
219 net::QuicErrorCode error = client.session()->error();
220 if (FLAGS_version_mismatch_ok && error == net::QUIC_INVALID_VERSION) {
221 cout << "Server talks QUIC, but none of the versions supoorted by "
222 << "this client: " << QuicVersionVectorToString(versions) << endl;
223 // Version mismatch is not deemed a failure.
224 return 0;
226 cerr << "Failed to connect to " << host_port
227 << ". Error: " << net::QuicUtils::ErrorToString(error) << endl;
228 return 1;
230 cout << "Connected to " << host_port << endl;
232 // Construct a GET or POST request for supplied URL.
233 net::HttpRequestInfo request;
234 request.method = FLAGS_body.empty() ? "GET" : "POST";
235 request.url = url;
237 // Append any additional headers supplied on the command line.
238 vector<string> headers_tokenized;
239 Tokenize(FLAGS_headers, ";", &headers_tokenized);
240 for (size_t i = 0; i < headers_tokenized.size(); ++i) {
241 string sp;
242 base::TrimWhitespaceASCII(headers_tokenized[i], base::TRIM_ALL, &sp);
243 if (sp.empty()) {
244 continue;
246 vector<string> kv;
247 base::SplitString(sp, ':', &kv);
248 CHECK_EQ(2u, kv.size());
249 string key;
250 base::TrimWhitespaceASCII(kv[0], base::TRIM_ALL, &key);
251 string value;
252 base::TrimWhitespaceASCII(kv[1], base::TRIM_ALL, &value);
253 request.extra_headers.SetHeader(key, value);
256 // Make sure to store the response, for later output.
257 client.set_store_response(true);
259 // Send the request.
260 net::SpdyHeaderBlock header_block;
261 net::CreateSpdyHeadersFromHttpRequest(request, request.extra_headers,
262 net::SPDY3, /*direct=*/ true,
263 &header_block);
264 client.SendRequestAndWaitForResponse(request, FLAGS_body, /*fin=*/true);
266 // Print request and response details.
267 if (!FLAGS_quiet) {
268 cout << "Request:" << endl;
269 cout << "headers:" << endl;
270 for (const std::pair<string, string>& kv : header_block) {
271 cout << " " << kv.first << ": " << kv.second << endl;
273 cout << "body: " << FLAGS_body << endl;
274 cout << endl;
275 cout << "Response:" << endl;
276 cout << "headers: " << client.latest_response_headers() << endl;
277 cout << "body: " << client.latest_response_body() << endl;
280 size_t response_code = client.latest_response_code();
281 if (response_code >= 200 && response_code < 300) {
282 cout << "Request succeeded (" << response_code << ")." << endl;
283 return 0;
284 } else if (response_code >= 300 && response_code < 400) {
285 if (FLAGS_redirect_is_success) {
286 cout << "Request succeeded (redirect " << response_code << ")." << endl;
287 return 0;
288 } else {
289 cout << "Request failed (redirect " << response_code << ")." << endl;
290 return 1;
292 } else {
293 cerr << "Request failed (" << response_code << ")." << endl;
294 return 1;