// processUntilDone processes the handshake until the handshaker service returns
// the results. Handshaker service takes care of frame parsing, so we read
// whatever received from the network and send it to the handshaker service.
161044
func (h *altsHandshaker) processUntilDone(resp *altspb.HandshakerResp, extra []byte) (*altspb.HandshakerResult, []byte, error) {
	for {
		if len(resp.OutFrames) > 0 {
			if _, err := h.conn.Write(resp.OutFrames); err != nil {
				return nil, nil, err
			}
		}
		if resp.Result != nil {
			return resp.Result, extra, nil
		}
		buf := make([]byte, frameLimit)
		n, err := h.conn.Read(buf)
		if err != nil && err != io.EOF {
			return nil, nil, err
		}
		// If there is nothing to send to the handshaker service, and
		// nothing is received from the peer, then we are stuck.
		// This covers the case when the peer is not responding. Note
		// that handshaker service connection issues are caught in
		// accessHandshakerService before we even get here.
		if len(resp.OutFrames) == 0 && n == 0 {
			return nil, nil, core.PeerNotRespondingError
		}
		// Append extra bytes from the previous interaction with the
		// handshaker service with the current buffer read from conn.
		p := append(extra, buf[:n]...)
		resp, err = h.accessHandshakerService(&altspb.HandshakerReq{
			ReqOneof: &altspb.HandshakerReq_Next{
				Next: &altspb.NextHandshakeMessageReq{
					InBytes: p,
				},
			},
		})
		if err != nil {
			return nil, nil, err
		}
		// Set extra based on handshaker service response.
		if n == 0 {
			extra = nil
		} else {
			extra = buf[resp.GetBytesConsumed():n]
		}
	}
}
355415
func (sc *serverCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	conn := tls.Server(rawConn, sc.serverConfig)
	if err := conn.Handshake(); err != nil {
		if sc.logger != nil {
			sc.logger.With("remote address",
				conn.RemoteAddr().String()).Errorf("TLS handshake failed with error %s", err)
		}
		return nil, nil, err
	}
	return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
}
1031093
func (cm *ClientManager) processed(node *ClientNode, maxCost, realCost uint64, now mclock.AbsTime) {
	cm.lock.Lock()
	defer cm.lock.Unlock()

	if realCost > maxCost {
		realCost = maxCost
	}
	cm.updateNodeRc(node, int64(maxCost-realCost), &node.params, now)
	if uint64(node.corrBufValue) > node.bufValue {
		if node.log != nil {
			node.log.add(now, fmt.Sprintf("corrected  bv=%d  oldBv=%d", node.corrBufValue, node.bufValue))
		}
		node.bufValue = uint64(node.corrBufValue)
	}
}
495838
func Handshake(conn net.Conn, options ...HandshakeOption) (net.Conn, error) {
	return DefaultClient.Handshake(conn, options...)
}
732842
func (prc *CorrectionProcessor) Process(nim image.Image, params imageserver.Params) (image.Image, error) {
	enabled, err := prc.isEnabled(params)
	if err != nil {
		return nil, err
	}
	if enabled {
		return prc.process(nim, params)
	}
	return prc.Processor.Process(nim, params)
}
867521
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	c.Lock()
	conn := tls.Server(rawConn, c.config)
	c.Unlock()
	if err := conn.Handshake(); err != nil {
		rawConn.Close()
		return nil, nil, err
	}

	return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
}
428964
func (nc *Conn) processExpectedInfo() error {

	c := &control{}

	// Read the protocol
	err := nc.readOp(c)
	if err != nil {
		return err
	}

	// The nats protocol should send INFO first always.
	if c.op != _INFO_OP_ {
		return ErrNoInfoReceived
	}

	// Parse the protocol
	if err := nc.processInfo(c.args); err != nil {
		return err
	}

	if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
		return ErrNkeysNotSupported
	}

	return nc.checkForSecure()
}
472066
func process(workload Workload, result *Result) (err error) {

	c := make(chan int, len(workload.Requests))
	result.Responses = make([]Response, len(workload.Requests))

	for index, _ := range workload.Requests {

		if workload.UseHeaders {
			replaceHeaderValues(&workload.Requests[index].Header, &workload.header)
		}

		if workload.StrictOrder {
			syncRequest(&workload.Requests[index], &result.Responses[index])
		} else {
			go asyncRequest(&workload.Requests[index], &result.Responses[index], c)
		}
	}

	// if async, wait for our responses or timeout
	if !workload.StrictOrder {

		// create a timeout so we don't wait forever
		var timeout <-chan time.Time

		if workload.Timeout > 0 {
			timeout = time.After(time.Duration(workload.Timeout))
		} else {
			timeout = time.After(DefaultTimeout)
		}

		for index := 0; index < len(workload.Requests); index++ {
			select {
			case <-c:
			case <-timeout:
				log.Warn("[process] Timed out waiting for all go routines to complete")
				break
			}
		}
	}
	return
}
845544
func processIOReader(fd io.Reader, contextID string) {
	reader := bufio.NewReader(fd)
	for {
		str, err := reader.ReadString('\n')
		if err != nil {
			return
		}
		fmt.Print("[" + contextID + "]:" + str)
	}
}
96217
func (s *Secure) Process(w http.ResponseWriter, r *http.Request) error {
	responseHeader, _, err := s.processRequest(w, r)
	addResponseHeaders(responseHeader, w)

	return err
}
224966
func (s *ServiceController) processServiceDeletion(key string) error {
	cachedService, ok := s.cache.get(key)
	if !ok {
		klog.Errorf("service %s not in cache even though the watcher thought it was. Ignoring the deletion", key)
		return nil
	}
	return s.processLoadBalancerDelete(cachedService, key)
}
231431
func (s *AuthService) ProcessPubSubPush(c context.Context, body []byte) (*Notification, error) {
	msg := pubSubMessage{}
	if err := json.Unmarshal(body, &msg); err != nil {
		logging.Errorf(c, "auth: bad PubSub notification, not JSON - %s", err)
		return nil, nil
	}

	// It's fine to return error here. Certificate fetch can fail due to bad
	// connectivity and we need a retry.
	certs, err := signing.FetchCertificatesFromLUCIService(c, s.URL)
	if err != nil {
		return nil, err
	}

	notify, err := s.decodeMessage(&msg, certs)
	if err != nil {
		logging.Errorf(c, "auth: bad PubSub notification - %s", err)
		return nil, nil
	}

	return &Notification{
		Revision: notify.GetRevision().GetAuthDbRev(),
		service:  s,
	}, nil
}
1172663
func (c *CertificateUpdater) Handle(done <-chan struct{}) error {
	addresses := c.addressWatcher.Addresses()
	if reflect.DeepEqual(addresses, c.addresses) {
		// Sometimes the watcher will tell us things have changed, when they
		// haven't as far as we can tell.
		logger.Debugf("addresses haven't really changed since last updated cert")
		return nil
	}
	return c.updateCertificate(addresses)
}
911556
func (router *Router) processMessage(conn *Connection, in []byte) {
	if name, data, err := router.protocol.Unpack(in); err == nil {
		if callback, ok := router.callbacks[name]; ok {
			callback(conn, data)
		}
	} // TODO: else error logging?

	defer recover()
}
1154445
func (b *SinkHandler) process() {
	for {
		rec, ok := <-b.sinkCh
		if !ok {
			b.inner.Close()
			break
		}

		b.inner.Handle(rec)
	}
	b.wg.Done()
}
624440
func (l *channelLink) processExitHop(pd *lnwallet.PaymentDescriptor,
	obfuscator ErrorEncrypter, fwdInfo ForwardingInfo, heightNow uint32) (
	bool, error) {

	// If hodl.ExitSettle is requested, we will not validate the final hop's
	// ADD, nor will we settle the corresponding invoice or respond with the
	// preimage.
	if l.cfg.DebugHTLC && l.cfg.HodlMask.Active(hodl.ExitSettle) {
		l.warnf(hodl.ExitSettle.Warning())

		return false, nil
	}

	// First, we'll check the expiry of the HTLC itself against, the current
	// block height. If the timeout is too soon, then we'll reject the HTLC.
	if pd.Timeout <= heightNow+l.cfg.FinalCltvRejectDelta {
		log.Errorf("htlc(%x) has an expiry that's too soon: expiry=%v"+
			", best_height=%v", pd.RHash[:], pd.Timeout, heightNow)

		failure := lnwire.NewFinalExpiryTooSoon()
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// We're the designated payment destination.  Therefore we attempt to
	// see if we have an invoice locally which'll allow us to settle this
	// htlc.
	//
	// Only the immutable data from LookupInvoice is used, because otherwise
	// a race condition may be created with concurrent writes to the invoice
	// registry. For example: cancelation of an invoice.
	invoiceHash := lntypes.Hash(pd.RHash)
	invoice, minCltvDelta, err := l.cfg.Registry.LookupInvoice(invoiceHash)
	if err != nil {
		log.Errorf("unable to query invoice registry: %v", err)
		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// If the invoice is already settled, we choose to accept the payment to
	// simplify failure recovery.
	//
	// NOTE: Though our recovery and forwarding logic is predominately
	// batched, settling invoices happens iteratively. We may reject one of
	// two payments for the same rhash at first, but then restart and reject
	// both after seeing that the invoice has been settled. Without any
	// record of which one settles first, it is ambiguous as to which one
	// actually settled the invoice. Thus, by accepting all payments, we
	// eliminate the race condition that can lead to this inconsistency.
	//
	// TODO(conner): track ownership of settlements to properly recover from
	// failures? or add batch invoice settlement
	//
	// TODO(joostjager): The log statement below is not always accurate, as
	// the invoice may have been canceled after the LookupInvoice call.
	// Leaving it as is for now, because fixing this would involve changing
	// the signature of InvoiceRegistry.SettleInvoice just because of this
	// log statement.
	if invoice.Terms.State == channeldb.ContractSettled {
		log.Warnf("Accepting duplicate payment for hash=%x",
			pd.RHash[:])
	}

	// If we're not currently in debug mode, and the extended htlc doesn't
	// meet the value requested, then we'll fail the htlc.  Otherwise, we
	// settle this htlc within our local state update log, then send the
	// update entry to the remote party.
	//
	// NOTE: We make an exception when the value requested by the invoice is
	// zero. This means the invoice allows the payee to specify the amount
	// of satoshis they wish to send.  So since we expect the htlc to have a
	// different amount, we should not fail.
	if !l.cfg.DebugHTLC && invoice.Terms.Value > 0 &&
		pd.Amount < invoice.Terms.Value {

		log.Errorf("rejecting htlc due to incorrect amount: expected "+
			"%v, received %v", invoice.Terms.Value, pd.Amount)

		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// As we're the exit hop, we'll double check the hop-payload included in
	// the HTLC to ensure that it was crafted correctly by the sender and
	// matches the HTLC we were extended.
	//
	// NOTE: We make an exception when the value requested by the invoice is
	// zero. This means the invoice allows the payee to specify the amount
	// of satoshis they wish to send.  So since we expect the htlc to have a
	// different amount, we should not fail.
	if !l.cfg.DebugHTLC && invoice.Terms.Value > 0 &&
		fwdInfo.AmountToForward < invoice.Terms.Value {

		log.Errorf("Onion payload of incoming htlc(%x) has incorrect "+
			"value: expected %v, got %v", pd.RHash,
			invoice.Terms.Value, fwdInfo.AmountToForward)

		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// We'll also ensure that our time-lock value has been computed
	// correctly. Only check the final cltv expiry for invoices when the
	// invoice has not yet moved to the accepted state. Otherwise hodl htlcs
	// would be canceled after a restart.
	expectedHeight := heightNow + minCltvDelta
	switch {
	case !l.cfg.DebugHTLC &&
		invoice.Terms.State == channeldb.ContractOpen &&
		pd.Timeout < expectedHeight:

		log.Errorf("Incoming htlc(%x) has an expiration that is too "+
			"soon: expected at least %v, got %v",
			pd.RHash[:], expectedHeight, pd.Timeout)

		failure := lnwire.FailFinalExpiryTooSoon{}
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil

	case !l.cfg.DebugHTLC && pd.Timeout != fwdInfo.OutgoingCTLV:
		log.Errorf("HTLC(%x) has incorrect time-lock: expected %v, "+
			"got %v", pd.RHash[:], pd.Timeout, fwdInfo.OutgoingCTLV)

		failure := lnwire.NewFinalIncorrectCltvExpiry(
			fwdInfo.OutgoingCTLV,
		)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// Notify the invoiceRegistry of the exit hop htlc. If we crash right
	// after this, this code will be re-executed after restart. We will
	// receive back a resolution event.
	event, err := l.cfg.Registry.NotifyExitHopHtlc(
		invoiceHash, pd.Amount, l.hodlQueue.ChanIn(),
	)
	if err != nil {
		return false, err
	}

	// Create a hodlHtlc struct and decide either resolved now or later.
	htlc := hodlHtlc{
		pd:         pd,
		obfuscator: obfuscator,
	}

	if event == nil {
		// Save payment descriptor for future reference.
		hodlHtlcs := l.hodlMap[invoiceHash]
		l.hodlMap[invoiceHash] = append(hodlHtlcs, htlc)

		return false, nil
	}

	// Process the received resolution.
	err = l.processHodlEvent(*event, htlc)
	if err != nil {
		return false, err
	}
	return true, nil
}
94361
func (e *Executor) ProcessEvent(id string, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
	switch et {
	case libcontainerdtypes.EventExit:
		deleteTaskAndContainer(context.Background(), e.client, id, nil)
		return e.exitHandler.HandleExitEvent(ei.ContainerID)
	}
	return nil
}