// Create new GoPacket packet handle from libmemif queue. rxCount determines how many packets will be read
// at once, minimum value is 1
493812
func (memif *Memif) NewPacketHandle(queueId uint8, rxCount uint16) *MemifPacketHandle {
	if rxCount == 0 {
		rxCount = 1
	}

	return &MemifPacketHandle{
		memif:   memif,
		queueId: queueId,
		rxCount: rxCount,
	}
}
271252
func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8, loop stack.PacketLooping) *tcpip.Error {
	length := uint16(hdr.UsedLength() + payload.Size())
	ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))
	ip.Encode(&header.IPv6Fields{
		PayloadLength: length,
		NextHeader:    uint8(protocol),
		HopLimit:      ttl,
		SrcAddr:       r.LocalAddress,
		DstAddr:       r.RemoteAddress,
	})

	if loop&stack.PacketLoop != 0 {
		views := make([]buffer.View, 1, 1+len(payload.Views()))
		views[0] = hdr.View()
		views = append(views, payload.Views()...)
		vv := buffer.NewVectorisedView(len(views[0])+payload.Size(), views)
		e.HandlePacket(r, vv)
	}
	if loop&stack.PacketOut == 0 {
		return nil
	}

	r.Stats().IP.PacketsSent.Increment()
	return e.linkEP.WritePacket(r, gso, hdr, payload, ProtocolNumber)
}
321502
func (c *Conn) receivePacket(h header, payload []byte) {
	c.packetReadTimeoutTimer.Reset(packetReadTimeout)
	c.processDelivery(h, payload)
}
1033609
func (session *pcapSession) addPacket(cons *PcapHTTPConsumer, pkt *pcap.Packet) {
	if len(pkt.Payload) == 0 {
		return //  ### return, no payload  ###
	}

	session.packets = session.packets.insert(pkt)

	if complete, size := session.packets.isComplete(); complete {
		payload := bytes.NewBuffer(make([]byte, 0, size))
		for _, pkt := range session.packets {
			payload.Write(pkt.Payload)
		}

		payloadReader := bufio.NewReader(payload)
		for {
			request, err := http.ReadRequest(payloadReader)
			if err != nil {
				session.lastError = err
				return // ### return, invalid request: packets pending? ###
			}

			request.Header.Add("X-Timestamp", strconv.FormatInt(time.Now().Unix(), 10))
			request.Header.Add("X-Client-Ip", session.client)

			extPayload := bytes.NewBuffer(nil)
			if err := request.Write(extPayload); err != nil {
				if err == io.ErrUnexpectedEOF {
					session.lastError = err
					return // ### return, invalid request: packets pending? ###
				}
				// Error: ignore this request
				session.logger.Error("PcapHTTPConsumer request writer: ", err)
			} else {
				// Enqueue this request
				cons.enqueueBuffer(extPayload.Bytes())
			}

			// Remove processed packets from list
			if payload.Len() == 0 {
				session.packets = session.packets[:0]
				return // ### return, processed everything ###
			}

			numReadBytes := size - payload.Len()
			size = payload.Len()
			session.dropPackets(numReadBytes)
		}
	}
}
1019455
func (e *endpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, vv buffer.VectorisedView) {
	e.rcvMu.Lock()

	// Drop the packet if our buffer is currently full.
	if !e.rcvReady || e.rcvClosed || e.rcvBufSize >= e.rcvBufSizeMax {
		e.stack.Stats().DroppedPackets.Increment()
		e.rcvMu.Unlock()
		return
	}

	wasEmpty := e.rcvBufSize == 0

	// Push new packet into receive list and increment the buffer size.
	pkt := &icmpPacket{
		senderAddress: tcpip.FullAddress{
			NIC:  r.NICID(),
			Addr: id.RemoteAddress,
		},
	}

	pkt.data = vv.Clone(pkt.views[:])

	e.rcvList.PushBack(pkt)
	e.rcvBufSize += pkt.data.Size()

	pkt.timestamp = e.stack.NowNanoseconds()

	e.rcvMu.Unlock()

	// Notify any waiters that there's data to be read now.
	if wasEmpty {
		e.waiterQueue.Notify(waiter.EventIn)
	}
}
416663
func (s *MemorySession) LookupPacket(dir Direction, id packet.ID) (packet.Generic, error) {
	return s.storeForDirection(dir).Lookup(id), nil
}
689488
func (s *Server) ListenPacket() (net.PacketConn, error) {
	if QUIC {
		udpAddr, err := net.ResolveUDPAddr("udp", s.Server.Addr)
		if err != nil {
			return nil, err
		}
		return net.ListenUDP("udp", udpAddr)
	}
	return nil, nil
}
724212
func (s *packetManager) readyPacket(pkt orderedResponse) {
	s.responses <- pkt
	s.working.Done()
}
676087
func (r *Route) WritePacket(gso *GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8) *tcpip.Error {
	err := r.ref.ep.WritePacket(r, gso, hdr, payload, protocol, ttl, r.loop)
	if err != nil {
		r.Stats().IP.OutgoingPacketErrors.Increment()
	} else {
		r.ref.nic.stats.Tx.Packets.Increment()
		r.ref.nic.stats.Tx.Bytes.IncrementBy(uint64(hdr.UsedLength() + payload.Size()))
	}
	return err
}
1366262
func NewPacketWithExtra(message string, extra Extra, interfaces ...Interface) *Packet {
	if extra == nil {
		extra = Extra{}
	}
	setExtraDefaults(extra)

	return &Packet{
		Message:    message,
		Interfaces: interfaces,
		Extra:      extra,
	}
}
613495
func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8, loop stack.PacketLooping) *tcpip.Error {
	ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))
	length := uint16(hdr.UsedLength() + payload.Size())
	id := uint32(0)
	if length > header.IPv4MaximumHeaderSize+8 {
		// Packets of 68 bytes or less are required by RFC 791 to not be
		// fragmented, so we only assign ids to larger packets.
		id = atomic.AddUint32(&ids[hashRoute(r, protocol)%buckets], 1)
	}
	ip.Encode(&header.IPv4Fields{
		IHL:         header.IPv4MinimumSize,
		TotalLength: length,
		ID:          uint16(id),
		TTL:         ttl,
		Protocol:    uint8(protocol),
		SrcAddr:     r.LocalAddress,
		DstAddr:     r.RemoteAddress,
	})
	ip.SetChecksum(^ip.CalculateChecksum())

	if loop&stack.PacketLoop != 0 {
		views := make([]buffer.View, 1, 1+len(payload.Views()))
		views[0] = hdr.View()
		views = append(views, payload.Views()...)
		vv := buffer.NewVectorisedView(len(views[0])+payload.Size(), views)
		e.HandlePacket(r, vv)
	}
	if loop&stack.PacketOut == 0 {
		return nil
	}

	r.Stats().IP.PacketsSent.Increment()
	return e.linkEP.WritePacket(r, gso, hdr, payload, ProtocolNumber)
}
1259407
func newPacketQueue(maxFreeSlots int) *packetQueue {
	p := &packetQueue{
		outgoingPkts: make(chan *htlcPacket),
		freeSlots:    make(chan struct{}, maxFreeSlots),
		quit:         make(chan struct{}),
	}
	p.queueCond = sync.NewCond(&p.queueMtx)

	return p
}
349298
func (cli *Client) handlePacket(p packet.Packet) error {
	// Get the MQTT Control Packet type.
	ptype, err := p.Type()
	if err != nil {
		return err
	}

	switch ptype {
	case packet.TypeCONNACK:
		cli.handleCONNACK()
		return nil
	case packet.TypePUBLISH:
		return cli.handlePUBLISH(p)
	case packet.TypePUBACK:
		return cli.handlePUBACK(p)
	case packet.TypePUBREC:
		return cli.handlePUBREC(p)
	case packet.TypePUBREL:
		return cli.handlePUBREL(p)
	case packet.TypePUBCOMP:
		return cli.handlePUBCOMP(p)
	case packet.TypeSUBACK:
		return cli.handleSUBACK(p)
	case packet.TypeUNSUBACK:
		return cli.handleUNSUBACK(p)
	case packet.TypePINGRESP:
		return cli.handlePINGRESP()
	default:
		return packet.ErrInvalidPacketType
	}
}
781925
func (n *Driver) parsePacket(buf *bytes.Buffer) {
	for buf.Len() > 0 {
		b, _ := buf.ReadByte()
		switch b {
		case CodeEx:
			n.Publish(n.Event("extended"), nil)
		case CodeSignalQuality:
			ret, _ := buf.ReadByte()
			n.Publish(n.Event("signal"), ret)
		case CodeAttention:
			ret, _ := buf.ReadByte()
			n.Publish(n.Event("attention"), ret)
		case CodeMeditation:
			ret, _ := buf.ReadByte()
			n.Publish(n.Event("meditation"), ret)
		case CodeBlink:
			ret, _ := buf.ReadByte()
			n.Publish(n.Event("blink"), ret)
		case CodeWave:
			buf.Next(1)
			var ret = make([]byte, 2)
			buf.Read(ret)
			n.Publish(n.Event("wave"), int16(ret[0])<<8|int16(ret[1]))
		case CodeAsicEEG:
			ret := make([]byte, 25)
			i, _ := buf.Read(ret)
			if i == 25 {
				n.Publish(n.Event("eeg"), n.parseEEG(ret))
			}
		}
	}
}
259664
func (c *Conn) ReadPacket() (uint16, []byte, error) {
	c.Conn.SetReadDeadline(time.Now().Add(c.Timeout))
	var header [6]byte
	if _, err := io.ReadFull(c.Conn, header[:]); err != nil {
		return 0, nil, err
	}
	pType := binary.BigEndian.Uint16(header[:])
	pLength := binary.BigEndian.Uint32(header[2:])
	pLengthInt := int(pLength)
	if pLengthInt > c.MaximumPacketBytes {
		return 0, nil, errors.New("gumble: packet larger than maximum allowed size")
	}
	if pLengthInt > len(c.buffer) {
		c.buffer = make([]byte, pLengthInt)
	}
	if _, err := io.ReadFull(c.Conn, c.buffer[:pLengthInt]); err != nil {
		return 0, nil, err
	}
	return pType, c.buffer[:pLengthInt], nil
}
575472
func (t *Tx) CompletedPacket() (id uint64, ok bool) {
	for {
		b := t.rx.Pull()
		if b == nil {
			return 0, false
		}

		if len(b) != 8 {
			t.rx.Flush()
			log.Printf("Ignoring completed packet: size (%v) is less than expected (%v)", len(b), 8)
			continue
		}

		v := binary.LittleEndian.Uint64(b)

		t.rx.Flush()

		return v, true
	}
}
447843
func NewPackageReader(r io.ReaderAt, size int64) (*PackageReader, error) {
	zr, err := zip.NewReader(r, size)
	if err != nil {
		// Note: we rely here (and in other places where we return errors) on
		// zip.Reader NOT wrapping errors from 'r', so they inherit transient tags
		// in case of transient Google Storage errors.
		return nil, err
	}
	return &PackageReader{zr}, nil
}