// New creates a new DHCP client that sends and receives packets on the given
// interface.
179259
func New(iface netlink.Link, opts ...ClientOpt) (*Client, error) {
	c := &Client{
		iface:   iface,
		timeout: 10 * time.Second,
		retry:   3,
	}

	for _, opt := range opts {
		if err := opt(c); err != nil {
			return nil, err
		}
	}

	if c.conn == nil {
		var err error
		c.conn, err = NewPacketUDPConn(iface.Attrs().Name, ClientPort)
		if err != nil {
			return nil, err
		}
	}
	return c, nil
}
1175191
func New() (*Conn, error) {
	c := new(Conn)

	if err := c.initConnection(); err != nil {
		return nil, err
	}

	return c, nil
}
95996
func New(dialer httpstream.Dialer, ports []string, stopChan <-chan struct{}, readyChan chan struct{}, out, errOut io.Writer) (*PortForwarder, error) {
	return NewOnAddresses(dialer, []string{"localhost"}, ports, stopChan, readyChan, out, errOut)
}
840390
func New(opts *Options) (tcpip.LinkEndpointID, error) {
	if err := syscall.SetNonblock(opts.FD, true); err != nil {
		return 0, fmt.Errorf("syscall.SetNonblock(%v) failed: %v", opts.FD, err)
	}

	caps := stack.LinkEndpointCapabilities(0)
	if opts.RXChecksumOffload {
		caps |= stack.CapabilityRXChecksumOffload
	}

	if opts.TXChecksumOffload {
		caps |= stack.CapabilityTXChecksumOffload
	}

	hdrSize := 0
	if opts.EthernetHeader {
		hdrSize = header.EthernetMinimumSize
		caps |= stack.CapabilityResolutionRequired
	}

	if opts.SaveRestore {
		caps |= stack.CapabilitySaveRestore
	}

	if opts.DisconnectOk {
		caps |= stack.CapabilityDisconnectOk
	}

	e := &endpoint{
		fd:                 opts.FD,
		mtu:                opts.MTU,
		caps:               caps,
		closed:             opts.ClosedFunc,
		addr:               opts.Address,
		hdrSize:            hdrSize,
		packetDispatchMode: opts.PacketDispatchMode,
	}

	// For non-socket FDs we read one packet a time (e.g. TAP devices).
	msgsPerRecv := 1
	e.inboundDispatcher = e.dispatch

	isSocket, err := isSocketFD(opts.FD)
	if err != nil {
		return 0, err
	}
	if isSocket {
		if opts.GSOMaxSize != 0 {
			e.caps |= stack.CapabilityGSO
			e.gsoMaxSize = opts.GSOMaxSize
		}

		switch e.packetDispatchMode {
		case PacketMMap:
			if err := e.setupPacketRXRing(); err != nil {
				return 0, fmt.Errorf("e.setupPacketRXRing failed: %v", err)
			}
			e.inboundDispatcher = e.packetMMapDispatch
			return stack.RegisterLinkEndpoint(e), nil

		case RecvMMsg:
			// If the provided FD is a socket then we optimize
			// packet reads by using recvmmsg() instead of read() to
			// read packets in a batch.
			e.inboundDispatcher = e.recvMMsgDispatch
			msgsPerRecv = MaxMsgsPerRecv
		}
	}

	e.views = make([][]buffer.View, msgsPerRecv)
	for i := range e.views {
		e.views[i] = make([]buffer.View, len(BufConfig))
	}
	e.iovecs = make([][]syscall.Iovec, msgsPerRecv)
	iovLen := len(BufConfig)
	if e.Capabilities()&stack.CapabilityGSO != 0 {
		// virtioNetHdr is prepended before each packet.
		iovLen++
	}
	for i := range e.iovecs {
		e.iovecs[i] = make([]syscall.Iovec, iovLen)
	}
	e.msgHdrs = make([]rawfile.MMsgHdr, msgsPerRecv)
	for i := range e.msgHdrs {
		e.msgHdrs[i].Msg.Iov = &e.iovecs[i][0]
		e.msgHdrs[i].Msg.Iovlen = uint64(iovLen)
	}

	return stack.RegisterLinkEndpoint(e), nil
}
1199876
func New(port string) (*Server, error) {
	s := &Server{messages: []string{}}

	listener, err := net.Listen("tcp", "0.0.0.0:"+port)
	if err != nil {
		return s, err
	}
	s.Listener = listener
	return s, nil
}
801605
func New(addr utils.NetAddr,
	hostname string,
	signers []ssh.Signer,
	authService auth.AccessPoint,
	dataDir string,
	advertiseIP string,
	proxyPublicAddr utils.NetAddr,
	options ...ServerOption) (*Server, error) {

	// read the host UUID:
	uuid, err := utils.ReadOrMakeHostUUID(dataDir)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	ctx, cancel := context.WithCancel(context.TODO())
	s := &Server{
		addr:            addr,
		authService:     authService,
		hostname:        hostname,
		labelsMutex:     &sync.Mutex{},
		advertiseIP:     advertiseIP,
		proxyPublicAddr: proxyPublicAddr,
		uuid:            uuid,
		cancel:          cancel,
		ctx:             ctx,
		clock:           clockwork.NewRealClock(),
		dataDir:         dataDir,
	}
	s.limiter, err = limiter.NewLimiter(limiter.LimiterConfig{})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	for _, o := range options {
		if err := o(s); err != nil {
			return nil, trace.Wrap(err)
		}
	}

	// TODO(klizhentas): replace function arguments with struct
	if s.alog == nil {
		return nil, trace.BadParameter("setup valid AuditLog parameter using SetAuditLog")
	}

	if s.namespace == "" {
		return nil, trace.BadParameter("setup valid namespace parameter using SetNamespace")
	}

	var component string
	if s.proxyMode {
		component = teleport.ComponentProxy
	} else {
		component = teleport.ComponentNode
	}

	s.Entry = logrus.WithFields(logrus.Fields{
		trace.Component:       component,
		trace.ComponentFields: logrus.Fields{},
	})

	s.reg, err = srv.NewSessionRegistry(s)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// add in common auth handlers
	s.authHandlers = &srv.AuthHandlers{
		Entry: logrus.WithFields(logrus.Fields{
			trace.Component:       component,
			trace.ComponentFields: logrus.Fields{},
		}),
		Server:      s,
		Component:   component,
		AuditLog:    s.alog,
		AccessPoint: s.authService,
	}

	// common term handlers
	s.termHandlers = &srv.TermHandlers{
		SessionRegistry: s.reg,
	}

	server, err := sshutils.NewServer(
		component,
		addr, s, signers,
		sshutils.AuthMethods{PublicKey: s.authHandlers.UserKeyAuth},
		sshutils.SetLimiter(s.limiter),
		sshutils.SetRequestHandler(s),
		sshutils.SetCiphers(s.ciphers),
		sshutils.SetKEXAlgorithms(s.kexAlgorithms),
		sshutils.SetMACAlgorithms(s.macAlgorithms))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	s.srv = server

	var heartbeatMode srv.HeartbeatMode
	if s.proxyMode {
		heartbeatMode = srv.HeartbeatModeProxy
	} else {
		heartbeatMode = srv.HeartbeatModeNode
	}
	heartbeat, err := srv.NewHeartbeat(srv.HeartbeatConfig{
		Mode:            heartbeatMode,
		Context:         ctx,
		Component:       component,
		Announcer:       s.authService,
		GetServerInfo:   s.getServerInfo,
		KeepAlivePeriod: defaults.ServerKeepAliveTTL,
		AnnouncePeriod:  defaults.ServerAnnounceTTL/2 + utils.RandomDuration(defaults.ServerAnnounceTTL/10),
		ServerTTL:       defaults.ServerAnnounceTTL,
		CheckPeriod:     defaults.HeartbeatCheckPeriod,
		Clock:           s.clock,
	})
	if err != nil {
		s.srv.Close()
		return nil, trace.Wrap(err)
	}
	s.heartbeat = heartbeat
	return s, nil
}
401465
func (api *DNSAPI) New(zoneName string) *sacloud.DNS {
	return sacloud.CreateNewDNS(zoneName)
}
1046916
func New(pluginName string, networkClient networkclient.Interface, kClient kubernetes.Interface,
	networkInformers networkinformers.SharedInformerFactory) (*OsdnProxy, error) {
	return &OsdnProxy{
		kClient:          kClient,
		networkClient:    networkClient,
		networkInformers: networkInformers,
		ids:              make(map[string]uint32),
		egressDNS:        common.NewEgressDNS(),
		firewall:         make(map[string]*proxyFirewallItem),
		allEndpoints:     make(map[ktypes.UID]*proxyEndpoints),
	}, nil
}
947291
func New(ctx context.Context, next http.Handler, config config.IPWhiteList, name string) (http.Handler, error) {
	logger := middlewares.GetLogger(ctx, name, typeName)
	logger.Debug("Creating middleware")

	if len(config.SourceRange) == 0 {
		return nil, errors.New("sourceRange is empty, IPWhiteLister not created")
	}

	checker, err := ip.NewChecker(config.SourceRange)
	if err != nil {
		return nil, fmt.Errorf("cannot parse CIDR whitelist %s: %v", config.SourceRange, err)
	}

	strategy, err := config.IPStrategy.Get()
	if err != nil {
		return nil, err
	}

	logger.Debugf("Setting up IPWhiteLister with sourceRange: %s", config.SourceRange)
	return &ipWhiteLister{
		strategy:    strategy,
		whiteLister: checker,
		next:        next,
		name:        name,
	}, nil
}
631193
func New() (agent.Agent, net.Conn, error) {
	if !Available() {
		return nil, nil, errors.New("SSH agent requested but SSH_AUTH_SOCK not-specified")
	}

	sshAuthSock := os.Getenv("SSH_AUTH_SOCK")

	conn, err := net.Dial("unix", sshAuthSock)
	if err != nil {
		return nil, nil, fmt.Errorf("Error connecting to SSH_AUTH_SOCK: %v", err)
	}

	return agent.NewClient(conn), conn, nil
}
593008
func New(id string, client LockClient) (lock *Lock) {
	return &Lock{id, client}
}
849564
func New(ctx context.Context, h host.Host, options ...opts.Option) (*IpfsDHT, error) {
	var cfg opts.Options
	if err := cfg.Apply(append([]opts.Option{opts.Defaults}, options...)...); err != nil {
		return nil, err
	}
	dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols)

	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

	dht.proc = goprocessctx.WithContextAndTeardown(ctx, func() error {
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})

	dht.proc.AddChild(dht.providers.Process())
	dht.Validator = cfg.Validator

	if !cfg.Client {
		for _, p := range cfg.Protocols {
			h.SetStreamHandler(p, dht.handleNewStream)
		}
	}
	return dht, nil
}
251120
func New(name string, transport peer.Transport, availableChooser peer.ListImplementation, opts ...ListOption) *List {
	options := defaultListOptions
	for _, o := range opts {
		o.apply(&options)
	}

	return &List{
		once:               lifecycle.NewOnce(),
		name:               name,
		uninitializedPeers: make(map[string]peer.Identifier, options.capacity),
		unavailablePeers:   make(map[string]*peerThunk, options.capacity),
		availablePeers:     make(map[string]*peerThunk, options.capacity),
		availableChooser:   availableChooser,
		transport:          transport,
		noShuffle:          options.noShuffle,
		randSrc:            rand.NewSource(options.seed),
		peerAvailableEvent: make(chan struct{}, 1),
	}
}
462973
func New(host string, transport *http.Transport) types.APIClient {
	return &client{
		Client: http.Client{
			Transport: transport,
		},
		host: host,
	}
}
532414
func New(uri string) Client {
	return &client{http.DefaultClient, strings.TrimSuffix(uri, "/")}
}
468041
func New(address string, opts ...ClientOpt) (*Client, error) {
	var copts clientOpts
	for _, o := range opts {
		if err := o(&copts); err != nil {
			return nil, err
		}
	}
	if copts.timeout == 0 {
		copts.timeout = 10 * time.Second
	}
	rt := fmt.Sprintf("%s.%s", plugin.RuntimePlugin, runtime.GOOS)
	if copts.defaultRuntime != "" {
		rt = copts.defaultRuntime
	}
	c := &Client{
		runtime: rt,
	}
	if copts.services != nil {
		c.services = *copts.services
	}
	if address != "" {
		gopts := []grpc.DialOption{
			grpc.WithBlock(),
			grpc.WithInsecure(),
			grpc.FailOnNonTempDialError(true),
			grpc.WithBackoffMaxDelay(3 * time.Second),
			grpc.WithDialer(dialer.Dialer),

			// TODO(stevvooe): We may need to allow configuration of this on the client.
			grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),
			grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),
		}
		if len(copts.dialOptions) > 0 {
			gopts = copts.dialOptions
		}
		if copts.defaultns != "" {
			unary, stream := newNSInterceptors(copts.defaultns)
			gopts = append(gopts,
				grpc.WithUnaryInterceptor(unary),
				grpc.WithStreamInterceptor(stream),
			)
		}
		connector := func() (*grpc.ClientConn, error) {
			ctx, cancel := context.WithTimeout(context.Background(), copts.timeout)
			defer cancel()
			conn, err := grpc.DialContext(ctx, dialer.DialAddress(address), gopts...)
			if err != nil {
				return nil, errors.Wrapf(err, "failed to dial %q", address)
			}
			return conn, nil
		}
		conn, err := connector()
		if err != nil {
			return nil, err
		}
		c.conn, c.connector = conn, connector
	}
	if copts.services == nil && c.conn == nil {
		return nil, errors.New("no grpc connection or services is available")
	}

	// check namespace labels for default runtime
	if copts.defaultRuntime == "" && copts.defaultns != "" {
		namespaces := c.NamespaceService()
		ctx := context.Background()
		if labels, err := namespaces.Labels(ctx, copts.defaultns); err == nil {
			if defaultRuntime, ok := labels[defaults.DefaultRuntimeNSLabel]; ok {
				c.runtime = defaultRuntime
			}
		} else {
			return nil, err
		}
	}

	return c, nil
}
460796
func (c *Config) New(proxyTransport *http.Transport, serviceResolver webhook.ServiceResolver) ([]admission.PluginInitializer, server.PostStartHookFunc, error) {
	webhookAuthResolverWrapper := webhook.NewDefaultAuthenticationInfoResolverWrapper(proxyTransport, c.LoopbackClientConfig)
	webhookPluginInitializer := webhookinit.NewPluginInitializer(webhookAuthResolverWrapper, serviceResolver)

	var cloudConfig []byte
	if c.CloudConfigFile != "" {
		var err error
		cloudConfig, err = ioutil.ReadFile(c.CloudConfigFile)
		if err != nil {
			klog.Fatalf("Error reading from cloud configuration file %s: %#v", c.CloudConfigFile, err)
		}
	}
	clientset, err := kubernetes.NewForConfig(c.LoopbackClientConfig)
	if err != nil {
		return nil, nil, err
	}

	discoveryClient := cacheddiscovery.NewMemCacheClient(clientset.Discovery())
	discoveryRESTMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
	kubePluginInitializer := NewPluginInitializer(
		cloudConfig,
		discoveryRESTMapper,
		quotainstall.NewQuotaConfigurationForAdmission(),
	)

	admissionPostStartHook := func(context genericapiserver.PostStartHookContext) error {
		discoveryRESTMapper.Reset()
		go utilwait.Until(discoveryRESTMapper.Reset, 30*time.Second, context.StopCh)
		return nil
	}

	return []admission.PluginInitializer{webhookPluginInitializer, kubePluginInitializer}, admissionPostStartHook, nil
}