// sendAndReceiveV0SASLPlainAuth flows the v0 sasl auth NOT wrapped in the kafka protocol
966197
func (b *Broker) sendAndReceiveV0SASLPlainAuth() error {

	length := 1 + len(b.conf.Net.SASL.User) + 1 + len(b.conf.Net.SASL.Password)
	authBytes := make([]byte, length+4) //4 byte length header + auth data
	binary.BigEndian.PutUint32(authBytes, uint32(length))
	copy(authBytes[4:], []byte("\x00"+b.conf.Net.SASL.User+"\x00"+b.conf.Net.SASL.Password))

	err := b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout))
	if err != nil {
		Logger.Printf("Failed to set write deadline when doing SASL auth with broker %s: %s\n", b.addr, err.Error())
		return err
	}

	requestTime := time.Now()
	bytesWritten, err := b.conn.Write(authBytes)
	b.updateOutgoingCommunicationMetrics(bytesWritten)
	if err != nil {
		Logger.Printf("Failed to write SASL auth header to broker %s: %s\n", b.addr, err.Error())
		return err
	}

	header := make([]byte, 4)
	n, err := io.ReadFull(b.conn, header)
	b.updateIncomingCommunicationMetrics(n, time.Since(requestTime))
	// If the credentials are valid, we would get a 4 byte response filled with null characters.
	// Otherwise, the broker closes the connection and we get an EOF
	if err != nil {
		Logger.Printf("Failed to read response while authenticating with SASL to broker %s: %s\n", b.addr, err.Error())
		return err
	}

	Logger.Printf("SASL authentication successful with broker %s:%v - %v\n", b.addr, n, header)
	return nil
}
302048
func (ns *NatsRPCClient) SendPush(userID string, frontendSv *Server, push *protos.Push) error {
	topic := GetUserMessagesTopic(userID, frontendSv.Type)
	msg, err := proto.Marshal(push)
	if err != nil {
		return err
	}
	return ns.Send(topic, msg)
}
1333650
func (t *HTTPTransporter) SendSnapshotRecoveryRequest(server Server, peer *Peer, req *SnapshotRecoveryRequest) *SnapshotRecoveryResponse {
	var b bytes.Buffer
	if _, err := req.Encode(&b); err != nil {
		traceln("transporter.rv.encoding.error:", err)
		return nil
	}

	url := joinPath(peer.ConnectionString, t.snapshotRecoveryPath)
	traceln(server.Name(), "POST", url)

	httpResp, err := t.httpClient.Post(url, "application/protobuf", &b)
	if httpResp == nil || err != nil {
		traceln("transporter.rv.response.error:", err)
		return nil
	}
	defer httpResp.Body.Close()

	resp := &SnapshotRecoveryResponse{}
	if _, err = resp.Decode(httpResp.Body); err != nil && err != io.EOF {
		traceln("transporter.rv.decoding.error:", err)
		return nil
	}

	return resp
}
589395
func sendSocks4aResponseRejected(w io.Writer) error {
	emptyAddr := net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 0}
	return sendSocks4aResponse(w, socks4RequestRejected, &emptyAddr)
}
513696
func (s *Server) sendSubsToRoute(route *client) {
	s.mu.Lock()
	// Estimated size of all protocols. It does not have to be accurate at all.
	eSize := 0
	// Send over our account subscriptions.
	// copy accounts into array first
	accs := make([]*Account, 0, 32)
	s.accounts.Range(func(k, v interface{}) bool {
		a := v.(*Account)
		accs = append(accs, a)
		a.mu.RLock()
		// Proto looks like: "RS+ <account name> <subject>[ <queue weight>]\r\n"
		// If we wanted to have better estimates (or even accurate), we would
		// collect the subs here instead of capturing the accounts and then
		// later going over each account.
		eSize += len(a.rm) * (4 + len(a.Name) + 256)
		a.mu.RUnlock()
		return true
	})
	s.mu.Unlock()

	sendSubs := func(accs []*Account) {
		var raw [32]*subscription
		var closed bool

		route.mu.Lock()
		for _, a := range accs {
			subs := raw[:0]

			a.mu.RLock()
			c := a.randomClient()
			if c == nil {
				a.mu.RUnlock()
				continue
			}
			for key, n := range a.rm {
				// FIXME(dlc) - Just pass rme around.
				// Construct a sub on the fly. We need to place
				// a client (or im) to properly set the account.
				var subj, qn []byte
				s := strings.Split(key, " ")
				subj = []byte(s[0])
				if len(s) > 1 {
					qn = []byte(s[1])
				}
				// TODO(dlc) - This code needs to change, but even if left alone could be more
				// efficient with these tmp subs.
				sub := &subscription{client: c, subject: subj, queue: qn, qw: n}
				subs = append(subs, sub)

			}
			a.mu.RUnlock()

			closed = route.sendRouteSubProtos(subs, false, func(sub *subscription) bool {
				return route.canImport(string(sub.subject))
			})

			if closed {
				route.mu.Unlock()
				return
			}
		}
		route.mu.Unlock()
		if !closed {
			route.Debugf("Sent local subscriptions to route")
		}
	}
	// Decide if we call above function in go routine or in place.
	if eSize > sendRouteSubsInGoRoutineThreshold {
		s.startGoRoutine(func() {
			sendSubs(accs)
			s.grWG.Done()
		})
	} else {
		sendSubs(accs)
	}
}
146827
func BroadcastReceive(broadcast Broadcast, addr string, responses chan common.Status, errs chan error) {
	logger.Infof("calling OrdererClient.broadcastReceive")
	for {
		broadcastResponse, err := broadcast.Recv()
		if err == io.EOF {
			close(responses)
			return
		}

		if err != nil {
			rpcStatus, _ := status.FromError(err)
			errs <- errors.Wrapf(err, "broadcast recv error from orderer %s, rpcStatus=%+v", addr, rpcStatus)
			close(responses)
			return
		}

		if broadcastResponse.Status == common.Status_SUCCESS {
			responses <- broadcastResponse.Status
		} else {
			errs <- errors.Errorf("broadcast response error %d from orderer %s", int32(broadcastResponse.Status), addr)
		}
	}
}
128412
func (conn *BytesConnectionStr) SendAsyncByte(topic string, key []byte, value []byte, meta interface{}, successClb func(*client.ProducerMessage), errClb func(*client.ProducerError)) {
	conn.SendAsyncMessage(topic, sarama.ByteEncoder(key), sarama.ByteEncoder(value), meta, successClb, errClb)
}
872022
func (api *Client) SendAuthRevokeContext(ctx context.Context, token string) (*AuthRevokeResponse, error) {
	if token == "" {
		token = api.token
	}
	values := url.Values{
		"token": {token},
	}

	return api.authRequest(ctx, "auth.revoke", values)
}
578628
func (m *Memberlist) sendAndReceiveState(addr string, join bool) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	conn, err := m.transport.DialTimeout(addr, m.config.TCPTimeout)
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
	metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)

	// Send our state
	if err := m.sendLocalState(conn, join); err != nil {
		return nil, nil, err
	}

	conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
	msgType, bufConn, dec, err := m.readStream(conn)
	if err != nil {
		return nil, nil, err
	}

	if msgType == errMsg {
		var resp errResp
		if err := dec.Decode(&resp); err != nil {
			return nil, nil, err
		}
		return nil, nil, fmt.Errorf("remote error: %v", resp.Error)
	}

	// Quit if not push/pull
	if msgType != pushPullMsg {
		err := fmt.Errorf("received invalid msgType (%d), expected pushPullMsg (%d) %s", msgType, pushPullMsg, LogConn(conn))
		return nil, nil, err
	}

	// Read remote state
	_, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
	return remoteNodes, userState, err
}
276435
func (c *Client) SendWithBasicAuth(req *http.Request, v interface{}) error {
	req.SetBasicAuth(c.ClientID, c.Secret)

	return c.Send(req, v)
}
1225438
func WrapAudienceAgnosticRequest(implicit Audiences, delegate Request) Request {
	return &audAgnosticRequestAuthenticator{
		implicit: implicit,
		delegate: delegate,
	}
}
319444
func (c *client) sendRouteSubOrUnSubProtos(subs []*subscription, isSubProto, trace bool, filter func(sub *subscription) bool) bool {
	var (
		_buf   [1024]byte          // array on stack
		buf    = _buf[:0]          // our buffer will initially point to the stack buffer
		mbs    = maxBufSize * 2    // max size of the buffer
		mpMax  = int(c.out.mp / 2) // 50% of max_pending
		closed bool
	)
	// We need to make sure that we stay below the user defined max pending bytes.
	if mbs > mpMax {
		mbs = mpMax
	}
	for _, sub := range subs {
		if filter != nil && !filter(sub) {
			continue
		}
		// Determine the account. If sub has an ImportMap entry, use that, otherwise scoped to
		// client. Default to global if all else fails.
		var accName string
		if sub.client != nil && sub.client != c {
			sub.client.mu.Lock()
		}
		if sub.im != nil {
			accName = sub.im.acc.Name
		} else if sub.client != nil && sub.client.acc != nil {
			accName = sub.client.acc.Name
		} else {
			c.Debugf("Falling back to default account for sending subs")
			accName = globalAccountName
		}
		if sub.client != nil && sub.client != c {
			sub.client.mu.Unlock()
		}

		// Check if proto is going to fit.
		curSize := len(buf)
		// "RS+/- " + account + " " + subject + " " [+ queue + " " + weight] + CRLF
		curSize += 4 + len(accName) + 1 + len(sub.subject) + 1 + 2
		if len(sub.queue) > 0 {
			curSize += len(sub.queue)
			if isSubProto {
				// Estimate weightlen in 1000s
				curSize += 1 + 4
			}
		}
		if curSize >= mbs {
			if c.queueOutbound(buf) {
				// Need to allocate new array
				buf = make([]byte, 0, mbs)
			} else {
				// We can reuse previous buffer
				buf = buf[:0]
			}
			// Update last activity because flushOutbound() will release
			// the lock, which could cause pingTimer to think that this
			// connection is stale otherwise.
			c.last = time.Now()
			c.flushOutbound()
			if closed = c.flags.isSet(clearConnection); closed {
				break
			}
		}
		as := len(buf)
		if isSubProto {
			buf = append(buf, rSubBytes...)
		} else {
			buf = append(buf, rUnsubBytes...)
		}
		buf = append(buf, accName...)
		buf = append(buf, ' ')
		buf = append(buf, sub.subject...)
		if len(sub.queue) > 0 {
			buf = append(buf, ' ')
			buf = append(buf, sub.queue...)
			// Send our weight if we are a sub proto
			if isSubProto {
				buf = append(buf, ' ')
				var b [12]byte
				var i = len(b)
				for l := sub.qw; l > 0; l /= 10 {
					i--
					b[i] = digits[l%10]
				}
				buf = append(buf, b[i:]...)
			}
		}
		if trace {
			c.traceOutOp("", buf[as:])
		}
		buf = append(buf, CR_LF...)
	}
	if !closed && len(buf) > 0 {
		c.queueOutbound(buf)
		c.flushOutbound()
		closed = c.flags.isSet(clearConnection)
	}
	return closed
}
689443
func (s *Session) sendNoWait(hdr header) error {
	t := timerPool.Get()
	timer := t.(*time.Timer)
	timer.Reset(s.config.ConnectionWriteTimeout)
	defer func() {
		timer.Stop()
		select {
		case <-timer.C:
		default:
		}
		timerPool.Put(t)
	}()

	select {
	case s.sendCh <- sendReady{Hdr: hdr}:
		return nil
	case <-s.shutdownCh:
		return ErrSessionShutdown
	case <-timer.C:
		return ErrConnectionWriteTimeout
	}
}
253497
func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
	if msg == nil {
		return false, errors.New("nil message passed in")
	}

	var ignore bool

	if vppReply := ch.delayedReply; vppReply != nil {
		// try the delayed reply
		ch.delayedReply = nil
		ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
		if !ignore {
			return lastReplyReceived, err
		}
	}

	timer := time.NewTimer(ch.replyTimeout)
	for {
		select {
		// blocks until a reply comes to ReplyChan or until timeout expires
		case vppReply := <-ch.replyChan:
			ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
			if ignore {
				logrus.Warnf("ignoring reply: %+v", vppReply)
				continue
			}
			return lastReplyReceived, err

		case <-timer.C:
			err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
			return false, err
		}
	}
	return
}
232697
func (q *queue) InFlightReceipts() bool {
	q.lock.Lock()
	defer q.lock.Unlock()

	return len(q.receiptPendPool) > 0
}
915645
func (m *MockSentPacketHandler) SentPacketsAsRetransmission(arg0 []*ackhandler.Packet, arg1 protocol.PacketNumber) {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "SentPacketsAsRetransmission", arg0, arg1)
}
1285628
func (s *sender) sendDatagramAnticipate() (*net.UDPAddr, error) {
	err1 := s.conn.setDeadline(s.timeout)
	if err1 != nil {
		return nil, err1
	}
	var err error = nil
	ksz := uint(len(s.sendA.sends))
	knum := s.sendA.num
	if knum > ksz {
		err = fmt.Errorf("knum %v bigger than ksz %v", knum, ksz)
		return nil, err
	}

	for k := uint(0); k < knum; k++ {
		lx := s.sendA.sendslens[k]
		if lx < 4 {
			err = fmt.Errorf("lx smaller than 4")
			break
		}
		errx := s.conn.sendTo(s.sendA.sends[k][:lx], s.addr)
		if errx != nil {
			err = fmt.Errorf("k %v errx %v", k, errx.Error())
			break
		}
	}
	if err != nil {
		return nil, err
	}
	k := uint(0)
	for {
		n, addr, err := s.conn.readFrom(s.receive)
		if err != nil {
			return nil, err
		}
		if !addr.IP.Equal(s.addr.IP) || (s.tid != 0 && addr.Port != s.tid) {
			continue
		}
		p, err := parsePacket(s.receive[:n])
		if err != nil {
			continue
		}
		s.tid = addr.Port
		switch p := p.(type) {
		case pACK:
			if anticipateDebug {
				fmt.Printf(" **** pACK p.block %v  s.block %v k %v\n",
					p.block(), s.block, k)
			}
			if p.block() == s.block+uint16(k) {
				k++
				if k == knum {
					return addr, nil
				}
			}
		case pOACK:
			opts, err := unpackOACK(p)
			if s.block != 0 {
				continue
			}
			if err != nil {
				s.abort(err)
				return addr, err
			}
			for name, value := range opts {
				if name == "blksize" {
					err := s.setBlockSize(value)
					if err != nil {
						continue
					}
				}
			}
			return addr, nil
		case pERROR:
			return nil, fmt.Errorf("sending block %d: code=%d, error: %s",
				s.block, p.code(), p.message())
		}
	}
}