| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library curl_client; |
| 6 |
| 7 import 'dart:io'; |
| 8 |
| 9 import 'base_client.dart'; |
| 10 import 'base_request.dart'; |
| 11 import 'streamed_response.dart'; |
| 12 import 'utils.dart'; |
| 13 |
| 14 /// A drop-in replacement for [Client] that uses the `curl` command-line utility |
| 15 /// rather than [dart:io] to make requests. This class will only exist |
| 16 /// temporarily until [dart:io] natively supports requests over HTTPS. |
| 17 class CurlClient extends BaseClient { |
| 18 /// The path to the `curl` executable to run. By default, this will look up |
| 19 /// `curl` on the system path. |
| 20 final String executable; |
| 21 |
| 22 /// Creates a new [CurlClient] with [executable] as the path to the `curl` |
| 23 /// executable. By default, this will look up `curl` on the system path. |
| 24 CurlClient([String executable]) |
| 25 : executable = executable == null ? "curl" : executable; |
| 26 |
| 27 /// Sends a request via `curl` and returns the response. |
| 28 Future<StreamedResponse> send(BaseRequest request) { |
| 29 var requestStream = request.finalize(); |
| 30 return withTempDir((tempDir) { |
| 31 var headerFile = new Path(tempDir).append("curl-headers").toNativePath(); |
| 32 var arguments = _argumentsForRequest(request, headerFile); |
| 33 var process; |
| 34 return Process.start("curl", arguments).chain((process_) { |
| 35 process = process_; |
| 36 if (requestStream.closed) { |
| 37 process.stdin.close(); |
| 38 } else { |
| 39 requestStream.pipe(process.stdin); |
| 40 } |
| 41 |
| 42 return _waitForHeaders(process, expectBody: request.method != "HEAD"); |
| 43 }).chain((_) => new File(headerFile).readAsLines()) |
| 44 .transform((lines) => _buildResponse(process, lines)); |
| 45 }); |
| 46 } |
| 47 |
| 48 /// Returns the list of arguments to `curl` necessary for performing |
| 49 /// [request]. [headerFile] is the path to the file where the response headers |
| 50 /// should be stored. |
| 51 List<String> _argumentsForRequest(BaseRequest request, String headerFile) { |
| 52 var arguments = ["--dump-header", headerFile]; |
| 53 if (request.method == 'HEAD') { |
| 54 arguments.add("--head"); |
| 55 } else { |
| 56 arguments.add("--request"); |
| 57 arguments.add(request.method); |
| 58 } |
| 59 if (request.followRedirects) { |
| 60 arguments.add("--location"); |
| 61 arguments.add("--max-redirs"); |
| 62 arguments.add(request.maxRedirects.toString()); |
| 63 } |
| 64 if (request.contentLength != 0) { |
| 65 arguments.add("--data-binary"); |
| 66 arguments.add("@-"); |
| 67 } |
| 68 |
| 69 // Override the headers automatically added by curl. We want to make it |
| 70 // behave as much like the dart:io client as possible. |
| 71 var headers = { |
| 72 'accept': '', |
| 73 'user-agent': '' |
| 74 }; |
| 75 mapAddAll(headers, request.headers); |
| 76 if (request.contentLength < 0) { |
| 77 headers['content-length'] = ''; |
| 78 headers['transfer-encoding'] = 'chunked'; |
| 79 } else if (request.contentLength > 0) { |
| 80 headers['content-length'] = request.contentLength.toString(); |
| 81 } |
| 82 |
| 83 headers.forEach((name, value) { |
| 84 arguments.add("--header"); |
| 85 arguments.add("$name: $value"); |
| 86 }); |
| 87 arguments.add(request.url.toString()); |
| 88 |
| 89 return arguments; |
| 90 } |
| 91 |
| 92 /// Returns a [Future] that completes once the `curl` [process] has finished |
| 93 /// receiving the response headers. [expectBody] indicates that the server is |
| 94 /// expected to send a response body (which is not the case for HEAD |
| 95 /// requests). |
| 96 Future _waitForHeaders(Process process, {bool expectBody}) { |
| 97 var exitCompleter = new Completer<int>(); |
| 98 var exitFuture = exitCompleter.future; |
| 99 process.onExit = (exitCode) { |
| 100 if (exitCode == 0) { |
| 101 exitCompleter.complete(0); |
| 102 return; |
| 103 } |
| 104 |
| 105 chainToCompleter(consumeInputStream(process.stderr) |
| 106 .transform((stderrBytes) { |
| 107 var message = new String.fromCharCodes(stderrBytes); |
| 108 if (exitCode == 47) { |
| 109 throw new RedirectLimitExceededException(message); |
| 110 } else { |
| 111 throw new HttpException(message); |
| 112 } |
| 113 }), exitCompleter); |
| 114 }; |
| 115 |
| 116 // If there's not going to be a response body (e.g. for HEAD requests), curl |
| 117 // prints the headers to stdout instead of the body. We want to wait until |
| 118 // all the headers are received to read them from the header file. |
| 119 if (!expectBody) { |
| 120 return Futures.wait([ |
| 121 consumeInputStream(process.stdout), |
| 122 exitFuture |
| 123 ]); |
| 124 } |
| 125 |
| 126 var completer = new Completer(); |
| 127 resetCallbacks() { |
| 128 process.stdout.onData = null; |
| 129 process.stdout.onError = null; |
| 130 process.stdout.onClosed = null; |
| 131 } |
| 132 process.stdout.onData = () { |
| 133 // TODO(nweiz): If an error happens after the body data starts being |
| 134 // received, it should be piped through Response.stream once issue |
| 135 // 3657 is fixed. |
| 136 exitFuture.handleException((e) => true); |
| 137 resetCallbacks(); |
| 138 completer.complete(null); |
| 139 }; |
| 140 process.stdout.onError = (e) { |
| 141 resetCallbacks(); |
| 142 completer.completeException(e); |
| 143 }; |
| 144 process.stdout.onClosed = () { |
| 145 resetCallbacks(); |
| 146 chainToCompleter(exitFuture, completer); |
| 147 }; |
| 148 return completer.future; |
| 149 } |
| 150 |
| 151 /// Returns a [StreamedResponse] from the response data printed by the `curl` |
| 152 /// [process]. [lines] are the headers that `curl` wrote to a file. |
| 153 StreamedResponse _buildResponse(Process process, List<String> lines) { |
| 154 // When curl follows redirects, it prints the redirect headers as well as |
| 155 // the headers of the final request. Each block is separated by a blank |
| 156 // line. We just care about the last block. There is one trailing empty |
| 157 // line, though, which we don't want to consider a separator. |
| 158 var lastBlank = lines.lastIndexOf("", lines.length - 2); |
| 159 if (lastBlank != -1) lines.removeRange(0, lastBlank + 1); |
| 160 |
| 161 var statusParts = lines.removeAt(0).split(" "); |
| 162 var status = int.parse(statusParts[1]); |
| 163 var isRedirect = status >= 300 && status < 400; |
| 164 var reasonPhrase = |
| 165 Strings.join(" ", statusParts.getRange(2, statusParts.length - 2)); |
| 166 var headers = <String>{}; |
| 167 for (var line in lines) { |
| 168 if (line.isEmpty) continue; |
| 169 var split = split1(line, ":"); |
| 170 headers[split[0].toLowerCase()] = split[1].trim(); |
| 171 } |
| 172 var responseStream = process.stdout; |
| 173 if (responseStream.closed) { |
| 174 responseStream = new ListInputStream(); |
| 175 responseStream.markEndOfStream(); |
| 176 } |
| 177 var contentLength = -1; |
| 178 if (headers.containsKey('content-length')) { |
| 179 contentLength = int.parse(headers['content-length']); |
| 180 } |
| 181 |
| 182 return new StreamedResponse(responseStream, status, contentLength, |
| 183 headers: headers, |
| 184 isRedirect: isRedirect, |
| 185 reasonPhrase: reasonPhrase); |
| 186 } |
| 187 } |
| OLD | NEW |