# Copyright, 2018, by Samuel G. D. Williams. <http://www.codeotaku.com># # Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:# # The above copyright notice and this permission notice shall be included in# all copies or substantial portions of the Software.# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN# THE SOFTWARE.require'async/http/client'require'http/protocol/headers'moduleFalconmoduleBadRequestdefself.call(request)returnAsync::HTTP::Response[400,{},[]]enddefself.closeendendclassProxy<Async::HTTP::MiddlewareFORWARDED='forwarded'.freezeX_FORWARDED_FOR='x-forwarded-for'.freezeX_FORWARDED_PROTO='x-forwarded-proto'.freezeVIA='via'.freezeCONNECTION=::HTTP::Protocol::CONNECTIONHOP_HEADERS=['connection','keep-alive','public','proxy-authenticate','transfer-encoding','upgrade',]definitialize(app,hosts)super(app)@server_context=nil@hosts=hosts@clients={}@count=0endattr:countdefclose@clients.each_value(&:close)superenddefconnect(endpoint)@clients[endpoint]||=Async::HTTP::Client.new(endpoint)enddeflookup(request)# Trailing dot and port is ignored/normalized.ifauthority=request.authority.sub(/(\.)?(:\d+)?$/,'')return@hosts[authority]endenddefprepare_headers(headers)ifconnection=headers[CONNECTION]headers.slice!(connection)endheaders.slice!(HOP_HEADERS)enddefprepare_request(request)forwarded=[]ifaddress=request.remote_addressrequest.headers.add(X_FORWARDED_FOR,address.ip_address)forwarded<<"for=#{address.ip_address}"endifscheme=request.schemerequest.headers.add(X_FORWARDED_PROTO,scheme)forwarded<<"proto=#{scheme}"endunlessforwarded.empty?request.headers.add(FORWARDED,forwarded.join(';'))endrequest.headers.add(VIA,"#{request.version}#{self.class}")self.prepare_headers(request.headers)returnrequestenddefcall(request)ifendpoint=lookup(request)@count+=1request=self.prepare_request(request)client=connect(endpoint)client.call(request)elsesuperendrescueAsync.logger.error(self){$!}returnAsync::HTTP::Response[502,{'content-type'=>'text/plain'},["#{$!.inspect}: #{$!.backtrace.join("\n")}"]]endendend