// NewCONNACKFromBytes creates the CONNACK Packet
// from the byte data and returns it.
966046
func NewCONNACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) {
	// Validate the byte data.
	if err := validateCONNACKBytes(fixedHeader, variableHeader); err != nil {
		return nil, err
	}

	// Create a CONNACK Packet.
	p := &CONNACK{
		sessionPresent:    variableHeader[0]<<7 == 0x80,
		connectReturnCode: variableHeader[1],
	}

	// Set the fixed header to the Packet.
	p.fixedHeader = fixedHeader

	// Set the variable header to the Packet.
	p.variableHeader = variableHeader

	// Return the Packet.
	return p, nil
}
834751
func NewPacket(message string, interfaces ...Interface) *Packet {
	extra := Extra{}
	setExtraDefaults(extra)
	return &Packet{
		Message:    message,
		Interfaces: interfaces,
		Extra:      extra,
	}
}
197282
func newPacketConn(ifi *net.Interface, s socket, pbe uint16, filter []bpf.RawInstruction) (*packetConn, error) {
	pc := &packetConn{
		ifi: ifi,
		s:   s,
		pbe: pbe,
	}

	if len(filter) > 0 {
		if err := pc.SetBPF(filter); err != nil {
			return nil, err
		}
	}

	// Bind the packet socket to the interface specified by ifi
	// packet(7):
	//   Only the sll_protocol and the sll_ifindex address fields are used for
	//   purposes of binding.
	// This overrides the protocol given to socket(AF_PACKET).
	err := s.Bind(&unix.SockaddrLinklayer{
		Protocol: pc.pbe,
		Ifindex:  ifi.Index,
	})
	if err != nil {
		return nil, err
	}

	return pc, nil
}
508223
func NewValueFromBytes(b []byte) (*Value, error) {
	r := bytes.NewReader(b)
	return NewValueFromReader(r)
}
254990
func NewPUBRELFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) {
	// Validate the byte data.
	if err := validatePUBRELBytes(fixedHeader, variableHeader); err != nil {
		return nil, err
	}

	// Decode the Packet Identifier.
	// No error occur because of the precedent validation and
	// the returned error is not be taken care of.
	packetID, _ := decodeUint16(variableHeader)

	// Create a PUBREL Packet.
	p := &PUBREL{
		PacketID: packetID,
	}

	// Set the fixed header to the Packet.
	p.fixedHeader = fixedHeader

	// Set the variable header to the Packet.
	p.variableHeader = variableHeader

	// Return the Packet.
	return p, nil
}
596929
func NewLinkFrom(ifcName string) (Linker, error) {
	if ok, err := NetInterfaceNameValid(ifcName); !ok {
		return nil, err
	}

	newIfc, err := net.InterfaceByName(ifcName)
	if err != nil {
		return nil, fmt.Errorf("Could not find the new interface: %s", err)
	}

	return &Link{
		ifc: newIfc,
	}, nil
}
1174571
func NewBytesConnection(client Client, log logging.Logger) (*BytesConnectionRedis, error) {
	return &BytesConnectionRedis{log, client, make(chan string), false}, nil
}
783642
func (f *AckFrame) AcksPacket(p protocol.PacketNumber) bool {
	if p < f.LowestAcked() || p > f.LargestAcked() {
		return false
	}

	i := sort.Search(len(f.AckRanges), func(i int) bool {
		return p >= f.AckRanges[i].Smallest
	})
	// i will always be < len(f.AckRanges), since we checked above that p is not bigger than the largest acked
	return p <= f.AckRanges[i].Largest
}
835340
func NewNetConn(conn net.Conn, maxWriteDelay time.Duration) *NetConn {
	return &NetConn{
		BaseConn: NewBaseConn(conn, maxWriteDelay),
		conn:     conn,
	}
}
897459
func NewOnionPacket(paymentPath *PaymentPath, sessionKey *btcec.PrivateKey,
	assocData []byte) (*OnionPacket, error) {

	numHops := paymentPath.TrueRouteLength()

	hopSharedSecrets := generateSharedSecrets(
		paymentPath.NodeKeys(), sessionKey,
	)

	// Generate the padding, called "filler strings" in the paper.
	filler := generateHeaderPadding(
		"rho", numHops, HopDataSize, hopSharedSecrets,
	)

	// Allocate zero'd out byte slices to store the final mix header packet
	// and the hmac for each hop.
	var (
		mixHeader  [routingInfoSize]byte
		nextHmac   [HMACSize]byte
		hopDataBuf bytes.Buffer
	)

	// Now we compute the routing information for each hop, along with a
	// MAC of the routing info using the shared key for that hop.
	for i := numHops - 1; i >= 0; i-- {
		// We'll derive the two keys we need for each hop in order to:
		// generate our stream cipher bytes for the mixHeader, and
		// calculate the MAC over the entire constructed packet.
		rhoKey := generateKey("rho", &hopSharedSecrets[i])
		muKey := generateKey("mu", &hopSharedSecrets[i])

		// The HMAC for the final hop is simply zeroes. This allows the
		// last hop to recognize that it is the destination for a
		// particular payment.
		paymentPath[i].HopData.HMAC = nextHmac

		// Next, using the key dedicated for our stream cipher, we'll
		// generate enough bytes to obfuscate this layer of the onion
		// packet.
		streamBytes := generateCipherStream(rhoKey, numStreamBytes)

		// Before we assemble the packet, we'll shift the current
		// mix-header to the write in order to make room for this next
		// per-hop data.
		rightShift(mixHeader[:], HopDataSize)

		// With the mix header right-shifted, we'll encode the current
		// hop data into a buffer we'll re-use during the packet
		// construction.
		err := paymentPath[i].HopData.Encode(&hopDataBuf)
		if err != nil {
			return nil, err
		}
		copy(mixHeader[:], hopDataBuf.Bytes())

		// Once the packet for this hop has been assembled, we'll
		// re-encrypt the packet by XOR'ing with a stream of bytes
		// generated using our shared secret.
		xor(mixHeader[:], mixHeader[:], streamBytes[:routingInfoSize])

		// If this is the "last" hop, then we'll override the tail of
		// the hop data.
		if i == numHops-1 {
			copy(mixHeader[len(mixHeader)-len(filler):], filler)
		}

		// The packet for this hop consists of: mixHeader. When
		// calculating the MAC, we'll also include the optional
		// associated data which can allow higher level applications to
		// prevent replay attacks.
		packet := append(mixHeader[:], assocData...)
		nextHmac = calcMac(muKey, packet)

		hopDataBuf.Reset()
	}

	return &OnionPacket{
		Version:      baseVersion,
		EphemeralKey: sessionKey.PubKey(),
		RoutingInfo:  mixHeader,
		HeaderMAC:    nextHmac,
	}, nil
}
484994
func uint32FromNetwork(u uint32) uint32 {
	b := *(*[4]byte)(unsafe.Pointer(&u))
	return binary.BigEndian.Uint32(b[:])
}
837949
func (p *GncpPool) createConn() (net.Conn, error) {
	p.lock.Lock()
	defer p.lock.Unlock()
	if p.totalConnNum >= p.maxConnNum {
		return nil, fmt.Errorf("Connot Create new connection. Now has %d.Max is %d", p.totalConnNum, p.maxConnNum)
	}
	conn, err := p.connCreator()
	if err != nil {
		return nil, fmt.Errorf("Cannot create new connection.%s", err)
	}
	p.totalConnNum = p.totalConnNum + 1
	return conn, nil
}
809563
func NewPacketConn(s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*PacketConn, error) {
	// Create UDP endpoint and bind it.
	var wq waiter.Queue
	ep, err := s.NewEndpoint(udp.ProtocolNumber, network, &wq)
	if err != nil {
		return nil, errors.New(err.String())
	}

	if err := ep.Bind(addr); err != nil {
		ep.Close()
		return nil, &net.OpError{
			Op:   "bind",
			Net:  "udp",
			Addr: fullToUDPAddr(addr),
			Err:  errors.New(err.String()),
		}
	}

	c := &PacketConn{
		stack: s,
		ep:    ep,
		wq:    &wq,
	}
	c.deadlineTimer.init()
	return c, nil
}
1261553
func NewConn(rwc io.ReadWriteCloser) *Conn {
	return &Conn{
		Encoder: Encoder{
			writer: rwc,
		},
		Decoder: Decoder{
			reader: bufio.NewReader(rwc),
		},
		conn: rwc,
	}
}
883646
func NewClientConfigFromBytes(configBytes []byte) (ClientConfig, error) {
	config, err := Load(configBytes)
	if err != nil {
		return nil, err
	}

	return &DirectClientConfig{*config, "", &ConfigOverrides{}, nil, nil, promptedCredentials{}}, nil
}
727876
func validateCONNACKBytes(fixedHeader FixedHeader, variableHeader []byte) error {
	// Extract the MQTT Control Packet type.
	ptype, err := fixedHeader.ptype()
	if err != nil {
		return err
	}

	// Check the length of the fixed header.
	if len(fixedHeader) != lenCONNACKFixedHeader {
		return ErrInvalidFixedHeaderLen
	}

	// Check the MQTT Control Packet type.
	if ptype != TypeCONNACK {
		return ErrInvalidPacketType
	}

	// Check the reserved bits of the fixed header.
	if fixedHeader[0]<<4 != 0x00 {
		return ErrInvalidFixedHeader
	}

	// Check the Remaining Length of the fixed header.
	if fixedHeader[1] != lenCONNACKVariableHeader {
		return ErrInvalidRemainingLength
	}

	// Check the length of the variable header.
	if len(variableHeader) != lenCONNACKVariableHeader {
		return ErrInvalidVariableHeaderLen
	}

	// Check the reserved bits of the variable header.
	if variableHeader[0]>>1 != 0x00 {
		return ErrInvalidVariableHeader
	}

	// Check the Connect Return code of the variable header.
	switch variableHeader[1] {
	case
		connRetAccepted,
		connRetUnacceptableProtocolVersion,
		connRetIdentifierRejected,
		connRetServerUnavailable,
		connRetBadUserNameOrPassword,
		connRetNotAuthorized:
	default:
		return ErrInvalidConnectReturnCode
	}

	return nil
}
155543
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) {
	udpaddr, err := net.ResolveUDPAddr("udp", raddr)
	if err != nil {
		return nil, errors.Wrap(err, "net.ResolveUDPAddr")
	}

	var convid uint32
	binary.Read(rand.Reader, binary.LittleEndian, &convid)
	return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil
}