// ParseConnectionString parses a zookeeper connection string in the form of
// host1:2181,host2:2181/chroot and returns the list of servers, and the chroot.
355716
func ParseConnectionString(zookeeper string) (nodes []string, chroot string) {
	nodesAndChroot := strings.SplitN(zookeeper, "/", 2)
	if len(nodesAndChroot) == 2 {
		chroot = fmt.Sprintf("/%s", nodesAndChroot[1])
	}
	nodes = strings.Split(nodesAndChroot[0], ",")
	return
}
1301704
func handleConnection(conn net.Conn, errChan chan<- error) {

	// close the connection when we're done here
	defer conn.Close()

	// create a new client for each connection
	proxy := mist.NewProxy()
	defer proxy.Close()

	// add basic TCP command handlers for this connection
	handlers := GenerateHandlers()

	encoder := json.NewEncoder(conn)
	decoder := json.NewDecoder(conn)

	// publish mist messages (pong, etc.. and messages if subscriber attatched)
	// to connected tcp client (non-blocking)
	go func() {
		for msg := range proxy.Pipe {
			lumber.Trace("Got message - %#v", msg)
			// if the message fails to encode its probably a syntax issue and needs to
			// break the loop here because it will never be able to encode it; this will
			// disconnect the client.
			if err := encoder.Encode(msg); err != nil {
				errChan <- fmt.Errorf("Failed to pubilsh proxy.Pipe contents to TCP clients - %s", err.Error())
				break
			}
		}
	}()

	// connection loop (blocking); continually read off the connection. Once something
	// is read, check to see if it's a message the client understands to be one of
	// its commands. If so attempt to execute the command.
	for {
		msg := mist.Message{}

		// if the message fails to decode its probably a syntax issue and needs to
		// break the loop here because it will never be able to decode it; this will
		// disconnect the client.
		if err := decoder.Decode(&msg); err != nil {
			switch err {
			case io.EOF:
				lumber.Debug("Client disconnected")
			case io.ErrUnexpectedEOF:
				lumber.Debug("Client disconnected unexpedtedly")
			default:
				errChan <- fmt.Errorf("Failed to decode message from TCP connection - %s", err.Error())
			}
			return
		}

		// if an authenticator was passed, check for a token on connect to see if
		// auth commands are allowed
		if auth.IsConfigured() && !proxy.Authenticated {

			// if the next input does not match the token then
			if msg.Data != authtoken {
				lumber.Debug("Client data doesn't match configured auth token")
				// break // allow connection w/o admin commands
				return // disconnect client
			}

			// todo: is this still used?
			// add auth commands ("admin" mode)
			for k, v := range auth.GenerateHandlers() {
				handlers[k] = v
			}

			// establish that the connection has already authenticated
			proxy.Authenticated = true
		}

		// look for the command
		handler, found := handlers[msg.Command]

		// if the command isn't found, return an error and wait for the next command
		if !found {
			lumber.Trace("Command '%s' not found", msg.Command)
			encoder.Encode(&mist.Message{Command: msg.Command, Tags: msg.Tags, Data: msg.Data, Error: "Unknown Command"})
			continue
		}

		// attempt to run the command; if the command fails return the error and wait
		// for the next command
		lumber.Trace("TCP Running '%s'...", msg.Command)
		if err := handler(proxy, msg); err != nil {
			lumber.Debug("TCP Failed to run '%s' - %s", msg.Command, err.Error())
			encoder.Encode(&mist.Message{Command: msg.Command, Error: err.Error()})
			continue
		}
	}
}
1046567
func (t *Template) ParseString(s string) error {
	return t.Parse(strings.NewReader(s))
}
1064357
func (s *APIServer) getTunnelConnections(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) {
	conns, err := auth.GetTunnelConnections(p.ByName("cluster"))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	items := make([]json.RawMessage, len(conns))
	for i, conn := range conns {
		data, err := services.MarshalTunnelConnection(conn, services.WithVersion(version), services.PreserveResourceID())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		items[i] = data
	}
	return items, nil
}
882357
func ParsedConnectionFromStr(connStr string) (*ParsedConn, error) {
	var namespace, suffix, hubName, keyName, secret string
	splits := strings.Split(connStr, ";")
	for _, split := range splits {
		keyAndValue := strings.Split(split, "=")
		if len(keyAndValue) < 2 {
			return nil, errors.New("failed parsing connection string due to unmatched key value separated by '='")
		}

		// if a key value pair has `=` in the value, recombine them
		key := keyAndValue[0]
		value := strings.Join(keyAndValue[1:], "=")
		switch {
		case strings.EqualFold(endpointKey, key):
			u, err := url.Parse(value)
			if err != nil {
				return nil, errors.New("failed parsing connection string due to an incorrectly formatted Endpoint value")
			}
			hostSplits := strings.Split(u.Host, ".")
			if len(hostSplits) < 2 {
				return nil, errors.New("failed parsing connection string due to Endpoint value not containing a URL with a namespace and a suffix")
			}
			namespace = hostSplits[0]
			suffix = strings.Join(hostSplits[1:], ".")
		case strings.EqualFold(sharedAccessKeyNameKey, key):
			keyName = value
		case strings.EqualFold(sharedAccessKeyKey, key):
			secret = value
		case strings.EqualFold(entityPathKey, key):
			hubName = value
		}
	}

	parsed := newParsedConnection(namespace, suffix, hubName, keyName, secret)
	if namespace == "" {
		return parsed, fmt.Errorf("key %q must not be empty", endpointKey)
	}

	if keyName == "" {
		return parsed, fmt.Errorf("key %q must not be empty", sharedAccessKeyNameKey)
	}

	if secret == "" {
		return parsed, fmt.Errorf("key %q must not be empty", sharedAccessKeyKey)
	}

	return parsed, nil
}
394108
func parseConnectionInfo(s *terraform.InstanceState) (*connectionInfo, error) {
	connInfo := &connectionInfo{}
	decConf := &mapstructure.DecoderConfig{
		WeaklyTypedInput: true,
		Result:           connInfo,
	}
	dec, err := mapstructure.NewDecoder(decConf)
	if err != nil {
		return nil, err
	}
	if err := dec.Decode(s.Ephemeral.ConnInfo); err != nil {
		return nil, err
	}

	// To default Agent to true, we need to check the raw string, since the
	// decoded boolean can't represent "absence of config".
	//
	// And if SSH_AUTH_SOCK is not set, there's no agent to connect to, so we
	// shouldn't try.
	if s.Ephemeral.ConnInfo["agent"] == "" && os.Getenv("SSH_AUTH_SOCK") != "" {
		connInfo.Agent = true
	}

	if connInfo.User == "" {
		connInfo.User = DefaultUser
	}

	// Format the host if needed.
	// Needed for IPv6 support.
	connInfo.Host = shared.IpFormat(connInfo.Host)

	if connInfo.Port == 0 {
		connInfo.Port = DefaultPort
	}
	if connInfo.ScriptPath == "" {
		connInfo.ScriptPath = DefaultScriptPath
	}
	if connInfo.Timeout != "" {
		connInfo.TimeoutVal = safeDuration(connInfo.Timeout, DefaultTimeout)
	} else {
		connInfo.TimeoutVal = DefaultTimeout
	}

	// Default all bastion config attrs to their non-bastion counterparts
	if connInfo.BastionHost != "" {
		// Format the bastion host if needed.
		// Needed for IPv6 support.
		connInfo.BastionHost = shared.IpFormat(connInfo.BastionHost)

		if connInfo.BastionUser == "" {
			connInfo.BastionUser = connInfo.User
		}
		if connInfo.BastionPassword == "" {
			connInfo.BastionPassword = connInfo.Password
		}
		if connInfo.BastionPrivateKey == "" {
			connInfo.BastionPrivateKey = connInfo.PrivateKey
		}
		if connInfo.BastionPort == 0 {
			connInfo.BastionPort = connInfo.Port
		}
	}

	return connInfo, nil
}
233407
func (conn *BytesConnectionStr) SendAsyncString(topic string, key string, value string, meta interface{}, successClb func(*client.ProducerMessage), errClb func(*client.ProducerError)) {
	conn.SendAsyncMessage(topic, sarama.StringEncoder(key), sarama.StringEncoder(value), meta, successClb, errClb)
}
1242263
func (obj *Doc) GetConnections(ctx context.Context) ([]*Connection, error) {
	result := &struct {
		Connections []*Connection	`json:"qConnections"`
	} {}
	err := obj.rpc(ctx, "GetConnections", result)
	return result.Connections, err 
}
762414
func (s *ClusterInfo) SetZookeeperConnectString(v string) *ClusterInfo {
	s.ZookeeperConnectString = &v
	return s
}
768478
func parseConnSpec(connStr string) connSpec {
	var out connSpec
	out.Options = map[string]string{}

	partMatcher := regexp.MustCompile(`((.*):\/\/)?(([^\/?:]*)(:([^\/?:@]*))?@)?([^\/?]*)(\/([^\?]*))?(\?(.*))?`)
	hostMatcher := regexp.MustCompile(`([^;\,\:]+)(:([0-9]*))?(;\,)?`)
	kvMatcher := regexp.MustCompile(`([^=]*)=([^&?]*)[&?]?`)
	parts := partMatcher.FindStringSubmatch(connStr)

	if parts[2] != "" {
		out.Scheme = parts[2]
	}

	if parts[7] != "" {
		hosts := hostMatcher.FindAllStringSubmatch(parts[7], -1)
		for _, hostInfo := range hosts {
			port := 0
			if hostInfo[3] != "" {
				port, _ = strconv.Atoi(hostInfo[3])
			}

			out.Hosts = append(out.Hosts, connSpecAddr{
				Host: hostInfo[1],
				Port: uint16(port),
			})
		}
	}

	if parts[9] != "" {
		out.Bucket = parts[9]
	}

	if parts[11] != "" {
		kvs := kvMatcher.FindAllStringSubmatch(parts[11], -1)
		for _, kvInfo := range kvs {
			out.Options[kvInfo[1]] = kvInfo[2]
		}
	}

	return out
}
429990
func parsePorts(ports []networkingv1.NetworkPolicyPort) []api.PortRule {
	portRules := []api.PortRule{}
	for _, port := range ports {
		if port.Protocol == nil && port.Port == nil {
			continue
		}

		protocol := api.ProtoTCP
		if port.Protocol != nil {
			protocol, _ = api.ParseL4Proto(string(*port.Protocol))
		}

		portStr := ""
		if port.Port != nil {
			portStr = port.Port.String()
		}

		portRule := api.PortRule{
			Ports: []api.PortProtocol{
				{Port: portStr, Protocol: protocol},
			},
		}

		portRules = append(portRules, portRule)
	}

	return portRules
}
259518
func (l *LoadBalancer) trackConnection(backend NetAddr, conn net.Conn) int64 {
	l.Lock()
	defer l.Unlock()
	l.connID += 1
	tracker, ok := l.connections[backend]
	if !ok {
		tracker = make(map[int64]net.Conn)
		l.connections[backend] = tracker
	}
	tracker[l.connID] = conn
	return l.connID
}
689171
func splitConnectionStringURL(dsn string) (map[string]string, error) {
	res := map[string]string{}

	u, err := url.Parse(dsn)
	if err != nil {
		return res, err
	}

	if u.Scheme != "sqlserver" {
		return res, fmt.Errorf("scheme %s is not recognized", u.Scheme)
	}

	if u.User != nil {
		res["user id"] = u.User.Username()
		p, exists := u.User.Password()
		if exists {
			res["password"] = p
		}
	}

	host, port, err := net.SplitHostPort(u.Host)
	if err != nil {
		host = u.Host
	}

	if len(u.Path) > 0 {
		res["server"] = host + "\\" + u.Path[1:]
	} else {
		res["server"] = host
	}

	if len(port) > 0 {
		res["port"] = port
	}

	query := u.Query()
	for k, v := range query {
		if len(v) > 1 {
			return res, fmt.Errorf("key %s provided more than once", k)
		}
		res[strings.ToLower(k)] = v[0]
	}

	return res, nil
}
820167
func ParseString(s string, options ...Option) (*Token, error) {
	return Parse(strings.NewReader(s), options...)
}
343183
func (o *OIDCConnector) Parse() (services.OIDCConnector, error) {
	if o.Display == "" {
		o.Display = o.ID
	}

	var mappings []services.ClaimMapping
	for _, c := range o.ClaimsToRoles {
		var roles []string
		if len(c.Roles) > 0 {
			roles = append(roles, c.Roles...)
		}

		mappings = append(mappings, services.ClaimMapping{
			Claim:        c.Claim,
			Value:        c.Value,
			Roles:        roles,
			RoleTemplate: c.RoleTemplate,
		})
	}

	other := &services.OIDCConnectorV1{
		ID:            o.ID,
		Display:       o.Display,
		IssuerURL:     o.IssuerURL,
		ClientID:      o.ClientID,
		ClientSecret:  o.ClientSecret,
		RedirectURL:   o.RedirectURL,
		Scope:         o.Scope,
		ClaimsToRoles: mappings,
	}
	v2 := other.V2()
	v2.SetACR(o.ACR)
	v2.SetProvider(o.Provider)
	if err := v2.Check(); err != nil {
		return nil, trace.Wrap(err)
	}
	return v2, nil
}
473434
func (c *Client) ListConnections() (rec []ConnectionInfo, err error) {
	req, err := newGETRequest(c, "connections")
	if err != nil {
		return []ConnectionInfo{}, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return []ConnectionInfo{}, err
	}

	return rec, nil
}
1148136
func ParseString(b []byte) (string, error) {
	var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
	if bU, err := Unescape(b, stackbuf[:]); err != nil {
		return "", MalformedValueError
	} else {
		return string(bU), nil
	}
}