// GeneratePacketResponse returns an appropriate answer to an ARP request
// or an ICMP echo request.
7880
func GeneratePacketResponse(packet gopacket.Packet) (response gopacket.Packet, err error) {
	ethLayer := packet.Layer(layers.LayerTypeEthernet)
	eth, ok := ethLayer.(*layers.Ethernet)
	if !ok {
		fmt.Println("Missing ETH layer.")
		return nil, ErrUnhandledPacket
	}

	// Set up buffer and options for serialization.
	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}

	switch eth.EthernetType {
	case layers.EthernetTypeARP:
		// Handle ARP request.
		arpLayer := packet.Layer(layers.LayerTypeARP)
		arp, ok := arpLayer.(*layers.ARP)
		if !ok {
			fmt.Println("Missing ARP layer.")
			return nil, ErrUnhandledPacket
		}

		if arp.Operation != layers.ARPRequest {
			fmt.Println("Not ARP request.")
			return nil, ErrUnhandledPacket
		}

		fmt.Println("Received an ARP request.")

		// Build packet layers.
		ethResp := layers.Ethernet{
			SrcMAC:       hwAddr,
			DstMAC:       eth.SrcMAC,
			EthernetType: layers.EthernetTypeARP,
		}

		arpResp := layers.ARP{
			AddrType:          layers.LinkTypeEthernet,
			Protocol:          layers.EthernetTypeIPv4,
			HwAddressSize:     6,
			ProtAddressSize:   4,
			Operation:         layers.ARPReply,
			SourceHwAddress:   []byte(hwAddr),
			SourceProtAddress: []byte(ipAddr),
			DstHwAddress:      arp.SourceHwAddress,
			DstProtAddress:    arp.SourceProtAddress,
		}

		if err := gopacket.SerializeLayers(buf, opts, &ethResp, &arpResp); err != nil {
			fmt.Println("SerializeLayers error: ", err)
			return nil, ErrUnhandledPacket
		}
	case layers.EthernetTypeIPv4:
		// Respond to ICMP request.
		ipLayer := packet.Layer(layers.LayerTypeIPv4)
		ipv4, ok := ipLayer.(*layers.IPv4)
		if !ok {
			fmt.Println("Missing IPv4 layer.")
			return nil, ErrUnhandledPacket
		}

		if ipv4.Protocol != layers.IPProtocolICMPv4 {
			fmt.Println("Not ICMPv4 protocol.")
			return nil, ErrUnhandledPacket
		}

		icmpLayer := packet.Layer(layers.LayerTypeICMPv4)
		icmp, ok := icmpLayer.(*layers.ICMPv4)
		if !ok {
			fmt.Println("Missing ICMPv4 layer.")
			return nil, ErrUnhandledPacket
		}

		if icmp.TypeCode.Type() != layers.ICMPv4TypeEchoRequest {
			fmt.Println("Not ICMPv4 echo request.")
			return nil, ErrUnhandledPacket
		}

		fmt.Println("Received an ICMPv4 echo request.")

		// Build packet layers.
		ethResp := layers.Ethernet{
			SrcMAC:       hwAddr,
			DstMAC:       eth.SrcMAC,
			EthernetType: layers.EthernetTypeIPv4,
		}

		ipv4Resp := layers.IPv4{
			Version:    4,
			IHL:        5,
			TOS:        0,
			Id:         0,
			Flags:      0,
			FragOffset: 0,
			TTL:        255,
			Protocol:   layers.IPProtocolICMPv4,
			SrcIP:      ipAddr,
			DstIP:      ipv4.SrcIP,
		}

		icmpResp := layers.ICMPv4{
			TypeCode: layers.CreateICMPv4TypeCode(layers.ICMPv4TypeEchoReply, 0),
			Id:       icmp.Id,
			Seq:      icmp.Seq,
		}

		if err := gopacket.SerializeLayers(buf, opts, &ethResp, &ipv4Resp, &icmpResp, gopacket.Payload(icmp.Payload)); err != nil {
			fmt.Println("SerializeLayers error: ", err)
			return nil, ErrUnhandledPacket
		}
	default:
		return nil, ErrUnhandledPacket
	}

	return gopacket.NewPacket(buf.Bytes(), layers.LayerTypeEthernet, gopacket.Default), nil
}
240543
func (g *Generator) GeneratePrologue(pkg string) {
	g.populateImports()
	if g.ip {
		g.printf("package %s\n\n", g.iface.Pkg.Name())
	} else {
		g.printf("package %v\n\n", pkg)
	}

	g.generateImports()
	g.printf("\n")
}
1264664
func makePacket(p rxPacket) (requestPacket, error) {
	var pkt requestPacket
	switch p.pktType {
	case ssh_FXP_INIT:
		pkt = &sshFxInitPacket{}
	case ssh_FXP_LSTAT:
		pkt = &sshFxpLstatPacket{}
	case ssh_FXP_OPEN:
		pkt = &sshFxpOpenPacket{}
	case ssh_FXP_CLOSE:
		pkt = &sshFxpClosePacket{}
	case ssh_FXP_READ:
		pkt = &sshFxpReadPacket{}
	case ssh_FXP_WRITE:
		pkt = &sshFxpWritePacket{}
	case ssh_FXP_FSTAT:
		pkt = &sshFxpFstatPacket{}
	case ssh_FXP_SETSTAT:
		pkt = &sshFxpSetstatPacket{}
	case ssh_FXP_FSETSTAT:
		pkt = &sshFxpFsetstatPacket{}
	case ssh_FXP_OPENDIR:
		pkt = &sshFxpOpendirPacket{}
	case ssh_FXP_READDIR:
		pkt = &sshFxpReaddirPacket{}
	case ssh_FXP_REMOVE:
		pkt = &sshFxpRemovePacket{}
	case ssh_FXP_MKDIR:
		pkt = &sshFxpMkdirPacket{}
	case ssh_FXP_RMDIR:
		pkt = &sshFxpRmdirPacket{}
	case ssh_FXP_REALPATH:
		pkt = &sshFxpRealpathPacket{}
	case ssh_FXP_STAT:
		pkt = &sshFxpStatPacket{}
	case ssh_FXP_RENAME:
		pkt = &sshFxpRenamePacket{}
	case ssh_FXP_READLINK:
		pkt = &sshFxpReadlinkPacket{}
	case ssh_FXP_SYMLINK:
		pkt = &sshFxpSymlinkPacket{}
	case ssh_FXP_EXTENDED:
		pkt = &sshFxpExtendedPacket{}
	default:
		return nil, errors.Errorf("unhandled packet type: %s", p.pktType)
	}
	if err := pkt.UnmarshalBinary(p.pktBytes); err != nil {
		// Return partially unpacked packet to allow callers to return
		// error messages appropriately with necessary id() method.
		return pkt, err
	}
	return pkt, nil
}
1361898
func (r *Packet) Reply(payload interface{}, err error) ([]byte, error) {
	p := new(Packet)

	status := uint32(StatusSuccess)

	if err != nil {
		status = errorStatus(err)
	} else {
		p.Payload, err = MarshalBinary(payload)
		if err != nil {
			return nil, err
		}
	}

	p.Header = Header{
		Version:     HeaderVersion,
		Dummy:       OpNewHeader,
		PacketSize:  headerSize + uint32(len(p.Payload)),
		HeaderSize:  headerSize,
		RequestID:   r.RequestID,
		Op:          r.Op,
		Status:      status,
		Flags:       PacketFlagReply,
		Information: 0,
		SessionID:   r.SessionID,
	}

	if Trace {
		rc := "OK"
		if err != nil {
			rc = err.Error()
		}
		fmt.Fprintf(os.Stderr, "[hgfs] response %#v [%s]\n", p.Header, rc)
	} else if err != nil {
		log.Printf("[hgfs] op=%d error: %s", r.Op, err)
	}

	return p.MarshalBinary()
}
924156
func (qs *queryResponseStream) sendResponse(from string, payload []byte) error {
	header := responseHeader{
		Seq:   qs.seq,
		Error: "",
	}
	rec := queryRecord{
		Type:    queryRecordResponse,
		From:    from,
		Payload: payload,
	}
	return qs.client.Send(&header, &rec)
}
941161
func (req *SrvReq) RespondRcreate(qid *Qid, iounit uint32) {
	err := PackRcreate(req.Rc, qid, iounit)
	if err != nil {
		req.RespondError(err)
	} else {
		req.Respond()
	}
}
803271
func SendResponse(w http.ResponseWriter, resp []*Response, batch bool) error {
	w.Header().Set(contentTypeKey, contentTypeValue)
	if batch || len(resp) > 1 {
		return fastjson.NewEncoder(w).Encode(resp)
	} else if len(resp) == 1 {
		return fastjson.NewEncoder(w).Encode(resp[0])
	}
	return nil
}
632468
func (mm *messageManager) GenerateAckQuery(ids []string) (string, map[string]*querypb.BindVariable) {
	idbvs := &querypb.BindVariable{
		Type:   querypb.Type_TUPLE,
		Values: make([]*querypb.Value, 0, len(ids)),
	}
	for _, id := range ids {
		idbvs.Values = append(idbvs.Values, &querypb.Value{
			Type:  querypb.Type_VARCHAR,
			Value: []byte(id),
		})
	}
	return mm.ackQuery.Query, map[string]*querypb.BindVariable{
		"time_acked": sqltypes.Int64BindVariable(time.Now().UnixNano()),
		"ids":        idbvs,
	}
}
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
	}
}
539315
func GenerateQueryResponse() []chaospeddler.ServiceBinding {
	var res []chaospeddler.ServiceBinding

	for i := 0; i < 100; i++ {

		res = append(res, chaospeddler.ServiceBinding{
			InstanceID: fmt.Sprintf("randominstance-%v", i),
			BindingID:  fmt.Sprintf("something-binding-%v", i),
		})
	}
	return res
}
724212
func (s *packetManager) readyPacket(pkt orderedResponse) {
	s.responses <- pkt
	s.working.Done()
}
1000823
func ReadUnpackedResponse(r io.Reader) (int32, []byte, error) {
	resp, err := ReadResponse(r)
	if err != nil {
		return -1, nil, err
	}
	return UnpackResponse(resp)
}
116054
func NewPacket(fields ...Field) (*Packet, error) {
	p := &Packet{b: make([]byte, 0, MaxEIRPacketLength)}
	for _, f := range fields {
		if err := f(p); err != nil {
			return nil, err
		}
	}
	return p, nil
}
492231
func (p *PacketFlow) AppendPacket(pm PacketManipulator) int {

	p.flow = append(p.flow, pm)

	return p.GetNumPackets()
}
155099
func (req *SrvReq) RespondRstat(st *Dir) {
	err := PackRstat(req.Rc, st, req.Conn.Dotu)
	if err != nil {
		req.RespondError(err)
	} else {
		req.Respond()
	}
}
979151
func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
	data, err := mc.readPacket()
	if err == nil {
		switch data[0] {

		case iOK:
			return 0, mc.handleOkPacket(data)

		case iERR:
			return 0, mc.handleErrorPacket(data)

		case iLocalInFile:
			return 0, mc.handleInFileRequest(string(data[1:]))
		}

		// column count
		num, _, n := readLengthEncodedInteger(data)
		if n-len(data) == 0 {
			return int(num), nil
		}

		return 0, ErrMalformPkt
	}
	return 0, err
}
29904
func (setup *SetupClientController) handlePairStepStartResponse(in util.Container) (util.Container, error) {
	salt := in.GetBytes(TagSalt)
	serverPublicKey := in.GetBytes(TagPublicKey)

	if len(salt) != 16 {
		return nil, fmt.Errorf("Salt is invalid (%d bytes)", len(salt))
	}

	if len(serverPublicKey) != 384 {
		return nil, fmt.Errorf("B is invalid (%d bytes)", len(serverPublicKey))
	}

	fmt.Println("->     B:", hex.EncodeToString(serverPublicKey))
	fmt.Println("->     s:", hex.EncodeToString(salt))

	// Client
	// 1) Receive salt `s` and public key `B` and generates `S` and `A`
	err := setup.session.GenerateKeys(salt, serverPublicKey)
	if err != nil {
		return nil, err
	}
	fmt.Println("        S:", hex.EncodeToString(setup.session.PrivateKey))

	// 2) Send public key `A` and proof `M1`
	publicKey := setup.session.PublicKey // SRP public key
	proof := setup.session.Proof         // M1

	fmt.Println("<-     A:", hex.EncodeToString(publicKey))
	fmt.Println("<-     M1:", hex.EncodeToString(proof))

	out := util.NewTLV8Container()
	out.SetByte(TagPairingMethod, 0)
	out.SetByte(TagSequence, PairStepVerifyRequest.Byte())
	out.SetBytes(TagPublicKey, publicKey)
	out.SetBytes(TagProof, proof)

	return out, nil
}