// NewProxyQueryService returns a proxy query service based on the given queryController
// suitable for the storage read service.
184562
func NewProxyQueryService(queryController *pcontrol.Controller) query.ProxyQueryService {
	return query.ProxyQueryServiceBridge{
		QueryService: query.QueryServiceBridge{
			AsyncQueryService: queryController,
		},
	}
}
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
	}
}
994119
func NewProxy(target *url.URL) *WebsocketProxy {
	backend := func(r *http.Request) *url.URL {
		// Shallow copy
		u := *target
		u.Fragment = r.URL.Fragment
		u.Path = r.URL.Path
		u.RawQuery = r.URL.RawQuery
		return &u
	}
	return &WebsocketProxy{Backend: backend}
}
513035
func (proxier *Proxier) updateServiceMap() (result updateServiceMapResult) {
	result.staleServices = sets.NewString()

	var serviceMap proxyServiceMap = proxier.serviceMap
	var changes *serviceChangeMap = &proxier.serviceChanges

	func() {
		changes.lock.Lock()
		defer changes.lock.Unlock()
		for _, change := range changes.items {
			existingPorts := serviceMap.merge(change.current, proxier.endpointsMap)
			serviceMap.unmerge(change.previous, existingPorts, result.staleServices, proxier.endpointsMap)
		}
		changes.items = make(map[types.NamespacedName]*serviceChange)
	}()

	// TODO: If this will appear to be computationally expensive, consider
	// computing this incrementally similarly to serviceMap.
	result.hcServices = make(map[types.NamespacedName]uint16)
	for svcPortName, info := range serviceMap {
		if info.healthCheckNodePort != 0 {
			result.hcServices[svcPortName.NamespacedName] = uint16(info.healthCheckNodePort)
		}
	}

	return result
}
576448
func (proxier *Proxier) syncProxyRules() {
	proxier.mu.Lock()
	defer proxier.mu.Unlock()

	start := time.Now()
	defer func() {
		SyncProxyRulesLatency.Observe(sinceInSeconds(start))
		DeprecatedSyncProxyRulesLatency.Observe(sinceInMicroseconds(start))
		klog.V(4).Infof("syncProxyRules took %v", time.Since(start))
	}()
	// don't sync rules till we've received services and endpoints
	if !proxier.endpointsSynced || !proxier.servicesSynced {
		klog.V(2).Info("Not syncing hns until Services and Endpoints have been received from master")
		return
	}

	// We assume that if this was called, we really want to sync them,
	// even if nothing changed in the meantime. In other words, callers are
	// responsible for detecting no-op changes and not calling this function.
	serviceUpdateResult := proxier.updateServiceMap()
	endpointUpdateResult := proxier.updateEndpointsMap()

	staleServices := serviceUpdateResult.staleServices
	// merge stale services gathered from updateEndpointsMap
	for svcPortName := range endpointUpdateResult.staleServiceNames {
		if svcInfo, ok := proxier.serviceMap[svcPortName]; ok && svcInfo != nil && svcInfo.protocol == v1.ProtocolUDP {
			klog.V(2).Infof("Stale udp service %v -> %s", svcPortName, svcInfo.clusterIP.String())
			staleServices.Insert(svcInfo.clusterIP.String())
		}
	}

	klog.V(3).Infof("Syncing Policies")

	// Program HNS by adding corresponding policies for each service.
	for svcName, svcInfo := range proxier.serviceMap {
		if svcInfo.policyApplied {
			klog.V(4).Infof("Policy already applied for %s", spew.Sdump(svcInfo))
			continue
		}

		hnsNetworkName := proxier.network.name
		hns := proxier.hns
		if proxier.network.networkType == "Overlay" {
			serviceVipEndpoint, _ := hns.getEndpointByIpAddress(svcInfo.clusterIP.String(), hnsNetworkName)
			if serviceVipEndpoint == nil {
				klog.V(4).Infof("No existing remote endpoint for service VIP %v", svcInfo.clusterIP.String())
				hnsEndpoint := &endpointsInfo{
					ip:              svcInfo.clusterIP.String(),
					isLocal:         false,
					macAddress:      proxier.hostMac,
					providerAddress: proxier.nodeIP.String(),
				}

				newHnsEndpoint, err := hns.createEndpoint(hnsEndpoint, hnsNetworkName)
				if err != nil {
					klog.Errorf("Remote endpoint creation failed for service VIP: %v", err)
					continue
				}

				newHnsEndpoint.refCount++
				svcInfo.remoteEndpoint = newHnsEndpoint
			}
		}

		var hnsEndpoints []endpointsInfo
		klog.V(4).Infof("====Applying Policy for %s====", svcName)
		// Create Remote endpoints for every endpoint, corresponding to the service
		containsPublicIP := false

		for _, ep := range proxier.endpointsMap[svcName] {
			var newHnsEndpoint *endpointsInfo
			hnsNetworkName := proxier.network.name
			var err error

			// targetPort is zero if it is specified as a name in port.TargetPort, so the real port should be got from endpoints.
			// Note that hcsshim.AddLoadBalancer() doesn't support endpoints with different ports, so only port from first endpoint is used.
			// TODO(feiskyer): add support of different endpoint ports after hcsshim.AddLoadBalancer() add that.
			if svcInfo.targetPort == 0 {
				svcInfo.targetPort = int(ep.port)
			}

			if len(ep.hnsID) > 0 {
				newHnsEndpoint, err = hns.getEndpointByID(ep.hnsID)
			}

			if newHnsEndpoint == nil {
				// First check if an endpoint resource exists for this IP, on the current host
				// A Local endpoint could exist here already
				// A remote endpoint was already created and proxy was restarted
				newHnsEndpoint, err = hns.getEndpointByIpAddress(ep.ip, hnsNetworkName)
			}
			if newHnsEndpoint == nil {
				if ep.isLocal {
					klog.Errorf("Local endpoint not found for %v: err: %v on network %s", ep.ip, err, hnsNetworkName)
					continue
				}

				if proxier.network.networkType == "Overlay" {
					klog.Infof("Updating network %v to check for new remote subnet policies", proxier.network.name)
					networkName := proxier.network.name
					updatedNetwork, err := hns.getNetworkByName(networkName)
					if err != nil {
						klog.Fatalf("Failed to get network %v: %v", networkName, err)
					}
					proxier.network = *updatedNetwork
					var providerAddress string
					for _, rs := range proxier.network.remoteSubnets {
						_, ipNet, err := net.ParseCIDR(rs.destinationPrefix)
						if err != nil {
							klog.Fatalf("%v", err)
						}
						if ipNet.Contains(net.ParseIP(ep.ip)) {
							providerAddress = rs.providerAddress
						}
						if ep.ip == rs.providerAddress {
							providerAddress = rs.providerAddress
						}
					}
					if len(providerAddress) == 0 {
						klog.Errorf("Could not find provider address for %s", ep.ip)
						providerAddress = proxier.nodeIP.String()
						containsPublicIP = true
					}
					hnsEndpoint := &endpointsInfo{
						ip:              ep.ip,
						isLocal:         false,
						macAddress:      conjureMac("02-11", net.ParseIP(ep.ip)),
						providerAddress: providerAddress,
					}

					newHnsEndpoint, err = hns.createEndpoint(hnsEndpoint, hnsNetworkName)
					if err != nil {
						klog.Errorf("Remote endpoint creation failed: %v, %s", err, spew.Sdump(hnsEndpoint))
						continue
					}
				} else {
					hnsEndpoint := &endpointsInfo{
						ip:         ep.ip,
						isLocal:    false,
						macAddress: ep.macAddress,
					}

					newHnsEndpoint, err = hns.createEndpoint(hnsEndpoint, hnsNetworkName)
					if err != nil {
						klog.Errorf("Remote endpoint creation failed: %v", err)
						continue
					}
				}
			}

			// Save the hnsId for reference
			LogJson(newHnsEndpoint, "Hns Endpoint resource", 1)
			hnsEndpoints = append(hnsEndpoints, *newHnsEndpoint)
			ep.hnsID = newHnsEndpoint.hnsID
			ep.refCount++
			Log(ep, "Endpoint resource found", 3)
		}

		klog.V(3).Infof("Associated endpoints [%s] for service [%s]", spew.Sdump(hnsEndpoints), svcName)

		if len(svcInfo.hnsID) > 0 {
			// This should not happen
			klog.Warningf("Load Balancer already exists %s -- Debug ", svcInfo.hnsID)
		}

		if len(hnsEndpoints) == 0 {
			klog.Errorf("Endpoint information not available for service %s. Not applying any policy", svcName)
			continue
		}

		klog.V(4).Infof("Trying to Apply Policies for service %s", spew.Sdump(svcInfo))
		var hnsLoadBalancer *loadBalancerInfo
		var sourceVip = proxier.sourceVip
		if containsPublicIP {
			sourceVip = proxier.nodeIP.String()
		}
		hnsLoadBalancer, err := hns.getLoadBalancer(
			hnsEndpoints,
			false,
			proxier.isDSR,
			sourceVip,
			svcInfo.clusterIP.String(),
			Enum(svcInfo.protocol),
			uint16(svcInfo.targetPort),
			uint16(svcInfo.port),
		)
		if err != nil {
			klog.Errorf("Policy creation failed: %v", err)
			continue
		}

		svcInfo.hnsID = hnsLoadBalancer.hnsID
		klog.V(3).Infof("Hns LoadBalancer resource created for cluster ip resources %v, Id [%s]", svcInfo.clusterIP, hnsLoadBalancer.hnsID)

		// If nodePort is specified, user should be able to use nodeIP:nodePort to reach the backend endpoints
		if svcInfo.nodePort > 0 {
			hnsLoadBalancer, err := hns.getLoadBalancer(
				hnsEndpoints,
				false,
				false,
				sourceVip,
				"",
				Enum(svcInfo.protocol),
				uint16(svcInfo.targetPort),
				uint16(svcInfo.nodePort),
			)
			if err != nil {
				klog.Errorf("Policy creation failed: %v", err)
				continue
			}

			svcInfo.nodePorthnsID = hnsLoadBalancer.hnsID
			klog.V(3).Infof("Hns LoadBalancer resource created for nodePort resources %v, Id [%s]", svcInfo.clusterIP, hnsLoadBalancer.hnsID)
		}

		// Create a Load Balancer Policy for each external IP
		for _, externalIp := range svcInfo.externalIPs {
			// Try loading existing policies, if already available
			hnsLoadBalancer, err = hns.getLoadBalancer(
				hnsEndpoints,
				false,
				false,
				sourceVip,
				externalIp.ip,
				Enum(svcInfo.protocol),
				uint16(svcInfo.targetPort),
				uint16(svcInfo.port),
			)
			if err != nil {
				klog.Errorf("Policy creation failed: %v", err)
				continue
			}
			externalIp.hnsID = hnsLoadBalancer.hnsID
			klog.V(3).Infof("Hns LoadBalancer resource created for externalIp resources %v, Id[%s]", externalIp, hnsLoadBalancer.hnsID)
		}
		// Create a Load Balancer Policy for each loadbalancer ingress
		for _, lbIngressIp := range svcInfo.loadBalancerIngressIPs {
			// Try loading existing policies, if already available
			hnsLoadBalancer, err := hns.getLoadBalancer(
				hnsEndpoints,
				false,
				false,
				sourceVip,
				lbIngressIp.ip,
				Enum(svcInfo.protocol),
				uint16(svcInfo.targetPort),
				uint16(svcInfo.port),
			)
			if err != nil {
				klog.Errorf("Policy creation failed: %v", err)
				continue
			}
			lbIngressIp.hnsID = hnsLoadBalancer.hnsID
			klog.V(3).Infof("Hns LoadBalancer resource created for loadBalancer Ingress resources %v", lbIngressIp)
		}
		svcInfo.policyApplied = true
		Log(svcInfo, "+++Policy Successfully applied for service +++", 2)
	}

	// Update healthz timestamp.
	if proxier.healthzServer != nil {
		proxier.healthzServer.UpdateTimestamp()
	}

	// Update healthchecks.  The endpoints list might include services that are
	// not "OnlyLocal", but the services list will not, and the healthChecker
	// will just drop those endpoints.
	if err := proxier.healthChecker.SyncServices(serviceUpdateResult.hcServices); err != nil {
		klog.Errorf("Error syncing healthcheck services: %v", err)
	}
	if err := proxier.healthChecker.SyncEndpoints(endpointUpdateResult.hcEndpoints); err != nil {
		klog.Errorf("Error syncing healthcheck endpoints: %v", err)
	}

	// Finish housekeeping.
	// TODO: these could be made more consistent.
	for _, svcIP := range staleServices.UnsortedList() {
		// TODO : Check if this is required to cleanup stale services here
		klog.V(5).Infof("Pending delete stale service IP %s connections", svcIP)
	}

}
198022
func NewPercolateService(client *Client) *PercolateService {
	return &PercolateService{
		client:  client,
		routing: make([]string, 0),
	}
}
424755
func NewProxyWriterWithLogger(w http.ResponseWriter, l *log.Logger) *ProxyWriter {
	return &ProxyWriter{
		w:   w,
		log: l,
	}
}
372549
func NewJqueryVersionProxy() *goproxy.ProxyHttpServer {
	proxy := goproxy.NewProxyHttpServer()
	m := make(map[string]string)
	jqueryMatcher := regexp.MustCompile(`(?i:jquery\.)`)
	proxy.OnResponse(goproxy_html.IsHtml).Do(goproxy_html.HandleString(
		func(s string, ctx *goproxy.ProxyCtx) string {
			for _, src := range findScriptSrc(s) {
				if !jqueryMatcher.MatchString(src) {
					continue
				}
				prev, ok := m[ctx.Req.Host]
				if ok {
					if prev != src {
						ctx.Warnf("In %v, Contradicting jqueries %v %v",
							ctx.Req.URL, prev, src)
						break
					}
				} else {
					ctx.Warnf("%s uses jquery %s", ctx.Req.Host, src)
					m[ctx.Req.Host] = src
				}
			}
			return s
		}))
	return proxy
}
764727
func (conn *connection) reverseProxyRequest(w http.ResponseWriter,
	r *http.Request, path string, auth Auth) error {
	target, err := url.Parse(conn.url)
	if err != nil {
		return err
	}
	if auth != nil {
		auth.AddAuthHeaders(r)
	}
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, path)
	}
	rp := &httputil.ReverseProxy{Director: director}
	rp.ServeHTTP(w, r)
	return nil
}
163151
func (G *global_data) SetProxy(url string) *global_data {
	G.Req.Proxy = url
	return G
}
403840
func (s *ProxyQueryService) Query(ctx context.Context, w io.Writer, req *query.ProxyRequest) (int64, error) {
	return s.QueryFn(ctx, w, req)
}
924527
func SetProxy(proxy func(*http.Request) (*url.URL, error)) error {
	return std.SetProxy(proxy)
}
1242374
func NewProxyWithOptions(router route.Router, o Options) (*Proxy, error) {
	o, err := validateOptions(o)
	if err != nil {
		return nil, err
	}

	p := &Proxy{
		options: o,
		router:  router,
	}
	return p, nil
}
583123
func NewAsyncQueryServiceExecutor(logger *zap.Logger, qs query.AsyncQueryService, as influxdb.AuthorizationService, ts influxdb.TaskService) backend.Executor {
	return &asyncQueryServiceExecutor{logger: logger, qs: qs, as: as, ts: ts}
}
298537
func ReadProxyConfig(path string) (c ProxyConfig, err error) {
	f, err := os.Open(path)
	if err != nil {
		return c, err
	}
	defer f.Close()
	c, err = readProxyConfig(f)
	c.applyDefaults()
	return
}
484284
func newProxyDialer(dialer func(context.Context, string) (net.Conn, error)) func(context.Context, string) (net.Conn, error) {
	return func(ctx context.Context, addr string) (conn net.Conn, err error) {
		var newAddr string
		proxyURL, err := mapAddress(ctx, addr)
		if err != nil {
			if err != errDisabled {
				return nil, err
			}
			newAddr = addr
		} else {
			newAddr = proxyURL.Host
		}

		conn, err = dialer(ctx, newAddr)
		if err != nil {
			return
		}
		if proxyURL != nil {
			// proxy is disabled if proxyURL is nil.
			conn, err = doHTTPConnectHandshake(ctx, conn, addr, proxyURL)
		}
		return
	}
}
941000
func ParseProxyURL(proxy string) (*url.URL, error) {
	proxyURL, err := url.Parse(proxy)

	// logic copied from net/http.ProxyFromEnvironment
	if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
		// proxy was bogus. Try prepending "http://" to it and see if that
		// parses correctly. If not, we fall through and complain about the
		// original one.
		if proxyURL, err := url.Parse("http://" + proxy); err == nil {
			return proxyURL, nil
		}
	}

	return proxyURL, err
}