// packetMMapDispatch reads packets from an mmaped ring buffer and dispatches
// them to the network stack.
774857
func (e *endpoint) packetMMapDispatch() (bool, *tcpip.Error) {
	pkt, err := e.readMMappedPacket()
	if err != nil {
		return false, err
	}
	var (
		p             tcpip.NetworkProtocolNumber
		remote, local tcpip.LinkAddress
	)
	if e.hdrSize > 0 {
		eth := header.Ethernet(pkt)
		p = eth.Type()
		remote = eth.SourceAddress()
		local = eth.DestinationAddress()
	} else {
		// We don't get any indication of what the packet is, so try to guess
		// if it's an IPv4 or IPv6 packet.
		switch header.IPVersion(pkt) {
		case header.IPv4Version:
			p = header.IPv4ProtocolNumber
		case header.IPv6Version:
			p = header.IPv6ProtocolNumber
		default:
			return true, nil
		}
	}

	pkt = pkt[e.hdrSize:]
	e.dispatcher.DeliverNetworkPacket(e, remote, local, p, buffer.NewVectorisedView(len(pkt), []buffer.View{buffer.View(pkt)}))
	return true, nil
}
776158
func (c *IPHAConn) readIPv4Packet() (*packet, error) {
	b := recvBuffer
	n, err := c.recvConn.Read(b)
	if err != nil {
		return nil, err
	}
	if n < 20 {
		return nil, fmt.Errorf("IPHAConn.readIPv4Packet: Packet len %d is too small", n)
	} else if int(b[0])>>4 != 4 {
		return nil, fmt.Errorf("IPHAConn.readIPv4Packet: Expected an IPv4 packet")
	}
	hdrLen := (int(b[0]) & 0x0f) << 2
	if hdrLen > n {
		return nil, fmt.Errorf("IPHAConn.readIPv4Packet: Header len %d > total len %d", hdrLen, n)
	}
	return &packet{
		src:     net.IP{b[12], b[13], b[14], b[15]},
		dst:     net.IP{b[16], b[17], b[18], b[19]},
		ttl:     b[8],
		payload: b[hdrLen:n],
	}, nil
}
1182857
func (p *Packet) tcpDataDetach(optionLength uint16, dataLength uint16) (err error) {

	buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
	// Setup buffer for Options, Data and reduce the original buffer
	if dataLength != 0 {
		p.tcpHdr.tcpData = buffer[p.TCPDataStartBytes():]
	}

	if optionLength != 0 {
		p.tcpHdr.tcpOptions = buffer[p.TCPDataStartBytes()-optionLength : p.TCPDataStartBytes()]
	}

	p.ipHdr.Buffer = p.ipHdr.Buffer[:uint16(p.ipHdr.ipHeaderLen)+p.TCPDataStartBytes()-optionLength]

	return
}
198213
func (rc *RediffContext) OptimizePatch(patchReader savior.SeekSource, patchWriter io.Writer) error {
	var err error

	if rc.SourcePool == nil {
		return errors.WithStack(fmt.Errorf("SourcePool cannot be nil"))
	}

	if rc.TargetPool == nil {
		return errors.WithStack(fmt.Errorf("TargetPool cannot be nil"))
	}

	if rc.DiffMappings == nil {
		return errors.WithStack(fmt.Errorf("AnalyzePatch must be called before OptimizePatch"))
	}

	rctx := wire.NewReadContext(patchReader)
	wctx := wire.NewWriteContext(patchWriter)

	err = wctx.WriteMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	err = rctx.ExpectMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	ph := &PatchHeader{}
	err = rctx.ReadMessage(ph)
	if err != nil {
		return errors.WithStack(err)
	}

	compression := rc.Compression
	if compression == nil {
		compression = defaultRediffCompressionSettings()
	}

	wph := &PatchHeader{
		Compression: compression,
	}
	err = wctx.WriteMessage(wph)
	if err != nil {
		return errors.WithStack(err)
	}

	rctx, err = DecompressWire(rctx, ph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	wctx, err = CompressWire(wctx, wph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	targetContainer := &tlc.Container{}
	err = rctx.ReadMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wctx.WriteMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	sourceContainer := &tlc.Container{}
	err = rctx.ReadMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wctx.WriteMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}

	sh := &SyncHeader{}
	bh := &BsdiffHeader{}
	rop := &SyncOp{}

	bdc := &bsdiff.DiffContext{
		SuffixSortConcurrency: rc.SuffixSortConcurrency,
		Partitions:            rc.Partitions,
		Stats:                 rc.BsdiffStats,
		MeasureMem:            rc.MeasureMem,
	}

	if rc.Timeline != nil {
		rc.Timeline.Groups = append(rc.Timeline.Groups, TimelineGroup{
			ID:      0,
			Content: "Worker",
		})
	}

	initialStart := time.Now()
	bconsumer := &state.Consumer{}

	var biggestSourceFile int64
	var totalRediffSize int64

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		if _, ok := rc.DiffMappings[int64(sourceFileIndex)]; ok {
			if sourceFile.Size > biggestSourceFile {
				biggestSourceFile = sourceFile.Size
			}

			totalRediffSize += sourceFile.Size
		}
	}

	var doneSize int64

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		sh.Reset()
		err = rctx.ReadMessage(sh)
		if err != nil {
			return errors.WithStack(err)
		}

		if sh.FileIndex != int64(sourceFileIndex) {
			return errors.WithStack(fmt.Errorf("Malformed patch, expected index %d, got %d", sourceFileIndex, sh.FileIndex))
		}

		diffMapping := rc.DiffMappings[int64(sourceFileIndex)]

		if diffMapping == nil {
			// if no mapping, just copy ops straight up
			err = wctx.WriteMessage(sh)
			if err != nil {
				return errors.WithStack(err)
			}

			for {
				rop.Reset()
				err = rctx.ReadMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}

				if rop.Type == SyncOp_HEY_YOU_DID_IT {
					break
				}

				err = wctx.WriteMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}
			}
		} else {
			// signal bsdiff start to patcher
			sh.Reset()
			sh.FileIndex = int64(sourceFileIndex)
			sh.Type = SyncHeader_BSDIFF
			err = wctx.WriteMessage(sh)
			if err != nil {
				return errors.WithStack(err)
			}

			bh.Reset()
			bh.TargetIndex = diffMapping.TargetIndex
			err = wctx.WriteMessage(bh)
			if err != nil {
				return errors.WithStack(err)
			}

			// throw away old ops
			for {
				err = rctx.ReadMessage(rop)
				if err != nil {
					return errors.WithStack(err)
				}

				if rop.Type == SyncOp_HEY_YOU_DID_IT {
					break
				}
			}

			// then bsdiff
			sourceFileReader, err := rc.SourcePool.GetReadSeeker(int64(sourceFileIndex))
			if err != nil {
				return errors.WithStack(err)
			}

			targetFileReader, err := rc.TargetPool.GetReadSeeker(diffMapping.TargetIndex)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf(">%s", sourceFile.Path))

			_, err = sourceFileReader.Seek(0, io.SeekStart)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf("<%s", sourceFile.Path))

			_, err = targetFileReader.Seek(0, io.SeekStart)
			if err != nil {
				return errors.WithStack(err)
			}

			rc.Consumer.ProgressLabel(fmt.Sprintf("*%s", sourceFile.Path))

			startTime := time.Now()

			err = bdc.Do(targetFileReader, sourceFileReader, wctx.WriteMessage, bconsumer)

			endTime := time.Now()

			if rc.Timeline != nil {
				heat := int(float64(sourceFile.Size) / float64(biggestSourceFile) * 240.0)
				rc.Timeline.Items = append(rc.Timeline.Items, TimelineItem{
					Content: filepath.Base(sourceFile.Path),
					Style:   fmt.Sprintf("background-color: hsl(%d, 100%%, 50%%)", heat),
					Title:   fmt.Sprintf("%s %s", progress.FormatBytes(sourceFile.Size), sourceFile.Path),
					Start:   startTime.Sub(initialStart).Seconds(),
					End:     endTime.Sub(initialStart).Seconds(),
					Group:   0,
				})
			}

			doneSize += sourceFile.Size
		}

		// and don't forget to indicate success
		rop.Reset()
		rop.Type = SyncOp_HEY_YOU_DID_IT

		err = wctx.WriteMessage(rop)
		if err != nil {
			return errors.WithStack(err)
		}

		rc.Consumer.Progress(float64(doneSize) / float64(totalRediffSize))
	}

	err = wctx.Close()
	if err != nil {
		return errors.WithStack(err)
	}

	return nil
}
1253764
func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
	originalDoc := map[string]interface{}{}
	modifiedDoc := map[string]interface{}{}

	err := json.Unmarshal(originalJSON, &originalDoc)
	if err != nil {
		return nil, errBadJSONDoc
	}

	err = json.Unmarshal(modifiedJSON, &modifiedDoc)
	if err != nil {
		return nil, errBadJSONDoc
	}

	dest, err := getDiff(originalDoc, modifiedDoc)
	if err != nil {
		return nil, err
	}

	return json.Marshal(dest)
}
1139432
func WrapPacketConn(pc net.PacketConn) (PacketConn, error) {
	laddr, err := FromNetAddr(pc.LocalAddr())
	if err != nil {
		return nil, err
	}

	return &maPacketConn{
		PacketConn: pc,
		laddr:      laddr,
	}, nil
}
630181
func CreateStrategicMergePatch(original, modified []byte, dataStruct interface{}) ([]byte, error) {
	return CreateTwoWayMergePatch(original, modified, dataStruct)
}
163016
func (s *UDPSession) packetInput(data []byte) {
	dataValid := false
	if s.block != nil {
		s.block.Decrypt(data, data)
		data = data[nonceSize:]
		checksum := crc32.ChecksumIEEE(data[crcSize:])
		if checksum == binary.LittleEndian.Uint32(data) {
			data = data[crcSize:]
			dataValid = true
		} else {
			atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
		}
	} else if s.block == nil {
		dataValid = true
	}

	if dataValid {
		s.kcpInput(data)
	}
}
399138
func (u *Update) ApplyPatch(patchType PatchType) *Update {
	u.PatchType = patchType
	return u
}
1263120
func (m *RouteMux) Patch(pattern string, handler http.HandlerFunc) {
	m.AddRoute(PATCH, pattern, handler)
}
893565
func MakePatchProfileEndpoint(s Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(patchProfileRequest)
		e := s.PatchProfile(ctx, req.ID, req.Profile)
		return patchProfileResponse{Err: e}, nil
	}
}
962374
func (l *Listener) packetInput(data []byte, addr net.Addr) {
	dataValid := false
	if l.block != nil {
		l.block.Decrypt(data, data)
		data = data[nonceSize:]
		checksum := crc32.ChecksumIEEE(data[crcSize:])
		if checksum == binary.LittleEndian.Uint32(data) {
			data = data[crcSize:]
			dataValid = true
		} else {
			atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
		}
	} else if l.block == nil {
		dataValid = true
	}

	if dataValid {
		l.sessionLock.Lock()
		s, ok := l.sessions[addr.String()]
		l.sessionLock.Unlock()

		if !ok { // new address:port
			if len(l.chAccepts) < cap(l.chAccepts) { // do not let the new sessions overwhelm accept queue
				var conv uint32
				convValid := false
				if l.fecDecoder != nil {
					isfec := binary.LittleEndian.Uint16(data[4:])
					if isfec == typeData {
						conv = binary.LittleEndian.Uint32(data[fecHeaderSizePlus2:])
						convValid = true
					}
				} else {
					conv = binary.LittleEndian.Uint32(data)
					convValid = true
				}

				if convValid { // creates a new session only if the 'conv' field in kcp is accessible
					s := newUDPSession(conv, l.dataShards, l.parityShards, l, l.conn, addr, l.block)
					s.kcpInput(data)
					l.sessionLock.Lock()
					l.sessions[addr.String()] = s
					l.sessionLock.Unlock()
					l.chAccepts <- s
				}
			}
		} else {
			s.kcpInput(data)
		}
	}
}
225768
func (s *Server) Patch(ctx context.Context, q *ApplicationPatchRequest) (*appv1.Application, error) {

	patch, err := jsonpatch.DecodePatch([]byte(q.Patch))
	if err != nil {
		return nil, err
	}

	app, err := s.appclientset.ArgoprojV1alpha1().Applications(s.ns).Get(*q.Name, metav1.GetOptions{})
	if err != nil {
		return nil, err
	}

	if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, rbacpolicy.ActionUpdate, appRBACName(*app)); err != nil {
		return nil, err
	}

	jsonApp, err := json.Marshal(app)
	if err != nil {
		return nil, err
	}

	patchApp, err := patch.Apply(jsonApp)
	if err != nil {
		return nil, err
	}

	s.logEvent(app, ctx, argo.EventReasonResourceUpdated, fmt.Sprintf("patched application %s/%s", app.Namespace, app.Name))

	err = json.Unmarshal(patchApp, &app)
	if err != nil {
		return nil, err
	}

	err = s.validateAndNormalizeApp(ctx, app)
	if err != nil {
		return nil, err
	}

	return s.appclientset.ArgoprojV1alpha1().Applications(s.ns).Update(app)
}
1270200
func GetApplyPatch(obj runtime.Unstructured) ([]byte, []byte, types.PatchType, error) {
	beforeJSON, err := encodeToJSON(obj)
	if err != nil {
		return nil, []byte(""), types.MergePatchType, err
	}
	objCopy := obj.DeepCopyObject()
	accessor := meta.NewAccessor()
	annotations, err := accessor.Annotations(objCopy)
	if err != nil {
		return nil, beforeJSON, types.MergePatchType, err
	}
	if annotations == nil {
		annotations = map[string]string{}
	}
	annotations[corev1.LastAppliedConfigAnnotation] = string(beforeJSON)
	accessor.SetAnnotations(objCopy, annotations)
	afterJSON, err := encodeToJSON(objCopy.(runtime.Unstructured))
	if err != nil {
		return nil, beforeJSON, types.MergePatchType, err
	}
	patch, err := jsonpatch.CreateMergePatch(beforeJSON, afterJSON)
	return patch, beforeJSON, types.MergePatchType, err
}
565199
func (g *routeGroup) Patch(path string, h http.HandlerFunc) {
	g.handle(http.MethodPatch, path, h)
}
129500
func (s *Server) ServePacket(p net.PacketConn) error {
	s.m.Lock()
	s.server[udp] = &dns.Server{PacketConn: p, Net: "udp", Handler: dns.HandlerFunc(func(w dns.ResponseWriter, r *dns.Msg) {
		ctx := context.WithValue(context.Background(), Key{}, s)
		s.ServeDNS(ctx, w, r)
	})}
	s.m.Unlock()

	return s.server[udp].ActivateAndServe()
}
435627
func (m *MockSentPacketHandler) DequeuePacketForRetransmission() *ackhandler.Packet {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "DequeuePacketForRetransmission")
	ret0, _ := ret[0].(*ackhandler.Packet)
	return ret0
}