// StartMappingProxy listens for incoming http connections on `bind`
// and uses h to handle all requests.
// This function does not return unless there is a problem (like
// http.ListenAndServe).
439687
func StartMappingProxy(bind string, h http.Handler) error {
	s := http.Server{
		Addr:    bind,
		Handler: h,
	}
	return s.ListenAndServe()
}
913833
func (client *Client) Proxies() (map[string]*Proxy, error) {
	resp, err := http.Get(client.endpoint + "/proxies")
	if err != nil {
		return nil, err
	}

	err = checkError(resp, http.StatusOK, "Proxies")
	if err != nil {
		return nil, err
	}

	proxies := make(map[string]*Proxy)
	err = json.NewDecoder(resp.Body).Decode(&proxies)
	if err != nil {
		return nil, err
	}
	for _, proxy := range proxies {
		proxy.client = client
		proxy.created = true
	}

	return proxies, nil
}
274884
func (c *Client) StartServer() {
	mux := http.NewServeMux()
	mux.Handle("/", c)
	log.Printf("Listening on http://%v...\n", c.BindAddress)
	if err := http.ListenAndServe(c.BindAddress, mux); err != nil {
		log.Fatal(err)
	}
}
279957
func (c *Config) AptHTTPProxy() string {
	return addSchemeIfMissing("http", c.getWithFallback(AptHTTPProxyKey, JujuHTTPProxyKey, HTTPProxyKey))
}
689986
func Start(dir string, port int, tlsCrt, tlsKey, jwtPubKey, jwtPrivateKey, bind, authToken string) {
	var err error
	HttpDB, err = db.OpenDB(dir)
	if err != nil {
		panic(err)
	}

	// These endpoints are always available and do not require authentication
	http.HandleFunc("/", Welcome)
	http.HandleFunc("/version", Version)
	http.HandleFunc("/memstats", MemStats)

	// Install API endpoint handlers that may require authorization
	var authWrap func(http.HandlerFunc) http.HandlerFunc
	if authToken != "" {
		tdlog.Noticef("API endpoints now require the pre-shared token in Authorization header.")
		authWrap = func(originalHandler http.HandlerFunc) http.HandlerFunc {
			return func(w http.ResponseWriter, r *http.Request) {
				if "token "+authToken != r.Header.Get("Authorization") {
					http.Error(w, "", http.StatusUnauthorized)
					return
				}
				originalHandler(w, r)
			}
		}
	} else if jwtPubKey != "" && jwtPrivateKey != "" {
		tdlog.Noticef("API endpoints now require JWT in Authorization header.")
		var publicKeyContent, privateKeyContent []byte
		if publicKeyContent, err = ioutil.ReadFile(jwtPubKey); err != nil {
			panic(err)
		} else if publicKey, err = jwt.ParseRSAPublicKeyFromPEM(publicKeyContent); err != nil {
			panic(err)
		} else if privateKeyContent, err = ioutil.ReadFile(jwtPrivateKey); err != nil {
			panic(err)
		} else if privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateKeyContent); err != nil {
			panic(err)
		}
		jwtInitSetup()
		authWrap = jwtWrap
		// does not require JWT auth
		http.HandleFunc("/getjwt", getJWT)
		http.HandleFunc("/checkjwt", checkJWT)
	} else {
		tdlog.Noticef("API endpoints do not require Authorization header.")
		authWrap = func(originalHandler http.HandlerFunc) http.HandlerFunc {
			return originalHandler
		}
	}
	// collection management (stop-the-world)
	http.HandleFunc("/create", authWrap(Create))
	http.HandleFunc("/rename", authWrap(Rename))
	http.HandleFunc("/drop", authWrap(Drop))
	http.HandleFunc("/all", authWrap(All))
	http.HandleFunc("/scrub", authWrap(Scrub))
	http.HandleFunc("/sync", authWrap(Sync))
	// query
	http.HandleFunc("/query", authWrap(Query))
	http.HandleFunc("/count", authWrap(Count))
	// document management
	http.HandleFunc("/insert", authWrap(Insert))
	http.HandleFunc("/get", authWrap(Get))
	http.HandleFunc("/getpage", authWrap(GetPage))
	http.HandleFunc("/update", authWrap(Update))
	http.HandleFunc("/delete", authWrap(Delete))
	http.HandleFunc("/approxdoccount", authWrap(ApproxDocCount))
	// index management (stop-the-world)
	http.HandleFunc("/index", authWrap(Index))
	http.HandleFunc("/indexes", authWrap(Indexes))
	http.HandleFunc("/unindex", authWrap(Unindex))
	// misc (stop-the-world)
	http.HandleFunc("/shutdown", authWrap(Shutdown))
	http.HandleFunc("/dump", authWrap(Dump))

	iface := "all interfaces"
	if bind != "" {
		iface = bind
	}

	if tlsCrt != "" {
		tdlog.Noticef("Will listen on %s (HTTPS), port %d.", iface, port)
		if err := http.ListenAndServeTLS(fmt.Sprintf("%s:%d", bind, port), tlsCrt, tlsKey, nil); err != nil {
			tdlog.Panicf("Failed to start HTTPS service - %s", err)
		}
	} else {
		tdlog.Noticef("Will listen on %s (HTTP), port %d.", iface, port)
		http.ListenAndServe(fmt.Sprintf("%s:%d", bind, port), nil)
	}
}
881005
func NewProxy(ctx context.Context) *Proxy {
	var p Proxy

	passThrough = newProxyPassthrough(ctx)
	passThrough.readConfig(ctx)
	return &p
}
373830
func NewProxy(addr, trans string) *Proxy {
	p := &Proxy{
		addr:      addr,
		fails:     0,
		probe:     up.New(),
		transport: newTransport(addr),
	}
	p.health = NewHealthChecker(trans)
	runtime.SetFinalizer(p, (*Proxy).finalizer)
	return p
}
713588
func (F *Frisby) SetProxy(url string) *Frisby {
	F.Req.Proxy = url
	return F
}
570821
func (i *TeleInstance) StartNodeAndProxy(name string, sshPort, proxyWebPort, proxySSHPort int) error {
	dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName)
	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.Token = "token"
	tconf.HostUUID = name
	tconf.Hostname = name
	tconf.UploadEventsC = i.UploadEventsC
	tconf.DataDir = dataDir
	var ttl time.Duration
	tconf.CachePolicy = service.CachePolicy{
		Enabled:   true,
		RecentTTL: &ttl,
	}

	tconf.Auth.Enabled = false

	tconf.Proxy.Enabled = true
	tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxySSHPort))
	tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxyWebPort))
	tconf.Proxy.DisableReverseTunnel = true
	tconf.Proxy.DisableWebService = true

	tconf.SSH.Enabled = true
	tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", sshPort))
	tconf.SSH.PublicAddrs = []utils.NetAddr{
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Loopback,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Host,
		},
	}

	// 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.ProxySSHReady,
		service.NodeSSHReady,
	}

	// 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 node and proxy (in instance %v) started: %v/%v events received.",
		i.Secrets.SiteName, len(expectedEvents), len(receivedEvents))
	return nil
}
519796
func (parser *Parser) FindProxy(url, host string) (string, error) {
	if parser.rt == nil {
		return "", errors.New("A proxy auto-config file has not been loaded")
	}

	return parser.rt.findProxyForURL(url, host)
}
470299
func (r *Request) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Request {
	r.setting.Proxy = proxy
	return r
}
1312872
func NewProxy(target *querypb.Target, qs queryservice.QueryService, normalize bool) *Proxy {
	return &Proxy{
		target:    target,
		qs:        qs,
		normalize: normalize,
	}
}
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
}
917532
func (s *SubServer) Start(listenAddr string) error {
	s.listenAddr = listenAddr

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Example notify response
		/*
			Method:NOTIFY URL:/ Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[Nt:[upnp:event] Nts:[upnp:propchange] Sid:[uuid:054ce1c6-1dd2-11b2-864f-d1dbdfd9a2e2] Seq:[6] Content-Type:[text/xml; charset="utf-8"] Content-Length:[296]] Body:0xc4200dc300 ContentLength:296 TransferEncoding:[] Close:false Host:192.168.0.9:9000 Form:map[] PostForm:map[] MultipartForm:<nil> Trailer:map[] RemoteAddr:192.168.0.34:3663 RequestURI:/ TLS:<nil> Cancel:<nil> Response:<nil> ctx:0xc4200dc340}
		*/

		defer func() {
			w.WriteHeader(http.StatusOK)
		}()

		if r.Method != "NOTIFY" {
			return
		}

		sid, ok := r.Header["Sid"]
		if !ok {
			return
		}
		if len(sid) == 0 {
			return
		}
		sub, ok := s.subs[sid[0]]
		if !ok {
			return
		}

		// Just return a string, caller responsible for disassembling it
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return
		}
		sub.Subscriber.UPNPNotify(NotifyEvent{SID: sid[0], Body: string(body)})
	})

	return http.ListenAndServe(listenAddr, mux)
}
269899
func (e *Endpoint) WaitForProxyCompletions(proxyWaitGroup *completion.WaitGroup) error {
	if proxyWaitGroup == nil {
		return nil
	}

	err := proxyWaitGroup.Context().Err()
	if err != nil {
		return fmt.Errorf("context cancelled before waiting for proxy updates: %s", err)
	}

	start := time.Now()

	e.getLogger().Debug("Waiting for proxy updates to complete...")
	err = proxyWaitGroup.Wait()
	if err != nil {
		return fmt.Errorf("proxy state changes failed: %s", err)
	}
	e.getLogger().Debug("Wait time for proxy updates: ", time.Since(start))

	return nil
}
581228
func Start() {
	mux := &yarpcHTTPMux{
		handlers: make(map[string]http.Handler),
	}
	mux.HandleFunc("handlertimeout/raw", handlerTimeoutRawHandler)

	server = net.NewHTTPServer(
		&http.Server{
			Addr:         addr,
			Handler:      mux,
			ReadTimeout:  5 * time.Second,
			WriteTimeout: 5 * time.Second,
		})

	if err := server.ListenAndServe(); err != nil {
		log.Fatalf("failed to start HTTP server: %v", err)
	}
}
151638
func (h *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	h.ServeHTTPC(h.StartingContext, rw, r)
}