// buildProxyRequest creates a request object for the proxy request, it will ensure that
// the original request headers are preserved as well as setting openfaas system headers
350598
func buildProxyRequest(originalReq *http.Request, baseURL url.URL, extraPath string) (*http.Request, error) {

	host := baseURL.Host
	if baseURL.Port() == "" {
		host = baseURL.Host + ":" + watchdogPort
	}

	url := url.URL{
		Scheme:   baseURL.Scheme,
		Host:     host,
		Path:     extraPath,
		RawQuery: originalReq.URL.RawQuery,
	}

	upstreamReq, err := http.NewRequest(originalReq.Method, url.String(), nil)
	if err != nil {
		return nil, err
	}
	copyHeaders(upstreamReq.Header, &originalReq.Header)

	if len(originalReq.Host) > 0 && upstreamReq.Header.Get("X-Forwarded-Host") == "" {
		upstreamReq.Header["X-Forwarded-Host"] = []string{originalReq.Host}
	}
	if upstreamReq.Header.Get("X-Forwarded-For") == "" {
		upstreamReq.Header["X-Forwarded-For"] = []string{originalReq.RemoteAddr}
	}

	if originalReq.Body != nil {
		upstreamReq.Body = originalReq.Body
	}

	return upstreamReq, nil
}
563150
func (b *HttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *HttpRequest {
	b.setting.Proxy = proxy
	return b
}
713588
func (F *Frisby) SetProxy(url string) *Frisby {
	F.Req.Proxy = url
	return F
}
924527
func SetProxy(proxy func(*http.Request) (*url.URL, error)) error {
	return std.SetProxy(proxy)
}
993683
func (s *HTTPServer) AgentConnectProxyConfig(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Get the proxy ID. Note that this is the ID of a proxy's service instance.
	id := strings.TrimPrefix(req.URL.Path, "/v1/agent/connect/proxy/")

	// Maybe block
	var queryOpts structs.QueryOptions
	if parseWait(resp, req, &queryOpts) {
		// parseWait returns an error itself
		return nil, nil
	}

	// Parse the token - don't resolve a proxy token to a real token
	// that will be done with a call to verifyProxyToken later along with
	// other security relevant checks.
	var token string
	s.parseTokenWithoutResolvingProxyToken(req, &token)

	// Parse hash specially since it's only this endpoint that uses it currently.
	// Eventually this should happen in parseWait and end up in QueryOptions but I
	// didn't want to make very general changes right away.
	hash := req.URL.Query().Get("hash")

	return s.agentLocalBlockingQuery(resp, hash, &queryOpts,
		func(ws memdb.WatchSet) (string, interface{}, error) {
			// Retrieve the proxy specified
			proxy := s.agent.State.Proxy(id)
			if proxy == nil {
				resp.WriteHeader(http.StatusNotFound)
				fmt.Fprintf(resp, "unknown proxy service ID: %s", id)
				return "", nil, nil
			}

			// Lookup the target service as a convenience
			target := s.agent.State.Service(proxy.Proxy.TargetServiceID)
			if target == nil {
				// Not found since this endpoint is only useful for agent-managed proxies so
				// service missing means the service was deregistered racily with this call.
				resp.WriteHeader(http.StatusNotFound)
				fmt.Fprintf(resp, "unknown target service ID: %s", proxy.Proxy.TargetServiceID)
				return "", nil, nil
			}

			// Validate the ACL token - because this endpoint uses data local to a single
			// agent, this function is responsible for all enforcement regarding
			// protection of the configuration. verifyProxyToken will match the proxies
			// token to the correct service or in the case of being provide a real ACL
			// token it will ensure that the requester has ServiceWrite privileges
			// for this service.
			_, isProxyToken, err := s.agent.verifyProxyToken(token, target.Service, id)
			if err != nil {
				return "", nil, err
			}

			// Watch the proxy for changes
			ws.Add(proxy.WatchCh)

			hash, err := hashstructure.Hash(proxy.Proxy, nil)
			if err != nil {
				return "", nil, err
			}
			contentHash := fmt.Sprintf("%x", hash)

			// Set defaults
			config, err := s.agent.applyProxyConfigDefaults(proxy.Proxy)
			if err != nil {
				return "", nil, err
			}

			// Only merge in telemetry config from agent if the requested is
			// authorized with a proxy token. This prevents us leaking potentially
			// sensitive config like Circonus API token via a public endpoint. Proxy
			// tokens are only ever generated in-memory and passed via ENV to a child
			// proxy process so potential for abuse here seems small. This endpoint in
			// general is only useful for managed proxies now so it should _always_ be
			// true that auth is via a proxy token but inconvenient for testing if we
			// lock it down so strictly.
			if isProxyToken {
				// Add telemetry config. Copy the global config so we can customize the
				// prefix.
				telemetryCfg := s.agent.config.Telemetry
				telemetryCfg.MetricsPrefix = telemetryCfg.MetricsPrefix + ".proxy." + target.ID

				// First see if the user has specified telemetry
				if userRaw, ok := config["telemetry"]; ok {
					// User specified domething, see if it is compatible with agent
					// telemetry config:
					var uCfg lib.TelemetryConfig
					dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
						Result: &uCfg,
						// Make sure that if the user passes something that isn't just a
						// simple override of a valid TelemetryConfig that we fail so that we
						// don't clobber their custom config.
						ErrorUnused: true,
					})
					if err == nil {
						if err = dec.Decode(userRaw); err == nil {
							// It did decode! Merge any unspecified fields from agent config.
							uCfg.MergeDefaults(&telemetryCfg)
							config["telemetry"] = uCfg
						}
					}
					// Failed to decode, just keep user's config["telemetry"] verbatim
					// with no agent merge.
				} else {
					// Add agent telemetry config.
					config["telemetry"] = telemetryCfg
				}
			}

			reply := &api.ConnectProxyConfig{
				ProxyServiceID:    proxy.Proxy.ProxyService.ID,
				TargetServiceID:   target.ID,
				TargetServiceName: target.Service,
				ContentHash:       contentHash,
				ExecMode:          api.ProxyExecMode(proxy.Proxy.ExecMode.String()),
				Command:           proxy.Proxy.Command,
				Config:            config,
				Upstreams:         proxy.Proxy.Upstreams.ToAPI(),
			}
			return contentHash, reply, nil
		})
}
630776
func (self *proxy) initProxy() error {
	if self.reverseProxy == nil {
		uri, err := url.Parse(self.targetUrl)
		if err != nil {
			return err
		}
		self.reverseProxy = NewSingleHostReverseProxy(uri, self.fwdPath, IgnoreUpstreamCerts, self.prefixPath)
		self.healthy = true // assume newly added nodes are healthy
		lumber.Trace("[NANOBOX-ROUTER] New proxy set")
	}
	return nil
}
57858
func (c *Config) ParseProxyHost(proxyHost string) error {
	host, port, err := net.SplitHostPort(proxyHost)
	if err != nil {
		host = proxyHost
		port = ""
	}

	// Split on comma.
	parts := strings.Split(port, ",")

	switch {
	// Default ports for both the SSH and Web proxy.
	case len(parts) == 0:
		c.WebProxyAddr = net.JoinHostPort(host, strconv.Itoa(defaults.HTTPListenPort))
		c.SSHProxyAddr = net.JoinHostPort(host, strconv.Itoa(defaults.SSHProxyListenPort))
	// User defined HTTP proxy port, default SSH proxy port.
	case len(parts) == 1:
		webPort := parts[0]
		if webPort == "" {
			webPort = strconv.Itoa(defaults.HTTPListenPort)
		}
		c.WebProxyAddr = net.JoinHostPort(host, webPort)
		c.SSHProxyAddr = net.JoinHostPort(host, strconv.Itoa(defaults.SSHProxyListenPort))
	// User defined HTTP and SSH proxy ports.
	case len(parts) == 2:
		webPort := parts[0]
		if webPort == "" {
			webPort = strconv.Itoa(defaults.HTTPListenPort)
		}
		sshPort := parts[1]
		if sshPort == "" {
			sshPort = strconv.Itoa(defaults.SSHProxyListenPort)
		}
		c.WebProxyAddr = net.JoinHostPort(host, webPort)
		c.SSHProxyAddr = net.JoinHostPort(host, sshPort)
	default:
		return trace.BadParameter("unable to parse port: %v", port)
	}

	return nil
}
881005
func NewProxy(ctx context.Context) *Proxy {
	var p Proxy

	passThrough = newProxyPassthrough(ctx)
	passThrough.readConfig(ctx)
	return &p
}
743321
func (r *marathonClient) buildAPIRequest(method, path string, reader io.Reader) (request *http.Request, member string, err error) {
	// Grab a member from the cluster
	member, err = r.hosts.getMember()
	if err != nil {
		return nil, "", ErrMarathonDown
	}

	// Build the HTTP request to Marathon
	request, err = r.client.buildMarathonJSONRequest(method, member, path, reader)
	if err != nil {
		return nil, member, newRequestError{err}
	}
	return request, member, nil
}
46962
func UseProxy(w http.ResponseWriter, response interface{}) {
	Respond(w, http.StatusUseProxy, response)
}
1312872
func NewProxy(target *querypb.Target, qs queryservice.QueryService, normalize bool) *Proxy {
	return &Proxy{
		target:    target,
		qs:        qs,
		normalize: normalize,
	}
}
870982
func parseRequest(request *http.Request) (*proxyRequest, error) {
	path := request.URL.Path

	split := strings.SplitN(path, "/", 5)
	if len(split) < 5 {
		return nil, fmt.Errorf("Invalid request path '%s'", path)
	}

	if split[3] == "http" {
		return &proxyRequest{split[2], protocol.ID("/http"), split[4]}, nil
	}

	split = strings.SplitN(path, "/", 7)
	if split[3] != "x" || split[5] != "http" {
		return nil, fmt.Errorf("Invalid request path '%s'", path)
	}

	return &proxyRequest{split[2], protocol.ID("/x/" + split[4] + "/http"), split[6]}, nil
}
36069
func (twilio *Twilio) NewProxyService(service ProxyServiceRequest) (response *ProxyService, exception *Exception, err error) {

	twilioUrl := ProxyBaseUrl + "/Services"

	res, err := twilio.post(proxyServiceFormValues(service), twilioUrl)
	if err != nil {
		return response, exception, err
	}
	defer res.Body.Close()

	responseBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return response, exception, err
	}

	if res.StatusCode != http.StatusCreated {
		exception = new(Exception)
		err = json.Unmarshal(responseBody, exception)

		// We aren't checking the error because we don't actually care.
		// It's going to be passed to the client either way.
		return response, exception, err
	}

	response = new(ProxyService)
	err = json.Unmarshal(responseBody, response)
	return response, exception, err

}
822964
func (client *Client) CreateProxy(name, listen, upstream string) (*Proxy, error) {
	proxy := &Proxy{
		Name:     name,
		Listen:   listen,
		Upstream: upstream,
		Enabled:  true,
		client:   client,
	}

	err := proxy.Save()
	if err != nil {
		return nil, err
	}

	return proxy, nil
}
538515
func (fp *ForwardProxy) generateForwardRequest(inReq *http.Request) (*http.Request, error) {
	// Scheme has to be appended to avoid `unsupported protocol scheme ""` error.
	// `http://` is used, since this initial request itself is always HTTP, regardless of what client and server
	// may speak afterwards.
	if len(inReq.RequestURI) == 0 {
		return nil, errors.New("malformed request: empty URI")
	}
	strUrl := inReq.RequestURI
	if strUrl[0] == '/' {
		strUrl = inReq.Host + strUrl
	}
	if !strings.Contains(strUrl, "://") {
		strUrl = "http://" + strUrl
	}
	outReq, err := http.NewRequest(inReq.Method, strUrl, inReq.Body)
	if err != nil {
		return outReq, errors.New("failed to create NewRequest: " + err.Error())
	}
	for key, values := range inReq.Header {
		for _, value := range values {
			outReq.Header.Add(key, value)
		}
	}
	removeHopByHop(outReq.Header)

	if !fp.hideIP {
		outReq.Header.Add("Forwarded", "for=\""+inReq.RemoteAddr+"\"")
	}

	// https://tools.ietf.org/html/rfc7230#section-5.7.1
	outReq.Header.Add("Via", strconv.Itoa(inReq.ProtoMajor)+"."+strconv.Itoa(inReq.ProtoMinor)+" caddy")
	return outReq, nil
}
345425
func requestProto(request *http.Request) string {
	proto := "http"

	// If the request was received via TLS, use `https://` for the protocol
	if request.TLS != nil {
		proto = "https"
	}

	// Allow upstream proxies  to specify the forwarded protocol. Allow this value
	// to override our own guess.
	if specifiedProto := request.Header.Get("X-Forwarded-Proto"); specifiedProto != "" {
		proto = specifiedProto
	}

	return proto
}
1058052
func (p *Proxy) proxyRequest(w http.ResponseWriter, r *http.Request) error {

	// Create a unique request with sequential ids that will be passed to all interfaces.
	req := request.NewBaseRequest(r, atomic.AddInt64(&p.lastRequestId, 1), nil)
	location, err := p.router.Route(req)
	if err != nil {
		return err
	}

	// Router could not find a matching location, we can do nothing else.
	if location == nil {
		log.Errorf("%s failed to route", req)
		return errors.FromStatus(http.StatusBadGateway)
	}

	response, err := location.RoundTrip(req)
	if response != nil {
		netutils.CopyHeaders(w.Header(), response.Header)
		w.WriteHeader(response.StatusCode)
		io.Copy(w, response.Body)
		response.Body.Close()
		return nil
	} else {
		return err
	}
}