repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
google/netstack
tcpip/link/sharedmem/queue/tx.go
Enqueue
func (t *Tx) Enqueue(id uint64, totalDataLen, bufferCount uint32, buffer *TxBuffer) bool { // Reserve room in the tx pipe. totalLen := sizeOfPacketHeader + uint64(bufferCount)*sizeOfBufferDescriptor b := t.tx.Push(totalLen) if b == nil { return false } // Initialize the packet and buffer descriptors. binary.LittleEndian.PutUint64(b[packetID:], id) binary.LittleEndian.PutUint32(b[packetSize:], totalDataLen) binary.LittleEndian.PutUint32(b[packetReserved:], 0) offset := sizeOfPacketHeader for i := bufferCount; i != 0; i-- { binary.LittleEndian.PutUint64(b[offset+bufferOffset:], buffer.Offset) binary.LittleEndian.PutUint32(b[offset+bufferSize:], buffer.Size) offset += sizeOfBufferDescriptor buffer = buffer.Next } t.tx.Flush() return true }
go
func (t *Tx) Enqueue(id uint64, totalDataLen, bufferCount uint32, buffer *TxBuffer) bool { // Reserve room in the tx pipe. totalLen := sizeOfPacketHeader + uint64(bufferCount)*sizeOfBufferDescriptor b := t.tx.Push(totalLen) if b == nil { return false } // Initialize the packet and buffer descriptors. binary.LittleEndian.PutUint64(b[packetID:], id) binary.LittleEndian.PutUint32(b[packetSize:], totalDataLen) binary.LittleEndian.PutUint32(b[packetReserved:], 0) offset := sizeOfPacketHeader for i := bufferCount; i != 0; i-- { binary.LittleEndian.PutUint64(b[offset+bufferOffset:], buffer.Offset) binary.LittleEndian.PutUint32(b[offset+bufferSize:], buffer.Size) offset += sizeOfBufferDescriptor buffer = buffer.Next } t.tx.Flush() return true }
[ "func", "(", "t", "*", "Tx", ")", "Enqueue", "(", "id", "uint64", ",", "totalDataLen", ",", "bufferCount", "uint32", ",", "buffer", "*", "TxBuffer", ")", "bool", "{", "totalLen", ":=", "sizeOfPacketHeader", "+", "uint64", "(", "bufferCount", ")", "*", "sizeOfBufferDescriptor", "\n", "b", ":=", "t", ".", "tx", ".", "Push", "(", "totalLen", ")", "\n", "if", "b", "==", "nil", "{", "return", "false", "\n", "}", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "b", "[", "packetID", ":", "]", ",", "id", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "b", "[", "packetSize", ":", "]", ",", "totalDataLen", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "b", "[", "packetReserved", ":", "]", ",", "0", ")", "\n", "offset", ":=", "sizeOfPacketHeader", "\n", "for", "i", ":=", "bufferCount", ";", "i", "!=", "0", ";", "i", "--", "{", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "b", "[", "offset", "+", "bufferOffset", ":", "]", ",", "buffer", ".", "Offset", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "b", "[", "offset", "+", "bufferSize", ":", "]", ",", "buffer", ".", "Size", ")", "\n", "offset", "+=", "sizeOfBufferDescriptor", "\n", "buffer", "=", "buffer", ".", "Next", "\n", "}", "\n", "t", ".", "tx", ".", "Flush", "(", ")", "\n", "return", "true", "\n", "}" ]
// Enqueue queues the given linked list of buffers for transmission as one // packet. While it is queued, the caller must not modify them.
[ "Enqueue", "queues", "the", "given", "linked", "list", "of", "buffers", "for", "transmission", "as", "one", "packet", ".", "While", "it", "is", "queued", "the", "caller", "must", "not", "modify", "them", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/queue/tx.go#L64-L89
train
google/netstack
tcpip/link/sharedmem/queue/tx.go
DecodeTxPacketHeader
func DecodeTxPacketHeader(b []byte) TxPacketInfo { return TxPacketInfo{ ID: binary.LittleEndian.Uint64(b[packetID:]), Size: binary.LittleEndian.Uint32(b[packetSize:]), Reserved: binary.LittleEndian.Uint32(b[packetReserved:]), BufferCount: (len(b) - sizeOfPacketHeader) / sizeOfBufferDescriptor, } }
go
func DecodeTxPacketHeader(b []byte) TxPacketInfo { return TxPacketInfo{ ID: binary.LittleEndian.Uint64(b[packetID:]), Size: binary.LittleEndian.Uint32(b[packetSize:]), Reserved: binary.LittleEndian.Uint32(b[packetReserved:]), BufferCount: (len(b) - sizeOfPacketHeader) / sizeOfBufferDescriptor, } }
[ "func", "DecodeTxPacketHeader", "(", "b", "[", "]", "byte", ")", "TxPacketInfo", "{", "return", "TxPacketInfo", "{", "ID", ":", "binary", ".", "LittleEndian", ".", "Uint64", "(", "b", "[", "packetID", ":", "]", ")", ",", "Size", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "b", "[", "packetSize", ":", "]", ")", ",", "Reserved", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "b", "[", "packetReserved", ":", "]", ")", ",", "BufferCount", ":", "(", "len", "(", "b", ")", "-", "sizeOfPacketHeader", ")", "/", "sizeOfBufferDescriptor", ",", "}", "\n", "}" ]
// DecodeTxPacketHeader decodes the header of a packet sent over a tx queue.
[ "DecodeTxPacketHeader", "decodes", "the", "header", "of", "a", "packet", "sent", "over", "a", "tx", "queue", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/queue/tx.go#L129-L136
train
google/netstack
tcpip/link/sharedmem/queue/tx.go
DecodeTxBufferHeader
func DecodeTxBufferHeader(b []byte, i int) TxBuffer { b = b[sizeOfPacketHeader+i*sizeOfBufferDescriptor:] return TxBuffer{ Offset: binary.LittleEndian.Uint64(b[bufferOffset:]), Size: binary.LittleEndian.Uint32(b[bufferSize:]), } }
go
func DecodeTxBufferHeader(b []byte, i int) TxBuffer { b = b[sizeOfPacketHeader+i*sizeOfBufferDescriptor:] return TxBuffer{ Offset: binary.LittleEndian.Uint64(b[bufferOffset:]), Size: binary.LittleEndian.Uint32(b[bufferSize:]), } }
[ "func", "DecodeTxBufferHeader", "(", "b", "[", "]", "byte", ",", "i", "int", ")", "TxBuffer", "{", "b", "=", "b", "[", "sizeOfPacketHeader", "+", "i", "*", "sizeOfBufferDescriptor", ":", "]", "\n", "return", "TxBuffer", "{", "Offset", ":", "binary", ".", "LittleEndian", ".", "Uint64", "(", "b", "[", "bufferOffset", ":", "]", ")", ",", "Size", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "b", "[", "bufferSize", ":", "]", ")", ",", "}", "\n", "}" ]
// DecodeTxBufferHeader decodes the header of the i-th buffer of a packet sent // over a tx queue.
[ "DecodeTxBufferHeader", "decodes", "the", "header", "of", "the", "i", "-", "th", "buffer", "of", "a", "packet", "sent", "over", "a", "tx", "queue", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/queue/tx.go#L140-L146
train
google/netstack
tcpip/link/sharedmem/queue/tx.go
EncodeTxCompletion
func EncodeTxCompletion(b []byte, id uint64) { binary.LittleEndian.PutUint64(b, id) }
go
func EncodeTxCompletion(b []byte, id uint64) { binary.LittleEndian.PutUint64(b, id) }
[ "func", "EncodeTxCompletion", "(", "b", "[", "]", "byte", ",", "id", "uint64", ")", "{", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "b", ",", "id", ")", "\n", "}" ]
// EncodeTxCompletion encodes a tx completion header.
[ "EncodeTxCompletion", "encodes", "a", "tx", "completion", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/queue/tx.go#L149-L151
train
google/netstack
tcpip/header/arp.go
SetOp
func (a ARP) SetOp(op ARPOp) { a[6] = uint8(op >> 8) a[7] = uint8(op) }
go
func (a ARP) SetOp(op ARPOp) { a[6] = uint8(op >> 8) a[7] = uint8(op) }
[ "func", "(", "a", "ARP", ")", "SetOp", "(", "op", "ARPOp", ")", "{", "a", "[", "6", "]", "=", "uint8", "(", "op", ">>", "8", ")", "\n", "a", "[", "7", "]", "=", "uint8", "(", "op", ")", "\n", "}" ]
// SetOp sets the ARP opcode.
[ "SetOp", "sets", "the", "ARP", "opcode", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/arp.go#L48-L51
train
google/netstack
tcpip/header/arp.go
SetIPv4OverEthernet
func (a ARP) SetIPv4OverEthernet() { a[0], a[1] = 0, 1 // htypeEthernet a[2], a[3] = 0x08, 0x00 // IPv4ProtocolNumber a[4] = 6 // macSize a[5] = uint8(IPv4AddressSize) }
go
func (a ARP) SetIPv4OverEthernet() { a[0], a[1] = 0, 1 // htypeEthernet a[2], a[3] = 0x08, 0x00 // IPv4ProtocolNumber a[4] = 6 // macSize a[5] = uint8(IPv4AddressSize) }
[ "func", "(", "a", "ARP", ")", "SetIPv4OverEthernet", "(", ")", "{", "a", "[", "0", "]", ",", "a", "[", "1", "]", "=", "0", ",", "1", "\n", "a", "[", "2", "]", ",", "a", "[", "3", "]", "=", "0x08", ",", "0x00", "\n", "a", "[", "4", "]", "=", "6", "\n", "a", "[", "5", "]", "=", "uint8", "(", "IPv4AddressSize", ")", "\n", "}" ]
// SetIPv4OverEthernet configures the ARP packet for IPv4-over-Ethernet.
[ "SetIPv4OverEthernet", "configures", "the", "ARP", "packet", "for", "IPv4", "-", "over", "-", "Ethernet", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/arp.go#L54-L59
train
google/netstack
tcpip/header/arp.go
IsValid
func (a ARP) IsValid() bool { if len(a) < ARPSize { return false } const htypeEthernet = 1 const macSize = 6 return a.hardwareAddressSpace() == htypeEthernet && a.protocolAddressSpace() == uint16(IPv4ProtocolNumber) && a.hardwareAddressSize() == macSize && a.protocolAddressSize() == IPv4AddressSize }
go
func (a ARP) IsValid() bool { if len(a) < ARPSize { return false } const htypeEthernet = 1 const macSize = 6 return a.hardwareAddressSpace() == htypeEthernet && a.protocolAddressSpace() == uint16(IPv4ProtocolNumber) && a.hardwareAddressSize() == macSize && a.protocolAddressSize() == IPv4AddressSize }
[ "func", "(", "a", "ARP", ")", "IsValid", "(", ")", "bool", "{", "if", "len", "(", "a", ")", "<", "ARPSize", "{", "return", "false", "\n", "}", "\n", "const", "htypeEthernet", "=", "1", "\n", "const", "macSize", "=", "6", "\n", "return", "a", ".", "hardwareAddressSpace", "(", ")", "==", "htypeEthernet", "&&", "a", ".", "protocolAddressSpace", "(", ")", "==", "uint16", "(", "IPv4ProtocolNumber", ")", "&&", "a", ".", "hardwareAddressSize", "(", ")", "==", "macSize", "&&", "a", ".", "protocolAddressSize", "(", ")", "==", "IPv4AddressSize", "\n", "}" ]
// IsValid reports whether this is an ARP packet for IPv4 over Ethernet.
[ "IsValid", "reports", "whether", "this", "is", "an", "ARP", "packet", "for", "IPv4", "over", "Ethernet", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/arp.go#L90-L100
train
google/netstack
tcpip/network/ipv4/ipv4.go
NewEndpoint
func (p *protocol) NewEndpoint(nicid tcpip.NICID, addr tcpip.Address, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) { e := &endpoint{ nicid: nicid, id: stack.NetworkEndpointID{LocalAddress: addr}, linkEP: linkEP, dispatcher: dispatcher, fragmentation: fragmentation.NewFragmentation(fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout), } return e, nil }
go
func (p *protocol) NewEndpoint(nicid tcpip.NICID, addr tcpip.Address, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) { e := &endpoint{ nicid: nicid, id: stack.NetworkEndpointID{LocalAddress: addr}, linkEP: linkEP, dispatcher: dispatcher, fragmentation: fragmentation.NewFragmentation(fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout), } return e, nil }
[ "func", "(", "p", "*", "protocol", ")", "NewEndpoint", "(", "nicid", "tcpip", ".", "NICID", ",", "addr", "tcpip", ".", "Address", ",", "linkAddrCache", "stack", ".", "LinkAddressCache", ",", "dispatcher", "stack", ".", "TransportDispatcher", ",", "linkEP", "stack", ".", "LinkEndpoint", ")", "(", "stack", ".", "NetworkEndpoint", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ":=", "&", "endpoint", "{", "nicid", ":", "nicid", ",", "id", ":", "stack", ".", "NetworkEndpointID", "{", "LocalAddress", ":", "addr", "}", ",", "linkEP", ":", "linkEP", ",", "dispatcher", ":", "dispatcher", ",", "fragmentation", ":", "fragmentation", ".", "NewFragmentation", "(", "fragmentation", ".", "HighFragThreshold", ",", "fragmentation", ".", "LowFragThreshold", ",", "fragmentation", ".", "DefaultReassembleTimeout", ")", ",", "}", "\n", "return", "e", ",", "nil", "\n", "}" ]
// NewEndpoint creates a new ipv4 endpoint.
[ "NewEndpoint", "creates", "a", "new", "ipv4", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/ipv4/ipv4.go#L58-L68
train
google/netstack
tcpip/network/ipv4/ipv4.go
HandlePacket
func (e *endpoint) HandlePacket(r *stack.Route, vv buffer.VectorisedView) { headerView := vv.First() h := header.IPv4(headerView) if !h.IsValid(vv.Size()) { return } hlen := int(h.HeaderLength()) tlen := int(h.TotalLength()) vv.TrimFront(hlen) vv.CapLength(tlen - hlen) more := (h.Flags() & header.IPv4FlagMoreFragments) != 0 if more || h.FragmentOffset() != 0 { // The packet is a fragment, let's try to reassemble it. last := h.FragmentOffset() + uint16(vv.Size()) - 1 var ready bool vv, ready = e.fragmentation.Process(hash.IPv4FragmentHash(h), h.FragmentOffset(), last, more, vv) if !ready { return } } p := h.TransportProtocol() if p == header.ICMPv4ProtocolNumber { headerView.CapLength(hlen) e.handleICMP(r, headerView, vv) return } r.Stats().IP.PacketsDelivered.Increment() e.dispatcher.DeliverTransportPacket(r, p, headerView, vv) }
go
func (e *endpoint) HandlePacket(r *stack.Route, vv buffer.VectorisedView) { headerView := vv.First() h := header.IPv4(headerView) if !h.IsValid(vv.Size()) { return } hlen := int(h.HeaderLength()) tlen := int(h.TotalLength()) vv.TrimFront(hlen) vv.CapLength(tlen - hlen) more := (h.Flags() & header.IPv4FlagMoreFragments) != 0 if more || h.FragmentOffset() != 0 { // The packet is a fragment, let's try to reassemble it. last := h.FragmentOffset() + uint16(vv.Size()) - 1 var ready bool vv, ready = e.fragmentation.Process(hash.IPv4FragmentHash(h), h.FragmentOffset(), last, more, vv) if !ready { return } } p := h.TransportProtocol() if p == header.ICMPv4ProtocolNumber { headerView.CapLength(hlen) e.handleICMP(r, headerView, vv) return } r.Stats().IP.PacketsDelivered.Increment() e.dispatcher.DeliverTransportPacket(r, p, headerView, vv) }
[ "func", "(", "e", "*", "endpoint", ")", "HandlePacket", "(", "r", "*", "stack", ".", "Route", ",", "vv", "buffer", ".", "VectorisedView", ")", "{", "headerView", ":=", "vv", ".", "First", "(", ")", "\n", "h", ":=", "header", ".", "IPv4", "(", "headerView", ")", "\n", "if", "!", "h", ".", "IsValid", "(", "vv", ".", "Size", "(", ")", ")", "{", "return", "\n", "}", "\n", "hlen", ":=", "int", "(", "h", ".", "HeaderLength", "(", ")", ")", "\n", "tlen", ":=", "int", "(", "h", ".", "TotalLength", "(", ")", ")", "\n", "vv", ".", "TrimFront", "(", "hlen", ")", "\n", "vv", ".", "CapLength", "(", "tlen", "-", "hlen", ")", "\n", "more", ":=", "(", "h", ".", "Flags", "(", ")", "&", "header", ".", "IPv4FlagMoreFragments", ")", "!=", "0", "\n", "if", "more", "||", "h", ".", "FragmentOffset", "(", ")", "!=", "0", "{", "last", ":=", "h", ".", "FragmentOffset", "(", ")", "+", "uint16", "(", "vv", ".", "Size", "(", ")", ")", "-", "1", "\n", "var", "ready", "bool", "\n", "vv", ",", "ready", "=", "e", ".", "fragmentation", ".", "Process", "(", "hash", ".", "IPv4FragmentHash", "(", "h", ")", ",", "h", ".", "FragmentOffset", "(", ")", ",", "last", ",", "more", ",", "vv", ")", "\n", "if", "!", "ready", "{", "return", "\n", "}", "\n", "}", "\n", "p", ":=", "h", ".", "TransportProtocol", "(", ")", "\n", "if", "p", "==", "header", ".", "ICMPv4ProtocolNumber", "{", "headerView", ".", "CapLength", "(", "hlen", ")", "\n", "e", ".", "handleICMP", "(", "r", ",", "headerView", ",", "vv", ")", "\n", "return", "\n", "}", "\n", "r", ".", "Stats", "(", ")", ".", "IP", ".", "PacketsDelivered", ".", "Increment", "(", ")", "\n", "e", ".", "dispatcher", ".", "DeliverTransportPacket", "(", "r", ",", "p", ",", "headerView", ",", "vv", ")", "\n", "}" ]
// HandlePacket is called by the link layer when new ipv4 packets arrive for // this endpoint.
[ "HandlePacket", "is", "called", "by", "the", "link", "layer", "when", "new", "ipv4", "packets", "arrive", "for", "this", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/ipv4/ipv4.go#L148-L178
train
google/netstack
tcpip/network/ipv4/ipv4.go
ParseAddresses
func (*protocol) ParseAddresses(v buffer.View) (src, dst tcpip.Address) { h := header.IPv4(v) return h.SourceAddress(), h.DestinationAddress() }
go
func (*protocol) ParseAddresses(v buffer.View) (src, dst tcpip.Address) { h := header.IPv4(v) return h.SourceAddress(), h.DestinationAddress() }
[ "func", "(", "*", "protocol", ")", "ParseAddresses", "(", "v", "buffer", ".", "View", ")", "(", "src", ",", "dst", "tcpip", ".", "Address", ")", "{", "h", ":=", "header", ".", "IPv4", "(", "v", ")", "\n", "return", "h", ".", "SourceAddress", "(", ")", ",", "h", ".", "DestinationAddress", "(", ")", "\n", "}" ]
// ParseAddresses implements NetworkProtocol.ParseAddresses.
[ "ParseAddresses", "implements", "NetworkProtocol", ".", "ParseAddresses", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/ipv4/ipv4.go#L204-L207
train
google/netstack
tcpip/transport/tcp/rcv.go
acceptable
func (r *receiver) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool { rcvWnd := r.rcvNxt.Size(r.rcvAcc) if rcvWnd == 0 { return segLen == 0 && segSeq == r.rcvNxt } return segSeq.InWindow(r.rcvNxt, rcvWnd) || seqnum.Overlap(r.rcvNxt, rcvWnd, segSeq, segLen) }
go
func (r *receiver) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool { rcvWnd := r.rcvNxt.Size(r.rcvAcc) if rcvWnd == 0 { return segLen == 0 && segSeq == r.rcvNxt } return segSeq.InWindow(r.rcvNxt, rcvWnd) || seqnum.Overlap(r.rcvNxt, rcvWnd, segSeq, segLen) }
[ "func", "(", "r", "*", "receiver", ")", "acceptable", "(", "segSeq", "seqnum", ".", "Value", ",", "segLen", "seqnum", ".", "Size", ")", "bool", "{", "rcvWnd", ":=", "r", ".", "rcvNxt", ".", "Size", "(", "r", ".", "rcvAcc", ")", "\n", "if", "rcvWnd", "==", "0", "{", "return", "segLen", "==", "0", "&&", "segSeq", "==", "r", ".", "rcvNxt", "\n", "}", "\n", "return", "segSeq", ".", "InWindow", "(", "r", ".", "rcvNxt", ",", "rcvWnd", ")", "||", "seqnum", ".", "Overlap", "(", "r", ".", "rcvNxt", ",", "rcvWnd", ",", "segSeq", ",", "segLen", ")", "\n", "}" ]
// acceptable checks if the segment sequence number range is acceptable // according to the table on page 26 of RFC 793.
[ "acceptable", "checks", "if", "the", "segment", "sequence", "number", "range", "is", "acceptable", "according", "to", "the", "table", "on", "page", "26", "of", "RFC", "793", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/rcv.go#L62-L70
train
google/netstack
tcpip/transport/tcp/rcv.go
getSendParams
func (r *receiver) getSendParams() (rcvNxt seqnum.Value, rcvWnd seqnum.Size) { // Calculate the window size based on the current buffer size. n := r.ep.receiveBufferAvailable() acc := r.rcvNxt.Add(seqnum.Size(n)) if r.rcvAcc.LessThan(acc) { r.rcvAcc = acc } return r.rcvNxt, r.rcvNxt.Size(r.rcvAcc) >> r.rcvWndScale }
go
func (r *receiver) getSendParams() (rcvNxt seqnum.Value, rcvWnd seqnum.Size) { // Calculate the window size based on the current buffer size. n := r.ep.receiveBufferAvailable() acc := r.rcvNxt.Add(seqnum.Size(n)) if r.rcvAcc.LessThan(acc) { r.rcvAcc = acc } return r.rcvNxt, r.rcvNxt.Size(r.rcvAcc) >> r.rcvWndScale }
[ "func", "(", "r", "*", "receiver", ")", "getSendParams", "(", ")", "(", "rcvNxt", "seqnum", ".", "Value", ",", "rcvWnd", "seqnum", ".", "Size", ")", "{", "n", ":=", "r", ".", "ep", ".", "receiveBufferAvailable", "(", ")", "\n", "acc", ":=", "r", ".", "rcvNxt", ".", "Add", "(", "seqnum", ".", "Size", "(", "n", ")", ")", "\n", "if", "r", ".", "rcvAcc", ".", "LessThan", "(", "acc", ")", "{", "r", ".", "rcvAcc", "=", "acc", "\n", "}", "\n", "return", "r", ".", "rcvNxt", ",", "r", ".", "rcvNxt", ".", "Size", "(", "r", ".", "rcvAcc", ")", ">>", "r", ".", "rcvWndScale", "\n", "}" ]
// getSendParams returns the parameters needed by the sender when building // segments to send.
[ "getSendParams", "returns", "the", "parameters", "needed", "by", "the", "sender", "when", "building", "segments", "to", "send", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/rcv.go#L74-L83
train
google/netstack
tcpip/transport/tcp/rcv.go
nonZeroWindow
func (r *receiver) nonZeroWindow() { if (r.rcvAcc-r.rcvNxt)>>r.rcvWndScale != 0 { // We never got around to announcing a zero window size, so we // don't need to immediately announce a nonzero one. return } // Immediately send an ack. r.ep.snd.sendAck() }
go
func (r *receiver) nonZeroWindow() { if (r.rcvAcc-r.rcvNxt)>>r.rcvWndScale != 0 { // We never got around to announcing a zero window size, so we // don't need to immediately announce a nonzero one. return } // Immediately send an ack. r.ep.snd.sendAck() }
[ "func", "(", "r", "*", "receiver", ")", "nonZeroWindow", "(", ")", "{", "if", "(", "r", ".", "rcvAcc", "-", "r", ".", "rcvNxt", ")", ">>", "r", ".", "rcvWndScale", "!=", "0", "{", "return", "\n", "}", "\n", "r", ".", "ep", ".", "snd", ".", "sendAck", "(", ")", "\n", "}" ]
// nonZeroWindow is called when the receive window grows from zero to nonzero; // in such cases we may need to send an ack to indicate to our peer that it can // resume sending data.
[ "nonZeroWindow", "is", "called", "when", "the", "receive", "window", "grows", "from", "zero", "to", "nonzero", ";", "in", "such", "cases", "we", "may", "need", "to", "send", "an", "ack", "to", "indicate", "to", "our", "peer", "that", "it", "can", "resume", "sending", "data", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/rcv.go#L88-L97
train
google/netstack
tcpip/transport/tcp/rcv.go
consumeSegment
func (r *receiver) consumeSegment(s *segment, segSeq seqnum.Value, segLen seqnum.Size) bool { if segLen > 0 { // If the segment doesn't include the seqnum we're expecting to // consume now, we're missing a segment. We cannot proceed until // we receive that segment though. if !r.rcvNxt.InWindow(segSeq, segLen) { return false } // Trim segment to eliminate already acknowledged data. if segSeq.LessThan(r.rcvNxt) { diff := segSeq.Size(r.rcvNxt) segLen -= diff segSeq.UpdateForward(diff) s.sequenceNumber.UpdateForward(diff) s.data.TrimFront(int(diff)) } // Move segment to ready-to-deliver list. Wakeup any waiters. r.ep.readyToRead(s) } else if segSeq != r.rcvNxt { return false } // Update the segment that we're expecting to consume. r.rcvNxt = segSeq.Add(segLen) // Trim SACK Blocks to remove any SACK information that covers // sequence numbers that have been consumed. TrimSACKBlockList(&r.ep.sack, r.rcvNxt) if s.flagIsSet(header.TCPFlagFin) { r.rcvNxt++ // Send ACK immediately. r.ep.snd.sendAck() // Tell any readers that no more data will come. r.closed = true r.ep.readyToRead(nil) // Flush out any pending segments, except the very first one if // it happens to be the one we're handling now because the // caller is using it. first := 0 if len(r.pendingRcvdSegments) != 0 && r.pendingRcvdSegments[0] == s { first = 1 } for i := first; i < len(r.pendingRcvdSegments); i++ { r.pendingRcvdSegments[i].decRef() } r.pendingRcvdSegments = r.pendingRcvdSegments[:first] } return true }
go
func (r *receiver) consumeSegment(s *segment, segSeq seqnum.Value, segLen seqnum.Size) bool { if segLen > 0 { // If the segment doesn't include the seqnum we're expecting to // consume now, we're missing a segment. We cannot proceed until // we receive that segment though. if !r.rcvNxt.InWindow(segSeq, segLen) { return false } // Trim segment to eliminate already acknowledged data. if segSeq.LessThan(r.rcvNxt) { diff := segSeq.Size(r.rcvNxt) segLen -= diff segSeq.UpdateForward(diff) s.sequenceNumber.UpdateForward(diff) s.data.TrimFront(int(diff)) } // Move segment to ready-to-deliver list. Wakeup any waiters. r.ep.readyToRead(s) } else if segSeq != r.rcvNxt { return false } // Update the segment that we're expecting to consume. r.rcvNxt = segSeq.Add(segLen) // Trim SACK Blocks to remove any SACK information that covers // sequence numbers that have been consumed. TrimSACKBlockList(&r.ep.sack, r.rcvNxt) if s.flagIsSet(header.TCPFlagFin) { r.rcvNxt++ // Send ACK immediately. r.ep.snd.sendAck() // Tell any readers that no more data will come. r.closed = true r.ep.readyToRead(nil) // Flush out any pending segments, except the very first one if // it happens to be the one we're handling now because the // caller is using it. first := 0 if len(r.pendingRcvdSegments) != 0 && r.pendingRcvdSegments[0] == s { first = 1 } for i := first; i < len(r.pendingRcvdSegments); i++ { r.pendingRcvdSegments[i].decRef() } r.pendingRcvdSegments = r.pendingRcvdSegments[:first] } return true }
[ "func", "(", "r", "*", "receiver", ")", "consumeSegment", "(", "s", "*", "segment", ",", "segSeq", "seqnum", ".", "Value", ",", "segLen", "seqnum", ".", "Size", ")", "bool", "{", "if", "segLen", ">", "0", "{", "if", "!", "r", ".", "rcvNxt", ".", "InWindow", "(", "segSeq", ",", "segLen", ")", "{", "return", "false", "\n", "}", "\n", "if", "segSeq", ".", "LessThan", "(", "r", ".", "rcvNxt", ")", "{", "diff", ":=", "segSeq", ".", "Size", "(", "r", ".", "rcvNxt", ")", "\n", "segLen", "-=", "diff", "\n", "segSeq", ".", "UpdateForward", "(", "diff", ")", "\n", "s", ".", "sequenceNumber", ".", "UpdateForward", "(", "diff", ")", "\n", "s", ".", "data", ".", "TrimFront", "(", "int", "(", "diff", ")", ")", "\n", "}", "\n", "r", ".", "ep", ".", "readyToRead", "(", "s", ")", "\n", "}", "else", "if", "segSeq", "!=", "r", ".", "rcvNxt", "{", "return", "false", "\n", "}", "\n", "r", ".", "rcvNxt", "=", "segSeq", ".", "Add", "(", "segLen", ")", "\n", "TrimSACKBlockList", "(", "&", "r", ".", "ep", ".", "sack", ",", "r", ".", "rcvNxt", ")", "\n", "if", "s", ".", "flagIsSet", "(", "header", ".", "TCPFlagFin", ")", "{", "r", ".", "rcvNxt", "++", "\n", "r", ".", "ep", ".", "snd", ".", "sendAck", "(", ")", "\n", "r", ".", "closed", "=", "true", "\n", "r", ".", "ep", ".", "readyToRead", "(", "nil", ")", "\n", "first", ":=", "0", "\n", "if", "len", "(", "r", ".", "pendingRcvdSegments", ")", "!=", "0", "&&", "r", ".", "pendingRcvdSegments", "[", "0", "]", "==", "s", "{", "first", "=", "1", "\n", "}", "\n", "for", "i", ":=", "first", ";", "i", "<", "len", "(", "r", ".", "pendingRcvdSegments", ")", ";", "i", "++", "{", "r", ".", "pendingRcvdSegments", "[", "i", "]", ".", "decRef", "(", ")", "\n", "}", "\n", "r", ".", "pendingRcvdSegments", "=", "r", ".", "pendingRcvdSegments", "[", ":", "first", "]", "\n", "}", "\n", "return", "true", "\n", "}" ]
// consumeSegment attempts to consume a segment that was received by r. The // segment may have just been received or may have been received earlier but // wasn't ready to be consumed then. // // Returns true if the segment was consumed, false if it cannot be consumed // yet because of a missing segment.
[ "consumeSegment", "attempts", "to", "consume", "a", "segment", "that", "was", "received", "by", "r", ".", "The", "segment", "may", "have", "just", "been", "received", "or", "may", "have", "been", "received", "earlier", "but", "wasn", "t", "ready", "to", "be", "consumed", "then", ".", "Returns", "true", "if", "the", "segment", "was", "consumed", "false", "if", "it", "cannot", "be", "consumed", "yet", "because", "of", "a", "missing", "segment", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/rcv.go#L105-L162
train
google/netstack
tcpip/transport/tcp/rcv.go
handleRcvdSegment
func (r *receiver) handleRcvdSegment(s *segment) { // We don't care about receive processing anymore if the receive side // is closed. if r.closed { return } segLen := seqnum.Size(s.data.Size()) segSeq := s.sequenceNumber // If the sequence number range is outside the acceptable range, just // send an ACK. This is according to RFC 793, page 37. if !r.acceptable(segSeq, segLen) { r.ep.snd.sendAck() return } // Defer segment processing if it can't be consumed now. if !r.consumeSegment(s, segSeq, segLen) { if segLen > 0 || s.flagIsSet(header.TCPFlagFin) { // We only store the segment if it's within our buffer // size limit. if r.pendingBufUsed < r.pendingBufSize { r.pendingBufUsed += s.logicalLen() s.incRef() heap.Push(&r.pendingRcvdSegments, s) } UpdateSACKBlocks(&r.ep.sack, segSeq, segSeq.Add(segLen), r.rcvNxt) // Immediately send an ack so that the peer knows it may // have to retransmit. r.ep.snd.sendAck() } return } // By consuming the current segment, we may have filled a gap in the // sequence number domain that allows pending segments to be consumed // now. So try to do it. for !r.closed && r.pendingRcvdSegments.Len() > 0 { s := r.pendingRcvdSegments[0] segLen := seqnum.Size(s.data.Size()) segSeq := s.sequenceNumber // Skip segment altogether if it has already been acknowledged. if !segSeq.Add(segLen-1).LessThan(r.rcvNxt) && !r.consumeSegment(s, segSeq, segLen) { break } heap.Pop(&r.pendingRcvdSegments) r.pendingBufUsed -= s.logicalLen() s.decRef() } }
go
func (r *receiver) handleRcvdSegment(s *segment) { // We don't care about receive processing anymore if the receive side // is closed. if r.closed { return } segLen := seqnum.Size(s.data.Size()) segSeq := s.sequenceNumber // If the sequence number range is outside the acceptable range, just // send an ACK. This is according to RFC 793, page 37. if !r.acceptable(segSeq, segLen) { r.ep.snd.sendAck() return } // Defer segment processing if it can't be consumed now. if !r.consumeSegment(s, segSeq, segLen) { if segLen > 0 || s.flagIsSet(header.TCPFlagFin) { // We only store the segment if it's within our buffer // size limit. if r.pendingBufUsed < r.pendingBufSize { r.pendingBufUsed += s.logicalLen() s.incRef() heap.Push(&r.pendingRcvdSegments, s) } UpdateSACKBlocks(&r.ep.sack, segSeq, segSeq.Add(segLen), r.rcvNxt) // Immediately send an ack so that the peer knows it may // have to retransmit. r.ep.snd.sendAck() } return } // By consuming the current segment, we may have filled a gap in the // sequence number domain that allows pending segments to be consumed // now. So try to do it. for !r.closed && r.pendingRcvdSegments.Len() > 0 { s := r.pendingRcvdSegments[0] segLen := seqnum.Size(s.data.Size()) segSeq := s.sequenceNumber // Skip segment altogether if it has already been acknowledged. if !segSeq.Add(segLen-1).LessThan(r.rcvNxt) && !r.consumeSegment(s, segSeq, segLen) { break } heap.Pop(&r.pendingRcvdSegments) r.pendingBufUsed -= s.logicalLen() s.decRef() } }
[ "func", "(", "r", "*", "receiver", ")", "handleRcvdSegment", "(", "s", "*", "segment", ")", "{", "if", "r", ".", "closed", "{", "return", "\n", "}", "\n", "segLen", ":=", "seqnum", ".", "Size", "(", "s", ".", "data", ".", "Size", "(", ")", ")", "\n", "segSeq", ":=", "s", ".", "sequenceNumber", "\n", "if", "!", "r", ".", "acceptable", "(", "segSeq", ",", "segLen", ")", "{", "r", ".", "ep", ".", "snd", ".", "sendAck", "(", ")", "\n", "return", "\n", "}", "\n", "if", "!", "r", ".", "consumeSegment", "(", "s", ",", "segSeq", ",", "segLen", ")", "{", "if", "segLen", ">", "0", "||", "s", ".", "flagIsSet", "(", "header", ".", "TCPFlagFin", ")", "{", "if", "r", ".", "pendingBufUsed", "<", "r", ".", "pendingBufSize", "{", "r", ".", "pendingBufUsed", "+=", "s", ".", "logicalLen", "(", ")", "\n", "s", ".", "incRef", "(", ")", "\n", "heap", ".", "Push", "(", "&", "r", ".", "pendingRcvdSegments", ",", "s", ")", "\n", "}", "\n", "UpdateSACKBlocks", "(", "&", "r", ".", "ep", ".", "sack", ",", "segSeq", ",", "segSeq", ".", "Add", "(", "segLen", ")", ",", "r", ".", "rcvNxt", ")", "\n", "r", ".", "ep", ".", "snd", ".", "sendAck", "(", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "for", "!", "r", ".", "closed", "&&", "r", ".", "pendingRcvdSegments", ".", "Len", "(", ")", ">", "0", "{", "s", ":=", "r", ".", "pendingRcvdSegments", "[", "0", "]", "\n", "segLen", ":=", "seqnum", ".", "Size", "(", "s", ".", "data", ".", "Size", "(", ")", ")", "\n", "segSeq", ":=", "s", ".", "sequenceNumber", "\n", "if", "!", "segSeq", ".", "Add", "(", "segLen", "-", "1", ")", ".", "LessThan", "(", "r", ".", "rcvNxt", ")", "&&", "!", "r", ".", "consumeSegment", "(", "s", ",", "segSeq", ",", "segLen", ")", "{", "break", "\n", "}", "\n", "heap", ".", "Pop", "(", "&", "r", ".", "pendingRcvdSegments", ")", "\n", "r", ".", "pendingBufUsed", "-=", "s", ".", "logicalLen", "(", ")", "\n", "s", ".", "decRef", "(", ")", "\n", "}", "\n", "}" ]
// handleRcvdSegment handles TCP segments directed at the connection managed by // r as they arrive. It is called by the protocol main loop.
[ "handleRcvdSegment", "handles", "TCP", "segments", "directed", "at", "the", "connection", "managed", "by", "r", "as", "they", "arrive", ".", "It", "is", "called", "by", "the", "protocol", "main", "loop", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/rcv.go#L166-L221
train
google/netstack
dhcp/client.go
Address
func (c *Client) Address() tcpip.Address { c.mu.Lock() defer c.mu.Unlock() return c.addr }
go
func (c *Client) Address() tcpip.Address { c.mu.Lock() defer c.mu.Unlock() return c.addr }
[ "func", "(", "c", "*", "Client", ")", "Address", "(", ")", "tcpip", ".", "Address", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "addr", "\n", "}" ]
// Address reports the IP address acquired by the DHCP client.
[ "Address", "reports", "the", "IP", "address", "acquired", "by", "the", "DHCP", "client", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/dhcp/client.go#L104-L108
train
google/netstack
dhcp/client.go
Config
func (c *Client) Config() Config { c.mu.Lock() defer c.mu.Unlock() return c.cfg }
go
func (c *Client) Config() Config { c.mu.Lock() defer c.mu.Unlock() return c.cfg }
[ "func", "(", "c", "*", "Client", ")", "Config", "(", ")", "Config", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "cfg", "\n", "}" ]
// Config reports the DHCP configuration acquired with the IP address lease.
[ "Config", "reports", "the", "DHCP", "configuration", "acquired", "with", "the", "IP", "address", "lease", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/dhcp/client.go#L111-L115
train
google/netstack
tcpip/header/ipv4.go
IPVersion
func IPVersion(b []byte) int { // Length must be at least offset+length of version field. if len(b) < versIHL+1 { return -1 } return int(b[versIHL] >> 4) }
go
func IPVersion(b []byte) int { // Length must be at least offset+length of version field. if len(b) < versIHL+1 { return -1 } return int(b[versIHL] >> 4) }
[ "func", "IPVersion", "(", "b", "[", "]", "byte", ")", "int", "{", "if", "len", "(", "b", ")", "<", "versIHL", "+", "1", "{", "return", "-", "1", "\n", "}", "\n", "return", "int", "(", "b", "[", "versIHL", "]", ">>", "4", ")", "\n", "}" ]
// IPVersion returns the version of IP used in the given packet. It returns -1 // if the packet is not large enough to contain the version field.
[ "IPVersion", "returns", "the", "version", "of", "IP", "used", "in", "the", "given", "packet", ".", "It", "returns", "-", "1", "if", "the", "packet", "is", "not", "large", "enough", "to", "contain", "the", "version", "field", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L112-L118
train
google/netstack
tcpip/header/ipv4.go
Flags
func (b IPv4) Flags() uint8 { return uint8(binary.BigEndian.Uint16(b[flagsFO:]) >> 13) }
go
func (b IPv4) Flags() uint8 { return uint8(binary.BigEndian.Uint16(b[flagsFO:]) >> 13) }
[ "func", "(", "b", "IPv4", ")", "Flags", "(", ")", "uint8", "{", "return", "uint8", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "b", "[", "flagsFO", ":", "]", ")", ">>", "13", ")", "\n", "}" ]
// Flags returns the "flags" field of the ipv4 header.
[ "Flags", "returns", "the", "flags", "field", "of", "the", "ipv4", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L137-L139
train
google/netstack
tcpip/header/ipv4.go
SetTOS
func (b IPv4) SetTOS(v uint8, _ uint32) { b[tos] = v }
go
func (b IPv4) SetTOS(v uint8, _ uint32) { b[tos] = v }
[ "func", "(", "b", "IPv4", ")", "SetTOS", "(", "v", "uint8", ",", "_", "uint32", ")", "{", "b", "[", "tos", "]", "=", "v", "\n", "}" ]
// SetTOS sets the "type of service" field of the ipv4 header.
[ "SetTOS", "sets", "the", "type", "of", "service", "field", "of", "the", "ipv4", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L193-L195
train
google/netstack
tcpip/header/ipv4.go
SetTotalLength
func (b IPv4) SetTotalLength(totalLength uint16) { binary.BigEndian.PutUint16(b[totalLen:], totalLength) }
go
func (b IPv4) SetTotalLength(totalLength uint16) { binary.BigEndian.PutUint16(b[totalLen:], totalLength) }
[ "func", "(", "b", "IPv4", ")", "SetTotalLength", "(", "totalLength", "uint16", ")", "{", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "totalLen", ":", "]", ",", "totalLength", ")", "\n", "}" ]
// SetTotalLength sets the "total length" field of the ipv4 header.
[ "SetTotalLength", "sets", "the", "total", "length", "field", "of", "the", "ipv4", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L198-L200
train
google/netstack
tcpip/header/ipv4.go
SetChecksum
func (b IPv4) SetChecksum(v uint16) { binary.BigEndian.PutUint16(b[checksum:], v) }
go
func (b IPv4) SetChecksum(v uint16) { binary.BigEndian.PutUint16(b[checksum:], v) }
[ "func", "(", "b", "IPv4", ")", "SetChecksum", "(", "v", "uint16", ")", "{", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "checksum", ":", "]", ",", "v", ")", "\n", "}" ]
// SetChecksum sets the checksum field of the ipv4 header.
[ "SetChecksum", "sets", "the", "checksum", "field", "of", "the", "ipv4", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L203-L205
train
google/netstack
tcpip/header/ipv4.go
SetFlagsFragmentOffset
func (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16) { v := (uint16(flags) << 13) | (offset >> 3) binary.BigEndian.PutUint16(b[flagsFO:], v) }
go
func (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16) { v := (uint16(flags) << 13) | (offset >> 3) binary.BigEndian.PutUint16(b[flagsFO:], v) }
[ "func", "(", "b", "IPv4", ")", "SetFlagsFragmentOffset", "(", "flags", "uint8", ",", "offset", "uint16", ")", "{", "v", ":=", "(", "uint16", "(", "flags", ")", "<<", "13", ")", "|", "(", "offset", ">>", "3", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "flagsFO", ":", "]", ",", "v", ")", "\n", "}" ]
// SetFlagsFragmentOffset sets the "flags" and "fragment offset" fields of the // ipv4 header.
[ "SetFlagsFragmentOffset", "sets", "the", "flags", "and", "fragment", "offset", "fields", "of", "the", "ipv4", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L209-L212
train
google/netstack
tcpip/header/ipv4.go
SetID
func (b IPv4) SetID(v uint16) { binary.BigEndian.PutUint16(b[id:], v) }
go
func (b IPv4) SetID(v uint16) { binary.BigEndian.PutUint16(b[id:], v) }
[ "func", "(", "b", "IPv4", ")", "SetID", "(", "v", "uint16", ")", "{", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "id", ":", "]", ",", "v", ")", "\n", "}" ]
// SetID sets the identification field.
[ "SetID", "sets", "the", "identification", "field", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L215-L217
train
google/netstack
tcpip/header/ipv4.go
Encode
func (b IPv4) Encode(i *IPv4Fields) { b[versIHL] = (4 << 4) | ((i.IHL / 4) & 0xf) b[tos] = i.TOS b.SetTotalLength(i.TotalLength) binary.BigEndian.PutUint16(b[id:], i.ID) b.SetFlagsFragmentOffset(i.Flags, i.FragmentOffset) b[ttl] = i.TTL b[protocol] = i.Protocol b.SetChecksum(i.Checksum) copy(b[srcAddr:srcAddr+IPv4AddressSize], i.SrcAddr) copy(b[dstAddr:dstAddr+IPv4AddressSize], i.DstAddr) }
go
func (b IPv4) Encode(i *IPv4Fields) { b[versIHL] = (4 << 4) | ((i.IHL / 4) & 0xf) b[tos] = i.TOS b.SetTotalLength(i.TotalLength) binary.BigEndian.PutUint16(b[id:], i.ID) b.SetFlagsFragmentOffset(i.Flags, i.FragmentOffset) b[ttl] = i.TTL b[protocol] = i.Protocol b.SetChecksum(i.Checksum) copy(b[srcAddr:srcAddr+IPv4AddressSize], i.SrcAddr) copy(b[dstAddr:dstAddr+IPv4AddressSize], i.DstAddr) }
[ "func", "(", "b", "IPv4", ")", "Encode", "(", "i", "*", "IPv4Fields", ")", "{", "b", "[", "versIHL", "]", "=", "(", "4", "<<", "4", ")", "|", "(", "(", "i", ".", "IHL", "/", "4", ")", "&", "0xf", ")", "\n", "b", "[", "tos", "]", "=", "i", ".", "TOS", "\n", "b", ".", "SetTotalLength", "(", "i", ".", "TotalLength", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "id", ":", "]", ",", "i", ".", "ID", ")", "\n", "b", ".", "SetFlagsFragmentOffset", "(", "i", ".", "Flags", ",", "i", ".", "FragmentOffset", ")", "\n", "b", "[", "ttl", "]", "=", "i", ".", "TTL", "\n", "b", "[", "protocol", "]", "=", "i", ".", "Protocol", "\n", "b", ".", "SetChecksum", "(", "i", ".", "Checksum", ")", "\n", "copy", "(", "b", "[", "srcAddr", ":", "srcAddr", "+", "IPv4AddressSize", "]", ",", "i", ".", "SrcAddr", ")", "\n", "copy", "(", "b", "[", "dstAddr", ":", "dstAddr", "+", "IPv4AddressSize", "]", ",", "i", ".", "DstAddr", ")", "\n", "}" ]
// Encode encodes all the fields of the ipv4 header.
[ "Encode", "encodes", "all", "the", "fields", "of", "the", "ipv4", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L236-L247
train
google/netstack
tcpip/header/ipv4.go
EncodePartial
func (b IPv4) EncodePartial(partialChecksum, totalLength uint16) { b.SetTotalLength(totalLength) checksum := Checksum(b[totalLen:totalLen+2], partialChecksum) b.SetChecksum(^checksum) }
go
func (b IPv4) EncodePartial(partialChecksum, totalLength uint16) { b.SetTotalLength(totalLength) checksum := Checksum(b[totalLen:totalLen+2], partialChecksum) b.SetChecksum(^checksum) }
[ "func", "(", "b", "IPv4", ")", "EncodePartial", "(", "partialChecksum", ",", "totalLength", "uint16", ")", "{", "b", ".", "SetTotalLength", "(", "totalLength", ")", "\n", "checksum", ":=", "Checksum", "(", "b", "[", "totalLen", ":", "totalLen", "+", "2", "]", ",", "partialChecksum", ")", "\n", "b", ".", "SetChecksum", "(", "^", "checksum", ")", "\n", "}" ]
// EncodePartial updates the total length and checksum fields of ipv4 header, // taking in the partial checksum, which is the checksum of the header without // the total length and checksum fields. It is useful in cases when similar // packets are produced.
[ "EncodePartial", "updates", "the", "total", "length", "and", "checksum", "fields", "of", "ipv4", "header", "taking", "in", "the", "partial", "checksum", "which", "is", "the", "checksum", "of", "the", "header", "without", "the", "total", "length", "and", "checksum", "fields", ".", "It", "is", "useful", "in", "cases", "when", "similar", "packets", "are", "produced", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/ipv4.go#L253-L257
train
google/netstack
tcpip/network/fragmentation/reassembler.go
updateHoles
func (r *reassembler) updateHoles(first, last uint16, more bool) bool { used := false for i := range r.holes { if r.holes[i].deleted || first > r.holes[i].last || last < r.holes[i].first { continue } used = true r.deleted++ r.holes[i].deleted = true if first > r.holes[i].first { r.holes = append(r.holes, hole{r.holes[i].first, first - 1, false}) } if last < r.holes[i].last && more { r.holes = append(r.holes, hole{last + 1, r.holes[i].last, false}) } } return used }
go
func (r *reassembler) updateHoles(first, last uint16, more bool) bool { used := false for i := range r.holes { if r.holes[i].deleted || first > r.holes[i].last || last < r.holes[i].first { continue } used = true r.deleted++ r.holes[i].deleted = true if first > r.holes[i].first { r.holes = append(r.holes, hole{r.holes[i].first, first - 1, false}) } if last < r.holes[i].last && more { r.holes = append(r.holes, hole{last + 1, r.holes[i].last, false}) } } return used }
[ "func", "(", "r", "*", "reassembler", ")", "updateHoles", "(", "first", ",", "last", "uint16", ",", "more", "bool", ")", "bool", "{", "used", ":=", "false", "\n", "for", "i", ":=", "range", "r", ".", "holes", "{", "if", "r", ".", "holes", "[", "i", "]", ".", "deleted", "||", "first", ">", "r", ".", "holes", "[", "i", "]", ".", "last", "||", "last", "<", "r", ".", "holes", "[", "i", "]", ".", "first", "{", "continue", "\n", "}", "\n", "used", "=", "true", "\n", "r", ".", "deleted", "++", "\n", "r", ".", "holes", "[", "i", "]", ".", "deleted", "=", "true", "\n", "if", "first", ">", "r", ".", "holes", "[", "i", "]", ".", "first", "{", "r", ".", "holes", "=", "append", "(", "r", ".", "holes", ",", "hole", "{", "r", ".", "holes", "[", "i", "]", ".", "first", ",", "first", "-", "1", ",", "false", "}", ")", "\n", "}", "\n", "if", "last", "<", "r", ".", "holes", "[", "i", "]", ".", "last", "&&", "more", "{", "r", ".", "holes", "=", "append", "(", "r", ".", "holes", ",", "hole", "{", "last", "+", "1", ",", "r", ".", "holes", "[", "i", "]", ".", "last", ",", "false", "}", ")", "\n", "}", "\n", "}", "\n", "return", "used", "\n", "}" ]
// updateHoles updates the list of holes for an incoming fragment and // returns true iff the fragment filled at least part of an existing hole.
[ "updateHoles", "updates", "the", "list", "of", "holes", "for", "an", "incoming", "fragment", "and", "returns", "true", "iff", "the", "fragment", "filled", "at", "least", "part", "of", "an", "existing", "hole", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/fragmentation/reassembler.go#L62-L79
train
google/netstack
tcpip/transport/tcp/endpoint.go
Close
func (e *endpoint) Close() { // Issue a shutdown so that the peer knows we won't send any more data // if we're connected, or stop accepting if we're listening. e.Shutdown(tcpip.ShutdownWrite | tcpip.ShutdownRead) e.mu.Lock() // For listening sockets, we always release ports inline so that they // are immediately available for reuse after Close() is called. If also // registered, we unregister as well otherwise the next user would fail // in Listen() when trying to register. if e.state == stateListen && e.isPortReserved { if e.isRegistered { e.stack.UnregisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e) e.isRegistered = false } e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.id.LocalAddress, e.id.LocalPort) e.isPortReserved = false } // Either perform the local cleanup or kick the worker to make sure it // knows it needs to cleanup. tcpip.AddDanglingEndpoint(e) if !e.workerRunning { e.cleanupLocked() } else { e.workerCleanup = true e.notifyProtocolGoroutine(notifyClose) } e.mu.Unlock() }
go
func (e *endpoint) Close() { // Issue a shutdown so that the peer knows we won't send any more data // if we're connected, or stop accepting if we're listening. e.Shutdown(tcpip.ShutdownWrite | tcpip.ShutdownRead) e.mu.Lock() // For listening sockets, we always release ports inline so that they // are immediately available for reuse after Close() is called. If also // registered, we unregister as well otherwise the next user would fail // in Listen() when trying to register. if e.state == stateListen && e.isPortReserved { if e.isRegistered { e.stack.UnregisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e) e.isRegistered = false } e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.id.LocalAddress, e.id.LocalPort) e.isPortReserved = false } // Either perform the local cleanup or kick the worker to make sure it // knows it needs to cleanup. tcpip.AddDanglingEndpoint(e) if !e.workerRunning { e.cleanupLocked() } else { e.workerCleanup = true e.notifyProtocolGoroutine(notifyClose) } e.mu.Unlock() }
[ "func", "(", "e", "*", "endpoint", ")", "Close", "(", ")", "{", "e", ".", "Shutdown", "(", "tcpip", ".", "ShutdownWrite", "|", "tcpip", ".", "ShutdownRead", ")", "\n", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "e", ".", "state", "==", "stateListen", "&&", "e", ".", "isPortReserved", "{", "if", "e", ".", "isRegistered", "{", "e", ".", "stack", ".", "UnregisterTransportEndpoint", "(", "e", ".", "boundNICID", ",", "e", ".", "effectiveNetProtos", ",", "ProtocolNumber", ",", "e", ".", "id", ",", "e", ")", "\n", "e", ".", "isRegistered", "=", "false", "\n", "}", "\n", "e", ".", "stack", ".", "ReleasePort", "(", "e", ".", "effectiveNetProtos", ",", "ProtocolNumber", ",", "e", ".", "id", ".", "LocalAddress", ",", "e", ".", "id", ".", "LocalPort", ")", "\n", "e", ".", "isPortReserved", "=", "false", "\n", "}", "\n", "tcpip", ".", "AddDanglingEndpoint", "(", "e", ")", "\n", "if", "!", "e", ".", "workerRunning", "{", "e", ".", "cleanupLocked", "(", ")", "\n", "}", "else", "{", "e", ".", "workerCleanup", "=", "true", "\n", "e", ".", "notifyProtocolGoroutine", "(", "notifyClose", ")", "\n", "}", "\n", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Close puts the endpoint in a closed state and frees all resources associated // with it. It must be called only once and with no other concurrent calls to // the endpoint.
[ "Close", "puts", "the", "endpoint", "in", "a", "closed", "state", "and", "frees", "all", "resources", "associated", "with", "it", ".", "It", "must", "be", "called", "only", "once", "and", "with", "no", "other", "concurrent", "calls", "to", "the", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L415-L447
train
google/netstack
tcpip/transport/tcp/endpoint.go
Read
func (e *endpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages, *tcpip.Error) { e.mu.RLock() // The endpoint can be read if it's connected, or if it's already closed // but has some pending unread data. Also note that a RST being received // would cause the state to become stateError so we should allow the // reads to proceed before returning a ECONNRESET. e.rcvListMu.Lock() bufUsed := e.rcvBufUsed if s := e.state; s != stateConnected && s != stateClosed && bufUsed == 0 { e.rcvListMu.Unlock() he := e.hardError e.mu.RUnlock() if s == stateError { return buffer.View{}, tcpip.ControlMessages{}, he } return buffer.View{}, tcpip.ControlMessages{}, tcpip.ErrInvalidEndpointState } v, err := e.readLocked() e.rcvListMu.Unlock() e.mu.RUnlock() return v, tcpip.ControlMessages{}, err }
go
func (e *endpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages, *tcpip.Error) { e.mu.RLock() // The endpoint can be read if it's connected, or if it's already closed // but has some pending unread data. Also note that a RST being received // would cause the state to become stateError so we should allow the // reads to proceed before returning a ECONNRESET. e.rcvListMu.Lock() bufUsed := e.rcvBufUsed if s := e.state; s != stateConnected && s != stateClosed && bufUsed == 0 { e.rcvListMu.Unlock() he := e.hardError e.mu.RUnlock() if s == stateError { return buffer.View{}, tcpip.ControlMessages{}, he } return buffer.View{}, tcpip.ControlMessages{}, tcpip.ErrInvalidEndpointState } v, err := e.readLocked() e.rcvListMu.Unlock() e.mu.RUnlock() return v, tcpip.ControlMessages{}, err }
[ "func", "(", "e", "*", "endpoint", ")", "Read", "(", "*", "tcpip", ".", "FullAddress", ")", "(", "buffer", ".", "View", ",", "tcpip", ".", "ControlMessages", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "e", ".", "rcvListMu", ".", "Lock", "(", ")", "\n", "bufUsed", ":=", "e", ".", "rcvBufUsed", "\n", "if", "s", ":=", "e", ".", "state", ";", "s", "!=", "stateConnected", "&&", "s", "!=", "stateClosed", "&&", "bufUsed", "==", "0", "{", "e", ".", "rcvListMu", ".", "Unlock", "(", ")", "\n", "he", ":=", "e", ".", "hardError", "\n", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "s", "==", "stateError", "{", "return", "buffer", ".", "View", "{", "}", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "he", "\n", "}", "\n", "return", "buffer", ".", "View", "{", "}", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "tcpip", ".", "ErrInvalidEndpointState", "\n", "}", "\n", "v", ",", "err", ":=", "e", ".", "readLocked", "(", ")", "\n", "e", ".", "rcvListMu", ".", "Unlock", "(", ")", "\n", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "v", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "err", "\n", "}" ]
// Read reads data from the endpoint.
[ "Read", "reads", "data", "from", "the", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L482-L506
train
google/netstack
tcpip/transport/tcp/endpoint.go
Write
func (e *endpoint) Write(p tcpip.Payload, opts tcpip.WriteOptions) (uintptr, <-chan struct{}, *tcpip.Error) { // Linux completely ignores any address passed to sendto(2) for TCP sockets // (without the MSG_FASTOPEN flag). Corking is unimplemented, so opts.More // and opts.EndOfRecord are also ignored. e.mu.RLock() defer e.mu.RUnlock() // The endpoint cannot be written to if it's not connected. if e.state != stateConnected { switch e.state { case stateError: return 0, nil, e.hardError default: return 0, nil, tcpip.ErrClosedForSend } } // Nothing to do if the buffer is empty. if p.Size() == 0 { return 0, nil, nil } e.sndBufMu.Lock() // Check if the connection has already been closed for sends. if e.sndClosed { e.sndBufMu.Unlock() return 0, nil, tcpip.ErrClosedForSend } // Check against the limit. avail := e.sndBufSize - e.sndBufUsed if avail <= 0 { e.sndBufMu.Unlock() return 0, nil, tcpip.ErrWouldBlock } v, perr := p.Get(avail) if perr != nil { e.sndBufMu.Unlock() return 0, nil, perr } l := len(v) s := newSegmentFromView(&e.route, e.id, v) // Add data to the send queue. e.sndBufUsed += l e.sndBufInQueue += seqnum.Size(l) e.sndQueue.PushBack(s) e.sndBufMu.Unlock() if e.workMu.TryLock() { // Do the work inline. e.handleWrite() e.workMu.Unlock() } else { // Let the protocol goroutine do the work. e.sndWaker.Assert() } return uintptr(l), nil, nil }
go
func (e *endpoint) Write(p tcpip.Payload, opts tcpip.WriteOptions) (uintptr, <-chan struct{}, *tcpip.Error) { // Linux completely ignores any address passed to sendto(2) for TCP sockets // (without the MSG_FASTOPEN flag). Corking is unimplemented, so opts.More // and opts.EndOfRecord are also ignored. e.mu.RLock() defer e.mu.RUnlock() // The endpoint cannot be written to if it's not connected. if e.state != stateConnected { switch e.state { case stateError: return 0, nil, e.hardError default: return 0, nil, tcpip.ErrClosedForSend } } // Nothing to do if the buffer is empty. if p.Size() == 0 { return 0, nil, nil } e.sndBufMu.Lock() // Check if the connection has already been closed for sends. if e.sndClosed { e.sndBufMu.Unlock() return 0, nil, tcpip.ErrClosedForSend } // Check against the limit. avail := e.sndBufSize - e.sndBufUsed if avail <= 0 { e.sndBufMu.Unlock() return 0, nil, tcpip.ErrWouldBlock } v, perr := p.Get(avail) if perr != nil { e.sndBufMu.Unlock() return 0, nil, perr } l := len(v) s := newSegmentFromView(&e.route, e.id, v) // Add data to the send queue. e.sndBufUsed += l e.sndBufInQueue += seqnum.Size(l) e.sndQueue.PushBack(s) e.sndBufMu.Unlock() if e.workMu.TryLock() { // Do the work inline. e.handleWrite() e.workMu.Unlock() } else { // Let the protocol goroutine do the work. e.sndWaker.Assert() } return uintptr(l), nil, nil }
[ "func", "(", "e", "*", "endpoint", ")", "Write", "(", "p", "tcpip", ".", "Payload", ",", "opts", "tcpip", ".", "WriteOptions", ")", "(", "uintptr", ",", "<-", "chan", "struct", "{", "}", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "e", ".", "state", "!=", "stateConnected", "{", "switch", "e", ".", "state", "{", "case", "stateError", ":", "return", "0", ",", "nil", ",", "e", ".", "hardError", "\n", "default", ":", "return", "0", ",", "nil", ",", "tcpip", ".", "ErrClosedForSend", "\n", "}", "\n", "}", "\n", "if", "p", ".", "Size", "(", ")", "==", "0", "{", "return", "0", ",", "nil", ",", "nil", "\n", "}", "\n", "e", ".", "sndBufMu", ".", "Lock", "(", ")", "\n", "if", "e", ".", "sndClosed", "{", "e", ".", "sndBufMu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "nil", ",", "tcpip", ".", "ErrClosedForSend", "\n", "}", "\n", "avail", ":=", "e", ".", "sndBufSize", "-", "e", ".", "sndBufUsed", "\n", "if", "avail", "<=", "0", "{", "e", ".", "sndBufMu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "nil", ",", "tcpip", ".", "ErrWouldBlock", "\n", "}", "\n", "v", ",", "perr", ":=", "p", ".", "Get", "(", "avail", ")", "\n", "if", "perr", "!=", "nil", "{", "e", ".", "sndBufMu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "nil", ",", "perr", "\n", "}", "\n", "l", ":=", "len", "(", "v", ")", "\n", "s", ":=", "newSegmentFromView", "(", "&", "e", ".", "route", ",", "e", ".", "id", ",", "v", ")", "\n", "e", ".", "sndBufUsed", "+=", "l", "\n", "e", ".", "sndBufInQueue", "+=", "seqnum", ".", "Size", "(", "l", ")", "\n", "e", ".", "sndQueue", ".", "PushBack", "(", "s", ")", "\n", "e", ".", "sndBufMu", ".", "Unlock", "(", ")", "\n", "if", "e", ".", "workMu", ".", "TryLock", "(", ")", "{", "e", ".", "handleWrite", "(", ")", "\n", "e", ".", "workMu", ".", "Unlock", "(", ")", "\n", "}", "else", "{", "e", ".", "sndWaker", ".", "Assert", "(", ")", "\n", "}", "\n", "return", "uintptr", "(", "l", ")", ",", "nil", ",", "nil", "\n", "}" ]
// Write writes data to the endpoint's peer.
[ "Write", "writes", "data", "to", "the", "endpoint", "s", "peer", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L537-L600
train
google/netstack
tcpip/transport/tcp/endpoint.go
Peek
func (e *endpoint) Peek(vec [][]byte) (uintptr, tcpip.ControlMessages, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() // The endpoint can be read if it's connected, or if it's already closed // but has some pending unread data. if s := e.state; s != stateConnected && s != stateClosed { if s == stateError { return 0, tcpip.ControlMessages{}, e.hardError } return 0, tcpip.ControlMessages{}, tcpip.ErrInvalidEndpointState } e.rcvListMu.Lock() defer e.rcvListMu.Unlock() if e.rcvBufUsed == 0 { if e.rcvClosed || e.state != stateConnected { return 0, tcpip.ControlMessages{}, tcpip.ErrClosedForReceive } return 0, tcpip.ControlMessages{}, tcpip.ErrWouldBlock } // Make a copy of vec so we can modify the slide headers. vec = append([][]byte(nil), vec...) var num uintptr for s := e.rcvList.Front(); s != nil; s = s.Next() { views := s.data.Views() for i := s.viewToDeliver; i < len(views); i++ { v := views[i] for len(v) > 0 { if len(vec) == 0 { return num, tcpip.ControlMessages{}, nil } if len(vec[0]) == 0 { vec = vec[1:] continue } n := copy(vec[0], v) v = v[n:] vec[0] = vec[0][n:] num += uintptr(n) } } } return num, tcpip.ControlMessages{}, nil }
go
func (e *endpoint) Peek(vec [][]byte) (uintptr, tcpip.ControlMessages, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() // The endpoint can be read if it's connected, or if it's already closed // but has some pending unread data. if s := e.state; s != stateConnected && s != stateClosed { if s == stateError { return 0, tcpip.ControlMessages{}, e.hardError } return 0, tcpip.ControlMessages{}, tcpip.ErrInvalidEndpointState } e.rcvListMu.Lock() defer e.rcvListMu.Unlock() if e.rcvBufUsed == 0 { if e.rcvClosed || e.state != stateConnected { return 0, tcpip.ControlMessages{}, tcpip.ErrClosedForReceive } return 0, tcpip.ControlMessages{}, tcpip.ErrWouldBlock } // Make a copy of vec so we can modify the slide headers. vec = append([][]byte(nil), vec...) var num uintptr for s := e.rcvList.Front(); s != nil; s = s.Next() { views := s.data.Views() for i := s.viewToDeliver; i < len(views); i++ { v := views[i] for len(v) > 0 { if len(vec) == 0 { return num, tcpip.ControlMessages{}, nil } if len(vec[0]) == 0 { vec = vec[1:] continue } n := copy(vec[0], v) v = v[n:] vec[0] = vec[0][n:] num += uintptr(n) } } } return num, tcpip.ControlMessages{}, nil }
[ "func", "(", "e", "*", "endpoint", ")", "Peek", "(", "vec", "[", "]", "[", "]", "byte", ")", "(", "uintptr", ",", "tcpip", ".", "ControlMessages", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "s", ":=", "e", ".", "state", ";", "s", "!=", "stateConnected", "&&", "s", "!=", "stateClosed", "{", "if", "s", "==", "stateError", "{", "return", "0", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "e", ".", "hardError", "\n", "}", "\n", "return", "0", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "tcpip", ".", "ErrInvalidEndpointState", "\n", "}", "\n", "e", ".", "rcvListMu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "rcvListMu", ".", "Unlock", "(", ")", "\n", "if", "e", ".", "rcvBufUsed", "==", "0", "{", "if", "e", ".", "rcvClosed", "||", "e", ".", "state", "!=", "stateConnected", "{", "return", "0", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "tcpip", ".", "ErrClosedForReceive", "\n", "}", "\n", "return", "0", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "tcpip", ".", "ErrWouldBlock", "\n", "}", "\n", "vec", "=", "append", "(", "[", "]", "[", "]", "byte", "(", "nil", ")", ",", "vec", "...", ")", "\n", "var", "num", "uintptr", "\n", "for", "s", ":=", "e", ".", "rcvList", ".", "Front", "(", ")", ";", "s", "!=", "nil", ";", "s", "=", "s", ".", "Next", "(", ")", "{", "views", ":=", "s", ".", "data", ".", "Views", "(", ")", "\n", "for", "i", ":=", "s", ".", "viewToDeliver", ";", "i", "<", "len", "(", "views", ")", ";", "i", "++", "{", "v", ":=", "views", "[", "i", "]", "\n", "for", "len", "(", "v", ")", ">", "0", "{", "if", "len", "(", "vec", ")", "==", "0", "{", "return", "num", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "nil", "\n", "}", "\n", "if", "len", "(", "vec", "[", "0", "]", ")", "==", "0", "{", "vec", "=", "vec", "[", "1", ":", "]", "\n", "continue", "\n", "}", "\n", "n", ":=", "copy", "(", "vec", "[", "0", "]", ",", "v", ")", "\n", "v", "=", "v", "[", "n", ":", "]", "\n", "vec", "[", "0", "]", "=", "vec", "[", "0", "]", "[", "n", ":", "]", "\n", "num", "+=", "uintptr", "(", "n", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "num", ",", "tcpip", ".", "ControlMessages", "{", "}", ",", "nil", "\n", "}" ]
// Peek reads data without consuming it from the endpoint. // // This method does not block if there is no data pending.
[ "Peek", "reads", "data", "without", "consuming", "it", "from", "the", "endpoint", ".", "This", "method", "does", "not", "block", "if", "there", "is", "no", "data", "pending", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L605-L657
train
google/netstack
tcpip/transport/tcp/endpoint.go
zeroReceiveWindow
func (e *endpoint) zeroReceiveWindow(scale uint8) bool { if e.rcvBufUsed >= e.rcvBufSize { return true } return ((e.rcvBufSize - e.rcvBufUsed) >> scale) == 0 }
go
func (e *endpoint) zeroReceiveWindow(scale uint8) bool { if e.rcvBufUsed >= e.rcvBufSize { return true } return ((e.rcvBufSize - e.rcvBufUsed) >> scale) == 0 }
[ "func", "(", "e", "*", "endpoint", ")", "zeroReceiveWindow", "(", "scale", "uint8", ")", "bool", "{", "if", "e", ".", "rcvBufUsed", ">=", "e", ".", "rcvBufSize", "{", "return", "true", "\n", "}", "\n", "return", "(", "(", "e", ".", "rcvBufSize", "-", "e", ".", "rcvBufUsed", ")", ">>", "scale", ")", "==", "0", "\n", "}" ]
// zeroReceiveWindow checks if the receive window to be announced now would be // zero, based on the amount of available buffer and the receive window scaling. // // It must be called with rcvListMu held.
[ "zeroReceiveWindow", "checks", "if", "the", "receive", "window", "to", "be", "announced", "now", "would", "be", "zero", "based", "on", "the", "amount", "of", "available", "buffer", "and", "the", "receive", "window", "scaling", ".", "It", "must", "be", "called", "with", "rcvListMu", "held", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L663-L669
train
google/netstack
tcpip/transport/tcp/endpoint.go
readyReceiveSize
func (e *endpoint) readyReceiveSize() (int, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() // The endpoint cannot be in listen state. if e.state == stateListen { return 0, tcpip.ErrInvalidEndpointState } e.rcvListMu.Lock() defer e.rcvListMu.Unlock() return e.rcvBufUsed, nil }
go
func (e *endpoint) readyReceiveSize() (int, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() // The endpoint cannot be in listen state. if e.state == stateListen { return 0, tcpip.ErrInvalidEndpointState } e.rcvListMu.Lock() defer e.rcvListMu.Unlock() return e.rcvBufUsed, nil }
[ "func", "(", "e", "*", "endpoint", ")", "readyReceiveSize", "(", ")", "(", "int", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "e", ".", "state", "==", "stateListen", "{", "return", "0", ",", "tcpip", ".", "ErrInvalidEndpointState", "\n", "}", "\n", "e", ".", "rcvListMu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "rcvListMu", ".", "Unlock", "(", ")", "\n", "return", "e", ".", "rcvBufUsed", ",", "nil", "\n", "}" ]
// readyReceiveSize returns the number of bytes ready to be received.
[ "readyReceiveSize", "returns", "the", "number", "of", "bytes", "ready", "to", "be", "received", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L837-L850
train
google/netstack
tcpip/transport/tcp/endpoint.go
Connect
func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error { return e.connect(addr, true, true) }
go
func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error { return e.connect(addr, true, true) }
[ "func", "(", "e", "*", "endpoint", ")", "Connect", "(", "addr", "tcpip", ".", "FullAddress", ")", "*", "tcpip", ".", "Error", "{", "return", "e", ".", "connect", "(", "addr", ",", "true", ",", "true", ")", "\n", "}" ]
// Connect connects the endpoint to its peer.
[ "Connect", "connects", "the", "endpoint", "to", "its", "peer", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1030-L1032
train
google/netstack
tcpip/transport/tcp/endpoint.go
Listen
func (e *endpoint) Listen(backlog int) (err *tcpip.Error) { e.mu.Lock() defer e.mu.Unlock() defer func() { if err != nil && !err.IgnoreStats() { e.stack.Stats().TCP.FailedConnectionAttempts.Increment() } }() // Allow the backlog to be adjusted if the endpoint is not shutting down. // When the endpoint shuts down, it sets workerCleanup to true, and from // that point onward, acceptedChan is the responsibility of the cleanup() // method (and should not be touched anywhere else, including here). if e.state == stateListen && !e.workerCleanup { // Adjust the size of the channel iff we can fix existing // pending connections into the new one. if len(e.acceptedChan) > backlog { return tcpip.ErrInvalidEndpointState } if cap(e.acceptedChan) == backlog { return nil } origChan := e.acceptedChan e.acceptedChan = make(chan *endpoint, backlog) close(origChan) for ep := range origChan { e.acceptedChan <- ep } return nil } // Endpoint must be bound before it can transition to listen mode. if e.state != stateBound { return tcpip.ErrInvalidEndpointState } // Register the endpoint. if err := e.stack.RegisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e, e.reusePort); err != nil { return err } e.isRegistered = true e.state = stateListen if e.acceptedChan == nil { e.acceptedChan = make(chan *endpoint, backlog) } e.workerRunning = true e.stack.Stats().TCP.PassiveConnectionOpenings.Increment() go e.protocolListenLoop( seqnum.Size(e.receiveBufferAvailable())) return nil }
go
func (e *endpoint) Listen(backlog int) (err *tcpip.Error) { e.mu.Lock() defer e.mu.Unlock() defer func() { if err != nil && !err.IgnoreStats() { e.stack.Stats().TCP.FailedConnectionAttempts.Increment() } }() // Allow the backlog to be adjusted if the endpoint is not shutting down. // When the endpoint shuts down, it sets workerCleanup to true, and from // that point onward, acceptedChan is the responsibility of the cleanup() // method (and should not be touched anywhere else, including here). if e.state == stateListen && !e.workerCleanup { // Adjust the size of the channel iff we can fix existing // pending connections into the new one. if len(e.acceptedChan) > backlog { return tcpip.ErrInvalidEndpointState } if cap(e.acceptedChan) == backlog { return nil } origChan := e.acceptedChan e.acceptedChan = make(chan *endpoint, backlog) close(origChan) for ep := range origChan { e.acceptedChan <- ep } return nil } // Endpoint must be bound before it can transition to listen mode. if e.state != stateBound { return tcpip.ErrInvalidEndpointState } // Register the endpoint. if err := e.stack.RegisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e, e.reusePort); err != nil { return err } e.isRegistered = true e.state = stateListen if e.acceptedChan == nil { e.acceptedChan = make(chan *endpoint, backlog) } e.workerRunning = true e.stack.Stats().TCP.PassiveConnectionOpenings.Increment() go e.protocolListenLoop( seqnum.Size(e.receiveBufferAvailable())) return nil }
[ "func", "(", "e", "*", "endpoint", ")", "Listen", "(", "backlog", "int", ")", "(", "err", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "&&", "!", "err", ".", "IgnoreStats", "(", ")", "{", "e", ".", "stack", ".", "Stats", "(", ")", ".", "TCP", ".", "FailedConnectionAttempts", ".", "Increment", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "e", ".", "state", "==", "stateListen", "&&", "!", "e", ".", "workerCleanup", "{", "if", "len", "(", "e", ".", "acceptedChan", ")", ">", "backlog", "{", "return", "tcpip", ".", "ErrInvalidEndpointState", "\n", "}", "\n", "if", "cap", "(", "e", ".", "acceptedChan", ")", "==", "backlog", "{", "return", "nil", "\n", "}", "\n", "origChan", ":=", "e", ".", "acceptedChan", "\n", "e", ".", "acceptedChan", "=", "make", "(", "chan", "*", "endpoint", ",", "backlog", ")", "\n", "close", "(", "origChan", ")", "\n", "for", "ep", ":=", "range", "origChan", "{", "e", ".", "acceptedChan", "<-", "ep", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "e", ".", "state", "!=", "stateBound", "{", "return", "tcpip", ".", "ErrInvalidEndpointState", "\n", "}", "\n", "if", "err", ":=", "e", ".", "stack", ".", "RegisterTransportEndpoint", "(", "e", ".", "boundNICID", ",", "e", ".", "effectiveNetProtos", ",", "ProtocolNumber", ",", "e", ".", "id", ",", "e", ",", "e", ".", "reusePort", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "e", ".", "isRegistered", "=", "true", "\n", "e", ".", "state", "=", "stateListen", "\n", "if", "e", ".", "acceptedChan", "==", "nil", "{", "e", ".", "acceptedChan", "=", "make", "(", "chan", "*", "endpoint", ",", "backlog", ")", "\n", "}", "\n", "e", ".", "workerRunning", "=", "true", "\n", "e", ".", "stack", ".", "Stats", "(", ")", ".", "TCP", ".", "PassiveConnectionOpenings", ".", "Increment", "(", ")", "\n", "go", "e", ".", "protocolListenLoop", "(", "seqnum", ".", "Size", "(", "e", ".", "receiveBufferAvailable", "(", ")", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Listen puts the endpoint in "listen" mode, which allows it to accept // new connections.
[ "Listen", "puts", "the", "endpoint", "in", "listen", "mode", "which", "allows", "it", "to", "accept", "new", "connections", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1257-L1310
train
google/netstack
tcpip/transport/tcp/endpoint.go
startAcceptedLoop
func (e *endpoint) startAcceptedLoop(waiterQueue *waiter.Queue) { e.waiterQueue = waiterQueue e.workerRunning = true go e.protocolMainLoop(false) }
go
func (e *endpoint) startAcceptedLoop(waiterQueue *waiter.Queue) { e.waiterQueue = waiterQueue e.workerRunning = true go e.protocolMainLoop(false) }
[ "func", "(", "e", "*", "endpoint", ")", "startAcceptedLoop", "(", "waiterQueue", "*", "waiter", ".", "Queue", ")", "{", "e", ".", "waiterQueue", "=", "waiterQueue", "\n", "e", ".", "workerRunning", "=", "true", "\n", "go", "e", ".", "protocolMainLoop", "(", "false", ")", "\n", "}" ]
// startAcceptedLoop sets up required state and starts a goroutine with the // main loop for accepted connections.
[ "startAcceptedLoop", "sets", "up", "required", "state", "and", "starts", "a", "goroutine", "with", "the", "main", "loop", "for", "accepted", "connections", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1314-L1318
train
google/netstack
tcpip/transport/tcp/endpoint.go
Accept
func (e *endpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() // Endpoint must be in listen state before it can accept connections. if e.state != stateListen { return nil, nil, tcpip.ErrInvalidEndpointState } // Get the new accepted endpoint. var n *endpoint select { case n = <-e.acceptedChan: default: return nil, nil, tcpip.ErrWouldBlock } // Start the protocol goroutine. wq := &waiter.Queue{} n.startAcceptedLoop(wq) return n, wq, nil }
go
func (e *endpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() // Endpoint must be in listen state before it can accept connections. if e.state != stateListen { return nil, nil, tcpip.ErrInvalidEndpointState } // Get the new accepted endpoint. var n *endpoint select { case n = <-e.acceptedChan: default: return nil, nil, tcpip.ErrWouldBlock } // Start the protocol goroutine. wq := &waiter.Queue{} n.startAcceptedLoop(wq) return n, wq, nil }
[ "func", "(", "e", "*", "endpoint", ")", "Accept", "(", ")", "(", "tcpip", ".", "Endpoint", ",", "*", "waiter", ".", "Queue", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "e", ".", "state", "!=", "stateListen", "{", "return", "nil", ",", "nil", ",", "tcpip", ".", "ErrInvalidEndpointState", "\n", "}", "\n", "var", "n", "*", "endpoint", "\n", "select", "{", "case", "n", "=", "<-", "e", ".", "acceptedChan", ":", "default", ":", "return", "nil", ",", "nil", ",", "tcpip", ".", "ErrWouldBlock", "\n", "}", "\n", "wq", ":=", "&", "waiter", ".", "Queue", "{", "}", "\n", "n", ".", "startAcceptedLoop", "(", "wq", ")", "\n", "return", "n", ",", "wq", ",", "nil", "\n", "}" ]
// Accept returns a new endpoint if a peer has established a connection // to an endpoint previously set to listen mode.
[ "Accept", "returns", "a", "new", "endpoint", "if", "a", "peer", "has", "established", "a", "connection", "to", "an", "endpoint", "previously", "set", "to", "listen", "mode", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1322-L1344
train
google/netstack
tcpip/transport/tcp/endpoint.go
Bind
func (e *endpoint) Bind(addr tcpip.FullAddress) (err *tcpip.Error) { e.mu.Lock() defer e.mu.Unlock() // Don't allow binding once endpoint is not in the initial state // anymore. This is because once the endpoint goes into a connected or // listen state, it is already bound. if e.state != stateInitial { return tcpip.ErrAlreadyBound } e.bindAddress = addr.Addr netProto, err := e.checkV4Mapped(&addr) if err != nil { return err } // Expand netProtos to include v4 and v6 if the caller is binding to a // wildcard (empty) address, and this is an IPv6 endpoint with v6only // set to false. netProtos := []tcpip.NetworkProtocolNumber{netProto} if netProto == header.IPv6ProtocolNumber && !e.v6only && addr.Addr == "" { netProtos = []tcpip.NetworkProtocolNumber{ header.IPv6ProtocolNumber, header.IPv4ProtocolNumber, } } port, err := e.stack.ReservePort(netProtos, ProtocolNumber, addr.Addr, addr.Port, e.reusePort) if err != nil { return err } e.isPortReserved = true e.effectiveNetProtos = netProtos e.id.LocalPort = port // Any failures beyond this point must remove the port registration. defer func() { if err != nil { e.stack.ReleasePort(netProtos, ProtocolNumber, addr.Addr, port) e.isPortReserved = false e.effectiveNetProtos = nil e.id.LocalPort = 0 e.id.LocalAddress = "" e.boundNICID = 0 } }() // If an address is specified, we must ensure that it's one of our // local addresses. if len(addr.Addr) != 0 { nic := e.stack.CheckLocalAddress(addr.NIC, netProto, addr.Addr) if nic == 0 { return tcpip.ErrBadLocalAddress } e.boundNICID = nic e.id.LocalAddress = addr.Addr } // Mark endpoint as bound. e.state = stateBound return nil }
go
func (e *endpoint) Bind(addr tcpip.FullAddress) (err *tcpip.Error) { e.mu.Lock() defer e.mu.Unlock() // Don't allow binding once endpoint is not in the initial state // anymore. This is because once the endpoint goes into a connected or // listen state, it is already bound. if e.state != stateInitial { return tcpip.ErrAlreadyBound } e.bindAddress = addr.Addr netProto, err := e.checkV4Mapped(&addr) if err != nil { return err } // Expand netProtos to include v4 and v6 if the caller is binding to a // wildcard (empty) address, and this is an IPv6 endpoint with v6only // set to false. netProtos := []tcpip.NetworkProtocolNumber{netProto} if netProto == header.IPv6ProtocolNumber && !e.v6only && addr.Addr == "" { netProtos = []tcpip.NetworkProtocolNumber{ header.IPv6ProtocolNumber, header.IPv4ProtocolNumber, } } port, err := e.stack.ReservePort(netProtos, ProtocolNumber, addr.Addr, addr.Port, e.reusePort) if err != nil { return err } e.isPortReserved = true e.effectiveNetProtos = netProtos e.id.LocalPort = port // Any failures beyond this point must remove the port registration. defer func() { if err != nil { e.stack.ReleasePort(netProtos, ProtocolNumber, addr.Addr, port) e.isPortReserved = false e.effectiveNetProtos = nil e.id.LocalPort = 0 e.id.LocalAddress = "" e.boundNICID = 0 } }() // If an address is specified, we must ensure that it's one of our // local addresses. if len(addr.Addr) != 0 { nic := e.stack.CheckLocalAddress(addr.NIC, netProto, addr.Addr) if nic == 0 { return tcpip.ErrBadLocalAddress } e.boundNICID = nic e.id.LocalAddress = addr.Addr } // Mark endpoint as bound. e.state = stateBound return nil }
[ "func", "(", "e", "*", "endpoint", ")", "Bind", "(", "addr", "tcpip", ".", "FullAddress", ")", "(", "err", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "e", ".", "state", "!=", "stateInitial", "{", "return", "tcpip", ".", "ErrAlreadyBound", "\n", "}", "\n", "e", ".", "bindAddress", "=", "addr", ".", "Addr", "\n", "netProto", ",", "err", ":=", "e", ".", "checkV4Mapped", "(", "&", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "netProtos", ":=", "[", "]", "tcpip", ".", "NetworkProtocolNumber", "{", "netProto", "}", "\n", "if", "netProto", "==", "header", ".", "IPv6ProtocolNumber", "&&", "!", "e", ".", "v6only", "&&", "addr", ".", "Addr", "==", "\"\"", "{", "netProtos", "=", "[", "]", "tcpip", ".", "NetworkProtocolNumber", "{", "header", ".", "IPv6ProtocolNumber", ",", "header", ".", "IPv4ProtocolNumber", ",", "}", "\n", "}", "\n", "port", ",", "err", ":=", "e", ".", "stack", ".", "ReservePort", "(", "netProtos", ",", "ProtocolNumber", ",", "addr", ".", "Addr", ",", "addr", ".", "Port", ",", "e", ".", "reusePort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "e", ".", "isPortReserved", "=", "true", "\n", "e", ".", "effectiveNetProtos", "=", "netProtos", "\n", "e", ".", "id", ".", "LocalPort", "=", "port", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "e", ".", "stack", ".", "ReleasePort", "(", "netProtos", ",", "ProtocolNumber", ",", "addr", ".", "Addr", ",", "port", ")", "\n", "e", ".", "isPortReserved", "=", "false", "\n", "e", ".", "effectiveNetProtos", "=", "nil", "\n", "e", ".", "id", ".", "LocalPort", "=", "0", "\n", "e", ".", "id", ".", "LocalAddress", "=", "\"\"", "\n", "e", ".", "boundNICID", "=", "0", "\n", "}", "\n", "}", "(", ")", "\n", "if", "len", "(", "addr", ".", "Addr", ")", "!=", "0", "{", "nic", ":=", "e", ".", "stack", ".", "CheckLocalAddress", "(", "addr", ".", "NIC", ",", "netProto", ",", "addr", ".", "Addr", ")", "\n", "if", "nic", "==", "0", "{", "return", "tcpip", ".", "ErrBadLocalAddress", "\n", "}", "\n", "e", ".", "boundNICID", "=", "nic", "\n", "e", ".", "id", ".", "LocalAddress", "=", "addr", ".", "Addr", "\n", "}", "\n", "e", ".", "state", "=", "stateBound", "\n", "return", "nil", "\n", "}" ]
// Bind binds the endpoint to a specific local port and optionally address.
[ "Bind", "binds", "the", "endpoint", "to", "a", "specific", "local", "port", "and", "optionally", "address", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1347-L1412
train
google/netstack
tcpip/transport/tcp/endpoint.go
GetRemoteAddress
func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() if e.state != stateConnected { return tcpip.FullAddress{}, tcpip.ErrNotConnected } return tcpip.FullAddress{ Addr: e.id.RemoteAddress, Port: e.id.RemotePort, NIC: e.boundNICID, }, nil }
go
func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, *tcpip.Error) { e.mu.RLock() defer e.mu.RUnlock() if e.state != stateConnected { return tcpip.FullAddress{}, tcpip.ErrNotConnected } return tcpip.FullAddress{ Addr: e.id.RemoteAddress, Port: e.id.RemotePort, NIC: e.boundNICID, }, nil }
[ "func", "(", "e", "*", "endpoint", ")", "GetRemoteAddress", "(", ")", "(", "tcpip", ".", "FullAddress", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "e", ".", "state", "!=", "stateConnected", "{", "return", "tcpip", ".", "FullAddress", "{", "}", ",", "tcpip", ".", "ErrNotConnected", "\n", "}", "\n", "return", "tcpip", ".", "FullAddress", "{", "Addr", ":", "e", ".", "id", ".", "RemoteAddress", ",", "Port", ":", "e", ".", "id", ".", "RemotePort", ",", "NIC", ":", "e", ".", "boundNICID", ",", "}", ",", "nil", "\n", "}" ]
// GetRemoteAddress returns the address to which the endpoint is connected.
[ "GetRemoteAddress", "returns", "the", "address", "to", "which", "the", "endpoint", "is", "connected", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1427-L1440
train
google/netstack
tcpip/transport/tcp/endpoint.go
updateSndBufferUsage
func (e *endpoint) updateSndBufferUsage(v int) { e.sndBufMu.Lock() notify := e.sndBufUsed >= e.sndBufSize>>1 e.sndBufUsed -= v // We only notify when there is half the sndBufSize available after // a full buffer event occurs. This ensures that we don't wake up // writers to queue just 1-2 segments and go back to sleep. notify = notify && e.sndBufUsed < e.sndBufSize>>1 e.sndBufMu.Unlock() if notify { e.waiterQueue.Notify(waiter.EventOut) } }
go
func (e *endpoint) updateSndBufferUsage(v int) { e.sndBufMu.Lock() notify := e.sndBufUsed >= e.sndBufSize>>1 e.sndBufUsed -= v // We only notify when there is half the sndBufSize available after // a full buffer event occurs. This ensures that we don't wake up // writers to queue just 1-2 segments and go back to sleep. notify = notify && e.sndBufUsed < e.sndBufSize>>1 e.sndBufMu.Unlock() if notify { e.waiterQueue.Notify(waiter.EventOut) } }
[ "func", "(", "e", "*", "endpoint", ")", "updateSndBufferUsage", "(", "v", "int", ")", "{", "e", ".", "sndBufMu", ".", "Lock", "(", ")", "\n", "notify", ":=", "e", ".", "sndBufUsed", ">=", "e", ".", "sndBufSize", ">>", "1", "\n", "e", ".", "sndBufUsed", "-=", "v", "\n", "notify", "=", "notify", "&&", "e", ".", "sndBufUsed", "<", "e", ".", "sndBufSize", ">>", "1", "\n", "e", ".", "sndBufMu", ".", "Unlock", "(", ")", "\n", "if", "notify", "{", "e", ".", "waiterQueue", ".", "Notify", "(", "waiter", ".", "EventOut", ")", "\n", "}", "\n", "}" ]
// updateSndBufferUsage is called by the protocol goroutine when room opens up // in the send buffer. The number of newly available bytes is v.
[ "updateSndBufferUsage", "is", "called", "by", "the", "protocol", "goroutine", "when", "room", "opens", "up", "in", "the", "send", "buffer", ".", "The", "number", "of", "newly", "available", "bytes", "is", "v", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1492-L1505
train
google/netstack
tcpip/transport/tcp/endpoint.go
receiveBufferAvailable
func (e *endpoint) receiveBufferAvailable() int { e.rcvListMu.Lock() size := e.rcvBufSize used := e.rcvBufUsed e.rcvListMu.Unlock() // We may use more bytes than the buffer size when the receive buffer // shrinks. if used >= size { return 0 } return size - used }
go
func (e *endpoint) receiveBufferAvailable() int { e.rcvListMu.Lock() size := e.rcvBufSize used := e.rcvBufUsed e.rcvListMu.Unlock() // We may use more bytes than the buffer size when the receive buffer // shrinks. if used >= size { return 0 } return size - used }
[ "func", "(", "e", "*", "endpoint", ")", "receiveBufferAvailable", "(", ")", "int", "{", "e", ".", "rcvListMu", ".", "Lock", "(", ")", "\n", "size", ":=", "e", ".", "rcvBufSize", "\n", "used", ":=", "e", ".", "rcvBufUsed", "\n", "e", ".", "rcvListMu", ".", "Unlock", "(", ")", "\n", "if", "used", ">=", "size", "{", "return", "0", "\n", "}", "\n", "return", "size", "-", "used", "\n", "}" ]
// receiveBufferAvailable calculates how many bytes are still available in the // receive buffer.
[ "receiveBufferAvailable", "calculates", "how", "many", "bytes", "are", "still", "available", "in", "the", "receive", "buffer", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1526-L1539
train
google/netstack
tcpip/transport/tcp/endpoint.go
maybeEnableTimestamp
func (e *endpoint) maybeEnableTimestamp(synOpts *header.TCPSynOptions) { if synOpts.TS { e.sendTSOk = true e.recentTS = synOpts.TSVal } }
go
func (e *endpoint) maybeEnableTimestamp(synOpts *header.TCPSynOptions) { if synOpts.TS { e.sendTSOk = true e.recentTS = synOpts.TSVal } }
[ "func", "(", "e", "*", "endpoint", ")", "maybeEnableTimestamp", "(", "synOpts", "*", "header", ".", "TCPSynOptions", ")", "{", "if", "synOpts", ".", "TS", "{", "e", ".", "sendTSOk", "=", "true", "\n", "e", ".", "recentTS", "=", "synOpts", ".", "TSVal", "\n", "}", "\n", "}" ]
// maybeEnableTimestamp marks the timestamp option enabled for this endpoint if // the SYN options indicate that timestamp option was negotiated. It also // initializes the recentTS with the value provided in synOpts.TSval.
[ "maybeEnableTimestamp", "marks", "the", "timestamp", "option", "enabled", "for", "this", "endpoint", "if", "the", "SYN", "options", "indicate", "that", "timestamp", "option", "was", "negotiated", ".", "It", "also", "initializes", "the", "recentTS", "with", "the", "value", "provided", "in", "synOpts", ".", "TSval", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1560-L1565
train
google/netstack
tcpip/transport/tcp/endpoint.go
tcpTimeStamp
func tcpTimeStamp(offset uint32) uint32 { now := time.Now() return uint32(now.Unix()*1000+int64(now.Nanosecond()/1e6)) + offset }
go
func tcpTimeStamp(offset uint32) uint32 { now := time.Now() return uint32(now.Unix()*1000+int64(now.Nanosecond()/1e6)) + offset }
[ "func", "tcpTimeStamp", "(", "offset", "uint32", ")", "uint32", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "return", "uint32", "(", "now", ".", "Unix", "(", ")", "*", "1000", "+", "int64", "(", "now", ".", "Nanosecond", "(", ")", "/", "1e6", ")", ")", "+", "offset", "\n", "}" ]
// tcpTimeStamp returns a timestamp offset by the provided offset. This is // not inlined above as it's used when SYN cookies are in use and endpoint // is not created at the time when the SYN cookie is sent.
[ "tcpTimeStamp", "returns", "a", "timestamp", "offset", "by", "the", "provided", "offset", ".", "This", "is", "not", "inlined", "above", "as", "it", "s", "used", "when", "SYN", "cookies", "are", "in", "use", "and", "endpoint", "is", "not", "created", "at", "the", "time", "when", "the", "SYN", "cookie", "is", "sent", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1576-L1579
train
google/netstack
tcpip/transport/tcp/endpoint.go
timeStampOffset
func timeStampOffset() uint32 { b := make([]byte, 4) if _, err := rand.Read(b); err != nil { panic(err) } // Initialize a random tsOffset that will be added to the recentTS // everytime the timestamp is sent when the Timestamp option is enabled. // // See https://tools.ietf.org/html/rfc7323#section-5.4 for details on // why this is required. // // NOTE: This is not completely to spec as normally this should be // initialized in a manner analogous to how sequence numbers are // randomized per connection basis. But for now this is sufficient. return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 }
go
func timeStampOffset() uint32 { b := make([]byte, 4) if _, err := rand.Read(b); err != nil { panic(err) } // Initialize a random tsOffset that will be added to the recentTS // everytime the timestamp is sent when the Timestamp option is enabled. // // See https://tools.ietf.org/html/rfc7323#section-5.4 for details on // why this is required. // // NOTE: This is not completely to spec as normally this should be // initialized in a manner analogous to how sequence numbers are // randomized per connection basis. But for now this is sufficient. return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 }
[ "func", "timeStampOffset", "(", ")", "uint32", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "b", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "uint32", "(", "b", "[", "0", "]", ")", "|", "uint32", "(", "b", "[", "1", "]", ")", "<<", "8", "|", "uint32", "(", "b", "[", "2", "]", ")", "<<", "16", "|", "uint32", "(", "b", "[", "3", "]", ")", "<<", "24", "\n", "}" ]
// timeStampOffset returns a randomized timestamp offset to be used when sending // timestamp values in a timestamp option for a TCP segment.
[ "timeStampOffset", "returns", "a", "randomized", "timestamp", "offset", "to", "be", "used", "when", "sending", "timestamp", "values", "in", "a", "timestamp", "option", "for", "a", "TCP", "segment", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1583-L1598
train
google/netstack
tcpip/transport/tcp/endpoint.go
maybeEnableSACKPermitted
func (e *endpoint) maybeEnableSACKPermitted(synOpts *header.TCPSynOptions) { var v SACKEnabled if err := e.stack.TransportProtocolOption(ProtocolNumber, &v); err != nil { // Stack doesn't support SACK. So just return. return } if bool(v) && synOpts.SACKPermitted { e.sackPermitted = true } }
go
func (e *endpoint) maybeEnableSACKPermitted(synOpts *header.TCPSynOptions) { var v SACKEnabled if err := e.stack.TransportProtocolOption(ProtocolNumber, &v); err != nil { // Stack doesn't support SACK. So just return. return } if bool(v) && synOpts.SACKPermitted { e.sackPermitted = true } }
[ "func", "(", "e", "*", "endpoint", ")", "maybeEnableSACKPermitted", "(", "synOpts", "*", "header", ".", "TCPSynOptions", ")", "{", "var", "v", "SACKEnabled", "\n", "if", "err", ":=", "e", ".", "stack", ".", "TransportProtocolOption", "(", "ProtocolNumber", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "bool", "(", "v", ")", "&&", "synOpts", ".", "SACKPermitted", "{", "e", ".", "sackPermitted", "=", "true", "\n", "}", "\n", "}" ]
// maybeEnableSACKPermitted marks the SACKPermitted option enabled for this endpoint // if the SYN options indicate that the SACK option was negotiated and the TCP // stack is configured to enable TCP SACK option.
[ "maybeEnableSACKPermitted", "marks", "the", "SACKPermitted", "option", "enabled", "for", "this", "endpoint", "if", "the", "SYN", "options", "indicate", "that", "the", "SACK", "option", "was", "negotiated", "and", "the", "TCP", "stack", "is", "configured", "to", "enable", "TCP", "SACK", "option", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1603-L1612
train
google/netstack
tcpip/transport/tcp/endpoint.go
maxOptionSize
func (e *endpoint) maxOptionSize() (size int) { var maxSackBlocks [header.TCPMaxSACKBlocks]header.SACKBlock options := e.makeOptions(maxSackBlocks[:]) size = len(options) putOptions(options) return size }
go
func (e *endpoint) maxOptionSize() (size int) { var maxSackBlocks [header.TCPMaxSACKBlocks]header.SACKBlock options := e.makeOptions(maxSackBlocks[:]) size = len(options) putOptions(options) return size }
[ "func", "(", "e", "*", "endpoint", ")", "maxOptionSize", "(", ")", "(", "size", "int", ")", "{", "var", "maxSackBlocks", "[", "header", ".", "TCPMaxSACKBlocks", "]", "header", ".", "SACKBlock", "\n", "options", ":=", "e", ".", "makeOptions", "(", "maxSackBlocks", "[", ":", "]", ")", "\n", "size", "=", "len", "(", "options", ")", "\n", "putOptions", "(", "options", ")", "\n", "return", "size", "\n", "}" ]
// maxOptionSize return the maximum size of TCP options.
[ "maxOptionSize", "return", "the", "maximum", "size", "of", "TCP", "options", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/endpoint.go#L1615-L1622
train
google/netstack
tmutex/tmutex.go
Lock
func (m *Mutex) Lock() { // Uncontended case. if atomic.AddInt32(&m.v, -1) == 0 { return } for { // Try to acquire the mutex again, at the same time making sure // that m.v is negative, which indicates to the owner of the // lock that it is contended, which will force it to try to wake // someone up when it releases the mutex. if v := atomic.LoadInt32(&m.v); v >= 0 && atomic.SwapInt32(&m.v, -1) == 1 { return } // Wait for the mutex to be released before trying again. <-m.ch } }
go
func (m *Mutex) Lock() { // Uncontended case. if atomic.AddInt32(&m.v, -1) == 0 { return } for { // Try to acquire the mutex again, at the same time making sure // that m.v is negative, which indicates to the owner of the // lock that it is contended, which will force it to try to wake // someone up when it releases the mutex. if v := atomic.LoadInt32(&m.v); v >= 0 && atomic.SwapInt32(&m.v, -1) == 1 { return } // Wait for the mutex to be released before trying again. <-m.ch } }
[ "func", "(", "m", "*", "Mutex", ")", "Lock", "(", ")", "{", "if", "atomic", ".", "AddInt32", "(", "&", "m", ".", "v", ",", "-", "1", ")", "==", "0", "{", "return", "\n", "}", "\n", "for", "{", "if", "v", ":=", "atomic", ".", "LoadInt32", "(", "&", "m", ".", "v", ")", ";", "v", ">=", "0", "&&", "atomic", ".", "SwapInt32", "(", "&", "m", ".", "v", ",", "-", "1", ")", "==", "1", "{", "return", "\n", "}", "\n", "<-", "m", ".", "ch", "\n", "}", "\n", "}" ]
// Lock acquires the mutex. If it is currently held by another goroutine, Lock // will wait until it has a chance to acquire it.
[ "Lock", "acquires", "the", "mutex", ".", "If", "it", "is", "currently", "held", "by", "another", "goroutine", "Lock", "will", "wait", "until", "it", "has", "a", "chance", "to", "acquire", "it", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tmutex/tmutex.go#L38-L56
train
google/netstack
tmutex/tmutex.go
TryLock
func (m *Mutex) TryLock() bool { v := atomic.LoadInt32(&m.v) if v <= 0 { return false } return atomic.CompareAndSwapInt32(&m.v, 1, 0) }
go
func (m *Mutex) TryLock() bool { v := atomic.LoadInt32(&m.v) if v <= 0 { return false } return atomic.CompareAndSwapInt32(&m.v, 1, 0) }
[ "func", "(", "m", "*", "Mutex", ")", "TryLock", "(", ")", "bool", "{", "v", ":=", "atomic", ".", "LoadInt32", "(", "&", "m", ".", "v", ")", "\n", "if", "v", "<=", "0", "{", "return", "false", "\n", "}", "\n", "return", "atomic", ".", "CompareAndSwapInt32", "(", "&", "m", ".", "v", ",", "1", ",", "0", ")", "\n", "}" ]
// TryLock attempts to acquire the mutex without blocking. If the mutex is // currently held by another goroutine, it fails to acquire it and returns // false.
[ "TryLock", "attempts", "to", "acquire", "the", "mutex", "without", "blocking", ".", "If", "the", "mutex", "is", "currently", "held", "by", "another", "goroutine", "it", "fails", "to", "acquire", "it", "and", "returns", "false", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tmutex/tmutex.go#L61-L67
train
google/netstack
tcpip/header/icmpv4.go
SetChecksum
func (b ICMPv4) SetChecksum(checksum uint16) { binary.BigEndian.PutUint16(b[2:], checksum) }
go
func (b ICMPv4) SetChecksum(checksum uint16) { binary.BigEndian.PutUint16(b[2:], checksum) }
[ "func", "(", "b", "ICMPv4", ")", "SetChecksum", "(", "checksum", "uint16", ")", "{", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "2", ":", "]", ",", "checksum", ")", "\n", "}" ]
// SetChecksum sets the ICMP checksum field.
[ "SetChecksum", "sets", "the", "ICMP", "checksum", "field", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/icmpv4.go#L83-L85
train
google/netstack
tcpip/network/hash/hash.go
RandN32
func RandN32(n int) []uint32 { b := make([]byte, 4*n) if _, err := rand.Read(b); err != nil { panic("unable to get random numbers: " + err.Error()) } r := make([]uint32, n) for i := range r { r[i] = binary.LittleEndian.Uint32(b[4*i : (4*i + 4)]) } return r }
go
func RandN32(n int) []uint32 { b := make([]byte, 4*n) if _, err := rand.Read(b); err != nil { panic("unable to get random numbers: " + err.Error()) } r := make([]uint32, n) for i := range r { r[i] = binary.LittleEndian.Uint32(b[4*i : (4*i + 4)]) } return r }
[ "func", "RandN32", "(", "n", "int", ")", "[", "]", "uint32", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "4", "*", "n", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "b", ")", ";", "err", "!=", "nil", "{", "panic", "(", "\"unable to get random numbers: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "r", ":=", "make", "(", "[", "]", "uint32", ",", "n", ")", "\n", "for", "i", ":=", "range", "r", "{", "r", "[", "i", "]", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "b", "[", "4", "*", "i", ":", "(", "4", "*", "i", "+", "4", ")", "]", ")", "\n", "}", "\n", "return", "r", "\n", "}" ]
// RandN32 generates a slice of n cryptographic random 32-bit numbers.
[ "RandN32", "generates", "a", "slice", "of", "n", "cryptographic", "random", "32", "-", "bit", "numbers", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/hash/hash.go#L28-L38
train
google/netstack
tcpip/network/hash/hash.go
Hash3Words
func Hash3Words(a, b, c, initval uint32) uint32 { const iv = 0xdeadbeef + (3 << 2) initval += iv a += initval b += initval c += initval c ^= b c -= rol32(b, 14) a ^= c a -= rol32(c, 11) b ^= a b -= rol32(a, 25) c ^= b c -= rol32(b, 16) a ^= c a -= rol32(c, 4) b ^= a b -= rol32(a, 14) c ^= b c -= rol32(b, 24) return c }
go
func Hash3Words(a, b, c, initval uint32) uint32 { const iv = 0xdeadbeef + (3 << 2) initval += iv a += initval b += initval c += initval c ^= b c -= rol32(b, 14) a ^= c a -= rol32(c, 11) b ^= a b -= rol32(a, 25) c ^= b c -= rol32(b, 16) a ^= c a -= rol32(c, 4) b ^= a b -= rol32(a, 14) c ^= b c -= rol32(b, 24) return c }
[ "func", "Hash3Words", "(", "a", ",", "b", ",", "c", ",", "initval", "uint32", ")", "uint32", "{", "const", "iv", "=", "0xdeadbeef", "+", "(", "3", "<<", "2", ")", "\n", "initval", "+=", "iv", "\n", "a", "+=", "initval", "\n", "b", "+=", "initval", "\n", "c", "+=", "initval", "\n", "c", "^=", "b", "\n", "c", "-=", "rol32", "(", "b", ",", "14", ")", "\n", "a", "^=", "c", "\n", "a", "-=", "rol32", "(", "c", ",", "11", ")", "\n", "b", "^=", "a", "\n", "b", "-=", "rol32", "(", "a", ",", "25", ")", "\n", "c", "^=", "b", "\n", "c", "-=", "rol32", "(", "b", ",", "16", ")", "\n", "a", "^=", "c", "\n", "a", "-=", "rol32", "(", "c", ",", "4", ")", "\n", "b", "^=", "a", "\n", "b", "-=", "rol32", "(", "a", ",", "14", ")", "\n", "c", "^=", "b", "\n", "c", "-=", "rol32", "(", "b", ",", "24", ")", "\n", "return", "c", "\n", "}" ]
// Hash3Words calculates the Jenkins hash of 3 32-bit words. This is adapted // from linux.
[ "Hash3Words", "calculates", "the", "Jenkins", "hash", "of", "3", "32", "-", "bit", "words", ".", "This", "is", "adapted", "from", "linux", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/hash/hash.go#L42-L66
train
google/netstack
tcpip/network/hash/hash.go
IPv4FragmentHash
func IPv4FragmentHash(h header.IPv4) uint32 { x := uint32(h.ID())<<16 | uint32(h.Protocol()) t := h.SourceAddress() y := uint32(t[0]) | uint32(t[1])<<8 | uint32(t[2])<<16 | uint32(t[3])<<24 t = h.DestinationAddress() z := uint32(t[0]) | uint32(t[1])<<8 | uint32(t[2])<<16 | uint32(t[3])<<24 return Hash3Words(x, y, z, hashIV) }
go
func IPv4FragmentHash(h header.IPv4) uint32 { x := uint32(h.ID())<<16 | uint32(h.Protocol()) t := h.SourceAddress() y := uint32(t[0]) | uint32(t[1])<<8 | uint32(t[2])<<16 | uint32(t[3])<<24 t = h.DestinationAddress() z := uint32(t[0]) | uint32(t[1])<<8 | uint32(t[2])<<16 | uint32(t[3])<<24 return Hash3Words(x, y, z, hashIV) }
[ "func", "IPv4FragmentHash", "(", "h", "header", ".", "IPv4", ")", "uint32", "{", "x", ":=", "uint32", "(", "h", ".", "ID", "(", ")", ")", "<<", "16", "|", "uint32", "(", "h", ".", "Protocol", "(", ")", ")", "\n", "t", ":=", "h", ".", "SourceAddress", "(", ")", "\n", "y", ":=", "uint32", "(", "t", "[", "0", "]", ")", "|", "uint32", "(", "t", "[", "1", "]", ")", "<<", "8", "|", "uint32", "(", "t", "[", "2", "]", ")", "<<", "16", "|", "uint32", "(", "t", "[", "3", "]", ")", "<<", "24", "\n", "t", "=", "h", ".", "DestinationAddress", "(", ")", "\n", "z", ":=", "uint32", "(", "t", "[", "0", "]", ")", "|", "uint32", "(", "t", "[", "1", "]", ")", "<<", "8", "|", "uint32", "(", "t", "[", "2", "]", ")", "<<", "16", "|", "uint32", "(", "t", "[", "3", "]", ")", "<<", "24", "\n", "return", "Hash3Words", "(", "x", ",", "y", ",", "z", ",", "hashIV", ")", "\n", "}" ]
// IPv4FragmentHash computes the hash of the IPv4 fragment as suggested in RFC 791.
[ "IPv4FragmentHash", "computes", "the", "hash", "of", "the", "IPv4", "fragment", "as", "suggested", "in", "RFC", "791", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/network/hash/hash.go#L69-L76
train
google/netstack
tcpip/transport/icmp/protocol.go
MinimumPacketSize
func (p *protocol) MinimumPacketSize() int { switch p.number { case ProtocolNumber4: return header.ICMPv4EchoMinimumSize case ProtocolNumber6: return header.ICMPv6EchoMinimumSize } panic(fmt.Sprint("unknown protocol number: ", p.number)) }
go
func (p *protocol) MinimumPacketSize() int { switch p.number { case ProtocolNumber4: return header.ICMPv4EchoMinimumSize case ProtocolNumber6: return header.ICMPv6EchoMinimumSize } panic(fmt.Sprint("unknown protocol number: ", p.number)) }
[ "func", "(", "p", "*", "protocol", ")", "MinimumPacketSize", "(", ")", "int", "{", "switch", "p", ".", "number", "{", "case", "ProtocolNumber4", ":", "return", "header", ".", "ICMPv4EchoMinimumSize", "\n", "case", "ProtocolNumber6", ":", "return", "header", ".", "ICMPv6EchoMinimumSize", "\n", "}", "\n", "panic", "(", "fmt", ".", "Sprint", "(", "\"unknown protocol number: \"", ",", "p", ".", "number", ")", ")", "\n", "}" ]
// MinimumPacketSize returns the minimum valid icmp packet size.
[ "MinimumPacketSize", "returns", "the", "minimum", "valid", "icmp", "packet", "size", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/icmp/protocol.go#L90-L98
train
google/netstack
tcpip/transport/icmp/protocol.go
ParsePorts
func (p *protocol) ParsePorts(v buffer.View) (src, dst uint16, err *tcpip.Error) { switch p.number { case ProtocolNumber4: return 0, binary.BigEndian.Uint16(v[header.ICMPv4MinimumSize:]), nil case ProtocolNumber6: return 0, binary.BigEndian.Uint16(v[header.ICMPv6MinimumSize:]), nil } panic(fmt.Sprint("unknown protocol number: ", p.number)) }
go
func (p *protocol) ParsePorts(v buffer.View) (src, dst uint16, err *tcpip.Error) { switch p.number { case ProtocolNumber4: return 0, binary.BigEndian.Uint16(v[header.ICMPv4MinimumSize:]), nil case ProtocolNumber6: return 0, binary.BigEndian.Uint16(v[header.ICMPv6MinimumSize:]), nil } panic(fmt.Sprint("unknown protocol number: ", p.number)) }
[ "func", "(", "p", "*", "protocol", ")", "ParsePorts", "(", "v", "buffer", ".", "View", ")", "(", "src", ",", "dst", "uint16", ",", "err", "*", "tcpip", ".", "Error", ")", "{", "switch", "p", ".", "number", "{", "case", "ProtocolNumber4", ":", "return", "0", ",", "binary", ".", "BigEndian", ".", "Uint16", "(", "v", "[", "header", ".", "ICMPv4MinimumSize", ":", "]", ")", ",", "nil", "\n", "case", "ProtocolNumber6", ":", "return", "0", ",", "binary", ".", "BigEndian", ".", "Uint16", "(", "v", "[", "header", ".", "ICMPv6MinimumSize", ":", "]", ")", ",", "nil", "\n", "}", "\n", "panic", "(", "fmt", ".", "Sprint", "(", "\"unknown protocol number: \"", ",", "p", ".", "number", ")", ")", "\n", "}" ]
// ParsePorts returns the source and destination ports stored in the given icmp // packet.
[ "ParsePorts", "returns", "the", "source", "and", "destination", "ports", "stored", "in", "the", "given", "icmp", "packet", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/icmp/protocol.go#L102-L110
train
google/netstack
tcpip/transport/icmp/protocol.go
HandleUnknownDestinationPacket
func (p *protocol) HandleUnknownDestinationPacket(*stack.Route, stack.TransportEndpointID, buffer.VectorisedView) bool { return true }
go
func (p *protocol) HandleUnknownDestinationPacket(*stack.Route, stack.TransportEndpointID, buffer.VectorisedView) bool { return true }
[ "func", "(", "p", "*", "protocol", ")", "HandleUnknownDestinationPacket", "(", "*", "stack", ".", "Route", ",", "stack", ".", "TransportEndpointID", ",", "buffer", ".", "VectorisedView", ")", "bool", "{", "return", "true", "\n", "}" ]
// HandleUnknownDestinationPacket handles packets targeted at this protocol but // that don't match any existing endpoint.
[ "HandleUnknownDestinationPacket", "handles", "packets", "targeted", "at", "this", "protocol", "but", "that", "don", "t", "match", "any", "existing", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/icmp/protocol.go#L114-L116
train
google/netstack
tcpip/link/sharedmem/pipe/pipe.go
payloadToSlotSize
func payloadToSlotSize(payloadSize uint64) uint64 { s := sizeOfSlotHeader + payloadSize return (s + sizeOfSlotHeader - 1) &^ (sizeOfSlotHeader - 1) }
go
func payloadToSlotSize(payloadSize uint64) uint64 { s := sizeOfSlotHeader + payloadSize return (s + sizeOfSlotHeader - 1) &^ (sizeOfSlotHeader - 1) }
[ "func", "payloadToSlotSize", "(", "payloadSize", "uint64", ")", "uint64", "{", "s", ":=", "sizeOfSlotHeader", "+", "payloadSize", "\n", "return", "(", "s", "+", "sizeOfSlotHeader", "-", "1", ")", "&^", "(", "sizeOfSlotHeader", "-", "1", ")", "\n", "}" ]
// payloadToSlotSize calculates the total size of a slot based on its payload // size. The total size is the header size, plus the payload size, plus padding // if necessary to make the total size a multiple of sizeOfSlotHeader.
[ "payloadToSlotSize", "calculates", "the", "total", "size", "of", "a", "slot", "based", "on", "its", "payload", "size", ".", "The", "total", "size", "is", "the", "header", "size", "plus", "the", "payload", "size", "plus", "padding", "if", "necessary", "to", "make", "the", "total", "size", "a", "multiple", "of", "sizeOfSlotHeader", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/pipe/pipe.go#L48-L51
train
google/netstack
tcpip/link/sharedmem/pipe/pipe.go
init
func (p *pipe) init(b []byte) { p.buffer = b[:len(b)&^(sizeOfSlotHeader-1)] }
go
func (p *pipe) init(b []byte) { p.buffer = b[:len(b)&^(sizeOfSlotHeader-1)] }
[ "func", "(", "p", "*", "pipe", ")", "init", "(", "b", "[", "]", "byte", ")", "{", "p", ".", "buffer", "=", "b", "[", ":", "len", "(", "b", ")", "&^", "(", "sizeOfSlotHeader", "-", "1", ")", "]", "\n", "}" ]
// init initializes the pipe buffer such that its size is a multiple of the size // of the slot header.
[ "init", "initializes", "the", "pipe", "buffer", "such", "that", "its", "size", "is", "a", "multiple", "of", "the", "size", "of", "the", "slot", "header", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/pipe/pipe.go#L70-L72
train
google/netstack
tcpip/link/sharedmem/pipe/rx.go
Init
func (r *Rx) Init(b []byte) { r.p.init(b) r.tail = 0xfffffffe * jump r.head = r.tail }
go
func (r *Rx) Init(b []byte) { r.p.init(b) r.tail = 0xfffffffe * jump r.head = r.tail }
[ "func", "(", "r", "*", "Rx", ")", "Init", "(", "b", "[", "]", "byte", ")", "{", "r", ".", "p", ".", "init", "(", "b", ")", "\n", "r", ".", "tail", "=", "0xfffffffe", "*", "jump", "\n", "r", ".", "head", "=", "r", ".", "tail", "\n", "}" ]
// Init initializes the receive end of the pipe. In the initial state, the next // slot to be inspected is the very first one.
[ "Init", "initializes", "the", "receive", "end", "of", "the", "pipe", ".", "In", "the", "initial", "state", "the", "next", "slot", "to", "be", "inspected", "is", "the", "very", "first", "one", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/pipe/rx.go#L27-L31
train
google/netstack
tcpip/link/loopback/loopback.go
Capabilities
func (*endpoint) Capabilities() stack.LinkEndpointCapabilities { return stack.CapabilityRXChecksumOffload | stack.CapabilityTXChecksumOffload | stack.CapabilitySaveRestore | stack.CapabilityLoopback }
go
func (*endpoint) Capabilities() stack.LinkEndpointCapabilities { return stack.CapabilityRXChecksumOffload | stack.CapabilityTXChecksumOffload | stack.CapabilitySaveRestore | stack.CapabilityLoopback }
[ "func", "(", "*", "endpoint", ")", "Capabilities", "(", ")", "stack", ".", "LinkEndpointCapabilities", "{", "return", "stack", ".", "CapabilityRXChecksumOffload", "|", "stack", ".", "CapabilityTXChecksumOffload", "|", "stack", ".", "CapabilitySaveRestore", "|", "stack", ".", "CapabilityLoopback", "\n", "}" ]
// Capabilities implements stack.LinkEndpoint.Capabilities. Loopback advertises // itself as supporting checksum offload, but in reality it's just omitted.
[ "Capabilities", "implements", "stack", ".", "LinkEndpoint", ".", "Capabilities", ".", "Loopback", "advertises", "itself", "as", "supporting", "checksum", "offload", "but", "in", "reality", "it", "s", "just", "omitted", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/loopback/loopback.go#L58-L60
train
google/netstack
tcpip/link/loopback/loopback.go
WritePacket
func (e *endpoint) WritePacket(_ *stack.Route, _ *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) *tcpip.Error { 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) // Because we're immediately turning around and writing the packet back to the // rx path, we intentionally don't preserve the remote and local link // addresses from the stack.Route we're passed. e.dispatcher.DeliverNetworkPacket(e, "" /* remote */, "" /* local */, protocol, vv) return nil }
go
func (e *endpoint) WritePacket(_ *stack.Route, _ *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) *tcpip.Error { 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) // Because we're immediately turning around and writing the packet back to the // rx path, we intentionally don't preserve the remote and local link // addresses from the stack.Route we're passed. e.dispatcher.DeliverNetworkPacket(e, "" /* remote */, "" /* local */, protocol, vv) return nil }
[ "func", "(", "e", "*", "endpoint", ")", "WritePacket", "(", "_", "*", "stack", ".", "Route", ",", "_", "*", "stack", ".", "GSO", ",", "hdr", "buffer", ".", "Prependable", ",", "payload", "buffer", ".", "VectorisedView", ",", "protocol", "tcpip", ".", "NetworkProtocolNumber", ")", "*", "tcpip", ".", "Error", "{", "views", ":=", "make", "(", "[", "]", "buffer", ".", "View", ",", "1", ",", "1", "+", "len", "(", "payload", ".", "Views", "(", ")", ")", ")", "\n", "views", "[", "0", "]", "=", "hdr", ".", "View", "(", ")", "\n", "views", "=", "append", "(", "views", ",", "payload", ".", "Views", "(", ")", "...", ")", "\n", "vv", ":=", "buffer", ".", "NewVectorisedView", "(", "len", "(", "views", "[", "0", "]", ")", "+", "payload", ".", "Size", "(", ")", ",", "views", ")", "\n", "e", ".", "dispatcher", ".", "DeliverNetworkPacket", "(", "e", ",", "\"\"", ",", "\"\"", ",", "protocol", ",", "vv", ")", "\n", "return", "nil", "\n", "}" ]
// WritePacket implements stack.LinkEndpoint.WritePacket. It delivers outbound // packets to the network-layer dispatcher.
[ "WritePacket", "implements", "stack", ".", "LinkEndpoint", ".", "WritePacket", ".", "It", "delivers", "outbound", "packets", "to", "the", "network", "-", "layer", "dispatcher", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/loopback/loopback.go#L75-L87
train
google/netstack
tcpip/transport/tcp/segment.go
logicalLen
func (s *segment) logicalLen() seqnum.Size { l := seqnum.Size(s.data.Size()) if s.flagIsSet(header.TCPFlagSyn) { l++ } if s.flagIsSet(header.TCPFlagFin) { l++ } return l }
go
func (s *segment) logicalLen() seqnum.Size { l := seqnum.Size(s.data.Size()) if s.flagIsSet(header.TCPFlagSyn) { l++ } if s.flagIsSet(header.TCPFlagFin) { l++ } return l }
[ "func", "(", "s", "*", "segment", ")", "logicalLen", "(", ")", "seqnum", ".", "Size", "{", "l", ":=", "seqnum", ".", "Size", "(", "s", ".", "data", ".", "Size", "(", ")", ")", "\n", "if", "s", ".", "flagIsSet", "(", "header", ".", "TCPFlagSyn", ")", "{", "l", "++", "\n", "}", "\n", "if", "s", ".", "flagIsSet", "(", "header", ".", "TCPFlagFin", ")", "{", "l", "++", "\n", "}", "\n", "return", "l", "\n", "}" ]
// logicalLen is the segment length in the sequence number space. It's defined // as the data length plus one for each of the SYN and FIN bits set.
[ "logicalLen", "is", "the", "segment", "length", "in", "the", "sequence", "number", "space", ".", "It", "s", "defined", "as", "the", "data", "length", "plus", "one", "for", "each", "of", "the", "SYN", "and", "FIN", "bits", "set", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/segment.go#L118-L127
train
google/netstack
tcpip/transport/tcp/segment.go
parse
func (s *segment) parse() bool { h := header.TCP(s.data.First()) // h is the header followed by the payload. We check that the offset to // the data respects the following constraints: // 1. That it's at least the minimum header size; if we don't do this // then part of the header would be delivered to user. // 2. That the header fits within the buffer; if we don't do this, we // would panic when we tried to access data beyond the buffer. // // N.B. The segment has already been validated as having at least the // minimum TCP size before reaching here, so it's safe to read the // fields. offset := int(h.DataOffset()) if offset < header.TCPMinimumSize || offset > len(h) { return false } s.options = []byte(h[header.TCPMinimumSize:offset]) s.parsedOptions = header.ParseTCPOptions(s.options) // Query the link capabilities to decide if checksum validation is // required. verifyChecksum := true if s.route.Capabilities()&stack.CapabilityRXChecksumOffload != 0 { s.csumValid = true verifyChecksum = false s.data.TrimFront(offset) } if verifyChecksum { s.csum = h.Checksum() xsum := s.route.PseudoHeaderChecksum(ProtocolNumber, uint16(s.data.Size())) xsum = h.CalculateChecksum(xsum) s.data.TrimFront(offset) xsum = header.ChecksumVV(s.data, xsum) s.csumValid = xsum == 0xffff } s.sequenceNumber = seqnum.Value(h.SequenceNumber()) s.ackNumber = seqnum.Value(h.AckNumber()) s.flags = h.Flags() s.window = seqnum.Size(h.WindowSize()) return true }
go
func (s *segment) parse() bool { h := header.TCP(s.data.First()) // h is the header followed by the payload. We check that the offset to // the data respects the following constraints: // 1. That it's at least the minimum header size; if we don't do this // then part of the header would be delivered to user. // 2. That the header fits within the buffer; if we don't do this, we // would panic when we tried to access data beyond the buffer. // // N.B. The segment has already been validated as having at least the // minimum TCP size before reaching here, so it's safe to read the // fields. offset := int(h.DataOffset()) if offset < header.TCPMinimumSize || offset > len(h) { return false } s.options = []byte(h[header.TCPMinimumSize:offset]) s.parsedOptions = header.ParseTCPOptions(s.options) // Query the link capabilities to decide if checksum validation is // required. verifyChecksum := true if s.route.Capabilities()&stack.CapabilityRXChecksumOffload != 0 { s.csumValid = true verifyChecksum = false s.data.TrimFront(offset) } if verifyChecksum { s.csum = h.Checksum() xsum := s.route.PseudoHeaderChecksum(ProtocolNumber, uint16(s.data.Size())) xsum = h.CalculateChecksum(xsum) s.data.TrimFront(offset) xsum = header.ChecksumVV(s.data, xsum) s.csumValid = xsum == 0xffff } s.sequenceNumber = seqnum.Value(h.SequenceNumber()) s.ackNumber = seqnum.Value(h.AckNumber()) s.flags = h.Flags() s.window = seqnum.Size(h.WindowSize()) return true }
[ "func", "(", "s", "*", "segment", ")", "parse", "(", ")", "bool", "{", "h", ":=", "header", ".", "TCP", "(", "s", ".", "data", ".", "First", "(", ")", ")", "\n", "offset", ":=", "int", "(", "h", ".", "DataOffset", "(", ")", ")", "\n", "if", "offset", "<", "header", ".", "TCPMinimumSize", "||", "offset", ">", "len", "(", "h", ")", "{", "return", "false", "\n", "}", "\n", "s", ".", "options", "=", "[", "]", "byte", "(", "h", "[", "header", ".", "TCPMinimumSize", ":", "offset", "]", ")", "\n", "s", ".", "parsedOptions", "=", "header", ".", "ParseTCPOptions", "(", "s", ".", "options", ")", "\n", "verifyChecksum", ":=", "true", "\n", "if", "s", ".", "route", ".", "Capabilities", "(", ")", "&", "stack", ".", "CapabilityRXChecksumOffload", "!=", "0", "{", "s", ".", "csumValid", "=", "true", "\n", "verifyChecksum", "=", "false", "\n", "s", ".", "data", ".", "TrimFront", "(", "offset", ")", "\n", "}", "\n", "if", "verifyChecksum", "{", "s", ".", "csum", "=", "h", ".", "Checksum", "(", ")", "\n", "xsum", ":=", "s", ".", "route", ".", "PseudoHeaderChecksum", "(", "ProtocolNumber", ",", "uint16", "(", "s", ".", "data", ".", "Size", "(", ")", ")", ")", "\n", "xsum", "=", "h", ".", "CalculateChecksum", "(", "xsum", ")", "\n", "s", ".", "data", ".", "TrimFront", "(", "offset", ")", "\n", "xsum", "=", "header", ".", "ChecksumVV", "(", "s", ".", "data", ",", "xsum", ")", "\n", "s", ".", "csumValid", "=", "xsum", "==", "0xffff", "\n", "}", "\n", "s", ".", "sequenceNumber", "=", "seqnum", ".", "Value", "(", "h", ".", "SequenceNumber", "(", ")", ")", "\n", "s", ".", "ackNumber", "=", "seqnum", ".", "Value", "(", "h", ".", "AckNumber", "(", ")", ")", "\n", "s", ".", "flags", "=", "h", ".", "Flags", "(", ")", "\n", "s", ".", "window", "=", "seqnum", ".", "Size", "(", "h", ".", "WindowSize", "(", ")", ")", "\n", "return", "true", "\n", "}" ]
// parse populates the sequence & ack numbers, flags, and window fields of the // segment from the TCP header stored in the data. It then updates the view to // skip the header. // // Returns boolean indicating if the parsing was successful. // // If checksum verification is not offloaded then parse also verifies the // TCP checksum and stores the checksum and result of checksum verification in // the csum and csumValid fields of the segment.
[ "parse", "populates", "the", "sequence", "&", "ack", "numbers", "flags", "and", "window", "fields", "of", "the", "segment", "from", "the", "TCP", "header", "stored", "in", "the", "data", ".", "It", "then", "updates", "the", "view", "to", "skip", "the", "header", ".", "Returns", "boolean", "indicating", "if", "the", "parsing", "was", "successful", ".", "If", "checksum", "verification", "is", "not", "offloaded", "then", "parse", "also", "verifies", "the", "TCP", "checksum", "and", "stores", "the", "checksum", "and", "result", "of", "checksum", "verification", "in", "the", "csum", "and", "csumValid", "fields", "of", "the", "segment", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/segment.go#L138-L181
train
google/netstack
tcpip/link/waitable/waitable.go
DeliverNetworkPacket
func (e *Endpoint) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView) { if !e.dispatchGate.Enter() { return } e.dispatcher.DeliverNetworkPacket(e, remote, local, protocol, vv) e.dispatchGate.Leave() }
go
func (e *Endpoint) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView) { if !e.dispatchGate.Enter() { return } e.dispatcher.DeliverNetworkPacket(e, remote, local, protocol, vv) e.dispatchGate.Leave() }
[ "func", "(", "e", "*", "Endpoint", ")", "DeliverNetworkPacket", "(", "linkEP", "stack", ".", "LinkEndpoint", ",", "remote", ",", "local", "tcpip", ".", "LinkAddress", ",", "protocol", "tcpip", ".", "NetworkProtocolNumber", ",", "vv", "buffer", ".", "VectorisedView", ")", "{", "if", "!", "e", ".", "dispatchGate", ".", "Enter", "(", ")", "{", "return", "\n", "}", "\n", "e", ".", "dispatcher", ".", "DeliverNetworkPacket", "(", "e", ",", "remote", ",", "local", ",", "protocol", ",", "vv", ")", "\n", "e", ".", "dispatchGate", ".", "Leave", "(", ")", "\n", "}" ]
// DeliverNetworkPacket implements stack.NetworkDispatcher.DeliverNetworkPacket. // It is called by the link-layer endpoint being wrapped when a packet arrives, // and only forwards to the actual dispatcher if Wait or WaitDispatch haven't // been called.
[ "DeliverNetworkPacket", "implements", "stack", ".", "NetworkDispatcher", ".", "DeliverNetworkPacket", ".", "It", "is", "called", "by", "the", "link", "-", "layer", "endpoint", "being", "wrapped", "when", "a", "packet", "arrives", "and", "only", "forwards", "to", "the", "actual", "dispatcher", "if", "Wait", "or", "WaitDispatch", "haven", "t", "been", "called", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/waitable/waitable.go#L54-L61
train
google/netstack
tcpip/link/waitable/waitable.go
Attach
func (e *Endpoint) Attach(dispatcher stack.NetworkDispatcher) { e.dispatcher = dispatcher e.lower.Attach(e) }
go
func (e *Endpoint) Attach(dispatcher stack.NetworkDispatcher) { e.dispatcher = dispatcher e.lower.Attach(e) }
[ "func", "(", "e", "*", "Endpoint", ")", "Attach", "(", "dispatcher", "stack", ".", "NetworkDispatcher", ")", "{", "e", ".", "dispatcher", "=", "dispatcher", "\n", "e", ".", "lower", ".", "Attach", "(", "e", ")", "\n", "}" ]
// Attach implements stack.LinkEndpoint.Attach. It saves the dispatcher and // registers with the lower endpoint as its dispatcher so that "e" is called // for inbound packets.
[ "Attach", "implements", "stack", ".", "LinkEndpoint", ".", "Attach", ".", "It", "saves", "the", "dispatcher", "and", "registers", "with", "the", "lower", "endpoint", "as", "its", "dispatcher", "so", "that", "e", "is", "called", "for", "inbound", "packets", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/waitable/waitable.go#L66-L69
train
google/netstack
tcpip/link/waitable/waitable.go
WritePacket
func (e *Endpoint) WritePacket(r *stack.Route, gso *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) *tcpip.Error { if !e.writeGate.Enter() { return nil } err := e.lower.WritePacket(r, gso, hdr, payload, protocol) e.writeGate.Leave() return err }
go
func (e *Endpoint) WritePacket(r *stack.Route, gso *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) *tcpip.Error { if !e.writeGate.Enter() { return nil } err := e.lower.WritePacket(r, gso, hdr, payload, protocol) e.writeGate.Leave() return err }
[ "func", "(", "e", "*", "Endpoint", ")", "WritePacket", "(", "r", "*", "stack", ".", "Route", ",", "gso", "*", "stack", ".", "GSO", ",", "hdr", "buffer", ".", "Prependable", ",", "payload", "buffer", ".", "VectorisedView", ",", "protocol", "tcpip", ".", "NetworkProtocolNumber", ")", "*", "tcpip", ".", "Error", "{", "if", "!", "e", ".", "writeGate", ".", "Enter", "(", ")", "{", "return", "nil", "\n", "}", "\n", "err", ":=", "e", ".", "lower", ".", "WritePacket", "(", "r", ",", "gso", ",", "hdr", ",", "payload", ",", "protocol", ")", "\n", "e", ".", "writeGate", ".", "Leave", "(", ")", "\n", "return", "err", "\n", "}" ]
// WritePacket implements stack.LinkEndpoint.WritePacket. It is called by // higher-level protocols to write packets. It only forwards packets to the // lower endpoint if Wait or WaitWrite haven't been called.
[ "WritePacket", "implements", "stack", ".", "LinkEndpoint", ".", "WritePacket", ".", "It", "is", "called", "by", "higher", "-", "level", "protocols", "to", "write", "packets", ".", "It", "only", "forwards", "packets", "to", "the", "lower", "endpoint", "if", "Wait", "or", "WaitWrite", "haven", "t", "been", "called", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/waitable/waitable.go#L103-L111
train
google/netstack
tcpip/link/sharedmem/pipe/tx.go
Init
func (t *Tx) Init(b []byte) { t.p.init(b) // maxPayloadSize excludes the header of the payload, and the header // of the wrapping message. t.maxPayloadSize = uint64(len(t.p.buffer)) - 2*sizeOfSlotHeader t.tail = 0xfffffffe * jump t.next = t.tail t.head = t.tail + jump t.p.write(t.tail, slotFree) }
go
func (t *Tx) Init(b []byte) { t.p.init(b) // maxPayloadSize excludes the header of the payload, and the header // of the wrapping message. t.maxPayloadSize = uint64(len(t.p.buffer)) - 2*sizeOfSlotHeader t.tail = 0xfffffffe * jump t.next = t.tail t.head = t.tail + jump t.p.write(t.tail, slotFree) }
[ "func", "(", "t", "*", "Tx", ")", "Init", "(", "b", "[", "]", "byte", ")", "{", "t", ".", "p", ".", "init", "(", "b", ")", "\n", "t", ".", "maxPayloadSize", "=", "uint64", "(", "len", "(", "t", ".", "p", ".", "buffer", ")", ")", "-", "2", "*", "sizeOfSlotHeader", "\n", "t", ".", "tail", "=", "0xfffffffe", "*", "jump", "\n", "t", ".", "next", "=", "t", ".", "tail", "\n", "t", ".", "head", "=", "t", ".", "tail", "+", "jump", "\n", "t", ".", "p", ".", "write", "(", "t", ".", "tail", ",", "slotFree", ")", "\n", "}" ]
// Init initializes the transmit end of the pipe. In the initial state, the next // slot to be written is the very first one, and the transmitter has the whole // ring buffer available to it.
[ "Init", "initializes", "the", "transmit", "end", "of", "the", "pipe", ".", "In", "the", "initial", "state", "the", "next", "slot", "to", "be", "written", "is", "the", "very", "first", "one", "and", "the", "transmitter", "has", "the", "whole", "ring", "buffer", "available", "to", "it", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/pipe/tx.go#L32-L41
train
google/netstack
tcpip/link/sharedmem/pipe/tx.go
Capacity
func (t *Tx) Capacity(recordSize uint64) uint64 { available := uint64(len(t.p.buffer)) - sizeOfSlotHeader entryLen := payloadToSlotSize(recordSize) return available / entryLen }
go
func (t *Tx) Capacity(recordSize uint64) uint64 { available := uint64(len(t.p.buffer)) - sizeOfSlotHeader entryLen := payloadToSlotSize(recordSize) return available / entryLen }
[ "func", "(", "t", "*", "Tx", ")", "Capacity", "(", "recordSize", "uint64", ")", "uint64", "{", "available", ":=", "uint64", "(", "len", "(", "t", ".", "p", ".", "buffer", ")", ")", "-", "sizeOfSlotHeader", "\n", "entryLen", ":=", "payloadToSlotSize", "(", "recordSize", ")", "\n", "return", "available", "/", "entryLen", "\n", "}" ]
// Capacity determines how many records of the given size can be written to the // pipe before it fills up.
[ "Capacity", "determines", "how", "many", "records", "of", "the", "given", "size", "can", "be", "written", "to", "the", "pipe", "before", "it", "fills", "up", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/pipe/tx.go#L45-L49
train
google/netstack
tcpip/link/fdbased/endpoint.go
New
func New(opts *Options) (tcpip.LinkEndpointID, error) { if err := syscall.SetNonblock(opts.FD, true); err != nil { return 0, fmt.Errorf("syscall.SetNonblock(%v) failed: %v", opts.FD, err) } caps := stack.LinkEndpointCapabilities(0) if opts.RXChecksumOffload { caps |= stack.CapabilityRXChecksumOffload } if opts.TXChecksumOffload { caps |= stack.CapabilityTXChecksumOffload } hdrSize := 0 if opts.EthernetHeader { hdrSize = header.EthernetMinimumSize caps |= stack.CapabilityResolutionRequired } if opts.SaveRestore { caps |= stack.CapabilitySaveRestore } if opts.DisconnectOk { caps |= stack.CapabilityDisconnectOk } e := &endpoint{ fd: opts.FD, mtu: opts.MTU, caps: caps, closed: opts.ClosedFunc, addr: opts.Address, hdrSize: hdrSize, packetDispatchMode: opts.PacketDispatchMode, } // For non-socket FDs we read one packet a time (e.g. TAP devices). msgsPerRecv := 1 e.inboundDispatcher = e.dispatch isSocket, err := isSocketFD(opts.FD) if err != nil { return 0, err } if isSocket { if opts.GSOMaxSize != 0 { e.caps |= stack.CapabilityGSO e.gsoMaxSize = opts.GSOMaxSize } switch e.packetDispatchMode { case PacketMMap: if err := e.setupPacketRXRing(); err != nil { return 0, fmt.Errorf("e.setupPacketRXRing failed: %v", err) } e.inboundDispatcher = e.packetMMapDispatch return stack.RegisterLinkEndpoint(e), nil case RecvMMsg: // If the provided FD is a socket then we optimize // packet reads by using recvmmsg() instead of read() to // read packets in a batch. e.inboundDispatcher = e.recvMMsgDispatch msgsPerRecv = MaxMsgsPerRecv } } e.views = make([][]buffer.View, msgsPerRecv) for i := range e.views { e.views[i] = make([]buffer.View, len(BufConfig)) } e.iovecs = make([][]syscall.Iovec, msgsPerRecv) iovLen := len(BufConfig) if e.Capabilities()&stack.CapabilityGSO != 0 { // virtioNetHdr is prepended before each packet. iovLen++ } for i := range e.iovecs { e.iovecs[i] = make([]syscall.Iovec, iovLen) } e.msgHdrs = make([]rawfile.MMsgHdr, msgsPerRecv) for i := range e.msgHdrs { e.msgHdrs[i].Msg.Iov = &e.iovecs[i][0] e.msgHdrs[i].Msg.Iovlen = uint64(iovLen) } return stack.RegisterLinkEndpoint(e), nil }
go
func New(opts *Options) (tcpip.LinkEndpointID, error) { if err := syscall.SetNonblock(opts.FD, true); err != nil { return 0, fmt.Errorf("syscall.SetNonblock(%v) failed: %v", opts.FD, err) } caps := stack.LinkEndpointCapabilities(0) if opts.RXChecksumOffload { caps |= stack.CapabilityRXChecksumOffload } if opts.TXChecksumOffload { caps |= stack.CapabilityTXChecksumOffload } hdrSize := 0 if opts.EthernetHeader { hdrSize = header.EthernetMinimumSize caps |= stack.CapabilityResolutionRequired } if opts.SaveRestore { caps |= stack.CapabilitySaveRestore } if opts.DisconnectOk { caps |= stack.CapabilityDisconnectOk } e := &endpoint{ fd: opts.FD, mtu: opts.MTU, caps: caps, closed: opts.ClosedFunc, addr: opts.Address, hdrSize: hdrSize, packetDispatchMode: opts.PacketDispatchMode, } // For non-socket FDs we read one packet a time (e.g. TAP devices). msgsPerRecv := 1 e.inboundDispatcher = e.dispatch isSocket, err := isSocketFD(opts.FD) if err != nil { return 0, err } if isSocket { if opts.GSOMaxSize != 0 { e.caps |= stack.CapabilityGSO e.gsoMaxSize = opts.GSOMaxSize } switch e.packetDispatchMode { case PacketMMap: if err := e.setupPacketRXRing(); err != nil { return 0, fmt.Errorf("e.setupPacketRXRing failed: %v", err) } e.inboundDispatcher = e.packetMMapDispatch return stack.RegisterLinkEndpoint(e), nil case RecvMMsg: // If the provided FD is a socket then we optimize // packet reads by using recvmmsg() instead of read() to // read packets in a batch. e.inboundDispatcher = e.recvMMsgDispatch msgsPerRecv = MaxMsgsPerRecv } } e.views = make([][]buffer.View, msgsPerRecv) for i := range e.views { e.views[i] = make([]buffer.View, len(BufConfig)) } e.iovecs = make([][]syscall.Iovec, msgsPerRecv) iovLen := len(BufConfig) if e.Capabilities()&stack.CapabilityGSO != 0 { // virtioNetHdr is prepended before each packet. iovLen++ } for i := range e.iovecs { e.iovecs[i] = make([]syscall.Iovec, iovLen) } e.msgHdrs = make([]rawfile.MMsgHdr, msgsPerRecv) for i := range e.msgHdrs { e.msgHdrs[i].Msg.Iov = &e.iovecs[i][0] e.msgHdrs[i].Msg.Iovlen = uint64(iovLen) } return stack.RegisterLinkEndpoint(e), nil }
[ "func", "New", "(", "opts", "*", "Options", ")", "(", "tcpip", ".", "LinkEndpointID", ",", "error", ")", "{", "if", "err", ":=", "syscall", ".", "SetNonblock", "(", "opts", ".", "FD", ",", "true", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"syscall.SetNonblock(%v) failed: %v\"", ",", "opts", ".", "FD", ",", "err", ")", "\n", "}", "\n", "caps", ":=", "stack", ".", "LinkEndpointCapabilities", "(", "0", ")", "\n", "if", "opts", ".", "RXChecksumOffload", "{", "caps", "|=", "stack", ".", "CapabilityRXChecksumOffload", "\n", "}", "\n", "if", "opts", ".", "TXChecksumOffload", "{", "caps", "|=", "stack", ".", "CapabilityTXChecksumOffload", "\n", "}", "\n", "hdrSize", ":=", "0", "\n", "if", "opts", ".", "EthernetHeader", "{", "hdrSize", "=", "header", ".", "EthernetMinimumSize", "\n", "caps", "|=", "stack", ".", "CapabilityResolutionRequired", "\n", "}", "\n", "if", "opts", ".", "SaveRestore", "{", "caps", "|=", "stack", ".", "CapabilitySaveRestore", "\n", "}", "\n", "if", "opts", ".", "DisconnectOk", "{", "caps", "|=", "stack", ".", "CapabilityDisconnectOk", "\n", "}", "\n", "e", ":=", "&", "endpoint", "{", "fd", ":", "opts", ".", "FD", ",", "mtu", ":", "opts", ".", "MTU", ",", "caps", ":", "caps", ",", "closed", ":", "opts", ".", "ClosedFunc", ",", "addr", ":", "opts", ".", "Address", ",", "hdrSize", ":", "hdrSize", ",", "packetDispatchMode", ":", "opts", ".", "PacketDispatchMode", ",", "}", "\n", "msgsPerRecv", ":=", "1", "\n", "e", ".", "inboundDispatcher", "=", "e", ".", "dispatch", "\n", "isSocket", ",", "err", ":=", "isSocketFD", "(", "opts", ".", "FD", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "isSocket", "{", "if", "opts", ".", "GSOMaxSize", "!=", "0", "{", "e", ".", "caps", "|=", "stack", ".", "CapabilityGSO", "\n", "e", ".", "gsoMaxSize", "=", "opts", ".", "GSOMaxSize", "\n", "}", "\n", "switch", "e", ".", "packetDispatchMode", "{", "case", "PacketMMap", ":", "if", "err", ":=", "e", ".", "setupPacketRXRing", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"e.setupPacketRXRing failed: %v\"", ",", "err", ")", "\n", "}", "\n", "e", ".", "inboundDispatcher", "=", "e", ".", "packetMMapDispatch", "\n", "return", "stack", ".", "RegisterLinkEndpoint", "(", "e", ")", ",", "nil", "\n", "case", "RecvMMsg", ":", "e", ".", "inboundDispatcher", "=", "e", ".", "recvMMsgDispatch", "\n", "msgsPerRecv", "=", "MaxMsgsPerRecv", "\n", "}", "\n", "}", "\n", "e", ".", "views", "=", "make", "(", "[", "]", "[", "]", "buffer", ".", "View", ",", "msgsPerRecv", ")", "\n", "for", "i", ":=", "range", "e", ".", "views", "{", "e", ".", "views", "[", "i", "]", "=", "make", "(", "[", "]", "buffer", ".", "View", ",", "len", "(", "BufConfig", ")", ")", "\n", "}", "\n", "e", ".", "iovecs", "=", "make", "(", "[", "]", "[", "]", "syscall", ".", "Iovec", ",", "msgsPerRecv", ")", "\n", "iovLen", ":=", "len", "(", "BufConfig", ")", "\n", "if", "e", ".", "Capabilities", "(", ")", "&", "stack", ".", "CapabilityGSO", "!=", "0", "{", "iovLen", "++", "\n", "}", "\n", "for", "i", ":=", "range", "e", ".", "iovecs", "{", "e", ".", "iovecs", "[", "i", "]", "=", "make", "(", "[", "]", "syscall", ".", "Iovec", ",", "iovLen", ")", "\n", "}", "\n", "e", ".", "msgHdrs", "=", "make", "(", "[", "]", "rawfile", ".", "MMsgHdr", ",", "msgsPerRecv", ")", "\n", "for", "i", ":=", "range", "e", ".", "msgHdrs", "{", "e", ".", "msgHdrs", "[", "i", "]", ".", "Msg", ".", "Iov", "=", "&", "e", ".", "iovecs", "[", "i", "]", "[", "0", "]", "\n", "e", ".", "msgHdrs", "[", "i", "]", ".", "Msg", ".", "Iovlen", "=", "uint64", "(", "iovLen", ")", "\n", "}", "\n", "return", "stack", ".", "RegisterLinkEndpoint", "(", "e", ")", ",", "nil", "\n", "}" ]
// New creates a new fd-based endpoint. // // Makes fd non-blocking, but does not take ownership of fd, which must remain // open for the lifetime of the returned endpoint.
[ "New", "creates", "a", "new", "fd", "-", "based", "endpoint", ".", "Makes", "fd", "non", "-", "blocking", "but", "does", "not", "take", "ownership", "of", "fd", "which", "must", "remain", "open", "for", "the", "lifetime", "of", "the", "returned", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/fdbased/endpoint.go#L139-L228
train
google/netstack
tcpip/link/fdbased/endpoint.go
Attach
func (e *endpoint) Attach(dispatcher stack.NetworkDispatcher) { e.dispatcher = dispatcher // Link endpoints are not savable. When transportation endpoints are // saved, they stop sending outgoing packets and all incoming packets // are rejected. go e.dispatchLoop() }
go
func (e *endpoint) Attach(dispatcher stack.NetworkDispatcher) { e.dispatcher = dispatcher // Link endpoints are not savable. When transportation endpoints are // saved, they stop sending outgoing packets and all incoming packets // are rejected. go e.dispatchLoop() }
[ "func", "(", "e", "*", "endpoint", ")", "Attach", "(", "dispatcher", "stack", ".", "NetworkDispatcher", ")", "{", "e", ".", "dispatcher", "=", "dispatcher", "\n", "go", "e", ".", "dispatchLoop", "(", ")", "\n", "}" ]
// Attach launches the goroutine that reads packets from the file descriptor and // dispatches them via the provided dispatcher.
[ "Attach", "launches", "the", "goroutine", "that", "reads", "packets", "from", "the", "file", "descriptor", "and", "dispatches", "them", "via", "the", "provided", "dispatcher", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/fdbased/endpoint.go#L240-L246
train
google/netstack
tcpip/link/fdbased/endpoint.go
WriteRawPacket
func (e *endpoint) WriteRawPacket(dest tcpip.Address, packet []byte) *tcpip.Error { return rawfile.NonBlockingWrite(e.fd, packet) }
go
func (e *endpoint) WriteRawPacket(dest tcpip.Address, packet []byte) *tcpip.Error { return rawfile.NonBlockingWrite(e.fd, packet) }
[ "func", "(", "e", "*", "endpoint", ")", "WriteRawPacket", "(", "dest", "tcpip", ".", "Address", ",", "packet", "[", "]", "byte", ")", "*", "tcpip", ".", "Error", "{", "return", "rawfile", ".", "NonBlockingWrite", "(", "e", ".", "fd", ",", "packet", ")", "\n", "}" ]
// WriteRawPacket writes a raw packet directly to the file descriptor.
[ "WriteRawPacket", "writes", "a", "raw", "packet", "directly", "to", "the", "file", "descriptor", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/fdbased/endpoint.go#L346-L348
train
google/netstack
tcpip/link/fdbased/endpoint.go
recvMMsgDispatch
func (e *endpoint) recvMMsgDispatch() (bool, *tcpip.Error) { e.allocateViews(BufConfig) nMsgs, err := rawfile.BlockingRecvMMsg(e.fd, e.msgHdrs) if err != nil { return false, err } // Process each of received packets. for k := 0; k < nMsgs; k++ { n := int(e.msgHdrs[k].Len) if e.Capabilities()&stack.CapabilityGSO != 0 { n -= virtioNetHdrSize } if n <= e.hdrSize { return false, nil } var ( p tcpip.NetworkProtocolNumber remote, local tcpip.LinkAddress ) if e.hdrSize > 0 { eth := header.Ethernet(e.views[k][0]) 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(e.views[k][0]) { case header.IPv4Version: p = header.IPv4ProtocolNumber case header.IPv6Version: p = header.IPv6ProtocolNumber default: return true, nil } } used := e.capViews(k, int(n), BufConfig) vv := buffer.NewVectorisedView(int(n), e.views[k][:used]) vv.TrimFront(e.hdrSize) e.dispatcher.DeliverNetworkPacket(e, remote, local, p, vv) // Prepare e.views for another packet: release used views. for i := 0; i < used; i++ { e.views[k][i] = nil } } for k := 0; k < nMsgs; k++ { e.msgHdrs[k].Len = 0 } return true, nil }
go
func (e *endpoint) recvMMsgDispatch() (bool, *tcpip.Error) { e.allocateViews(BufConfig) nMsgs, err := rawfile.BlockingRecvMMsg(e.fd, e.msgHdrs) if err != nil { return false, err } // Process each of received packets. for k := 0; k < nMsgs; k++ { n := int(e.msgHdrs[k].Len) if e.Capabilities()&stack.CapabilityGSO != 0 { n -= virtioNetHdrSize } if n <= e.hdrSize { return false, nil } var ( p tcpip.NetworkProtocolNumber remote, local tcpip.LinkAddress ) if e.hdrSize > 0 { eth := header.Ethernet(e.views[k][0]) 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(e.views[k][0]) { case header.IPv4Version: p = header.IPv4ProtocolNumber case header.IPv6Version: p = header.IPv6ProtocolNumber default: return true, nil } } used := e.capViews(k, int(n), BufConfig) vv := buffer.NewVectorisedView(int(n), e.views[k][:used]) vv.TrimFront(e.hdrSize) e.dispatcher.DeliverNetworkPacket(e, remote, local, p, vv) // Prepare e.views for another packet: release used views. for i := 0; i < used; i++ { e.views[k][i] = nil } } for k := 0; k < nMsgs; k++ { e.msgHdrs[k].Len = 0 } return true, nil }
[ "func", "(", "e", "*", "endpoint", ")", "recvMMsgDispatch", "(", ")", "(", "bool", ",", "*", "tcpip", ".", "Error", ")", "{", "e", ".", "allocateViews", "(", "BufConfig", ")", "\n", "nMsgs", ",", "err", ":=", "rawfile", ".", "BlockingRecvMMsg", "(", "e", ".", "fd", ",", "e", ".", "msgHdrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "for", "k", ":=", "0", ";", "k", "<", "nMsgs", ";", "k", "++", "{", "n", ":=", "int", "(", "e", ".", "msgHdrs", "[", "k", "]", ".", "Len", ")", "\n", "if", "e", ".", "Capabilities", "(", ")", "&", "stack", ".", "CapabilityGSO", "!=", "0", "{", "n", "-=", "virtioNetHdrSize", "\n", "}", "\n", "if", "n", "<=", "e", ".", "hdrSize", "{", "return", "false", ",", "nil", "\n", "}", "\n", "var", "(", "p", "tcpip", ".", "NetworkProtocolNumber", "\n", "remote", ",", "local", "tcpip", ".", "LinkAddress", "\n", ")", "\n", "if", "e", ".", "hdrSize", ">", "0", "{", "eth", ":=", "header", ".", "Ethernet", "(", "e", ".", "views", "[", "k", "]", "[", "0", "]", ")", "\n", "p", "=", "eth", ".", "Type", "(", ")", "\n", "remote", "=", "eth", ".", "SourceAddress", "(", ")", "\n", "local", "=", "eth", ".", "DestinationAddress", "(", ")", "\n", "}", "else", "{", "switch", "header", ".", "IPVersion", "(", "e", ".", "views", "[", "k", "]", "[", "0", "]", ")", "{", "case", "header", ".", "IPv4Version", ":", "p", "=", "header", ".", "IPv4ProtocolNumber", "\n", "case", "header", ".", "IPv6Version", ":", "p", "=", "header", ".", "IPv6ProtocolNumber", "\n", "default", ":", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "used", ":=", "e", ".", "capViews", "(", "k", ",", "int", "(", "n", ")", ",", "BufConfig", ")", "\n", "vv", ":=", "buffer", ".", "NewVectorisedView", "(", "int", "(", "n", ")", ",", "e", ".", "views", "[", "k", "]", "[", ":", "used", "]", ")", "\n", "vv", ".", "TrimFront", "(", "e", ".", "hdrSize", ")", "\n", "e", ".", "dispatcher", ".", "DeliverNetworkPacket", "(", "e", ",", "remote", ",", "local", ",", "p", ",", "vv", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "used", ";", "i", "++", "{", "e", ".", "views", "[", "k", "]", "[", "i", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "for", "k", ":=", "0", ";", "k", "<", "nMsgs", ";", "k", "++", "{", "e", ".", "msgHdrs", "[", "k", "]", ".", "Len", "=", "0", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// recvMMsgDispatch reads more than one packet at a time from the file // descriptor and dispatches it.
[ "recvMMsgDispatch", "reads", "more", "than", "one", "packet", "at", "a", "time", "from", "the", "file", "descriptor", "and", "dispatches", "it", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/fdbased/endpoint.go#L445-L500
train
google/netstack
tcpip/link/fdbased/endpoint.go
dispatchLoop
func (e *endpoint) dispatchLoop() *tcpip.Error { for { cont, err := e.inboundDispatcher() if err != nil || !cont { if e.closed != nil { e.closed(err) } return err } } }
go
func (e *endpoint) dispatchLoop() *tcpip.Error { for { cont, err := e.inboundDispatcher() if err != nil || !cont { if e.closed != nil { e.closed(err) } return err } } }
[ "func", "(", "e", "*", "endpoint", ")", "dispatchLoop", "(", ")", "*", "tcpip", ".", "Error", "{", "for", "{", "cont", ",", "err", ":=", "e", ".", "inboundDispatcher", "(", ")", "\n", "if", "err", "!=", "nil", "||", "!", "cont", "{", "if", "e", ".", "closed", "!=", "nil", "{", "e", ".", "closed", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// dispatchLoop reads packets from the file descriptor in a loop and dispatches // them to the network stack.
[ "dispatchLoop", "reads", "packets", "from", "the", "file", "descriptor", "in", "a", "loop", "and", "dispatches", "them", "to", "the", "network", "stack", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/fdbased/endpoint.go#L504-L514
train
google/netstack
tcpip/link/fdbased/endpoint.go
NewInjectable
func NewInjectable(fd int, mtu uint32, capabilities stack.LinkEndpointCapabilities) (tcpip.LinkEndpointID, *InjectableEndpoint) { syscall.SetNonblock(fd, true) e := &InjectableEndpoint{endpoint: endpoint{ fd: fd, mtu: mtu, caps: capabilities, }} return stack.RegisterLinkEndpoint(e), e }
go
func NewInjectable(fd int, mtu uint32, capabilities stack.LinkEndpointCapabilities) (tcpip.LinkEndpointID, *InjectableEndpoint) { syscall.SetNonblock(fd, true) e := &InjectableEndpoint{endpoint: endpoint{ fd: fd, mtu: mtu, caps: capabilities, }} return stack.RegisterLinkEndpoint(e), e }
[ "func", "NewInjectable", "(", "fd", "int", ",", "mtu", "uint32", ",", "capabilities", "stack", ".", "LinkEndpointCapabilities", ")", "(", "tcpip", ".", "LinkEndpointID", ",", "*", "InjectableEndpoint", ")", "{", "syscall", ".", "SetNonblock", "(", "fd", ",", "true", ")", "\n", "e", ":=", "&", "InjectableEndpoint", "{", "endpoint", ":", "endpoint", "{", "fd", ":", "fd", ",", "mtu", ":", "mtu", ",", "caps", ":", "capabilities", ",", "}", "}", "\n", "return", "stack", ".", "RegisterLinkEndpoint", "(", "e", ")", ",", "e", "\n", "}" ]
// NewInjectable creates a new fd-based InjectableEndpoint.
[ "NewInjectable", "creates", "a", "new", "fd", "-", "based", "InjectableEndpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/fdbased/endpoint.go#L541-L551
train
google/netstack
tcpip/transport/tcp/sack.go
UpdateSACKBlocks
func UpdateSACKBlocks(sack *SACKInfo, segStart seqnum.Value, segEnd seqnum.Value, rcvNxt seqnum.Value) { newSB := header.SACKBlock{Start: segStart, End: segEnd} if sack.NumBlocks == 0 { sack.Blocks[0] = newSB sack.NumBlocks = 1 return } var n = 0 for i := 0; i < sack.NumBlocks; i++ { start, end := sack.Blocks[i].Start, sack.Blocks[i].End if end.LessThanEq(start) || start.LessThanEq(rcvNxt) { // Discard any invalid blocks where end is before start // and discard any sack blocks that are before rcvNxt as // those have already been acked. continue } if newSB.Start.LessThanEq(end) && start.LessThanEq(newSB.End) { // Merge this SACK block into newSB and discard this SACK // block. if start.LessThan(newSB.Start) { newSB.Start = start } if newSB.End.LessThan(end) { newSB.End = end } } else { // Save this block. sack.Blocks[n] = sack.Blocks[i] n++ } } if rcvNxt.LessThan(newSB.Start) { // If this was an out of order segment then make sure that the // first SACK block is the one that includes the segment. // // See the first bullet point in // https://tools.ietf.org/html/rfc2018#section-4 if n == MaxSACKBlocks { // If the number of SACK blocks is equal to // MaxSACKBlocks then discard the last SACK block. n-- } for i := n - 1; i >= 0; i-- { sack.Blocks[i+1] = sack.Blocks[i] } sack.Blocks[0] = newSB n++ } sack.NumBlocks = n }
go
func UpdateSACKBlocks(sack *SACKInfo, segStart seqnum.Value, segEnd seqnum.Value, rcvNxt seqnum.Value) { newSB := header.SACKBlock{Start: segStart, End: segEnd} if sack.NumBlocks == 0 { sack.Blocks[0] = newSB sack.NumBlocks = 1 return } var n = 0 for i := 0; i < sack.NumBlocks; i++ { start, end := sack.Blocks[i].Start, sack.Blocks[i].End if end.LessThanEq(start) || start.LessThanEq(rcvNxt) { // Discard any invalid blocks where end is before start // and discard any sack blocks that are before rcvNxt as // those have already been acked. continue } if newSB.Start.LessThanEq(end) && start.LessThanEq(newSB.End) { // Merge this SACK block into newSB and discard this SACK // block. if start.LessThan(newSB.Start) { newSB.Start = start } if newSB.End.LessThan(end) { newSB.End = end } } else { // Save this block. sack.Blocks[n] = sack.Blocks[i] n++ } } if rcvNxt.LessThan(newSB.Start) { // If this was an out of order segment then make sure that the // first SACK block is the one that includes the segment. // // See the first bullet point in // https://tools.ietf.org/html/rfc2018#section-4 if n == MaxSACKBlocks { // If the number of SACK blocks is equal to // MaxSACKBlocks then discard the last SACK block. n-- } for i := n - 1; i >= 0; i-- { sack.Blocks[i+1] = sack.Blocks[i] } sack.Blocks[0] = newSB n++ } sack.NumBlocks = n }
[ "func", "UpdateSACKBlocks", "(", "sack", "*", "SACKInfo", ",", "segStart", "seqnum", ".", "Value", ",", "segEnd", "seqnum", ".", "Value", ",", "rcvNxt", "seqnum", ".", "Value", ")", "{", "newSB", ":=", "header", ".", "SACKBlock", "{", "Start", ":", "segStart", ",", "End", ":", "segEnd", "}", "\n", "if", "sack", ".", "NumBlocks", "==", "0", "{", "sack", ".", "Blocks", "[", "0", "]", "=", "newSB", "\n", "sack", ".", "NumBlocks", "=", "1", "\n", "return", "\n", "}", "\n", "var", "n", "=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "sack", ".", "NumBlocks", ";", "i", "++", "{", "start", ",", "end", ":=", "sack", ".", "Blocks", "[", "i", "]", ".", "Start", ",", "sack", ".", "Blocks", "[", "i", "]", ".", "End", "\n", "if", "end", ".", "LessThanEq", "(", "start", ")", "||", "start", ".", "LessThanEq", "(", "rcvNxt", ")", "{", "continue", "\n", "}", "\n", "if", "newSB", ".", "Start", ".", "LessThanEq", "(", "end", ")", "&&", "start", ".", "LessThanEq", "(", "newSB", ".", "End", ")", "{", "if", "start", ".", "LessThan", "(", "newSB", ".", "Start", ")", "{", "newSB", ".", "Start", "=", "start", "\n", "}", "\n", "if", "newSB", ".", "End", ".", "LessThan", "(", "end", ")", "{", "newSB", ".", "End", "=", "end", "\n", "}", "\n", "}", "else", "{", "sack", ".", "Blocks", "[", "n", "]", "=", "sack", ".", "Blocks", "[", "i", "]", "\n", "n", "++", "\n", "}", "\n", "}", "\n", "if", "rcvNxt", ".", "LessThan", "(", "newSB", ".", "Start", ")", "{", "if", "n", "==", "MaxSACKBlocks", "{", "n", "--", "\n", "}", "\n", "for", "i", ":=", "n", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "sack", ".", "Blocks", "[", "i", "+", "1", "]", "=", "sack", ".", "Blocks", "[", "i", "]", "\n", "}", "\n", "sack", ".", "Blocks", "[", "0", "]", "=", "newSB", "\n", "n", "++", "\n", "}", "\n", "sack", ".", "NumBlocks", "=", "n", "\n", "}" ]
// UpdateSACKBlocks updates the list of SACK blocks to include the segment // specified by segStart->segEnd. If the segment happens to be an out of order // delivery then the first block in the sack.blocks always includes the // segment identified by segStart->segEnd.
[ "UpdateSACKBlocks", "updates", "the", "list", "of", "SACK", "blocks", "to", "include", "the", "segment", "specified", "by", "segStart", "-", ">", "segEnd", ".", "If", "the", "segment", "happens", "to", "be", "an", "out", "of", "order", "delivery", "then", "the", "first", "block", "in", "the", "sack", ".", "blocks", "always", "includes", "the", "segment", "identified", "by", "segStart", "-", ">", "segEnd", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack.go#L32-L81
train
google/netstack
tcpip/tcpip.go
NewSubnet
func NewSubnet(a Address, m AddressMask) (Subnet, error) { if len(a) != len(m) { return Subnet{}, errSubnetLengthMismatch } for i := 0; i < len(a); i++ { if a[i]&^m[i] != 0 { return Subnet{}, errSubnetAddressMasked } } return Subnet{a, m}, nil }
go
func NewSubnet(a Address, m AddressMask) (Subnet, error) { if len(a) != len(m) { return Subnet{}, errSubnetLengthMismatch } for i := 0; i < len(a); i++ { if a[i]&^m[i] != 0 { return Subnet{}, errSubnetAddressMasked } } return Subnet{a, m}, nil }
[ "func", "NewSubnet", "(", "a", "Address", ",", "m", "AddressMask", ")", "(", "Subnet", ",", "error", ")", "{", "if", "len", "(", "a", ")", "!=", "len", "(", "m", ")", "{", "return", "Subnet", "{", "}", ",", "errSubnetLengthMismatch", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "a", ")", ";", "i", "++", "{", "if", "a", "[", "i", "]", "&^", "m", "[", "i", "]", "!=", "0", "{", "return", "Subnet", "{", "}", ",", "errSubnetAddressMasked", "\n", "}", "\n", "}", "\n", "return", "Subnet", "{", "a", ",", "m", "}", ",", "nil", "\n", "}" ]
// NewSubnet creates a new Subnet, checking that the address and mask are the same length.
[ "NewSubnet", "creates", "a", "new", "Subnet", "checking", "that", "the", "address", "and", "mask", "are", "the", "same", "length", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L157-L167
train
google/netstack
tcpip/tcpip.go
Contains
func (s *Subnet) Contains(a Address) bool { if len(a) != len(s.address) { return false } for i := 0; i < len(a); i++ { if a[i]&s.mask[i] != s.address[i] { return false } } return true }
go
func (s *Subnet) Contains(a Address) bool { if len(a) != len(s.address) { return false } for i := 0; i < len(a); i++ { if a[i]&s.mask[i] != s.address[i] { return false } } return true }
[ "func", "(", "s", "*", "Subnet", ")", "Contains", "(", "a", "Address", ")", "bool", "{", "if", "len", "(", "a", ")", "!=", "len", "(", "s", ".", "address", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "a", ")", ";", "i", "++", "{", "if", "a", "[", "i", "]", "&", "s", ".", "mask", "[", "i", "]", "!=", "s", ".", "address", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Contains returns true iff the address is of the same length and matches the // subnet address and mask.
[ "Contains", "returns", "true", "iff", "the", "address", "is", "of", "the", "same", "length", "and", "matches", "the", "subnet", "address", "and", "mask", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L171-L181
train
google/netstack
tcpip/tcpip.go
Prefix
func (s *Subnet) Prefix() int { for i, b := range []byte(s.mask) { for j := 7; j >= 0; j-- { if b&(1<<uint(j)) == 0 { return i*8 + 7 - j } } } return len(s.mask) * 8 }
go
func (s *Subnet) Prefix() int { for i, b := range []byte(s.mask) { for j := 7; j >= 0; j-- { if b&(1<<uint(j)) == 0 { return i*8 + 7 - j } } } return len(s.mask) * 8 }
[ "func", "(", "s", "*", "Subnet", ")", "Prefix", "(", ")", "int", "{", "for", "i", ",", "b", ":=", "range", "[", "]", "byte", "(", "s", ".", "mask", ")", "{", "for", "j", ":=", "7", ";", "j", ">=", "0", ";", "j", "--", "{", "if", "b", "&", "(", "1", "<<", "uint", "(", "j", ")", ")", "==", "0", "{", "return", "i", "*", "8", "+", "7", "-", "j", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "len", "(", "s", ".", "mask", ")", "*", "8", "\n", "}" ]
// Prefix returns the number of bits before the first host bit.
[ "Prefix", "returns", "the", "number", "of", "bits", "before", "the", "first", "host", "bit", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L204-L213
train
google/netstack
tcpip/tcpip.go
Get
func (s SlicePayload) Get(size int) ([]byte, *Error) { if size > s.Size() { size = s.Size() } return s[:size], nil }
go
func (s SlicePayload) Get(size int) ([]byte, *Error) { if size > s.Size() { size = s.Size() } return s[:size], nil }
[ "func", "(", "s", "SlicePayload", ")", "Get", "(", "size", "int", ")", "(", "[", "]", "byte", ",", "*", "Error", ")", "{", "if", "size", ">", "s", ".", "Size", "(", ")", "{", "size", "=", "s", ".", "Size", "(", ")", "\n", "}", "\n", "return", "s", "[", ":", "size", "]", ",", "nil", "\n", "}" ]
// Get implements Payload.
[ "Get", "implements", "Payload", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L268-L273
train
google/netstack
tcpip/tcpip.go
Match
func (r *Route) Match(addr Address) bool { if len(addr) != len(r.Destination) { return false } // Using header.Ipv4Broadcast would introduce an import cycle, so // we'll use a literal instead. if addr == "\xff\xff\xff\xff" { return true } for i := 0; i < len(r.Destination); i++ { if (addr[i] & r.Mask[i]) != r.Destination[i] { return false } } return true }
go
func (r *Route) Match(addr Address) bool { if len(addr) != len(r.Destination) { return false } // Using header.Ipv4Broadcast would introduce an import cycle, so // we'll use a literal instead. if addr == "\xff\xff\xff\xff" { return true } for i := 0; i < len(r.Destination); i++ { if (addr[i] & r.Mask[i]) != r.Destination[i] { return false } } return true }
[ "func", "(", "r", "*", "Route", ")", "Match", "(", "addr", "Address", ")", "bool", "{", "if", "len", "(", "addr", ")", "!=", "len", "(", "r", ".", "Destination", ")", "{", "return", "false", "\n", "}", "\n", "if", "addr", "==", "\"\\xff\\xff\\xff\\xff\"", "\\xff", "\n", "\\xff", "\n", "\\xff", "\n", "}" ]
// Match determines if r is viable for the given destination address.
[ "Match", "determines", "if", "r", "is", "viable", "for", "the", "given", "destination", "address", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L532-L550
train
google/netstack
tcpip/tcpip.go
IncrementBy
func (s *StatCounter) IncrementBy(v uint64) { atomic.AddUint64(&s.count, v) }
go
func (s *StatCounter) IncrementBy(v uint64) { atomic.AddUint64(&s.count, v) }
[ "func", "(", "s", "*", "StatCounter", ")", "IncrementBy", "(", "v", "uint64", ")", "{", "atomic", ".", "AddUint64", "(", "&", "s", ".", "count", ",", "v", ")", "\n", "}" ]
// IncrementBy increments the counter by v.
[ "IncrementBy", "increments", "the", "counter", "by", "v", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L577-L579
train
google/netstack
tcpip/tcpip.go
FillIn
func (s Stats) FillIn() Stats { fillIn(reflect.ValueOf(&s).Elem()) return s }
go
func (s Stats) FillIn() Stats { fillIn(reflect.ValueOf(&s).Elem()) return s }
[ "func", "(", "s", "Stats", ")", "FillIn", "(", ")", "Stats", "{", "fillIn", "(", "reflect", ".", "ValueOf", "(", "&", "s", ")", ".", "Elem", "(", ")", ")", "\n", "return", "s", "\n", "}" ]
// FillIn returns a copy of s with nil fields initialized to new StatCounters.
[ "FillIn", "returns", "a", "copy", "of", "s", "with", "nil", "fields", "initialized", "to", "new", "StatCounters", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L877-L880
train
google/netstack
tcpip/tcpip.go
To4
func (a Address) To4() Address { const ( ipv4len = 4 ipv6len = 16 ) if len(a) == ipv4len { return a } if len(a) == ipv6len && isZeros(a[0:10]) && a[10] == 0xff && a[11] == 0xff { return a[12:16] } return "" }
go
func (a Address) To4() Address { const ( ipv4len = 4 ipv6len = 16 ) if len(a) == ipv4len { return a } if len(a) == ipv6len && isZeros(a[0:10]) && a[10] == 0xff && a[11] == 0xff { return a[12:16] } return "" }
[ "func", "(", "a", "Address", ")", "To4", "(", ")", "Address", "{", "const", "(", "ipv4len", "=", "4", "\n", "ipv6len", "=", "16", "\n", ")", "\n", "if", "len", "(", "a", ")", "==", "ipv4len", "{", "return", "a", "\n", "}", "\n", "if", "len", "(", "a", ")", "==", "ipv6len", "&&", "isZeros", "(", "a", "[", "0", ":", "10", "]", ")", "&&", "a", "[", "10", "]", "==", "0xff", "&&", "a", "[", "11", "]", "==", "0xff", "{", "return", "a", "[", "12", ":", "16", "]", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// To4 converts the IPv4 address to a 4-byte representation. // If the address is not an IPv4 address, To4 returns "".
[ "To4", "converts", "the", "IPv4", "address", "to", "a", "4", "-", "byte", "representation", ".", "If", "the", "address", "is", "not", "an", "IPv4", "address", "To4", "returns", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L931-L946
train
google/netstack
tcpip/tcpip.go
isZeros
func isZeros(a Address) bool { for i := 0; i < len(a); i++ { if a[i] != 0 { return false } } return true }
go
func isZeros(a Address) bool { for i := 0; i < len(a); i++ { if a[i] != 0 { return false } } return true }
[ "func", "isZeros", "(", "a", "Address", ")", "bool", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "a", ")", ";", "i", "++", "{", "if", "a", "[", "i", "]", "!=", "0", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isZeros reports whether a is all zeros.
[ "isZeros", "reports", "whether", "a", "is", "all", "zeros", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L949-L956
train
google/netstack
tcpip/tcpip.go
GetDanglingEndpoints
func GetDanglingEndpoints() []Endpoint { es := make([]Endpoint, 0, len(danglingEndpoints)) danglingEndpointsMu.Lock() for e := range danglingEndpoints { es = append(es, e) } danglingEndpointsMu.Unlock() return es }
go
func GetDanglingEndpoints() []Endpoint { es := make([]Endpoint, 0, len(danglingEndpoints)) danglingEndpointsMu.Lock() for e := range danglingEndpoints { es = append(es, e) } danglingEndpointsMu.Unlock() return es }
[ "func", "GetDanglingEndpoints", "(", ")", "[", "]", "Endpoint", "{", "es", ":=", "make", "(", "[", "]", "Endpoint", ",", "0", ",", "len", "(", "danglingEndpoints", ")", ")", "\n", "danglingEndpointsMu", ".", "Lock", "(", ")", "\n", "for", "e", ":=", "range", "danglingEndpoints", "{", "es", "=", "append", "(", "es", ",", "e", ")", "\n", "}", "\n", "danglingEndpointsMu", ".", "Unlock", "(", ")", "\n", "return", "es", "\n", "}" ]
// GetDanglingEndpoints returns all dangling endpoints.
[ "GetDanglingEndpoints", "returns", "all", "dangling", "endpoints", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L1010-L1018
train
google/netstack
tcpip/tcpip.go
DeleteDanglingEndpoint
func DeleteDanglingEndpoint(e Endpoint) { danglingEndpointsMu.Lock() delete(danglingEndpoints, e) danglingEndpointsMu.Unlock() }
go
func DeleteDanglingEndpoint(e Endpoint) { danglingEndpointsMu.Lock() delete(danglingEndpoints, e) danglingEndpointsMu.Unlock() }
[ "func", "DeleteDanglingEndpoint", "(", "e", "Endpoint", ")", "{", "danglingEndpointsMu", ".", "Lock", "(", ")", "\n", "delete", "(", "danglingEndpoints", ",", "e", ")", "\n", "danglingEndpointsMu", ".", "Unlock", "(", ")", "\n", "}" ]
// DeleteDanglingEndpoint removes a dangling endpoint.
[ "DeleteDanglingEndpoint", "removes", "a", "dangling", "endpoint", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/tcpip.go#L1028-L1032
train
google/netstack
tcpip/buffer/view.go
NewVectorisedView
func NewVectorisedView(size int, views []View) VectorisedView { return VectorisedView{views: views, size: size} }
go
func NewVectorisedView(size int, views []View) VectorisedView { return VectorisedView{views: views, size: size} }
[ "func", "NewVectorisedView", "(", "size", "int", ",", "views", "[", "]", "View", ")", "VectorisedView", "{", "return", "VectorisedView", "{", "views", ":", "views", ",", "size", ":", "size", "}", "\n", "}" ]
// NewVectorisedView creates a new vectorised view from an already-allocated slice // of View and sets its size.
[ "NewVectorisedView", "creates", "a", "new", "vectorised", "view", "from", "an", "already", "-", "allocated", "slice", "of", "View", "and", "sets", "its", "size", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L64-L66
train
google/netstack
tcpip/buffer/view.go
TrimFront
func (vv *VectorisedView) TrimFront(count int) { for count > 0 && len(vv.views) > 0 { if count < len(vv.views[0]) { vv.size -= count vv.views[0].TrimFront(count) return } count -= len(vv.views[0]) vv.RemoveFirst() } }
go
func (vv *VectorisedView) TrimFront(count int) { for count > 0 && len(vv.views) > 0 { if count < len(vv.views[0]) { vv.size -= count vv.views[0].TrimFront(count) return } count -= len(vv.views[0]) vv.RemoveFirst() } }
[ "func", "(", "vv", "*", "VectorisedView", ")", "TrimFront", "(", "count", "int", ")", "{", "for", "count", ">", "0", "&&", "len", "(", "vv", ".", "views", ")", ">", "0", "{", "if", "count", "<", "len", "(", "vv", ".", "views", "[", "0", "]", ")", "{", "vv", ".", "size", "-=", "count", "\n", "vv", ".", "views", "[", "0", "]", ".", "TrimFront", "(", "count", ")", "\n", "return", "\n", "}", "\n", "count", "-=", "len", "(", "vv", ".", "views", "[", "0", "]", ")", "\n", "vv", ".", "RemoveFirst", "(", ")", "\n", "}", "\n", "}" ]
// TrimFront removes the first "count" bytes of the vectorised view.
[ "TrimFront", "removes", "the", "first", "count", "bytes", "of", "the", "vectorised", "view", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L69-L79
train
google/netstack
tcpip/buffer/view.go
CapLength
func (vv *VectorisedView) CapLength(length int) { if length < 0 { length = 0 } if vv.size < length { return } vv.size = length for i := range vv.views { v := &vv.views[i] if len(*v) >= length { if length == 0 { vv.views = vv.views[:i] } else { v.CapLength(length) vv.views = vv.views[:i+1] } return } length -= len(*v) } }
go
func (vv *VectorisedView) CapLength(length int) { if length < 0 { length = 0 } if vv.size < length { return } vv.size = length for i := range vv.views { v := &vv.views[i] if len(*v) >= length { if length == 0 { vv.views = vv.views[:i] } else { v.CapLength(length) vv.views = vv.views[:i+1] } return } length -= len(*v) } }
[ "func", "(", "vv", "*", "VectorisedView", ")", "CapLength", "(", "length", "int", ")", "{", "if", "length", "<", "0", "{", "length", "=", "0", "\n", "}", "\n", "if", "vv", ".", "size", "<", "length", "{", "return", "\n", "}", "\n", "vv", ".", "size", "=", "length", "\n", "for", "i", ":=", "range", "vv", ".", "views", "{", "v", ":=", "&", "vv", ".", "views", "[", "i", "]", "\n", "if", "len", "(", "*", "v", ")", ">=", "length", "{", "if", "length", "==", "0", "{", "vv", ".", "views", "=", "vv", ".", "views", "[", ":", "i", "]", "\n", "}", "else", "{", "v", ".", "CapLength", "(", "length", ")", "\n", "vv", ".", "views", "=", "vv", ".", "views", "[", ":", "i", "+", "1", "]", "\n", "}", "\n", "return", "\n", "}", "\n", "length", "-=", "len", "(", "*", "v", ")", "\n", "}", "\n", "}" ]
// CapLength irreversibly reduces the length of the vectorised view.
[ "CapLength", "irreversibly", "reduces", "the", "length", "of", "the", "vectorised", "view", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L82-L103
train
google/netstack
tcpip/buffer/view.go
Clone
func (vv VectorisedView) Clone(buffer []View) VectorisedView { return VectorisedView{views: append(buffer[:0], vv.views...), size: vv.size} }
go
func (vv VectorisedView) Clone(buffer []View) VectorisedView { return VectorisedView{views: append(buffer[:0], vv.views...), size: vv.size} }
[ "func", "(", "vv", "VectorisedView", ")", "Clone", "(", "buffer", "[", "]", "View", ")", "VectorisedView", "{", "return", "VectorisedView", "{", "views", ":", "append", "(", "buffer", "[", ":", "0", "]", ",", "vv", ".", "views", "...", ")", ",", "size", ":", "vv", ".", "size", "}", "\n", "}" ]
// Clone returns a clone of this VectorisedView. // If the buffer argument is large enough to contain all the Views of this VectorisedView, // the method will avoid allocations and use the buffer to store the Views of the clone.
[ "Clone", "returns", "a", "clone", "of", "this", "VectorisedView", ".", "If", "the", "buffer", "argument", "is", "large", "enough", "to", "contain", "all", "the", "Views", "of", "this", "VectorisedView", "the", "method", "will", "avoid", "allocations", "and", "use", "the", "buffer", "to", "store", "the", "Views", "of", "the", "clone", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L108-L110
train
google/netstack
tcpip/buffer/view.go
First
func (vv VectorisedView) First() View { if len(vv.views) == 0 { return nil } return vv.views[0] }
go
func (vv VectorisedView) First() View { if len(vv.views) == 0 { return nil } return vv.views[0] }
[ "func", "(", "vv", "VectorisedView", ")", "First", "(", ")", "View", "{", "if", "len", "(", "vv", ".", "views", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "vv", ".", "views", "[", "0", "]", "\n", "}" ]
// First returns the first view of the vectorised view.
[ "First", "returns", "the", "first", "view", "of", "the", "vectorised", "view", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L113-L118
train
google/netstack
tcpip/buffer/view.go
RemoveFirst
func (vv *VectorisedView) RemoveFirst() { if len(vv.views) == 0 { return } vv.size -= len(vv.views[0]) vv.views = vv.views[1:] }
go
func (vv *VectorisedView) RemoveFirst() { if len(vv.views) == 0 { return } vv.size -= len(vv.views[0]) vv.views = vv.views[1:] }
[ "func", "(", "vv", "*", "VectorisedView", ")", "RemoveFirst", "(", ")", "{", "if", "len", "(", "vv", ".", "views", ")", "==", "0", "{", "return", "\n", "}", "\n", "vv", ".", "size", "-=", "len", "(", "vv", ".", "views", "[", "0", "]", ")", "\n", "vv", ".", "views", "=", "vv", ".", "views", "[", "1", ":", "]", "\n", "}" ]
// RemoveFirst removes the first view of the vectorised view.
[ "RemoveFirst", "removes", "the", "first", "view", "of", "the", "vectorised", "view", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L121-L127
train
google/netstack
tcpip/buffer/view.go
ToView
func (vv VectorisedView) ToView() View { if len(vv.views) == 1 { return vv.views[0] } u := make([]byte, 0, vv.size) for _, v := range vv.views { u = append(u, v...) } return u }
go
func (vv VectorisedView) ToView() View { if len(vv.views) == 1 { return vv.views[0] } u := make([]byte, 0, vv.size) for _, v := range vv.views { u = append(u, v...) } return u }
[ "func", "(", "vv", "VectorisedView", ")", "ToView", "(", ")", "View", "{", "if", "len", "(", "vv", ".", "views", ")", "==", "1", "{", "return", "vv", ".", "views", "[", "0", "]", "\n", "}", "\n", "u", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "vv", ".", "size", ")", "\n", "for", "_", ",", "v", ":=", "range", "vv", ".", "views", "{", "u", "=", "append", "(", "u", ",", "v", "...", ")", "\n", "}", "\n", "return", "u", "\n", "}" ]
// ToView returns a single view containing the content of the vectorised view. // // If the vectorised view contains a single view, that view will be returned // directly.
[ "ToView", "returns", "a", "single", "view", "containing", "the", "content", "of", "the", "vectorised", "view", ".", "If", "the", "vectorised", "view", "contains", "a", "single", "view", "that", "view", "will", "be", "returned", "directly", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L138-L147
train
google/netstack
tcpip/buffer/view.go
Append
func (vv *VectorisedView) Append(vv2 VectorisedView) { vv.views = append(vv.views, vv2.views...) vv.size += vv2.size }
go
func (vv *VectorisedView) Append(vv2 VectorisedView) { vv.views = append(vv.views, vv2.views...) vv.size += vv2.size }
[ "func", "(", "vv", "*", "VectorisedView", ")", "Append", "(", "vv2", "VectorisedView", ")", "{", "vv", ".", "views", "=", "append", "(", "vv", ".", "views", ",", "vv2", ".", "views", "...", ")", "\n", "vv", ".", "size", "+=", "vv2", ".", "size", "\n", "}" ]
// Append appends the views in a vectorised view to this vectorised view.
[ "Append", "appends", "the", "views", "in", "a", "vectorised", "view", "to", "this", "vectorised", "view", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/buffer/view.go#L155-L158
train
google/netstack
tcpip/transport/tcp/cubic.go
newCubicCC
func newCubicCC(s *sender) *cubicState { return &cubicState{ t: time.Now(), beta: 0.7, c: 0.4, s: s, } }
go
func newCubicCC(s *sender) *cubicState { return &cubicState{ t: time.Now(), beta: 0.7, c: 0.4, s: s, } }
[ "func", "newCubicCC", "(", "s", "*", "sender", ")", "*", "cubicState", "{", "return", "&", "cubicState", "{", "t", ":", "time", ".", "Now", "(", ")", ",", "beta", ":", "0.7", ",", "c", ":", "0.4", ",", "s", ":", "s", ",", "}", "\n", "}" ]
// newCubicCC returns a partially initialized cubic state with the constants // beta and c set and t set to current time.
[ "newCubicCC", "returns", "a", "partially", "initialized", "cubic", "state", "with", "the", "constants", "beta", "and", "c", "set", "and", "t", "set", "to", "current", "time", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/cubic.go#L73-L80
train
google/netstack
tcpip/transport/tcp/cubic.go
updateSlowStart
func (c *cubicState) updateSlowStart(packetsAcked int) int { // Don't let the congestion window cross into the congestion // avoidance range. newcwnd := c.s.sndCwnd + packetsAcked enterCA := false if newcwnd >= c.s.sndSsthresh { newcwnd = c.s.sndSsthresh c.s.sndCAAckCount = 0 enterCA = true } packetsAcked -= newcwnd - c.s.sndCwnd c.s.sndCwnd = newcwnd if enterCA { c.enterCongestionAvoidance() } return packetsAcked }
go
func (c *cubicState) updateSlowStart(packetsAcked int) int { // Don't let the congestion window cross into the congestion // avoidance range. newcwnd := c.s.sndCwnd + packetsAcked enterCA := false if newcwnd >= c.s.sndSsthresh { newcwnd = c.s.sndSsthresh c.s.sndCAAckCount = 0 enterCA = true } packetsAcked -= newcwnd - c.s.sndCwnd c.s.sndCwnd = newcwnd if enterCA { c.enterCongestionAvoidance() } return packetsAcked }
[ "func", "(", "c", "*", "cubicState", ")", "updateSlowStart", "(", "packetsAcked", "int", ")", "int", "{", "newcwnd", ":=", "c", ".", "s", ".", "sndCwnd", "+", "packetsAcked", "\n", "enterCA", ":=", "false", "\n", "if", "newcwnd", ">=", "c", ".", "s", ".", "sndSsthresh", "{", "newcwnd", "=", "c", ".", "s", ".", "sndSsthresh", "\n", "c", ".", "s", ".", "sndCAAckCount", "=", "0", "\n", "enterCA", "=", "true", "\n", "}", "\n", "packetsAcked", "-=", "newcwnd", "-", "c", ".", "s", ".", "sndCwnd", "\n", "c", ".", "s", ".", "sndCwnd", "=", "newcwnd", "\n", "if", "enterCA", "{", "c", ".", "enterCongestionAvoidance", "(", ")", "\n", "}", "\n", "return", "packetsAcked", "\n", "}" ]
// updateSlowStart will update the congestion window as per the slow-start // algorithm used by NewReno. If after adjusting the congestion window we cross // the ssThresh then it will return the number of packets that must be consumed // in congestion avoidance mode.
[ "updateSlowStart", "will", "update", "the", "congestion", "window", "as", "per", "the", "slow", "-", "start", "algorithm", "used", "by", "NewReno", ".", "If", "after", "adjusting", "the", "congestion", "window", "we", "cross", "the", "ssThresh", "then", "it", "will", "return", "the", "number", "of", "packets", "that", "must", "be", "consumed", "in", "congestion", "avoidance", "mode", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/cubic.go#L103-L120
train
google/netstack
tcpip/transport/tcp/cubic.go
cubicCwnd
func (c *cubicState) cubicCwnd(t float64) float64 { return c.c*math.Pow(t, 3.0) + c.wMax }
go
func (c *cubicState) cubicCwnd(t float64) float64 { return c.c*math.Pow(t, 3.0) + c.wMax }
[ "func", "(", "c", "*", "cubicState", ")", "cubicCwnd", "(", "t", "float64", ")", "float64", "{", "return", "c", ".", "c", "*", "math", ".", "Pow", "(", "t", ",", "3.0", ")", "+", "c", ".", "wMax", "\n", "}" ]
// cubicCwnd computes the CUBIC congestion window after t seconds from last // congestion event.
[ "cubicCwnd", "computes", "the", "CUBIC", "congestion", "window", "after", "t", "seconds", "from", "last", "congestion", "event", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/cubic.go#L141-L143
train
google/netstack
tcpip/transport/tcp/cubic.go
HandleNDupAcks
func (c *cubicState) HandleNDupAcks() { // See: https://tools.ietf.org/html/rfc8312#section-4.5 c.numCongestionEvents++ c.t = time.Now() c.wLastMax = c.wMax c.wMax = float64(c.s.sndCwnd) c.fastConvergence() c.reduceSlowStartThreshold() }
go
func (c *cubicState) HandleNDupAcks() { // See: https://tools.ietf.org/html/rfc8312#section-4.5 c.numCongestionEvents++ c.t = time.Now() c.wLastMax = c.wMax c.wMax = float64(c.s.sndCwnd) c.fastConvergence() c.reduceSlowStartThreshold() }
[ "func", "(", "c", "*", "cubicState", ")", "HandleNDupAcks", "(", ")", "{", "c", ".", "numCongestionEvents", "++", "\n", "c", ".", "t", "=", "time", ".", "Now", "(", ")", "\n", "c", ".", "wLastMax", "=", "c", ".", "wMax", "\n", "c", ".", "wMax", "=", "float64", "(", "c", ".", "s", ".", "sndCwnd", ")", "\n", "c", ".", "fastConvergence", "(", ")", "\n", "c", ".", "reduceSlowStartThreshold", "(", ")", "\n", "}" ]
// HandleNDupAcks implements congestionControl.HandleNDupAcks.
[ "HandleNDupAcks", "implements", "congestionControl", ".", "HandleNDupAcks", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/cubic.go#L181-L190
train
google/netstack
tcpip/link/sharedmem/tx.go
init
func (t *tx) init(mtu uint32, c *QueueConfig) error { // Map in all buffers. txPipe, err := getBuffer(c.TxPipeFD) if err != nil { return err } rxPipe, err := getBuffer(c.RxPipeFD) if err != nil { syscall.Munmap(txPipe) return err } data, err := getBuffer(c.DataFD) if err != nil { syscall.Munmap(txPipe) syscall.Munmap(rxPipe) return err } // Initialize state based on buffers. t.q.Init(txPipe, rxPipe) t.ids.init() t.bufs.init(0, len(data), int(mtu)) t.data = data return nil }
go
func (t *tx) init(mtu uint32, c *QueueConfig) error { // Map in all buffers. txPipe, err := getBuffer(c.TxPipeFD) if err != nil { return err } rxPipe, err := getBuffer(c.RxPipeFD) if err != nil { syscall.Munmap(txPipe) return err } data, err := getBuffer(c.DataFD) if err != nil { syscall.Munmap(txPipe) syscall.Munmap(rxPipe) return err } // Initialize state based on buffers. t.q.Init(txPipe, rxPipe) t.ids.init() t.bufs.init(0, len(data), int(mtu)) t.data = data return nil }
[ "func", "(", "t", "*", "tx", ")", "init", "(", "mtu", "uint32", ",", "c", "*", "QueueConfig", ")", "error", "{", "txPipe", ",", "err", ":=", "getBuffer", "(", "c", ".", "TxPipeFD", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rxPipe", ",", "err", ":=", "getBuffer", "(", "c", ".", "RxPipeFD", ")", "\n", "if", "err", "!=", "nil", "{", "syscall", ".", "Munmap", "(", "txPipe", ")", "\n", "return", "err", "\n", "}", "\n", "data", ",", "err", ":=", "getBuffer", "(", "c", ".", "DataFD", ")", "\n", "if", "err", "!=", "nil", "{", "syscall", ".", "Munmap", "(", "txPipe", ")", "\n", "syscall", ".", "Munmap", "(", "rxPipe", ")", "\n", "return", "err", "\n", "}", "\n", "t", ".", "q", ".", "Init", "(", "txPipe", ",", "rxPipe", ")", "\n", "t", ".", "ids", ".", "init", "(", ")", "\n", "t", ".", "bufs", ".", "init", "(", "0", ",", "len", "(", "data", ")", ",", "int", "(", "mtu", ")", ")", "\n", "t", ".", "data", "=", "data", "\n", "return", "nil", "\n", "}" ]
// init initializes all state needed by the tx queue based on the information // provided. // // The caller always retains ownership of all file descriptors passed in. The // queue implementation will duplicate any that it may need in the future.
[ "init", "initializes", "all", "state", "needed", "by", "the", "tx", "queue", "based", "on", "the", "information", "provided", ".", "The", "caller", "always", "retains", "ownership", "of", "all", "file", "descriptors", "passed", "in", ".", "The", "queue", "implementation", "will", "duplicate", "any", "that", "it", "may", "need", "in", "the", "future", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L41-L68
train
google/netstack
tcpip/link/sharedmem/tx.go
transmit
func (t *tx) transmit(a, b []byte) bool { // Pull completions from the tx queue and add their buffers back to the // pool so that we can reuse them. for { id, ok := t.q.CompletedPacket() if !ok { break } if buf := t.ids.remove(id); buf != nil { t.bufs.free(buf) } } bSize := t.bufs.entrySize total := uint32(len(a) + len(b)) bufCount := (total + bSize - 1) / bSize // Allocate enough buffers to hold all the data. var buf *queue.TxBuffer for i := bufCount; i != 0; i-- { b := t.bufs.alloc() if b == nil { // Failed to get all buffers. Return to the pool // whatever we had managed to get. if buf != nil { t.bufs.free(buf) } return false } b.Next = buf buf = b } // Copy data into allocated buffers. nBuf := buf var dBuf []byte for _, data := range [][]byte{a, b} { for len(data) > 0 { if len(dBuf) == 0 { dBuf = t.data[nBuf.Offset:][:nBuf.Size] nBuf = nBuf.Next } n := copy(dBuf, data) data = data[n:] dBuf = dBuf[n:] } } // Get an id for this packet and send it out. id := t.ids.add(buf) if !t.q.Enqueue(id, total, bufCount, buf) { t.ids.remove(id) t.bufs.free(buf) return false } return true }
go
func (t *tx) transmit(a, b []byte) bool { // Pull completions from the tx queue and add their buffers back to the // pool so that we can reuse them. for { id, ok := t.q.CompletedPacket() if !ok { break } if buf := t.ids.remove(id); buf != nil { t.bufs.free(buf) } } bSize := t.bufs.entrySize total := uint32(len(a) + len(b)) bufCount := (total + bSize - 1) / bSize // Allocate enough buffers to hold all the data. var buf *queue.TxBuffer for i := bufCount; i != 0; i-- { b := t.bufs.alloc() if b == nil { // Failed to get all buffers. Return to the pool // whatever we had managed to get. if buf != nil { t.bufs.free(buf) } return false } b.Next = buf buf = b } // Copy data into allocated buffers. nBuf := buf var dBuf []byte for _, data := range [][]byte{a, b} { for len(data) > 0 { if len(dBuf) == 0 { dBuf = t.data[nBuf.Offset:][:nBuf.Size] nBuf = nBuf.Next } n := copy(dBuf, data) data = data[n:] dBuf = dBuf[n:] } } // Get an id for this packet and send it out. id := t.ids.add(buf) if !t.q.Enqueue(id, total, bufCount, buf) { t.ids.remove(id) t.bufs.free(buf) return false } return true }
[ "func", "(", "t", "*", "tx", ")", "transmit", "(", "a", ",", "b", "[", "]", "byte", ")", "bool", "{", "for", "{", "id", ",", "ok", ":=", "t", ".", "q", ".", "CompletedPacket", "(", ")", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "if", "buf", ":=", "t", ".", "ids", ".", "remove", "(", "id", ")", ";", "buf", "!=", "nil", "{", "t", ".", "bufs", ".", "free", "(", "buf", ")", "\n", "}", "\n", "}", "\n", "bSize", ":=", "t", ".", "bufs", ".", "entrySize", "\n", "total", ":=", "uint32", "(", "len", "(", "a", ")", "+", "len", "(", "b", ")", ")", "\n", "bufCount", ":=", "(", "total", "+", "bSize", "-", "1", ")", "/", "bSize", "\n", "var", "buf", "*", "queue", ".", "TxBuffer", "\n", "for", "i", ":=", "bufCount", ";", "i", "!=", "0", ";", "i", "--", "{", "b", ":=", "t", ".", "bufs", ".", "alloc", "(", ")", "\n", "if", "b", "==", "nil", "{", "if", "buf", "!=", "nil", "{", "t", ".", "bufs", ".", "free", "(", "buf", ")", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "b", ".", "Next", "=", "buf", "\n", "buf", "=", "b", "\n", "}", "\n", "nBuf", ":=", "buf", "\n", "var", "dBuf", "[", "]", "byte", "\n", "for", "_", ",", "data", ":=", "range", "[", "]", "[", "]", "byte", "{", "a", ",", "b", "}", "{", "for", "len", "(", "data", ")", ">", "0", "{", "if", "len", "(", "dBuf", ")", "==", "0", "{", "dBuf", "=", "t", ".", "data", "[", "nBuf", ".", "Offset", ":", "]", "[", ":", "nBuf", ".", "Size", "]", "\n", "nBuf", "=", "nBuf", ".", "Next", "\n", "}", "\n", "n", ":=", "copy", "(", "dBuf", ",", "data", ")", "\n", "data", "=", "data", "[", "n", ":", "]", "\n", "dBuf", "=", "dBuf", "[", "n", ":", "]", "\n", "}", "\n", "}", "\n", "id", ":=", "t", ".", "ids", ".", "add", "(", "buf", ")", "\n", "if", "!", "t", ".", "q", ".", "Enqueue", "(", "id", ",", "total", ",", "bufCount", ",", "buf", ")", "{", "t", ".", "ids", ".", "remove", "(", "id", ")", "\n", "t", ".", "bufs", ".", "free", "(", "buf", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// transmit sends a packet made up of up to two buffers. Returns a boolean that // specifies whether the packet was successfully transmitted.
[ "transmit", "sends", "a", "packet", "made", "up", "of", "up", "to", "two", "buffers", ".", "Returns", "a", "boolean", "that", "specifies", "whether", "the", "packet", "was", "successfully", "transmitted", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L81-L139
train
google/netstack
tcpip/link/sharedmem/tx.go
getBuffer
func getBuffer(fd int) ([]byte, error) { var s syscall.Stat_t if err := syscall.Fstat(fd, &s); err != nil { return nil, err } // Check that size doesn't overflow an int. if s.Size > int64(^uint(0)>>1) { return nil, syscall.EDOM } return syscall.Mmap(fd, 0, int(s.Size), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED|syscall.MAP_FILE) }
go
func getBuffer(fd int) ([]byte, error) { var s syscall.Stat_t if err := syscall.Fstat(fd, &s); err != nil { return nil, err } // Check that size doesn't overflow an int. if s.Size > int64(^uint(0)>>1) { return nil, syscall.EDOM } return syscall.Mmap(fd, 0, int(s.Size), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED|syscall.MAP_FILE) }
[ "func", "getBuffer", "(", "fd", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "s", "syscall", ".", "Stat_t", "\n", "if", "err", ":=", "syscall", ".", "Fstat", "(", "fd", ",", "&", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "s", ".", "Size", ">", "int64", "(", "^", "uint", "(", "0", ")", ">>", "1", ")", "{", "return", "nil", ",", "syscall", ".", "EDOM", "\n", "}", "\n", "return", "syscall", ".", "Mmap", "(", "fd", ",", "0", ",", "int", "(", "s", ".", "Size", ")", ",", "syscall", ".", "PROT_READ", "|", "syscall", ".", "PROT_WRITE", ",", "syscall", ".", "MAP_SHARED", "|", "syscall", ".", "MAP_FILE", ")", "\n", "}" ]
// getBuffer returns a memory region mapped to the full contents of the given // file descriptor.
[ "getBuffer", "returns", "a", "memory", "region", "mapped", "to", "the", "full", "contents", "of", "the", "given", "file", "descriptor", "." ]
70ebca9c30730cf3887cdef3b85bb96ed7a97593
https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L143-L155
train