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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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",
"[",
"i",
"]",
".",
"buf",
"=",
"b",
"\n",
"m",
".",
"freeList",
"=",
"m",
".",
"ids",
"[",
"i",
"]",
".",
"nextFree",
"\n",
"return",
"i",
"\n",
"}",
"\n\n",
"// We need to expand the id descriptor.",
"m",
".",
"ids",
"=",
"append",
"(",
"m",
".",
"ids",
",",
"idDescriptor",
"{",
"buf",
":",
"b",
"}",
")",
"\n",
"return",
"uint64",
"(",
"len",
"(",
"m",
".",
"ids",
")",
"-",
"1",
")",
"\n",
"}"
] | // 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 | train |
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",
":=",
"&",
"m",
".",
"ids",
"[",
"i",
"]",
"\n",
"b",
":=",
"desc",
".",
"buf",
"\n",
"if",
"b",
"==",
"nil",
"{",
"// The provided id is not currently assigned.",
"return",
"nil",
"\n",
"}",
"\n\n",
"desc",
".",
"buf",
"=",
"nil",
"\n",
"desc",
".",
"nextFree",
"=",
"m",
".",
"freeList",
"\n",
"m",
".",
"freeList",
"=",
"i",
"\n\n",
"return",
"b",
"\n",
"}"
] | // 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 | train |
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",
"=",
"uint64",
"(",
"initialOffset",
"+",
"size",
"/",
"entrySize",
"*",
"entrySize",
")",
"\n",
"b",
".",
"entrySize",
"=",
"uint32",
"(",
"entrySize",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"freeList",
"=",
"d",
".",
"Next",
"\n",
"d",
".",
"Next",
"=",
"nil",
"\n",
"return",
"d",
"\n",
"}",
"\n\n",
"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",
",",
"}",
"\n",
"b",
".",
"curOffset",
"+=",
"uint64",
"(",
"b",
".",
"entrySize",
")",
"\n",
"return",
"d",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"}",
"\n\n",
"// Push list onto free list.",
"last",
".",
"Next",
"=",
"b",
".",
"freeList",
"\n",
"b",
".",
"freeList",
"=",
"d",
"\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 | train |
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",
"}",
"\n\n",
"synRcvdCount",
".",
"pending",
".",
"Add",
"(",
"1",
")",
"\n",
"synRcvdCount",
".",
"value",
"++",
"\n\n",
"return",
"true",
"\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",
"fails",
"otherwise",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L108-L120 | train |
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 | train |
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",
"{",
"stack",
":",
"stack",
",",
"rcvWnd",
":",
"rcvWnd",
",",
"hasher",
":",
"sha1",
".",
"New",
"(",
")",
",",
"v6only",
":",
"v6only",
",",
"netProto",
":",
"netProto",
",",
"}",
"\n\n",
"rand",
".",
"Read",
"(",
"l",
".",
"nonce",
"[",
"0",
"]",
"[",
":",
"]",
")",
"\n",
"rand",
".",
"Read",
"(",
"l",
".",
"nonce",
"[",
"1",
"]",
"[",
":",
"]",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] | // 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 | train |
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",
"]",
"byte",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"payload",
"[",
"0",
":",
"]",
",",
"id",
".",
"LocalPort",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"payload",
"[",
"2",
":",
"]",
",",
"id",
".",
"RemotePort",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"payload",
"[",
"4",
":",
"]",
",",
"ts",
")",
"\n\n",
"// Feed everything to the hasher.",
"l",
".",
"hasherMu",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"hasher",
".",
"Reset",
"(",
")",
"\n",
"l",
".",
"hasher",
".",
"Write",
"(",
"payload",
"[",
":",
"]",
")",
"\n",
"l",
".",
"hasher",
".",
"Write",
"(",
"l",
".",
"nonce",
"[",
"nonceIndex",
"]",
"[",
":",
"]",
")",
"\n",
"io",
".",
"WriteString",
"(",
"l",
".",
"hasher",
",",
"string",
"(",
"id",
".",
"LocalAddress",
")",
")",
"\n",
"io",
".",
"WriteString",
"(",
"l",
".",
"hasher",
",",
"string",
"(",
"id",
".",
"RemoteAddress",
")",
")",
"\n\n",
"// Finalize the calculation of the hash and return the first 4 bytes.",
"h",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"sha1",
".",
"Size",
")",
"\n",
"h",
"=",
"l",
".",
"hasher",
".",
"Sum",
"(",
"h",
")",
"\n",
"l",
".",
"hasherMu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"h",
"[",
":",
"]",
")",
"\n",
"}"
] | // 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 | train |
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",
":=",
"l",
".",
"cookieHash",
"(",
"id",
",",
"0",
",",
"0",
")",
"+",
"uint32",
"(",
"seq",
")",
"+",
"(",
"ts",
"<<",
"tsOffset",
")",
"\n",
"v",
"+=",
"(",
"l",
".",
"cookieHash",
"(",
"id",
",",
"ts",
",",
"1",
")",
"+",
"data",
")",
"&",
"hashMask",
"\n",
"return",
"seqnum",
".",
"Value",
"(",
"v",
")",
"\n",
"}"
] | // 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 | train |
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",
"(",
")",
"\n",
"v",
":=",
"uint32",
"(",
"cookie",
")",
"-",
"l",
".",
"cookieHash",
"(",
"id",
",",
"0",
",",
"0",
")",
"-",
"uint32",
"(",
"seq",
")",
"\n",
"cookieTS",
":=",
"v",
">>",
"tsOffset",
"\n",
"if",
"(",
"(",
"ts",
"-",
"cookieTS",
")",
"&",
"tsMask",
")",
">",
"maxTSDiff",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n\n",
"return",
"(",
"v",
"-",
"l",
".",
"cookieHash",
"(",
"id",
",",
"cookieTS",
",",
"1",
")",
")",
"&",
"hashMask",
",",
"true",
"\n",
"}"
] | // 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",
"createCookie",
"was",
"called",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L187-L196 | train |
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",
",",
"*",
"tcpip",
".",
"Error",
")",
"{",
"// Create a new endpoint.",
"netProto",
":=",
"l",
".",
"netProto",
"\n",
"if",
"netProto",
"==",
"0",
"{",
"netProto",
"=",
"s",
".",
"route",
".",
"NetProto",
"\n",
"}",
"\n",
"n",
":=",
"newEndpoint",
"(",
"l",
".",
"stack",
",",
"netProto",
",",
"nil",
")",
"\n",
"n",
".",
"v6only",
"=",
"l",
".",
"v6only",
"\n",
"n",
".",
"id",
"=",
"s",
".",
"id",
"\n",
"n",
".",
"boundNICID",
"=",
"s",
".",
"route",
".",
"NICID",
"(",
")",
"\n",
"n",
".",
"route",
"=",
"s",
".",
"route",
".",
"Clone",
"(",
")",
"\n",
"n",
".",
"effectiveNetProtos",
"=",
"[",
"]",
"tcpip",
".",
"NetworkProtocolNumber",
"{",
"s",
".",
"route",
".",
"NetProto",
"}",
"\n",
"n",
".",
"rcvBufSize",
"=",
"int",
"(",
"l",
".",
"rcvWnd",
")",
"\n\n",
"n",
".",
"maybeEnableTimestamp",
"(",
"rcvdSynOpts",
")",
"\n",
"n",
".",
"maybeEnableSACKPermitted",
"(",
"rcvdSynOpts",
")",
"\n\n",
"n",
".",
"initGSO",
"(",
")",
"\n\n",
"// 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",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"n",
".",
"isRegistered",
"=",
"true",
"\n",
"n",
".",
"state",
"=",
"stateConnected",
"\n\n",
"// 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",
"n",
".",
"rcv",
"=",
"newReceiver",
"(",
"n",
",",
"irs",
",",
"l",
".",
"rcvWnd",
",",
"0",
")",
"\n\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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.",
"irs",
":=",
"s",
".",
"sequenceNumber",
"\n",
"cookie",
":=",
"l",
".",
"createCookie",
"(",
"s",
".",
"id",
",",
"irs",
",",
"encodeMSS",
"(",
"opts",
".",
"MSS",
")",
")",
"\n",
"ep",
",",
"err",
":=",
"l",
".",
"createConnectedEndpoint",
"(",
"s",
",",
"cookie",
",",
"irs",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Perform the 3-way handshake.",
"h",
":=",
"newHandshake",
"(",
"ep",
",",
"l",
".",
"rcvWnd",
")",
"\n\n",
"h",
".",
"resetToSynRcvd",
"(",
"cookie",
",",
"irs",
",",
"opts",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"execute",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"ep",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n\n",
"return",
"ep",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
".",
"waiterQueue",
".",
"Notify",
"(",
"waiter",
".",
"EventIn",
")",
"\n",
"}",
"else",
"{",
"n",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"e",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"(",
")",
"\n\n",
"n",
",",
"err",
":=",
"ctx",
".",
"createEndpointAndPerformHandshake",
"(",
"s",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"e",
".",
"deliverAccepted",
"(",
"n",
")",
"\n",
"}"
] | // 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",
"for",
"acceptance",
".",
"A",
"limited",
"number",
"of",
"these",
"goroutines",
"are",
"allowed",
"before",
"TCP",
"starts",
"using",
"SYN",
"cookies",
"to",
"accept",
"connections",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcp/accept.go#L286-L296 | train |
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",
"(",
"s",
")",
"\n",
"if",
"incSynRcvdCount",
"(",
")",
"{",
"s",
".",
"incRef",
"(",
")",
"\n",
"go",
"e",
".",
"handleSynSegment",
"(",
"ctx",
",",
"s",
",",
"&",
"opts",
")",
"\n",
"}",
"else",
"{",
"cookie",
":=",
"ctx",
".",
"createCookie",
"(",
"s",
".",
"id",
",",
"s",
".",
"sequenceNumber",
",",
"encodeMSS",
"(",
"opts",
".",
"MSS",
")",
")",
"\n",
"// 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",
",",
"}",
"\n",
"sendSynTCP",
"(",
"&",
"s",
".",
"route",
",",
"s",
".",
"id",
",",
"header",
".",
"TCPFlagSyn",
"|",
"header",
".",
"TCPFlagAck",
",",
"cookie",
",",
"s",
".",
"sequenceNumber",
"+",
"1",
",",
"ctx",
".",
"rcvWnd",
",",
"synOpts",
")",
"\n",
"}",
"\n\n",
"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",
",",
"}",
"\n",
"// 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",
"\n",
"rcvdSynOptions",
".",
"TSVal",
"=",
"s",
".",
"parsedOptions",
".",
"TSVal",
"\n",
"rcvdSynOptions",
".",
"TSEcr",
"=",
"s",
".",
"parsedOptions",
".",
"TSEcr",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"ctx",
".",
"createConnectedEndpoint",
"(",
"s",
",",
"s",
".",
"ackNumber",
"-",
"1",
",",
"s",
".",
"sequenceNumber",
"-",
"1",
",",
"rcvdSynOptions",
")",
"\n",
"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",
"\n",
"e",
".",
"deliverAccepted",
"(",
"n",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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 attempting to queue new connections",
"// to the endpoint.",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
".",
"state",
"=",
"stateClosed",
"\n\n",
"// Do cleanup if needed.",
"e",
".",
"completeWorkerLocked",
"(",
")",
"\n\n",
"if",
"e",
".",
"drainDone",
"!=",
"nil",
"{",
"close",
"(",
"e",
".",
"drainDone",
")",
"\n",
"}",
"\n",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Notify waiters that the endpoint is shutdown.",
"e",
".",
"waiterQueue",
".",
"Notify",
"(",
"waiter",
".",
"EventIn",
"|",
"waiter",
".",
"EventOut",
")",
"\n",
"}",
"(",
")",
"\n\n",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"v6only",
":=",
"e",
".",
"v6only",
"\n",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"ctx",
":=",
"newListenContext",
"(",
"e",
".",
"stack",
",",
"rcvWnd",
",",
"v6only",
",",
"e",
".",
"netProto",
")",
"\n\n",
"s",
":=",
"sleep",
".",
"Sleeper",
"{",
"}",
"\n",
"s",
".",
"AddWaker",
"(",
"&",
"e",
".",
"notificationWaker",
",",
"wakerForNotification",
")",
"\n",
"s",
".",
"AddWaker",
"(",
"&",
"e",
".",
"newSegmentWaker",
",",
"wakerForNewSegment",
")",
"\n",
"for",
"{",
"switch",
"index",
",",
"_",
":=",
"s",
".",
"Fetch",
"(",
"true",
")",
";",
"index",
"{",
"case",
"wakerForNotification",
":",
"n",
":=",
"e",
".",
"fetchNotifications",
"(",
")",
"\n",
"if",
"n",
"&",
"notifyClose",
"!=",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"n",
"&",
"notifyDrain",
"!=",
"0",
"{",
"for",
"!",
"e",
".",
"segmentQueue",
".",
"empty",
"(",
")",
"{",
"s",
":=",
"e",
".",
"segmentQueue",
".",
"dequeue",
"(",
")",
"\n",
"e",
".",
"handleListenSegment",
"(",
"ctx",
",",
"s",
")",
"\n",
"s",
".",
"decRef",
"(",
")",
"\n",
"}",
"\n",
"synRcvdCount",
".",
"pending",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"e",
".",
"drainDone",
")",
"\n",
"<-",
"e",
".",
"undrain",
"\n",
"}",
"\n\n",
"case",
"wakerForNewSegment",
":",
"// Process at most maxSegmentsPerWake segments.",
"mayRequeue",
":=",
"true",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"maxSegmentsPerWake",
";",
"i",
"++",
"{",
"s",
":=",
"e",
".",
"segmentQueue",
".",
"dequeue",
"(",
")",
"\n",
"if",
"s",
"==",
"nil",
"{",
"mayRequeue",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n\n",
"e",
".",
"handleListenSegment",
"(",
"ctx",
",",
"s",
")",
"\n",
"s",
".",
"decRef",
"(",
")",
"\n",
"}",
"\n\n",
"// If the queue is not empty, make sure we'll wake up",
"// in the next iteration.",
"if",
"mayRequeue",
"&&",
"!",
"e",
".",
"segmentQueue",
".",
"empty",
"(",
")",
"{",
"e",
".",
"newSegmentWaker",
".",
"Assert",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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 | train |
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 | train |
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 | train |
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",
"(",
")",
"\n\n",
"list",
":=",
"n",
".",
"primary",
"[",
"protocol",
"]",
"\n",
"if",
"list",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"for",
"e",
":=",
"list",
".",
"Front",
"(",
")",
";",
"e",
"!=",
"nil",
";",
"e",
"=",
"e",
".",
"Next",
"(",
")",
"{",
"r",
":=",
"e",
".",
"(",
"*",
"referencedNetworkEndpoint",
")",
"\n",
"// TODO(crawshaw): allow broadcast address when SO_BROADCAST is set.",
"switch",
"r",
".",
"ep",
".",
"ID",
"(",
")",
".",
"LocalAddress",
"{",
"case",
"header",
".",
"IPv4Broadcast",
",",
"header",
".",
"IPv4Any",
":",
"continue",
"\n",
"}",
"\n",
"if",
"r",
".",
"tryIncRef",
"(",
")",
"{",
"return",
"r",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"{",
"address",
"}",
"\n\n",
"n",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"ref",
":=",
"n",
".",
"endpoints",
"[",
"id",
"]",
"\n",
"if",
"ref",
"!=",
"nil",
"&&",
"!",
"ref",
".",
"tryIncRef",
"(",
")",
"{",
"ref",
"=",
"nil",
"\n",
"}",
"\n",
"spoofing",
":=",
"n",
".",
"spoofing",
"\n",
"n",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"ref",
"!=",
"nil",
"||",
"!",
"spoofing",
"{",
"return",
"ref",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n",
"ref",
"=",
"n",
".",
"endpoints",
"[",
"id",
"]",
"\n",
"if",
"ref",
"==",
"nil",
"||",
"!",
"ref",
".",
"tryIncRef",
"(",
")",
"{",
"ref",
",",
"_",
"=",
"n",
".",
"addAddressLocked",
"(",
"protocol",
",",
"address",
",",
"peb",
",",
"true",
")",
"\n",
"if",
"ref",
"!=",
"nil",
"{",
"ref",
".",
"holdsInsertRef",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ref",
"\n",
"}"
] | // 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 | train |
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",
"(",
"[",
"]",
"tcpip",
".",
"ProtocolAddress",
",",
"0",
",",
"len",
"(",
"n",
".",
"endpoints",
")",
")",
"\n",
"for",
"nid",
",",
"ep",
":=",
"range",
"n",
".",
"endpoints",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"tcpip",
".",
"ProtocolAddress",
"{",
"Protocol",
":",
"ep",
".",
"protocol",
",",
"Address",
":",
"nid",
".",
"LocalAddress",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"addrs",
"\n",
"}"
] | // 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 | train |
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",
".",
"subnets",
",",
"subnet",
")",
"\n",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\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 | train |
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",
"_",
",",
"sub",
":=",
"range",
"n",
".",
"subnets",
"{",
"if",
"sub",
"!=",
"subnet",
"{",
"tmp",
"=",
"append",
"(",
"tmp",
",",
"sub",
")",
"\n",
"}",
"\n",
"}",
"\n",
"n",
".",
"subnets",
"=",
"tmp",
"\n\n",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\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 | train |
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",
".",
"Subnet",
",",
"0",
",",
"len",
"(",
"n",
".",
"subnets",
")",
"+",
"len",
"(",
"n",
".",
"endpoints",
")",
")",
"\n",
"for",
"nid",
":=",
"range",
"n",
".",
"endpoints",
"{",
"sn",
",",
"err",
":=",
"tcpip",
".",
"NewSubnet",
"(",
"nid",
".",
"LocalAddress",
",",
"tcpip",
".",
"AddressMask",
"(",
"strings",
".",
"Repeat",
"(",
"\"",
"\\xff",
"\"",
",",
"len",
"(",
"nid",
".",
"LocalAddress",
")",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// This should never happen as the mask has been carefully crafted to",
"// match the address.",
"panic",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"sns",
"=",
"append",
"(",
"sns",
",",
"sn",
")",
"\n",
"}",
"\n",
"return",
"append",
"(",
"sns",
",",
"n",
".",
"subnets",
"...",
")",
"\n",
"}"
] | // 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 | train |
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",
"}",
"]",
"\n",
"if",
"r",
"==",
"nil",
"||",
"!",
"r",
".",
"holdsInsertRef",
"{",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"tcpip",
".",
"ErrBadLocalAddress",
"\n",
"}",
"\n\n",
"r",
".",
"holdsInsertRef",
"=",
"false",
"\n",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"r",
".",
"decRef",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
":=",
"n",
".",
"stack",
".",
"transportProtocols",
"[",
"protocol",
"]",
"\n",
"if",
"!",
"ok",
"{",
"n",
".",
"stack",
".",
"stats",
".",
"UnknownProtocolRcvdPackets",
".",
"Increment",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"transProto",
":=",
"state",
".",
"proto",
"\n",
"if",
"len",
"(",
"vv",
".",
"First",
"(",
")",
")",
"<",
"transProto",
".",
"MinimumPacketSize",
"(",
")",
"{",
"n",
".",
"stack",
".",
"stats",
".",
"MalformedRcvdPackets",
".",
"Increment",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"srcPort",
",",
"dstPort",
",",
"err",
":=",
"transProto",
".",
"ParsePorts",
"(",
"vv",
".",
"First",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"n",
".",
"stack",
".",
"stats",
".",
"MalformedRcvdPackets",
".",
"Increment",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"id",
":=",
"TransportEndpointID",
"{",
"dstPort",
",",
"r",
".",
"LocalAddress",
",",
"srcPort",
",",
"r",
".",
"RemoteAddress",
"}",
"\n",
"if",
"n",
".",
"demux",
".",
"deliverPacket",
"(",
"r",
",",
"protocol",
",",
"netHeader",
",",
"vv",
",",
"id",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"n",
".",
"stack",
".",
"demux",
".",
"deliverPacket",
"(",
"r",
",",
"protocol",
",",
"netHeader",
",",
"vv",
",",
"id",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// Try to deliver to per-stack default handler.",
"if",
"state",
".",
"defaultHandler",
"!=",
"nil",
"{",
"if",
"state",
".",
"defaultHandler",
"(",
"r",
",",
"id",
",",
"netHeader",
",",
"vv",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
",",
"extra",
"uint32",
",",
"vv",
"buffer",
".",
"VectorisedView",
")",
"{",
"state",
",",
"ok",
":=",
"n",
".",
"stack",
".",
"transportProtocols",
"[",
"trans",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"transProto",
":=",
"state",
".",
"proto",
"\n\n",
"// 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",
"\n",
"}",
"\n\n",
"srcPort",
",",
"dstPort",
",",
"err",
":=",
"transProto",
".",
"ParsePorts",
"(",
"vv",
".",
"First",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"id",
":=",
"TransportEndpointID",
"{",
"srcPort",
",",
"local",
",",
"dstPort",
",",
"remote",
"}",
"\n",
"if",
"n",
".",
"demux",
".",
"deliverControlPacket",
"(",
"net",
",",
"trans",
",",
"typ",
",",
"extra",
",",
"vv",
",",
"id",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"n",
".",
"stack",
".",
"demux",
".",
"deliverControlPacket",
"(",
"net",
",",
"trans",
",",
"typ",
",",
"extra",
",",
"vv",
",",
"id",
")",
"{",
"return",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
"}",
"\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 | train |
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",
"if",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"r",
".",
"refs",
",",
"v",
",",
"v",
"+",
"1",
")",
"{",
"return",
"true",
"\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",
"alive",
"and",
"do",
"nothing",
"if",
"it",
"has",
"already",
"been",
"clean",
"up",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/stack/nic.go#L657-L668 | train |
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",
".",
"SourcePort",
"(",
")",
",",
"h",
".",
"DestinationPort",
"(",
")",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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 | train |
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",
"}",
"\n",
"if",
"!",
"reuse",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"b",
"{",
"if",
"!",
"n",
".",
"reuse",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"// If all addresses for this portDescriptor are already bound, no",
"// address is available.",
"if",
"n",
",",
"ok",
":=",
"b",
"[",
"anyIPAddress",
"]",
";",
"ok",
"{",
"if",
"!",
"reuse",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"n",
".",
"reuse",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"n",
",",
"ok",
":=",
"b",
"[",
"addr",
"]",
";",
"ok",
"{",
"if",
"!",
"reuse",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"n",
".",
"reuse",
"\n",
"}",
"\n",
"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 | train |
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",
")",
"{",
"count",
":=",
"uint16",
"(",
"math",
".",
"MaxUint16",
"-",
"FirstEphemeral",
"+",
"1",
")",
"\n",
"offset",
":=",
"uint16",
"(",
"rand",
".",
"Int31n",
"(",
"int32",
"(",
"count",
")",
")",
")",
"\n\n",
"for",
"i",
":=",
"uint16",
"(",
"0",
")",
";",
"i",
"<",
"count",
";",
"i",
"++",
"{",
"port",
"=",
"FirstEphemeral",
"+",
"(",
"offset",
"+",
"i",
")",
"%",
"count",
"\n",
"ok",
",",
"err",
":=",
"testPort",
"(",
"port",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"ok",
"{",
"return",
"port",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"0",
",",
"tcpip",
".",
"ErrNoPortAvailable",
"\n",
"}"
] | // 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",
"stopping",
"when",
"a",
"port",
"is",
"found",
"or",
"an",
"error",
"occurs",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/ports/ports.go#L99-L116 | train |
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",
"bool",
")",
"bool",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
".",
"isPortAvailableLocked",
"(",
"networks",
",",
"transport",
",",
"addr",
",",
"port",
",",
"reuse",
")",
"\n",
"}"
] | // 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 | train |
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",
",",
"reuse",
"bool",
")",
"bool",
"{",
"if",
"!",
"s",
".",
"isPortAvailableLocked",
"(",
"networks",
",",
"transport",
",",
"addr",
",",
"port",
",",
"reuse",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Reserve port on all network protocols.",
"for",
"_",
",",
"network",
":=",
"range",
"networks",
"{",
"desc",
":=",
"portDescriptor",
"{",
"network",
",",
"transport",
",",
"port",
"}",
"\n",
"m",
",",
"ok",
":=",
"s",
".",
"allocatedPorts",
"[",
"desc",
"]",
"\n",
"if",
"!",
"ok",
"{",
"m",
"=",
"make",
"(",
"bindAddresses",
")",
"\n",
"s",
".",
"allocatedPorts",
"[",
"desc",
"]",
"=",
"m",
"\n",
"}",
"\n",
"if",
"n",
",",
"ok",
":=",
"m",
"[",
"addr",
"]",
";",
"ok",
"{",
"n",
".",
"refs",
"++",
"\n",
"m",
"[",
"addr",
"]",
"=",
"n",
"\n",
"}",
"else",
"{",
"m",
"[",
"addr",
"]",
"=",
"portNode",
"{",
"reuse",
":",
"reuse",
",",
"refs",
":",
"1",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | // 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 | train |
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 acquired in beforeSave() so regular endpoint closing",
"// logic can proceed after save.",
"ep",
".",
"rcvMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"max",
"\n",
"}"
] | // 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 | train |
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",
"ep",
".",
"connected",
"{",
"var",
"err",
"*",
"tcpip",
".",
"Error",
"\n",
"ep",
".",
"route",
",",
"err",
"=",
"ep",
".",
"stack",
".",
"FindRoute",
"(",
"ep",
".",
"registeredNIC",
",",
"ep",
".",
"boundAddr",
",",
"ep",
".",
"route",
".",
"RemoteAddress",
",",
"ep",
".",
"netProto",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"*",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"ep",
".",
"stack",
".",
"RegisterRawTransportEndpoint",
"(",
"ep",
".",
"registeredNIC",
",",
"ep",
".",
"netProto",
",",
"ep",
".",
"transProto",
",",
"ep",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"*",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
".",
"Value",
"(",
"initialSyn",
".",
"SequenceNumber",
"(",
")",
")",
"\n",
"t",
".",
"outbound",
".",
"una",
"=",
"iss",
"\n",
"t",
".",
"outbound",
".",
"nxt",
"=",
"iss",
".",
"Add",
"(",
"logicalLen",
"(",
"initialSyn",
")",
")",
"\n",
"t",
".",
"outbound",
".",
"end",
"=",
"t",
".",
"outbound",
".",
"nxt",
"\n\n",
"// 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",
"\n",
"t",
".",
"inbound",
".",
"nxt",
"=",
"0",
"\n",
"t",
".",
"inbound",
".",
"end",
"=",
"seqnum",
".",
"Value",
"(",
"initialSyn",
".",
"WindowSize",
"(",
")",
")",
"\n",
"t",
".",
"state",
"=",
"ResultConnecting",
"\n",
"return",
"t",
".",
"state",
"\n",
"}"
] | // 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 | train |
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",
"=",
"st",
"\n",
"}",
"\n",
"return",
"st",
"\n",
"}"
] | // 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 | train |
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",
"=",
"st",
"\n",
"}",
"\n",
"return",
"st",
"\n",
"}"
] | // 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 | train |
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",
".",
"closed",
"(",
")",
"{",
"return",
"r",
"\n",
"}",
"\n\n",
"// Find out which was closed first.",
"if",
"t",
".",
"firstFin",
"==",
"&",
"t",
".",
"outbound",
"{",
"return",
"ResultClosedBySelf",
"\n",
"}",
"\n\n",
"return",
"ResultClosedByPeer",
"\n",
"}"
] | // 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",
"returned",
"unmodified",
".",
"Otherwise",
"it",
"s",
"converted",
"to",
"either",
"ClosedBySelf",
"or",
"ClosedByPeer",
"depending",
"on",
"which",
"stream",
"was",
"closed",
"first",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L129-L141 | train |
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",
":=",
"seqnum",
".",
"Value",
"(",
"tcp",
".",
"AckNumber",
"(",
")",
")",
"\n\n",
"// Ignore segment if ack is present but not acceptable.",
"if",
"ackPresent",
"&&",
"!",
"(",
"ack",
"-",
"1",
")",
".",
"InRange",
"(",
"t",
".",
"outbound",
".",
"una",
",",
"t",
".",
"outbound",
".",
"nxt",
")",
"{",
"return",
"ResultConnecting",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"return",
"ResultReset",
"\n",
"}",
"\n",
"return",
"ResultConnecting",
"\n",
"}",
"\n\n",
"// Ignore segment if SYN is not set.",
"if",
"flags",
"&",
"header",
".",
"TCPFlagSyn",
"==",
"0",
"{",
"return",
"ResultConnecting",
"\n",
"}",
"\n\n",
"// Update state informed by this SYN.",
"irs",
":=",
"seqnum",
".",
"Value",
"(",
"tcp",
".",
"SequenceNumber",
"(",
")",
")",
"\n",
"t",
".",
"inbound",
".",
"una",
"=",
"irs",
"\n",
"t",
".",
"inbound",
".",
"nxt",
"=",
"irs",
".",
"Add",
"(",
"logicalLen",
"(",
"tcp",
")",
")",
"\n",
"t",
".",
"inbound",
".",
"end",
"+=",
"irs",
"\n\n",
"t",
".",
"outbound",
".",
"end",
"=",
"t",
".",
"outbound",
".",
"una",
".",
"Add",
"(",
"seqnum",
".",
"Size",
"(",
"tcp",
".",
"WindowSize",
"(",
")",
")",
")",
"\n\n",
"// 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",
"\n",
"}",
"\n\n",
"if",
"end",
":=",
"ack",
".",
"Add",
"(",
"seqnum",
".",
"Size",
"(",
"tcp",
".",
"WindowSize",
"(",
")",
")",
")",
";",
"t",
".",
"outbound",
".",
"end",
".",
"LessThan",
"(",
"end",
")",
"{",
"t",
".",
"outbound",
".",
"end",
"=",
"end",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Update handlers so that new calls will be handled by new state.",
"t",
".",
"handlerInbound",
"=",
"allOtherInbound",
"\n",
"t",
".",
"handlerOutbound",
"=",
"allOtherOutbound",
"\n\n",
"return",
"ResultAlive",
"\n",
"}"
] | // 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 | train |
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",
".",
"SequenceNumber",
"(",
")",
"!=",
"uint32",
"(",
"t",
".",
"outbound",
".",
"una",
")",
"{",
"return",
"ResultDrop",
"\n",
"}",
"\n\n",
"// 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",
"\n",
"}",
"\n\n",
"return",
"ResultConnecting",
"\n",
"}"
] | // 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 | train |
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",
".",
"firstFin",
")",
")",
"\n",
"}"
] | // 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 | train |
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",
"{",
"return",
"segLen",
"==",
"0",
"&&",
"segSeq",
"==",
"s",
".",
"una",
"\n",
"}",
"\n\n",
"// Make sure [segSeq, seqSeq+segLen) is non-empty.",
"if",
"segLen",
"==",
"0",
"{",
"segLen",
"=",
"1",
"\n",
"}",
"\n\n",
"return",
"seqnum",
".",
"Overlap",
"(",
"s",
".",
"una",
",",
"wnd",
",",
"segSeq",
",",
"segLen",
")",
"\n",
"}"
] | // 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",
"the",
"window",
"is",
"zero",
"if",
"it",
"s",
"a",
"packet",
"with",
"no",
"payload",
"and",
"sequence",
"number",
"equal",
"to",
"una",
"."
] | 70ebca9c30730cf3887cdef3b85bb96ed7a97593 | https://github.com/google/netstack/blob/70ebca9c30730cf3887cdef3b85bb96ed7a97593/tcpip/transport/tcpconntrack/tcp_conntrack.go#L313-L325 | train |
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 | train |
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 | train |
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",
"{",
"l",
"++",
"\n",
"}",
"\n",
"if",
"flags",
"&",
"header",
".",
"TCPFlagFin",
"!=",
"0",
"{",
"l",
"++",
"\n",
"}",
"\n",
"return",
"l",
"\n",
"}"
] | // 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 | train |
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 | train |
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 | train |
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",
"[",
":",
"n",
"-",
"1",
"]",
"\n",
"return",
"x",
"\n",
"}"
] | // 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 | train |
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",
")",
",",
"maxSACKED",
":",
"iss",
",",
"}",
"\n",
"}"
] | // 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 | train |
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 | train |
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",
")",
"bool",
"{",
"sacked",
":=",
"i",
".",
"(",
"header",
".",
"SACKBlock",
")",
"\n",
"if",
"sacked",
".",
"End",
".",
"LessThan",
"(",
"r",
".",
"Start",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"sacked",
".",
"Contains",
"(",
"r",
")",
"{",
"found",
"=",
"true",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"return",
"found",
"\n",
"}"
] | // 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 | train |
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",
".",
"Item",
")",
"bool",
"{",
"str",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
")",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"str",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"str",
".",
"String",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
":=",
"[",
"]",
"btree",
".",
"Item",
"{",
"}",
"\n",
"r",
":=",
"header",
".",
"SACKBlock",
"{",
"seq",
",",
"seq",
".",
"Add",
"(",
"1",
")",
"}",
"\n",
"s",
".",
"ranges",
".",
"DescendLessOrEqual",
"(",
"r",
",",
"func",
"(",
"i",
"btree",
".",
"Item",
")",
"bool",
"{",
"if",
"i",
"==",
"r",
"{",
"return",
"true",
"\n",
"}",
"\n",
"sb",
":=",
"i",
".",
"(",
"header",
".",
"SACKBlock",
")",
"\n",
"toDelete",
"=",
"append",
"(",
"toDelete",
",",
"i",
")",
"\n",
"if",
"sb",
".",
"End",
".",
"LessThanEq",
"(",
"seq",
")",
"{",
"s",
".",
"sacked",
"-=",
"sb",
".",
"Start",
".",
"Size",
"(",
"sb",
".",
"End",
")",
"\n",
"}",
"else",
"{",
"newSB",
":=",
"header",
".",
"SACKBlock",
"{",
"seq",
",",
"sb",
".",
"End",
"}",
"\n",
"toInsert",
"=",
"append",
"(",
"toInsert",
",",
"newSB",
")",
"\n",
"s",
".",
"sacked",
"-=",
"sb",
".",
"Start",
".",
"Size",
"(",
"seq",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"for",
"_",
",",
"sb",
":=",
"range",
"toDelete",
"{",
"s",
".",
"ranges",
".",
"Delete",
"(",
"sb",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"sb",
":=",
"range",
"toInsert",
"{",
"s",
".",
"ranges",
".",
"ReplaceOrInsert",
"(",
"sb",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
".",
"Item",
")",
"bool",
"{",
"sackBlocks",
"=",
"append",
"(",
"sackBlocks",
",",
"i",
".",
"(",
"header",
".",
"SACKBlock",
")",
")",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"return",
"sackBlocks",
",",
"s",
".",
"maxSACKED",
"\n",
"}"
] | // 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 | train |
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",
")",
"\n",
"q",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // 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 | train |
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 | train |
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",
".",
"Next",
"(",
")",
"{",
"if",
"mask",
"&",
"e",
".",
"mask",
"!=",
"0",
"{",
"e",
".",
"Callback",
".",
"Callback",
"(",
"e",
")",
"\n",
"}",
"\n",
"}",
"\n",
"q",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] | // 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 | train |
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",
"!=",
"nil",
";",
"e",
"=",
"e",
".",
"Next",
"(",
")",
"{",
"ret",
"|=",
"e",
".",
"mask",
"\n",
"}",
"\n",
"q",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"ret",
"\n",
"}"
] | // 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 | train |
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",
"\n",
"}"
] | // 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 | train |
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",
"|",
"i",
".",
"Type",
"<<",
"6",
"|",
"(",
"i",
".",
"HeaderLength",
"-",
"4",
")",
"/",
"4",
"\n",
"b",
"[",
"encapProto",
"]",
"=",
"i",
".",
"Protocol",
"\n",
"}"
] | // 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 | train |
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",
",",
"_",
"=",
"pem",
".",
"Decode",
"(",
"key",
")",
";",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrKeyMustBePEMEncoded",
"\n",
"}",
"\n\n",
"var",
"parsedKey",
"interface",
"{",
"}",
"\n",
"if",
"parsedKey",
",",
"err",
"=",
"x509",
".",
"ParsePKCS1PrivateKey",
"(",
"block",
".",
"Bytes",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"parsedKey",
",",
"err",
"=",
"x509",
".",
"ParsePKCS8PrivateKey",
"(",
"block",
".",
"Bytes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"pkey",
"*",
"rsa",
".",
"PrivateKey",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"pkey",
",",
"ok",
"=",
"parsedKey",
".",
"(",
"*",
"rsa",
".",
"PrivateKey",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrNotRSAPrivateKey",
"\n",
"}",
"\n\n",
"return",
"pkey",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
".",
"Block",
"\n",
"if",
"block",
",",
"_",
"=",
"pem",
".",
"Decode",
"(",
"key",
")",
";",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrKeyMustBePEMEncoded",
"\n",
"}",
"\n\n",
"var",
"parsedKey",
"interface",
"{",
"}",
"\n\n",
"var",
"blockDecrypted",
"[",
"]",
"byte",
"\n",
"if",
"blockDecrypted",
",",
"err",
"=",
"x509",
".",
"DecryptPEMBlock",
"(",
"block",
",",
"[",
"]",
"byte",
"(",
"password",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"parsedKey",
",",
"err",
"=",
"x509",
".",
"ParsePKCS1PrivateKey",
"(",
"blockDecrypted",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"parsedKey",
",",
"err",
"=",
"x509",
".",
"ParsePKCS8PrivateKey",
"(",
"blockDecrypted",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"pkey",
"*",
"rsa",
".",
"PrivateKey",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"pkey",
",",
"ok",
"=",
"parsedKey",
".",
"(",
"*",
"rsa",
".",
"PrivateKey",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrNotRSAPrivateKey",
"\n",
"}",
"\n\n",
"return",
"pkey",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
",",
"_",
"=",
"pem",
".",
"Decode",
"(",
"key",
")",
";",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrKeyMustBePEMEncoded",
"\n",
"}",
"\n\n",
"// Parse the key",
"var",
"parsedKey",
"interface",
"{",
"}",
"\n",
"if",
"parsedKey",
",",
"err",
"=",
"x509",
".",
"ParsePKIXPublicKey",
"(",
"block",
".",
"Bytes",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"block",
".",
"Bytes",
")",
";",
"err",
"==",
"nil",
"{",
"parsedKey",
"=",
"cert",
".",
"PublicKey",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"pkey",
"*",
"rsa",
".",
"PublicKey",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"pkey",
",",
"ok",
"=",
"parsedKey",
".",
"(",
"*",
"rsa",
".",
"PublicKey",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrNotRSAPublicKey",
"\n",
"}",
"\n\n",
"return",
"pkey",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"\n",
"if",
"sig",
",",
"err",
"=",
"DecodeSegment",
"(",
"signature",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get the key",
"var",
"ecdsaKey",
"*",
"ecdsa",
".",
"PublicKey",
"\n",
"switch",
"k",
":=",
"key",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ecdsa",
".",
"PublicKey",
":",
"ecdsaKey",
"=",
"k",
"\n",
"default",
":",
"return",
"ErrInvalidKeyType",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"sig",
")",
"!=",
"2",
"*",
"m",
".",
"KeySize",
"{",
"return",
"ErrECDSAVerification",
"\n",
"}",
"\n\n",
"r",
":=",
"big",
".",
"NewInt",
"(",
"0",
")",
".",
"SetBytes",
"(",
"sig",
"[",
":",
"m",
".",
"KeySize",
"]",
")",
"\n",
"s",
":=",
"big",
".",
"NewInt",
"(",
"0",
")",
".",
"SetBytes",
"(",
"sig",
"[",
"m",
".",
"KeySize",
":",
"]",
")",
"\n\n",
"// Create hasher",
"if",
"!",
"m",
".",
"Hash",
".",
"Available",
"(",
")",
"{",
"return",
"ErrHashUnavailable",
"\n",
"}",
"\n",
"hasher",
":=",
"m",
".",
"Hash",
".",
"New",
"(",
")",
"\n",
"hasher",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"signingString",
")",
")",
"\n\n",
"// Verify the signature",
"if",
"verifystatus",
":=",
"ecdsa",
".",
"Verify",
"(",
"ecdsaKey",
",",
"hasher",
".",
"Sum",
"(",
"nil",
")",
",",
"r",
",",
"s",
")",
";",
"verifystatus",
"==",
"true",
"{",
"return",
"nil",
"\n",
"}",
"else",
"{",
"return",
"ErrECDSAVerification",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
"k",
":=",
"key",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ecdsa",
".",
"PrivateKey",
":",
"ecdsaKey",
"=",
"k",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"ErrInvalidKeyType",
"\n",
"}",
"\n\n",
"// Create the hasher",
"if",
"!",
"m",
".",
"Hash",
".",
"Available",
"(",
")",
"{",
"return",
"\"",
"\"",
",",
"ErrHashUnavailable",
"\n",
"}",
"\n\n",
"hasher",
":=",
"m",
".",
"Hash",
".",
"New",
"(",
")",
"\n",
"hasher",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"signingString",
")",
")",
"\n\n",
"// 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",
"\n\n",
"if",
"m",
".",
"CurveBits",
"!=",
"curveBits",
"{",
"return",
"\"",
"\"",
",",
"ErrInvalidKey",
"\n",
"}",
"\n\n",
"keyBytes",
":=",
"curveBits",
"/",
"8",
"\n",
"if",
"curveBits",
"%",
"8",
">",
"0",
"{",
"keyBytes",
"+=",
"1",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n",
"rBytesPadded",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"keyBytes",
")",
"\n",
"copy",
"(",
"rBytesPadded",
"[",
"keyBytes",
"-",
"len",
"(",
"rBytes",
")",
":",
"]",
",",
"rBytes",
")",
"\n\n",
"sBytes",
":=",
"s",
".",
"Bytes",
"(",
")",
"\n",
"sBytesPadded",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"keyBytes",
")",
"\n",
"copy",
"(",
"sBytesPadded",
"[",
"keyBytes",
"-",
"len",
"(",
"sBytes",
")",
":",
"]",
",",
"sBytes",
")",
"\n\n",
"out",
":=",
"append",
"(",
"rBytesPadded",
",",
"sBytesPadded",
"...",
")",
"\n\n",
"return",
"EncodeSegment",
"(",
"out",
")",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
"*",
"flagShow",
"!=",
"\"",
"\"",
"{",
"return",
"showToken",
"(",
")",
"\n",
"}",
"else",
"{",
"flag",
".",
"Usage",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
"}",
"\n\n",
"// trim possible whitespace from token",
"tokData",
"=",
"regexp",
".",
"MustCompile",
"(",
"`\\s*$`",
")",
".",
"ReplaceAll",
"(",
"tokData",
",",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"if",
"*",
"flagDebug",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"len",
"(",
"tokData",
")",
")",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"isEs",
"(",
")",
"{",
"return",
"jwt",
".",
"ParseECPublicKeyFromPEM",
"(",
"data",
")",
"\n",
"}",
"else",
"if",
"isRs",
"(",
")",
"{",
"return",
"jwt",
".",
"ParseRSAPublicKeyFromPEM",
"(",
"data",
")",
"\n",
"}",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}",
")",
"\n\n",
"// Print some debug data",
"if",
"*",
"flagDebug",
"&&",
"token",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"token",
".",
"Header",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"token",
".",
"Claims",
")",
"\n",
"}",
"\n\n",
"// Print an error if we can't parse for some reason",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Is token invalid?",
"if",
"!",
"token",
".",
"Valid",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Print the token details",
"if",
"err",
":=",
"printJSON",
"(",
"token",
".",
"Claims",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\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 | train |
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",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"if",
"*",
"flagDebug",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"len",
"(",
"tokData",
")",
")",
"\n",
"}",
"\n\n",
"// parse the JSON of the claims",
"var",
"claims",
"jwt",
".",
"MapClaims",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"tokData",
",",
"&",
"claims",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// add command line claims",
"if",
"len",
"(",
"flagClaims",
")",
">",
"0",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"flagClaims",
"{",
"claims",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n\n",
"// get the key",
"var",
"key",
"interface",
"{",
"}",
"\n",
"key",
",",
"err",
"=",
"loadData",
"(",
"*",
"flagKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// get the signing alg",
"alg",
":=",
"jwt",
".",
"GetSigningMethod",
"(",
"*",
"flagAlg",
")",
"\n",
"if",
"alg",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"flagAlg",
")",
"\n",
"}",
"\n\n",
"// create a new token",
"token",
":=",
"jwt",
".",
"NewWithClaims",
"(",
"alg",
",",
"claims",
")",
"\n\n",
"// add command line headers",
"if",
"len",
"(",
"flagHead",
")",
">",
"0",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"flagHead",
"{",
"token",
".",
"Header",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"isEs",
"(",
")",
"{",
"if",
"k",
",",
"ok",
":=",
"key",
".",
"(",
"[",
"]",
"byte",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"key",
",",
"err",
"=",
"jwt",
".",
"ParseECPrivateKeyFromPEM",
"(",
"k",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"isRs",
"(",
")",
"{",
"if",
"k",
",",
"ok",
":=",
"key",
".",
"(",
"[",
"]",
"byte",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"key",
",",
"err",
"=",
"jwt",
".",
"ParseRSAPrivateKeyFromPEM",
"(",
"k",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"out",
",",
"err",
":=",
"token",
".",
"SignedString",
"(",
"key",
")",
";",
"err",
"==",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"out",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"}",
"\n\n",
"// trim possible whitespace from token",
"tokData",
"=",
"regexp",
".",
"MustCompile",
"(",
"`\\s*$`",
")",
".",
"ReplaceAll",
"(",
"tokData",
",",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"if",
"*",
"flagDebug",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"len",
"(",
"tokData",
")",
")",
"\n",
"}",
"\n\n",
"token",
",",
"err",
":=",
"jwt",
".",
"Parse",
"(",
"string",
"(",
"tokData",
")",
",",
"nil",
")",
"\n",
"if",
"token",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Print the token details",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"printJSON",
"(",
"token",
".",
"Header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"printJSON",
"(",
"token",
".",
"Claims",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\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 | train |
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",
"]",
")",
"==",
"\"",
"\"",
"{",
"return",
"tok",
"[",
"7",
":",
"]",
",",
"nil",
"\n",
"}",
"\n",
"return",
"tok",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
".",
"SigningString",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"sig",
",",
"err",
"=",
"t",
".",
"Method",
".",
"Sign",
"(",
"sstr",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"sstr",
",",
"sig",
"}",
",",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // Get the complete, signed token | [
"Get",
"the",
"complete",
"signed",
"token"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/token.go#L49-L59 | train |
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",
"{",
"var",
"jsonValue",
"[",
"]",
"byte",
"\n",
"if",
"i",
"==",
"0",
"{",
"if",
"jsonValue",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"t",
".",
"Header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"jsonValue",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"t",
".",
"Claims",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"parts",
"[",
"i",
"]",
"=",
"EncodeSegment",
"(",
"jsonValue",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"parts",
",",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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 | train |
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",
"-",
"l",
")",
"\n",
"}",
"\n\n",
"return",
"base64",
".",
"URLEncoding",
".",
"DecodeString",
"(",
"seg",
")",
"\n",
"}"
] | // 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 | train |
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 | train |
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",
"!=",
"\"",
"\"",
"{",
"return",
"e",
".",
"text",
"\n",
"}",
"else",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
":=",
"signingMethods",
"[",
"alg",
"]",
";",
"ok",
"{",
"method",
"=",
"methodF",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // 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 | train |
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",
"\n",
"if",
"sig",
",",
"err",
"=",
"DecodeSegment",
"(",
"signature",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"rsaKey",
"*",
"rsa",
".",
"PublicKey",
"\n",
"switch",
"k",
":=",
"key",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PublicKey",
":",
"rsaKey",
"=",
"k",
"\n",
"default",
":",
"return",
"ErrInvalidKey",
"\n",
"}",
"\n\n",
"// Create hasher",
"if",
"!",
"m",
".",
"Hash",
".",
"Available",
"(",
")",
"{",
"return",
"ErrHashUnavailable",
"\n",
"}",
"\n",
"hasher",
":=",
"m",
".",
"Hash",
".",
"New",
"(",
")",
"\n",
"hasher",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"signingString",
")",
")",
"\n\n",
"return",
"rsa",
".",
"VerifyPSS",
"(",
"rsaKey",
",",
"m",
".",
"Hash",
",",
"hasher",
".",
"Sum",
"(",
"nil",
")",
",",
"sig",
",",
"m",
".",
"Options",
")",
"\n",
"}"
] | // 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 | train |
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",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PrivateKey",
":",
"rsaKey",
"=",
"k",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"ErrInvalidKeyType",
"\n",
"}",
"\n\n",
"// Create the hasher",
"if",
"!",
"m",
".",
"Hash",
".",
"Available",
"(",
")",
"{",
"return",
"\"",
"\"",
",",
"ErrHashUnavailable",
"\n",
"}",
"\n\n",
"hasher",
":=",
"m",
".",
"Hash",
".",
"New",
"(",
")",
"\n",
"hasher",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"signingString",
")",
")",
"\n\n",
"// 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",
"\n",
"}",
"else",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
",",
"_",
"=",
"pem",
".",
"Decode",
"(",
"key",
")",
";",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrKeyMustBePEMEncoded",
"\n",
"}",
"\n\n",
"// Parse the key",
"var",
"parsedKey",
"interface",
"{",
"}",
"\n",
"if",
"parsedKey",
",",
"err",
"=",
"x509",
".",
"ParseECPrivateKey",
"(",
"block",
".",
"Bytes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"pkey",
"*",
"ecdsa",
".",
"PrivateKey",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"pkey",
",",
"ok",
"=",
"parsedKey",
".",
"(",
"*",
"ecdsa",
".",
"PrivateKey",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrNotECPrivateKey",
"\n",
"}",
"\n\n",
"return",
"pkey",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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 'none' signing method",
"if",
"_",
",",
"ok",
":=",
"key",
".",
"(",
"unsafeNoneMagicConstant",
")",
";",
"!",
"ok",
"{",
"return",
"NoneSignatureTypeDisallowedError",
"\n",
"}",
"\n",
"// If signing method is none, signature must be an empty string",
"if",
"signature",
"!=",
"\"",
"\"",
"{",
"return",
"NewValidationError",
"(",
"\"",
"\"",
",",
"ValidationErrorSignatureInvalid",
",",
")",
"\n",
"}",
"\n\n",
"// Accept 'none' signing method.",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
")",
";",
"ok",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"NoneSignatureTypeDisallowedError",
"\n",
"}"
] | // 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 | train |
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",
")",
"{",
"// Create basic parser struct",
"p",
":=",
"&",
"fromRequestParser",
"{",
"req",
",",
"extractor",
",",
"nil",
",",
"nil",
"}",
"\n\n",
"// Handle options",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"p",
")",
"\n",
"}",
"\n\n",
"// Set defaults",
"if",
"p",
".",
"claims",
"==",
"nil",
"{",
"p",
".",
"claims",
"=",
"jwt",
".",
"MapClaims",
"{",
"}",
"\n",
"}",
"\n",
"if",
"p",
".",
"parser",
"==",
"nil",
"{",
"p",
".",
"parser",
"=",
"&",
"jwt",
".",
"Parser",
"{",
"}",
"\n",
"}",
"\n\n",
"// perform extract",
"tokenString",
",",
"err",
":=",
"p",
".",
"extractor",
".",
"ExtractToken",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// perform parse",
"return",
"p",
".",
"parser",
".",
"ParseWithClaims",
"(",
"tokenString",
",",
"p",
".",
"claims",
",",
"keyFunc",
")",
"\n",
"}"
] | // 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",
"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"
] | 3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8 | https://github.com/dgrijalva/jwt-go/blob/3af4c746e1c248ee8491a3e0c6f7a9cd831e95f8/request/request.go#L14-L39 | train |
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 | train |
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 | train |
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",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrInvalidKeyType",
"\n",
"}",
"\n\n",
"// Decode signature, for comparison",
"sig",
",",
"err",
":=",
"DecodeSegment",
"(",
"signature",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Can we use the specified hashing method?",
"if",
"!",
"m",
".",
"Hash",
".",
"Available",
"(",
")",
"{",
"return",
"ErrHashUnavailable",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"hasher",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"signingString",
")",
")",
"\n",
"if",
"!",
"hmac",
".",
"Equal",
"(",
"sig",
",",
"hasher",
".",
"Sum",
"(",
"nil",
")",
")",
"{",
"return",
"ErrSignatureInvalid",
"\n",
"}",
"\n\n",
"// No validation errors. Signature is good.",
"return",
"nil",
"\n",
"}"
] | // 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 | train |
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",
"\n",
"}",
"\n",
"if",
"pipe",
".",
"IsSkip",
"(",
"err",
")",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // 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 | train |
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",
",",
"err",
":=",
"git",
".",
"Run",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"extractRepoFromURL",
"(",
"out",
")",
",",
"nil",
"\n",
"}"
] | // 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 | train |
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",
".",
"Extra",
"[",
"key",
"]",
"\n",
"}"
] | // 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 | train |
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",
"artifacts",
".",
"items",
"{",
"plat",
":=",
"a",
".",
"Goos",
"+",
"a",
".",
"Goarch",
"+",
"a",
".",
"Goarm",
"\n",
"result",
"[",
"plat",
"]",
"=",
"append",
"(",
"result",
"[",
"plat",
"]",
",",
"a",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // 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 | train |
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",
".",
"Fields",
"{",
"\"",
"\"",
":",
"a",
".",
"Name",
",",
"\"",
"\"",
":",
"a",
".",
"Path",
",",
"\"",
"\"",
":",
"a",
".",
"Type",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"artifacts",
".",
"items",
"=",
"append",
"(",
"artifacts",
".",
"items",
",",
"a",
")",
"\n",
"}"
] | // 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 | train |
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 | train |
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 | train |
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 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.