vibe.http.proxy 0/111(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
/** HTTP (reverse) proxy implementation Copyright: © 2012 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.http.proxy; import vibe.core.log; import vibe.http.client; import vibe.http.server; import vibe.inet.message; import vibe.stream.operations; import vibe.internal.interfaceproxy : InterfaceProxy; import std.conv; import std.exception; /* TODO: - use a client pool - implement a path based reverse proxy */ /** Transparently forwards all requests to the proxy to another host. The configurations set in 'settings' and 'proxy_settings' determines the exact behavior. */ void listenHTTPProxy(HTTPServerSettings settings, HTTPProxySettings proxy_settings) { // disable all advanced parsing in the server settings.options = HTTPServerOption.None; listenHTTP(settings, proxyRequest(proxy_settings)); } // Compatibility alias - will be deprecated soon. alias listenHTTPReverseProxy = listenHTTPProxy; /** Transparently forwards all requests to the proxy to a destination_host. You can use the hostName field in the 'settings' to combine multiple internal HTTP servers into one public web server with multiple virtual hosts. */ void listenHTTPReverseProxy(HTTPServerSettings settings, string destination_host, ushort destination_port) { URL url; url.schema = "http"; url.host = destination_host; url.port = destination_port; auto proxy_settings = new HTTPProxySettings(ProxyMode.reverse); proxy_settings.destination = url; listenHTTPReverseProxy(settings, proxy_settings); } /** Transparently forwards all requests to the proxy to the requestURL of the request. */ void listenHTTPForwardProxy(HTTPServerSettings settings) { auto proxy_settings = new HTTPProxySettings(ProxyMode.forward); proxy_settings.handleConnectRequests = true; listenHTTPProxy(settings, proxy_settings); } /** Returns a HTTP request handler that forwards any request to the specified or requested host/port. */ HTTPServerRequestDelegateS proxyRequest(HTTPProxySettings settings) { static immutable string[] non_forward_headers = ["Content-Length", "Transfer-Encoding", "Content-Encoding", "Connection"]; static InetHeaderMap non_forward_headers_map; if (non_forward_headers_map.length == 0) foreach (n; non_forward_headers) non_forward_headers_map[n] = ""; void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe { auto url = settings.destination; if (settings.proxyMode == ProxyMode.reverse) { url.localURI = req.requestURL; } else { url = URL(req.requestURL); } //handle connect tunnels if (req.method == HTTPMethod.CONNECT) { if (!settings.handleConnectRequests) { throw new HTTPStatusException(HTTPStatus.methodNotAllowed); } // CONNECT resources are of the form server:port and not // schema://server:port, so they need some adjustment // TODO: use a more efficient means to parse this url = URL.parse("http://"~req.requestURL); TCPConnection ccon; try ccon = connectTCP(url.getFilteredHost, url.port); catch (Exception e) { throw new HTTPStatusException(HTTPStatus.badGateway, "Connection to upstream server failed: "~e.msg); } res.writeVoidBody(); auto scon = res.connectProxy(); assert (scon); import vibe.core.core : runTask; runTask({ scon.pipe(ccon); }); ccon.pipe(scon); return; } //handle protocol upgrades auto pUpgrade = "Upgrade" in req.headers; auto pConnection = "Connection" in req.headers; import std.algorithm : splitter, canFind; import vibe.utils.string : icmp2; bool isUpgrade = pConnection && (*pConnection).splitter(',').canFind!(a => a.icmp2("upgrade")); void setupClientRequest(scope HTTPClientRequest creq) { creq.method = req.method; creq.headers = req.headers.dup; creq.headers["Host"] = url.getFilteredHost; //handle protocol upgrades if (!isUpgrade) { creq.headers["Connection"] = "keep-alive"; } if (settings.avoidCompressedRequests && "Accept-Encoding" in creq.headers) creq.headers.remove("Accept-Encoding"); if (auto pfh = "X-Forwarded-Host" !in creq.headers) creq.headers["X-Forwarded-Host"] = req.headers["Host"]; if (auto pfp = "X-Forwarded-Proto" !in creq.headers) creq.headers["X-Forwarded-Proto"] = req.tls ? "https" : "http"; if (auto pff = "X-Forwarded-For" in req.headers) creq.headers["X-Forwarded-For"] = *pff ~ ", " ~ req.peer; else creq.headers["X-Forwarded-For"] = req.peer; req.bodyReader.pipe(creq.bodyWriter); } void handleClientResponse(scope HTTPClientResponse cres) { import vibe.utils.string; // copy the response to the original requester res.statusCode = cres.statusCode; //handle protocol upgrades if (cres.statusCode == HTTPStatus.switchingProtocols && isUpgrade) { res.headers = cres.headers.dup; auto scon = res.switchProtocol(""); auto ccon = cres.switchProtocol(""); import vibe.core.core : runTask; runTask({ ccon.pipe(scon); }); scon.pipe(ccon); return; } // special case for empty response bodies if ("Content-Length" !in cres.headers && "Transfer-Encoding" !in cres.headers || req.method == HTTPMethod.HEAD) { foreach (key, ref value; cres.headers) if (icmp2(key, "Connection") != 0) res.headers[key] = value; res.writeVoidBody(); return; } // enforce compatibility with HTTP/1.0 clients that do not support chunked encoding // (Squid and some other proxies) if (res.httpVersion == HTTPVersion.HTTP_1_0 && ("Transfer-Encoding" in cres.headers || "Content-Length" !in cres.headers)) { // copy all headers that may pass from upstream to client foreach (n, ref v; cres.headers) if (n !in non_forward_headers_map) res.headers[n] = v; if ("Transfer-Encoding" in res.headers) res.headers.remove("Transfer-Encoding"); auto content = cres.bodyReader.readAll(1024*1024); res.headers["Content-Length"] = to!string(content.length); if (res.isHeadResponse) res.writeVoidBody(); else res.bodyWriter.write(content); return; } // to perform a verbatim copy of the client response if ("Content-Length" in cres.headers) { if ("Content-Encoding" in res.headers) res.headers.remove("Content-Encoding"); foreach (key, ref value; cres.headers) if (icmp2(key, "Connection") != 0) res.headers[key] = value; auto size = cres.headers["Content-Length"].to!size_t(); if (res.isHeadResponse) res.writeVoidBody(); else cres.readRawBody((scope InterfaceProxy!InputStream reader) { res.writeRawBody(reader, size); }); assert(res.headerWritten); return; } // fall back to a generic re-encoding of the response // copy all headers that may pass from upstream to client foreach (n, ref v; cres.headers) if (n !in non_forward_headers_map) res.headers[n] = v; if (res.isHeadResponse) res.writeVoidBody(); else cres.bodyReader.pipe(res.bodyWriter); } try requestHTTP(url, &setupClientRequest, &handleClientResponse); catch (Exception e) { throw new HTTPStatusException(HTTPStatus.badGateway, "Connection to upstream server failed: "~e.msg); } } return &handleRequest; } /// Compatibility alias - will be deprecated soon alias reverseProxyRequest = proxyRequest; /** Returns a HTTP request handler that forwards any request to the specified host/port. */ HTTPServerRequestDelegateS reverseProxyRequest(string destination_host, ushort destination_port) { URL url; url.schema = "http"; url.host = destination_host; url.port = destination_port; auto settings = new HTTPProxySettings(ProxyMode.reverse); settings.destination = url; return proxyRequest(settings); } /// ditto HTTPServerRequestDelegateS reverseProxyRequest(URL destination) { auto settings = new HTTPProxySettings(ProxyMode.reverse); settings.destination = destination; return proxyRequest(settings); } /** Returns a HTTP request handler that forwards any request to the requested host/port. */ HTTPServerRequestDelegateS forwardProxyRequest() { return proxyRequest(new HTTPProxySettings(ProxyMode.forward)); } /** Enum to represent the two modes a proxy can operate as. */ enum ProxyMode {forward, reverse} /** Provides advanced configuration facilities for reverse proxy servers. */ final class HTTPProxySettings { /// Scheduled for deprecation - use `destination.host` instead. @property string destinationHost() const { return destination.host; } /// ditto @property void destinationHost(string host) { destination.host = host; } /// Scheduled for deprecation - use `destination.port` instead. @property ushort destinationPort() const { return destination.port; } /// ditto @property void destinationPort(ushort port) { destination.port = port; } /// The destination URL to forward requests to URL destination = URL("http", InetPath("")); /// The mode of the proxy i.e forward, reverse ProxyMode proxyMode; /// Avoids compressed transfers between proxy and destination hosts bool avoidCompressedRequests; /// Handle CONNECT requests for creating a tunnel to the destination host bool handleConnectRequests; /// Empty default constructor for backwards compatibility - will be deprecated soon. this() { } /// Explicitly sets the proxy mode. this(ProxyMode mode) { proxyMode = mode; } } /// Compatibility alias - will be deprecated soon. alias HTTPReverseProxySettings = HTTPProxySettings;