// UDPDirectForwardListener creates a Listener for UDP port forwarding server.
351797
func UDPDirectForwardListener(addr string, ttl time.Duration) (Listener, error) {
	laddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return nil, err
	}
	ln, err := net.ListenUDP("udp", laddr)
	if err != nil {
		return nil, err
	}
	l := &udpDirectForwardListener{
		ln:       ln,
		conns:    make(map[string]*udpServerConn),
		connChan: make(chan net.Conn, 1024),
		errChan:  make(chan error, 1),
		ttl:      ttl,
	}
	go l.listenLoop()
	return l, nil
}
125950
func (s *ClusterMetadata) SetForwardingAddressId(v string) *ClusterMetadata {
	s.ForwardingAddressId = &v
	return s
}
539066
func (t *Tunnel) ForwardPort() error {
	// Build a url to the portforward endpoint
	// example: http://localhost:8080/api/v1/namespaces/helm/pods/tiller-deploy-9itlq/portforward
	u := t.client.Post().
		Resource("pods").
		Namespace(t.Namespace).
		Name(t.PodName).
		SubResource("portforward").URL()

	transport, upgrader, err := spdy.RoundTripperFor(t.config)
	if err != nil {
		return err
	}
	dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", u)

	local, err := getAvailablePort()
	if err != nil {
		return fmt.Errorf("could not find an available port: %s", err)
	}
	t.Local = local

	ports := []string{fmt.Sprintf("%d:%d", t.Local, t.Remote)}

	pf, err := portforward.New(dialer, ports, t.stopChan, t.readyChan, t.Out, t.Out)
	if err != nil {
		return err
	}

	errChan := make(chan error)
	go func() {
		errChan <- pf.ForwardPorts()
	}()

	select {
	case err = <-errChan:
		return fmt.Errorf("forwarding ports: %v", err)
	case <-pf.Ready:
		return nil
	}
}
717336
func (pf *PortForwarder) ForwardPorts() error {
	defer pf.Close()

	var err error
	pf.streamConn, _, err = pf.dialer.Dial(PortForwardProtocolV1Name)
	if err != nil {
		return fmt.Errorf("error upgrading connection: %s", err)
	}
	defer pf.streamConn.Close()

	return pf.forward()
}
1108796
func (f *Forwarder) portForward(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) {
	f.Debugf("Port forward: %v. req headers: %v", req.URL.String(), req.Header)
	sess, err := f.getOrCreateClusterSession(*ctx)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	if err := f.setupForwardingHeaders(ctx, sess, req); err != nil {
		f.Debugf("DENIED Port forward: %v.", req.URL.String())
		return nil, trace.Wrap(err)
	}

	dialer, err := f.getDialer(*ctx, sess, req)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	onPortForward := func(addr string, success bool) {
		event := events.PortForward
		if !success {
			event = events.PortForwardFailure
		}
		f.AuditLog.EmitAuditEvent(event, events.EventFields{
			events.EventProtocol:      events.EventProtocolKube,
			events.PortForwardAddr:    addr,
			events.PortForwardSuccess: success,
			events.EventLogin:         ctx.User.GetName(),
			events.EventUser:          ctx.User.GetName(),
			events.LocalAddr:          sess.cluster.targetAddr,
			events.RemoteAddr:         req.RemoteAddr,
		})
	}

	q := req.URL.Query()
	request := portForwardRequest{
		podNamespace:       p.ByName("podNamespace"),
		podName:            p.ByName("podName"),
		ports:              q["ports"],
		context:            req.Context(),
		httpRequest:        req,
		httpResponseWriter: w,
		onPortForward:      onPortForward,
		targetDialer:       dialer,
	}
	f.Debugf("Starting %v.", request)
	err = runPortForwarding(request)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	f.Debugf("Done %v.", request)
	return nil, nil
}
165114
func WithForwardedHeaders(fn func(header string) bool) Option {
	return func(p *Proxy) {
		p.headerForwarder = fn
	}
}
258461
func (r *Runtime) PortForwardContainer(c *Container, port int32, stream io.ReadWriter) error {
	impl, err := r.RuntimeImpl(c)
	if err != nil {
		return err
	}

	return impl.PortForwardContainer(c, port, stream)
}
756990
func NewForwarder(host string, passedConf *ForwarderConfig) (*Forwarder, error) {

	conf := pointer.FillDefaultFrom(passedConf, defaultForwarderConfig).(*ForwarderConfig)

	connectionAddress := net.JoinHostPort(host, strconv.FormatUint(uint64(*conf.Port), 10))
	var d net.Dialer
	d.Deadline = time.Now().Add(*conf.Timeout)
	conn, err := d.Dial("tcp", connectionAddress)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot dial address %s", connectionAddress)
	}
	ret := &Forwarder{
		dimensionComparor: dpdimsort.NewOrdering(conf.DimensionOrder),
		connectionTimeout: *conf.Timeout,
		connectionAddress: connectionAddress,
		tk:                conf.Timer,
		dialer:            net.DialTimeout,
		pool: connPool{
			conns: make([]net.Conn, 0, *conf.IdleConnectionPoolSize),
		},
	}
	err = ret.Setup(passedConf.Filters)
	if err != nil {
		return nil, err
	}

	ret.pool.Return(conn)
	return ret, nil
}
768929
func WithForwardTimeout(d time.Duration) Option {
	return func(opts *options) {
		opts.forwardTimeout = d
	}
}
1114844
func (c *Client) UpdatePortForwardingRule(p *UpdatePortForwardingRuleParameter) (*PortForwardingRule, error) {
	obj, err := c.Request("updatePortForwardingRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*PortForwardingRule), err
}
1337338
func SSHForwardHandler(opts ...HandlerOption) Handler {
	h := &sshForwardHandler{}
	h.Init(opts...)

	return h
}
545085
func (s *Stack) Forwarding() bool {
	// TODO(igudger, bgeffon): Expose via /proc/sys/net/ipv4/ip_forward.
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.forwarding
}
71036
func UDPRemoteForwardHandler(raddr string, opts ...HandlerOption) Handler {
	h := &udpRemoteForwardHandler{
		raddr: raddr,
		group: NewNodeGroup(),
	}

	for i, addr := range strings.Split(raddr, ",") {
		if addr == "" {
			continue
		}
		// We treat the remote target server as a node, so we can put them in a group,
		// and perform the node selection for load balancing.
		h.group.AddNode(Node{
			ID:   i + 1,
			Addr: addr,
			Host: addr,
		})
	}

	h.Init(opts...)

	return h
}
949480
func (c *NodeClient) dynamicListenAndForward(ctx context.Context, ln net.Listener) {
	defer ln.Close()
	defer c.Close()

	for {
		// Accept connection from the client. Here the client is typically
		// something like a web browser or other SOCKS5 aware application.
		conn, err := ln.Accept()
		if err != nil {
			log.Errorf("Dynamic port forwarding (SOCKS5) failed: %v.", err)
			break
		}

		// Perform the SOCKS5 handshake with the client to find out the remote
		// address to proxy.
		remoteAddr, err := socks.Handshake(conn)
		if err != nil {
			log.Errorf("SOCKS5 handshake failed: %v.", err)
			break
		}
		log.Debugf("SOCKS5 proxy forwarding requests to %v.", remoteAddr)

		// Proxy the connection to the remote address.
		go func() {
			err := c.proxyConnection(ctx, conn, remoteAddr)
			if err != nil {
				log.Warnf("Failed to proxy connection: %v.", err)
			}
		}()
	}
}
1017183
func (s *UpdateJobInput) SetForwardingAddressId(v string) *UpdateJobInput {
	s.ForwardingAddressId = &v
	return s
}
999208
func (pf *PortForwarder) forward() error {
	var err error

	listenSuccess := false
	for i := range pf.ports {
		port := &pf.ports[i]
		err = pf.listenOnPort(port)
		switch {
		case err == nil:
			listenSuccess = true
		default:
			if pf.errOut != nil {
				fmt.Fprintf(pf.errOut, "Unable to listen on port %d: %v\n", port.Local, err)
			}
		}
	}

	if !listenSuccess {
		return fmt.Errorf("Unable to listen on any of the requested ports: %v", pf.ports)
	}

	if pf.Ready != nil {
		close(pf.Ready)
	}

	// wait for interrupt or conn closure
	select {
	case <-pf.stopChan:
	case <-pf.streamConn.CloseChan():
		runtime.HandleError(errors.New("lost connection to pod"))
	}

	return nil
}
981592
func (f *ForwardingLog) AddForwardingEvents(events []ForwardingEvent) error {
	// Before we create the database transaction, we'll ensure that the set
	// of forwarding events are properly sorted according to their
	// timestamp.
	sort.Slice(events, func(i, j int) bool {
		return events[i].Timestamp.Before(events[j].Timestamp)
	})

	var timestamp [8]byte

	return f.db.Batch(func(tx *bbolt.Tx) error {
		// First, we'll fetch the bucket that stores our time series
		// log.
		logBucket, err := tx.CreateBucketIfNotExists(
			forwardingLogBucket,
		)
		if err != nil {
			return err
		}

		// With the bucket obtained, we can now begin to write out the
		// series of events.
		for _, event := range events {
			var eventBytes [forwardingEventSize]byte
			eventBuf := bytes.NewBuffer(eventBytes[0:0:forwardingEventSize])

			// First, we'll serialize this timestamp into our
			// timestamp buffer.
			byteOrder.PutUint64(
				timestamp[:], uint64(event.Timestamp.UnixNano()),
			)

			// With the key encoded, we'll then encode the event
			// into our buffer, then write it out to disk.
			err := encodeForwardingEvent(eventBuf, &event)
			if err != nil {
				return err
			}
			err = logBucket.Put(timestamp[:], eventBuf.Bytes())
			if err != nil {
				return err
			}
		}

		return nil
	})
}