id int32 0 167k | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
164,700 | google/netstack | tcpip/link/sharedmem/tx.go | add | func (m *idManager) add(b *queue.TxBuffer) uint64 {
if i := m.freeList; i != nilID {
// There is an id available in the free list, just use it.
m.ids[i].buf = b
m.freeList = m.ids[i].nextFree
return i
}
// We need to expand the id descriptor.
m.ids = append(m.ids, idDescriptor{buf: b})
return uint64(len(m.ids) - 1)
} | go | func (m *idManager) add(b *queue.TxBuffer) uint64 {
if i := m.freeList; i != nilID {
// There is an id available in the free list, just use it.
m.ids[i].buf = b
m.freeList = m.ids[i].nextFree
return i
}
// We need to expand the id descriptor.
m.ids = append(m.ids, idDescriptor{buf: b})
return uint64(len(m.ids) - 1)
} | [
"func",
"(",
"m",
"*",
"idManager",
")",
"add",
"(",
"b",
"*",
"queue",
".",
"TxBuffer",
")",
"uint64",
"{",
"if",
"i",
":=",
"m",
".",
"freeList",
";",
"i",
"!=",
"nilID",
"{",
"// There is an id available in the free list, just use it.",
"m",
".",
"ids",... | // add assigns an ID to the given tx buffer. | [
"add",
"assigns",
"an",
"ID",
"to",
"the",
"given",
"tx",
"buffer",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L185-L196 |
164,701 | google/netstack | tcpip/link/sharedmem/tx.go | remove | func (m *idManager) remove(i uint64) *queue.TxBuffer {
if i >= uint64(len(m.ids)) {
return nil
}
desc := &m.ids[i]
b := desc.buf
if b == nil {
// The provided id is not currently assigned.
return nil
}
desc.buf = nil
desc.nextFree = m.freeList
m.freeList = i
return b
} | go | func (m *idManager) remove(i uint64) *queue.TxBuffer {
if i >= uint64(len(m.ids)) {
return nil
}
desc := &m.ids[i]
b := desc.buf
if b == nil {
// The provided id is not currently assigned.
return nil
}
desc.buf = nil
desc.nextFree = m.freeList
m.freeList = i
return b
} | [
"func",
"(",
"m",
"*",
"idManager",
")",
"remove",
"(",
"i",
"uint64",
")",
"*",
"queue",
".",
"TxBuffer",
"{",
"if",
"i",
">=",
"uint64",
"(",
"len",
"(",
"m",
".",
"ids",
")",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"desc",
":=",
"&",
... | // remove retrieves the tx buffer associated with the given ID, and removes the
// ID from the assigned table so that it can be reused in the future. | [
"remove",
"retrieves",
"the",
"tx",
"buffer",
"associated",
"with",
"the",
"given",
"ID",
"and",
"removes",
"the",
"ID",
"from",
"the",
"assigned",
"table",
"so",
"that",
"it",
"can",
"be",
"reused",
"in",
"the",
"future",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L200-L217 |
164,702 | google/netstack | tcpip/link/sharedmem/tx.go | init | func (b *bufferManager) init(initialOffset, size, entrySize int) {
b.freeList = nil
b.curOffset = uint64(initialOffset)
b.limit = uint64(initialOffset + size/entrySize*entrySize)
b.entrySize = uint32(entrySize)
} | go | func (b *bufferManager) init(initialOffset, size, entrySize int) {
b.freeList = nil
b.curOffset = uint64(initialOffset)
b.limit = uint64(initialOffset + size/entrySize*entrySize)
b.entrySize = uint32(entrySize)
} | [
"func",
"(",
"b",
"*",
"bufferManager",
")",
"init",
"(",
"initialOffset",
",",
"size",
",",
"entrySize",
"int",
")",
"{",
"b",
".",
"freeList",
"=",
"nil",
"\n",
"b",
".",
"curOffset",
"=",
"uint64",
"(",
"initialOffset",
")",
"\n",
"b",
".",
"limit... | // init initializes the buffer manager. | [
"init",
"initializes",
"the",
"buffer",
"manager",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L229-L234 |
164,703 | google/netstack | tcpip/link/sharedmem/tx.go | alloc | func (b *bufferManager) alloc() *queue.TxBuffer {
if b.freeList != nil {
// There is a descriptor ready for reuse in the free list.
d := b.freeList
b.freeList = d.Next
d.Next = nil
return d
}
if b.curOffset < b.limit {
// There is room available in the never-used range, so create
// a new descriptor for it.
d := &queue.TxBuffer{
Offset: b.curOffset,
Size: b.entrySize,
}
b.curOffset += uint64(b.entrySize)
return d
}
return nil
} | go | func (b *bufferManager) alloc() *queue.TxBuffer {
if b.freeList != nil {
// There is a descriptor ready for reuse in the free list.
d := b.freeList
b.freeList = d.Next
d.Next = nil
return d
}
if b.curOffset < b.limit {
// There is room available in the never-used range, so create
// a new descriptor for it.
d := &queue.TxBuffer{
Offset: b.curOffset,
Size: b.entrySize,
}
b.curOffset += uint64(b.entrySize)
return d
}
return nil
} | [
"func",
"(",
"b",
"*",
"bufferManager",
")",
"alloc",
"(",
")",
"*",
"queue",
".",
"TxBuffer",
"{",
"if",
"b",
".",
"freeList",
"!=",
"nil",
"{",
"// There is a descriptor ready for reuse in the free list.",
"d",
":=",
"b",
".",
"freeList",
"\n",
"b",
".",
... | // alloc allocates a buffer from the manager, if one is available. | [
"alloc",
"allocates",
"a",
"buffer",
"from",
"the",
"manager",
"if",
"one",
"is",
"available",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L237-L258 |
164,704 | google/netstack | tcpip/link/sharedmem/tx.go | free | func (b *bufferManager) free(d *queue.TxBuffer) {
// Find the last buffer in the list.
last := d
for last.Next != nil {
last = last.Next
}
// Push list onto free list.
last.Next = b.freeList
b.freeList = d
} | go | func (b *bufferManager) free(d *queue.TxBuffer) {
// Find the last buffer in the list.
last := d
for last.Next != nil {
last = last.Next
}
// Push list onto free list.
last.Next = b.freeList
b.freeList = d
} | [
"func",
"(",
"b",
"*",
"bufferManager",
")",
"free",
"(",
"d",
"*",
"queue",
".",
"TxBuffer",
")",
"{",
"// Find the last buffer in the list.",
"last",
":=",
"d",
"\n",
"for",
"last",
".",
"Next",
"!=",
"nil",
"{",
"last",
"=",
"last",
".",
"Next",
"\n... | // free returns all buffers in the list to the buffer manager so that they can
// be reused. | [
"free",
"returns",
"all",
"buffers",
"in",
"the",
"list",
"to",
"the",
"buffer",
"manager",
"so",
"that",
"they",
"can",
"be",
"reused",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/link/sharedmem/tx.go#L262-L272 |
164,705 | google/netstack | tcpip/transport/tcp/accept.go | incSynRcvdCount | func incSynRcvdCount() bool {
synRcvdCount.Lock()
defer synRcvdCount.Unlock()
if synRcvdCount.value >= SynRcvdCountThreshold {
return false
}
synRcvdCount.pending.Add(1)
synRcvdCount.value++
return true
} | go | func incSynRcvdCount() bool {
synRcvdCount.Lock()
defer synRcvdCount.Unlock()
if synRcvdCount.value >= SynRcvdCountThreshold {
return false
}
synRcvdCount.pending.Add(1)
synRcvdCount.value++
return true
} | [
"func",
"incSynRcvdCount",
"(",
")",
"bool",
"{",
"synRcvdCount",
".",
"Lock",
"(",
")",
"\n",
"defer",
"synRcvdCount",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"synRcvdCount",
".",
"value",
">=",
"SynRcvdCountThreshold",
"{",
"return",
"false",
"\n",
"}",
"... | // incSynRcvdCount tries to increment the global number of endpoints in SYN-RCVD
// state. It succeeds if the increment doesn't make the count go beyond the
// threshold, and fails otherwise. | [
"incSynRcvdCount",
"tries",
"to",
"increment",
"the",
"global",
"number",
"of",
"endpoints",
"in",
"SYN",
"-",
"RCVD",
"state",
".",
"It",
"succeeds",
"if",
"the",
"increment",
"doesn",
"t",
"make",
"the",
"count",
"go",
"beyond",
"the",
"threshold",
"and",
... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L108-L120 |
164,706 | google/netstack | tcpip/transport/tcp/accept.go | decSynRcvdCount | func decSynRcvdCount() {
synRcvdCount.Lock()
defer synRcvdCount.Unlock()
synRcvdCount.value--
synRcvdCount.pending.Done()
} | go | func decSynRcvdCount() {
synRcvdCount.Lock()
defer synRcvdCount.Unlock()
synRcvdCount.value--
synRcvdCount.pending.Done()
} | [
"func",
"decSynRcvdCount",
"(",
")",
"{",
"synRcvdCount",
".",
"Lock",
"(",
")",
"\n",
"defer",
"synRcvdCount",
".",
"Unlock",
"(",
")",
"\n\n",
"synRcvdCount",
".",
"value",
"--",
"\n",
"synRcvdCount",
".",
"pending",
".",
"Done",
"(",
")",
"\n",
"}"
] | // decSynRcvdCount atomically decrements the global number of endpoints in
// SYN-RCVD state. It must only be called if a previous call to incSynRcvdCount
// succeeded. | [
"decSynRcvdCount",
"atomically",
"decrements",
"the",
"global",
"number",
"of",
"endpoints",
"in",
"SYN",
"-",
"RCVD",
"state",
".",
"It",
"must",
"only",
"be",
"called",
"if",
"a",
"previous",
"call",
"to",
"incSynRcvdCount",
"succeeded",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L125-L131 |
164,707 | google/netstack | tcpip/transport/tcp/accept.go | newListenContext | func newListenContext(stack *stack.Stack, rcvWnd seqnum.Size, v6only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {
l := &listenContext{
stack: stack,
rcvWnd: rcvWnd,
hasher: sha1.New(),
v6only: v6only,
netProto: netProto,
}
rand.Read(l.nonce[0][:])
rand.Read(l.nonce[1][:])
return l
} | go | func newListenContext(stack *stack.Stack, rcvWnd seqnum.Size, v6only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {
l := &listenContext{
stack: stack,
rcvWnd: rcvWnd,
hasher: sha1.New(),
v6only: v6only,
netProto: netProto,
}
rand.Read(l.nonce[0][:])
rand.Read(l.nonce[1][:])
return l
} | [
"func",
"newListenContext",
"(",
"stack",
"*",
"stack",
".",
"Stack",
",",
"rcvWnd",
"seqnum",
".",
"Size",
",",
"v6only",
"bool",
",",
"netProto",
"tcpip",
".",
"NetworkProtocolNumber",
")",
"*",
"listenContext",
"{",
"l",
":=",
"&",
"listenContext",
"{",
... | // newListenContext creates a new listen context. | [
"newListenContext",
"creates",
"a",
"new",
"listen",
"context",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L134-L147 |
164,708 | google/netstack | tcpip/transport/tcp/accept.go | cookieHash | func (l *listenContext) cookieHash(id stack.TransportEndpointID, ts uint32, nonceIndex int) uint32 {
// Initialize block with fixed-size data: local ports and v.
var payload [8]byte
binary.BigEndian.PutUint16(payload[0:], id.LocalPort)
binary.BigEndian.PutUint16(payload[2:], id.RemotePort)
binary.BigEndian.PutUint32(payload[4:], ts)
// Feed everything to the hasher.
l.hasherMu.Lock()
l.hasher.Reset()
l.hasher.Write(payload[:])
l.hasher.Write(l.nonce[nonceIndex][:])
io.WriteString(l.hasher, string(id.LocalAddress))
io.WriteString(l.hasher, string(id.RemoteAddress))
// Finalize the calculation of the hash and return the first 4 bytes.
h := make([]byte, 0, sha1.Size)
h = l.hasher.Sum(h)
l.hasherMu.Unlock()
return binary.BigEndian.Uint32(h[:])
} | go | func (l *listenContext) cookieHash(id stack.TransportEndpointID, ts uint32, nonceIndex int) uint32 {
// Initialize block with fixed-size data: local ports and v.
var payload [8]byte
binary.BigEndian.PutUint16(payload[0:], id.LocalPort)
binary.BigEndian.PutUint16(payload[2:], id.RemotePort)
binary.BigEndian.PutUint32(payload[4:], ts)
// Feed everything to the hasher.
l.hasherMu.Lock()
l.hasher.Reset()
l.hasher.Write(payload[:])
l.hasher.Write(l.nonce[nonceIndex][:])
io.WriteString(l.hasher, string(id.LocalAddress))
io.WriteString(l.hasher, string(id.RemoteAddress))
// Finalize the calculation of the hash and return the first 4 bytes.
h := make([]byte, 0, sha1.Size)
h = l.hasher.Sum(h)
l.hasherMu.Unlock()
return binary.BigEndian.Uint32(h[:])
} | [
"func",
"(",
"l",
"*",
"listenContext",
")",
"cookieHash",
"(",
"id",
"stack",
".",
"TransportEndpointID",
",",
"ts",
"uint32",
",",
"nonceIndex",
"int",
")",
"uint32",
"{",
"// Initialize block with fixed-size data: local ports and v.",
"var",
"payload",
"[",
"8",
... | // cookieHash calculates the cookieHash for the given id, timestamp and nonce
// index. The hash is used to create and validate cookies. | [
"cookieHash",
"calculates",
"the",
"cookieHash",
"for",
"the",
"given",
"id",
"timestamp",
"and",
"nonce",
"index",
".",
"The",
"hash",
"is",
"used",
"to",
"create",
"and",
"validate",
"cookies",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L151-L173 |
164,709 | google/netstack | tcpip/transport/tcp/accept.go | createCookie | func (l *listenContext) createCookie(id stack.TransportEndpointID, seq seqnum.Value, data uint32) seqnum.Value {
ts := timeStamp()
v := l.cookieHash(id, 0, 0) + uint32(seq) + (ts << tsOffset)
v += (l.cookieHash(id, ts, 1) + data) & hashMask
return seqnum.Value(v)
} | go | func (l *listenContext) createCookie(id stack.TransportEndpointID, seq seqnum.Value, data uint32) seqnum.Value {
ts := timeStamp()
v := l.cookieHash(id, 0, 0) + uint32(seq) + (ts << tsOffset)
v += (l.cookieHash(id, ts, 1) + data) & hashMask
return seqnum.Value(v)
} | [
"func",
"(",
"l",
"*",
"listenContext",
")",
"createCookie",
"(",
"id",
"stack",
".",
"TransportEndpointID",
",",
"seq",
"seqnum",
".",
"Value",
",",
"data",
"uint32",
")",
"seqnum",
".",
"Value",
"{",
"ts",
":=",
"timeStamp",
"(",
")",
"\n",
"v",
":="... | // createCookie creates a SYN cookie for the given id and incoming sequence
// number. | [
"createCookie",
"creates",
"a",
"SYN",
"cookie",
"for",
"the",
"given",
"id",
"and",
"incoming",
"sequence",
"number",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L177-L182 |
164,710 | google/netstack | tcpip/transport/tcp/accept.go | isCookieValid | func (l *listenContext) isCookieValid(id stack.TransportEndpointID, cookie seqnum.Value, seq seqnum.Value) (uint32, bool) {
ts := timeStamp()
v := uint32(cookie) - l.cookieHash(id, 0, 0) - uint32(seq)
cookieTS := v >> tsOffset
if ((ts - cookieTS) & tsMask) > maxTSDiff {
return 0, false
}
return (v - l.cookieHash(id, cookieTS, 1)) & hashMask, true
} | go | func (l *listenContext) isCookieValid(id stack.TransportEndpointID, cookie seqnum.Value, seq seqnum.Value) (uint32, bool) {
ts := timeStamp()
v := uint32(cookie) - l.cookieHash(id, 0, 0) - uint32(seq)
cookieTS := v >> tsOffset
if ((ts - cookieTS) & tsMask) > maxTSDiff {
return 0, false
}
return (v - l.cookieHash(id, cookieTS, 1)) & hashMask, true
} | [
"func",
"(",
"l",
"*",
"listenContext",
")",
"isCookieValid",
"(",
"id",
"stack",
".",
"TransportEndpointID",
",",
"cookie",
"seqnum",
".",
"Value",
",",
"seq",
"seqnum",
".",
"Value",
")",
"(",
"uint32",
",",
"bool",
")",
"{",
"ts",
":=",
"timeStamp",
... | // isCookieValid checks if the supplied cookie is valid for the given id and
// sequence number. If it is, it also returns the data originally encoded in the
// cookie when createCookie was called. | [
"isCookieValid",
"checks",
"if",
"the",
"supplied",
"cookie",
"is",
"valid",
"for",
"the",
"given",
"id",
"and",
"sequence",
"number",
".",
"If",
"it",
"is",
"it",
"also",
"returns",
"the",
"data",
"originally",
"encoded",
"in",
"the",
"cookie",
"when",
"c... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L187-L196 |
164,711 | google/netstack | tcpip/transport/tcp/accept.go | createConnectedEndpoint | func (l *listenContext) createConnectedEndpoint(s *segment, iss seqnum.Value, irs seqnum.Value, rcvdSynOpts *header.TCPSynOptions) (*endpoint, *tcpip.Error) {
// Create a new endpoint.
netProto := l.netProto
if netProto == 0 {
netProto = s.route.NetProto
}
n := newEndpoint(l.stack, netProto, nil)
n.v6only = l.v6only
n.id = s.id
n.boundNICID = s.route.NICID()
n.route = s.route.Clone()
n.effectiveNetProtos = []tcpip.NetworkProtocolNumber{s.route.NetProto}
n.rcvBufSize = int(l.rcvWnd)
n.maybeEnableTimestamp(rcvdSynOpts)
n.maybeEnableSACKPermitted(rcvdSynOpts)
n.initGSO()
// Register new endpoint so that packets are routed to it.
if err := n.stack.RegisterTransportEndpoint(n.boundNICID, n.effectiveNetProtos, ProtocolNumber, n.id, n, n.reusePort); err != nil {
n.Close()
return nil, err
}
n.isRegistered = true
n.state = stateConnected
// Create sender and receiver.
//
// The receiver at least temporarily has a zero receive window scale,
// but the caller may change it (before starting the protocol loop).
n.snd = newSender(n, iss, irs, s.window, rcvdSynOpts.MSS, rcvdSynOpts.WS)
n.rcv = newReceiver(n, irs, l.rcvWnd, 0)
return n, nil
} | go | func (l *listenContext) createConnectedEndpoint(s *segment, iss seqnum.Value, irs seqnum.Value, rcvdSynOpts *header.TCPSynOptions) (*endpoint, *tcpip.Error) {
// Create a new endpoint.
netProto := l.netProto
if netProto == 0 {
netProto = s.route.NetProto
}
n := newEndpoint(l.stack, netProto, nil)
n.v6only = l.v6only
n.id = s.id
n.boundNICID = s.route.NICID()
n.route = s.route.Clone()
n.effectiveNetProtos = []tcpip.NetworkProtocolNumber{s.route.NetProto}
n.rcvBufSize = int(l.rcvWnd)
n.maybeEnableTimestamp(rcvdSynOpts)
n.maybeEnableSACKPermitted(rcvdSynOpts)
n.initGSO()
// Register new endpoint so that packets are routed to it.
if err := n.stack.RegisterTransportEndpoint(n.boundNICID, n.effectiveNetProtos, ProtocolNumber, n.id, n, n.reusePort); err != nil {
n.Close()
return nil, err
}
n.isRegistered = true
n.state = stateConnected
// Create sender and receiver.
//
// The receiver at least temporarily has a zero receive window scale,
// but the caller may change it (before starting the protocol loop).
n.snd = newSender(n, iss, irs, s.window, rcvdSynOpts.MSS, rcvdSynOpts.WS)
n.rcv = newReceiver(n, irs, l.rcvWnd, 0)
return n, nil
} | [
"func",
"(",
"l",
"*",
"listenContext",
")",
"createConnectedEndpoint",
"(",
"s",
"*",
"segment",
",",
"iss",
"seqnum",
".",
"Value",
",",
"irs",
"seqnum",
".",
"Value",
",",
"rcvdSynOpts",
"*",
"header",
".",
"TCPSynOptions",
")",
"(",
"*",
"endpoint",
... | // createConnectedEndpoint creates a new connected endpoint, with the connection
// parameters given by the arguments. | [
"createConnectedEndpoint",
"creates",
"a",
"new",
"connected",
"endpoint",
"with",
"the",
"connection",
"parameters",
"given",
"by",
"the",
"arguments",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L200-L236 |
164,712 | google/netstack | tcpip/transport/tcp/accept.go | createEndpointAndPerformHandshake | func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *header.TCPSynOptions) (*endpoint, *tcpip.Error) {
// Create new endpoint.
irs := s.sequenceNumber
cookie := l.createCookie(s.id, irs, encodeMSS(opts.MSS))
ep, err := l.createConnectedEndpoint(s, cookie, irs, opts)
if err != nil {
return nil, err
}
// Perform the 3-way handshake.
h := newHandshake(ep, l.rcvWnd)
h.resetToSynRcvd(cookie, irs, opts)
if err := h.execute(); err != nil {
ep.Close()
return nil, err
}
// Update the receive window scaling. We can't do it before the
// handshake because it's possible that the peer doesn't support window
// scaling.
ep.rcv.rcvWndScale = h.effectiveRcvWndScale()
return ep, nil
} | go | func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *header.TCPSynOptions) (*endpoint, *tcpip.Error) {
// Create new endpoint.
irs := s.sequenceNumber
cookie := l.createCookie(s.id, irs, encodeMSS(opts.MSS))
ep, err := l.createConnectedEndpoint(s, cookie, irs, opts)
if err != nil {
return nil, err
}
// Perform the 3-way handshake.
h := newHandshake(ep, l.rcvWnd)
h.resetToSynRcvd(cookie, irs, opts)
if err := h.execute(); err != nil {
ep.Close()
return nil, err
}
// Update the receive window scaling. We can't do it before the
// handshake because it's possible that the peer doesn't support window
// scaling.
ep.rcv.rcvWndScale = h.effectiveRcvWndScale()
return ep, nil
} | [
"func",
"(",
"l",
"*",
"listenContext",
")",
"createEndpointAndPerformHandshake",
"(",
"s",
"*",
"segment",
",",
"opts",
"*",
"header",
".",
"TCPSynOptions",
")",
"(",
"*",
"endpoint",
",",
"*",
"tcpip",
".",
"Error",
")",
"{",
"// Create new endpoint.",
"ir... | // createEndpoint creates a new endpoint in connected state and then performs
// the TCP 3-way handshake. | [
"createEndpoint",
"creates",
"a",
"new",
"endpoint",
"in",
"connected",
"state",
"and",
"then",
"performs",
"the",
"TCP",
"3",
"-",
"way",
"handshake",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L240-L264 |
164,713 | google/netstack | tcpip/transport/tcp/accept.go | deliverAccepted | func (e *endpoint) deliverAccepted(n *endpoint) {
e.mu.RLock()
if e.state == stateListen {
e.acceptedChan <- n
e.waiterQueue.Notify(waiter.EventIn)
} else {
n.Close()
}
e.mu.RUnlock()
} | go | func (e *endpoint) deliverAccepted(n *endpoint) {
e.mu.RLock()
if e.state == stateListen {
e.acceptedChan <- n
e.waiterQueue.Notify(waiter.EventIn)
} else {
n.Close()
}
e.mu.RUnlock()
} | [
"func",
"(",
"e",
"*",
"endpoint",
")",
"deliverAccepted",
"(",
"n",
"*",
"endpoint",
")",
"{",
"e",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"if",
"e",
".",
"state",
"==",
"stateListen",
"{",
"e",
".",
"acceptedChan",
"<-",
"n",
"\n",
"e",
".",
... | // deliverAccepted delivers the newly-accepted endpoint to the listener. If the
// endpoint has transitioned out of the listen state, the new endpoint is closed
// instead. | [
"deliverAccepted",
"delivers",
"the",
"newly",
"-",
"accepted",
"endpoint",
"to",
"the",
"listener",
".",
"If",
"the",
"endpoint",
"has",
"transitioned",
"out",
"of",
"the",
"listen",
"state",
"the",
"new",
"endpoint",
"is",
"closed",
"instead",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L269-L278 |
164,714 | google/netstack | tcpip/transport/tcp/accept.go | handleSynSegment | func (e *endpoint) handleSynSegment(ctx *listenContext, s *segment, opts *header.TCPSynOptions) {
defer decSynRcvdCount()
defer s.decRef()
n, err := ctx.createEndpointAndPerformHandshake(s, opts)
if err != nil {
return
}
e.deliverAccepted(n)
} | go | func (e *endpoint) handleSynSegment(ctx *listenContext, s *segment, opts *header.TCPSynOptions) {
defer decSynRcvdCount()
defer s.decRef()
n, err := ctx.createEndpointAndPerformHandshake(s, opts)
if err != nil {
return
}
e.deliverAccepted(n)
} | [
"func",
"(",
"e",
"*",
"endpoint",
")",
"handleSynSegment",
"(",
"ctx",
"*",
"listenContext",
",",
"s",
"*",
"segment",
",",
"opts",
"*",
"header",
".",
"TCPSynOptions",
")",
"{",
"defer",
"decSynRcvdCount",
"(",
")",
"\n",
"defer",
"s",
".",
"decRef",
... | // handleSynSegment is called in its own goroutine once the listening endpoint
// receives a SYN segment. It is responsible for completing the handshake and
// queueing the new endpoint for acceptance.
//
// A limited number of these goroutines are allowed before TCP starts using SYN
// cookies to accept connections. | [
"handleSynSegment",
"is",
"called",
"in",
"its",
"own",
"goroutine",
"once",
"the",
"listening",
"endpoint",
"receives",
"a",
"SYN",
"segment",
".",
"It",
"is",
"responsible",
"for",
"completing",
"the",
"handshake",
"and",
"queueing",
"the",
"new",
"endpoint",
... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L286-L296 |
164,715 | google/netstack | tcpip/transport/tcp/accept.go | handleListenSegment | func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {
switch s.flags {
case header.TCPFlagSyn:
opts := parseSynSegmentOptions(s)
if incSynRcvdCount() {
s.incRef()
go e.handleSynSegment(ctx, s, &opts)
} else {
cookie := ctx.createCookie(s.id, s.sequenceNumber, encodeMSS(opts.MSS))
// Send SYN with window scaling because we currently
// dont't encode this information in the cookie.
//
// Enable Timestamp option if the original syn did have
// the timestamp option specified.
synOpts := header.TCPSynOptions{
WS: -1,
TS: opts.TS,
TSVal: tcpTimeStamp(timeStampOffset()),
TSEcr: opts.TSVal,
}
sendSynTCP(&s.route, s.id, header.TCPFlagSyn|header.TCPFlagAck, cookie, s.sequenceNumber+1, ctx.rcvWnd, synOpts)
}
case header.TCPFlagAck:
if data, ok := ctx.isCookieValid(s.id, s.ackNumber-1, s.sequenceNumber-1); ok && int(data) < len(mssTable) {
// Create newly accepted endpoint and deliver it.
rcvdSynOptions := &header.TCPSynOptions{
MSS: mssTable[data],
// Disable Window scaling as original SYN is
// lost.
WS: -1,
}
// When syn cookies are in use we enable timestamp only
// if the ack specifies the timestamp option assuming
// that the other end did in fact negotiate the
// timestamp option in the original SYN.
if s.parsedOptions.TS {
rcvdSynOptions.TS = true
rcvdSynOptions.TSVal = s.parsedOptions.TSVal
rcvdSynOptions.TSEcr = s.parsedOptions.TSEcr
}
n, err := ctx.createConnectedEndpoint(s, s.ackNumber-1, s.sequenceNumber-1, rcvdSynOptions)
if err == nil {
// clear the tsOffset for the newly created
// endpoint as the Timestamp was already
// randomly offset when the original SYN-ACK was
// sent above.
n.tsOffset = 0
e.deliverAccepted(n)
}
}
}
} | go | func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {
switch s.flags {
case header.TCPFlagSyn:
opts := parseSynSegmentOptions(s)
if incSynRcvdCount() {
s.incRef()
go e.handleSynSegment(ctx, s, &opts)
} else {
cookie := ctx.createCookie(s.id, s.sequenceNumber, encodeMSS(opts.MSS))
// Send SYN with window scaling because we currently
// dont't encode this information in the cookie.
//
// Enable Timestamp option if the original syn did have
// the timestamp option specified.
synOpts := header.TCPSynOptions{
WS: -1,
TS: opts.TS,
TSVal: tcpTimeStamp(timeStampOffset()),
TSEcr: opts.TSVal,
}
sendSynTCP(&s.route, s.id, header.TCPFlagSyn|header.TCPFlagAck, cookie, s.sequenceNumber+1, ctx.rcvWnd, synOpts)
}
case header.TCPFlagAck:
if data, ok := ctx.isCookieValid(s.id, s.ackNumber-1, s.sequenceNumber-1); ok && int(data) < len(mssTable) {
// Create newly accepted endpoint and deliver it.
rcvdSynOptions := &header.TCPSynOptions{
MSS: mssTable[data],
// Disable Window scaling as original SYN is
// lost.
WS: -1,
}
// When syn cookies are in use we enable timestamp only
// if the ack specifies the timestamp option assuming
// that the other end did in fact negotiate the
// timestamp option in the original SYN.
if s.parsedOptions.TS {
rcvdSynOptions.TS = true
rcvdSynOptions.TSVal = s.parsedOptions.TSVal
rcvdSynOptions.TSEcr = s.parsedOptions.TSEcr
}
n, err := ctx.createConnectedEndpoint(s, s.ackNumber-1, s.sequenceNumber-1, rcvdSynOptions)
if err == nil {
// clear the tsOffset for the newly created
// endpoint as the Timestamp was already
// randomly offset when the original SYN-ACK was
// sent above.
n.tsOffset = 0
e.deliverAccepted(n)
}
}
}
} | [
"func",
"(",
"e",
"*",
"endpoint",
")",
"handleListenSegment",
"(",
"ctx",
"*",
"listenContext",
",",
"s",
"*",
"segment",
")",
"{",
"switch",
"s",
".",
"flags",
"{",
"case",
"header",
".",
"TCPFlagSyn",
":",
"opts",
":=",
"parseSynSegmentOptions",
"(",
... | // handleListenSegment is called when a listening endpoint receives a segment
// and needs to handle it. | [
"handleListenSegment",
"is",
"called",
"when",
"a",
"listening",
"endpoint",
"receives",
"a",
"segment",
"and",
"needs",
"to",
"handle",
"it",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L300-L352 |
164,716 | google/netstack | tcpip/transport/tcp/accept.go | protocolListenLoop | func (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) *tcpip.Error {
defer func() {
// Mark endpoint as closed. This will prevent goroutines running
// handleSynSegment() from attempting to queue new connections
// to the endpoint.
e.mu.Lock()
e.state = stateClosed
// Do cleanup if needed.
e.completeWorkerLocked()
if e.drainDone != nil {
close(e.drainDone)
}
e.mu.Unlock()
// Notify waiters that the endpoint is shutdown.
e.waiterQueue.Notify(waiter.EventIn | waiter.EventOut)
}()
e.mu.Lock()
v6only := e.v6only
e.mu.Unlock()
ctx := newListenContext(e.stack, rcvWnd, v6only, e.netProto)
s := sleep.Sleeper{}
s.AddWaker(&e.notificationWaker, wakerForNotification)
s.AddWaker(&e.newSegmentWaker, wakerForNewSegment)
for {
switch index, _ := s.Fetch(true); index {
case wakerForNotification:
n := e.fetchNotifications()
if n¬ifyClose != 0 {
return nil
}
if n¬ifyDrain != 0 {
for !e.segmentQueue.empty() {
s := e.segmentQueue.dequeue()
e.handleListenSegment(ctx, s)
s.decRef()
}
synRcvdCount.pending.Wait()
close(e.drainDone)
<-e.undrain
}
case wakerForNewSegment:
// Process at most maxSegmentsPerWake segments.
mayRequeue := true
for i := 0; i < maxSegmentsPerWake; i++ {
s := e.segmentQueue.dequeue()
if s == nil {
mayRequeue = false
break
}
e.handleListenSegment(ctx, s)
s.decRef()
}
// If the queue is not empty, make sure we'll wake up
// in the next iteration.
if mayRequeue && !e.segmentQueue.empty() {
e.newSegmentWaker.Assert()
}
}
}
} | go | func (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) *tcpip.Error {
defer func() {
// Mark endpoint as closed. This will prevent goroutines running
// handleSynSegment() from attempting to queue new connections
// to the endpoint.
e.mu.Lock()
e.state = stateClosed
// Do cleanup if needed.
e.completeWorkerLocked()
if e.drainDone != nil {
close(e.drainDone)
}
e.mu.Unlock()
// Notify waiters that the endpoint is shutdown.
e.waiterQueue.Notify(waiter.EventIn | waiter.EventOut)
}()
e.mu.Lock()
v6only := e.v6only
e.mu.Unlock()
ctx := newListenContext(e.stack, rcvWnd, v6only, e.netProto)
s := sleep.Sleeper{}
s.AddWaker(&e.notificationWaker, wakerForNotification)
s.AddWaker(&e.newSegmentWaker, wakerForNewSegment)
for {
switch index, _ := s.Fetch(true); index {
case wakerForNotification:
n := e.fetchNotifications()
if n¬ifyClose != 0 {
return nil
}
if n¬ifyDrain != 0 {
for !e.segmentQueue.empty() {
s := e.segmentQueue.dequeue()
e.handleListenSegment(ctx, s)
s.decRef()
}
synRcvdCount.pending.Wait()
close(e.drainDone)
<-e.undrain
}
case wakerForNewSegment:
// Process at most maxSegmentsPerWake segments.
mayRequeue := true
for i := 0; i < maxSegmentsPerWake; i++ {
s := e.segmentQueue.dequeue()
if s == nil {
mayRequeue = false
break
}
e.handleListenSegment(ctx, s)
s.decRef()
}
// If the queue is not empty, make sure we'll wake up
// in the next iteration.
if mayRequeue && !e.segmentQueue.empty() {
e.newSegmentWaker.Assert()
}
}
}
} | [
"func",
"(",
"e",
"*",
"endpoint",
")",
"protocolListenLoop",
"(",
"rcvWnd",
"seqnum",
".",
"Size",
")",
"*",
"tcpip",
".",
"Error",
"{",
"defer",
"func",
"(",
")",
"{",
"// Mark endpoint as closed. This will prevent goroutines running",
"// handleSynSegment() from at... | // protocolListenLoop is the main loop of a listening TCP endpoint. It runs in
// its own goroutine and is responsible for handling connection requests. | [
"protocolListenLoop",
"is",
"the",
"main",
"loop",
"of",
"a",
"listening",
"TCP",
"endpoint",
".",
"It",
"runs",
"in",
"its",
"own",
"goroutine",
"and",
"is",
"responsible",
"for",
"handling",
"connection",
"requests",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L356-L424 |
164,717 | google/netstack | tcpip/header/icmpv6.go | SetChecksum | func (b ICMPv6) SetChecksum(checksum uint16) {
binary.BigEndian.PutUint16(b[2:], checksum)
} | go | func (b ICMPv6) SetChecksum(checksum uint16) {
binary.BigEndian.PutUint16(b[2:], checksum)
} | [
"func",
"(",
"b",
"ICMPv6",
")",
"SetChecksum",
"(",
"checksum",
"uint16",
")",
"{",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"b",
"[",
"2",
":",
"]",
",",
"checksum",
")",
"\n",
"}"
] | // SetChecksum calculates and sets the ICMP checksum field. | [
"SetChecksum",
"calculates",
"and",
"sets",
"the",
"ICMP",
"checksum",
"field",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/icmpv6.go#L96-L98 |
164,718 | google/netstack | tcpip/stack/nic.go | setPromiscuousMode | func (n *NIC) setPromiscuousMode(enable bool) {
n.mu.Lock()
n.promiscuous = enable
n.mu.Unlock()
} | go | func (n *NIC) setPromiscuousMode(enable bool) {
n.mu.Lock()
n.promiscuous = enable
n.mu.Unlock()
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"setPromiscuousMode",
"(",
"enable",
"bool",
")",
"{",
"n",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"n",
".",
"promiscuous",
"=",
"enable",
"\n",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // setPromiscuousMode enables or disables promiscuous mode. | [
"setPromiscuousMode",
"enables",
"or",
"disables",
"promiscuous",
"mode",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L110-L114 |
164,719 | google/netstack | tcpip/stack/nic.go | setSpoofing | func (n *NIC) setSpoofing(enable bool) {
n.mu.Lock()
n.spoofing = enable
n.mu.Unlock()
} | go | func (n *NIC) setSpoofing(enable bool) {
n.mu.Lock()
n.spoofing = enable
n.mu.Unlock()
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"setSpoofing",
"(",
"enable",
"bool",
")",
"{",
"n",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"n",
".",
"spoofing",
"=",
"enable",
"\n",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // setSpoofing enables or disables address spoofing. | [
"setSpoofing",
"enables",
"or",
"disables",
"address",
"spoofing",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L124-L128 |
164,720 | google/netstack | tcpip/stack/nic.go | primaryEndpoint | func (n *NIC) primaryEndpoint(protocol tcpip.NetworkProtocolNumber) *referencedNetworkEndpoint {
n.mu.RLock()
defer n.mu.RUnlock()
list := n.primary[protocol]
if list == nil {
return nil
}
for e := list.Front(); e != nil; e = e.Next() {
r := e.(*referencedNetworkEndpoint)
// TODO(crawshaw): allow broadcast address when SO_BROADCAST is set.
switch r.ep.ID().LocalAddress {
case header.IPv4Broadcast, header.IPv4Any:
continue
}
if r.tryIncRef() {
return r
}
}
return nil
} | go | func (n *NIC) primaryEndpoint(protocol tcpip.NetworkProtocolNumber) *referencedNetworkEndpoint {
n.mu.RLock()
defer n.mu.RUnlock()
list := n.primary[protocol]
if list == nil {
return nil
}
for e := list.Front(); e != nil; e = e.Next() {
r := e.(*referencedNetworkEndpoint)
// TODO(crawshaw): allow broadcast address when SO_BROADCAST is set.
switch r.ep.ID().LocalAddress {
case header.IPv4Broadcast, header.IPv4Any:
continue
}
if r.tryIncRef() {
return r
}
}
return nil
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"primaryEndpoint",
"(",
"protocol",
"tcpip",
".",
"NetworkProtocolNumber",
")",
"*",
"referencedNetworkEndpoint",
"{",
"n",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"n",
".",
"mu",
".",
"RUnlock",
"(",
")",
"... | // primaryEndpoint returns the primary endpoint of n for the given network
// protocol. | [
"primaryEndpoint",
"returns",
"the",
"primary",
"endpoint",
"of",
"n",
"for",
"the",
"given",
"network",
"protocol",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L168-L190 |
164,721 | google/netstack | tcpip/stack/nic.go | findEndpoint | func (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) *referencedNetworkEndpoint {
id := NetworkEndpointID{address}
n.mu.RLock()
ref := n.endpoints[id]
if ref != nil && !ref.tryIncRef() {
ref = nil
}
spoofing := n.spoofing
n.mu.RUnlock()
if ref != nil || !spoofing {
return ref
}
// Try again with the lock in exclusive mode. If we still can't get the
// endpoint, create a new "temporary" endpoint. It will only exist while
// there's a route through it.
n.mu.Lock()
ref = n.endpoints[id]
if ref == nil || !ref.tryIncRef() {
ref, _ = n.addAddressLocked(protocol, address, peb, true)
if ref != nil {
ref.holdsInsertRef = false
}
}
n.mu.Unlock()
return ref
} | go | func (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) *referencedNetworkEndpoint {
id := NetworkEndpointID{address}
n.mu.RLock()
ref := n.endpoints[id]
if ref != nil && !ref.tryIncRef() {
ref = nil
}
spoofing := n.spoofing
n.mu.RUnlock()
if ref != nil || !spoofing {
return ref
}
// Try again with the lock in exclusive mode. If we still can't get the
// endpoint, create a new "temporary" endpoint. It will only exist while
// there's a route through it.
n.mu.Lock()
ref = n.endpoints[id]
if ref == nil || !ref.tryIncRef() {
ref, _ = n.addAddressLocked(protocol, address, peb, true)
if ref != nil {
ref.holdsInsertRef = false
}
}
n.mu.Unlock()
return ref
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"findEndpoint",
"(",
"protocol",
"tcpip",
".",
"NetworkProtocolNumber",
",",
"address",
"tcpip",
".",
"Address",
",",
"peb",
"PrimaryEndpointBehavior",
")",
"*",
"referencedNetworkEndpoint",
"{",
"id",
":=",
"NetworkEndpointID",
... | // findEndpoint finds the endpoint, if any, with the given address. | [
"findEndpoint",
"finds",
"the",
"endpoint",
"if",
"any",
"with",
"the",
"given",
"address",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L193-L221 |
164,722 | google/netstack | tcpip/stack/nic.go | Addresses | func (n *NIC) Addresses() []tcpip.ProtocolAddress {
n.mu.RLock()
defer n.mu.RUnlock()
addrs := make([]tcpip.ProtocolAddress, 0, len(n.endpoints))
for nid, ep := range n.endpoints {
addrs = append(addrs, tcpip.ProtocolAddress{
Protocol: ep.protocol,
Address: nid.LocalAddress,
})
}
return addrs
} | go | func (n *NIC) Addresses() []tcpip.ProtocolAddress {
n.mu.RLock()
defer n.mu.RUnlock()
addrs := make([]tcpip.ProtocolAddress, 0, len(n.endpoints))
for nid, ep := range n.endpoints {
addrs = append(addrs, tcpip.ProtocolAddress{
Protocol: ep.protocol,
Address: nid.LocalAddress,
})
}
return addrs
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"Addresses",
"(",
")",
"[",
"]",
"tcpip",
".",
"ProtocolAddress",
"{",
"n",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"n",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"addrs",
":=",
"make",
"(",
"[",
... | // Addresses returns the addresses associated with this NIC. | [
"Addresses",
"returns",
"the",
"addresses",
"associated",
"with",
"this",
"NIC",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L295-L306 |
164,723 | google/netstack | tcpip/stack/nic.go | AddSubnet | func (n *NIC) AddSubnet(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) {
n.mu.Lock()
n.subnets = append(n.subnets, subnet)
n.mu.Unlock()
} | go | func (n *NIC) AddSubnet(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) {
n.mu.Lock()
n.subnets = append(n.subnets, subnet)
n.mu.Unlock()
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"AddSubnet",
"(",
"protocol",
"tcpip",
".",
"NetworkProtocolNumber",
",",
"subnet",
"tcpip",
".",
"Subnet",
")",
"{",
"n",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"n",
".",
"subnets",
"=",
"append",
"(",
"n",
".",... | // AddSubnet adds a new subnet to n, so that it starts accepting packets
// targeted at the given address and network protocol. | [
"AddSubnet",
"adds",
"a",
"new",
"subnet",
"to",
"n",
"so",
"that",
"it",
"starts",
"accepting",
"packets",
"targeted",
"at",
"the",
"given",
"address",
"and",
"network",
"protocol",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L310-L314 |
164,724 | google/netstack | tcpip/stack/nic.go | RemoveSubnet | func (n *NIC) RemoveSubnet(subnet tcpip.Subnet) {
n.mu.Lock()
// Use the same underlying array.
tmp := n.subnets[:0]
for _, sub := range n.subnets {
if sub != subnet {
tmp = append(tmp, sub)
}
}
n.subnets = tmp
n.mu.Unlock()
} | go | func (n *NIC) RemoveSubnet(subnet tcpip.Subnet) {
n.mu.Lock()
// Use the same underlying array.
tmp := n.subnets[:0]
for _, sub := range n.subnets {
if sub != subnet {
tmp = append(tmp, sub)
}
}
n.subnets = tmp
n.mu.Unlock()
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"RemoveSubnet",
"(",
"subnet",
"tcpip",
".",
"Subnet",
")",
"{",
"n",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"// Use the same underlying array.",
"tmp",
":=",
"n",
".",
"subnets",
"[",
":",
"0",
"]",
"\n",
"for",... | // RemoveSubnet removes the given subnet from n. | [
"RemoveSubnet",
"removes",
"the",
"given",
"subnet",
"from",
"n",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L317-L330 |
164,725 | google/netstack | tcpip/stack/nic.go | ContainsSubnet | func (n *NIC) ContainsSubnet(subnet tcpip.Subnet) bool {
for _, s := range n.Subnets() {
if s == subnet {
return true
}
}
return false
} | go | func (n *NIC) ContainsSubnet(subnet tcpip.Subnet) bool {
for _, s := range n.Subnets() {
if s == subnet {
return true
}
}
return false
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"ContainsSubnet",
"(",
"subnet",
"tcpip",
".",
"Subnet",
")",
"bool",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"n",
".",
"Subnets",
"(",
")",
"{",
"if",
"s",
"==",
"subnet",
"{",
"return",
"true",
"\n",
"}",
... | // ContainsSubnet reports whether this NIC contains the given subnet. | [
"ContainsSubnet",
"reports",
"whether",
"this",
"NIC",
"contains",
"the",
"given",
"subnet",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L333-L340 |
164,726 | google/netstack | tcpip/stack/nic.go | Subnets | func (n *NIC) Subnets() []tcpip.Subnet {
n.mu.RLock()
defer n.mu.RUnlock()
sns := make([]tcpip.Subnet, 0, len(n.subnets)+len(n.endpoints))
for nid := range n.endpoints {
sn, err := tcpip.NewSubnet(nid.LocalAddress, tcpip.AddressMask(strings.Repeat("\xff", len(nid.LocalAddress))))
if err != nil {
// This should never happen as the mask has been carefully crafted to
// match the address.
panic("Invalid endpoint subnet: " + err.Error())
}
sns = append(sns, sn)
}
return append(sns, n.subnets...)
} | go | func (n *NIC) Subnets() []tcpip.Subnet {
n.mu.RLock()
defer n.mu.RUnlock()
sns := make([]tcpip.Subnet, 0, len(n.subnets)+len(n.endpoints))
for nid := range n.endpoints {
sn, err := tcpip.NewSubnet(nid.LocalAddress, tcpip.AddressMask(strings.Repeat("\xff", len(nid.LocalAddress))))
if err != nil {
// This should never happen as the mask has been carefully crafted to
// match the address.
panic("Invalid endpoint subnet: " + err.Error())
}
sns = append(sns, sn)
}
return append(sns, n.subnets...)
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"Subnets",
"(",
")",
"[",
"]",
"tcpip",
".",
"Subnet",
"{",
"n",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"n",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"sns",
":=",
"make",
"(",
"[",
"]",
"tcpip... | // Subnets returns the Subnets associated with this NIC. | [
"Subnets",
"returns",
"the",
"Subnets",
"associated",
"with",
"this",
"NIC",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L343-L357 |
164,727 | google/netstack | tcpip/stack/nic.go | RemoveAddress | func (n *NIC) RemoveAddress(addr tcpip.Address) *tcpip.Error {
n.mu.Lock()
r := n.endpoints[NetworkEndpointID{addr}]
if r == nil || !r.holdsInsertRef {
n.mu.Unlock()
return tcpip.ErrBadLocalAddress
}
r.holdsInsertRef = false
n.mu.Unlock()
r.decRef()
return nil
} | go | func (n *NIC) RemoveAddress(addr tcpip.Address) *tcpip.Error {
n.mu.Lock()
r := n.endpoints[NetworkEndpointID{addr}]
if r == nil || !r.holdsInsertRef {
n.mu.Unlock()
return tcpip.ErrBadLocalAddress
}
r.holdsInsertRef = false
n.mu.Unlock()
r.decRef()
return nil
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"RemoveAddress",
"(",
"addr",
"tcpip",
".",
"Address",
")",
"*",
"tcpip",
".",
"Error",
"{",
"n",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"r",
":=",
"n",
".",
"endpoints",
"[",
"NetworkEndpointID",
"{",
"addr",
... | // RemoveAddress removes an address from n. | [
"RemoveAddress",
"removes",
"an",
"address",
"from",
"n",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L388-L402 |
164,728 | google/netstack | tcpip/stack/nic.go | DeliverTransportPacket | func (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, netHeader buffer.View, vv buffer.VectorisedView) {
state, ok := n.stack.transportProtocols[protocol]
if !ok {
n.stack.stats.UnknownProtocolRcvdPackets.Increment()
return
}
transProto := state.proto
if len(vv.First()) < transProto.MinimumPacketSize() {
n.stack.stats.MalformedRcvdPackets.Increment()
return
}
srcPort, dstPort, err := transProto.ParsePorts(vv.First())
if err != nil {
n.stack.stats.MalformedRcvdPackets.Increment()
return
}
id := TransportEndpointID{dstPort, r.LocalAddress, srcPort, r.RemoteAddress}
if n.demux.deliverPacket(r, protocol, netHeader, vv, id) {
return
}
if n.stack.demux.deliverPacket(r, protocol, netHeader, vv, id) {
return
}
// Try to deliver to per-stack default handler.
if state.defaultHandler != nil {
if state.defaultHandler(r, id, netHeader, vv) {
return
}
}
// We could not find an appropriate destination for this packet, so
// deliver it to the global handler.
if !transProto.HandleUnknownDestinationPacket(r, id, vv) {
n.stack.stats.MalformedRcvdPackets.Increment()
}
} | go | func (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, netHeader buffer.View, vv buffer.VectorisedView) {
state, ok := n.stack.transportProtocols[protocol]
if !ok {
n.stack.stats.UnknownProtocolRcvdPackets.Increment()
return
}
transProto := state.proto
if len(vv.First()) < transProto.MinimumPacketSize() {
n.stack.stats.MalformedRcvdPackets.Increment()
return
}
srcPort, dstPort, err := transProto.ParsePorts(vv.First())
if err != nil {
n.stack.stats.MalformedRcvdPackets.Increment()
return
}
id := TransportEndpointID{dstPort, r.LocalAddress, srcPort, r.RemoteAddress}
if n.demux.deliverPacket(r, protocol, netHeader, vv, id) {
return
}
if n.stack.demux.deliverPacket(r, protocol, netHeader, vv, id) {
return
}
// Try to deliver to per-stack default handler.
if state.defaultHandler != nil {
if state.defaultHandler(r, id, netHeader, vv) {
return
}
}
// We could not find an appropriate destination for this packet, so
// deliver it to the global handler.
if !transProto.HandleUnknownDestinationPacket(r, id, vv) {
n.stack.stats.MalformedRcvdPackets.Increment()
}
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"DeliverTransportPacket",
"(",
"r",
"*",
"Route",
",",
"protocol",
"tcpip",
".",
"TransportProtocolNumber",
",",
"netHeader",
"buffer",
".",
"View",
",",
"vv",
"buffer",
".",
"VectorisedView",
")",
"{",
"state",
",",
"ok"... | // DeliverTransportPacket delivers the packets to the appropriate transport
// protocol endpoint. | [
"DeliverTransportPacket",
"delivers",
"the",
"packets",
"to",
"the",
"appropriate",
"transport",
"protocol",
"endpoint",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L544-L583 |
164,729 | google/netstack | tcpip/stack/nic.go | DeliverTransportControlPacket | func (n *NIC) DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, typ ControlType, extra uint32, vv buffer.VectorisedView) {
state, ok := n.stack.transportProtocols[trans]
if !ok {
return
}
transProto := state.proto
// ICMPv4 only guarantees that 8 bytes of the transport protocol will
// be present in the payload. We know that the ports are within the
// first 8 bytes for all known transport protocols.
if len(vv.First()) < 8 {
return
}
srcPort, dstPort, err := transProto.ParsePorts(vv.First())
if err != nil {
return
}
id := TransportEndpointID{srcPort, local, dstPort, remote}
if n.demux.deliverControlPacket(net, trans, typ, extra, vv, id) {
return
}
if n.stack.demux.deliverControlPacket(net, trans, typ, extra, vv, id) {
return
}
} | go | func (n *NIC) DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, typ ControlType, extra uint32, vv buffer.VectorisedView) {
state, ok := n.stack.transportProtocols[trans]
if !ok {
return
}
transProto := state.proto
// ICMPv4 only guarantees that 8 bytes of the transport protocol will
// be present in the payload. We know that the ports are within the
// first 8 bytes for all known transport protocols.
if len(vv.First()) < 8 {
return
}
srcPort, dstPort, err := transProto.ParsePorts(vv.First())
if err != nil {
return
}
id := TransportEndpointID{srcPort, local, dstPort, remote}
if n.demux.deliverControlPacket(net, trans, typ, extra, vv, id) {
return
}
if n.stack.demux.deliverControlPacket(net, trans, typ, extra, vv, id) {
return
}
} | [
"func",
"(",
"n",
"*",
"NIC",
")",
"DeliverTransportControlPacket",
"(",
"local",
",",
"remote",
"tcpip",
".",
"Address",
",",
"net",
"tcpip",
".",
"NetworkProtocolNumber",
",",
"trans",
"tcpip",
".",
"TransportProtocolNumber",
",",
"typ",
"ControlType",
",",
... | // DeliverTransportControlPacket delivers control packets to the appropriate
// transport protocol endpoint. | [
"DeliverTransportControlPacket",
"delivers",
"control",
"packets",
"to",
"the",
"appropriate",
"transport",
"protocol",
"endpoint",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L587-L614 |
164,730 | google/netstack | tcpip/stack/nic.go | decRef | func (r *referencedNetworkEndpoint) decRef() {
if atomic.AddInt32(&r.refs, -1) == 0 {
r.nic.removeEndpoint(r)
}
} | go | func (r *referencedNetworkEndpoint) decRef() {
if atomic.AddInt32(&r.refs, -1) == 0 {
r.nic.removeEndpoint(r)
}
} | [
"func",
"(",
"r",
"*",
"referencedNetworkEndpoint",
")",
"decRef",
"(",
")",
"{",
"if",
"atomic",
".",
"AddInt32",
"(",
"&",
"r",
".",
"refs",
",",
"-",
"1",
")",
"==",
"0",
"{",
"r",
".",
"nic",
".",
"removeEndpoint",
"(",
"r",
")",
"\n",
"}",
... | // decRef decrements the ref count and cleans up the endpoint once it reaches
// zero. | [
"decRef",
"decrements",
"the",
"ref",
"count",
"and",
"cleans",
"up",
"the",
"endpoint",
"once",
"it",
"reaches",
"zero",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L641-L645 |
164,731 | google/netstack | tcpip/stack/nic.go | tryIncRef | func (r *referencedNetworkEndpoint) tryIncRef() bool {
for {
v := atomic.LoadInt32(&r.refs)
if v == 0 {
return false
}
if atomic.CompareAndSwapInt32(&r.refs, v, v+1) {
return true
}
}
} | go | func (r *referencedNetworkEndpoint) tryIncRef() bool {
for {
v := atomic.LoadInt32(&r.refs)
if v == 0 {
return false
}
if atomic.CompareAndSwapInt32(&r.refs, v, v+1) {
return true
}
}
} | [
"func",
"(",
"r",
"*",
"referencedNetworkEndpoint",
")",
"tryIncRef",
"(",
")",
"bool",
"{",
"for",
"{",
"v",
":=",
"atomic",
".",
"LoadInt32",
"(",
"&",
"r",
".",
"refs",
")",
"\n",
"if",
"v",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
... | // tryIncRef attempts to increment the ref count from n to n+1, but only if n is
// not zero. That is, it will increment the count if the endpoint is still
// alive, and do nothing if it has already been clean up. | [
"tryIncRef",
"attempts",
"to",
"increment",
"the",
"ref",
"count",
"from",
"n",
"to",
"n",
"+",
"1",
"but",
"only",
"if",
"n",
"is",
"not",
"zero",
".",
"That",
"is",
"it",
"will",
"increment",
"the",
"count",
"if",
"the",
"endpoint",
"is",
"still",
... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L657-L668 |
164,732 | google/netstack | tcpip/transport/udp/protocol.go | ParsePorts | func (*protocol) ParsePorts(v buffer.View) (src, dst uint16, err *tcpip.Error) {
h := header.UDP(v)
return h.SourcePort(), h.DestinationPort(), nil
} | go | func (*protocol) ParsePorts(v buffer.View) (src, dst uint16, err *tcpip.Error) {
h := header.UDP(v)
return h.SourcePort(), h.DestinationPort(), nil
} | [
"func",
"(",
"*",
"protocol",
")",
"ParsePorts",
"(",
"v",
"buffer",
".",
"View",
")",
"(",
"src",
",",
"dst",
"uint16",
",",
"err",
"*",
"tcpip",
".",
"Error",
")",
"{",
"h",
":=",
"header",
".",
"UDP",
"(",
"v",
")",
"\n",
"return",
"h",
".",... | // ParsePorts returns the source and destination ports stored in the given udp
// packet. | [
"ParsePorts",
"returns",
"the",
"source",
"and",
"destination",
"ports",
"stored",
"in",
"the",
"given",
"udp",
"packet",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/udp/protocol.go#L64-L67 |
164,733 | google/netstack | tcpip/time_unsafe.go | NowNanoseconds | func (*StdClock) NowNanoseconds() int64 {
sec, nsec, _ := now()
return sec*1e9 + int64(nsec)
} | go | func (*StdClock) NowNanoseconds() int64 {
sec, nsec, _ := now()
return sec*1e9 + int64(nsec)
} | [
"func",
"(",
"*",
"StdClock",
")",
"NowNanoseconds",
"(",
")",
"int64",
"{",
"sec",
",",
"nsec",
",",
"_",
":=",
"now",
"(",
")",
"\n",
"return",
"sec",
"*",
"1e9",
"+",
"int64",
"(",
"nsec",
")",
"\n",
"}"
] | // NowNanoseconds implements Clock.NowNanoseconds. | [
"NowNanoseconds",
"implements",
"Clock",
".",
"NowNanoseconds",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/time_unsafe.go#L34-L37 |
164,734 | google/netstack | tcpip/ports/ports.go | isAvailable | func (b bindAddresses) isAvailable(addr tcpip.Address, reuse bool) bool {
if addr == anyIPAddress {
if len(b) == 0 {
return true
}
if !reuse {
return false
}
for _, n := range b {
if !n.reuse {
return false
}
}
return true
}
// If all addresses for this portDescriptor are already bound, no
// address is available.
if n, ok := b[anyIPAddress]; ok {
if !reuse {
return false
}
if !n.reuse {
return false
}
}
if n, ok := b[addr]; ok {
if !reuse {
return false
}
return n.reuse
}
return true
} | go | func (b bindAddresses) isAvailable(addr tcpip.Address, reuse bool) bool {
if addr == anyIPAddress {
if len(b) == 0 {
return true
}
if !reuse {
return false
}
for _, n := range b {
if !n.reuse {
return false
}
}
return true
}
// If all addresses for this portDescriptor are already bound, no
// address is available.
if n, ok := b[anyIPAddress]; ok {
if !reuse {
return false
}
if !n.reuse {
return false
}
}
if n, ok := b[addr]; ok {
if !reuse {
return false
}
return n.reuse
}
return true
} | [
"func",
"(",
"b",
"bindAddresses",
")",
"isAvailable",
"(",
"addr",
"tcpip",
".",
"Address",
",",
"reuse",
"bool",
")",
"bool",
"{",
"if",
"addr",
"==",
"anyIPAddress",
"{",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"... | // isAvailable checks whether an IP address is available to bind to. | [
"isAvailable",
"checks",
"whether",
"an",
"IP",
"address",
"is",
"available",
"to",
"bind",
"to",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/ports/ports.go#L54-L88 |
164,735 | google/netstack | tcpip/ports/ports.go | PickEphemeralPort | func (s *PortManager) PickEphemeralPort(testPort func(p uint16) (bool, *tcpip.Error)) (port uint16, err *tcpip.Error) {
count := uint16(math.MaxUint16 - FirstEphemeral + 1)
offset := uint16(rand.Int31n(int32(count)))
for i := uint16(0); i < count; i++ {
port = FirstEphemeral + (offset+i)%count
ok, err := testPort(port)
if err != nil {
return 0, err
}
if ok {
return port, nil
}
}
return 0, tcpip.ErrNoPortAvailable
} | go | func (s *PortManager) PickEphemeralPort(testPort func(p uint16) (bool, *tcpip.Error)) (port uint16, err *tcpip.Error) {
count := uint16(math.MaxUint16 - FirstEphemeral + 1)
offset := uint16(rand.Int31n(int32(count)))
for i := uint16(0); i < count; i++ {
port = FirstEphemeral + (offset+i)%count
ok, err := testPort(port)
if err != nil {
return 0, err
}
if ok {
return port, nil
}
}
return 0, tcpip.ErrNoPortAvailable
} | [
"func",
"(",
"s",
"*",
"PortManager",
")",
"PickEphemeralPort",
"(",
"testPort",
"func",
"(",
"p",
"uint16",
")",
"(",
"bool",
",",
"*",
"tcpip",
".",
"Error",
")",
")",
"(",
"port",
"uint16",
",",
"err",
"*",
"tcpip",
".",
"Error",
")",
"{",
"coun... | // PickEphemeralPort randomly chooses a starting point and iterates over all
// possible ephemeral ports, allowing the caller to decide whether a given port
// is suitable for its needs, and stopping when a port is found or an error
// occurs. | [
"PickEphemeralPort",
"randomly",
"chooses",
"a",
"starting",
"point",
"and",
"iterates",
"over",
"all",
"possible",
"ephemeral",
"ports",
"allowing",
"the",
"caller",
"to",
"decide",
"whether",
"a",
"given",
"port",
"is",
"suitable",
"for",
"its",
"needs",
"and"... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/ports/ports.go#L99-L116 |
164,736 | google/netstack | tcpip/ports/ports.go | IsPortAvailable | func (s *PortManager) IsPortAvailable(networks []tcpip.NetworkProtocolNumber, transport tcpip.TransportProtocolNumber, addr tcpip.Address, port uint16, reuse bool) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.isPortAvailableLocked(networks, transport, addr, port, reuse)
} | go | func (s *PortManager) IsPortAvailable(networks []tcpip.NetworkProtocolNumber, transport tcpip.TransportProtocolNumber, addr tcpip.Address, port uint16, reuse bool) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.isPortAvailableLocked(networks, transport, addr, port, reuse)
} | [
"func",
"(",
"s",
"*",
"PortManager",
")",
"IsPortAvailable",
"(",
"networks",
"[",
"]",
"tcpip",
".",
"NetworkProtocolNumber",
",",
"transport",
"tcpip",
".",
"TransportProtocolNumber",
",",
"addr",
"tcpip",
".",
"Address",
",",
"port",
"uint16",
",",
"reuse"... | // IsPortAvailable tests if the given port is available on all given protocols. | [
"IsPortAvailable",
"tests",
"if",
"the",
"given",
"port",
"is",
"available",
"on",
"all",
"given",
"protocols",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/ports/ports.go#L119-L123 |
164,737 | google/netstack | tcpip/ports/ports.go | reserveSpecificPort | func (s *PortManager) reserveSpecificPort(networks []tcpip.NetworkProtocolNumber, transport tcpip.TransportProtocolNumber, addr tcpip.Address, port uint16, reuse bool) bool {
if !s.isPortAvailableLocked(networks, transport, addr, port, reuse) {
return false
}
// Reserve port on all network protocols.
for _, network := range networks {
desc := portDescriptor{network, transport, port}
m, ok := s.allocatedPorts[desc]
if !ok {
m = make(bindAddresses)
s.allocatedPorts[desc] = m
}
if n, ok := m[addr]; ok {
n.refs++
m[addr] = n
} else {
m[addr] = portNode{reuse: reuse, refs: 1}
}
}
return true
} | go | func (s *PortManager) reserveSpecificPort(networks []tcpip.NetworkProtocolNumber, transport tcpip.TransportProtocolNumber, addr tcpip.Address, port uint16, reuse bool) bool {
if !s.isPortAvailableLocked(networks, transport, addr, port, reuse) {
return false
}
// Reserve port on all network protocols.
for _, network := range networks {
desc := portDescriptor{network, transport, port}
m, ok := s.allocatedPorts[desc]
if !ok {
m = make(bindAddresses)
s.allocatedPorts[desc] = m
}
if n, ok := m[addr]; ok {
n.refs++
m[addr] = n
} else {
m[addr] = portNode{reuse: reuse, refs: 1}
}
}
return true
} | [
"func",
"(",
"s",
"*",
"PortManager",
")",
"reserveSpecificPort",
"(",
"networks",
"[",
"]",
"tcpip",
".",
"NetworkProtocolNumber",
",",
"transport",
"tcpip",
".",
"TransportProtocolNumber",
",",
"addr",
"tcpip",
".",
"Address",
",",
"port",
"uint16",
",",
"re... | // reserveSpecificPort tries to reserve the given port on all given protocols. | [
"reserveSpecificPort",
"tries",
"to",
"reserve",
"the",
"given",
"port",
"on",
"all",
"given",
"protocols",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/ports/ports.go#L161-L183 |
164,738 | google/netstack | tcpip/transport/raw/state.go | saveRcvBufSizeMax | func (ep *endpoint) saveRcvBufSizeMax() int {
max := ep.rcvBufSizeMax
// Make sure no new packets will be handled regardless of the lock.
ep.rcvBufSizeMax = 0
// Release the lock acquired in beforeSave() so regular endpoint closing
// logic can proceed after save.
ep.rcvMu.Unlock()
return max
} | go | func (ep *endpoint) saveRcvBufSizeMax() int {
max := ep.rcvBufSizeMax
// Make sure no new packets will be handled regardless of the lock.
ep.rcvBufSizeMax = 0
// Release the lock acquired in beforeSave() so regular endpoint closing
// logic can proceed after save.
ep.rcvMu.Unlock()
return max
} | [
"func",
"(",
"ep",
"*",
"endpoint",
")",
"saveRcvBufSizeMax",
"(",
")",
"int",
"{",
"max",
":=",
"ep",
".",
"rcvBufSizeMax",
"\n",
"// Make sure no new packets will be handled regardless of the lock.",
"ep",
".",
"rcvBufSizeMax",
"=",
"0",
"\n",
"// Release the lock a... | // saveRcvBufSizeMax is invoked by stateify. | [
"saveRcvBufSizeMax",
"is",
"invoked",
"by",
"stateify",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/raw/state.go#L49-L57 |
164,739 | google/netstack | tcpip/transport/raw/state.go | afterLoad | func (ep *endpoint) afterLoad() {
// StackFromEnv is a stack used specifically for save/restore.
ep.stack = stack.StackFromEnv
// If the endpoint is connected, re-connect via the save/restore stack.
if ep.connected {
var err *tcpip.Error
ep.route, err = ep.stack.FindRoute(ep.registeredNIC, ep.boundAddr, ep.route.RemoteAddress, ep.netProto, false)
if err != nil {
panic(*err)
}
}
// If the endpoint is bound, re-bind via the save/restore stack.
if ep.bound {
if ep.stack.CheckLocalAddress(ep.registeredNIC, ep.netProto, ep.boundAddr) == 0 {
panic(tcpip.ErrBadLocalAddress)
}
}
if err := ep.stack.RegisterRawTransportEndpoint(ep.registeredNIC, ep.netProto, ep.transProto, ep); err != nil {
panic(*err)
}
} | go | func (ep *endpoint) afterLoad() {
// StackFromEnv is a stack used specifically for save/restore.
ep.stack = stack.StackFromEnv
// If the endpoint is connected, re-connect via the save/restore stack.
if ep.connected {
var err *tcpip.Error
ep.route, err = ep.stack.FindRoute(ep.registeredNIC, ep.boundAddr, ep.route.RemoteAddress, ep.netProto, false)
if err != nil {
panic(*err)
}
}
// If the endpoint is bound, re-bind via the save/restore stack.
if ep.bound {
if ep.stack.CheckLocalAddress(ep.registeredNIC, ep.netProto, ep.boundAddr) == 0 {
panic(tcpip.ErrBadLocalAddress)
}
}
if err := ep.stack.RegisterRawTransportEndpoint(ep.registeredNIC, ep.netProto, ep.transProto, ep); err != nil {
panic(*err)
}
} | [
"func",
"(",
"ep",
"*",
"endpoint",
")",
"afterLoad",
"(",
")",
"{",
"// StackFromEnv is a stack used specifically for save/restore.",
"ep",
".",
"stack",
"=",
"stack",
".",
"StackFromEnv",
"\n\n",
"// If the endpoint is connected, re-connect via the save/restore stack.",
"if... | // afterLoad is invoked by stateify. | [
"afterLoad",
"is",
"invoked",
"by",
"stateify",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/raw/state.go#L65-L88 |
164,740 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | Init | func (t *TCB) Init(initialSyn header.TCP) Result {
t.handlerInbound = synSentStateInbound
t.handlerOutbound = synSentStateOutbound
iss := seqnum.Value(initialSyn.SequenceNumber())
t.outbound.una = iss
t.outbound.nxt = iss.Add(logicalLen(initialSyn))
t.outbound.end = t.outbound.nxt
// Even though "end" is a sequence number, we don't know the initial
// receive sequence number yet, so we store the window size until we get
// a SYN from the peer.
t.inbound.una = 0
t.inbound.nxt = 0
t.inbound.end = seqnum.Value(initialSyn.WindowSize())
t.state = ResultConnecting
return t.state
} | go | func (t *TCB) Init(initialSyn header.TCP) Result {
t.handlerInbound = synSentStateInbound
t.handlerOutbound = synSentStateOutbound
iss := seqnum.Value(initialSyn.SequenceNumber())
t.outbound.una = iss
t.outbound.nxt = iss.Add(logicalLen(initialSyn))
t.outbound.end = t.outbound.nxt
// Even though "end" is a sequence number, we don't know the initial
// receive sequence number yet, so we store the window size until we get
// a SYN from the peer.
t.inbound.una = 0
t.inbound.nxt = 0
t.inbound.end = seqnum.Value(initialSyn.WindowSize())
t.state = ResultConnecting
return t.state
} | [
"func",
"(",
"t",
"*",
"TCB",
")",
"Init",
"(",
"initialSyn",
"header",
".",
"TCP",
")",
"Result",
"{",
"t",
".",
"handlerInbound",
"=",
"synSentStateInbound",
"\n",
"t",
".",
"handlerOutbound",
"=",
"synSentStateOutbound",
"\n\n",
"iss",
":=",
"seqnum",
"... | // Init initializes the state of the TCB according to the initial SYN. | [
"Init",
"initializes",
"the",
"state",
"of",
"the",
"TCB",
"according",
"to",
"the",
"initial",
"SYN",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L70-L87 |
164,741 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | UpdateStateInbound | func (t *TCB) UpdateStateInbound(tcp header.TCP) Result {
st := t.handlerInbound(t, tcp)
if st != ResultDrop {
t.state = st
}
return st
} | go | func (t *TCB) UpdateStateInbound(tcp header.TCP) Result {
st := t.handlerInbound(t, tcp)
if st != ResultDrop {
t.state = st
}
return st
} | [
"func",
"(",
"t",
"*",
"TCB",
")",
"UpdateStateInbound",
"(",
"tcp",
"header",
".",
"TCP",
")",
"Result",
"{",
"st",
":=",
"t",
".",
"handlerInbound",
"(",
"t",
",",
"tcp",
")",
"\n",
"if",
"st",
"!=",
"ResultDrop",
"{",
"t",
".",
"state",
"=",
"... | // UpdateStateInbound updates the state of the TCB based on the supplied inbound
// segment. | [
"UpdateStateInbound",
"updates",
"the",
"state",
"of",
"the",
"TCB",
"based",
"on",
"the",
"supplied",
"inbound",
"segment",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L91-L97 |
164,742 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | UpdateStateOutbound | func (t *TCB) UpdateStateOutbound(tcp header.TCP) Result {
st := t.handlerOutbound(t, tcp)
if st != ResultDrop {
t.state = st
}
return st
} | go | func (t *TCB) UpdateStateOutbound(tcp header.TCP) Result {
st := t.handlerOutbound(t, tcp)
if st != ResultDrop {
t.state = st
}
return st
} | [
"func",
"(",
"t",
"*",
"TCB",
")",
"UpdateStateOutbound",
"(",
"tcp",
"header",
".",
"TCP",
")",
"Result",
"{",
"st",
":=",
"t",
".",
"handlerOutbound",
"(",
"t",
",",
"tcp",
")",
"\n",
"if",
"st",
"!=",
"ResultDrop",
"{",
"t",
".",
"state",
"=",
... | // UpdateStateOutbound updates the state of the TCB based on the supplied
// outbound segment. | [
"UpdateStateOutbound",
"updates",
"the",
"state",
"of",
"the",
"TCB",
"based",
"on",
"the",
"supplied",
"outbound",
"segment",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L101-L107 |
164,743 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | adaptResult | func (t *TCB) adaptResult(r Result) Result {
// Check the unmodified case.
if r != ResultAlive || !t.inbound.closed() || !t.outbound.closed() {
return r
}
// Find out which was closed first.
if t.firstFin == &t.outbound {
return ResultClosedBySelf
}
return ResultClosedByPeer
} | go | func (t *TCB) adaptResult(r Result) Result {
// Check the unmodified case.
if r != ResultAlive || !t.inbound.closed() || !t.outbound.closed() {
return r
}
// Find out which was closed first.
if t.firstFin == &t.outbound {
return ResultClosedBySelf
}
return ResultClosedByPeer
} | [
"func",
"(",
"t",
"*",
"TCB",
")",
"adaptResult",
"(",
"r",
"Result",
")",
"Result",
"{",
"// Check the unmodified case.",
"if",
"r",
"!=",
"ResultAlive",
"||",
"!",
"t",
".",
"inbound",
".",
"closed",
"(",
")",
"||",
"!",
"t",
".",
"outbound",
".",
... | // adapResult modifies the supplied "Result" according to the state of the TCB;
// if r is anything other than "Alive", or if one of the streams isn't closed
// yet, it is returned unmodified. Otherwise it's converted to either
// ClosedBySelf or ClosedByPeer depending on which stream was closed first. | [
"adapResult",
"modifies",
"the",
"supplied",
"Result",
"according",
"to",
"the",
"state",
"of",
"the",
"TCB",
";",
"if",
"r",
"is",
"anything",
"other",
"than",
"Alive",
"or",
"if",
"one",
"of",
"the",
"streams",
"isn",
"t",
"closed",
"yet",
"it",
"is",
... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L129-L141 |
164,744 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | synSentStateInbound | func synSentStateInbound(t *TCB, tcp header.TCP) Result {
flags := tcp.Flags()
ackPresent := flags&header.TCPFlagAck != 0
ack := seqnum.Value(tcp.AckNumber())
// Ignore segment if ack is present but not acceptable.
if ackPresent && !(ack-1).InRange(t.outbound.una, t.outbound.nxt) {
return ResultConnecting
}
// If reset is specified, we will let the packet through no matter what
// but we will also destroy the connection if the ACK is present (and
// implicitly acceptable).
if flags&header.TCPFlagRst != 0 {
if ackPresent {
t.inbound.rstSeen = true
return ResultReset
}
return ResultConnecting
}
// Ignore segment if SYN is not set.
if flags&header.TCPFlagSyn == 0 {
return ResultConnecting
}
// Update state informed by this SYN.
irs := seqnum.Value(tcp.SequenceNumber())
t.inbound.una = irs
t.inbound.nxt = irs.Add(logicalLen(tcp))
t.inbound.end += irs
t.outbound.end = t.outbound.una.Add(seqnum.Size(tcp.WindowSize()))
// If the ACK was set (it is acceptable), update our unacknowledgement
// tracking.
if ackPresent {
// Advance the "una" and "end" indices of the outbound stream.
if t.outbound.una.LessThan(ack) {
t.outbound.una = ack
}
if end := ack.Add(seqnum.Size(tcp.WindowSize())); t.outbound.end.LessThan(end) {
t.outbound.end = end
}
}
// Update handlers so that new calls will be handled by new state.
t.handlerInbound = allOtherInbound
t.handlerOutbound = allOtherOutbound
return ResultAlive
} | go | func synSentStateInbound(t *TCB, tcp header.TCP) Result {
flags := tcp.Flags()
ackPresent := flags&header.TCPFlagAck != 0
ack := seqnum.Value(tcp.AckNumber())
// Ignore segment if ack is present but not acceptable.
if ackPresent && !(ack-1).InRange(t.outbound.una, t.outbound.nxt) {
return ResultConnecting
}
// If reset is specified, we will let the packet through no matter what
// but we will also destroy the connection if the ACK is present (and
// implicitly acceptable).
if flags&header.TCPFlagRst != 0 {
if ackPresent {
t.inbound.rstSeen = true
return ResultReset
}
return ResultConnecting
}
// Ignore segment if SYN is not set.
if flags&header.TCPFlagSyn == 0 {
return ResultConnecting
}
// Update state informed by this SYN.
irs := seqnum.Value(tcp.SequenceNumber())
t.inbound.una = irs
t.inbound.nxt = irs.Add(logicalLen(tcp))
t.inbound.end += irs
t.outbound.end = t.outbound.una.Add(seqnum.Size(tcp.WindowSize()))
// If the ACK was set (it is acceptable), update our unacknowledgement
// tracking.
if ackPresent {
// Advance the "una" and "end" indices of the outbound stream.
if t.outbound.una.LessThan(ack) {
t.outbound.una = ack
}
if end := ack.Add(seqnum.Size(tcp.WindowSize())); t.outbound.end.LessThan(end) {
t.outbound.end = end
}
}
// Update handlers so that new calls will be handled by new state.
t.handlerInbound = allOtherInbound
t.handlerOutbound = allOtherOutbound
return ResultAlive
} | [
"func",
"synSentStateInbound",
"(",
"t",
"*",
"TCB",
",",
"tcp",
"header",
".",
"TCP",
")",
"Result",
"{",
"flags",
":=",
"tcp",
".",
"Flags",
"(",
")",
"\n",
"ackPresent",
":=",
"flags",
"&",
"header",
".",
"TCPFlagAck",
"!=",
"0",
"\n",
"ack",
":="... | // synSentStateInbound is the state handler for inbound segments when the
// connection is in SYN-SENT state. | [
"synSentStateInbound",
"is",
"the",
"state",
"handler",
"for",
"inbound",
"segments",
"when",
"the",
"connection",
"is",
"in",
"SYN",
"-",
"SENT",
"state",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L145-L197 |
164,745 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | synSentStateOutbound | func synSentStateOutbound(t *TCB, tcp header.TCP) Result {
// Drop outbound segments that aren't retransmits of the original one.
if tcp.Flags() != header.TCPFlagSyn ||
tcp.SequenceNumber() != uint32(t.outbound.una) {
return ResultDrop
}
// Update the receive window. We only remember the largest value seen.
if wnd := seqnum.Value(tcp.WindowSize()); wnd > t.inbound.end {
t.inbound.end = wnd
}
return ResultConnecting
} | go | func synSentStateOutbound(t *TCB, tcp header.TCP) Result {
// Drop outbound segments that aren't retransmits of the original one.
if tcp.Flags() != header.TCPFlagSyn ||
tcp.SequenceNumber() != uint32(t.outbound.una) {
return ResultDrop
}
// Update the receive window. We only remember the largest value seen.
if wnd := seqnum.Value(tcp.WindowSize()); wnd > t.inbound.end {
t.inbound.end = wnd
}
return ResultConnecting
} | [
"func",
"synSentStateOutbound",
"(",
"t",
"*",
"TCB",
",",
"tcp",
"header",
".",
"TCP",
")",
"Result",
"{",
"// Drop outbound segments that aren't retransmits of the original one.",
"if",
"tcp",
".",
"Flags",
"(",
")",
"!=",
"header",
".",
"TCPFlagSyn",
"||",
"tcp... | // synSentStateOutbound is the state handler for outbound segments when the
// connection is in SYN-SENT state. | [
"synSentStateOutbound",
"is",
"the",
"state",
"handler",
"for",
"outbound",
"segments",
"when",
"the",
"connection",
"is",
"in",
"SYN",
"-",
"SENT",
"state",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L201-L214 |
164,746 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | allOtherInbound | func allOtherInbound(t *TCB, tcp header.TCP) Result {
return t.adaptResult(update(tcp, &t.inbound, &t.outbound, &t.firstFin))
} | go | func allOtherInbound(t *TCB, tcp header.TCP) Result {
return t.adaptResult(update(tcp, &t.inbound, &t.outbound, &t.firstFin))
} | [
"func",
"allOtherInbound",
"(",
"t",
"*",
"TCB",
",",
"tcp",
"header",
".",
"TCP",
")",
"Result",
"{",
"return",
"t",
".",
"adaptResult",
"(",
"update",
"(",
"tcp",
",",
"&",
"t",
".",
"inbound",
",",
"&",
"t",
".",
"outbound",
",",
"&",
"t",
"."... | // allOtherInbound is the state handler for inbound segments in all states
// except SYN-SENT. | [
"allOtherInbound",
"is",
"the",
"state",
"handler",
"for",
"inbound",
"segments",
"in",
"all",
"states",
"except",
"SYN",
"-",
"SENT",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L275-L277 |
164,747 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | acceptable | func (s *stream) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool {
wnd := s.una.Size(s.end)
if wnd == 0 {
return segLen == 0 && segSeq == s.una
}
// Make sure [segSeq, seqSeq+segLen) is non-empty.
if segLen == 0 {
segLen = 1
}
return seqnum.Overlap(s.una, wnd, segSeq, segLen)
} | go | func (s *stream) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool {
wnd := s.una.Size(s.end)
if wnd == 0 {
return segLen == 0 && segSeq == s.una
}
// Make sure [segSeq, seqSeq+segLen) is non-empty.
if segLen == 0 {
segLen = 1
}
return seqnum.Overlap(s.una, wnd, segSeq, segLen)
} | [
"func",
"(",
"s",
"*",
"stream",
")",
"acceptable",
"(",
"segSeq",
"seqnum",
".",
"Value",
",",
"segLen",
"seqnum",
".",
"Size",
")",
"bool",
"{",
"wnd",
":=",
"s",
".",
"una",
".",
"Size",
"(",
"s",
".",
"end",
")",
"\n",
"if",
"wnd",
"==",
"0... | // acceptable determines if the segment with the given sequence number and data
// length is acceptable, i.e., if it's within the [una, end) window or, in case
// the window is zero, if it's a packet with no payload and sequence number
// equal to una. | [
"acceptable",
"determines",
"if",
"the",
"segment",
"with",
"the",
"given",
"sequence",
"number",
"and",
"data",
"length",
"is",
"acceptable",
"i",
".",
"e",
".",
"if",
"it",
"s",
"within",
"the",
"[",
"una",
"end",
")",
"window",
"or",
"in",
"case",
"... | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L313-L325 |
164,748 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | closed | func (s *stream) closed() bool {
return s.finSeen && s.fin.LessThan(s.una)
} | go | func (s *stream) closed() bool {
return s.finSeen && s.fin.LessThan(s.una)
} | [
"func",
"(",
"s",
"*",
"stream",
")",
"closed",
"(",
")",
"bool",
"{",
"return",
"s",
".",
"finSeen",
"&&",
"s",
".",
"fin",
".",
"LessThan",
"(",
"s",
".",
"una",
")",
"\n",
"}"
] | // closed determines if the stream has already been closed. This happens when
// a FIN has been set by the sender and acknowledged by the receiver. | [
"closed",
"determines",
"if",
"the",
"stream",
"has",
"already",
"been",
"closed",
".",
"This",
"happens",
"when",
"a",
"FIN",
"has",
"been",
"set",
"by",
"the",
"sender",
"and",
"acknowledged",
"by",
"the",
"receiver",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L329-L331 |
164,749 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | dataLen | func dataLen(tcp header.TCP) seqnum.Size {
return seqnum.Size(len(tcp) - int(tcp.DataOffset()))
} | go | func dataLen(tcp header.TCP) seqnum.Size {
return seqnum.Size(len(tcp) - int(tcp.DataOffset()))
} | [
"func",
"dataLen",
"(",
"tcp",
"header",
".",
"TCP",
")",
"seqnum",
".",
"Size",
"{",
"return",
"seqnum",
".",
"Size",
"(",
"len",
"(",
"tcp",
")",
"-",
"int",
"(",
"tcp",
".",
"DataOffset",
"(",
")",
")",
")",
"\n",
"}"
] | // dataLen returns the length of the TCP segment payload. | [
"dataLen",
"returns",
"the",
"length",
"of",
"the",
"TCP",
"segment",
"payload",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L334-L336 |
164,750 | google/netstack | tcpip/transport/tcpconntrack/tcp_conntrack.go | logicalLen | func logicalLen(tcp header.TCP) seqnum.Size {
l := dataLen(tcp)
flags := tcp.Flags()
if flags&header.TCPFlagSyn != 0 {
l++
}
if flags&header.TCPFlagFin != 0 {
l++
}
return l
} | go | func logicalLen(tcp header.TCP) seqnum.Size {
l := dataLen(tcp)
flags := tcp.Flags()
if flags&header.TCPFlagSyn != 0 {
l++
}
if flags&header.TCPFlagFin != 0 {
l++
}
return l
} | [
"func",
"logicalLen",
"(",
"tcp",
"header",
".",
"TCP",
")",
"seqnum",
".",
"Size",
"{",
"l",
":=",
"dataLen",
"(",
"tcp",
")",
"\n",
"flags",
":=",
"tcp",
".",
"Flags",
"(",
")",
"\n",
"if",
"flags",
"&",
"header",
".",
"TCPFlagSyn",
"!=",
"0",
... | // logicalLen calculates the logical length of the TCP segment. | [
"logicalLen",
"calculates",
"the",
"logical",
"length",
"of",
"the",
"TCP",
"segment",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L339-L349 |
164,751 | google/netstack | tcpip/transport/tcp/segment_heap.go | Less | func (h segmentHeap) Less(i, j int) bool {
return h[i].sequenceNumber.LessThan(h[j].sequenceNumber)
} | go | func (h segmentHeap) Less(i, j int) bool {
return h[i].sequenceNumber.LessThan(h[j].sequenceNumber)
} | [
"func",
"(",
"h",
"segmentHeap",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"h",
"[",
"i",
"]",
".",
"sequenceNumber",
".",
"LessThan",
"(",
"h",
"[",
"j",
"]",
".",
"sequenceNumber",
")",
"\n",
"}"
] | // Less determines whether the i-th element of h is less than the j-th element. | [
"Less",
"determines",
"whether",
"the",
"i",
"-",
"th",
"element",
"of",
"h",
"is",
"less",
"than",
"the",
"j",
"-",
"th",
"element",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/segment_heap.go#L25-L27 |
164,752 | google/netstack | tcpip/transport/tcp/segment_heap.go | Swap | func (h segmentHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
} | go | func (h segmentHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
} | [
"func",
"(",
"h",
"segmentHeap",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"h",
"[",
"i",
"]",
",",
"h",
"[",
"j",
"]",
"=",
"h",
"[",
"j",
"]",
",",
"h",
"[",
"i",
"]",
"\n",
"}"
] | // Swap swaps the i-th and j-th elements of h. | [
"Swap",
"swaps",
"the",
"i",
"-",
"th",
"and",
"j",
"-",
"th",
"elements",
"of",
"h",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/segment_heap.go#L30-L32 |
164,753 | google/netstack | tcpip/transport/tcp/segment_heap.go | Pop | func (h *segmentHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
} | go | func (h *segmentHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
} | [
"func",
"(",
"h",
"*",
"segmentHeap",
")",
"Pop",
"(",
")",
"interface",
"{",
"}",
"{",
"old",
":=",
"*",
"h",
"\n",
"n",
":=",
"len",
"(",
"old",
")",
"\n",
"x",
":=",
"old",
"[",
"n",
"-",
"1",
"]",
"\n",
"*",
"h",
"=",
"old",
"[",
":",... | // Pop removes the last element of h and returns it. | [
"Pop",
"removes",
"the",
"last",
"element",
"of",
"h",
"and",
"returns",
"it",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/segment_heap.go#L40-L46 |
164,754 | google/netstack | tcpip/transport/tcp/sack_scoreboard.go | NewSACKScoreboard | func NewSACKScoreboard(smss uint16, iss seqnum.Value) *SACKScoreboard {
return &SACKScoreboard{
smss: smss,
ranges: btree.New(defaultBtreeDegree),
maxSACKED: iss,
}
} | go | func NewSACKScoreboard(smss uint16, iss seqnum.Value) *SACKScoreboard {
return &SACKScoreboard{
smss: smss,
ranges: btree.New(defaultBtreeDegree),
maxSACKED: iss,
}
} | [
"func",
"NewSACKScoreboard",
"(",
"smss",
"uint16",
",",
"iss",
"seqnum",
".",
"Value",
")",
"*",
"SACKScoreboard",
"{",
"return",
"&",
"SACKScoreboard",
"{",
"smss",
":",
"smss",
",",
"ranges",
":",
"btree",
".",
"New",
"(",
"defaultBtreeDegree",
")",
","... | // NewSACKScoreboard returns a new SACK Scoreboard. | [
"NewSACKScoreboard",
"returns",
"a",
"new",
"SACK",
"Scoreboard",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack_scoreboard.go#L48-L54 |
164,755 | google/netstack | tcpip/transport/tcp/sack_scoreboard.go | Reset | func (s *SACKScoreboard) Reset() {
s.ranges = btree.New(defaultBtreeDegree)
s.sacked = 0
} | go | func (s *SACKScoreboard) Reset() {
s.ranges = btree.New(defaultBtreeDegree)
s.sacked = 0
} | [
"func",
"(",
"s",
"*",
"SACKScoreboard",
")",
"Reset",
"(",
")",
"{",
"s",
".",
"ranges",
"=",
"btree",
".",
"New",
"(",
"defaultBtreeDegree",
")",
"\n",
"s",
".",
"sacked",
"=",
"0",
"\n",
"}"
] | // Reset erases all known range information from the SACK scoreboard. | [
"Reset",
"erases",
"all",
"known",
"range",
"information",
"from",
"the",
"SACK",
"scoreboard",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack_scoreboard.go#L57-L60 |
164,756 | google/netstack | tcpip/transport/tcp/sack_scoreboard.go | IsSACKED | func (s *SACKScoreboard) IsSACKED(r header.SACKBlock) bool {
found := false
s.ranges.DescendLessOrEqual(r, func(i btree.Item) bool {
sacked := i.(header.SACKBlock)
if sacked.End.LessThan(r.Start) {
return false
}
if sacked.Contains(r) {
found = true
return false
}
return true
})
return found
} | go | func (s *SACKScoreboard) IsSACKED(r header.SACKBlock) bool {
found := false
s.ranges.DescendLessOrEqual(r, func(i btree.Item) bool {
sacked := i.(header.SACKBlock)
if sacked.End.LessThan(r.Start) {
return false
}
if sacked.Contains(r) {
found = true
return false
}
return true
})
return found
} | [
"func",
"(",
"s",
"*",
"SACKScoreboard",
")",
"IsSACKED",
"(",
"r",
"header",
".",
"SACKBlock",
")",
"bool",
"{",
"found",
":=",
"false",
"\n",
"s",
".",
"ranges",
".",
"DescendLessOrEqual",
"(",
"r",
",",
"func",
"(",
"i",
"btree",
".",
"Item",
")",... | // IsSACKED returns true if the a given range of sequence numbers denoted by r
// are already covered by SACK information in the scoreboard. | [
"IsSACKED",
"returns",
"true",
"if",
"the",
"a",
"given",
"range",
"of",
"sequence",
"numbers",
"denoted",
"by",
"r",
"are",
"already",
"covered",
"by",
"SACK",
"information",
"in",
"the",
"scoreboard",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack_scoreboard.go#L140-L154 |
164,757 | google/netstack | tcpip/transport/tcp/sack_scoreboard.go | String | func (s *SACKScoreboard) String() string {
var str strings.Builder
str.WriteString("SACKScoreboard: {")
s.ranges.Ascend(func(i btree.Item) bool {
str.WriteString(fmt.Sprintf("%v,", i))
return true
})
str.WriteString("}\n")
return str.String()
} | go | func (s *SACKScoreboard) String() string {
var str strings.Builder
str.WriteString("SACKScoreboard: {")
s.ranges.Ascend(func(i btree.Item) bool {
str.WriteString(fmt.Sprintf("%v,", i))
return true
})
str.WriteString("}\n")
return str.String()
} | [
"func",
"(",
"s",
"*",
"SACKScoreboard",
")",
"String",
"(",
")",
"string",
"{",
"var",
"str",
"strings",
".",
"Builder",
"\n",
"str",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"s",
".",
"ranges",
".",
"Ascend",
"(",
"func",
"(",
"i",
"btree"... | // Dump prints the state of the scoreboard structure. | [
"Dump",
"prints",
"the",
"state",
"of",
"the",
"scoreboard",
"structure",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack_scoreboard.go#L157-L166 |
164,758 | google/netstack | tcpip/transport/tcp/sack_scoreboard.go | Delete | func (s *SACKScoreboard) Delete(seq seqnum.Value) {
if s.Empty() {
return
}
toDelete := []btree.Item{}
toInsert := []btree.Item{}
r := header.SACKBlock{seq, seq.Add(1)}
s.ranges.DescendLessOrEqual(r, func(i btree.Item) bool {
if i == r {
return true
}
sb := i.(header.SACKBlock)
toDelete = append(toDelete, i)
if sb.End.LessThanEq(seq) {
s.sacked -= sb.Start.Size(sb.End)
} else {
newSB := header.SACKBlock{seq, sb.End}
toInsert = append(toInsert, newSB)
s.sacked -= sb.Start.Size(seq)
}
return true
})
for _, sb := range toDelete {
s.ranges.Delete(sb)
}
for _, sb := range toInsert {
s.ranges.ReplaceOrInsert(sb)
}
} | go | func (s *SACKScoreboard) Delete(seq seqnum.Value) {
if s.Empty() {
return
}
toDelete := []btree.Item{}
toInsert := []btree.Item{}
r := header.SACKBlock{seq, seq.Add(1)}
s.ranges.DescendLessOrEqual(r, func(i btree.Item) bool {
if i == r {
return true
}
sb := i.(header.SACKBlock)
toDelete = append(toDelete, i)
if sb.End.LessThanEq(seq) {
s.sacked -= sb.Start.Size(sb.End)
} else {
newSB := header.SACKBlock{seq, sb.End}
toInsert = append(toInsert, newSB)
s.sacked -= sb.Start.Size(seq)
}
return true
})
for _, sb := range toDelete {
s.ranges.Delete(sb)
}
for _, sb := range toInsert {
s.ranges.ReplaceOrInsert(sb)
}
} | [
"func",
"(",
"s",
"*",
"SACKScoreboard",
")",
"Delete",
"(",
"seq",
"seqnum",
".",
"Value",
")",
"{",
"if",
"s",
".",
"Empty",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"toDelete",
":=",
"[",
"]",
"btree",
".",
"Item",
"{",
"}",
"\n",
"toInsert",... | // Delete removes all SACK information prior to seq. | [
"Delete",
"removes",
"all",
"SACK",
"information",
"prior",
"to",
"seq",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack_scoreboard.go#L169-L197 |
164,759 | google/netstack | tcpip/transport/tcp/sack_scoreboard.go | Copy | func (s *SACKScoreboard) Copy() (sackBlocks []header.SACKBlock, maxSACKED seqnum.Value) {
s.ranges.Ascend(func(i btree.Item) bool {
sackBlocks = append(sackBlocks, i.(header.SACKBlock))
return true
})
return sackBlocks, s.maxSACKED
} | go | func (s *SACKScoreboard) Copy() (sackBlocks []header.SACKBlock, maxSACKED seqnum.Value) {
s.ranges.Ascend(func(i btree.Item) bool {
sackBlocks = append(sackBlocks, i.(header.SACKBlock))
return true
})
return sackBlocks, s.maxSACKED
} | [
"func",
"(",
"s",
"*",
"SACKScoreboard",
")",
"Copy",
"(",
")",
"(",
"sackBlocks",
"[",
"]",
"header",
".",
"SACKBlock",
",",
"maxSACKED",
"seqnum",
".",
"Value",
")",
"{",
"s",
".",
"ranges",
".",
"Ascend",
"(",
"func",
"(",
"i",
"btree",
".",
"It... | // Copy provides a copy of the SACK scoreboard. | [
"Copy",
"provides",
"a",
"copy",
"of",
"the",
"SACK",
"scoreboard",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/sack_scoreboard.go#L200-L206 |
164,760 | google/netstack | waiter/waiter.go | EventRegister | func (q *Queue) EventRegister(e *Entry, mask EventMask) {
q.mu.Lock()
e.mask = mask
q.list.PushBack(e)
q.mu.Unlock()
} | go | func (q *Queue) EventRegister(e *Entry, mask EventMask) {
q.mu.Lock()
e.mask = mask
q.list.PushBack(e)
q.mu.Unlock()
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"EventRegister",
"(",
"e",
"*",
"Entry",
",",
"mask",
"EventMask",
")",
"{",
"q",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
".",
"mask",
"=",
"mask",
"\n",
"q",
".",
"list",
".",
"PushBack",
"(",
"e",
"... | // EventRegister adds a waiter to the wait queue; the waiter will be notified
// when at least one of the events specified in mask happens. | [
"EventRegister",
"adds",
"a",
"waiter",
"to",
"the",
"wait",
"queue",
";",
"the",
"waiter",
"will",
"be",
"notified",
"when",
"at",
"least",
"one",
"of",
"the",
"events",
"specified",
"in",
"mask",
"happens",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/waiter/waiter.go#L183-L188 |
164,761 | google/netstack | waiter/waiter.go | EventUnregister | func (q *Queue) EventUnregister(e *Entry) {
q.mu.Lock()
q.list.Remove(e)
q.mu.Unlock()
} | go | func (q *Queue) EventUnregister(e *Entry) {
q.mu.Lock()
q.list.Remove(e)
q.mu.Unlock()
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"EventUnregister",
"(",
"e",
"*",
"Entry",
")",
"{",
"q",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"q",
".",
"list",
".",
"Remove",
"(",
"e",
")",
"\n",
"q",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
... | // EventUnregister removes the given waiter entry from the wait queue. | [
"EventUnregister",
"removes",
"the",
"given",
"waiter",
"entry",
"from",
"the",
"wait",
"queue",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/waiter/waiter.go#L191-L195 |
164,762 | google/netstack | waiter/waiter.go | Notify | func (q *Queue) Notify(mask EventMask) {
q.mu.RLock()
for e := q.list.Front(); e != nil; e = e.Next() {
if mask&e.mask != 0 {
e.Callback.Callback(e)
}
}
q.mu.RUnlock()
} | go | func (q *Queue) Notify(mask EventMask) {
q.mu.RLock()
for e := q.list.Front(); e != nil; e = e.Next() {
if mask&e.mask != 0 {
e.Callback.Callback(e)
}
}
q.mu.RUnlock()
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Notify",
"(",
"mask",
"EventMask",
")",
"{",
"q",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"for",
"e",
":=",
"q",
".",
"list",
".",
"Front",
"(",
")",
";",
"e",
"!=",
"nil",
";",
"e",
"=",
"e",
".",
"... | // Notify notifies all waiters in the queue whose masks have at least one bit
// in common with the notification mask. | [
"Notify",
"notifies",
"all",
"waiters",
"in",
"the",
"queue",
"whose",
"masks",
"have",
"at",
"least",
"one",
"bit",
"in",
"common",
"with",
"the",
"notification",
"mask",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/waiter/waiter.go#L199-L207 |
164,763 | google/netstack | waiter/waiter.go | Events | func (q *Queue) Events() EventMask {
ret := EventMask(0)
q.mu.RLock()
for e := q.list.Front(); e != nil; e = e.Next() {
ret |= e.mask
}
q.mu.RUnlock()
return ret
} | go | func (q *Queue) Events() EventMask {
ret := EventMask(0)
q.mu.RLock()
for e := q.list.Front(); e != nil; e = e.Next() {
ret |= e.mask
}
q.mu.RUnlock()
return ret
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Events",
"(",
")",
"EventMask",
"{",
"ret",
":=",
"EventMask",
"(",
"0",
")",
"\n\n",
"q",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"for",
"e",
":=",
"q",
".",
"list",
".",
"Front",
"(",
")",
";",
"e",
... | // Events returns the set of events being waited on. It is the union of the
// masks of all registered entries. | [
"Events",
"returns",
"the",
"set",
"of",
"events",
"being",
"waited",
"on",
".",
"It",
"is",
"the",
"union",
"of",
"the",
"masks",
"of",
"all",
"registered",
"entries",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/waiter/waiter.go#L211-L221 |
164,764 | google/netstack | waiter/waiter.go | IsEmpty | func (q *Queue) IsEmpty() bool {
q.mu.Lock()
defer q.mu.Unlock()
return q.list.Front() == nil
} | go | func (q *Queue) IsEmpty() bool {
q.mu.Lock()
defer q.mu.Unlock()
return q.list.Front() == nil
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"IsEmpty",
"(",
")",
"bool",
"{",
"q",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"q",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"q",
".",
"list",
".",
"Front",
"(",
")",
"==",
"nil",
"... | // IsEmpty returns if the wait queue is empty or not. | [
"IsEmpty",
"returns",
"if",
"the",
"wait",
"queue",
"is",
"empty",
"or",
"not",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/waiter/waiter.go#L224-L229 |
164,765 | google/netstack | tcpip/header/gue.go | Encode | func (b GUE) Encode(i *GUEFields) {
ctl := uint8(0)
if i.Control {
ctl = 1 << 5
}
b[typeHLen] = ctl | i.Type<<6 | (i.HeaderLength-4)/4
b[encapProto] = i.Protocol
} | go | func (b GUE) Encode(i *GUEFields) {
ctl := uint8(0)
if i.Control {
ctl = 1 << 5
}
b[typeHLen] = ctl | i.Type<<6 | (i.HeaderLength-4)/4
b[encapProto] = i.Protocol
} | [
"func",
"(",
"b",
"GUE",
")",
"Encode",
"(",
"i",
"*",
"GUEFields",
")",
"{",
"ctl",
":=",
"uint8",
"(",
"0",
")",
"\n",
"if",
"i",
".",
"Control",
"{",
"ctl",
"=",
"1",
"<<",
"5",
"\n",
"}",
"\n",
"b",
"[",
"typeHLen",
"]",
"=",
"ctl",
"|"... | // Encode encodes all the fields of the GUE header. | [
"Encode",
"encodes",
"all",
"the",
"fields",
"of",
"the",
"GUE",
"header",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/header/gue.go#L66-L73 |
164,766 | dgrijalva/jwt-go | rsa_utils.go | ParseRSAPrivateKeyFromPEM | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err
}
}
var pkey *rsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, ErrNotRSAPrivateKey
}
return pkey, nil
} | go | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err
}
}
var pkey *rsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, ErrNotRSAPrivateKey
}
return pkey, nil
} | [
"func",
"ParseRSAPrivateKeyFromPEM",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"*",
"rsa",
".",
"PrivateKey",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"// Parse PEM block",
"var",
"block",
"*",
"pem",
".",
"Block",
"\n",
"if",
"block",
",",
... | // Parse PEM encoded PKCS1 or PKCS8 private key | [
"Parse",
"PEM",
"encoded",
"PKCS1",
"or",
"PKCS8",
"private",
"key"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/rsa_utils.go#L17-L40 |
164,767 | dgrijalva/jwt-go | rsa_utils.go | ParseRSAPrivateKeyFromPEMWithPassword | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
var parsedKey interface{}
var blockDecrypted []byte
if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil {
return nil, err
}
if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil {
return nil, err
}
}
var pkey *rsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, ErrNotRSAPrivateKey
}
return pkey, nil
} | go | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
var parsedKey interface{}
var blockDecrypted []byte
if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil {
return nil, err
}
if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil {
return nil, err
}
}
var pkey *rsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, ErrNotRSAPrivateKey
}
return pkey, nil
} | [
"func",
"ParseRSAPrivateKeyFromPEMWithPassword",
"(",
"key",
"[",
"]",
"byte",
",",
"password",
"string",
")",
"(",
"*",
"rsa",
".",
"PrivateKey",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"// Parse PEM block",
"var",
"block",
"*",
"pem",
".",
... | // Parse PEM encoded PKCS1 or PKCS8 private key protected with password | [
"Parse",
"PEM",
"encoded",
"PKCS1",
"or",
"PKCS8",
"private",
"key",
"protected",
"with",
"password"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/rsa_utils.go#L43-L72 |
164,768 | dgrijalva/jwt-go | rsa_utils.go | ParseRSAPublicKeyFromPEM | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
// Parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
var pkey *rsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
return nil, ErrNotRSAPublicKey
}
return pkey, nil
} | go | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
// Parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
var pkey *rsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
return nil, ErrNotRSAPublicKey
}
return pkey, nil
} | [
"func",
"ParseRSAPublicKeyFromPEM",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"*",
"rsa",
".",
"PublicKey",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"// Parse PEM block",
"var",
"block",
"*",
"pem",
".",
"Block",
"\n",
"if",
"block",
",",
"... | // Parse PEM encoded PKCS1 or PKCS8 public key | [
"Parse",
"PEM",
"encoded",
"PKCS1",
"or",
"PKCS8",
"public",
"key"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/rsa_utils.go#L75-L101 |
164,769 | dgrijalva/jwt-go | ecdsa.go | Verify | func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error {
var err error
// Decode the signature
var sig []byte
if sig, err = DecodeSegment(signature); err != nil {
return err
}
// Get the key
var ecdsaKey *ecdsa.PublicKey
switch k := key.(type) {
case *ecdsa.PublicKey:
ecdsaKey = k
default:
return ErrInvalidKeyType
}
if len(sig) != 2*m.KeySize {
return ErrECDSAVerification
}
r := big.NewInt(0).SetBytes(sig[:m.KeySize])
s := big.NewInt(0).SetBytes(sig[m.KeySize:])
// Create hasher
if !m.Hash.Available() {
return ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Verify the signature
if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
return nil
} else {
return ErrECDSAVerification
}
} | go | func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error {
var err error
// Decode the signature
var sig []byte
if sig, err = DecodeSegment(signature); err != nil {
return err
}
// Get the key
var ecdsaKey *ecdsa.PublicKey
switch k := key.(type) {
case *ecdsa.PublicKey:
ecdsaKey = k
default:
return ErrInvalidKeyType
}
if len(sig) != 2*m.KeySize {
return ErrECDSAVerification
}
r := big.NewInt(0).SetBytes(sig[:m.KeySize])
s := big.NewInt(0).SetBytes(sig[m.KeySize:])
// Create hasher
if !m.Hash.Available() {
return ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Verify the signature
if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
return nil
} else {
return ErrECDSAVerification
}
} | [
"func",
"(",
"m",
"*",
"SigningMethodECDSA",
")",
"Verify",
"(",
"signingString",
",",
"signature",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"// Decode the signature",
"var",
"sig",
"[",
"]",
"byte",
"\... | // Implements the Verify method from SigningMethod
// For this verify method, key must be an ecdsa.PublicKey struct | [
"Implements",
"the",
"Verify",
"method",
"from",
"SigningMethod",
"For",
"this",
"verify",
"method",
"key",
"must",
"be",
"an",
"ecdsa",
".",
"PublicKey",
"struct"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/ecdsa.go#L58-L96 |
164,770 | dgrijalva/jwt-go | ecdsa.go | Sign | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) {
// Get the key
var ecdsaKey *ecdsa.PrivateKey
switch k := key.(type) {
case *ecdsa.PrivateKey:
ecdsaKey = k
default:
return "", ErrInvalidKeyType
}
// Create the hasher
if !m.Hash.Available() {
return "", ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Sign the string and return r, s
if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
curveBits := ecdsaKey.Curve.Params().BitSize
if m.CurveBits != curveBits {
return "", ErrInvalidKey
}
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes += 1
}
// We serialize the outpus (r and s) into big-endian byte arrays and pad
// them with zeros on the left to make sure the sizes work out. Both arrays
// must be keyBytes long, and the output must be 2*keyBytes long.
rBytes := r.Bytes()
rBytesPadded := make([]byte, keyBytes)
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
sBytes := s.Bytes()
sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
out := append(rBytesPadded, sBytesPadded...)
return EncodeSegment(out), nil
} else {
return "", err
}
} | go | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) {
// Get the key
var ecdsaKey *ecdsa.PrivateKey
switch k := key.(type) {
case *ecdsa.PrivateKey:
ecdsaKey = k
default:
return "", ErrInvalidKeyType
}
// Create the hasher
if !m.Hash.Available() {
return "", ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Sign the string and return r, s
if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
curveBits := ecdsaKey.Curve.Params().BitSize
if m.CurveBits != curveBits {
return "", ErrInvalidKey
}
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes += 1
}
// We serialize the outpus (r and s) into big-endian byte arrays and pad
// them with zeros on the left to make sure the sizes work out. Both arrays
// must be keyBytes long, and the output must be 2*keyBytes long.
rBytes := r.Bytes()
rBytesPadded := make([]byte, keyBytes)
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
sBytes := s.Bytes()
sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
out := append(rBytesPadded, sBytesPadded...)
return EncodeSegment(out), nil
} else {
return "", err
}
} | [
"func",
"(",
"m",
"*",
"SigningMethodECDSA",
")",
"Sign",
"(",
"signingString",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Get the key",
"var",
"ecdsaKey",
"*",
"ecdsa",
".",
"PrivateKey",
"\n",
"switch",
... | // Implements the Sign method from SigningMethod
// For this signing method, key must be an ecdsa.PrivateKey struct | [
"Implements",
"the",
"Sign",
"method",
"from",
"SigningMethod",
"For",
"this",
"signing",
"method",
"key",
"must",
"be",
"an",
"ecdsa",
".",
"PrivateKey",
"struct"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/ecdsa.go#L100-L148 |
164,771 | dgrijalva/jwt-go | cmd/jwt/app.go | start | func start() error {
if *flagSign != "" {
return signToken()
} else if *flagVerify != "" {
return verifyToken()
} else if *flagShow != "" {
return showToken()
} else {
flag.Usage()
return fmt.Errorf("None of the required flags are present. What do you want me to do?")
}
} | go | func start() error {
if *flagSign != "" {
return signToken()
} else if *flagVerify != "" {
return verifyToken()
} else if *flagShow != "" {
return showToken()
} else {
flag.Usage()
return fmt.Errorf("None of the required flags are present. What do you want me to do?")
}
} | [
"func",
"start",
"(",
")",
"error",
"{",
"if",
"*",
"flagSign",
"!=",
"\"",
"\"",
"{",
"return",
"signToken",
"(",
")",
"\n",
"}",
"else",
"if",
"*",
"flagVerify",
"!=",
"\"",
"\"",
"{",
"return",
"verifyToken",
"(",
")",
"\n",
"}",
"else",
"if",
... | // Figure out which thing to do and then do that | [
"Figure",
"out",
"which",
"thing",
"to",
"do",
"and",
"then",
"do",
"that"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/cmd/jwt/app.go#L61-L72 |
164,772 | dgrijalva/jwt-go | cmd/jwt/app.go | verifyToken | func verifyToken() error {
// get the token
tokData, err := loadData(*flagVerify)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
}
// trim possible whitespace from token
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
if *flagDebug {
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
}
// Parse the token. Load the key from command line option
token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
data, err := loadData(*flagKey)
if err != nil {
return nil, err
}
if isEs() {
return jwt.ParseECPublicKeyFromPEM(data)
} else if isRs() {
return jwt.ParseRSAPublicKeyFromPEM(data)
}
return data, nil
})
// Print some debug data
if *flagDebug && token != nil {
fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
}
// Print an error if we can't parse for some reason
if err != nil {
return fmt.Errorf("Couldn't parse token: %v", err)
}
// Is token invalid?
if !token.Valid {
return fmt.Errorf("Token is invalid")
}
// Print the token details
if err := printJSON(token.Claims); err != nil {
return fmt.Errorf("Failed to output claims: %v", err)
}
return nil
} | go | func verifyToken() error {
// get the token
tokData, err := loadData(*flagVerify)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
}
// trim possible whitespace from token
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
if *flagDebug {
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
}
// Parse the token. Load the key from command line option
token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
data, err := loadData(*flagKey)
if err != nil {
return nil, err
}
if isEs() {
return jwt.ParseECPublicKeyFromPEM(data)
} else if isRs() {
return jwt.ParseRSAPublicKeyFromPEM(data)
}
return data, nil
})
// Print some debug data
if *flagDebug && token != nil {
fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
}
// Print an error if we can't parse for some reason
if err != nil {
return fmt.Errorf("Couldn't parse token: %v", err)
}
// Is token invalid?
if !token.Valid {
return fmt.Errorf("Token is invalid")
}
// Print the token details
if err := printJSON(token.Claims); err != nil {
return fmt.Errorf("Failed to output claims: %v", err)
}
return nil
} | [
"func",
"verifyToken",
"(",
")",
"error",
"{",
"// get the token",
"tokData",
",",
"err",
":=",
"loadData",
"(",
"*",
"flagVerify",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",... | // Verify a token and output the claims. This is a great example
// of how to verify and view a token. | [
"Verify",
"a",
"token",
"and",
"output",
"the",
"claims",
".",
"This",
"is",
"a",
"great",
"example",
"of",
"how",
"to",
"verify",
"and",
"view",
"a",
"token",
"."
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/cmd/jwt/app.go#L116-L165 |
164,773 | dgrijalva/jwt-go | cmd/jwt/app.go | signToken | func signToken() error {
// get the token data from command line arguments
tokData, err := loadData(*flagSign)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
} else if *flagDebug {
fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
}
// parse the JSON of the claims
var claims jwt.MapClaims
if err := json.Unmarshal(tokData, &claims); err != nil {
return fmt.Errorf("Couldn't parse claims JSON: %v", err)
}
// add command line claims
if len(flagClaims) > 0 {
for k, v := range flagClaims {
claims[k] = v
}
}
// get the key
var key interface{}
key, err = loadData(*flagKey)
if err != nil {
return fmt.Errorf("Couldn't read key: %v", err)
}
// get the signing alg
alg := jwt.GetSigningMethod(*flagAlg)
if alg == nil {
return fmt.Errorf("Couldn't find signing method: %v", *flagAlg)
}
// create a new token
token := jwt.NewWithClaims(alg, claims)
// add command line headers
if len(flagHead) > 0 {
for k, v := range flagHead {
token.Header[k] = v
}
}
if isEs() {
if k, ok := key.([]byte); !ok {
return fmt.Errorf("Couldn't convert key data to key")
} else {
key, err = jwt.ParseECPrivateKeyFromPEM(k)
if err != nil {
return err
}
}
} else if isRs() {
if k, ok := key.([]byte); !ok {
return fmt.Errorf("Couldn't convert key data to key")
} else {
key, err = jwt.ParseRSAPrivateKeyFromPEM(k)
if err != nil {
return err
}
}
}
if out, err := token.SignedString(key); err == nil {
fmt.Println(out)
} else {
return fmt.Errorf("Error signing token: %v", err)
}
return nil
} | go | func signToken() error {
// get the token data from command line arguments
tokData, err := loadData(*flagSign)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
} else if *flagDebug {
fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
}
// parse the JSON of the claims
var claims jwt.MapClaims
if err := json.Unmarshal(tokData, &claims); err != nil {
return fmt.Errorf("Couldn't parse claims JSON: %v", err)
}
// add command line claims
if len(flagClaims) > 0 {
for k, v := range flagClaims {
claims[k] = v
}
}
// get the key
var key interface{}
key, err = loadData(*flagKey)
if err != nil {
return fmt.Errorf("Couldn't read key: %v", err)
}
// get the signing alg
alg := jwt.GetSigningMethod(*flagAlg)
if alg == nil {
return fmt.Errorf("Couldn't find signing method: %v", *flagAlg)
}
// create a new token
token := jwt.NewWithClaims(alg, claims)
// add command line headers
if len(flagHead) > 0 {
for k, v := range flagHead {
token.Header[k] = v
}
}
if isEs() {
if k, ok := key.([]byte); !ok {
return fmt.Errorf("Couldn't convert key data to key")
} else {
key, err = jwt.ParseECPrivateKeyFromPEM(k)
if err != nil {
return err
}
}
} else if isRs() {
if k, ok := key.([]byte); !ok {
return fmt.Errorf("Couldn't convert key data to key")
} else {
key, err = jwt.ParseRSAPrivateKeyFromPEM(k)
if err != nil {
return err
}
}
}
if out, err := token.SignedString(key); err == nil {
fmt.Println(out)
} else {
return fmt.Errorf("Error signing token: %v", err)
}
return nil
} | [
"func",
"signToken",
"(",
")",
"error",
"{",
"// get the token data from command line arguments",
"tokData",
",",
"err",
":=",
"loadData",
"(",
"*",
"flagSign",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
... | // Create, sign, and output a token. This is a great, simple example of
// how to use this library to create and sign a token. | [
"Create",
"sign",
"and",
"output",
"a",
"token",
".",
"This",
"is",
"a",
"great",
"simple",
"example",
"of",
"how",
"to",
"use",
"this",
"library",
"to",
"create",
"and",
"sign",
"a",
"token",
"."
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/cmd/jwt/app.go#L169-L241 |
164,774 | dgrijalva/jwt-go | cmd/jwt/app.go | showToken | func showToken() error {
// get the token
tokData, err := loadData(*flagShow)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
}
// trim possible whitespace from token
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
if *flagDebug {
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
}
token, err := jwt.Parse(string(tokData), nil)
if token == nil {
return fmt.Errorf("malformed token: %v", err)
}
// Print the token details
fmt.Println("Header:")
if err := printJSON(token.Header); err != nil {
return fmt.Errorf("Failed to output header: %v", err)
}
fmt.Println("Claims:")
if err := printJSON(token.Claims); err != nil {
return fmt.Errorf("Failed to output claims: %v", err)
}
return nil
} | go | func showToken() error {
// get the token
tokData, err := loadData(*flagShow)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
}
// trim possible whitespace from token
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
if *flagDebug {
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
}
token, err := jwt.Parse(string(tokData), nil)
if token == nil {
return fmt.Errorf("malformed token: %v", err)
}
// Print the token details
fmt.Println("Header:")
if err := printJSON(token.Header); err != nil {
return fmt.Errorf("Failed to output header: %v", err)
}
fmt.Println("Claims:")
if err := printJSON(token.Claims); err != nil {
return fmt.Errorf("Failed to output claims: %v", err)
}
return nil
} | [
"func",
"showToken",
"(",
")",
"error",
"{",
"// get the token",
"tokData",
",",
"err",
":=",
"loadData",
"(",
"*",
"flagShow",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"... | // showToken pretty-prints the token on the command line. | [
"showToken",
"pretty",
"-",
"prints",
"the",
"token",
"on",
"the",
"command",
"line",
"."
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/cmd/jwt/app.go#L244-L274 |
164,775 | dgrijalva/jwt-go | request/oauth2.go | stripBearerPrefixFromTokenString | func stripBearerPrefixFromTokenString(tok string) (string, error) {
// Should be a bearer token
if len(tok) > 6 && strings.ToUpper(tok[0:7]) == "BEARER " {
return tok[7:], nil
}
return tok, nil
} | go | func stripBearerPrefixFromTokenString(tok string) (string, error) {
// Should be a bearer token
if len(tok) > 6 && strings.ToUpper(tok[0:7]) == "BEARER " {
return tok[7:], nil
}
return tok, nil
} | [
"func",
"stripBearerPrefixFromTokenString",
"(",
"tok",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Should be a bearer token",
"if",
"len",
"(",
"tok",
")",
">",
"6",
"&&",
"strings",
".",
"ToUpper",
"(",
"tok",
"[",
"0",
":",
"7",
"]",
")"... | // Strips 'Bearer ' prefix from bearer token string | [
"Strips",
"Bearer",
"prefix",
"from",
"bearer",
"token",
"string"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/request/oauth2.go#L8-L14 |
164,776 | dgrijalva/jwt-go | token.go | SignedString | func (t *Token) SignedString(key interface{}) (string, error) {
var sig, sstr string
var err error
if sstr, err = t.SigningString(); err != nil {
return "", err
}
if sig, err = t.Method.Sign(sstr, key); err != nil {
return "", err
}
return strings.Join([]string{sstr, sig}, "."), nil
} | go | func (t *Token) SignedString(key interface{}) (string, error) {
var sig, sstr string
var err error
if sstr, err = t.SigningString(); err != nil {
return "", err
}
if sig, err = t.Method.Sign(sstr, key); err != nil {
return "", err
}
return strings.Join([]string{sstr, sig}, "."), nil
} | [
"func",
"(",
"t",
"*",
"Token",
")",
"SignedString",
"(",
"key",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"sig",
",",
"sstr",
"string",
"\n",
"var",
"err",
"error",
"\n",
"if",
"sstr",
",",
"err",
"=",
"t",
".",
... | // Get the complete, signed token | [
"Get",
"the",
"complete",
"signed",
"token"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/token.go#L49-L59 |
164,777 | dgrijalva/jwt-go | token.go | SigningString | func (t *Token) SigningString() (string, error) {
var err error
parts := make([]string, 2)
for i, _ := range parts {
var jsonValue []byte
if i == 0 {
if jsonValue, err = json.Marshal(t.Header); err != nil {
return "", err
}
} else {
if jsonValue, err = json.Marshal(t.Claims); err != nil {
return "", err
}
}
parts[i] = EncodeSegment(jsonValue)
}
return strings.Join(parts, "."), nil
} | go | func (t *Token) SigningString() (string, error) {
var err error
parts := make([]string, 2)
for i, _ := range parts {
var jsonValue []byte
if i == 0 {
if jsonValue, err = json.Marshal(t.Header); err != nil {
return "", err
}
} else {
if jsonValue, err = json.Marshal(t.Claims); err != nil {
return "", err
}
}
parts[i] = EncodeSegment(jsonValue)
}
return strings.Join(parts, "."), nil
} | [
"func",
"(",
"t",
"*",
"Token",
")",
"SigningString",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"parts",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"2",
")",
"\n",
"for",
"i",
",",
"_",
":=",
"range",
"parts... | // Generate the signing string. This is the
// most expensive part of the whole deal. Unless you
// need this for something special, just go straight for
// the SignedString. | [
"Generate",
"the",
"signing",
"string",
".",
"This",
"is",
"the",
"most",
"expensive",
"part",
"of",
"the",
"whole",
"deal",
".",
"Unless",
"you",
"need",
"this",
"for",
"something",
"special",
"just",
"go",
"straight",
"for",
"the",
"SignedString",
"."
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/token.go#L65-L83 |
164,778 | dgrijalva/jwt-go | token.go | EncodeSegment | func EncodeSegment(seg []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
} | go | func EncodeSegment(seg []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
} | [
"func",
"EncodeSegment",
"(",
"seg",
"[",
"]",
"byte",
")",
"string",
"{",
"return",
"strings",
".",
"TrimRight",
"(",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"seg",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Encode JWT specific base64url encoding with padding stripped | [
"Encode",
"JWT",
"specific",
"base64url",
"encoding",
"with",
"padding",
"stripped"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/token.go#L97-L99 |
164,779 | dgrijalva/jwt-go | token.go | DecodeSegment | func DecodeSegment(seg string) ([]byte, error) {
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(seg)
} | go | func DecodeSegment(seg string) ([]byte, error) {
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(seg)
} | [
"func",
"DecodeSegment",
"(",
"seg",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"l",
":=",
"len",
"(",
"seg",
")",
"%",
"4",
";",
"l",
">",
"0",
"{",
"seg",
"+=",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"4",
... | // Decode JWT specific base64url encoding with padding stripped | [
"Decode",
"JWT",
"specific",
"base64url",
"encoding",
"with",
"padding",
"stripped"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/token.go#L102-L108 |
164,780 | dgrijalva/jwt-go | errors.go | NewValidationError | func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
return &ValidationError{
text: errorText,
Errors: errorFlags,
}
} | go | func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
return &ValidationError{
text: errorText,
Errors: errorFlags,
}
} | [
"func",
"NewValidationError",
"(",
"errorText",
"string",
",",
"errorFlags",
"uint32",
")",
"*",
"ValidationError",
"{",
"return",
"&",
"ValidationError",
"{",
"text",
":",
"errorText",
",",
"Errors",
":",
"errorFlags",
",",
"}",
"\n",
"}"
] | // Helper for constructing a ValidationError with a string error message | [
"Helper",
"for",
"constructing",
"a",
"ValidationError",
"with",
"a",
"string",
"error",
"message"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/errors.go#L31-L36 |
164,781 | dgrijalva/jwt-go | errors.go | Error | func (e ValidationError) Error() string {
if e.Inner != nil {
return e.Inner.Error()
} else if e.text != "" {
return e.text
} else {
return "token is invalid"
}
} | go | func (e ValidationError) Error() string {
if e.Inner != nil {
return e.Inner.Error()
} else if e.text != "" {
return e.text
} else {
return "token is invalid"
}
} | [
"func",
"(",
"e",
"ValidationError",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"e",
".",
"Inner",
"!=",
"nil",
"{",
"return",
"e",
".",
"Inner",
".",
"Error",
"(",
")",
"\n",
"}",
"else",
"if",
"e",
".",
"text",
"!=",
"\"",
"\"",
"{",
"retur... | // Validation error is an error type | [
"Validation",
"error",
"is",
"an",
"error",
"type"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/errors.go#L46-L54 |
164,782 | dgrijalva/jwt-go | signing_method.go | GetSigningMethod | func GetSigningMethod(alg string) (method SigningMethod) {
signingMethodLock.RLock()
defer signingMethodLock.RUnlock()
if methodF, ok := signingMethods[alg]; ok {
method = methodF()
}
return
} | go | func GetSigningMethod(alg string) (method SigningMethod) {
signingMethodLock.RLock()
defer signingMethodLock.RUnlock()
if methodF, ok := signingMethods[alg]; ok {
method = methodF()
}
return
} | [
"func",
"GetSigningMethod",
"(",
"alg",
"string",
")",
"(",
"method",
"SigningMethod",
")",
"{",
"signingMethodLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"signingMethodLock",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"methodF",
",",
"ok",
":=",
"signingMeth... | // Get a signing method from an "alg" string | [
"Get",
"a",
"signing",
"method",
"from",
"an",
"alg",
"string"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/signing_method.go#L27-L35 |
164,783 | dgrijalva/jwt-go | rsa_pss.go | Verify | func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error {
var err error
// Decode the signature
var sig []byte
if sig, err = DecodeSegment(signature); err != nil {
return err
}
var rsaKey *rsa.PublicKey
switch k := key.(type) {
case *rsa.PublicKey:
rsaKey = k
default:
return ErrInvalidKey
}
// Create hasher
if !m.Hash.Available() {
return ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
} | go | func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error {
var err error
// Decode the signature
var sig []byte
if sig, err = DecodeSegment(signature); err != nil {
return err
}
var rsaKey *rsa.PublicKey
switch k := key.(type) {
case *rsa.PublicKey:
rsaKey = k
default:
return ErrInvalidKey
}
// Create hasher
if !m.Hash.Available() {
return ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
} | [
"func",
"(",
"m",
"*",
"SigningMethodRSAPSS",
")",
"Verify",
"(",
"signingString",
",",
"signature",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"// Decode the signature",
"var",
"sig",
"[",
"]",
"byte",
"... | // Implements the Verify method from SigningMethod
// For this verify method, key must be an rsa.PublicKey struct | [
"Implements",
"the",
"Verify",
"method",
"from",
"SigningMethod",
"For",
"this",
"verify",
"method",
"key",
"must",
"be",
"an",
"rsa",
".",
"PublicKey",
"struct"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/rsa_pss.go#L73-L98 |
164,784 | dgrijalva/jwt-go | rsa_pss.go | Sign | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) {
var rsaKey *rsa.PrivateKey
switch k := key.(type) {
case *rsa.PrivateKey:
rsaKey = k
default:
return "", ErrInvalidKeyType
}
// Create the hasher
if !m.Hash.Available() {
return "", ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Sign the string and return the encoded bytes
if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
return EncodeSegment(sigBytes), nil
} else {
return "", err
}
} | go | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) {
var rsaKey *rsa.PrivateKey
switch k := key.(type) {
case *rsa.PrivateKey:
rsaKey = k
default:
return "", ErrInvalidKeyType
}
// Create the hasher
if !m.Hash.Available() {
return "", ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Sign the string and return the encoded bytes
if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
return EncodeSegment(sigBytes), nil
} else {
return "", err
}
} | [
"func",
"(",
"m",
"*",
"SigningMethodRSAPSS",
")",
"Sign",
"(",
"signingString",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"rsaKey",
"*",
"rsa",
".",
"PrivateKey",
"\n\n",
"switch",
"k",
":=",
"key"... | // Implements the Sign method from SigningMethod
// For this signing method, key must be an rsa.PrivateKey struct | [
"Implements",
"the",
"Sign",
"method",
"from",
"SigningMethod",
"For",
"this",
"signing",
"method",
"key",
"must",
"be",
"an",
"rsa",
".",
"PrivateKey",
"struct"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/rsa_pss.go#L102-L126 |
164,785 | dgrijalva/jwt-go | ecdsa_utils.go | ParseECPrivateKeyFromPEM | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
// Parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
return nil, err
}
var pkey *ecdsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
return nil, ErrNotECPrivateKey
}
return pkey, nil
} | go | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrKeyMustBePEMEncoded
}
// Parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
return nil, err
}
var pkey *ecdsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
return nil, ErrNotECPrivateKey
}
return pkey, nil
} | [
"func",
"ParseECPrivateKeyFromPEM",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"*",
"ecdsa",
".",
"PrivateKey",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"// Parse PEM block",
"var",
"block",
"*",
"pem",
".",
"Block",
"\n",
"if",
"block",
",",
... | // Parse PEM encoded Elliptic Curve Private Key Structure | [
"Parse",
"PEM",
"encoded",
"Elliptic",
"Curve",
"Private",
"Key",
"Structure"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/ecdsa_utils.go#L16-L38 |
164,786 | dgrijalva/jwt-go | none.go | Verify | func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) {
// Key must be UnsafeAllowNoneSignatureType to prevent accidentally
// accepting 'none' signing method
if _, ok := key.(unsafeNoneMagicConstant); !ok {
return NoneSignatureTypeDisallowedError
}
// If signing method is none, signature must be an empty string
if signature != "" {
return NewValidationError(
"'none' signing method with non-empty signature",
ValidationErrorSignatureInvalid,
)
}
// Accept 'none' signing method.
return nil
} | go | func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) {
// Key must be UnsafeAllowNoneSignatureType to prevent accidentally
// accepting 'none' signing method
if _, ok := key.(unsafeNoneMagicConstant); !ok {
return NoneSignatureTypeDisallowedError
}
// If signing method is none, signature must be an empty string
if signature != "" {
return NewValidationError(
"'none' signing method with non-empty signature",
ValidationErrorSignatureInvalid,
)
}
// Accept 'none' signing method.
return nil
} | [
"func",
"(",
"m",
"*",
"signingMethodNone",
")",
"Verify",
"(",
"signingString",
",",
"signature",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"// Key must be UnsafeAllowNoneSignatureType to prevent accidentally",
"// accepting 'no... | // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key | [
"Only",
"allow",
"none",
"alg",
"type",
"if",
"UnsafeAllowNoneSignatureType",
"is",
"specified",
"as",
"the",
"key"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/none.go#L28-L44 |
164,787 | dgrijalva/jwt-go | none.go | Sign | func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) {
if _, ok := key.(unsafeNoneMagicConstant); ok {
return "", nil
}
return "", NoneSignatureTypeDisallowedError
} | go | func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) {
if _, ok := key.(unsafeNoneMagicConstant); ok {
return "", nil
}
return "", NoneSignatureTypeDisallowedError
} | [
"func",
"(",
"m",
"*",
"signingMethodNone",
")",
"Sign",
"(",
"signingString",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"key",
".",
"(",
"unsafeNoneMagicConstant",
")",
";",
... | // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key | [
"Only",
"allow",
"none",
"signing",
"if",
"UnsafeAllowNoneSignatureType",
"is",
"specified",
"as",
"the",
"key"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/none.go#L47-L52 |
164,788 | dgrijalva/jwt-go | request/request.go | ParseFromRequest | func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error) {
// Create basic parser struct
p := &fromRequestParser{req, extractor, nil, nil}
// Handle options
for _, option := range options {
option(p)
}
// Set defaults
if p.claims == nil {
p.claims = jwt.MapClaims{}
}
if p.parser == nil {
p.parser = &jwt.Parser{}
}
// perform extract
tokenString, err := p.extractor.ExtractToken(req)
if err != nil {
return nil, err
}
// perform parse
return p.parser.ParseWithClaims(tokenString, p.claims, keyFunc)
} | go | func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error) {
// Create basic parser struct
p := &fromRequestParser{req, extractor, nil, nil}
// Handle options
for _, option := range options {
option(p)
}
// Set defaults
if p.claims == nil {
p.claims = jwt.MapClaims{}
}
if p.parser == nil {
p.parser = &jwt.Parser{}
}
// perform extract
tokenString, err := p.extractor.ExtractToken(req)
if err != nil {
return nil, err
}
// perform parse
return p.parser.ParseWithClaims(tokenString, p.claims, keyFunc)
} | [
"func",
"ParseFromRequest",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"extractor",
"Extractor",
",",
"keyFunc",
"jwt",
".",
"Keyfunc",
",",
"options",
"...",
"ParseFromRequestOption",
")",
"(",
"token",
"*",
"jwt",
".",
"Token",
",",
"err",
"error",
")... | // Extract and parse a JWT token from an HTTP request.
// This behaves the same as Parse, but accepts a request and an extractor
// instead of a token string. The Extractor interface allows you to define
// the logic for extracting a token. Several useful implementations are provided.
//
// You can provide options to modify parsing behavior | [
"Extract",
"and",
"parse",
"a",
"JWT",
"token",
"from",
"an",
"HTTP",
"request",
".",
"This",
"behaves",
"the",
"same",
"as",
"Parse",
"but",
"accepts",
"a",
"request",
"and",
"an",
"extractor",
"instead",
"of",
"a",
"token",
"string",
".",
"The",
"Extra... | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/request/request.go#L14-L39 |
164,789 | dgrijalva/jwt-go | request/request.go | WithClaims | func WithClaims(claims jwt.Claims) ParseFromRequestOption {
return func(p *fromRequestParser) {
p.claims = claims
}
} | go | func WithClaims(claims jwt.Claims) ParseFromRequestOption {
return func(p *fromRequestParser) {
p.claims = claims
}
} | [
"func",
"WithClaims",
"(",
"claims",
"jwt",
".",
"Claims",
")",
"ParseFromRequestOption",
"{",
"return",
"func",
"(",
"p",
"*",
"fromRequestParser",
")",
"{",
"p",
".",
"claims",
"=",
"claims",
"\n",
"}",
"\n",
"}"
] | // Parse with custom claims | [
"Parse",
"with",
"custom",
"claims"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/request/request.go#L57-L61 |
164,790 | dgrijalva/jwt-go | request/request.go | WithParser | func WithParser(parser *jwt.Parser) ParseFromRequestOption {
return func(p *fromRequestParser) {
p.parser = parser
}
} | go | func WithParser(parser *jwt.Parser) ParseFromRequestOption {
return func(p *fromRequestParser) {
p.parser = parser
}
} | [
"func",
"WithParser",
"(",
"parser",
"*",
"jwt",
".",
"Parser",
")",
"ParseFromRequestOption",
"{",
"return",
"func",
"(",
"p",
"*",
"fromRequestParser",
")",
"{",
"p",
".",
"parser",
"=",
"parser",
"\n",
"}",
"\n",
"}"
] | // Parse using a custom parser | [
"Parse",
"using",
"a",
"custom",
"parser"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/request/request.go#L64-L68 |
164,791 | dgrijalva/jwt-go | hmac.go | Verify | func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
// Verify the key is the right type
keyBytes, ok := key.([]byte)
if !ok {
return ErrInvalidKeyType
}
// Decode signature, for comparison
sig, err := DecodeSegment(signature)
if err != nil {
return err
}
// Can we use the specified hashing method?
if !m.Hash.Available() {
return ErrHashUnavailable
}
// This signing method is symmetric, so we validate the signature
// by reproducing the signature from the signing string and key, then
// comparing that against the provided signature.
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
if !hmac.Equal(sig, hasher.Sum(nil)) {
return ErrSignatureInvalid
}
// No validation errors. Signature is good.
return nil
} | go | func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
// Verify the key is the right type
keyBytes, ok := key.([]byte)
if !ok {
return ErrInvalidKeyType
}
// Decode signature, for comparison
sig, err := DecodeSegment(signature)
if err != nil {
return err
}
// Can we use the specified hashing method?
if !m.Hash.Available() {
return ErrHashUnavailable
}
// This signing method is symmetric, so we validate the signature
// by reproducing the signature from the signing string and key, then
// comparing that against the provided signature.
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
if !hmac.Equal(sig, hasher.Sum(nil)) {
return ErrSignatureInvalid
}
// No validation errors. Signature is good.
return nil
} | [
"func",
"(",
"m",
"*",
"SigningMethodHMAC",
")",
"Verify",
"(",
"signingString",
",",
"signature",
"string",
",",
"key",
"interface",
"{",
"}",
")",
"error",
"{",
"// Verify the key is the right type",
"keyBytes",
",",
"ok",
":=",
"key",
".",
"(",
"[",
"]",
... | // Verify the signature of HSXXX tokens. Returns nil if the signature is valid. | [
"Verify",
"the",
"signature",
"of",
"HSXXX",
"tokens",
".",
"Returns",
"nil",
"if",
"the",
"signature",
"is",
"valid",
"."
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/hmac.go#L49-L78 |
164,792 | goreleaser/goreleaser | internal/middleware/error.go | ErrHandler | func ErrHandler(action Action) Action {
return func(ctx *context.Context) error {
var err = action(ctx)
if err == nil {
return nil
}
if pipe.IsSkip(err) {
log.WithError(err).Warn("pipe skipped")
return nil
}
return err
}
} | go | func ErrHandler(action Action) Action {
return func(ctx *context.Context) error {
var err = action(ctx)
if err == nil {
return nil
}
if pipe.IsSkip(err) {
log.WithError(err).Warn("pipe skipped")
return nil
}
return err
}
} | [
"func",
"ErrHandler",
"(",
"action",
"Action",
")",
"Action",
"{",
"return",
"func",
"(",
"ctx",
"*",
"context",
".",
"Context",
")",
"error",
"{",
"var",
"err",
"=",
"action",
"(",
"ctx",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
... | // ErrHandler handles an action error, ignoring and logging pipe skipped
// errors. | [
"ErrHandler",
"handles",
"an",
"action",
"error",
"ignoring",
"and",
"logging",
"pipe",
"skipped",
"errors",
"."
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/middleware/error.go#L11-L23 |
164,793 | goreleaser/goreleaser | internal/pipe/release/remote.go | remoteRepo | func remoteRepo() (result config.Repo, err error) {
if !git.IsRepo() {
return result, errors.New("current folder is not a git repository")
}
out, err := git.Run("config", "--get", "remote.origin.url")
if err != nil {
return result, fmt.Errorf("repository doesn't have an `origin` remote")
}
return extractRepoFromURL(out), nil
} | go | func remoteRepo() (result config.Repo, err error) {
if !git.IsRepo() {
return result, errors.New("current folder is not a git repository")
}
out, err := git.Run("config", "--get", "remote.origin.url")
if err != nil {
return result, fmt.Errorf("repository doesn't have an `origin` remote")
}
return extractRepoFromURL(out), nil
} | [
"func",
"remoteRepo",
"(",
")",
"(",
"result",
"config",
".",
"Repo",
",",
"err",
"error",
")",
"{",
"if",
"!",
"git",
".",
"IsRepo",
"(",
")",
"{",
"return",
"result",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"out",
",... | // remoteRepo gets the repo name from the Git config. | [
"remoteRepo",
"gets",
"the",
"repo",
"name",
"from",
"the",
"Git",
"config",
"."
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/pipe/release/remote.go#L13-L22 |
164,794 | goreleaser/goreleaser | internal/artifact/artifact.go | ExtraOr | func (a Artifact) ExtraOr(key string, or interface{}) interface{} {
if a.Extra[key] == nil {
return or
}
return a.Extra[key]
} | go | func (a Artifact) ExtraOr(key string, or interface{}) interface{} {
if a.Extra[key] == nil {
return or
}
return a.Extra[key]
} | [
"func",
"(",
"a",
"Artifact",
")",
"ExtraOr",
"(",
"key",
"string",
",",
"or",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"if",
"a",
".",
"Extra",
"[",
"key",
"]",
"==",
"nil",
"{",
"return",
"or",
"\n",
"}",
"\n",
"return",
"a",
"... | // ExtraOr returns the Extra field with the given key or the or value specified
// if it is nil. | [
"ExtraOr",
"returns",
"the",
"Extra",
"field",
"with",
"the",
"given",
"key",
"or",
"the",
"or",
"value",
"specified",
"if",
"it",
"is",
"nil",
"."
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L81-L86 |
164,795 | goreleaser/goreleaser | internal/artifact/artifact.go | GroupByPlatform | func (artifacts Artifacts) GroupByPlatform() map[string][]Artifact {
var result = map[string][]Artifact{}
for _, a := range artifacts.items {
plat := a.Goos + a.Goarch + a.Goarm
result[plat] = append(result[plat], a)
}
return result
} | go | func (artifacts Artifacts) GroupByPlatform() map[string][]Artifact {
var result = map[string][]Artifact{}
for _, a := range artifacts.items {
plat := a.Goos + a.Goarch + a.Goarm
result[plat] = append(result[plat], a)
}
return result
} | [
"func",
"(",
"artifacts",
"Artifacts",
")",
"GroupByPlatform",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"Artifact",
"{",
"var",
"result",
"=",
"map",
"[",
"string",
"]",
"[",
"]",
"Artifact",
"{",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range... | // GroupByPlatform groups the artifacts by their platform | [
"GroupByPlatform",
"groups",
"the",
"artifacts",
"by",
"their",
"platform"
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L143-L150 |
164,796 | goreleaser/goreleaser | internal/artifact/artifact.go | Add | func (artifacts *Artifacts) Add(a Artifact) {
artifacts.lock.Lock()
defer artifacts.lock.Unlock()
log.WithFields(log.Fields{
"name": a.Name,
"path": a.Path,
"type": a.Type,
}).Debug("added new artifact")
artifacts.items = append(artifacts.items, a)
} | go | func (artifacts *Artifacts) Add(a Artifact) {
artifacts.lock.Lock()
defer artifacts.lock.Unlock()
log.WithFields(log.Fields{
"name": a.Name,
"path": a.Path,
"type": a.Type,
}).Debug("added new artifact")
artifacts.items = append(artifacts.items, a)
} | [
"func",
"(",
"artifacts",
"*",
"Artifacts",
")",
"Add",
"(",
"a",
"Artifact",
")",
"{",
"artifacts",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"artifacts",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"log",
".",
"WithFields",
"(",
"log",
"... | // Add safely adds a new artifact to an artifact list | [
"Add",
"safely",
"adds",
"a",
"new",
"artifact",
"to",
"an",
"artifact",
"list"
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L153-L162 |
164,797 | goreleaser/goreleaser | internal/artifact/artifact.go | ByGoos | func ByGoos(s string) Filter {
return func(a Artifact) bool {
return a.Goos == s
}
} | go | func ByGoos(s string) Filter {
return func(a Artifact) bool {
return a.Goos == s
}
} | [
"func",
"ByGoos",
"(",
"s",
"string",
")",
"Filter",
"{",
"return",
"func",
"(",
"a",
"Artifact",
")",
"bool",
"{",
"return",
"a",
".",
"Goos",
"==",
"s",
"\n",
"}",
"\n",
"}"
] | // ByGoos is a predefined filter that filters by the given goos | [
"ByGoos",
"is",
"a",
"predefined",
"filter",
"that",
"filters",
"by",
"the",
"given",
"goos"
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L169-L173 |
164,798 | goreleaser/goreleaser | internal/artifact/artifact.go | ByGoarch | func ByGoarch(s string) Filter {
return func(a Artifact) bool {
return a.Goarch == s
}
} | go | func ByGoarch(s string) Filter {
return func(a Artifact) bool {
return a.Goarch == s
}
} | [
"func",
"ByGoarch",
"(",
"s",
"string",
")",
"Filter",
"{",
"return",
"func",
"(",
"a",
"Artifact",
")",
"bool",
"{",
"return",
"a",
".",
"Goarch",
"==",
"s",
"\n",
"}",
"\n",
"}"
] | // ByGoarch is a predefined filter that filters by the given goarch | [
"ByGoarch",
"is",
"a",
"predefined",
"filter",
"that",
"filters",
"by",
"the",
"given",
"goarch"
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L176-L180 |
164,799 | goreleaser/goreleaser | internal/artifact/artifact.go | ByGoarm | func ByGoarm(s string) Filter {
return func(a Artifact) bool {
return a.Goarm == s
}
} | go | func ByGoarm(s string) Filter {
return func(a Artifact) bool {
return a.Goarm == s
}
} | [
"func",
"ByGoarm",
"(",
"s",
"string",
")",
"Filter",
"{",
"return",
"func",
"(",
"a",
"Artifact",
")",
"bool",
"{",
"return",
"a",
".",
"Goarm",
"==",
"s",
"\n",
"}",
"\n",
"}"
] | // ByGoarm is a predefined filter that filters by the given goarm | [
"ByGoarm",
"is",
"a",
"predefined",
"filter",
"that",
"filters",
"by",
"the",
"given",
"goarm"
] | 76fa5909a2dbf261ec188188db66a294786188c8 | https://github.com/goreleaser/goreleaser/blob/76fa5909a2dbf261ec188188db66a294786188c8/internal/artifact/artifact.go#L183-L187 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.