// handleConnection implements SOCKS protocol.
518815
func (s *Server) handleConnection(ctx context.Context, conn net.Conn) {
	conn.SetDeadline(time.Now().Add(negotiationTimeout))

	var preamble [2]byte
	_, err := io.ReadFull(conn, preamble[:])
	if err != nil {
		fields := well.FieldsFromContext(ctx)
		fields["client_addr"] = conn.RemoteAddr().String()
		fields[log.FnError] = err.Error()
		s.Logger.Error("failed to read preamble", fields)
		return
	}

	connVer := version(preamble[0])
	var destConn net.Conn
	switch connVer {
	case SOCKS4:
		destConn = s.handleSOCKS4(ctx, conn, preamble[1])
		if destConn == nil {
			return
		}
	case SOCKS5:
		destConn = s.handleSOCKS5(ctx, conn, preamble[1])
		if destConn == nil {
			return
		}
	default:
		fields := well.FieldsFromContext(ctx)
		fields["client_addr"] = conn.RemoteAddr().String()
		s.Logger.Error("unknown SOCKS version", fields)
		return
	}
	defer destConn.Close()
	netutil.SetKeepAlive(destConn)

	// negotiation completed.
	var zeroTime time.Time
	conn.SetDeadline(zeroTime)

	// do proxy
	st := time.Now()
	env := well.NewEnvironment(ctx)
	env.Go(func(ctx context.Context) error {
		buf := s.pool.Get().([]byte)
		_, err := io.CopyBuffer(destConn, conn, buf)
		s.pool.Put(buf)
		if hc, ok := destConn.(netutil.HalfCloser); ok {
			hc.CloseWrite()
		}
		if hc, ok := conn.(netutil.HalfCloser); ok {
			hc.CloseRead()
		}
		return err
	})
	env.Go(func(ctx context.Context) error {
		buf := s.pool.Get().([]byte)
		_, err := io.CopyBuffer(conn, destConn, buf)
		s.pool.Put(buf)
		if hc, ok := conn.(netutil.HalfCloser); ok {
			hc.CloseWrite()
		}
		if hc, ok := destConn.(netutil.HalfCloser); ok {
			hc.CloseRead()
		}
		return err
	})
	env.Stop()
	err = env.Wait()

	fields := well.FieldsFromContext(ctx)
	fields["elapsed"] = time.Since(st).Seconds()
	if err != nil {
		fields[log.FnError] = err.Error()
		s.Logger.Error("proxy ends with an error", fields)
		return
	}
	s.Logger.Info("proxy ends", fields)
}
800120
func (ed *Dispatcher) HandleRegisterConnectionEvent(e esdispatcher.Event) {
	evt := e.(*RegisterConnectionEvent)

	if ed.connectionRegistration != nil {
		evt.ErrCh <- errors.New("registration already exists for connection event")
		return
	}

	ed.connectionRegistration = evt.Reg
	evt.RegCh <- evt.Reg
}
606994
func (c *Collector) handleConnection(conn net.Conn) {
	defer conn.Close()
	reader := &countingReader{conn, 0}
	avroReader, err := goavro.NewReader(goavro.FromReader(reader))
	if err != nil {
		fwColLog.Errorf("Failed to create avro reader: %s", err)
		return // close connection
	}
	defer func() {
		if err := avroReader.Close(); err != nil {
			fwColLog.Errorf("Failed to close avro reader: %s", err)
		}
	}()

	nextInputResetTime := time.Now().Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
	var lastBytesCount int64
	var recordCount int64
	for {
		lastBytesCount = reader.inputBytes
		// Wait for records to be available:
		if !avroReader.Scan() {
			// Stream closed, exit
			break
		}
		datum, err := avroReader.Read()
		if err != nil {
			fwColLog.Errorf("Cannot read avro record from %+v: %s\n", conn.RemoteAddr(), err)
			continue
		}

		// TODO(roger): !ok
		topic, _ := getTopic(datum)

		// increment counters before reader.inputBytes is modified too much
		// NOTE: inputBytes is effectively being modified by a gofunc in avroReader, so it's not a perfect measurement
		recordCount++
		approxBytesRead := reader.inputBytes - lastBytesCount

		// reset throttle counter if needed, before enforcing it below
		// ideally we'd use a ticker for this, but the goavro api already requires we use manual polling
		now := time.Now()
		if now.After(nextInputResetTime) {
			// Limit period has transpired, reset limit count before continuing
			// TODO(MALNICK) Don't case like this...
			if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
				fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds. "+
					"Of this, ~%d KB was dropped due to throttling.\n",
					recordCount,
					reader.inputBytes/1024,
					conn.RemoteAddr(),
					c.InputLimitPeriodFlag,
					// TODO (MALNICK) don't cast like this..
					reader.inputBytes/1024-int64(c.InputLimitAmountKBytesFlag))
			} else {
				fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds\n",
					recordCount, reader.inputBytes/1024, conn.RemoteAddr(), c.InputLimitPeriodFlag)
			}
			recordCount = 0
			reader.inputBytes = 0
			nextInputResetTime = now.Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
		}

		// TODO (MALNICK) Don't cast like this
		if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
			// input limit reached, skip
			continue
		}

		ad := &AvroDatum{datum, topic, approxBytesRead}
		pmm, err := ad.transform(c.nodeInfo, c.containerTaskRels)
		if err != nil {
			fwColLog.Error(err)
		}
		c.metricsChan <- pmm
	}
}
448727
func (s *SocketHub) AddConnection(ws *SocketWorker) {
	var ok bool

	s.so.RLock()
	ok = s.sockets[ws]
	s.so.RUnlock()

	if ok {
		return
	}

	s.so.Lock()
	s.sockets[ws] = true
	s.so.Unlock()

	go s.manageSocket(ws)
}
498375
func wrapConnection(conn net.Conn) net.Conn {
	return &connectionWrapper{
		Conn:       conn,
		clientAddr: conn.RemoteAddr(),
	}
}
391159
func ReconnectHandler(cb ConnHandler) Option {
	return func(o *Options) error {
		o.ReconnectedCB = cb
		return nil
	}
}
939948
func (eh relationshipAddEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*RelationshipAdd); ok {
		eh(s, t)
	}
}
933543
func newConnection(s *websocket.Conn, r *Router) *Connection {
	return &Connection{
		socket:    s,
		router:    r,
		send:      make(chan *message, sendChannelSize),
		extension: nil,
	}
}
492630
func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Time) {
	if l.connReadTimeout != 0 || l.connWriteTimeout != 0 {
		conn = netutil.NewConnWithTimeouts(conn, l.connReadTimeout, l.connWriteTimeout)
	}
	c := newServerConn(conn, l)
	c.ConnectionID = connectionID

	// Catch panics, and close the connection in any case.
	defer func() {
		if x := recover(); x != nil {
			log.Errorf("mysql_server caught panic:\n%v\n%s", x, tb.Stack(4))
		}
		// We call flush here in case there's a premature return after
		// startWriterBuffering is called
		c.flush()

		conn.Close()
	}()

	// Tell the handler about the connection coming and going.
	l.handler.NewConnection(c)
	defer l.handler.ConnectionClosed(c)

	// Adjust the count of open connections
	defer connCount.Add(-1)

	// First build and send the server handshake packet.
	salt, err := c.writeHandshakeV10(l.ServerVersion, l.authServer, l.TLSConfig != nil)
	if err != nil {
		if err != io.EOF {
			log.Errorf("Cannot send HandshakeV10 packet to %s: %v", c, err)
		}
		return
	}

	// Wait for the client response. This has to be a direct read,
	// so we don't buffer the TLS negotiation packets.
	response, err := c.readEphemeralPacketDirect()
	if err != nil {
		// Don't log EOF errors. They cause too much spam, same as main read loop.
		if err != io.EOF {
			log.Errorf("Cannot read client handshake response from %s: %v", c, err)
		}
		return
	}
	user, authMethod, authResponse, err := l.parseClientHandshakePacket(c, true, response)
	if err != nil {
		log.Errorf("Cannot parse client handshake response from %s: %v", c, err)
		return
	}

	c.recycleReadPacket()

	if c.Capabilities&CapabilityClientSSL > 0 {
		// SSL was enabled. We need to re-read the auth packet.
		response, err = c.readEphemeralPacket()
		if err != nil {
			log.Errorf("Cannot read post-SSL client handshake response from %s: %v", c, err)
			return
		}

		// Returns copies of the data, so we can recycle the buffer.
		user, authMethod, authResponse, err = l.parseClientHandshakePacket(c, false, response)
		if err != nil {
			log.Errorf("Cannot parse post-SSL client handshake response from %s: %v", c, err)
			return
		}
		c.recycleReadPacket()

		if con, ok := c.conn.(*tls.Conn); ok {
			connState := con.ConnectionState()
			tlsVerStr := tlsVersionToString(connState.Version)
			if tlsVerStr != "" {
				connCountByTLSVer.Add(tlsVerStr, 1)
				defer connCountByTLSVer.Add(tlsVerStr, -1)
			}
		}
	} else {
		if l.RequireSecureTransport {
			c.writeErrorPacketFromError(vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "server does not allow insecure connections, client must use SSL/TLS"))
		}
		connCountByTLSVer.Add(versionNoTLS, 1)
		defer connCountByTLSVer.Add(versionNoTLS, -1)
	}

	// See what auth method the AuthServer wants to use for that user.
	authServerMethod, err := l.authServer.AuthMethod(user)
	if err != nil {
		c.writeErrorPacketFromError(err)
		return
	}

	// Compare with what the client sent back.
	switch {
	case authServerMethod == MysqlNativePassword && authMethod == MysqlNativePassword:
		// Both server and client want to use MysqlNativePassword:
		// the negotiation can be completed right away, using the
		// ValidateHash() method.
		userData, err := l.authServer.ValidateHash(salt, user, authResponse, conn.RemoteAddr())
		if err != nil {
			log.Warningf("Error authenticating user using MySQL native password: %v", err)
			c.writeErrorPacketFromError(err)
			return
		}
		c.User = user
		c.UserData = userData

	case authServerMethod == MysqlNativePassword:
		// The server really wants to use MysqlNativePassword,
		// but the client returned a result for something else.

		salt, err := l.authServer.Salt()
		if err != nil {
			return
		}
		//lint:ignore SA4006 This line is required because the binary protocol requires padding with 0
		data := make([]byte, 21)
		data = append(salt, byte(0x00))
		if err := c.writeAuthSwitchRequest(MysqlNativePassword, data); err != nil {
			log.Errorf("Error writing auth switch packet for %s: %v", c, err)
			return
		}

		response, err := c.readEphemeralPacket()
		if err != nil {
			log.Errorf("Error reading auth switch response for %s: %v", c, err)
			return
		}
		c.recycleReadPacket()

		userData, err := l.authServer.ValidateHash(salt, user, response, conn.RemoteAddr())
		if err != nil {
			log.Warningf("Error authenticating user using MySQL native password: %v", err)
			c.writeErrorPacketFromError(err)
			return
		}
		c.User = user
		c.UserData = userData

	default:
		// The server wants to use something else, re-negotiate.

		// The negotiation happens in clear text. Let's check we can.
		if !l.AllowClearTextWithoutTLS && c.Capabilities&CapabilityClientSSL == 0 {
			c.writeErrorPacket(CRServerHandshakeErr, SSUnknownSQLState, "Cannot use clear text authentication over non-SSL connections.")
			return
		}

		// Switch our auth method to what the server wants.
		// Dialog plugin expects an AskPassword prompt.
		var data []byte
		if authServerMethod == MysqlDialog {
			data = authServerDialogSwitchData()
		}
		if err := c.writeAuthSwitchRequest(authServerMethod, data); err != nil {
			log.Errorf("Error writing auth switch packet for %s: %v", c, err)
			return
		}

		// Then hand over the rest of the negotiation to the
		// auth server.
		userData, err := l.authServer.Negotiate(c, user, conn.RemoteAddr())
		if err != nil {
			c.writeErrorPacketFromError(err)
			return
		}
		c.User = user
		c.UserData = userData
	}

	if c.User != "" {
		connCountPerUser.Add(c.User, 1)
		defer connCountPerUser.Add(c.User, -1)
	}

	// Negotiation worked, send OK packet.
	if err := c.writeOKPacket(0, 0, c.StatusFlags, 0); err != nil {
		log.Errorf("Cannot write OK packet to %s: %v", c, err)
		return
	}

	// Record how long we took to establish the connection
	timings.Record(connectTimingKey, acceptTime)

	// Log a warning if it took too long to connect
	connectTime := time.Since(acceptTime)
	if l.SlowConnectWarnThreshold != 0 && connectTime > l.SlowConnectWarnThreshold {
		connSlow.Add(1)
		log.Warningf("Slow connection from %s: %v", c, connectTime)
	}

	for {
		err := c.handleNextCommand(l.handler)
		if err != nil {
			return
		}
	}
}
215861
func (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) {
	connectionHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderConnection))
	upgradeHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderUpgrade))
	if (resp.StatusCode != http.StatusSwitchingProtocols) || !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
		defer resp.Body.Close()
		responseError := ""
		responseErrorBytes, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			responseError = "unable to read error from server response"
		} else {
			// TODO: I don't belong here, I should be abstracted from this class
			if obj, _, err := statusCodecs.UniversalDecoder().Decode(responseErrorBytes, nil, &metav1.Status{}); err == nil {
				if status, ok := obj.(*metav1.Status); ok {
					return nil, &apierrors.StatusError{ErrStatus: *status}
				}
			}
			responseError = string(responseErrorBytes)
			responseError = strings.TrimSpace(responseError)
		}

		return nil, fmt.Errorf("unable to upgrade connection: %s", responseError)
	}

	return NewClientConnection(s.conn)
}
1337910
func (l Listener) OnConnect(e *gumble.ConnectEvent) {
	if l.Connect != nil {
		l.Connect(e)
	}
}
345619
func handleGetConnectionCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	return s.cfg.ConnMgr.ConnectedCount(), nil
}
864038
func (c *Connection) connectHandler(h Headers) (e error) {
	//fmt.Printf("CHDB01\n")
	c.rdr = bufio.NewReader(c.netconn)
	b, e := c.rdr.ReadBytes(0)
	if e != nil {
		return e
	}
	//fmt.Printf("CHDB02\n")
	f, e := connectResponse(string(b))
	if e != nil {
		return e
	}
	//fmt.Printf("CHDB03\n")
	//
	c.ConnectResponse = &Message{f.Command, f.Headers, f.Body}
	if c.ConnectResponse.Command == ERROR {
		return &CONNERROR{ECONERR, string(f.Body)}
	}
	//fmt.Printf("CHDB04\n")
	//
	e = c.setProtocolLevel(h, c.ConnectResponse.Headers)
	if e != nil {
		return e
	}
	//fmt.Printf("CHDB05\n")
	//
	if s, ok := c.ConnectResponse.Headers.Contains(HK_SESSION); ok {
		c.sessLock.Lock()
		c.session = s
		c.sessLock.Unlock()
	}

	if c.Protocol() >= SPL_11 {
		e = c.initializeHeartBeats(h)
		if e != nil {
			return e
		}
	}
	//fmt.Printf("CHDB06\n")

	c.connected = true
	c.mets.tfr += 1
	c.mets.tbr += c.ConnectResponse.Size(false)
	return nil
}
411996
func DisconnectHandler(cb ConnHandler) Option {
	return func(o *Options) error {
		o.DisconnectedCB = cb
		return nil
	}
}
1150876
func (s *Service) handleQuery(connID uint64, w http.ResponseWriter, r *http.Request) {
	isAtomic, err := isAtomic(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	timings, err := timings(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	lvl, err := level(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Get the query statement(s), and do tx if necessary.
	queries, err := requestQueries(r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// Get the right queryer object.
	var queryer Queryer
	if connID == defaultConnID {
		queryer = s.store
	} else {
		c, ok := s.store.Connection(connID)
		if !ok {
			http.Error(w, "connection not found", http.StatusNotFound)
			return
		}
		queryer = c
	}

	var resp Response
	results, err := queryer.Query(&store.QueryRequest{queries, timings, isAtomic, lvl})
	if err != nil {
		if err == store.ErrNotLeader {
			leader := s.leaderAPIAddr()
			if leader == "" {
				http.Error(w, err.Error(), http.StatusServiceUnavailable)
				return
			}

			redirect := s.FormRedirect(r, leader)
			http.Redirect(w, r, redirect, http.StatusMovedPermanently)
			return
		}
		resp.Error = err.Error()
	} else {
		resp.Results = results.Rows
		if timings {
			resp.Time = results.Time
		}
		resp.Raft = results.Raft
	}
	writeResponse(w, r, &resp)
}
856813
func (s *Service) handleJoin(w http.ResponseWriter, r *http.Request) {
	b, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	md := map[string]interface{}{}
	if err := json.Unmarshal(b, &md); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	remoteID, ok := md["id"]
	if !ok {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	remoteAddr, ok := md["addr"]
	if !ok {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	var m map[string]string
	if _, ok := md["meta"].(map[string]interface{}); ok {
		m = make(map[string]string)
		for k, v := range md["meta"].(map[string]interface{}) {
			m[k] = v.(string)
		}
	}

	if err := s.store.Join(remoteID.(string), remoteAddr.(string), m); err != nil {
		if err == store.ErrNotLeader {
			leader := s.leaderAPIAddr()
			if leader == "" {
				http.Error(w, err.Error(), http.StatusServiceUnavailable)
				return
			}

			redirect := s.FormRedirect(r, leader)
			http.Redirect(w, r, redirect, http.StatusMovedPermanently)
			return
		}

		b := bytes.NewBufferString(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		w.Write(b.Bytes())
		return
	}
}
81158
func (p *Provider) handleConnection(conn net.Conn) {
	// Create an RPC server to handle inbound
	pe := &providerEndpoint{p: p}
	rpcServer := rpc.NewServer()
	rpcServer.RegisterName("Client", pe)
	rpcCodec := msgpackrpc.NewCodec(false, false, conn)

	defer func() {
		if !pe.hijacked() {
			conn.Close()
		}
	}()

	for !p.IsShutdown() {
		if err := rpcServer.ServeRequest(rpcCodec); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") {
				p.logger.Printf("[ERR] scada-client: RPC error: %v", err)
			}
			return
		}

		// Handle potential hijack in Client.Connect
		if pe.hijacked() {
			cb := pe.getHijack()
			cb(conn)
			return
		}
	}
}