Transform X-Forwarded-- to Forwarded headers and set to outbound request.

@see <a href="https://tools.ietf.org/html/rfc7239#section-7.4">rfc7239</a>
16131
public void transformAndSetForwardedHeader() {
        if (xForwardedForHeader != null && xForwardedByHeader != null) {
            //Transition is not done, as it's not possible to know in which order the existing fields were added.
            LOG.info("Header transition is not done as both X-Forwarded-For and X-Forwarded-By headers are present.");
            return;
        }
        StringBuilder headerValue = new StringBuilder();
        if (xForwardedForHeader != null) {
            String[] parts = xForwardedForHeader.split(COMMA);
            for (String part : parts) {
                headerValue.append(FOR).append(resolveIP(part.trim())).append(COMMA).append(" ");
            }
            headerValue.replace(headerValue.length() - 2, headerValue.length(), SEMI_COLON + " ");
            httpOutboundRequest.removeHeader(Constants.X_FORWARDED_FOR);
        }
        if (xForwardedByHeader != null) {
            headerValue.append(FOR).append(resolveIP(xForwardedByHeader.trim())).append(SEMI_COLON).append(" ");
            httpOutboundRequest.removeHeader(Constants.X_FORWARDED_BY);
        }
        headerValue.append(BY).append(resolveIP(localAddress));
        if (xForwardedHostHeader != null) {
            headerValue.append(SEMI_COLON + " " + HOST).append(xForwardedHostHeader);
            httpOutboundRequest.removeHeader(Constants.X_FORWARDED_HOST);
        }
        if (xForwardedProtoHeader != null) {
            headerValue.append(SEMI_COLON + " " + PROTO).append(xForwardedProtoHeader);
            httpOutboundRequest.removeHeader(Constants.X_FORWARDED_PROTO);
        }
        httpOutboundRequest.setHeader(Constants.FORWARDED, headerValue.toString());
    }
329278
void handleService(KNXnetIPHeader h, byte[] data, int offset)
		throws KNXFormatException
	{
		final int svc = h.getServiceType();
		if (h.getVersion() != KNXNETIP_VERSION_10)
			close(ConnectionCloseEvent.INTERNAL, "protocol version changed",
				LogLevel.ERROR, null);
		else if (svc == KNXnetIPHeader.ROUTING_IND) {
			final RoutingIndication ind = new RoutingIndication(data, offset,
				h.getTotalLength() - h.getStructLength());
			fireFrameReceived(ind.getCEMI());
		}
		else if (svc == KNXnetIPHeader.ROUTING_LOST_MSG) {
			final RoutingLostMessage lost = new RoutingLostMessage(data, offset);
			fireLostMessage(lost);
		}
		else
			logger.warn("received unknown frame (service type 0x"
				+ Integer.toHexString(svc) + ") - ignored");
	}
189523
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest)
            throws URISyntaxException {
        // Get an Enumeration of all of the header names sent by the client
        Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames();
        while (enumerationOfHeaderNames.hasMoreElements()) {
            String headerName = (String) enumerationOfHeaderNames.nextElement();
            //Instead the content-length is effectively set via InputStreamEntity
            if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) {
                Enumeration<?> headers = servletRequest.getHeaders(headerName);
                while (headers.hasMoreElements()) {//sometimes more than one value
                    String headerValue = (String) headers.nextElement();
                    // In case the proxy host is running multiple virtual servers,
                    // rewrite the Host header to ensure that we get content from
                    // the correct virtual server
                    if (headerName.equalsIgnoreCase(HOST)) {
                        HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl()));
                        headerValue = host.getHostName();
                        if (host.getPort() != -1) {
                            headerValue += ":" + host.getPort();
                        }
                    }
                    proxyRequest.addHeader(headerName, headerValue);
                }
            }
        }
    }
87313
@Override
    public void lookupChainedProxies(HttpRequest request, Queue<ChainedProxy> chainedProxies) {
        final InetSocketAddress originalProxy = originalProxies.get(URI.create(request.getUri()).getScheme());
        if (originalProxy != null) {
            ChainedProxy chainProxy = new ChainedProxyAdapter() {
                @Override
                public InetSocketAddress getChainedProxyAddress() {
                    return originalProxy;
                }
            };
            chainedProxies.add(chainProxy);
        } else {
            chainedProxies.add(ChainedProxyAdapter.FALLBACK_TO_DIRECT_CONNECTION);
        }
    }
367669
def send_headers(self):
        
        hkeys = [key.lower() for key, value in self.outheaders]
        status = int(self.status[:3])

        if status == 413:
            # Request Entity Too Large. Close conn to avoid garbage.
            self.close_connection = True
        elif b'content-length' not in hkeys:
            # "All 1xx (informational), 204 (no content),
            # and 304 (not modified) responses MUST NOT
            # include a message-body." So no point chunking.
            if status < 200 or status in (204, 205, 304):
                pass
            else:
                needs_chunked = (
                    self.response_protocol == 'HTTP/1.1'
                    and self.method != b'HEAD'
                )
                if needs_chunked:
                    # Use the chunked transfer-coding
                    self.chunked_write = True
                    self.outheaders.append((b'Transfer-Encoding', b'chunked'))
                else:
                    # Closing the conn is the only way to determine len.
                    self.close_connection = True

        if b'connection' not in hkeys:
            if self.response_protocol == 'HTTP/1.1':
                # Both server and client are HTTP/1.1 or better
                if self.close_connection:
                    self.outheaders.append((b'Connection', b'close'))
            else:
                # Server and/or client are HTTP/1.0
                if not self.close_connection:
                    self.outheaders.append((b'Connection', b'Keep-Alive'))

        if (not self.close_connection) and (not self.chunked_read):
            # Read any remaining request body data on the socket.
            # "If an origin server receives a request that does not include an
            # Expect request-header field with the "100-continue" expectation,
            # the request includes a request body, and the server responds
            # with a final status code before reading the entire request body
            # from the transport connection, then the server SHOULD NOT close
            # the transport connection until it has read the entire request,
            # or until the client closes the connection. Otherwise, the client
            # might not reliably receive the response message. However, this
            # requirement is not be construed as preventing a server from
            # defending itself against denial-of-service attacks, or from
            # badly broken client implementations."
            remaining = getattr(self.rfile, 'remaining', 0)
            if remaining > 0:
                self.rfile.read(remaining)

        if b'date' not in hkeys:
            self.outheaders.append((
                b'Date',
                email.utils.formatdate(usegmt=True).encode('ISO-8859-1'),
            ))

        if b'server' not in hkeys:
            self.outheaders.append((
                b'Server',
                self.server.server_name.encode('ISO-8859-1'),
            ))

        proto = self.server.protocol.encode('ascii')
        buf = [proto + SPACE + self.status + CRLF]
        for k, v in self.outheaders:
            buf.append(k + COLON + SPACE + v + CRLF)
        buf.append(CRLF)
        self.conn.wfile.write(EMPTY.join(buf))
260477
function forward(){
  return function forward(req, res, next){
    var url  = utils.processUrl(req);
    var options = {
      url: url,
      method: req.method,
      headers: req.headers
    }
    var buffers = [];

    log.debug('forward: ' + url);
    
    if(req.method === 'POST'){
      req.on('data', function(chunk){
        buffers.push(chunk);
      });

      req.on('end', function(){
        options.data = Buffer.concat(buffers);
        utils.request(options, function(err, data, proxyRes){
          _forwardHandler(err, data, proxyRes, res);
        });
      });
    }else{
      utils.request(options, function(err, data, proxyRes){
        _forwardHandler(err, data, proxyRes, res)
      }); 
    }
  };
}
499374
public static void forward(
		String contextRelativePath,
		RequestDispatcher dispatcher,
		HttpServletRequest request,
		HttpServletResponse response,
		Map<String,?> args
	) throws ServletException, IOException {
		// Track original page when first accessed
		final String oldOriginal = getOriginalPage(request);
		try {
			// Set original request path if not already set
			if(oldOriginal == null) {
				setOriginalPage(request, request.getServletPath());
			}
			// Keep old dispatch page to restore
			final String oldDispatchPage = getDispatchedPage(request);
			try {
				// Store as new relative path source
				setDispatchedPage(request, contextRelativePath);
				// Keep old arguments to restore
				final Object oldArgs = request.getAttribute(Dispatcher.ARG_MAP_REQUEST_ATTRIBUTE_NAME);
				try {
					// Set new arguments
					request.setAttribute(
						Dispatcher.ARG_MAP_REQUEST_ATTRIBUTE_NAME,
						args==null ? null : AoCollections.optimalUnmodifiableMap(args)
					);
					// Perform dispatch
					dispatcher.forward(request, response);
				} finally {
					// Restore any previous args
					request.setAttribute(Dispatcher.ARG_MAP_REQUEST_ATTRIBUTE_NAME, oldArgs);
				}
			} finally {
				setDispatchedPage(request, oldDispatchPage);
			}
		} finally {
			if(oldOriginal == null) {
				setOriginalPage(request, null);
			}
		}
	}
416779
public function sendHeaders(): void
	{
		// Send status header

		$protocol = $this->request->getServer()->get('SERVER_PROTOCOL', 'HTTP/1.1');

		header($protocol . ' ' . $this->statusCode . ' ' . $this->statusCodes[$this->statusCode]);

		// Send content type header

		$contentType = $this->contentType;

		if(stripos($contentType, 'text/') === 0 || in_array($contentType, ['application/json', 'application/xml', 'application/rss+xml', 'application/atom+xml']))
		{
			$contentType .= '; charset=' . $this->charset;
		}

		header('Content-Type: ' . $contentType);

		// Send other headers

		foreach($this->headers->all() as $name => $values)
		{
			foreach($values as $value)
			{
				header($name . ': ' . $value, false);
			}
		}

		// Send cookie headers

		foreach($this->cookies->all() as $cookie)
		{
			['raw' => $raw, 'name' => $name, 'value' => $value, 'options' => $options] = $cookie;

			if($raw)
			{
				setrawcookie($name, $value, $options['expires'], $options['path'], $options['domain'], $options['secure'], $options['httponly']);
			}
			else
			{
				setcookie($name, $value, $options['expires'], $options['path'], $options['domain'], $options['secure'], $options['httponly']);
			}
		}
	}
279823
function () {
                req.date = new Date();
                if (self._conn.options.customHeaders){
                    var headers = self._conn.options.customHeaders;
                    for (var header in headers) {
                        if (headers.hasOwnProperty(header)) {
                            req.xhr.setRequestHeader(header, headers[header]);
                        }
                    }
                }
                req.xhr.send(req.data);
            }
1029543
function createConnectionObject(context) {
  const { req } = context.bindings;
  const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;

  return {
    encrypted     : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
    remoteAddress : removePortFromAddress(xForwardedFor)
  };
}
1114600
public void setDefactoForwardedHeaders() {
        if (xForwardedForHeader != null && xForwardedByHeader != null) {
            httpOutboundRequest.setHeader(Constants.X_FORWARDED_FOR,
                    xForwardedForHeader.trim() + COMMA + " " + xForwardedByHeader.trim());
        } else if (xForwardedByHeader != null) {
            httpOutboundRequest.setHeader(Constants.X_FORWARDED_FOR, xForwardedByHeader.trim());
        }
        httpOutboundRequest.setHeader(Constants.X_FORWARDED_BY, localAddress);
    }
164171
function(xhr, promise, headers, method) {
            // XDR cannot set requestheaders, only XHR:
            if (!xhr._isXDR) {
                console.log(NAME, '_setHeaders');
                var name;
                if ((method!=='POST') && (method!=='PUT')) {
                    // force GET-request to make a request instead of using cache (like IE does):
                    headers['If-Modified-Since'] = 'Wed, 15 Nov 1995 01:00:00 GMT';
                    // header 'Content-Type' should only be set with POST or PUT requests:
                    delete headers[CONTENT_TYPE];
                }
                // set all headers
                for (name in headers) {
                    xhr.setRequestHeader(name, headers[name]);
                }

                // in case of POST or PUT method: always make sure 'Content-Type' is specified
                ((method!=='POST') && (method!=='PUT')) || (headers && (CONTENT_TYPE in headers)) || xhr.setRequestHeader(CONTENT_TYPE, DEF_CONTENT_TYPE_POST);
            }
        }
1252133
function setHeaders(req, headers) {
        var i;
        for (i = 0; i < headers.length; ++i) {
            req.setRequestHeader(headers[i][0], headers[i][1]);
        }
    }
636547
public void doGet(String url, HttpResponse response, Map<String, Object> headers, boolean followRedirect) {
        response.setRequest(url);
        httpClient.get(url, response, headers, followRedirect);
    }
1276964
function Request_forward(route, params) {

        var request;

        if (router.trim(this.route, "/") === router.trim(route, '/')) {
            throw new error.HttpError(500, {
                route: route,
                params: params
            }, 'Cannot forward to same route');
        } else {

            this.stopPromiseChain();

            request = new Request({
                request: this.request,
                response: this.response,
                isForwarded: true,
                body: this.body
            }, router.createUrl(route, params));

            this.isRendered = true;

            logger.info('Request.forward.route:', {
                route: route,
                params: params
            });

            return request.parse();
        }
    }
323677
private void dispatchOutsideContainer(SipServletRequestImpl sipServletRequest) throws DispatcherException {
		final Request request = (Request) sipServletRequest.getMessage();
		if(logger.isInfoEnabled()) {
			logger.info("Dispatching the request event outside the container");
		}
		//check if the request point to another domain
		if(request.getRequestURI() instanceof TelURL ||
				// https://github.com/RestComm/sip-servlets/issues/108
				!(request.getRequestURI() instanceof javax.sip.address.SipURI)) {
			throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot dispatch a request with a tel url or generic request uri outside the container ");
		}
		javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
		
		String host = sipRequestUri.getHost();
		int port = sipRequestUri.getPort();
		String transport = JainSipUtils.findTransport(request);
		boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);			
		ListIterator<String> routeHeaders = sipServletRequest.getHeaders(RouteHeader.NAME);				
		if(isAnotherDomain || routeHeaders.hasNext()) {
			try {
				forwardRequestStatefully(sipServletRequest, SipSessionRoutingType.PREVIOUS_SESSION, SipRouteModifier.NO_ROUTE);
			} catch (Exception e) {
				throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Unexpected Exception while trying to forward statefully the following initial request " + request, e);
			}
		} else {
			// the Request-URI does not point to another domain, and there is no Route header, 
			// the container should not send the request as it will cause a loop. 
			// Instead, the container must reject the request with 404 Not Found final response with no Retry-After header.
			throw new DispatcherException(Response.NOT_FOUND, "the Request-URI does not point to another domain, and there is no Route header," + 
					"the container should not send the request as it will cause a loop. " +
					"Instead, the container must reject the request with 404 Not Found final response with no Retry-After header. You may want to check your dar configuration file to see if the request can be handled or make sure you use the correct Application Router jar.");				
		}
	}
1174614
function useProxyIfExternal(connectUrl) {
        if (Core.isChromeApp()) {
            return connectUrl;
        }
        var host = window.location.host;
        if (!_.startsWith(connectUrl, "http://" + host + "/") && !_.startsWith(connectUrl, "https://" + host + "/")) {
            // lets remove the http stuff
            var idx = connectUrl.indexOf("://");
            if (idx > 0) {
                connectUrl = connectUrl.substring(idx + 3);
            }
            // lets replace the : with a /
            connectUrl = connectUrl.replace(":", "/");
            connectUrl = Core.trimLeading(connectUrl, "/");
            connectUrl = Core.trimTrailing(connectUrl, "/");
            connectUrl = Core.url("/proxy/" + connectUrl);
        }
        return connectUrl;
    }