// GetMQTT connects a new MQTT clients with the specified credentials
970287
func GetMQTT(ctx ttnlog.Interface, accessKey string) mqtt.Client {
	username, password, err := getMQTTCredentials(ctx, accessKey)
	if err != nil {
		ctx.WithError(err).Fatal("Failed to get MQTT credentials")
	}

	mqttProto := "tcp"
	if strings.HasSuffix(viper.GetString("mqtt-address"), ":8883") {
		mqttProto = "ssl"
		ctx.Fatal("TLS connections are not yet supported by ttnctl")
	}
	broker := fmt.Sprintf("%s://%s", mqttProto, viper.GetString("mqtt-address"))
	client := mqtt.NewClient(ctx, "ttnctl", username, password, broker)

	ctx.WithFields(ttnlog.Fields{
		"MQTT Broker": broker,
		"Username":    username,
	}).Info("Connecting to MQTT...")

	if err := client.Connect(); err != nil {
		ctx.WithError(err).Fatal("Could not connect")
	}

	return client
}
112462
func (ctx *CtxId) GetMIC(qopReq QOP, messageBuffer *Buffer) (
	messageToken *Buffer, err error) {

	min := C.OM_uint32(0)

	token, err := ctx.MakeBuffer(allocGSSAPI)
	if err != nil {
		return nil, err
	}

	maj := C.wrap_gss_get_mic(ctx.Fp_gss_get_mic,
		&min,
		ctx.C_gss_ctx_id_t,
		C.gss_qop_t(qopReq),
		messageBuffer.C_gss_buffer_t,
		token.C_gss_buffer_t)

	err = ctx.stashLastStatus(maj, min)
	if err != nil {
		return nil, err
	}

	return token, nil
}
305170
func GetT(t testing.T, n int) (ports []int) {
	ports, err := Free(n)
	if err != nil {
		t.Fatalf("Failed retrieving free port: %v", err)
	}

	return ports
}
882052
func GetSockets(steamid string) (sockets []*wsevent.Client, success bool) {
	socketsMu.RLock()
	defer socketsMu.RUnlock()

	sockets, success = steamIDSockets[steamid]
	return
}
158297
func (_m *ClientInterface) GetHost(hostID string) (*host.Host, error) {
	ret := _m.Called(hostID)

	var r0 *host.Host
	if rf, ok := ret.Get(0).(func(string) *host.Host); ok {
		r0 = rf(hostID)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*host.Host)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string) error); ok {
		r1 = rf(hostID)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
307508
func (r Network_Interconnect_Tenant) GetPorts(provider *string) (resp string, err error) {
	params := []interface{}{
		provider,
	}
	err = r.Session.DoRequest("SoftLayer_Network_Interconnect_Tenant", "getPorts", params, &r.Options, &resp)
	return
}
1269969
func getTLSConfig(cfg *config) (*tls.Config, *credentials.TransportCredentials,
	string, error) {

	// Ensure we create TLS key and certificate if they don't exist
	if !fileExists(cfg.TLSCertPath) && !fileExists(cfg.TLSKeyPath) {
		err := genCertPair(cfg.TLSCertPath, cfg.TLSKeyPath)
		if err != nil {
			return nil, nil, "", err
		}
	}

	cert, err := tls.LoadX509KeyPair(cfg.TLSCertPath, cfg.TLSKeyPath)
	if err != nil {
		return nil, nil, "", err
	}

	tlsCfg := &tls.Config{
		Certificates: []tls.Certificate{cert},
		CipherSuites: tlsCipherSuites,
		MinVersion:   tls.VersionTLS12,
	}

	restCreds, err := credentials.NewClientTLSFromFile(cfg.TLSCertPath, "")
	if err != nil {
		return nil, nil, "", err
	}

	restProxyDest := cfg.RPCListeners[0].String()
	switch {
	case strings.Contains(restProxyDest, "0.0.0.0"):
		restProxyDest = strings.Replace(
			restProxyDest, "0.0.0.0", "127.0.0.1", 1,
		)

	case strings.Contains(restProxyDest, "[::]"):
		restProxyDest = strings.Replace(
			restProxyDest, "[::]", "[::1]", 1,
		)
	}

	return tlsCfg, &restCreds, restProxyDest, nil
}
972498
func NewAMQPTarget(id string, args AMQPArgs) (*AMQPTarget, error) {
	var conn *amqp.Connection
	var err error
	// Retry 5 times with time interval of 2 seconds.
	for i := 1; i <= 5; i++ {
		conn, err = amqp.Dial(args.URL.String())
		if err == nil {
			break
		}
		if err != nil && i == 5 {
			return nil, err
		}
		time.Sleep(2 * time.Second)
	}

	return &AMQPTarget{
		id:   event.TargetID{ID: id, Name: "amqp"},
		args: args,
		conn: conn,
	}, nil
}
1320400
func (c *Client) GetMember(name string) *GetMemberResult {
	resp, err := c.do("GET", fmt.Sprintf("/tribe/member/%s", name), ContentTypeJSON, nil)
	if err != nil {
		return &GetMemberResult{Err: err}
	}
	switch resp.Meta.Type {
	case rbody.TribeMemberShowType:
		// Success
		return &GetMemberResult{resp.Body.(*rbody.TribeMemberShow), nil}
	case rbody.ErrorType:
		return &GetMemberResult{Err: resp.Body.(*rbody.Error)}
	default:
		return &GetMemberResult{Err: ErrAPIResponseMetaType}
	}
}
895193
func ZmqRequestSocket(ip string, request_ports []int) *zmq.Socket {
	context, _ := zmq.NewContext()
	socket, _ := context.NewSocket(zmq.REQ)
	for _, _port := range request_ports {
		socket.Connect(fmt.Sprintf("tcp://%s:%d", ip, _port))
	}
	return socket
}
1022629
func (s *PresenceService) GetTunnelConnection(clusterName, connectionName string, opts ...services.MarshalOption) (services.TunnelConnection, error) {
	item, err := s.Get(context.TODO(), backend.Key(tunnelConnectionsPrefix, clusterName, connectionName))
	if err != nil {
		if trace.IsNotFound(err) {
			return nil, trace.NotFound("trusted cluster connection %q is not found", connectionName)
		}
		return nil, trace.Wrap(err)
	}
	conn, err := services.UnmarshalTunnelConnection(item.Value,
		services.AddOptions(opts, services.WithResourceID(item.ID), services.WithExpires(item.Expires))...)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return conn, nil
}
737436
func (c *DefaultClient) Connect() error {
	if c.mqtt.IsConnected() {
		return nil
	}
	var err error
	for retries := 0; retries < ConnectRetries; retries++ {
		token := c.mqtt.Connect()
		finished := token.WaitTimeout(1 * time.Second)
		if !finished {
			c.ctx.Warn("mqtt: connection took longer than expected...")
			token.Wait()
		}
		err = token.Error()
		if err == nil {
			break
		}
		c.ctx.Warnf("mqtt: could not connect (%s), retrying...", err)
		<-time.After(ConnectRetryDelay)
	}
	if err != nil {
		return fmt.Errorf("Could not connect to MQTT Broker (%s)", err)
	}
	return nil
}
531249
func (a *AuthMiddleware) GetUser(r *http.Request) (interface{}, error) {
	peers := r.TLS.PeerCertificates
	if len(peers) > 1 {
		// when turning intermediaries on, don't forget to verify
		// https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59
		return nil, trace.AccessDenied("access denied: intermediaries are not supported")
	}
	localClusterName, err := a.AccessPoint.GetClusterName()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	// with no client authentication in place, middleware
	// assumes not-privileged Nop role.
	// it theoretically possible to use bearer token auth even
	// for connections without auth, but this is not active use-case
	// therefore it is not allowed to reduce scope
	if len(peers) == 0 {
		return BuiltinRole{
			GetClusterConfig: a.AccessPoint.GetClusterConfig,
			Role:             teleport.RoleNop,
			Username:         string(teleport.RoleNop),
			ClusterName:      localClusterName.GetClusterName(),
		}, nil
	}
	clientCert := peers[0]
	certClusterName, err := tlsca.ClusterName(clientCert.Issuer)
	if err != nil {
		log.Warnf("Failed to parse client certificate %v.", err)
		return nil, trace.AccessDenied("access denied: invalid client certificate")
	}

	identity, err := tlsca.FromSubject(clientCert.Subject)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	// If there is any restriction on the certificate usage
	// reject the API server request. This is done so some classes
	// of certificates issued for kubernetes usage by proxy, can not be used
	// against auth server. Later on we can extend more
	// advanced cert usage, but for now this is the safest option.
	if len(identity.Usage) != 0 && !utils.StringSlicesEqual(a.AcceptedUsage, identity.Usage) {
		log.Warningf("Restricted certificate of user %q with usage %v rejected while accessing the auth endpoint with acceptable usage %v.",
			identity.Username, identity.Usage, a.AcceptedUsage)
		return nil, trace.AccessDenied("access denied: invalid client certificate")
	}

	// this block assumes interactive user from remote cluster
	// based on the remote certificate authority cluster name encoded in
	// x509 organization name. This is a safe check because:
	// 1. Trust and verification is established during TLS handshake
	// by creating a cert pool constructed of trusted certificate authorities
	// 2. Remote CAs are not allowed to have the same cluster name
	// as the local certificate authority
	if certClusterName != localClusterName.GetClusterName() {
		// make sure that this user does not have system role
		// the local auth server can not truste remote servers
		// to issue certificates with system roles (e.g. Admin),
		// to get unrestricted access to the local cluster
		systemRole := findSystemRole(identity.Groups)
		if systemRole != nil {
			return RemoteBuiltinRole{
				Role:        *systemRole,
				Username:    identity.Username,
				ClusterName: certClusterName,
			}, nil
		}
		return RemoteUser{
			ClusterName:      certClusterName,
			Username:         identity.Username,
			Principals:       identity.Principals,
			KubernetesGroups: identity.KubernetesGroups,
			RemoteRoles:      identity.Groups,
		}, nil
	}
	// code below expects user or service from local cluster, to distinguish between
	// interactive users and services (e.g. proxies), the code below
	// checks for presence of system roles issued in certificate identity
	systemRole := findSystemRole(identity.Groups)
	// in case if the system role is present, assume this is a service
	// agent, e.g. Proxy, connecting to the cluster
	if systemRole != nil {
		return BuiltinRole{
			GetClusterConfig: a.AccessPoint.GetClusterConfig,
			Role:             *systemRole,
			Username:         identity.Username,
			ClusterName:      localClusterName.GetClusterName(),
		}, nil
	}
	// otherwise assume that is a local role, no need to pass the roles
	// as it will be fetched from the local database
	return LocalUser{
		Username: identity.Username,
	}, nil
}
733741
func (c *Client) GetCACert() ([]byte, error) {
	var cert bytes.Buffer
	res, err := c.RawReq("GET", "/ca-cert", nil, nil, nil)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if _, err := io.Copy(&cert, res.Body); err != nil {
		return nil, err
	}
	return cert.Bytes(), nil
}
1086644
func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {
	switch o := opt.(type) {
	case tcpip.ErrorOption:
		return nil

	case *tcpip.SendBufferSizeOption:
		e.mu.Lock()
		*o = tcpip.SendBufferSizeOption(e.sndBufSize)
		e.mu.Unlock()
		return nil

	case *tcpip.ReceiveBufferSizeOption:
		e.rcvMu.Lock()
		*o = tcpip.ReceiveBufferSizeOption(e.rcvBufSizeMax)
		e.rcvMu.Unlock()
		return nil

	case *tcpip.V6OnlyOption:
		// We only recognize this option on v6 endpoints.
		if e.netProto != header.IPv6ProtocolNumber {
			return tcpip.ErrUnknownProtocolOption
		}

		e.mu.Lock()
		v := e.v6only
		e.mu.Unlock()

		*o = 0
		if v {
			*o = 1
		}
		return nil

	case *tcpip.ReceiveQueueSizeOption:
		e.rcvMu.Lock()
		if e.rcvList.Empty() {
			*o = 0
		} else {
			p := e.rcvList.Front()
			*o = tcpip.ReceiveQueueSizeOption(p.data.Size())
		}
		e.rcvMu.Unlock()
		return nil

	case *tcpip.MulticastTTLOption:
		e.mu.Lock()
		*o = tcpip.MulticastTTLOption(e.multicastTTL)
		e.mu.Unlock()
		return nil

	case *tcpip.MulticastInterfaceOption:
		e.mu.Lock()
		*o = tcpip.MulticastInterfaceOption{
			e.multicastNICID,
			e.multicastAddr,
		}
		e.mu.Unlock()
		return nil

	case *tcpip.MulticastLoopOption:
		e.mu.RLock()
		v := e.multicastLoop
		e.mu.RUnlock()

		*o = tcpip.MulticastLoopOption(v)
		return nil

	case *tcpip.ReusePortOption:
		e.mu.RLock()
		v := e.reusePort
		e.mu.RUnlock()

		*o = 0
		if v {
			*o = 1
		}
		return nil

	case *tcpip.KeepaliveEnabledOption:
		*o = 0
		return nil

	case *tcpip.BroadcastOption:
		e.mu.RLock()
		v := e.broadcast
		e.mu.RUnlock()

		*o = 0
		if v {
			*o = 1
		}
		return nil

	default:
		return tcpip.ErrUnknownProtocolOption
	}
}
926344
func (p *ConnPool) getClient(dc string, addr net.Addr, version int, useTLS bool) (*Conn, *StreamClient, error) {
	retries := 0
START:
	// Try to get a conn first
	conn, err := p.acquire(dc, addr, version, useTLS)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to get conn: %v", err)
	}

	// Get a client
	client, err := conn.getClient()
	if err != nil {
		p.clearConn(conn)
		p.releaseConn(conn)

		// Try to redial, possible that the TCP session closed due to timeout
		if retries == 0 {
			retries++
			goto START
		}
		return nil, nil, fmt.Errorf("failed to start stream: %v", err)
	}
	return conn, client, nil
}
1191330
func GetCredentialSupport() *CredentialSupport {

	once.Do(func() {
		credSupport = &CredentialSupport{
			CASupport: &CASupport{
				AppRootCAsByChain:     make(map[string][][]byte),
				OrdererRootCAsByChain: make(map[string][][]byte),
			},
		}
	})
	return credSupport
}