// failAddPacket encrypts a fail packet back to an add packet's source.
// The ciphertext will be derived from the failure message proivded by context.
// This method returns the failErr if all other steps complete successfully.
771016
func (s *Switch) failAddPacket(packet *htlcPacket,
	failure lnwire.FailureMessage, failErr error) error {

	// Encrypt the failure so that the sender will be able to read the error
	// message. Since we failed this packet, we use EncryptFirstHop to
	// obfuscate the failure for their eyes only.
	reason, err := packet.obfuscator.EncryptFirstHop(failure)
	if err != nil {
		err := fmt.Errorf("unable to obfuscate "+
			"error: %v", err)
		log.Error(err)
		return err
	}

	log.Error(failErr)

	failPkt := &htlcPacket{
		sourceRef:      packet.sourceRef,
		incomingChanID: packet.incomingChanID,
		incomingHTLCID: packet.incomingHTLCID,
		circuit:        packet.circuit,
		htlc: &lnwire.UpdateFailHTLC{
			Reason: reason,
		},
	}

	// Route a fail packet back to the source link.
	err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
	if err != nil {
		err = fmt.Errorf("source chanid=%v unable to "+
			"handle switch packet: %v",
			packet.incomingChanID, err)
		log.Error(err)
		return err
	}

	return failErr
}
1373300
func (f *DedupSQSFilter) Failed(msg *sqs.Message) {
	msgBody := aws.StringValue(msg.Body)
	_ = f.cache.Unset(msgBody)
}
666105
func (c *Client) SendDiscoverPacket() (dhcp4.Packet, error) {
	discoveryPacket := c.DiscoverPacket()
	discoveryPacket.PadToMinSize()

	return discoveryPacket, c.SendPacket(discoveryPacket)
}
782816
func (client *Client) UploadBuildpack(buildpackGUID string, buildpackPath string, buildpack io.Reader, buildpackLength int64) (Warnings, error) {

	contentLength, err := buildpacks.CalculateRequestSize(buildpackLength, buildpackPath, "buildpack")
	if err != nil {
		return nil, err
	}

	contentType, body, writeErrors := buildpacks.CreateMultipartBodyAndHeader(buildpack, buildpackPath, "buildpack")

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PutBuildpackBitsRequest,
		URIParams:   Params{"buildpack_guid": buildpackGUID},
		Body:        body,
	})

	if err != nil {
		return nil, err
	}

	request.Header.Set("Content-Type", contentType)
	request.ContentLength = contentLength

	_, warnings, err := client.uploadBuildpackAsynchronously(request, writeErrors)
	if err != nil {
		return warnings, err
	}
	return warnings, nil
}
357112
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
	if h, ok := t.(tHelper); ok {
		h.Helper()
	}
	content := []labeledContent{
		{"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
		{"Error", failureMessage},
	}

	// Add test name if the Go version supports it
	if n, ok := t.(interface {
		Name() string
	}); ok {
		content = append(content, labeledContent{"Test", n.Name()})
	}

	message := messageFromMsgAndArgs(msgAndArgs...)
	if len(message) > 0 {
		content = append(content, labeledContent{"Messages", message})
	}

	t.Errorf("\n%s", ""+labeledOutput(content...))

	return false
}
664221
func (mc *mysqlConn) writeCommandPacket(command byte) error {
	// Reset Packet Sequence
	mc.sequence = 0

	data := mc.buf.takeSmallBuffer(4 + 1)
	if data == nil {
		// can not take the buffer. Something must be wrong with the connection
		errLog.Print(ErrBusyBuffer)
		return driver.ErrBadConn
	}

	// Add command byte
	data[4] = command

	// Send CMD packet
	return mc.writePacket(data)
}
1049368
func (p *PacketFilter) AddUDPRuleAt(sourceNetwork string, sourcePort string, destPort string, description string, isAllow bool, index int) (*PacketFilterExpression, error) {
	exp := p.createUDPRule(sourceNetwork, sourcePort, destPort, description, isAllow)
	p.addRuleAt(exp, index)
	return exp, nil
}
1074171
func (c package_cache) append_packages(ps map[string]*package_file_cache, pkgs []package_import) {
	for _, m := range pkgs {
		if _, ok := ps[m.abspath]; ok {
			continue
		}

		if mod, ok := c[m.abspath]; ok {
			ps[m.abspath] = mod
		} else {
			mod = new_package_file_cache(m.abspath, m.path)
			ps[m.abspath] = mod
			c[m.abspath] = mod
		}
	}
}
868335
func (d *Datapath) processUDPFinPacket(udpPacket *packet.Packet) (err error) { // nolint

	// add it to the udp fin cache. If we have already received the fin packet
	// for this flow. There is no need to change the connmark label again.
	if d.udpFinPacketTracker.AddOrUpdate(udpPacket.L4ReverseFlowHash(), true) {
		return nil
	}

	// clear cache entries.
	if err := d.udpAppOrigConnectionTracker.Remove(udpPacket.L4ReverseFlowHash()); err != nil {
		zap.L().Debug("Failed to clean cache udpappOrigConnectionTracker", zap.Error(err))
	}

	if err := d.udpSourcePortConnectionCache.Remove(udpPacket.SourcePortHash(packet.PacketTypeNetwork)); err != nil {
		zap.L().Debug("Failed to clean cache udpsourcePortConnectionCache", zap.Error(err))
	}

	zap.L().Debug("Updating the connmark label", zap.String("flow", udpPacket.L4FlowHash()))
	if err = d.conntrack.UpdateNetworkFlowMark(
		udpPacket.SourceAddress(),
		udpPacket.DestinationAddress(),
		udpPacket.IPProto(),
		udpPacket.SourcePort(),
		udpPacket.DestPort(),
		constants.DeleteConnmark,
	); err != nil {
		zap.L().Error("Failed to update conntrack table for flow to terminate connection",
			zap.String("app-conn", udpPacket.L4FlowHash()),
			zap.Error(err),
		)
	}

	return nil
}
393867
func (ps *PeerSet) TryAdd(p peer.ID) bool {
	var success bool
	ps.lk.Lock()
	if _, ok := ps.ps[p]; !ok && (len(ps.ps) < ps.size || ps.size == -1) {
		success = true
		ps.ps[p] = struct{}{}
	}
	ps.lk.Unlock()
	return success
}
785103
func (conn *ProtoManualConnection) NewAsyncPublisherToPartition(topic string, partition int32, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) {
	return &protoManualAsyncPublisherKafka{conn, topic, partition, successClb, errorClb}, nil
}
436574
func SetPackageHidden(c context.Context, pkg string, hidden bool) error {
	return Txn(c, "SetPackageHidden", func(c context.Context) error {
		p := &Package{Name: pkg}
		switch err := datastore.Get(c, p); {
		case err == datastore.ErrNoSuchEntity:
			return err
		case err != nil:
			return transient.Tag.Apply(err)
		case p.Hidden == hidden:
			return nil
		}

		p.Hidden = hidden
		if err := datastore.Put(c, p); err != nil {
			return transient.Tag.Apply(err)
		}

		ev := api.EventKind_PACKAGE_HIDDEN
		if !hidden {
			ev = api.EventKind_PACKAGE_UNHIDDEN
		}
		return EmitEvent(c, &api.Event{Kind: ev, Package: pkg})
	})
}
618144
func (f *FailureResponse) AppendErrorMessage(msg string) *FailureResponse {
	return &FailureResponse{
		error:         errors.New(fmt.Sprintf("%s %s", f.Error(), msg)),
		statusCode:    f.statusCode,
		loggerAction:  f.loggerAction,
		emptyResponse: f.emptyResponse,
		errorKey:      f.errorKey,
	}
}
494013
func failDefault(is *Is, format string, args ...interface{}) {
	is.TB.Helper()

	failFmt := format
	if len(is.failFormat) != 0 {
		failFmt = fmt.Sprintf("%s - %s", format, is.failFormat)
		args = append(args, is.failArgs...)
	}
	if is.strict {
		is.TB.Fatalf(failFmt, args...)
	} else {
		is.TB.Errorf(failFmt, args...)
	}
}
1283136
func (s *server) handleAddPeerMsg(state *peerState, sp *serverPeer) bool {
	if sp == nil {
		return false
	}

	// Disconnect peers with unwanted user agents.
	if sp.HasUndesiredUserAgent(s.agentBlacklist, s.agentWhitelist) {
		sp.Disconnect()
		return false
	}

	// Ignore new peers if we're shutting down.
	if atomic.LoadInt32(&s.shutdown) != 0 {
		srvrLog.Infof("New peer %s ignored - server is shutting down", sp)
		sp.Disconnect()
		return false
	}

	// Disconnect banned peers.
	host, _, err := net.SplitHostPort(sp.Addr())
	if err != nil {
		srvrLog.Debugf("can't split hostport %v", err)
		sp.Disconnect()
		return false
	}
	if banEnd, ok := state.banned[host]; ok {
		if time.Now().Before(banEnd) {
			srvrLog.Debugf("Peer %s is banned for another %v - disconnecting",
				host, time.Until(banEnd))
			sp.Disconnect()
			return false
		}

		srvrLog.Infof("Peer %s is no longer banned", host)
		delete(state.banned, host)
	}

	// TODO: Check for max peers from a single IP.

	// Limit max number of total peers.
	if state.Count() >= cfg.MaxPeers {
		srvrLog.Infof("Max peers reached [%d] - disconnecting peer %s",
			cfg.MaxPeers, sp)
		sp.Disconnect()
		// TODO: how to handle permanent peers here?
		// they should be rescheduled.
		return false
	}

	// Add the new peer and start it.
	srvrLog.Debugf("New peer %s", sp)
	if sp.Inbound() {
		state.inboundPeers[sp.ID()] = sp
	} else {
		state.outboundGroups[addrmgr.GroupKey(sp.NA())]++
		if sp.persistent {
			state.persistentPeers[sp.ID()] = sp
		} else {
			state.outboundPeers[sp.ID()] = sp
		}
	}

	return true
}
312277
func (client *Client) UpdateBuildpack(buildpack Buildpack) (Buildpack, Warnings, error) {
	body, err := json.Marshal(buildpack)
	if err != nil {
		return Buildpack{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PutBuildpackRequest,
		URIParams:   Params{"buildpack_guid": buildpack.GUID},
		Body:        bytes.NewReader(body),
	})
	if err != nil {
		return Buildpack{}, nil, err
	}

	var updatedBuildpack Buildpack
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &updatedBuildpack,
	}

	err = client.connection.Make(request, &response)
	if err != nil {
		return Buildpack{}, response.Warnings, err
	}

	return updatedBuildpack, response.Warnings, nil
}
1010286
func (e *Error) EncodeMsgpack(enc *msgpack.Encoder) error {
	var err error
	switch v := e.err.(type) {
	case *Error:
		err = enc.Encode(ErrorLocal)
		if err != nil {
			return err
		}
		err = enc.Encode(v)
		if err != nil {
			return err
		}
	case error:
		err = enc.Encode(ErrorGo)
		if err != nil {
			return err
		}
		err = enc.Encode(GoError(v.Error()))
		if err != nil {
			return err
		}
	default:
		panic("type not supported")
	}
	err = enc.Encode(e.args)
	if err != nil {
		return err
	}
	err = enc.Encode(e.pkg)
	if err != nil {
		return err
	}
	err = enc.Encode(e.file)
	if err != nil {
		return err
	}
	err = enc.Encode(e.line)
	if err != nil {
		return err
	}
	err = enc.Encode(e.debugInfo)
	if err != nil {
		return err
	}
	if e.next == nil {
		err = enc.Encode(NextIsNill)
		if err != nil {
			return err
		}
	} else {
		err = enc.Encode(Next)
		if err != nil {
			return err
		}
		err = enc.Encode(e.next)
		if err != nil {
			return err
		}
	}
	return nil
}