// Newproxy create a new proxy object. It starts listening on the prxy port asynchronously.
2543
func newProxy(name, tenantEndpointID string, tcpMuxPort uint16, useTLS bool, listener net.Listener, allowDirectConn bool) (p *proxy, err error) {
	if len(name) == 0 {
		return nil, fmt.Errorf("prxy: name can not be empty")
	}
	p = &proxy{
		name:             name,
		tenantEndpointID: tenantEndpointID,
		addresses:        make([]addressTuple, 0),
		tcpMuxPort:       tcpMuxPort,
		useTLS:           useTLS,
		listener:         listener,
		allowDirectConn:  allowDirectConn,
	}
	p.newAddresses = make(chan []addressTuple, 2)
	go p.listenAndproxy()
	return p, nil
}
55220
func New(configFile string, pidFile string) *HAproxy {
	reloadCmd := "haproxy -f " + configFile + " -p " + pidFile + " `[[ -f " + pidFile + " ]] && echo \"-sf $(cat " + pidFile + ")\"]]`"
	verifyCmd := "haproxy -c -f " + configFile

	proxy := HAproxy{
		ReloadCmd:  reloadCmd,
		VerifyCmd:  verifyCmd,
		Template:   "views/haproxy.cfg",
		ConfigFile: configFile,
		PidFile:    pidFile,
	}

	return &proxy
}
1264635
func NewNodeProxy() (*NodeSvcProxy, error) {
	ipTablesPath, err := osexec.LookPath("iptables")
	if err != nil {
		return nil, err
	}

	// Install contiv chain and jump
	out, err := osexec.Command(ipTablesPath, "-w", iptablesWaitLock,
		"-t", "nat", "-N", contivNPChain).CombinedOutput()
	if err != nil {
		if !strings.Contains(string(out), "Chain already exists") {
			log.Errorf("Failed to setup contiv nodeport chain %v out: %s",
				err, out)
			return nil, err
		}
	}

	_, err = osexec.Command(ipTablesPath, "-w", iptablesWaitLock, "-t", "nat",
		"-C", "PREROUTING", "-m", "addrtype", "--dst-type", "LOCAL", "-j",
		contivNPChain).CombinedOutput()
	if err != nil {
		out, err = osexec.Command(ipTablesPath, "-w", iptablesWaitLock,
			"-t", "nat", "-I", "PREROUTING", "-m", "addrtype", "--dst-type",
			"LOCAL", "-j", contivNPChain).CombinedOutput()
		if err != nil {
			log.Errorf("Failed to setup contiv nodeport chain jump %v out: %s",
				err, out)
			return nil, err
		}
	}

	// Flush any old rules we might have added. They will get re-added
	// if the service is still active
	osexec.Command(ipTablesPath, "-w", iptablesWaitLock, "-t", "nat", "-F",
		contivNPChain).CombinedOutput()

	proxy := NodeSvcProxy{}
	proxy.SvcMap = make(map[string]core.ServiceSpec)
	proxy.ProvMap = make(map[string]Presence)
	proxy.LocalIP = make(map[string]string)
	proxy.ipTablesPath = ipTablesPath
	proxy.natRules = make(map[string][]string)
	return &proxy, nil
}
1331252
func NewReverseProxy(bf BackendListFunc, stickyKey *[32]byte, sticky bool, rt RequestTracker, l log15.Logger) *ReverseProxy {
	return &ReverseProxy{
		transport: &transport{
			getBackends:       bf,
			stickyCookieKey:   stickyKey,
			useStickySessions: sticky,
		},
		FlushInterval:  10 * time.Millisecond,
		RequestTracker: rt,
		Logger:         l,
	}
}
177061
func NewProxy(id int, st stapler.Stapler, o proxy.Options) (proxy.Proxy, error) {
	return mux.New(id, st, o)
}
553113
func NewHTTPProxy(
	c collector.EventCollector,
	puContext string,
	caPool *x509.CertPool,
	applicationProxy bool,
	mark int,
	secrets secrets.Secrets,
	registry *serviceregistry.Registry,
) *Config {

	return &Config{
		collector:        c,
		puContext:        puContext,
		ca:               caPool,
		applicationProxy: applicationProxy,
		mark:             mark,
		secrets:          secrets,
		localIPs:         markedconn.GetInterfaces(),
		registry:         registry,
		tlsClientConfig: &tls.Config{
			RootCAs: caPool,
		},
	}
}
126823
func NewUnidlerProxier(loadBalancer userspace.LoadBalancer, listenIP net.IP, iptables iptables.Interface, exec utilexec.Interface, pr utilnet.PortRange, syncPeriod, minSyncPeriod, udpIdleTimeout time.Duration, nodePortAddresses []string, signaler NeedPodsSignaler) (*userspace.Proxier, error) {
	newFunc := func(protocol corev1.Protocol, ip net.IP, port int) (userspace.ProxySocket, error) {
		return newUnidlerSocket(protocol, ip, port, signaler)
	}
	return userspace.NewCustomProxier(loadBalancer, listenIP, iptables, exec, pr, syncPeriod, minSyncPeriod, udpIdleTimeout, nodePortAddresses, newFunc)
}
1365135
func (process *TeleportProcess) initProxy() error {
	// if no TLS key was provided for the web UI, generate a self signed cert
	if process.Config.Proxy.TLSKey == "" && !process.Config.Proxy.DisableTLS && !process.Config.Proxy.DisableWebService {
		err := initSelfSignedHTTPSCert(process.Config)
		if err != nil {
			return trace.Wrap(err)
		}
	}
	process.registerWithAuthServer(teleport.RoleProxy, ProxyIdentityEvent)
	process.RegisterCriticalFunc("proxy.init", func() error {
		eventsC := make(chan Event)
		process.WaitForEvent(process.ExitContext(), ProxyIdentityEvent, eventsC)

		var event Event
		select {
		case event = <-eventsC:
			process.Debugf("Received event %q.", event.Name)
		case <-process.ExitContext().Done():
			process.Debugf("Process is exiting.")
			return nil
		}

		conn, ok := (event.Payload).(*Connector)
		if !ok {
			return trace.BadParameter("unsupported connector type: %T", event.Payload)
		}

		err := process.initProxyEndpoint(conn)
		if err != nil {
			return trace.Wrap(err)
		}

		return nil
	})
	return nil
}
1147727
func NewProxyLBServer(ipaddress string, port int) *ProxyLBServer {
	return &ProxyLBServer{
		IPAddress: ipaddress,
		Port:      port,
		Enabled:   true,
	}
}
963952
func New(options *Options) *AuthProxy {
	header := options.Ctx.Req.Header.Get(setting.AuthProxyHeaderName)

	return &AuthProxy{
		store:  options.Store,
		ctx:    options.Ctx,
		orgID:  options.OrgID,
		header: header,

		LDAP: ldap.New,

		enabled:     setting.AuthProxyEnabled,
		headerType:  setting.AuthProxyHeaderProperty,
		headers:     setting.AuthProxyHeaders,
		whitelistIP: setting.AuthProxyWhitelist,
		cacheTTL:    setting.AuthProxyLdapSyncTtl,
	}
}
634828
func NewProxyServer(o *Options) (*ProxyServer, error) {
	return newProxyServer(o.config, o.CleanupAndExit, o.scheme, o.master)
}
815871
func NewProxy(address string) (*Proxy, error) {
	tcpAddr, err := net.ResolveTCPAddr("tcp", address)
	if err != nil {
		return nil, err
	}
	return &Proxy{
		target: tcpAddr,
	}, nil
}
932487
func (f *Request) Proxy(p string) *Request {
	f.proxy = p
	return f
}
917767
func NewUDPProxy(frontendAddr, backendAddr *net.UDPAddr, ops ...func(*UDPProxy)) (*UDPProxy, error) {
	listener, err := net.ListenUDP("udp", frontendAddr)
	if err != nil {
		return nil, err
	}

	proxy := &UDPProxy{
		listener:       listener,
		frontendAddr:   listener.LocalAddr().(*net.UDPAddr),
		backendAddr:    backendAddr,
		connTrackTable: make(connTrackMap),
		Logger:         &noopLogger{},
	}

	for _, op := range ops {
		op(proxy)
	}

	return proxy, nil
}
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
}
1220436
func (i *TeleInstance) StartProxy(cfg ProxyConfig) error {
	dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName+"-"+cfg.Name)
	if err != nil {
		return trace.Wrap(err)
	}

	tconf := service.MakeDefaultConfig()

	authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth()))
	tconf.AuthServers = append(tconf.AuthServers, *authServer)
	tconf.CachePolicy = service.CachePolicy{Enabled: true}
	tconf.DataDir = dataDir
	tconf.UploadEventsC = i.UploadEventsC
	tconf.HostUUID = cfg.Name
	tconf.Hostname = cfg.Name
	tconf.Token = "token"

	tconf.Auth.Enabled = false

	tconf.SSH.Enabled = false

	tconf.Proxy.Enabled = true
	tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.SSHPort))
	tconf.Proxy.PublicAddrs = []utils.NetAddr{
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Loopback,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Host,
		},
	}
	tconf.Proxy.ReverseTunnelListenAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.ReverseTunnelPort))
	tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.WebPort))
	tconf.Proxy.DisableReverseTunnel = false
	tconf.Proxy.DisableWebService = true

	// Create a new Teleport process and add it to the list of nodes that
	// compose this "cluster".
	process, err := service.NewTeleport(tconf)
	if err != nil {
		return trace.Wrap(err)
	}
	i.Nodes = append(i.Nodes, process)

	// Build a list of expected events to wait for before unblocking based off
	// the configuration passed in.
	expectedEvents := []string{
		service.ProxyReverseTunnelReady,
		service.ProxySSHReady,
	}

	// Start the process and block until the expected events have arrived.
	receivedEvents, err := startAndWait(process, expectedEvents)
	if err != nil {
		return trace.Wrap(err)
	}

	log.Debugf("Teleport proxy (in instance %v) started: %v/%v events received.",
		i.Secrets.SiteName, len(expectedEvents), len(receivedEvents))
	return nil
}
3640
func (p *Proxy) releaseProxyPort(name string) error {
	pp := findProxyPort(name)
	if pp == nil {
		return fmt.Errorf("Can't find proxy port %s", name)
	}
	if pp.nRedirects == 0 {
		return fmt.Errorf("Can't release proxy port: proxy %s on %d has refcount 0", name, pp.proxyPort)
	}

	pp.nRedirects--
	if pp.nRedirects == 0 {
		delete(allocatedPorts, pp.proxyPort)
		// Force new port allocation the next time this ProxyPort is used.
		pp.configured = false
		// Leave the datapath rules behind on the hope that they get reused later.
		// This becomes possible when we are able to keep the proxy listeners
		// configured also when there are no redirects.
		log.WithField(fieldProxyRedirectID, name).Debugf("Delayed release of proxy port %d", pp.proxyPort)
	}

	return nil
}