platform/lib/src/proxy_layer.dart

158 lines
4.7 KiB
Dart
Raw Normal View History

2017-06-20 19:31:35 +00:00
import 'dart:async';
2016-11-23 22:03:06 +00:00
import 'dart:io';
2018-11-02 04:22:32 +00:00
import 'dart:convert';
2016-11-23 22:03:06 +00:00
import 'package:angel_framework/angel_framework.dart';
2018-11-02 04:22:32 +00:00
import 'package:http_parser/http_parser.dart';
import 'package:http/http.dart' as http;
2016-11-23 22:03:06 +00:00
final RegExp _straySlashes = new RegExp(r'(^/+)|(/+$)');
2018-11-02 04:22:32 +00:00
final MediaType _fallbackMediaType = MediaType('application', 'octet-stream');
2016-11-23 22:03:06 +00:00
2017-09-24 18:49:18 +00:00
class Proxy {
2016-11-23 22:03:06 +00:00
String _prefix;
2017-04-26 12:20:14 +00:00
2018-11-02 04:22:32 +00:00
final http.Client httpClient;
2017-09-24 18:49:18 +00:00
2017-04-26 12:20:14 +00:00
/// If `true` (default), then the plug-in will ignore failures to connect to the proxy, and allow other handlers to run.
final bool recoverFromDead;
2017-09-24 18:49:18 +00:00
final bool recoverFrom404;
2016-11-23 22:03:06 +00:00
final String host, mapTo, publicPath;
final int port;
2017-01-09 02:11:20 +00:00
final String protocol;
2018-11-02 04:22:32 +00:00
/// If `null` then no timout is added for requests
2017-06-20 19:31:35 +00:00
final Duration timeout;
2017-09-24 18:49:18 +00:00
Proxy(
this.httpClient,
this.host, {
this.port,
2017-06-20 19:31:35 +00:00
this.mapTo: '/',
this.publicPath: '/',
this.protocol: 'http',
this.recoverFromDead: true,
this.recoverFrom404: true,
this.timeout,
}) {
2018-11-02 04:22:32 +00:00
if (this.recoverFromDead == null) throw ArgumentError.notNull("recoverFromDead");
if (this.recoverFrom404 == null) throw ArgumentError.notNull("recoverFrom404");
_prefix = publicPath?.replaceAll(_straySlashes, '') ?? '';
2016-11-23 22:03:06 +00:00
}
2017-09-24 18:49:18 +00:00
void close() => httpClient.close();
2016-11-23 22:03:06 +00:00
2017-09-24 18:49:18 +00:00
/// Handles an incoming HTTP request.
Future<bool> handleRequest(RequestContext req, ResponseContext res) {
var path = req.path.replaceAll(_straySlashes, '');
2016-11-23 22:03:06 +00:00
2018-11-02 04:22:32 +00:00
if (_prefix.isNotEmpty) {
if (!path.startsWith(_prefix)) return new Future<bool>.value(true);
path = path.replaceFirst(_prefix, '').replaceAll(_straySlashes, '');
2016-11-23 22:03:06 +00:00
}
2017-09-24 18:49:18 +00:00
return servePath(path, req, res);
2016-11-23 22:03:06 +00:00
}
2017-09-24 18:49:18 +00:00
/// Proxies a request to the given path on the remote server.
2018-11-02 04:22:32 +00:00
Future<bool> servePath(String path, RequestContext req, ResponseContext res) async {
2017-09-24 18:49:18 +00:00
http.StreamedResponse rs;
2016-11-23 22:03:06 +00:00
2017-09-24 18:49:18 +00:00
final mapping = '$mapTo/$path'.replaceAll(_straySlashes, '');
2017-04-26 12:20:14 +00:00
try {
2017-09-24 18:49:18 +00:00
Future<http.StreamedResponse> accessRemote() async {
var url = port == null ? host : '$host:$port';
url = url.replaceAll(_straySlashes, '');
url = '$url/$mapping';
2018-11-02 11:24:22 +00:00
if (!url.startsWith(protocol)) url = '$protocol://$url';
2017-09-24 18:49:18 +00:00
url = url.replaceAll(_straySlashes, '');
var headers = <String, String>{
'host': port == null ? host : '$host:$port',
'x-forwarded-for': req.remoteAddress.address,
'x-forwarded-port': req.uri.port.toString(),
2018-11-02 04:22:32 +00:00
'x-forwarded-host': req.headers.host ?? req.headers.value('host') ?? 'none',
2017-09-24 18:49:18 +00:00
'x-forwarded-proto': protocol,
};
req.headers.forEach((name, values) {
headers[name] = values.join(',');
});
2018-11-02 04:22:32 +00:00
headers[HttpHeaders.cookieHeader] = req.cookies.map<String>((c) => '${c.name}=${c.value}').join('; ');
2017-09-24 18:49:18 +00:00
var body;
if (req.method != 'GET' && req.app.keepRawRequestBuffers == true) {
2018-11-02 04:22:32 +00:00
body = (await req.parse()).originalBuffer;
2017-06-20 19:31:35 +00:00
}
2017-09-24 18:49:18 +00:00
var rq = new http.Request(req.method, Uri.parse(url));
rq.headers.addAll(headers);
rq.headers['host'] = rq.url.host;
2018-11-02 04:22:32 +00:00
rq.encoding = Utf8Codec(allowMalformed: true);
2017-09-24 18:49:18 +00:00
if (body != null) rq.bodyBytes = body;
return httpClient.send(rq);
2017-04-26 12:20:14 +00:00
}
2017-06-20 19:31:35 +00:00
var future = accessRemote();
if (timeout != null) future = future.timeout(timeout);
rs = await future;
} on TimeoutException catch (e, st) {
2018-11-02 04:22:32 +00:00
if (recoverFromDead) return true;
throw new AngelHttpException(
e,
stackTrace: st,
statusCode: 504,
message: 'Connection to remote host "$host" timed out after ${timeout.inMilliseconds}ms.',
);
} catch (e) {
if (recoverFromDead) return true;
rethrow;
}
if (rs.statusCode == 404 && recoverFrom404) return true;
if (rs.contentLength == 0 && recoverFromDead) return true;
MediaType mediaType;
if (rs.headers.containsKey(HttpHeaders.contentTypeHeader)) {
try {
mediaType = MediaType.parse(rs.headers[HttpHeaders.contentTypeHeader]);
} on FormatException catch (e, st) {
if (recoverFromDead) return true;
2017-09-24 18:49:18 +00:00
throw new AngelHttpException(
e,
stackTrace: st,
statusCode: 504,
2018-11-02 04:22:32 +00:00
message: 'Host "$host" returned a malformed content-type',
2017-09-24 18:49:18 +00:00
);
2018-11-02 04:22:32 +00:00
}
} else {
mediaType = _fallbackMediaType;
2017-04-02 02:06:27 +00:00
}
2018-11-02 04:22:32 +00:00
var proxiedHeaders = new Map<String, String>.from(rs.headers);
2017-04-24 20:46:52 +00:00
2017-04-02 02:06:27 +00:00
res
2018-11-02 04:22:32 +00:00
..contentType = mediaType
2017-04-02 02:06:27 +00:00
..statusCode = rs.statusCode
2018-11-02 04:22:32 +00:00
..headers.addAll(proxiedHeaders);
2017-04-22 18:46:00 +00:00
2017-09-24 18:49:18 +00:00
var stream = rs.stream;
2017-04-24 20:46:52 +00:00
2018-11-02 04:22:32 +00:00
// [upgrading to dart2] Keeping this workaround as a reference. It's not properly typed for dart2
//if (rs.headers[HttpHeaders.contentEncodingHeader] == 'gzip') stream = stream.transform(gzip.encoder);
2017-04-24 20:46:52 +00:00
2017-09-24 18:49:18 +00:00
await stream.pipe(res);
2017-04-22 18:46:00 +00:00
2017-09-24 18:49:18 +00:00
return false;
2016-11-23 22:03:06 +00:00
}
}