id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
149,400 | vulcand/oxy | utils/netutils.go | CopyURL | func CopyURL(i *url.URL) *url.URL {
out := *i
if i.User != nil {
out.User = &(*i.User)
}
return &out
} | go | func CopyURL(i *url.URL) *url.URL {
out := *i
if i.User != nil {
out.User = &(*i.User)
}
return &out
} | [
"func",
"CopyURL",
"(",
"i",
"*",
"url",
".",
"URL",
")",
"*",
"url",
".",
"URL",
"{",
"out",
":=",
"*",
"i",
"\n",
"if",
"i",
".",
"User",
"!=",
"nil",
"{",
"out",
".",
"User",
"=",
"&",
"(",
"*",
"i",
".",
"User",
")",
"\n",
"}",
"\n",
"return",
"&",
"out",
"\n",
"}"
] | // CopyURL provides update safe copy by avoiding shallow copying User field | [
"CopyURL",
"provides",
"update",
"safe",
"copy",
"by",
"avoiding",
"shallow",
"copying",
"User",
"field"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L160-L166 |
149,401 | vulcand/oxy | utils/netutils.go | CopyHeaders | func CopyHeaders(dst http.Header, src http.Header) {
for k, vv := range src {
dst[k] = append(dst[k], vv...)
}
} | go | func CopyHeaders(dst http.Header, src http.Header) {
for k, vv := range src {
dst[k] = append(dst[k], vv...)
}
} | [
"func",
"CopyHeaders",
"(",
"dst",
"http",
".",
"Header",
",",
"src",
"http",
".",
"Header",
")",
"{",
"for",
"k",
",",
"vv",
":=",
"range",
"src",
"{",
"dst",
"[",
"k",
"]",
"=",
"append",
"(",
"dst",
"[",
"k",
"]",
",",
"vv",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // CopyHeaders copies http headers from source to destination, it
// does not overide, but adds multiple headers | [
"CopyHeaders",
"copies",
"http",
"headers",
"from",
"source",
"to",
"destination",
"it",
"does",
"not",
"overide",
"but",
"adds",
"multiple",
"headers"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L170-L174 |
149,402 | vulcand/oxy | utils/netutils.go | HasHeaders | func HasHeaders(names []string, headers http.Header) bool {
for _, h := range names {
if headers.Get(h) != "" {
return true
}
}
return false
} | go | func HasHeaders(names []string, headers http.Header) bool {
for _, h := range names {
if headers.Get(h) != "" {
return true
}
}
return false
} | [
"func",
"HasHeaders",
"(",
"names",
"[",
"]",
"string",
",",
"headers",
"http",
".",
"Header",
")",
"bool",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"names",
"{",
"if",
"headers",
".",
"Get",
"(",
"h",
")",
"!=",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasHeaders determines whether any of the header names is present in the http headers | [
"HasHeaders",
"determines",
"whether",
"any",
"of",
"the",
"header",
"names",
"is",
"present",
"in",
"the",
"http",
"headers"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L177-L184 |
149,403 | vulcand/oxy | cbreaker/effect.go | NewWebhookSideEffectsWithLogger | func NewWebhookSideEffectsWithLogger(w Webhook, l *log.Logger) (*WebhookSideEffect, error) {
if w.Method == "" {
return nil, fmt.Errorf("Supply method")
}
_, err := url.Parse(w.URL)
if err != nil {
return nil, err
}
return &WebhookSideEffect{w: w, log: l}, nil
} | go | func NewWebhookSideEffectsWithLogger(w Webhook, l *log.Logger) (*WebhookSideEffect, error) {
if w.Method == "" {
return nil, fmt.Errorf("Supply method")
}
_, err := url.Parse(w.URL)
if err != nil {
return nil, err
}
return &WebhookSideEffect{w: w, log: l}, nil
} | [
"func",
"NewWebhookSideEffectsWithLogger",
"(",
"w",
"Webhook",
",",
"l",
"*",
"log",
".",
"Logger",
")",
"(",
"*",
"WebhookSideEffect",
",",
"error",
")",
"{",
"if",
"w",
".",
"Method",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"w",
".",
"URL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"WebhookSideEffect",
"{",
"w",
":",
"w",
",",
"log",
":",
"l",
"}",
",",
"nil",
"\n",
"}"
] | // NewWebhookSideEffectsWithLogger creates a new WebhookSideEffect | [
"NewWebhookSideEffectsWithLogger",
"creates",
"a",
"new",
"WebhookSideEffect"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/effect.go#L38-L48 |
149,404 | vulcand/oxy | cbreaker/effect.go | Exec | func (w *WebhookSideEffect) Exec() error {
r, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody())
if err != nil {
return err
}
if len(w.w.Headers) != 0 {
utils.CopyHeaders(r.Header, w.w.Headers)
}
if len(w.w.Form) != 0 {
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
re, err := http.DefaultClient.Do(r)
if err != nil {
return err
}
if re.Body != nil {
defer re.Body.Close()
}
body, err := ioutil.ReadAll(re.Body)
if err != nil {
return err
}
w.log.Debugf("%v got response: (%s): %s", w, re.Status, string(body))
return nil
} | go | func (w *WebhookSideEffect) Exec() error {
r, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody())
if err != nil {
return err
}
if len(w.w.Headers) != 0 {
utils.CopyHeaders(r.Header, w.w.Headers)
}
if len(w.w.Form) != 0 {
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
re, err := http.DefaultClient.Do(r)
if err != nil {
return err
}
if re.Body != nil {
defer re.Body.Close()
}
body, err := ioutil.ReadAll(re.Body)
if err != nil {
return err
}
w.log.Debugf("%v got response: (%s): %s", w, re.Status, string(body))
return nil
} | [
"func",
"(",
"w",
"*",
"WebhookSideEffect",
")",
"Exec",
"(",
")",
"error",
"{",
"r",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"w",
".",
"w",
".",
"Method",
",",
"w",
".",
"w",
".",
"URL",
",",
"w",
".",
"getBody",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"w",
".",
"w",
".",
"Headers",
")",
"!=",
"0",
"{",
"utils",
".",
"CopyHeaders",
"(",
"r",
".",
"Header",
",",
"w",
".",
"w",
".",
"Headers",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"w",
".",
"w",
".",
"Form",
")",
"!=",
"0",
"{",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"re",
",",
"err",
":=",
"http",
".",
"DefaultClient",
".",
"Do",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"re",
".",
"Body",
"!=",
"nil",
"{",
"defer",
"re",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"re",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"w",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"w",
",",
"re",
".",
"Status",
",",
"string",
"(",
"body",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Exec execute the side effect | [
"Exec",
"execute",
"the",
"side",
"effect"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/effect.go#L66-L90 |
149,405 | vulcand/oxy | memmetrics/counter.go | CounterClock | func CounterClock(c timetools.TimeProvider) rcOptSetter {
return func(r *RollingCounter) error {
r.clock = c
return nil
}
} | go | func CounterClock(c timetools.TimeProvider) rcOptSetter {
return func(r *RollingCounter) error {
r.clock = c
return nil
}
} | [
"func",
"CounterClock",
"(",
"c",
"timetools",
".",
"TimeProvider",
")",
"rcOptSetter",
"{",
"return",
"func",
"(",
"r",
"*",
"RollingCounter",
")",
"error",
"{",
"r",
".",
"clock",
"=",
"c",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // CounterClock defines a counter clock | [
"CounterClock",
"defines",
"a",
"counter",
"clock"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L13-L18 |
149,406 | vulcand/oxy | memmetrics/counter.go | NewCounter | func NewCounter(buckets int, resolution time.Duration, options ...rcOptSetter) (*RollingCounter, error) {
if buckets <= 0 {
return nil, fmt.Errorf("Buckets should be >= 0")
}
if resolution < time.Second {
return nil, fmt.Errorf("Resolution should be larger than a second")
}
rc := &RollingCounter{
lastBucket: -1,
resolution: resolution,
values: make([]int, buckets),
}
for _, o := range options {
if err := o(rc); err != nil {
return nil, err
}
}
if rc.clock == nil {
rc.clock = &timetools.RealTime{}
}
return rc, nil
} | go | func NewCounter(buckets int, resolution time.Duration, options ...rcOptSetter) (*RollingCounter, error) {
if buckets <= 0 {
return nil, fmt.Errorf("Buckets should be >= 0")
}
if resolution < time.Second {
return nil, fmt.Errorf("Resolution should be larger than a second")
}
rc := &RollingCounter{
lastBucket: -1,
resolution: resolution,
values: make([]int, buckets),
}
for _, o := range options {
if err := o(rc); err != nil {
return nil, err
}
}
if rc.clock == nil {
rc.clock = &timetools.RealTime{}
}
return rc, nil
} | [
"func",
"NewCounter",
"(",
"buckets",
"int",
",",
"resolution",
"time",
".",
"Duration",
",",
"options",
"...",
"rcOptSetter",
")",
"(",
"*",
"RollingCounter",
",",
"error",
")",
"{",
"if",
"buckets",
"<=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"resolution",
"<",
"time",
".",
"Second",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"rc",
":=",
"&",
"RollingCounter",
"{",
"lastBucket",
":",
"-",
"1",
",",
"resolution",
":",
"resolution",
",",
"values",
":",
"make",
"(",
"[",
"]",
"int",
",",
"buckets",
")",
",",
"}",
"\n\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"if",
"err",
":=",
"o",
"(",
"rc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"rc",
".",
"clock",
"==",
"nil",
"{",
"rc",
".",
"clock",
"=",
"&",
"timetools",
".",
"RealTime",
"{",
"}",
"\n",
"}",
"\n\n",
"return",
"rc",
",",
"nil",
"\n",
"}"
] | // NewCounter creates a counter with fixed amount of buckets that are rotated every resolution period.
// E.g. 10 buckets with 1 second means that every new second the bucket is refreshed, so it maintains 10 second rolling window.
// By default creates a bucket with 10 buckets and 1 second resolution | [
"NewCounter",
"creates",
"a",
"counter",
"with",
"fixed",
"amount",
"of",
"buckets",
"that",
"are",
"rotated",
"every",
"resolution",
"period",
".",
"E",
".",
"g",
".",
"10",
"buckets",
"with",
"1",
"second",
"means",
"that",
"every",
"new",
"second",
"the",
"bucket",
"is",
"refreshed",
"so",
"it",
"maintains",
"10",
"second",
"rolling",
"window",
".",
"By",
"default",
"creates",
"a",
"bucket",
"with",
"10",
"buckets",
"and",
"1",
"second",
"resolution"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L33-L59 |
149,407 | vulcand/oxy | memmetrics/counter.go | Append | func (c *RollingCounter) Append(o *RollingCounter) error {
c.Inc(int(o.Count()))
return nil
} | go | func (c *RollingCounter) Append(o *RollingCounter) error {
c.Inc(int(o.Count()))
return nil
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"Append",
"(",
"o",
"*",
"RollingCounter",
")",
"error",
"{",
"c",
".",
"Inc",
"(",
"int",
"(",
"o",
".",
"Count",
"(",
")",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Append append a counter | [
"Append",
"append",
"a",
"counter"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L62-L65 |
149,408 | vulcand/oxy | memmetrics/counter.go | Clone | func (c *RollingCounter) Clone() *RollingCounter {
c.cleanup()
other := &RollingCounter{
resolution: c.resolution,
values: make([]int, len(c.values)),
clock: c.clock,
lastBucket: c.lastBucket,
lastUpdated: c.lastUpdated,
}
copy(other.values, c.values)
return other
} | go | func (c *RollingCounter) Clone() *RollingCounter {
c.cleanup()
other := &RollingCounter{
resolution: c.resolution,
values: make([]int, len(c.values)),
clock: c.clock,
lastBucket: c.lastBucket,
lastUpdated: c.lastUpdated,
}
copy(other.values, c.values)
return other
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"Clone",
"(",
")",
"*",
"RollingCounter",
"{",
"c",
".",
"cleanup",
"(",
")",
"\n",
"other",
":=",
"&",
"RollingCounter",
"{",
"resolution",
":",
"c",
".",
"resolution",
",",
"values",
":",
"make",
"(",
"[",
"]",
"int",
",",
"len",
"(",
"c",
".",
"values",
")",
")",
",",
"clock",
":",
"c",
".",
"clock",
",",
"lastBucket",
":",
"c",
".",
"lastBucket",
",",
"lastUpdated",
":",
"c",
".",
"lastUpdated",
",",
"}",
"\n",
"copy",
"(",
"other",
".",
"values",
",",
"c",
".",
"values",
")",
"\n",
"return",
"other",
"\n",
"}"
] | // Clone clone a counter | [
"Clone",
"clone",
"a",
"counter"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L68-L79 |
149,409 | vulcand/oxy | memmetrics/counter.go | Reset | func (c *RollingCounter) Reset() {
c.lastBucket = -1
c.countedBuckets = 0
c.lastUpdated = time.Time{}
for i := range c.values {
c.values[i] = 0
}
} | go | func (c *RollingCounter) Reset() {
c.lastBucket = -1
c.countedBuckets = 0
c.lastUpdated = time.Time{}
for i := range c.values {
c.values[i] = 0
}
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"Reset",
"(",
")",
"{",
"c",
".",
"lastBucket",
"=",
"-",
"1",
"\n",
"c",
".",
"countedBuckets",
"=",
"0",
"\n",
"c",
".",
"lastUpdated",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"c",
".",
"values",
"{",
"c",
".",
"values",
"[",
"i",
"]",
"=",
"0",
"\n",
"}",
"\n",
"}"
] | // Reset reset a counter | [
"Reset",
"reset",
"a",
"counter"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L82-L89 |
149,410 | vulcand/oxy | memmetrics/counter.go | WindowSize | func (c *RollingCounter) WindowSize() time.Duration {
return time.Duration(len(c.values)) * c.resolution
} | go | func (c *RollingCounter) WindowSize() time.Duration {
return time.Duration(len(c.values)) * c.resolution
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"WindowSize",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"len",
"(",
"c",
".",
"values",
")",
")",
"*",
"c",
".",
"resolution",
"\n",
"}"
] | // WindowSize gets windows size | [
"WindowSize",
"gets",
"windows",
"size"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L113-L115 |
149,411 | vulcand/oxy | memmetrics/counter.go | Inc | func (c *RollingCounter) Inc(v int) {
c.cleanup()
c.incBucketValue(v)
} | go | func (c *RollingCounter) Inc(v int) {
c.cleanup()
c.incBucketValue(v)
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"Inc",
"(",
"v",
"int",
")",
"{",
"c",
".",
"cleanup",
"(",
")",
"\n",
"c",
".",
"incBucketValue",
"(",
"v",
")",
"\n",
"}"
] | // Inc increment counter | [
"Inc",
"increment",
"counter"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L118-L121 |
149,412 | vulcand/oxy | memmetrics/counter.go | getBucket | func (c *RollingCounter) getBucket(t time.Time) int {
return int(t.Truncate(c.resolution).Unix() % int64(len(c.values)))
} | go | func (c *RollingCounter) getBucket(t time.Time) int {
return int(t.Truncate(c.resolution).Unix() % int64(len(c.values)))
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"getBucket",
"(",
"t",
"time",
".",
"Time",
")",
"int",
"{",
"return",
"int",
"(",
"t",
".",
"Truncate",
"(",
"c",
".",
"resolution",
")",
".",
"Unix",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"c",
".",
"values",
")",
")",
")",
"\n",
"}"
] | // Returns the number in the moving window bucket that this slot occupies | [
"Returns",
"the",
"number",
"in",
"the",
"moving",
"window",
"bucket",
"that",
"this",
"slot",
"occupies"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L140-L142 |
149,413 | vulcand/oxy | memmetrics/counter.go | cleanup | func (c *RollingCounter) cleanup() {
now := c.clock.UtcNow()
for i := 0; i < len(c.values); i++ {
now = now.Add(time.Duration(-1*i) * c.resolution)
if now.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) {
c.values[c.getBucket(now)] = 0
} else {
break
}
}
} | go | func (c *RollingCounter) cleanup() {
now := c.clock.UtcNow()
for i := 0; i < len(c.values); i++ {
now = now.Add(time.Duration(-1*i) * c.resolution)
if now.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) {
c.values[c.getBucket(now)] = 0
} else {
break
}
}
} | [
"func",
"(",
"c",
"*",
"RollingCounter",
")",
"cleanup",
"(",
")",
"{",
"now",
":=",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"c",
".",
"values",
")",
";",
"i",
"++",
"{",
"now",
"=",
"now",
".",
"Add",
"(",
"time",
".",
"Duration",
"(",
"-",
"1",
"*",
"i",
")",
"*",
"c",
".",
"resolution",
")",
"\n",
"if",
"now",
".",
"Truncate",
"(",
"c",
".",
"resolution",
")",
".",
"After",
"(",
"c",
".",
"lastUpdated",
".",
"Truncate",
"(",
"c",
".",
"resolution",
")",
")",
"{",
"c",
".",
"values",
"[",
"c",
".",
"getBucket",
"(",
"now",
")",
"]",
"=",
"0",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Reset buckets that were not updated | [
"Reset",
"buckets",
"that",
"were",
"not",
"updated"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L145-L155 |
149,414 | rs/xid | id.go | readMachineID | func readMachineID() []byte {
id := make([]byte, 3)
hid, err := readPlatformMachineID()
if err != nil || len(hid) == 0 {
hid, err = os.Hostname()
}
if err == nil && len(hid) != 0 {
hw := md5.New()
hw.Write([]byte(hid))
copy(id, hw.Sum(nil))
} else {
// Fallback to rand number if machine id can't be gathered
if _, randErr := rand.Reader.Read(id); randErr != nil {
panic(fmt.Errorf("xid: cannot get hostname nor generate a random number: %v; %v", err, randErr))
}
}
return id
} | go | func readMachineID() []byte {
id := make([]byte, 3)
hid, err := readPlatformMachineID()
if err != nil || len(hid) == 0 {
hid, err = os.Hostname()
}
if err == nil && len(hid) != 0 {
hw := md5.New()
hw.Write([]byte(hid))
copy(id, hw.Sum(nil))
} else {
// Fallback to rand number if machine id can't be gathered
if _, randErr := rand.Reader.Read(id); randErr != nil {
panic(fmt.Errorf("xid: cannot get hostname nor generate a random number: %v; %v", err, randErr))
}
}
return id
} | [
"func",
"readMachineID",
"(",
")",
"[",
"]",
"byte",
"{",
"id",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"3",
")",
"\n",
"hid",
",",
"err",
":=",
"readPlatformMachineID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"hid",
")",
"==",
"0",
"{",
"hid",
",",
"err",
"=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"hid",
")",
"!=",
"0",
"{",
"hw",
":=",
"md5",
".",
"New",
"(",
")",
"\n",
"hw",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"hid",
")",
")",
"\n",
"copy",
"(",
"id",
",",
"hw",
".",
"Sum",
"(",
"nil",
")",
")",
"\n",
"}",
"else",
"{",
"// Fallback to rand number if machine id can't be gathered",
"if",
"_",
",",
"randErr",
":=",
"rand",
".",
"Reader",
".",
"Read",
"(",
"id",
")",
";",
"randErr",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"randErr",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"id",
"\n",
"}"
] | // readMachineId generates machine id and puts it into the machineId global
// variable. If this function fails to get the hostname, it will cause
// a runtime error. | [
"readMachineId",
"generates",
"machine",
"id",
"and",
"puts",
"it",
"into",
"the",
"machineId",
"global",
"variable",
".",
"If",
"this",
"function",
"fails",
"to",
"get",
"the",
"hostname",
"it",
"will",
"cause",
"a",
"runtime",
"error",
"."
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L117-L134 |
149,415 | rs/xid | id.go | randInt | func randInt() uint32 {
b := make([]byte, 3)
if _, err := rand.Reader.Read(b); err != nil {
panic(fmt.Errorf("xid: cannot generate random number: %v;", err))
}
return uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])
} | go | func randInt() uint32 {
b := make([]byte, 3)
if _, err := rand.Reader.Read(b); err != nil {
panic(fmt.Errorf("xid: cannot generate random number: %v;", err))
}
return uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])
} | [
"func",
"randInt",
"(",
")",
"uint32",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"3",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Reader",
".",
"Read",
"(",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"uint32",
"(",
"b",
"[",
"0",
"]",
")",
"<<",
"16",
"|",
"uint32",
"(",
"b",
"[",
"1",
"]",
")",
"<<",
"8",
"|",
"uint32",
"(",
"b",
"[",
"2",
"]",
")",
"\n",
"}"
] | // randInt generates a random uint32 | [
"randInt",
"generates",
"a",
"random",
"uint32"
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L137-L143 |
149,416 | rs/xid | id.go | NewWithTime | func NewWithTime(t time.Time) ID {
var id ID
// Timestamp, 4 bytes, big endian
binary.BigEndian.PutUint32(id[:], uint32(t.Unix()))
// Machine, first 3 bytes of md5(hostname)
id[4] = machineID[0]
id[5] = machineID[1]
id[6] = machineID[2]
// Pid, 2 bytes, specs don't specify endianness, but we use big endian.
id[7] = byte(pid >> 8)
id[8] = byte(pid)
// Increment, 3 bytes, big endian
i := atomic.AddUint32(&objectIDCounter, 1)
id[9] = byte(i >> 16)
id[10] = byte(i >> 8)
id[11] = byte(i)
return id
} | go | func NewWithTime(t time.Time) ID {
var id ID
// Timestamp, 4 bytes, big endian
binary.BigEndian.PutUint32(id[:], uint32(t.Unix()))
// Machine, first 3 bytes of md5(hostname)
id[4] = machineID[0]
id[5] = machineID[1]
id[6] = machineID[2]
// Pid, 2 bytes, specs don't specify endianness, but we use big endian.
id[7] = byte(pid >> 8)
id[8] = byte(pid)
// Increment, 3 bytes, big endian
i := atomic.AddUint32(&objectIDCounter, 1)
id[9] = byte(i >> 16)
id[10] = byte(i >> 8)
id[11] = byte(i)
return id
} | [
"func",
"NewWithTime",
"(",
"t",
"time",
".",
"Time",
")",
"ID",
"{",
"var",
"id",
"ID",
"\n",
"// Timestamp, 4 bytes, big endian",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"id",
"[",
":",
"]",
",",
"uint32",
"(",
"t",
".",
"Unix",
"(",
")",
")",
")",
"\n",
"// Machine, first 3 bytes of md5(hostname)",
"id",
"[",
"4",
"]",
"=",
"machineID",
"[",
"0",
"]",
"\n",
"id",
"[",
"5",
"]",
"=",
"machineID",
"[",
"1",
"]",
"\n",
"id",
"[",
"6",
"]",
"=",
"machineID",
"[",
"2",
"]",
"\n",
"// Pid, 2 bytes, specs don't specify endianness, but we use big endian.",
"id",
"[",
"7",
"]",
"=",
"byte",
"(",
"pid",
">>",
"8",
")",
"\n",
"id",
"[",
"8",
"]",
"=",
"byte",
"(",
"pid",
")",
"\n",
"// Increment, 3 bytes, big endian",
"i",
":=",
"atomic",
".",
"AddUint32",
"(",
"&",
"objectIDCounter",
",",
"1",
")",
"\n",
"id",
"[",
"9",
"]",
"=",
"byte",
"(",
"i",
">>",
"16",
")",
"\n",
"id",
"[",
"10",
"]",
"=",
"byte",
"(",
"i",
">>",
"8",
")",
"\n",
"id",
"[",
"11",
"]",
"=",
"byte",
"(",
"i",
")",
"\n",
"return",
"id",
"\n",
"}"
] | // NewWithTime generates a globally unique ID with the passed in time | [
"NewWithTime",
"generates",
"a",
"globally",
"unique",
"ID",
"with",
"the",
"passed",
"in",
"time"
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L151-L168 |
149,417 | rs/xid | id.go | FromString | func FromString(id string) (ID, error) {
i := &ID{}
err := i.UnmarshalText([]byte(id))
return *i, err
} | go | func FromString(id string) (ID, error) {
i := &ID{}
err := i.UnmarshalText([]byte(id))
return *i, err
} | [
"func",
"FromString",
"(",
"id",
"string",
")",
"(",
"ID",
",",
"error",
")",
"{",
"i",
":=",
"&",
"ID",
"{",
"}",
"\n",
"err",
":=",
"i",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"id",
")",
")",
"\n",
"return",
"*",
"i",
",",
"err",
"\n",
"}"
] | // FromString reads an ID from its string representation | [
"FromString",
"reads",
"an",
"ID",
"from",
"its",
"string",
"representation"
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L171-L175 |
149,418 | rs/xid | id.go | encode | func encode(dst, id []byte) {
_ = dst[19]
_ = id[11]
dst[19] = encoding[(id[11]<<4)&0x1F]
dst[18] = encoding[(id[11]>>1)&0x1F]
dst[17] = encoding[(id[11]>>6)&0x1F|(id[10]<<2)&0x1F]
dst[16] = encoding[id[10]>>3]
dst[15] = encoding[id[9]&0x1F]
dst[14] = encoding[(id[9]>>5)|(id[8]<<3)&0x1F]
dst[13] = encoding[(id[8]>>2)&0x1F]
dst[12] = encoding[id[8]>>7|(id[7]<<1)&0x1F]
dst[11] = encoding[(id[7]>>4)&0x1F|(id[6]<<4)&0x1F]
dst[10] = encoding[(id[6]>>1)&0x1F]
dst[9] = encoding[(id[6]>>6)&0x1F|(id[5]<<2)&0x1F]
dst[8] = encoding[id[5]>>3]
dst[7] = encoding[id[4]&0x1F]
dst[6] = encoding[id[4]>>5|(id[3]<<3)&0x1F]
dst[5] = encoding[(id[3]>>2)&0x1F]
dst[4] = encoding[id[3]>>7|(id[2]<<1)&0x1F]
dst[3] = encoding[(id[2]>>4)&0x1F|(id[1]<<4)&0x1F]
dst[2] = encoding[(id[1]>>1)&0x1F]
dst[1] = encoding[(id[1]>>6)&0x1F|(id[0]<<2)&0x1F]
dst[0] = encoding[id[0]>>3]
} | go | func encode(dst, id []byte) {
_ = dst[19]
_ = id[11]
dst[19] = encoding[(id[11]<<4)&0x1F]
dst[18] = encoding[(id[11]>>1)&0x1F]
dst[17] = encoding[(id[11]>>6)&0x1F|(id[10]<<2)&0x1F]
dst[16] = encoding[id[10]>>3]
dst[15] = encoding[id[9]&0x1F]
dst[14] = encoding[(id[9]>>5)|(id[8]<<3)&0x1F]
dst[13] = encoding[(id[8]>>2)&0x1F]
dst[12] = encoding[id[8]>>7|(id[7]<<1)&0x1F]
dst[11] = encoding[(id[7]>>4)&0x1F|(id[6]<<4)&0x1F]
dst[10] = encoding[(id[6]>>1)&0x1F]
dst[9] = encoding[(id[6]>>6)&0x1F|(id[5]<<2)&0x1F]
dst[8] = encoding[id[5]>>3]
dst[7] = encoding[id[4]&0x1F]
dst[6] = encoding[id[4]>>5|(id[3]<<3)&0x1F]
dst[5] = encoding[(id[3]>>2)&0x1F]
dst[4] = encoding[id[3]>>7|(id[2]<<1)&0x1F]
dst[3] = encoding[(id[2]>>4)&0x1F|(id[1]<<4)&0x1F]
dst[2] = encoding[(id[1]>>1)&0x1F]
dst[1] = encoding[(id[1]>>6)&0x1F|(id[0]<<2)&0x1F]
dst[0] = encoding[id[0]>>3]
} | [
"func",
"encode",
"(",
"dst",
",",
"id",
"[",
"]",
"byte",
")",
"{",
"_",
"=",
"dst",
"[",
"19",
"]",
"\n",
"_",
"=",
"id",
"[",
"11",
"]",
"\n\n",
"dst",
"[",
"19",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"11",
"]",
"<<",
"4",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"18",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"11",
"]",
">>",
"1",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"17",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"11",
"]",
">>",
"6",
")",
"&",
"0x1F",
"|",
"(",
"id",
"[",
"10",
"]",
"<<",
"2",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"16",
"]",
"=",
"encoding",
"[",
"id",
"[",
"10",
"]",
">>",
"3",
"]",
"\n",
"dst",
"[",
"15",
"]",
"=",
"encoding",
"[",
"id",
"[",
"9",
"]",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"14",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"9",
"]",
">>",
"5",
")",
"|",
"(",
"id",
"[",
"8",
"]",
"<<",
"3",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"13",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"8",
"]",
">>",
"2",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"12",
"]",
"=",
"encoding",
"[",
"id",
"[",
"8",
"]",
">>",
"7",
"|",
"(",
"id",
"[",
"7",
"]",
"<<",
"1",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"11",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"7",
"]",
">>",
"4",
")",
"&",
"0x1F",
"|",
"(",
"id",
"[",
"6",
"]",
"<<",
"4",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"10",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"6",
"]",
">>",
"1",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"9",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"6",
"]",
">>",
"6",
")",
"&",
"0x1F",
"|",
"(",
"id",
"[",
"5",
"]",
"<<",
"2",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"8",
"]",
"=",
"encoding",
"[",
"id",
"[",
"5",
"]",
">>",
"3",
"]",
"\n",
"dst",
"[",
"7",
"]",
"=",
"encoding",
"[",
"id",
"[",
"4",
"]",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"6",
"]",
"=",
"encoding",
"[",
"id",
"[",
"4",
"]",
">>",
"5",
"|",
"(",
"id",
"[",
"3",
"]",
"<<",
"3",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"5",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"3",
"]",
">>",
"2",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"4",
"]",
"=",
"encoding",
"[",
"id",
"[",
"3",
"]",
">>",
"7",
"|",
"(",
"id",
"[",
"2",
"]",
"<<",
"1",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"3",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"2",
"]",
">>",
"4",
")",
"&",
"0x1F",
"|",
"(",
"id",
"[",
"1",
"]",
"<<",
"4",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"2",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"1",
"]",
">>",
"1",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"1",
"]",
"=",
"encoding",
"[",
"(",
"id",
"[",
"1",
"]",
">>",
"6",
")",
"&",
"0x1F",
"|",
"(",
"id",
"[",
"0",
"]",
"<<",
"2",
")",
"&",
"0x1F",
"]",
"\n",
"dst",
"[",
"0",
"]",
"=",
"encoding",
"[",
"id",
"[",
"0",
"]",
">>",
"3",
"]",
"\n",
"}"
] | // encode by unrolling the stdlib base32 algorithm + removing all safe checks | [
"encode",
"by",
"unrolling",
"the",
"stdlib",
"base32",
"algorithm",
"+",
"removing",
"all",
"safe",
"checks"
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L203-L227 |
149,419 | rs/xid | id.go | decode | func decode(id *ID, src []byte) {
_ = src[19]
_ = id[11]
id[11] = dec[src[17]]<<6 | dec[src[18]]<<1 | dec[src[19]]>>4
id[10] = dec[src[16]]<<3 | dec[src[17]]>>2
id[9] = dec[src[14]]<<5 | dec[src[15]]
id[8] = dec[src[12]]<<7 | dec[src[13]]<<2 | dec[src[14]]>>3
id[7] = dec[src[11]]<<4 | dec[src[12]]>>1
id[6] = dec[src[9]]<<6 | dec[src[10]]<<1 | dec[src[11]]>>4
id[5] = dec[src[8]]<<3 | dec[src[9]]>>2
id[4] = dec[src[6]]<<5 | dec[src[7]]
id[3] = dec[src[4]]<<7 | dec[src[5]]<<2 | dec[src[6]]>>3
id[2] = dec[src[3]]<<4 | dec[src[4]]>>1
id[1] = dec[src[1]]<<6 | dec[src[2]]<<1 | dec[src[3]]>>4
id[0] = dec[src[0]]<<3 | dec[src[1]]>>2
} | go | func decode(id *ID, src []byte) {
_ = src[19]
_ = id[11]
id[11] = dec[src[17]]<<6 | dec[src[18]]<<1 | dec[src[19]]>>4
id[10] = dec[src[16]]<<3 | dec[src[17]]>>2
id[9] = dec[src[14]]<<5 | dec[src[15]]
id[8] = dec[src[12]]<<7 | dec[src[13]]<<2 | dec[src[14]]>>3
id[7] = dec[src[11]]<<4 | dec[src[12]]>>1
id[6] = dec[src[9]]<<6 | dec[src[10]]<<1 | dec[src[11]]>>4
id[5] = dec[src[8]]<<3 | dec[src[9]]>>2
id[4] = dec[src[6]]<<5 | dec[src[7]]
id[3] = dec[src[4]]<<7 | dec[src[5]]<<2 | dec[src[6]]>>3
id[2] = dec[src[3]]<<4 | dec[src[4]]>>1
id[1] = dec[src[1]]<<6 | dec[src[2]]<<1 | dec[src[3]]>>4
id[0] = dec[src[0]]<<3 | dec[src[1]]>>2
} | [
"func",
"decode",
"(",
"id",
"*",
"ID",
",",
"src",
"[",
"]",
"byte",
")",
"{",
"_",
"=",
"src",
"[",
"19",
"]",
"\n",
"_",
"=",
"id",
"[",
"11",
"]",
"\n\n",
"id",
"[",
"11",
"]",
"=",
"dec",
"[",
"src",
"[",
"17",
"]",
"]",
"<<",
"6",
"|",
"dec",
"[",
"src",
"[",
"18",
"]",
"]",
"<<",
"1",
"|",
"dec",
"[",
"src",
"[",
"19",
"]",
"]",
">>",
"4",
"\n",
"id",
"[",
"10",
"]",
"=",
"dec",
"[",
"src",
"[",
"16",
"]",
"]",
"<<",
"3",
"|",
"dec",
"[",
"src",
"[",
"17",
"]",
"]",
">>",
"2",
"\n",
"id",
"[",
"9",
"]",
"=",
"dec",
"[",
"src",
"[",
"14",
"]",
"]",
"<<",
"5",
"|",
"dec",
"[",
"src",
"[",
"15",
"]",
"]",
"\n",
"id",
"[",
"8",
"]",
"=",
"dec",
"[",
"src",
"[",
"12",
"]",
"]",
"<<",
"7",
"|",
"dec",
"[",
"src",
"[",
"13",
"]",
"]",
"<<",
"2",
"|",
"dec",
"[",
"src",
"[",
"14",
"]",
"]",
">>",
"3",
"\n",
"id",
"[",
"7",
"]",
"=",
"dec",
"[",
"src",
"[",
"11",
"]",
"]",
"<<",
"4",
"|",
"dec",
"[",
"src",
"[",
"12",
"]",
"]",
">>",
"1",
"\n",
"id",
"[",
"6",
"]",
"=",
"dec",
"[",
"src",
"[",
"9",
"]",
"]",
"<<",
"6",
"|",
"dec",
"[",
"src",
"[",
"10",
"]",
"]",
"<<",
"1",
"|",
"dec",
"[",
"src",
"[",
"11",
"]",
"]",
">>",
"4",
"\n",
"id",
"[",
"5",
"]",
"=",
"dec",
"[",
"src",
"[",
"8",
"]",
"]",
"<<",
"3",
"|",
"dec",
"[",
"src",
"[",
"9",
"]",
"]",
">>",
"2",
"\n",
"id",
"[",
"4",
"]",
"=",
"dec",
"[",
"src",
"[",
"6",
"]",
"]",
"<<",
"5",
"|",
"dec",
"[",
"src",
"[",
"7",
"]",
"]",
"\n",
"id",
"[",
"3",
"]",
"=",
"dec",
"[",
"src",
"[",
"4",
"]",
"]",
"<<",
"7",
"|",
"dec",
"[",
"src",
"[",
"5",
"]",
"]",
"<<",
"2",
"|",
"dec",
"[",
"src",
"[",
"6",
"]",
"]",
">>",
"3",
"\n",
"id",
"[",
"2",
"]",
"=",
"dec",
"[",
"src",
"[",
"3",
"]",
"]",
"<<",
"4",
"|",
"dec",
"[",
"src",
"[",
"4",
"]",
"]",
">>",
"1",
"\n",
"id",
"[",
"1",
"]",
"=",
"dec",
"[",
"src",
"[",
"1",
"]",
"]",
"<<",
"6",
"|",
"dec",
"[",
"src",
"[",
"2",
"]",
"]",
"<<",
"1",
"|",
"dec",
"[",
"src",
"[",
"3",
"]",
"]",
">>",
"4",
"\n",
"id",
"[",
"0",
"]",
"=",
"dec",
"[",
"src",
"[",
"0",
"]",
"]",
"<<",
"3",
"|",
"dec",
"[",
"src",
"[",
"1",
"]",
"]",
">>",
"2",
"\n",
"}"
] | // decode by unrolling the stdlib base32 algorithm + removing all safe checks | [
"decode",
"by",
"unrolling",
"the",
"stdlib",
"base32",
"algorithm",
"+",
"removing",
"all",
"safe",
"checks"
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L254-L270 |
149,420 | rs/xid | id.go | Time | func (id ID) Time() time.Time {
// First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch.
secs := int64(binary.BigEndian.Uint32(id[0:4]))
return time.Unix(secs, 0)
} | go | func (id ID) Time() time.Time {
// First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch.
secs := int64(binary.BigEndian.Uint32(id[0:4]))
return time.Unix(secs, 0)
} | [
"func",
"(",
"id",
"ID",
")",
"Time",
"(",
")",
"time",
".",
"Time",
"{",
"// First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch.",
"secs",
":=",
"int64",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"id",
"[",
"0",
":",
"4",
"]",
")",
")",
"\n",
"return",
"time",
".",
"Unix",
"(",
"secs",
",",
"0",
")",
"\n",
"}"
] | // Time returns the timestamp part of the id.
// It's a runtime error to call this method with an invalid id. | [
"Time",
"returns",
"the",
"timestamp",
"part",
"of",
"the",
"id",
".",
"It",
"s",
"a",
"runtime",
"error",
"to",
"call",
"this",
"method",
"with",
"an",
"invalid",
"id",
"."
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L274-L278 |
149,421 | rs/xid | id.go | Counter | func (id ID) Counter() int32 {
b := id[9:12]
// Counter is stored as big-endian 3-byte value
return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]))
} | go | func (id ID) Counter() int32 {
b := id[9:12]
// Counter is stored as big-endian 3-byte value
return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]))
} | [
"func",
"(",
"id",
"ID",
")",
"Counter",
"(",
")",
"int32",
"{",
"b",
":=",
"id",
"[",
"9",
":",
"12",
"]",
"\n",
"// Counter is stored as big-endian 3-byte value",
"return",
"int32",
"(",
"uint32",
"(",
"b",
"[",
"0",
"]",
")",
"<<",
"16",
"|",
"uint32",
"(",
"b",
"[",
"1",
"]",
")",
"<<",
"8",
"|",
"uint32",
"(",
"b",
"[",
"2",
"]",
")",
")",
"\n",
"}"
] | // Counter returns the incrementing value part of the id.
// It's a runtime error to call this method with an invalid id. | [
"Counter",
"returns",
"the",
"incrementing",
"value",
"part",
"of",
"the",
"id",
".",
"It",
"s",
"a",
"runtime",
"error",
"to",
"call",
"this",
"method",
"with",
"an",
"invalid",
"id",
"."
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L294-L298 |
149,422 | rs/xid | id.go | FromBytes | func FromBytes(b []byte) (ID, error) {
var id ID
if len(b) != rawLen {
return id, ErrInvalidID
}
copy(id[:], b)
return id, nil
} | go | func FromBytes(b []byte) (ID, error) {
var id ID
if len(b) != rawLen {
return id, ErrInvalidID
}
copy(id[:], b)
return id, nil
} | [
"func",
"FromBytes",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"ID",
",",
"error",
")",
"{",
"var",
"id",
"ID",
"\n",
"if",
"len",
"(",
"b",
")",
"!=",
"rawLen",
"{",
"return",
"id",
",",
"ErrInvalidID",
"\n",
"}",
"\n",
"copy",
"(",
"id",
"[",
":",
"]",
",",
"b",
")",
"\n",
"return",
"id",
",",
"nil",
"\n",
"}"
] | // FromBytes convert the byte array representation of `ID` back to `ID` | [
"FromBytes",
"convert",
"the",
"byte",
"array",
"representation",
"of",
"ID",
"back",
"to",
"ID"
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L340-L347 |
149,423 | rs/xid | id.go | Compare | func (id ID) Compare(other ID) int {
return bytes.Compare(id[:], other[:])
} | go | func (id ID) Compare(other ID) int {
return bytes.Compare(id[:], other[:])
} | [
"func",
"(",
"id",
"ID",
")",
"Compare",
"(",
"other",
"ID",
")",
"int",
"{",
"return",
"bytes",
".",
"Compare",
"(",
"id",
"[",
":",
"]",
",",
"other",
"[",
":",
"]",
")",
"\n",
"}"
] | // Compare returns an integer comparing two IDs. It behaves just like `bytes.Compare`.
// The result will be 0 if two IDs are identical, -1 if current id is less than the other one,
// and 1 if current id is greater than the other. | [
"Compare",
"returns",
"an",
"integer",
"comparing",
"two",
"IDs",
".",
"It",
"behaves",
"just",
"like",
"bytes",
".",
"Compare",
".",
"The",
"result",
"will",
"be",
"0",
"if",
"two",
"IDs",
"are",
"identical",
"-",
"1",
"if",
"current",
"id",
"is",
"less",
"than",
"the",
"other",
"one",
"and",
"1",
"if",
"current",
"id",
"is",
"greater",
"than",
"the",
"other",
"."
] | ba6f703301d6c14cbc05faa3b512058f2304e16c | https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L352-L354 |
149,424 | crewjam/saml | xmlenc/fuzz.go | Fuzz | func Fuzz(data []byte) int {
doc := etree.NewDocument()
if err := doc.ReadFromBytes(data); err != nil {
return 0
}
if doc.Root() == nil {
return 0
}
if _, err := Decrypt(testKey, doc.Root()); err != nil {
return 0
}
return 1
} | go | func Fuzz(data []byte) int {
doc := etree.NewDocument()
if err := doc.ReadFromBytes(data); err != nil {
return 0
}
if doc.Root() == nil {
return 0
}
if _, err := Decrypt(testKey, doc.Root()); err != nil {
return 0
}
return 1
} | [
"func",
"Fuzz",
"(",
"data",
"[",
"]",
"byte",
")",
"int",
"{",
"doc",
":=",
"etree",
".",
"NewDocument",
"(",
")",
"\n",
"if",
"err",
":=",
"doc",
".",
"ReadFromBytes",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"if",
"doc",
".",
"Root",
"(",
")",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"Decrypt",
"(",
"testKey",
",",
"doc",
".",
"Root",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"1",
"\n",
"}"
] | // Fuzz is the go-fuzz fuzzing function | [
"Fuzz",
"is",
"the",
"go",
"-",
"fuzz",
"fuzzing",
"function"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/xmlenc/fuzz.go#L36-L49 |
149,425 | crewjam/saml | samlidp/session.go | sendLoginForm | func (s *Server) sendLoginForm(w http.ResponseWriter, r *http.Request, req *saml.IdpAuthnRequest, toast string) {
tmpl := template.Must(template.New("saml-post-form").Parse(`` +
`<html>` +
`<p>{{.Toast}}</p>` +
`<form method="post" action="{{.URL}}">` +
`<input type="text" name="user" placeholder="user" value="" />` +
`<input type="password" name="password" placeholder="password" value="" />` +
`<input type="hidden" name="SAMLRequest" value="{{.SAMLRequest}}" />` +
`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
`<input type="submit" value="Log In" />` +
`</form>` +
`</html>`))
data := struct {
Toast string
URL string
SAMLRequest string
RelayState string
}{
Toast: toast,
URL: req.IDP.SSOURL.String(),
SAMLRequest: base64.StdEncoding.EncodeToString(req.RequestBuffer),
RelayState: req.RelayState,
}
if err := tmpl.Execute(w, data); err != nil {
panic(err)
}
} | go | func (s *Server) sendLoginForm(w http.ResponseWriter, r *http.Request, req *saml.IdpAuthnRequest, toast string) {
tmpl := template.Must(template.New("saml-post-form").Parse(`` +
`<html>` +
`<p>{{.Toast}}</p>` +
`<form method="post" action="{{.URL}}">` +
`<input type="text" name="user" placeholder="user" value="" />` +
`<input type="password" name="password" placeholder="password" value="" />` +
`<input type="hidden" name="SAMLRequest" value="{{.SAMLRequest}}" />` +
`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
`<input type="submit" value="Log In" />` +
`</form>` +
`</html>`))
data := struct {
Toast string
URL string
SAMLRequest string
RelayState string
}{
Toast: toast,
URL: req.IDP.SSOURL.String(),
SAMLRequest: base64.StdEncoding.EncodeToString(req.RequestBuffer),
RelayState: req.RelayState,
}
if err := tmpl.Execute(w, data); err != nil {
panic(err)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendLoginForm",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"req",
"*",
"saml",
".",
"IdpAuthnRequest",
",",
"toast",
"string",
")",
"{",
"tmpl",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"``",
"+",
"`<html>`",
"+",
"`<p>{{.Toast}}</p>`",
"+",
"`<form method=\"post\" action=\"{{.URL}}\">`",
"+",
"`<input type=\"text\" name=\"user\" placeholder=\"user\" value=\"\" />`",
"+",
"`<input type=\"password\" name=\"password\" placeholder=\"password\" value=\"\" />`",
"+",
"`<input type=\"hidden\" name=\"SAMLRequest\" value=\"{{.SAMLRequest}}\" />`",
"+",
"`<input type=\"hidden\" name=\"RelayState\" value=\"{{.RelayState}}\" />`",
"+",
"`<input type=\"submit\" value=\"Log In\" />`",
"+",
"`</form>`",
"+",
"`</html>`",
")",
")",
"\n",
"data",
":=",
"struct",
"{",
"Toast",
"string",
"\n",
"URL",
"string",
"\n",
"SAMLRequest",
"string",
"\n",
"RelayState",
"string",
"\n",
"}",
"{",
"Toast",
":",
"toast",
",",
"URL",
":",
"req",
".",
"IDP",
".",
"SSOURL",
".",
"String",
"(",
")",
",",
"SAMLRequest",
":",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"req",
".",
"RequestBuffer",
")",
",",
"RelayState",
":",
"req",
".",
"RelayState",
",",
"}",
"\n\n",
"if",
"err",
":=",
"tmpl",
".",
"Execute",
"(",
"w",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // sendLoginForm produces a form which requests a username and password and directs the user
// back to the IDP authorize URL to restart the SAML login flow, this time establishing a
// session based on the credentials that were provided. | [
"sendLoginForm",
"produces",
"a",
"form",
"which",
"requests",
"a",
"username",
"and",
"password",
"and",
"directs",
"the",
"user",
"back",
"to",
"the",
"IDP",
"authorize",
"URL",
"to",
"restart",
"the",
"SAML",
"login",
"flow",
"this",
"time",
"establishing",
"a",
"session",
"based",
"on",
"the",
"credentials",
"that",
"were",
"provided",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/session.go#L102-L129 |
149,426 | crewjam/saml | samlsp/token.go | Get | func (a Attributes) Get(key string) string {
if a == nil {
return ""
}
v := a[key]
if len(v) == 0 {
return ""
}
return v[0]
} | go | func (a Attributes) Get(key string) string {
if a == nil {
return ""
}
v := a[key]
if len(v) == 0 {
return ""
}
return v[0]
} | [
"func",
"(",
"a",
"Attributes",
")",
"Get",
"(",
"key",
"string",
")",
"string",
"{",
"if",
"a",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"v",
":=",
"a",
"[",
"key",
"]",
"\n",
"if",
"len",
"(",
"v",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"v",
"[",
"0",
"]",
"\n",
"}"
] | // Get returns the first attribute named `key` or an empty string if
// no such attributes is present. | [
"Get",
"returns",
"the",
"first",
"attribute",
"named",
"key",
"or",
"an",
"empty",
"string",
"if",
"no",
"such",
"attributes",
"is",
"present",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/token.go#L20-L29 |
149,427 | crewjam/saml | samlsp/token.go | Token | func Token(ctx context.Context) *AuthorizationToken {
v := ctx.Value(tokenIndex)
if v == nil {
return nil
}
return v.(*AuthorizationToken)
} | go | func Token(ctx context.Context) *AuthorizationToken {
v := ctx.Value(tokenIndex)
if v == nil {
return nil
}
return v.(*AuthorizationToken)
} | [
"func",
"Token",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"AuthorizationToken",
"{",
"v",
":=",
"ctx",
".",
"Value",
"(",
"tokenIndex",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"v",
".",
"(",
"*",
"AuthorizationToken",
")",
"\n",
"}"
] | // Token returns the token associated with ctx, or nil if no token are associated | [
"Token",
"returns",
"the",
"token",
"associated",
"with",
"ctx",
"or",
"nil",
"if",
"no",
"token",
"are",
"associated"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/token.go#L36-L42 |
149,428 | crewjam/saml | samlsp/token.go | WithToken | func WithToken(ctx context.Context, token *AuthorizationToken) context.Context {
return context.WithValue(ctx, tokenIndex, token)
} | go | func WithToken(ctx context.Context, token *AuthorizationToken) context.Context {
return context.WithValue(ctx, tokenIndex, token)
} | [
"func",
"WithToken",
"(",
"ctx",
"context",
".",
"Context",
",",
"token",
"*",
"AuthorizationToken",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"tokenIndex",
",",
"token",
")",
"\n",
"}"
] | // WithToken returns a new context with token associated | [
"WithToken",
"returns",
"a",
"new",
"context",
"with",
"token",
"associated"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/token.go#L45-L47 |
149,429 | crewjam/saml | samlidp/memory_store.go | Get | func (s *MemoryStore) Get(key string, value interface{}) error {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.data[key]
if !ok {
return ErrNotFound
}
return json.Unmarshal([]byte(v), value)
} | go | func (s *MemoryStore) Get(key string, value interface{}) error {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.data[key]
if !ok {
return ErrNotFound
}
return json.Unmarshal([]byte(v), value)
} | [
"func",
"(",
"s",
"*",
"MemoryStore",
")",
"Get",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"s",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"v",
",",
"ok",
":=",
"s",
".",
"data",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"v",
")",
",",
"value",
")",
"\n",
"}"
] | // Get fetches the data stored in `key` and unmarshals it into `value`. | [
"Get",
"fetches",
"the",
"data",
"stored",
"in",
"key",
"and",
"unmarshals",
"it",
"into",
"value",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/memory_store.go#L17-L26 |
149,430 | crewjam/saml | samlidp/memory_store.go | Put | func (s *MemoryStore) Put(key string, value interface{}) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.data == nil {
s.data = map[string]string{}
}
buf, err := json.Marshal(value)
if err != nil {
return err
}
s.data[key] = string(buf)
return nil
} | go | func (s *MemoryStore) Put(key string, value interface{}) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.data == nil {
s.data = map[string]string{}
}
buf, err := json.Marshal(value)
if err != nil {
return err
}
s.data[key] = string(buf)
return nil
} | [
"func",
"(",
"s",
"*",
"MemoryStore",
")",
"Put",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"data",
"==",
"nil",
"{",
"s",
".",
"data",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"data",
"[",
"key",
"]",
"=",
"string",
"(",
"buf",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Put marshals `value` and stores it in `key`. | [
"Put",
"marshals",
"value",
"and",
"stores",
"it",
"in",
"key",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/memory_store.go#L29-L42 |
149,431 | crewjam/saml | samlidp/memory_store.go | Delete | func (s *MemoryStore) Delete(key string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.data, key)
return nil
} | go | func (s *MemoryStore) Delete(key string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.data, key)
return nil
} | [
"func",
"(",
"s",
"*",
"MemoryStore",
")",
"Delete",
"(",
"key",
"string",
")",
"error",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"data",
",",
"key",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete removes `key` | [
"Delete",
"removes",
"key"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/memory_store.go#L45-L50 |
149,432 | crewjam/saml | example/service.go | CreateLink | func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) {
account := r.Header.Get("X-Remote-User")
l := Link{
ShortLink: uniuri.New(),
Target: r.FormValue("t"),
Owner: account,
}
links[l.ShortLink] = l
fmt.Fprintf(w, "%s\n", l.ShortLink)
return
} | go | func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) {
account := r.Header.Get("X-Remote-User")
l := Link{
ShortLink: uniuri.New(),
Target: r.FormValue("t"),
Owner: account,
}
links[l.ShortLink] = l
fmt.Fprintf(w, "%s\n", l.ShortLink)
return
} | [
"func",
"CreateLink",
"(",
"c",
"web",
".",
"C",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"account",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"l",
":=",
"Link",
"{",
"ShortLink",
":",
"uniuri",
".",
"New",
"(",
")",
",",
"Target",
":",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
",",
"Owner",
":",
"account",
",",
"}",
"\n",
"links",
"[",
"l",
".",
"ShortLink",
"]",
"=",
"l",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"l",
".",
"ShortLink",
")",
"\n",
"return",
"\n",
"}"
] | // CreateLink handles requests to create links | [
"CreateLink",
"handles",
"requests",
"to",
"create",
"links"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/example/service.go#L35-L46 |
149,433 | crewjam/saml | example/service.go | ServeLink | func ServeLink(c web.C, w http.ResponseWriter, r *http.Request) {
l, ok := links[strings.TrimPrefix(r.URL.Path, "/")]
if !ok {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
http.Redirect(w, r, l.Target, http.StatusFound)
return
} | go | func ServeLink(c web.C, w http.ResponseWriter, r *http.Request) {
l, ok := links[strings.TrimPrefix(r.URL.Path, "/")]
if !ok {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
http.Redirect(w, r, l.Target, http.StatusFound)
return
} | [
"func",
"ServeLink",
"(",
"c",
"web",
".",
"C",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"l",
",",
"ok",
":=",
"links",
"[",
"strings",
".",
"TrimPrefix",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusNotFound",
")",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"l",
".",
"Target",
",",
"http",
".",
"StatusFound",
")",
"\n",
"return",
"\n",
"}"
] | // ServeLink handles requests to redirect to a link | [
"ServeLink",
"handles",
"requests",
"to",
"redirect",
"to",
"a",
"link"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/example/service.go#L49-L57 |
149,434 | crewjam/saml | example/service.go | ListLinks | func ListLinks(c web.C, w http.ResponseWriter, r *http.Request) {
account := r.Header.Get("X-Remote-User")
for _, l := range links {
if l.Owner == account {
fmt.Fprintf(w, "%s\n", l.ShortLink)
}
}
} | go | func ListLinks(c web.C, w http.ResponseWriter, r *http.Request) {
account := r.Header.Get("X-Remote-User")
for _, l := range links {
if l.Owner == account {
fmt.Fprintf(w, "%s\n", l.ShortLink)
}
}
} | [
"func",
"ListLinks",
"(",
"c",
"web",
".",
"C",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"account",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"l",
":=",
"range",
"links",
"{",
"if",
"l",
".",
"Owner",
"==",
"account",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"l",
".",
"ShortLink",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ListLinks returns a list of the current user's links | [
"ListLinks",
"returns",
"a",
"list",
"of",
"the",
"current",
"user",
"s",
"links"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/example/service.go#L60-L67 |
149,435 | crewjam/saml | schema.go | Element | func (r *AuthnRequest) Element() *etree.Element {
el := etree.NewElement("samlp:AuthnRequest")
el.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion")
el.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol")
el.CreateAttr("ID", r.ID)
el.CreateAttr("Version", r.Version)
el.CreateAttr("IssueInstant", r.IssueInstant.Format(timeFormat))
if r.Destination != "" {
el.CreateAttr("Destination", r.Destination)
}
if r.Consent != "" {
el.CreateAttr("Consent", r.Consent)
}
if r.Issuer != nil {
el.AddChild(r.Issuer.Element())
}
if r.Signature != nil {
el.AddChild(r.Signature)
}
if r.Subject != nil {
el.AddChild(r.Subject.Element())
}
if r.NameIDPolicy != nil {
el.AddChild(r.NameIDPolicy.Element())
}
if r.Conditions != nil {
el.AddChild(r.Conditions.Element())
}
//if r.RequestedAuthnContext != nil {
// el.AddChild(r.RequestedAuthnContext.Element())
//}
//if r.Scoping != nil {
// el.AddChild(r.Scoping.Element())
//}
if r.ForceAuthn != nil {
el.CreateAttr("ForceAuthn", strconv.FormatBool(*r.ForceAuthn))
}
if r.IsPassive != nil {
el.CreateAttr("IsPassive", strconv.FormatBool(*r.IsPassive))
}
if r.AssertionConsumerServiceIndex != "" {
el.CreateAttr("AssertionConsumerServiceIndex", r.AssertionConsumerServiceIndex)
}
if r.AssertionConsumerServiceURL != "" {
el.CreateAttr("AssertionConsumerServiceURL", r.AssertionConsumerServiceURL)
}
if r.ProtocolBinding != "" {
el.CreateAttr("ProtocolBinding", r.ProtocolBinding)
}
if r.AttributeConsumingServiceIndex != "" {
el.CreateAttr("AttributeConsumingServiceIndex", r.AttributeConsumingServiceIndex)
}
if r.ProviderName != "" {
el.CreateAttr("ProviderName", r.ProviderName)
}
return el
} | go | func (r *AuthnRequest) Element() *etree.Element {
el := etree.NewElement("samlp:AuthnRequest")
el.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion")
el.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol")
el.CreateAttr("ID", r.ID)
el.CreateAttr("Version", r.Version)
el.CreateAttr("IssueInstant", r.IssueInstant.Format(timeFormat))
if r.Destination != "" {
el.CreateAttr("Destination", r.Destination)
}
if r.Consent != "" {
el.CreateAttr("Consent", r.Consent)
}
if r.Issuer != nil {
el.AddChild(r.Issuer.Element())
}
if r.Signature != nil {
el.AddChild(r.Signature)
}
if r.Subject != nil {
el.AddChild(r.Subject.Element())
}
if r.NameIDPolicy != nil {
el.AddChild(r.NameIDPolicy.Element())
}
if r.Conditions != nil {
el.AddChild(r.Conditions.Element())
}
//if r.RequestedAuthnContext != nil {
// el.AddChild(r.RequestedAuthnContext.Element())
//}
//if r.Scoping != nil {
// el.AddChild(r.Scoping.Element())
//}
if r.ForceAuthn != nil {
el.CreateAttr("ForceAuthn", strconv.FormatBool(*r.ForceAuthn))
}
if r.IsPassive != nil {
el.CreateAttr("IsPassive", strconv.FormatBool(*r.IsPassive))
}
if r.AssertionConsumerServiceIndex != "" {
el.CreateAttr("AssertionConsumerServiceIndex", r.AssertionConsumerServiceIndex)
}
if r.AssertionConsumerServiceURL != "" {
el.CreateAttr("AssertionConsumerServiceURL", r.AssertionConsumerServiceURL)
}
if r.ProtocolBinding != "" {
el.CreateAttr("ProtocolBinding", r.ProtocolBinding)
}
if r.AttributeConsumingServiceIndex != "" {
el.CreateAttr("AttributeConsumingServiceIndex", r.AttributeConsumingServiceIndex)
}
if r.ProviderName != "" {
el.CreateAttr("ProviderName", r.ProviderName)
}
return el
} | [
"func",
"(",
"r",
"*",
"AuthnRequest",
")",
"Element",
"(",
")",
"*",
"etree",
".",
"Element",
"{",
"el",
":=",
"etree",
".",
"NewElement",
"(",
"\"",
"\"",
")",
"\n",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"ID",
")",
"\n",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"Version",
")",
"\n",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"IssueInstant",
".",
"Format",
"(",
"timeFormat",
")",
")",
"\n",
"if",
"r",
".",
"Destination",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"Destination",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Consent",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"Consent",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Issuer",
"!=",
"nil",
"{",
"el",
".",
"AddChild",
"(",
"r",
".",
"Issuer",
".",
"Element",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Signature",
"!=",
"nil",
"{",
"el",
".",
"AddChild",
"(",
"r",
".",
"Signature",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Subject",
"!=",
"nil",
"{",
"el",
".",
"AddChild",
"(",
"r",
".",
"Subject",
".",
"Element",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"NameIDPolicy",
"!=",
"nil",
"{",
"el",
".",
"AddChild",
"(",
"r",
".",
"NameIDPolicy",
".",
"Element",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Conditions",
"!=",
"nil",
"{",
"el",
".",
"AddChild",
"(",
"r",
".",
"Conditions",
".",
"Element",
"(",
")",
")",
"\n",
"}",
"\n",
"//if r.RequestedAuthnContext != nil {",
"//\tel.AddChild(r.RequestedAuthnContext.Element())",
"//}",
"//if r.Scoping != nil {",
"//\tel.AddChild(r.Scoping.Element())",
"//}",
"if",
"r",
".",
"ForceAuthn",
"!=",
"nil",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"strconv",
".",
"FormatBool",
"(",
"*",
"r",
".",
"ForceAuthn",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"IsPassive",
"!=",
"nil",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"strconv",
".",
"FormatBool",
"(",
"*",
"r",
".",
"IsPassive",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"AssertionConsumerServiceIndex",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"AssertionConsumerServiceIndex",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"AssertionConsumerServiceURL",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"AssertionConsumerServiceURL",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"ProtocolBinding",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"ProtocolBinding",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"AttributeConsumingServiceIndex",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"AttributeConsumingServiceIndex",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"ProviderName",
"!=",
"\"",
"\"",
"{",
"el",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"r",
".",
"ProviderName",
")",
"\n",
"}",
"\n",
"return",
"el",
"\n",
"}"
] | // Element returns an etree.Element representing the object
// Element returns an etree.Element representing the object in XML form. | [
"Element",
"returns",
"an",
"etree",
".",
"Element",
"representing",
"the",
"object",
"Element",
"returns",
"an",
"etree",
".",
"Element",
"representing",
"the",
"object",
"in",
"XML",
"form",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/schema.go#L44-L100 |
149,436 | crewjam/saml | samlsp/middleware.go | ServeHTTP | func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == m.ServiceProvider.MetadataURL.Path {
buf, _ := xml.MarshalIndent(m.ServiceProvider.Metadata(), "", " ")
w.Header().Set("Content-Type", "application/samlmetadata+xml")
w.Write(buf)
return
}
if r.URL.Path == m.ServiceProvider.AcsURL.Path {
r.ParseForm()
assertion, err := m.ServiceProvider.ParseResponse(r, m.getPossibleRequestIDs(r))
if err != nil {
if parseErr, ok := err.(*saml.InvalidResponseError); ok {
m.ServiceProvider.Logger.Printf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s",
parseErr.Response, parseErr.Now, parseErr.PrivateErr)
}
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
m.Authorize(w, r, assertion)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
} | go | func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == m.ServiceProvider.MetadataURL.Path {
buf, _ := xml.MarshalIndent(m.ServiceProvider.Metadata(), "", " ")
w.Header().Set("Content-Type", "application/samlmetadata+xml")
w.Write(buf)
return
}
if r.URL.Path == m.ServiceProvider.AcsURL.Path {
r.ParseForm()
assertion, err := m.ServiceProvider.ParseResponse(r, m.getPossibleRequestIDs(r))
if err != nil {
if parseErr, ok := err.(*saml.InvalidResponseError); ok {
m.ServiceProvider.Logger.Printf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s",
parseErr.Response, parseErr.Now, parseErr.PrivateErr)
}
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
m.Authorize(w, r, assertion)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
} | [
"func",
"(",
"m",
"*",
"Middleware",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"URL",
".",
"Path",
"==",
"m",
".",
"ServiceProvider",
".",
"MetadataURL",
".",
"Path",
"{",
"buf",
",",
"_",
":=",
"xml",
".",
"MarshalIndent",
"(",
"m",
".",
"ServiceProvider",
".",
"Metadata",
"(",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Write",
"(",
"buf",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"URL",
".",
"Path",
"==",
"m",
".",
"ServiceProvider",
".",
"AcsURL",
".",
"Path",
"{",
"r",
".",
"ParseForm",
"(",
")",
"\n",
"assertion",
",",
"err",
":=",
"m",
".",
"ServiceProvider",
".",
"ParseResponse",
"(",
"r",
",",
"m",
".",
"getPossibleRequestIDs",
"(",
"r",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"parseErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"saml",
".",
"InvalidResponseError",
")",
";",
"ok",
"{",
"m",
".",
"ServiceProvider",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
",",
"parseErr",
".",
"Response",
",",
"parseErr",
".",
"Now",
",",
"parseErr",
".",
"PrivateErr",
")",
"\n",
"}",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusForbidden",
")",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"m",
".",
"Authorize",
"(",
"w",
",",
"r",
",",
"assertion",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"http",
".",
"NotFoundHandler",
"(",
")",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}"
] | // ServeHTTP implements http.Handler and serves the SAML-specific HTTP endpoints
// on the URIs specified by m.ServiceProvider.MetadataURL and
// m.ServiceProvider.AcsURL. | [
"ServeHTTP",
"implements",
"http",
".",
"Handler",
"and",
"serves",
"the",
"SAML",
"-",
"specific",
"HTTP",
"endpoints",
"on",
"the",
"URIs",
"specified",
"by",
"m",
".",
"ServiceProvider",
".",
"MetadataURL",
"and",
"m",
".",
"ServiceProvider",
".",
"AcsURL",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L67-L92 |
149,437 | crewjam/saml | samlsp/middleware.go | RequireAccount | func (m *Middleware) RequireAccount(handler http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if token := m.GetAuthorizationToken(r); token != nil {
r = r.WithContext(WithToken(r.Context(), token))
handler.ServeHTTP(w, r)
return
}
m.RequireAccountHandler(w, r)
}
return http.HandlerFunc(fn)
} | go | func (m *Middleware) RequireAccount(handler http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if token := m.GetAuthorizationToken(r); token != nil {
r = r.WithContext(WithToken(r.Context(), token))
handler.ServeHTTP(w, r)
return
}
m.RequireAccountHandler(w, r)
}
return http.HandlerFunc(fn)
} | [
"func",
"(",
"m",
"*",
"Middleware",
")",
"RequireAccount",
"(",
"handler",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"fn",
":=",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"token",
":=",
"m",
".",
"GetAuthorizationToken",
"(",
"r",
")",
";",
"token",
"!=",
"nil",
"{",
"r",
"=",
"r",
".",
"WithContext",
"(",
"WithToken",
"(",
"r",
".",
"Context",
"(",
")",
",",
"token",
")",
")",
"\n",
"handler",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"m",
".",
"RequireAccountHandler",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"fn",
")",
"\n",
"}"
] | // RequireAccount is HTTP middleware that requires that each request be
// associated with a valid session. If the request is not associated with a valid
// session, then rather than serve the request, the middlware redirects the user
// to start the SAML auth flow. | [
"RequireAccount",
"is",
"HTTP",
"middleware",
"that",
"requires",
"that",
"each",
"request",
"be",
"associated",
"with",
"a",
"valid",
"session",
".",
"If",
"the",
"request",
"is",
"not",
"associated",
"with",
"a",
"valid",
"session",
"then",
"rather",
"than",
"serve",
"the",
"request",
"the",
"middlware",
"redirects",
"the",
"user",
"to",
"start",
"the",
"SAML",
"auth",
"flow",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L98-L108 |
149,438 | crewjam/saml | samlsp/middleware.go | Authorize | func (m *Middleware) Authorize(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) {
secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key)
redirectURI := "/"
if relayState := r.Form.Get("RelayState"); relayState != "" {
stateValue := m.ClientState.GetState(r, relayState)
if stateValue == "" {
m.ServiceProvider.Logger.Printf("cannot find corresponding state: %s", relayState)
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
jwtParser := jwt.Parser{
ValidMethods: []string{jwtSigningMethod.Name},
}
state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) {
return secretBlock, nil
})
if err != nil || !state.Valid {
m.ServiceProvider.Logger.Printf("Cannot decode state JWT: %s (%s)", err, stateValue)
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
claims := state.Claims.(jwt.MapClaims)
redirectURI = claims["uri"].(string)
// delete the cookie
m.ClientState.DeleteState(w, r, relayState)
}
now := saml.TimeNow()
claims := AuthorizationToken{}
claims.Audience = m.ServiceProvider.Metadata().EntityID
claims.IssuedAt = now.Unix()
claims.ExpiresAt = now.Add(m.TokenMaxAge).Unix()
claims.NotBefore = now.Unix()
if sub := assertion.Subject; sub != nil {
if nameID := sub.NameID; nameID != nil {
claims.StandardClaims.Subject = nameID.Value
}
}
for _, attributeStatement := range assertion.AttributeStatements {
claims.Attributes = map[string][]string{}
for _, attr := range attributeStatement.Attributes {
claimName := attr.FriendlyName
if claimName == "" {
claimName = attr.Name
}
for _, value := range attr.Values {
claims.Attributes[claimName] = append(claims.Attributes[claimName], value.Value)
}
}
}
signedToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256,
claims).SignedString(secretBlock)
if err != nil {
panic(err)
}
m.ClientToken.SetToken(w, r, signedToken, m.TokenMaxAge)
http.Redirect(w, r, redirectURI, http.StatusFound)
} | go | func (m *Middleware) Authorize(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) {
secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key)
redirectURI := "/"
if relayState := r.Form.Get("RelayState"); relayState != "" {
stateValue := m.ClientState.GetState(r, relayState)
if stateValue == "" {
m.ServiceProvider.Logger.Printf("cannot find corresponding state: %s", relayState)
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
jwtParser := jwt.Parser{
ValidMethods: []string{jwtSigningMethod.Name},
}
state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) {
return secretBlock, nil
})
if err != nil || !state.Valid {
m.ServiceProvider.Logger.Printf("Cannot decode state JWT: %s (%s)", err, stateValue)
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
claims := state.Claims.(jwt.MapClaims)
redirectURI = claims["uri"].(string)
// delete the cookie
m.ClientState.DeleteState(w, r, relayState)
}
now := saml.TimeNow()
claims := AuthorizationToken{}
claims.Audience = m.ServiceProvider.Metadata().EntityID
claims.IssuedAt = now.Unix()
claims.ExpiresAt = now.Add(m.TokenMaxAge).Unix()
claims.NotBefore = now.Unix()
if sub := assertion.Subject; sub != nil {
if nameID := sub.NameID; nameID != nil {
claims.StandardClaims.Subject = nameID.Value
}
}
for _, attributeStatement := range assertion.AttributeStatements {
claims.Attributes = map[string][]string{}
for _, attr := range attributeStatement.Attributes {
claimName := attr.FriendlyName
if claimName == "" {
claimName = attr.Name
}
for _, value := range attr.Values {
claims.Attributes[claimName] = append(claims.Attributes[claimName], value.Value)
}
}
}
signedToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256,
claims).SignedString(secretBlock)
if err != nil {
panic(err)
}
m.ClientToken.SetToken(w, r, signedToken, m.TokenMaxAge)
http.Redirect(w, r, redirectURI, http.StatusFound)
} | [
"func",
"(",
"m",
"*",
"Middleware",
")",
"Authorize",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"assertion",
"*",
"saml",
".",
"Assertion",
")",
"{",
"secretBlock",
":=",
"x509",
".",
"MarshalPKCS1PrivateKey",
"(",
"m",
".",
"ServiceProvider",
".",
"Key",
")",
"\n\n",
"redirectURI",
":=",
"\"",
"\"",
"\n",
"if",
"relayState",
":=",
"r",
".",
"Form",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"relayState",
"!=",
"\"",
"\"",
"{",
"stateValue",
":=",
"m",
".",
"ClientState",
".",
"GetState",
"(",
"r",
",",
"relayState",
")",
"\n",
"if",
"stateValue",
"==",
"\"",
"\"",
"{",
"m",
".",
"ServiceProvider",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"relayState",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusForbidden",
")",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"jwtParser",
":=",
"jwt",
".",
"Parser",
"{",
"ValidMethods",
":",
"[",
"]",
"string",
"{",
"jwtSigningMethod",
".",
"Name",
"}",
",",
"}",
"\n",
"state",
",",
"err",
":=",
"jwtParser",
".",
"Parse",
"(",
"stateValue",
",",
"func",
"(",
"t",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"secretBlock",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"state",
".",
"Valid",
"{",
"m",
".",
"ServiceProvider",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
",",
"stateValue",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusForbidden",
")",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"claims",
":=",
"state",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n",
"redirectURI",
"=",
"claims",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n\n",
"// delete the cookie",
"m",
".",
"ClientState",
".",
"DeleteState",
"(",
"w",
",",
"r",
",",
"relayState",
")",
"\n",
"}",
"\n\n",
"now",
":=",
"saml",
".",
"TimeNow",
"(",
")",
"\n",
"claims",
":=",
"AuthorizationToken",
"{",
"}",
"\n",
"claims",
".",
"Audience",
"=",
"m",
".",
"ServiceProvider",
".",
"Metadata",
"(",
")",
".",
"EntityID",
"\n",
"claims",
".",
"IssuedAt",
"=",
"now",
".",
"Unix",
"(",
")",
"\n",
"claims",
".",
"ExpiresAt",
"=",
"now",
".",
"Add",
"(",
"m",
".",
"TokenMaxAge",
")",
".",
"Unix",
"(",
")",
"\n",
"claims",
".",
"NotBefore",
"=",
"now",
".",
"Unix",
"(",
")",
"\n",
"if",
"sub",
":=",
"assertion",
".",
"Subject",
";",
"sub",
"!=",
"nil",
"{",
"if",
"nameID",
":=",
"sub",
".",
"NameID",
";",
"nameID",
"!=",
"nil",
"{",
"claims",
".",
"StandardClaims",
".",
"Subject",
"=",
"nameID",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"attributeStatement",
":=",
"range",
"assertion",
".",
"AttributeStatements",
"{",
"claims",
".",
"Attributes",
"=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"attr",
":=",
"range",
"attributeStatement",
".",
"Attributes",
"{",
"claimName",
":=",
"attr",
".",
"FriendlyName",
"\n",
"if",
"claimName",
"==",
"\"",
"\"",
"{",
"claimName",
"=",
"attr",
".",
"Name",
"\n",
"}",
"\n",
"for",
"_",
",",
"value",
":=",
"range",
"attr",
".",
"Values",
"{",
"claims",
".",
"Attributes",
"[",
"claimName",
"]",
"=",
"append",
"(",
"claims",
".",
"Attributes",
"[",
"claimName",
"]",
",",
"value",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"signedToken",
",",
"err",
":=",
"jwt",
".",
"NewWithClaims",
"(",
"jwt",
".",
"SigningMethodHS256",
",",
"claims",
")",
".",
"SignedString",
"(",
"secretBlock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"m",
".",
"ClientToken",
".",
"SetToken",
"(",
"w",
",",
"r",
",",
"signedToken",
",",
"m",
".",
"TokenMaxAge",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirectURI",
",",
"http",
".",
"StatusFound",
")",
"\n",
"}"
] | // Authorize is invoked by ServeHTTP when we have a new, valid SAML assertion.
// It sets a cookie that contains a signed JWT containing the assertion attributes.
// It then redirects the user's browser to the original URL contained in RelayState. | [
"Authorize",
"is",
"invoked",
"by",
"ServeHTTP",
"when",
"we",
"have",
"a",
"new",
"valid",
"SAML",
"assertion",
".",
"It",
"sets",
"a",
"cookie",
"that",
"contains",
"a",
"signed",
"JWT",
"containing",
"the",
"assertion",
"attributes",
".",
"It",
"then",
"redirects",
"the",
"user",
"s",
"browser",
"to",
"the",
"original",
"URL",
"contained",
"in",
"RelayState",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L204-L265 |
149,439 | crewjam/saml | samlsp/middleware.go | GetAuthorizationToken | func (m *Middleware) GetAuthorizationToken(r *http.Request) *AuthorizationToken {
tokenStr := m.ClientToken.GetToken(r)
if tokenStr == "" {
return nil
}
tokenClaims := AuthorizationToken{}
token, err := jwt.ParseWithClaims(tokenStr, &tokenClaims, func(t *jwt.Token) (interface{}, error) {
secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key)
return secretBlock, nil
})
if err != nil || !token.Valid {
m.ServiceProvider.Logger.Printf("ERROR: invalid token: %s", err)
return nil
}
if err := tokenClaims.StandardClaims.Valid(); err != nil {
m.ServiceProvider.Logger.Printf("ERROR: invalid token claims: %s", err)
return nil
}
if tokenClaims.Audience != m.ServiceProvider.Metadata().EntityID {
m.ServiceProvider.Logger.Printf("ERROR: tokenClaims.Audience does not match EntityID")
return nil
}
return &tokenClaims
} | go | func (m *Middleware) GetAuthorizationToken(r *http.Request) *AuthorizationToken {
tokenStr := m.ClientToken.GetToken(r)
if tokenStr == "" {
return nil
}
tokenClaims := AuthorizationToken{}
token, err := jwt.ParseWithClaims(tokenStr, &tokenClaims, func(t *jwt.Token) (interface{}, error) {
secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key)
return secretBlock, nil
})
if err != nil || !token.Valid {
m.ServiceProvider.Logger.Printf("ERROR: invalid token: %s", err)
return nil
}
if err := tokenClaims.StandardClaims.Valid(); err != nil {
m.ServiceProvider.Logger.Printf("ERROR: invalid token claims: %s", err)
return nil
}
if tokenClaims.Audience != m.ServiceProvider.Metadata().EntityID {
m.ServiceProvider.Logger.Printf("ERROR: tokenClaims.Audience does not match EntityID")
return nil
}
return &tokenClaims
} | [
"func",
"(",
"m",
"*",
"Middleware",
")",
"GetAuthorizationToken",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"AuthorizationToken",
"{",
"tokenStr",
":=",
"m",
".",
"ClientToken",
".",
"GetToken",
"(",
"r",
")",
"\n",
"if",
"tokenStr",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"tokenClaims",
":=",
"AuthorizationToken",
"{",
"}",
"\n",
"token",
",",
"err",
":=",
"jwt",
".",
"ParseWithClaims",
"(",
"tokenStr",
",",
"&",
"tokenClaims",
",",
"func",
"(",
"t",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"secretBlock",
":=",
"x509",
".",
"MarshalPKCS1PrivateKey",
"(",
"m",
".",
"ServiceProvider",
".",
"Key",
")",
"\n",
"return",
"secretBlock",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"token",
".",
"Valid",
"{",
"m",
".",
"ServiceProvider",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tokenClaims",
".",
"StandardClaims",
".",
"Valid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"m",
".",
"ServiceProvider",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"tokenClaims",
".",
"Audience",
"!=",
"m",
".",
"ServiceProvider",
".",
"Metadata",
"(",
")",
".",
"EntityID",
"{",
"m",
".",
"ServiceProvider",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"&",
"tokenClaims",
"\n",
"}"
] | // GetAuthorizationToken is invoked by RequireAccount to determine if the request
// is already authorized or if the user's browser should be redirected to the
// SAML login flow. If the request is authorized, then the request context is
// ammended with a Context object. | [
"GetAuthorizationToken",
"is",
"invoked",
"by",
"RequireAccount",
"to",
"determine",
"if",
"the",
"request",
"is",
"already",
"authorized",
"or",
"if",
"the",
"user",
"s",
"browser",
"should",
"be",
"redirected",
"to",
"the",
"SAML",
"login",
"flow",
".",
"If",
"the",
"request",
"is",
"authorized",
"then",
"the",
"request",
"context",
"is",
"ammended",
"with",
"a",
"Context",
"object",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L279-L304 |
149,440 | crewjam/saml | samlidp/shortcut.go | HandleIDPInitiated | func (s *Server) HandleIDPInitiated(c web.C, w http.ResponseWriter, r *http.Request) {
shortcutName := c.URLParams["shortcut"]
shortcut := Shortcut{}
if err := s.Store.Get(fmt.Sprintf("/shortcuts/%s", shortcutName), &shortcut); err != nil {
s.logger.Printf("ERROR: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
relayState := ""
switch {
case shortcut.RelayState != nil:
relayState = *shortcut.RelayState
case shortcut.URISuffixAsRelayState:
relayState, _ = c.URLParams["*"]
}
s.idpConfigMu.RLock()
defer s.idpConfigMu.RUnlock()
s.IDP.ServeIDPInitiated(w, r, shortcut.ServiceProviderID, relayState)
} | go | func (s *Server) HandleIDPInitiated(c web.C, w http.ResponseWriter, r *http.Request) {
shortcutName := c.URLParams["shortcut"]
shortcut := Shortcut{}
if err := s.Store.Get(fmt.Sprintf("/shortcuts/%s", shortcutName), &shortcut); err != nil {
s.logger.Printf("ERROR: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
relayState := ""
switch {
case shortcut.RelayState != nil:
relayState = *shortcut.RelayState
case shortcut.URISuffixAsRelayState:
relayState, _ = c.URLParams["*"]
}
s.idpConfigMu.RLock()
defer s.idpConfigMu.RUnlock()
s.IDP.ServeIDPInitiated(w, r, shortcut.ServiceProviderID, relayState)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"HandleIDPInitiated",
"(",
"c",
"web",
".",
"C",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"shortcutName",
":=",
"c",
".",
"URLParams",
"[",
"\"",
"\"",
"]",
"\n",
"shortcut",
":=",
"Shortcut",
"{",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"Store",
".",
"Get",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"shortcutName",
")",
",",
"&",
"shortcut",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusInternalServerError",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"relayState",
":=",
"\"",
"\"",
"\n",
"switch",
"{",
"case",
"shortcut",
".",
"RelayState",
"!=",
"nil",
":",
"relayState",
"=",
"*",
"shortcut",
".",
"RelayState",
"\n",
"case",
"shortcut",
".",
"URISuffixAsRelayState",
":",
"relayState",
",",
"_",
"=",
"c",
".",
"URLParams",
"[",
"\"",
"\"",
"]",
"\n",
"}",
"\n\n",
"s",
".",
"idpConfigMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"idpConfigMu",
".",
"RUnlock",
"(",
")",
"\n",
"s",
".",
"IDP",
".",
"ServeIDPInitiated",
"(",
"w",
",",
"r",
",",
"shortcut",
".",
"ServiceProviderID",
",",
"relayState",
")",
"\n",
"}"
] | // HandleIDPInitiated handles a request for an IDP initiated login flow. It looks up
// the specified shortcut, generates the appropriate SAML assertion and redirects the
// user via the HTTP-POST binding to the service providers ACS URL. | [
"HandleIDPInitiated",
"handles",
"a",
"request",
"for",
"an",
"IDP",
"initiated",
"login",
"flow",
".",
"It",
"looks",
"up",
"the",
"specified",
"shortcut",
"generates",
"the",
"appropriate",
"SAML",
"assertion",
"and",
"redirects",
"the",
"user",
"via",
"the",
"HTTP",
"-",
"POST",
"binding",
"to",
"the",
"service",
"providers",
"ACS",
"URL",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/shortcut.go#L89-L109 |
149,441 | crewjam/saml | identity_provider.go | Handler | func (idp *IdentityProvider) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc(idp.MetadataURL.Path, idp.ServeMetadata)
mux.HandleFunc(idp.SSOURL.Path, idp.ServeSSO)
return mux
} | go | func (idp *IdentityProvider) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc(idp.MetadataURL.Path, idp.ServeMetadata)
mux.HandleFunc(idp.SSOURL.Path, idp.ServeSSO)
return mux
} | [
"func",
"(",
"idp",
"*",
"IdentityProvider",
")",
"Handler",
"(",
")",
"http",
".",
"Handler",
"{",
"mux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n",
"mux",
".",
"HandleFunc",
"(",
"idp",
".",
"MetadataURL",
".",
"Path",
",",
"idp",
".",
"ServeMetadata",
")",
"\n",
"mux",
".",
"HandleFunc",
"(",
"idp",
".",
"SSOURL",
".",
"Path",
",",
"idp",
".",
"ServeSSO",
")",
"\n",
"return",
"mux",
"\n",
"}"
] | // Handler returns an http.Handler that serves the metadata and SSO
// URLs | [
"Handler",
"returns",
"an",
"http",
".",
"Handler",
"that",
"serves",
"the",
"metadata",
"and",
"SSO",
"URLs"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/identity_provider.go#L168-L173 |
149,442 | crewjam/saml | identity_provider.go | MakeAssertionEl | func (req *IdpAuthnRequest) MakeAssertionEl() error {
keyPair := tls.Certificate{
Certificate: [][]byte{req.IDP.Certificate.Raw},
PrivateKey: req.IDP.Key,
Leaf: req.IDP.Certificate,
}
for _, cert := range req.IDP.Intermediates {
keyPair.Certificate = append(keyPair.Certificate, cert.Raw)
}
keyStore := dsig.TLSCertKeyStore(keyPair)
signatureMethod := req.IDP.SignatureMethod
if signatureMethod == "" {
signatureMethod = dsig.RSASHA1SignatureMethod
}
signingContext := dsig.NewDefaultSigningContext(keyStore)
signingContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList)
if err := signingContext.SetSignatureMethod(signatureMethod); err != nil {
return err
}
assertionEl := req.Assertion.Element()
signedAssertionEl, err := signingContext.SignEnveloped(assertionEl)
if err != nil {
return err
}
sigEl := signedAssertionEl.Child[len(signedAssertionEl.Child)-1]
req.Assertion.Signature = sigEl.(*etree.Element)
signedAssertionEl = req.Assertion.Element()
certBuf, err := req.getSPEncryptionCert()
if err == os.ErrNotExist {
req.AssertionEl = signedAssertionEl
return nil
} else if err != nil {
return err
}
var signedAssertionBuf []byte
{
doc := etree.NewDocument()
doc.SetRoot(signedAssertionEl)
signedAssertionBuf, err = doc.WriteToBytes()
if err != nil {
return err
}
}
encryptor := xmlenc.OAEP()
encryptor.BlockCipher = xmlenc.AES128CBC
encryptor.DigestMethod = &xmlenc.SHA1
encryptedDataEl, err := encryptor.Encrypt(certBuf, signedAssertionBuf)
if err != nil {
return err
}
encryptedDataEl.CreateAttr("Type", "http://www.w3.org/2001/04/xmlenc#Element")
encryptedAssertionEl := etree.NewElement("saml:EncryptedAssertion")
encryptedAssertionEl.AddChild(encryptedDataEl)
req.AssertionEl = encryptedAssertionEl
return nil
} | go | func (req *IdpAuthnRequest) MakeAssertionEl() error {
keyPair := tls.Certificate{
Certificate: [][]byte{req.IDP.Certificate.Raw},
PrivateKey: req.IDP.Key,
Leaf: req.IDP.Certificate,
}
for _, cert := range req.IDP.Intermediates {
keyPair.Certificate = append(keyPair.Certificate, cert.Raw)
}
keyStore := dsig.TLSCertKeyStore(keyPair)
signatureMethod := req.IDP.SignatureMethod
if signatureMethod == "" {
signatureMethod = dsig.RSASHA1SignatureMethod
}
signingContext := dsig.NewDefaultSigningContext(keyStore)
signingContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList)
if err := signingContext.SetSignatureMethod(signatureMethod); err != nil {
return err
}
assertionEl := req.Assertion.Element()
signedAssertionEl, err := signingContext.SignEnveloped(assertionEl)
if err != nil {
return err
}
sigEl := signedAssertionEl.Child[len(signedAssertionEl.Child)-1]
req.Assertion.Signature = sigEl.(*etree.Element)
signedAssertionEl = req.Assertion.Element()
certBuf, err := req.getSPEncryptionCert()
if err == os.ErrNotExist {
req.AssertionEl = signedAssertionEl
return nil
} else if err != nil {
return err
}
var signedAssertionBuf []byte
{
doc := etree.NewDocument()
doc.SetRoot(signedAssertionEl)
signedAssertionBuf, err = doc.WriteToBytes()
if err != nil {
return err
}
}
encryptor := xmlenc.OAEP()
encryptor.BlockCipher = xmlenc.AES128CBC
encryptor.DigestMethod = &xmlenc.SHA1
encryptedDataEl, err := encryptor.Encrypt(certBuf, signedAssertionBuf)
if err != nil {
return err
}
encryptedDataEl.CreateAttr("Type", "http://www.w3.org/2001/04/xmlenc#Element")
encryptedAssertionEl := etree.NewElement("saml:EncryptedAssertion")
encryptedAssertionEl.AddChild(encryptedDataEl)
req.AssertionEl = encryptedAssertionEl
return nil
} | [
"func",
"(",
"req",
"*",
"IdpAuthnRequest",
")",
"MakeAssertionEl",
"(",
")",
"error",
"{",
"keyPair",
":=",
"tls",
".",
"Certificate",
"{",
"Certificate",
":",
"[",
"]",
"[",
"]",
"byte",
"{",
"req",
".",
"IDP",
".",
"Certificate",
".",
"Raw",
"}",
",",
"PrivateKey",
":",
"req",
".",
"IDP",
".",
"Key",
",",
"Leaf",
":",
"req",
".",
"IDP",
".",
"Certificate",
",",
"}",
"\n",
"for",
"_",
",",
"cert",
":=",
"range",
"req",
".",
"IDP",
".",
"Intermediates",
"{",
"keyPair",
".",
"Certificate",
"=",
"append",
"(",
"keyPair",
".",
"Certificate",
",",
"cert",
".",
"Raw",
")",
"\n",
"}",
"\n",
"keyStore",
":=",
"dsig",
".",
"TLSCertKeyStore",
"(",
"keyPair",
")",
"\n\n",
"signatureMethod",
":=",
"req",
".",
"IDP",
".",
"SignatureMethod",
"\n",
"if",
"signatureMethod",
"==",
"\"",
"\"",
"{",
"signatureMethod",
"=",
"dsig",
".",
"RSASHA1SignatureMethod",
"\n",
"}",
"\n\n",
"signingContext",
":=",
"dsig",
".",
"NewDefaultSigningContext",
"(",
"keyStore",
")",
"\n",
"signingContext",
".",
"Canonicalizer",
"=",
"dsig",
".",
"MakeC14N10ExclusiveCanonicalizerWithPrefixList",
"(",
"canonicalizerPrefixList",
")",
"\n",
"if",
"err",
":=",
"signingContext",
".",
"SetSignatureMethod",
"(",
"signatureMethod",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"assertionEl",
":=",
"req",
".",
"Assertion",
".",
"Element",
"(",
")",
"\n\n",
"signedAssertionEl",
",",
"err",
":=",
"signingContext",
".",
"SignEnveloped",
"(",
"assertionEl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"sigEl",
":=",
"signedAssertionEl",
".",
"Child",
"[",
"len",
"(",
"signedAssertionEl",
".",
"Child",
")",
"-",
"1",
"]",
"\n",
"req",
".",
"Assertion",
".",
"Signature",
"=",
"sigEl",
".",
"(",
"*",
"etree",
".",
"Element",
")",
"\n",
"signedAssertionEl",
"=",
"req",
".",
"Assertion",
".",
"Element",
"(",
")",
"\n\n",
"certBuf",
",",
"err",
":=",
"req",
".",
"getSPEncryptionCert",
"(",
")",
"\n",
"if",
"err",
"==",
"os",
".",
"ErrNotExist",
"{",
"req",
".",
"AssertionEl",
"=",
"signedAssertionEl",
"\n",
"return",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"signedAssertionBuf",
"[",
"]",
"byte",
"\n",
"{",
"doc",
":=",
"etree",
".",
"NewDocument",
"(",
")",
"\n",
"doc",
".",
"SetRoot",
"(",
"signedAssertionEl",
")",
"\n",
"signedAssertionBuf",
",",
"err",
"=",
"doc",
".",
"WriteToBytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"encryptor",
":=",
"xmlenc",
".",
"OAEP",
"(",
")",
"\n",
"encryptor",
".",
"BlockCipher",
"=",
"xmlenc",
".",
"AES128CBC",
"\n",
"encryptor",
".",
"DigestMethod",
"=",
"&",
"xmlenc",
".",
"SHA1",
"\n",
"encryptedDataEl",
",",
"err",
":=",
"encryptor",
".",
"Encrypt",
"(",
"certBuf",
",",
"signedAssertionBuf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"encryptedDataEl",
".",
"CreateAttr",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"encryptedAssertionEl",
":=",
"etree",
".",
"NewElement",
"(",
"\"",
"\"",
")",
"\n",
"encryptedAssertionEl",
".",
"AddChild",
"(",
"encryptedDataEl",
")",
"\n",
"req",
".",
"AssertionEl",
"=",
"encryptedAssertionEl",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // MakeAssertionEl sets `AssertionEl` to a signed, possibly encrypted, version of `Assertion`. | [
"MakeAssertionEl",
"sets",
"AssertionEl",
"to",
"a",
"signed",
"possibly",
"encrypted",
"version",
"of",
"Assertion",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/identity_provider.go#L713-L778 |
149,443 | crewjam/saml | samlidp/service.go | GetServiceProvider | func (s *Server) GetServiceProvider(r *http.Request, serviceProviderID string) (*saml.EntityDescriptor, error) {
s.idpConfigMu.RLock()
defer s.idpConfigMu.RUnlock()
rv, ok := s.serviceProviders[serviceProviderID]
if !ok {
return nil, os.ErrNotExist
}
return rv, nil
} | go | func (s *Server) GetServiceProvider(r *http.Request, serviceProviderID string) (*saml.EntityDescriptor, error) {
s.idpConfigMu.RLock()
defer s.idpConfigMu.RUnlock()
rv, ok := s.serviceProviders[serviceProviderID]
if !ok {
return nil, os.ErrNotExist
}
return rv, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"GetServiceProvider",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"serviceProviderID",
"string",
")",
"(",
"*",
"saml",
".",
"EntityDescriptor",
",",
"error",
")",
"{",
"s",
".",
"idpConfigMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"idpConfigMu",
".",
"RUnlock",
"(",
")",
"\n",
"rv",
",",
"ok",
":=",
"s",
".",
"serviceProviders",
"[",
"serviceProviderID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"os",
".",
"ErrNotExist",
"\n",
"}",
"\n",
"return",
"rv",
",",
"nil",
"\n",
"}"
] | // GetServiceProvider returns the Service Provider metadata for the
// service provider ID, which is typically the service provider's
// metadata URL. If an appropriate service provider cannot be found then
// the returned error must be os.ErrNotExist. | [
"GetServiceProvider",
"returns",
"the",
"Service",
"Provider",
"metadata",
"for",
"the",
"service",
"provider",
"ID",
"which",
"is",
"typically",
"the",
"service",
"provider",
"s",
"metadata",
"URL",
".",
"If",
"an",
"appropriate",
"service",
"provider",
"cannot",
"be",
"found",
"then",
"the",
"returned",
"error",
"must",
"be",
"os",
".",
"ErrNotExist",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/service.go#L27-L35 |
149,444 | crewjam/saml | samlidp/service.go | initializeServices | func (s *Server) initializeServices() error {
serviceNames, err := s.Store.List("/services/")
if err != nil {
return err
}
for _, serviceName := range serviceNames {
service := Service{}
if err := s.Store.Get(fmt.Sprintf("/services/%s", serviceName), &service); err != nil {
return err
}
s.idpConfigMu.Lock()
s.serviceProviders[service.Metadata.EntityID] = &service.Metadata
s.idpConfigMu.Unlock()
}
return nil
} | go | func (s *Server) initializeServices() error {
serviceNames, err := s.Store.List("/services/")
if err != nil {
return err
}
for _, serviceName := range serviceNames {
service := Service{}
if err := s.Store.Get(fmt.Sprintf("/services/%s", serviceName), &service); err != nil {
return err
}
s.idpConfigMu.Lock()
s.serviceProviders[service.Metadata.EntityID] = &service.Metadata
s.idpConfigMu.Unlock()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"initializeServices",
"(",
")",
"error",
"{",
"serviceNames",
",",
"err",
":=",
"s",
".",
"Store",
".",
"List",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"serviceName",
":=",
"range",
"serviceNames",
"{",
"service",
":=",
"Service",
"{",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"Store",
".",
"Get",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
")",
",",
"&",
"service",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"idpConfigMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"serviceProviders",
"[",
"service",
".",
"Metadata",
".",
"EntityID",
"]",
"=",
"&",
"service",
".",
"Metadata",
"\n",
"s",
".",
"idpConfigMu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // initializeServices reads all the stored services and initializes the underlying
// identity provider to accept them. | [
"initializeServices",
"reads",
"all",
"the",
"stored",
"services",
"and",
"initializes",
"the",
"underlying",
"identity",
"provider",
"to",
"accept",
"them",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/service.go#L118-L134 |
149,445 | crewjam/saml | service_provider.go | Element | func (n NameIDFormat) Element() *etree.Element {
el := etree.NewElement("")
el.SetText(string(n))
return el
} | go | func (n NameIDFormat) Element() *etree.Element {
el := etree.NewElement("")
el.SetText(string(n))
return el
} | [
"func",
"(",
"n",
"NameIDFormat",
")",
"Element",
"(",
")",
"*",
"etree",
".",
"Element",
"{",
"el",
":=",
"etree",
".",
"NewElement",
"(",
"\"",
"\"",
")",
"\n",
"el",
".",
"SetText",
"(",
"string",
"(",
"n",
")",
")",
"\n",
"return",
"el",
"\n",
"}"
] | // Element returns an XML element representation of n. | [
"Element",
"returns",
"an",
"XML",
"element",
"representation",
"of",
"n",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L29-L33 |
149,446 | crewjam/saml | service_provider.go | Redirect | func (req *AuthnRequest) Redirect(relayState string) *url.URL {
w := &bytes.Buffer{}
w1 := base64.NewEncoder(base64.StdEncoding, w)
w2, _ := flate.NewWriter(w1, 9)
doc := etree.NewDocument()
doc.SetRoot(req.Element())
if _, err := doc.WriteTo(w2); err != nil {
panic(err)
}
w2.Close()
w1.Close()
rv, _ := url.Parse(req.Destination)
query := rv.Query()
query.Set("SAMLRequest", string(w.Bytes()))
if relayState != "" {
query.Set("RelayState", relayState)
}
rv.RawQuery = query.Encode()
return rv
} | go | func (req *AuthnRequest) Redirect(relayState string) *url.URL {
w := &bytes.Buffer{}
w1 := base64.NewEncoder(base64.StdEncoding, w)
w2, _ := flate.NewWriter(w1, 9)
doc := etree.NewDocument()
doc.SetRoot(req.Element())
if _, err := doc.WriteTo(w2); err != nil {
panic(err)
}
w2.Close()
w1.Close()
rv, _ := url.Parse(req.Destination)
query := rv.Query()
query.Set("SAMLRequest", string(w.Bytes()))
if relayState != "" {
query.Set("RelayState", relayState)
}
rv.RawQuery = query.Encode()
return rv
} | [
"func",
"(",
"req",
"*",
"AuthnRequest",
")",
"Redirect",
"(",
"relayState",
"string",
")",
"*",
"url",
".",
"URL",
"{",
"w",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"w1",
":=",
"base64",
".",
"NewEncoder",
"(",
"base64",
".",
"StdEncoding",
",",
"w",
")",
"\n",
"w2",
",",
"_",
":=",
"flate",
".",
"NewWriter",
"(",
"w1",
",",
"9",
")",
"\n",
"doc",
":=",
"etree",
".",
"NewDocument",
"(",
")",
"\n",
"doc",
".",
"SetRoot",
"(",
"req",
".",
"Element",
"(",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"doc",
".",
"WriteTo",
"(",
"w2",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"w2",
".",
"Close",
"(",
")",
"\n",
"w1",
".",
"Close",
"(",
")",
"\n\n",
"rv",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"req",
".",
"Destination",
")",
"\n\n",
"query",
":=",
"rv",
".",
"Query",
"(",
")",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"string",
"(",
"w",
".",
"Bytes",
"(",
")",
")",
")",
"\n",
"if",
"relayState",
"!=",
"\"",
"\"",
"{",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"relayState",
")",
"\n",
"}",
"\n",
"rv",
".",
"RawQuery",
"=",
"query",
".",
"Encode",
"(",
")",
"\n\n",
"return",
"rv",
"\n",
"}"
] | // Redirect returns a URL suitable for using the redirect binding with the request | [
"Redirect",
"returns",
"a",
"URL",
"suitable",
"for",
"using",
"the",
"redirect",
"binding",
"with",
"the",
"request"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L171-L193 |
149,447 | crewjam/saml | service_provider.go | getIDPSigningCerts | func (sp *ServiceProvider) getIDPSigningCerts() ([]*x509.Certificate, error) {
var certStrs []string
for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors {
for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors {
if keyDescriptor.Use == "signing" {
certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate)
}
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if len(certStrs) == 0 {
for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors {
for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate)
break
}
}
}
}
if len(certStrs) == 0 {
return nil, errors.New("cannot find any signing certificate in the IDP SSO descriptor")
}
var certs []*x509.Certificate
// cleanup whitespace
regex := regexp.MustCompile(`\s+`)
for _, certStr := range certStrs {
certStr = regex.ReplaceAllString(certStr, "")
certBytes, err := base64.StdEncoding.DecodeString(certStr)
if err != nil {
return nil, fmt.Errorf("cannot parse certificate: %s", err)
}
parsedCert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
certs = append(certs, parsedCert)
}
return certs, nil
} | go | func (sp *ServiceProvider) getIDPSigningCerts() ([]*x509.Certificate, error) {
var certStrs []string
for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors {
for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors {
if keyDescriptor.Use == "signing" {
certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate)
}
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if len(certStrs) == 0 {
for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors {
for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate)
break
}
}
}
}
if len(certStrs) == 0 {
return nil, errors.New("cannot find any signing certificate in the IDP SSO descriptor")
}
var certs []*x509.Certificate
// cleanup whitespace
regex := regexp.MustCompile(`\s+`)
for _, certStr := range certStrs {
certStr = regex.ReplaceAllString(certStr, "")
certBytes, err := base64.StdEncoding.DecodeString(certStr)
if err != nil {
return nil, fmt.Errorf("cannot parse certificate: %s", err)
}
parsedCert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
certs = append(certs, parsedCert)
}
return certs, nil
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"getIDPSigningCerts",
"(",
")",
"(",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"var",
"certStrs",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"idpSSODescriptor",
":=",
"range",
"sp",
".",
"IDPMetadata",
".",
"IDPSSODescriptors",
"{",
"for",
"_",
",",
"keyDescriptor",
":=",
"range",
"idpSSODescriptor",
".",
"KeyDescriptors",
"{",
"if",
"keyDescriptor",
".",
"Use",
"==",
"\"",
"\"",
"{",
"certStrs",
"=",
"append",
"(",
"certStrs",
",",
"keyDescriptor",
".",
"KeyInfo",
".",
"Certificate",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If there are no explicitly signing certs, just return the first",
"// non-empty cert we find.",
"if",
"len",
"(",
"certStrs",
")",
"==",
"0",
"{",
"for",
"_",
",",
"idpSSODescriptor",
":=",
"range",
"sp",
".",
"IDPMetadata",
".",
"IDPSSODescriptors",
"{",
"for",
"_",
",",
"keyDescriptor",
":=",
"range",
"idpSSODescriptor",
".",
"KeyDescriptors",
"{",
"if",
"keyDescriptor",
".",
"Use",
"==",
"\"",
"\"",
"&&",
"keyDescriptor",
".",
"KeyInfo",
".",
"Certificate",
"!=",
"\"",
"\"",
"{",
"certStrs",
"=",
"append",
"(",
"certStrs",
",",
"keyDescriptor",
".",
"KeyInfo",
".",
"Certificate",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"certStrs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"certs",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"\n\n",
"// cleanup whitespace",
"regex",
":=",
"regexp",
".",
"MustCompile",
"(",
"`\\s+`",
")",
"\n",
"for",
"_",
",",
"certStr",
":=",
"range",
"certStrs",
"{",
"certStr",
"=",
"regex",
".",
"ReplaceAllString",
"(",
"certStr",
",",
"\"",
"\"",
")",
"\n",
"certBytes",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"certStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"parsedCert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"certBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"certs",
"=",
"append",
"(",
"certs",
",",
"parsedCert",
")",
"\n",
"}",
"\n\n",
"return",
"certs",
",",
"nil",
"\n",
"}"
] | // getIDPSigningCerts returns the certificates which we can use to verify things
// signed by the IDP in PEM format, or nil if no such certificate is found. | [
"getIDPSigningCerts",
"returns",
"the",
"certificates",
"which",
"we",
"can",
"use",
"to",
"verify",
"things",
"signed",
"by",
"the",
"IDP",
"in",
"PEM",
"format",
"or",
"nil",
"if",
"no",
"such",
"certificate",
"is",
"found",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L210-L256 |
149,448 | crewjam/saml | service_provider.go | validateSigned | func (sp *ServiceProvider) validateSigned(responseEl *etree.Element) error {
haveSignature := false
// Some SAML responses have the signature on the Response object, and some on the Assertion
// object, and some on both. We will require that at least one signature be present and that
// all signatures be valid
sigEl, err := findChild(responseEl, "http://www.w3.org/2000/09/xmldsig#", "Signature")
if err != nil {
return err
}
if sigEl != nil {
if err = sp.validateSignature(responseEl); err != nil {
return fmt.Errorf("cannot validate signature on Response: %v", err)
}
haveSignature = true
}
assertionEl, err := findChild(responseEl, "urn:oasis:names:tc:SAML:2.0:assertion", "Assertion")
if err != nil {
return err
}
if assertionEl != nil {
sigEl, err := findChild(assertionEl, "http://www.w3.org/2000/09/xmldsig#", "Signature")
if err != nil {
return err
}
if sigEl != nil {
if err = sp.validateSignature(assertionEl); err != nil {
return fmt.Errorf("cannot validate signature on Response: %v", err)
}
haveSignature = true
}
}
if !haveSignature {
return errors.New("either the Response or Assertion must be signed")
}
return nil
} | go | func (sp *ServiceProvider) validateSigned(responseEl *etree.Element) error {
haveSignature := false
// Some SAML responses have the signature on the Response object, and some on the Assertion
// object, and some on both. We will require that at least one signature be present and that
// all signatures be valid
sigEl, err := findChild(responseEl, "http://www.w3.org/2000/09/xmldsig#", "Signature")
if err != nil {
return err
}
if sigEl != nil {
if err = sp.validateSignature(responseEl); err != nil {
return fmt.Errorf("cannot validate signature on Response: %v", err)
}
haveSignature = true
}
assertionEl, err := findChild(responseEl, "urn:oasis:names:tc:SAML:2.0:assertion", "Assertion")
if err != nil {
return err
}
if assertionEl != nil {
sigEl, err := findChild(assertionEl, "http://www.w3.org/2000/09/xmldsig#", "Signature")
if err != nil {
return err
}
if sigEl != nil {
if err = sp.validateSignature(assertionEl); err != nil {
return fmt.Errorf("cannot validate signature on Response: %v", err)
}
haveSignature = true
}
}
if !haveSignature {
return errors.New("either the Response or Assertion must be signed")
}
return nil
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"validateSigned",
"(",
"responseEl",
"*",
"etree",
".",
"Element",
")",
"error",
"{",
"haveSignature",
":=",
"false",
"\n\n",
"// Some SAML responses have the signature on the Response object, and some on the Assertion",
"// object, and some on both. We will require that at least one signature be present and that",
"// all signatures be valid",
"sigEl",
",",
"err",
":=",
"findChild",
"(",
"responseEl",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"sigEl",
"!=",
"nil",
"{",
"if",
"err",
"=",
"sp",
".",
"validateSignature",
"(",
"responseEl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"haveSignature",
"=",
"true",
"\n",
"}",
"\n\n",
"assertionEl",
",",
"err",
":=",
"findChild",
"(",
"responseEl",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"assertionEl",
"!=",
"nil",
"{",
"sigEl",
",",
"err",
":=",
"findChild",
"(",
"assertionEl",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"sigEl",
"!=",
"nil",
"{",
"if",
"err",
"=",
"sp",
".",
"validateSignature",
"(",
"assertionEl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"haveSignature",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"haveSignature",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateSigned returns a nil error iff each of the signatures on the Response and Assertion elements
// are valid and there is at least one signature. | [
"validateSigned",
"returns",
"a",
"nil",
"error",
"iff",
"each",
"of",
"the",
"signatures",
"on",
"the",
"Response",
"and",
"Assertion",
"elements",
"are",
"valid",
"and",
"there",
"is",
"at",
"least",
"one",
"signature",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L594-L632 |
149,449 | crewjam/saml | service_provider.go | validateSignature | func (sp *ServiceProvider) validateSignature(el *etree.Element) error {
certs, err := sp.getIDPSigningCerts()
if err != nil {
return err
}
certificateStore := dsig.MemoryX509CertificateStore{
Roots: certs,
}
validationContext := dsig.NewDefaultValidationContext(&certificateStore)
validationContext.IdAttribute = "ID"
if Clock != nil {
validationContext.Clock = Clock
}
// Some SAML responses contain a RSAKeyValue element. One of two things is happening here:
//
// (1) We're getting something signed by a key we already know about -- the public key
// of the signing cert provided in the metadata.
// (2) We're getting something signed by a key we *don't* know about, and which we have
// no ability to verify.
//
// The best course of action is to just remove the KeyInfo so that dsig falls back to
// verifying against the public key provided in the metadata.
if el.FindElement("./Signature/KeyInfo/X509Data/X509Certificate") == nil {
if sigEl := el.FindElement("./Signature"); sigEl != nil {
if keyInfo := sigEl.FindElement("KeyInfo"); keyInfo != nil {
sigEl.RemoveChild(keyInfo)
}
}
}
ctx, err := etreeutils.NSBuildParentContext(el)
if err != nil {
return err
}
ctx, err = ctx.SubContext(el)
if err != nil {
return err
}
el, err = etreeutils.NSDetatch(ctx, el)
if err != nil {
return err
}
_, err = validationContext.Validate(el)
return err
} | go | func (sp *ServiceProvider) validateSignature(el *etree.Element) error {
certs, err := sp.getIDPSigningCerts()
if err != nil {
return err
}
certificateStore := dsig.MemoryX509CertificateStore{
Roots: certs,
}
validationContext := dsig.NewDefaultValidationContext(&certificateStore)
validationContext.IdAttribute = "ID"
if Clock != nil {
validationContext.Clock = Clock
}
// Some SAML responses contain a RSAKeyValue element. One of two things is happening here:
//
// (1) We're getting something signed by a key we already know about -- the public key
// of the signing cert provided in the metadata.
// (2) We're getting something signed by a key we *don't* know about, and which we have
// no ability to verify.
//
// The best course of action is to just remove the KeyInfo so that dsig falls back to
// verifying against the public key provided in the metadata.
if el.FindElement("./Signature/KeyInfo/X509Data/X509Certificate") == nil {
if sigEl := el.FindElement("./Signature"); sigEl != nil {
if keyInfo := sigEl.FindElement("KeyInfo"); keyInfo != nil {
sigEl.RemoveChild(keyInfo)
}
}
}
ctx, err := etreeutils.NSBuildParentContext(el)
if err != nil {
return err
}
ctx, err = ctx.SubContext(el)
if err != nil {
return err
}
el, err = etreeutils.NSDetatch(ctx, el)
if err != nil {
return err
}
_, err = validationContext.Validate(el)
return err
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"validateSignature",
"(",
"el",
"*",
"etree",
".",
"Element",
")",
"error",
"{",
"certs",
",",
"err",
":=",
"sp",
".",
"getIDPSigningCerts",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"certificateStore",
":=",
"dsig",
".",
"MemoryX509CertificateStore",
"{",
"Roots",
":",
"certs",
",",
"}",
"\n\n",
"validationContext",
":=",
"dsig",
".",
"NewDefaultValidationContext",
"(",
"&",
"certificateStore",
")",
"\n",
"validationContext",
".",
"IdAttribute",
"=",
"\"",
"\"",
"\n",
"if",
"Clock",
"!=",
"nil",
"{",
"validationContext",
".",
"Clock",
"=",
"Clock",
"\n",
"}",
"\n\n",
"// Some SAML responses contain a RSAKeyValue element. One of two things is happening here:",
"//",
"// (1) We're getting something signed by a key we already know about -- the public key",
"// of the signing cert provided in the metadata.",
"// (2) We're getting something signed by a key we *don't* know about, and which we have",
"// no ability to verify.",
"//",
"// The best course of action is to just remove the KeyInfo so that dsig falls back to",
"// verifying against the public key provided in the metadata.",
"if",
"el",
".",
"FindElement",
"(",
"\"",
"\"",
")",
"==",
"nil",
"{",
"if",
"sigEl",
":=",
"el",
".",
"FindElement",
"(",
"\"",
"\"",
")",
";",
"sigEl",
"!=",
"nil",
"{",
"if",
"keyInfo",
":=",
"sigEl",
".",
"FindElement",
"(",
"\"",
"\"",
")",
";",
"keyInfo",
"!=",
"nil",
"{",
"sigEl",
".",
"RemoveChild",
"(",
"keyInfo",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"ctx",
",",
"err",
":=",
"etreeutils",
".",
"NSBuildParentContext",
"(",
"el",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ctx",
",",
"err",
"=",
"ctx",
".",
"SubContext",
"(",
"el",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"el",
",",
"err",
"=",
"etreeutils",
".",
"NSDetatch",
"(",
"ctx",
",",
"el",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"validationContext",
".",
"Validate",
"(",
"el",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // validateSignature returns nill iff the Signature embedded in the element is valid | [
"validateSignature",
"returns",
"nill",
"iff",
"the",
"Signature",
"embedded",
"in",
"the",
"element",
"is",
"valid"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L635-L683 |
149,450 | crewjam/saml | samlidp/samlidp.go | New | func New(opts Options) (*Server, error) {
metadataURL := opts.URL
metadataURL.Path = metadataURL.Path + "/metadata"
ssoURL := opts.URL
ssoURL.Path = ssoURL.Path + "/sso"
logr := opts.Logger
if logr == nil {
logr = logger.DefaultLogger
}
s := &Server{
serviceProviders: map[string]*saml.EntityDescriptor{},
IDP: saml.IdentityProvider{
Key: opts.Key,
Logger: logr,
Certificate: opts.Certificate,
MetadataURL: metadataURL,
SSOURL: ssoURL,
},
logger: logr,
Store: opts.Store,
}
s.IDP.SessionProvider = s
s.IDP.ServiceProviderProvider = s
if err := s.initializeServices(); err != nil {
return nil, err
}
s.InitializeHTTP()
return s, nil
} | go | func New(opts Options) (*Server, error) {
metadataURL := opts.URL
metadataURL.Path = metadataURL.Path + "/metadata"
ssoURL := opts.URL
ssoURL.Path = ssoURL.Path + "/sso"
logr := opts.Logger
if logr == nil {
logr = logger.DefaultLogger
}
s := &Server{
serviceProviders: map[string]*saml.EntityDescriptor{},
IDP: saml.IdentityProvider{
Key: opts.Key,
Logger: logr,
Certificate: opts.Certificate,
MetadataURL: metadataURL,
SSOURL: ssoURL,
},
logger: logr,
Store: opts.Store,
}
s.IDP.SessionProvider = s
s.IDP.ServiceProviderProvider = s
if err := s.initializeServices(); err != nil {
return nil, err
}
s.InitializeHTTP()
return s, nil
} | [
"func",
"New",
"(",
"opts",
"Options",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"metadataURL",
":=",
"opts",
".",
"URL",
"\n",
"metadataURL",
".",
"Path",
"=",
"metadataURL",
".",
"Path",
"+",
"\"",
"\"",
"\n",
"ssoURL",
":=",
"opts",
".",
"URL",
"\n",
"ssoURL",
".",
"Path",
"=",
"ssoURL",
".",
"Path",
"+",
"\"",
"\"",
"\n",
"logr",
":=",
"opts",
".",
"Logger",
"\n",
"if",
"logr",
"==",
"nil",
"{",
"logr",
"=",
"logger",
".",
"DefaultLogger",
"\n",
"}",
"\n\n",
"s",
":=",
"&",
"Server",
"{",
"serviceProviders",
":",
"map",
"[",
"string",
"]",
"*",
"saml",
".",
"EntityDescriptor",
"{",
"}",
",",
"IDP",
":",
"saml",
".",
"IdentityProvider",
"{",
"Key",
":",
"opts",
".",
"Key",
",",
"Logger",
":",
"logr",
",",
"Certificate",
":",
"opts",
".",
"Certificate",
",",
"MetadataURL",
":",
"metadataURL",
",",
"SSOURL",
":",
"ssoURL",
",",
"}",
",",
"logger",
":",
"logr",
",",
"Store",
":",
"opts",
".",
"Store",
",",
"}",
"\n\n",
"s",
".",
"IDP",
".",
"SessionProvider",
"=",
"s",
"\n",
"s",
".",
"IDP",
".",
"ServiceProviderProvider",
"=",
"s",
"\n\n",
"if",
"err",
":=",
"s",
".",
"initializeServices",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"s",
".",
"InitializeHTTP",
"(",
")",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // New returns a new Server | [
"New",
"returns",
"a",
"new",
"Server"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/samlidp.go#L46-L77 |
149,451 | crewjam/saml | samlsp/cookie.go | SetState | func (c ClientCookies) SetState(w http.ResponseWriter, r *http.Request, id string, value string) {
http.SetCookie(w, &http.Cookie{
Name: stateCookiePrefix + id,
Value: value,
MaxAge: int(saml.MaxIssueDelay.Seconds()),
HttpOnly: true,
Secure: c.Secure || r.URL.Scheme == "https",
Path: c.ServiceProvider.AcsURL.Path,
})
} | go | func (c ClientCookies) SetState(w http.ResponseWriter, r *http.Request, id string, value string) {
http.SetCookie(w, &http.Cookie{
Name: stateCookiePrefix + id,
Value: value,
MaxAge: int(saml.MaxIssueDelay.Seconds()),
HttpOnly: true,
Secure: c.Secure || r.URL.Scheme == "https",
Path: c.ServiceProvider.AcsURL.Path,
})
} | [
"func",
"(",
"c",
"ClientCookies",
")",
"SetState",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"id",
"string",
",",
"value",
"string",
")",
"{",
"http",
".",
"SetCookie",
"(",
"w",
",",
"&",
"http",
".",
"Cookie",
"{",
"Name",
":",
"stateCookiePrefix",
"+",
"id",
",",
"Value",
":",
"value",
",",
"MaxAge",
":",
"int",
"(",
"saml",
".",
"MaxIssueDelay",
".",
"Seconds",
"(",
")",
")",
",",
"HttpOnly",
":",
"true",
",",
"Secure",
":",
"c",
".",
"Secure",
"||",
"r",
".",
"URL",
".",
"Scheme",
"==",
"\"",
"\"",
",",
"Path",
":",
"c",
".",
"ServiceProvider",
".",
"AcsURL",
".",
"Path",
",",
"}",
")",
"\n",
"}"
] | // SetState stores the named state value by setting a cookie. | [
"SetState",
"stores",
"the",
"named",
"state",
"value",
"by",
"setting",
"a",
"cookie",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L37-L46 |
149,452 | crewjam/saml | samlsp/cookie.go | GetStates | func (c ClientCookies) GetStates(r *http.Request) map[string]string {
rv := map[string]string{}
for _, cookie := range r.Cookies() {
if !strings.HasPrefix(cookie.Name, stateCookiePrefix) {
continue
}
name := strings.TrimPrefix(cookie.Name, stateCookiePrefix)
rv[name] = cookie.Value
}
return rv
} | go | func (c ClientCookies) GetStates(r *http.Request) map[string]string {
rv := map[string]string{}
for _, cookie := range r.Cookies() {
if !strings.HasPrefix(cookie.Name, stateCookiePrefix) {
continue
}
name := strings.TrimPrefix(cookie.Name, stateCookiePrefix)
rv[name] = cookie.Value
}
return rv
} | [
"func",
"(",
"c",
"ClientCookies",
")",
"GetStates",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"rv",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"cookie",
":=",
"range",
"r",
".",
"Cookies",
"(",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"cookie",
".",
"Name",
",",
"stateCookiePrefix",
")",
"{",
"continue",
"\n",
"}",
"\n",
"name",
":=",
"strings",
".",
"TrimPrefix",
"(",
"cookie",
".",
"Name",
",",
"stateCookiePrefix",
")",
"\n",
"rv",
"[",
"name",
"]",
"=",
"cookie",
".",
"Value",
"\n",
"}",
"\n",
"return",
"rv",
"\n",
"}"
] | // GetStates returns the currently stored states by reading cookies. | [
"GetStates",
"returns",
"the",
"currently",
"stored",
"states",
"by",
"reading",
"cookies",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L49-L59 |
149,453 | crewjam/saml | samlsp/cookie.go | GetState | func (c ClientCookies) GetState(r *http.Request, id string) string {
stateCookie, err := r.Cookie(stateCookiePrefix + id)
if err != nil {
return ""
}
return stateCookie.Value
} | go | func (c ClientCookies) GetState(r *http.Request, id string) string {
stateCookie, err := r.Cookie(stateCookiePrefix + id)
if err != nil {
return ""
}
return stateCookie.Value
} | [
"func",
"(",
"c",
"ClientCookies",
")",
"GetState",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"id",
"string",
")",
"string",
"{",
"stateCookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"stateCookiePrefix",
"+",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"stateCookie",
".",
"Value",
"\n",
"}"
] | // GetState returns a single stored state by reading the cookies | [
"GetState",
"returns",
"a",
"single",
"stored",
"state",
"by",
"reading",
"the",
"cookies"
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L62-L68 |
149,454 | crewjam/saml | samlsp/cookie.go | DeleteState | func (c ClientCookies) DeleteState(w http.ResponseWriter, r *http.Request, id string) error {
cookie, err := r.Cookie(stateCookiePrefix + id)
if err != nil {
return err
}
cookie.Value = ""
cookie.Expires = time.Unix(1, 0) // past time as close to epoch as possible, but not zero time.Time{}
http.SetCookie(w, cookie)
return nil
} | go | func (c ClientCookies) DeleteState(w http.ResponseWriter, r *http.Request, id string) error {
cookie, err := r.Cookie(stateCookiePrefix + id)
if err != nil {
return err
}
cookie.Value = ""
cookie.Expires = time.Unix(1, 0) // past time as close to epoch as possible, but not zero time.Time{}
http.SetCookie(w, cookie)
return nil
} | [
"func",
"(",
"c",
"ClientCookies",
")",
"DeleteState",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"id",
"string",
")",
"error",
"{",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"stateCookiePrefix",
"+",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cookie",
".",
"Value",
"=",
"\"",
"\"",
"\n",
"cookie",
".",
"Expires",
"=",
"time",
".",
"Unix",
"(",
"1",
",",
"0",
")",
"// past time as close to epoch as possible, but not zero time.Time{}",
"\n",
"http",
".",
"SetCookie",
"(",
"w",
",",
"cookie",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteState removes the named stored state by clearing the corresponding cookie. | [
"DeleteState",
"removes",
"the",
"named",
"stored",
"state",
"by",
"clearing",
"the",
"corresponding",
"cookie",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L71-L80 |
149,455 | crewjam/saml | samlsp/cookie.go | SetToken | func (c ClientCookies) SetToken(w http.ResponseWriter, r *http.Request, value string, maxAge time.Duration) {
http.SetCookie(w, &http.Cookie{
Name: c.Name,
Domain: c.Domain,
Value: value,
MaxAge: int(maxAge.Seconds()),
HttpOnly: true,
Secure: c.Secure || r.URL.Scheme == "https",
Path: "/",
})
} | go | func (c ClientCookies) SetToken(w http.ResponseWriter, r *http.Request, value string, maxAge time.Duration) {
http.SetCookie(w, &http.Cookie{
Name: c.Name,
Domain: c.Domain,
Value: value,
MaxAge: int(maxAge.Seconds()),
HttpOnly: true,
Secure: c.Secure || r.URL.Scheme == "https",
Path: "/",
})
} | [
"func",
"(",
"c",
"ClientCookies",
")",
"SetToken",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"value",
"string",
",",
"maxAge",
"time",
".",
"Duration",
")",
"{",
"http",
".",
"SetCookie",
"(",
"w",
",",
"&",
"http",
".",
"Cookie",
"{",
"Name",
":",
"c",
".",
"Name",
",",
"Domain",
":",
"c",
".",
"Domain",
",",
"Value",
":",
"value",
",",
"MaxAge",
":",
"int",
"(",
"maxAge",
".",
"Seconds",
"(",
")",
")",
",",
"HttpOnly",
":",
"true",
",",
"Secure",
":",
"c",
".",
"Secure",
"||",
"r",
".",
"URL",
".",
"Scheme",
"==",
"\"",
"\"",
",",
"Path",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}"
] | // SetToken assigns the specified token by setting a cookie. | [
"SetToken",
"assigns",
"the",
"specified",
"token",
"by",
"setting",
"a",
"cookie",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L83-L93 |
149,456 | crewjam/saml | samlsp/cookie.go | GetToken | func (c ClientCookies) GetToken(r *http.Request) string {
cookie, err := r.Cookie(c.Name)
if err != nil {
return ""
}
return cookie.Value
} | go | func (c ClientCookies) GetToken(r *http.Request) string {
cookie, err := r.Cookie(c.Name)
if err != nil {
return ""
}
return cookie.Value
} | [
"func",
"(",
"c",
"ClientCookies",
")",
"GetToken",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"c",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"cookie",
".",
"Value",
"\n",
"}"
] | // GetToken returns the token by reading the cookie. | [
"GetToken",
"returns",
"the",
"token",
"by",
"reading",
"the",
"cookie",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L96-L102 |
149,457 | crewjam/saml | xmlenc/pubkey.go | OAEP | func OAEP() RSA {
return RSA{
BlockCipher: AES256CBC,
DigestMethod: SHA256,
algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p",
keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) {
return rsa.EncryptOAEP(e.DigestMethod.Hash(), RandReader, pubKey, plaintext, nil)
},
keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
return rsa.DecryptOAEP(e.DigestMethod.Hash(), RandReader, privKey, ciphertext, nil)
},
}
} | go | func OAEP() RSA {
return RSA{
BlockCipher: AES256CBC,
DigestMethod: SHA256,
algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p",
keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) {
return rsa.EncryptOAEP(e.DigestMethod.Hash(), RandReader, pubKey, plaintext, nil)
},
keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
return rsa.DecryptOAEP(e.DigestMethod.Hash(), RandReader, privKey, ciphertext, nil)
},
}
} | [
"func",
"OAEP",
"(",
")",
"RSA",
"{",
"return",
"RSA",
"{",
"BlockCipher",
":",
"AES256CBC",
",",
"DigestMethod",
":",
"SHA256",
",",
"algorithm",
":",
"\"",
"\"",
",",
"keyEncrypter",
":",
"func",
"(",
"e",
"RSA",
",",
"pubKey",
"*",
"rsa",
".",
"PublicKey",
",",
"plaintext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"rsa",
".",
"EncryptOAEP",
"(",
"e",
".",
"DigestMethod",
".",
"Hash",
"(",
")",
",",
"RandReader",
",",
"pubKey",
",",
"plaintext",
",",
"nil",
")",
"\n",
"}",
",",
"keyDecrypter",
":",
"func",
"(",
"e",
"RSA",
",",
"privKey",
"*",
"rsa",
".",
"PrivateKey",
",",
"ciphertext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"rsa",
".",
"DecryptOAEP",
"(",
"e",
".",
"DigestMethod",
".",
"Hash",
"(",
")",
",",
"RandReader",
",",
"privKey",
",",
"ciphertext",
",",
"nil",
")",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // OAEP returns a version of RSA that implements RSA in OAEP-MGF1P mode. By default
// the block cipher used is AES-256 CBC and the digest method is SHA-256. You can
// specify other ciphers and digest methods by assigning to BlockCipher or
// DigestMethod. | [
"OAEP",
"returns",
"a",
"version",
"of",
"RSA",
"that",
"implements",
"RSA",
"in",
"OAEP",
"-",
"MGF1P",
"mode",
".",
"By",
"default",
"the",
"block",
"cipher",
"used",
"is",
"AES",
"-",
"256",
"CBC",
"and",
"the",
"digest",
"method",
"is",
"SHA",
"-",
"256",
".",
"You",
"can",
"specify",
"other",
"ciphers",
"and",
"digest",
"methods",
"by",
"assigning",
"to",
"BlockCipher",
"or",
"DigestMethod",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/xmlenc/pubkey.go#L127-L139 |
149,458 | crewjam/saml | xmlenc/pubkey.go | PKCS1v15 | func PKCS1v15() RSA {
return RSA{
BlockCipher: AES256CBC,
DigestMethod: nil,
algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-1_5",
keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) {
return rsa.EncryptPKCS1v15(RandReader, pubKey, plaintext)
},
keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
return rsa.DecryptPKCS1v15(RandReader, privKey, ciphertext)
},
}
} | go | func PKCS1v15() RSA {
return RSA{
BlockCipher: AES256CBC,
DigestMethod: nil,
algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-1_5",
keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) {
return rsa.EncryptPKCS1v15(RandReader, pubKey, plaintext)
},
keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
return rsa.DecryptPKCS1v15(RandReader, privKey, ciphertext)
},
}
} | [
"func",
"PKCS1v15",
"(",
")",
"RSA",
"{",
"return",
"RSA",
"{",
"BlockCipher",
":",
"AES256CBC",
",",
"DigestMethod",
":",
"nil",
",",
"algorithm",
":",
"\"",
"\"",
",",
"keyEncrypter",
":",
"func",
"(",
"e",
"RSA",
",",
"pubKey",
"*",
"rsa",
".",
"PublicKey",
",",
"plaintext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"rsa",
".",
"EncryptPKCS1v15",
"(",
"RandReader",
",",
"pubKey",
",",
"plaintext",
")",
"\n",
"}",
",",
"keyDecrypter",
":",
"func",
"(",
"e",
"RSA",
",",
"privKey",
"*",
"rsa",
".",
"PrivateKey",
",",
"ciphertext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"rsa",
".",
"DecryptPKCS1v15",
"(",
"RandReader",
",",
"privKey",
",",
"ciphertext",
")",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // PKCS1v15 returns a version of RSA that implements RSA in PKCS1v15 mode. By default
// the block cipher used is AES-256 CBC. The DigestMethod field is ignored because PKCS1v15
// does not use a digest function. | [
"PKCS1v15",
"returns",
"a",
"version",
"of",
"RSA",
"that",
"implements",
"RSA",
"in",
"PKCS1v15",
"mode",
".",
"By",
"default",
"the",
"block",
"cipher",
"used",
"is",
"AES",
"-",
"256",
"CBC",
".",
"The",
"DigestMethod",
"field",
"is",
"ignored",
"because",
"PKCS1v15",
"does",
"not",
"use",
"a",
"digest",
"function",
"."
] | 724cb1c4fab17ba90fa24c4dde8f6f594d105071 | https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/xmlenc/pubkey.go#L144-L156 |
149,459 | tidwall/redcon | append.go | AppendUint | func AppendUint(b []byte, n uint64) []byte {
b = append(b, ':')
b = strconv.AppendUint(b, n, 10)
return append(b, '\r', '\n')
} | go | func AppendUint(b []byte, n uint64) []byte {
b = append(b, ':')
b = strconv.AppendUint(b, n, 10)
return append(b, '\r', '\n')
} | [
"func",
"AppendUint",
"(",
"b",
"[",
"]",
"byte",
",",
"n",
"uint64",
")",
"[",
"]",
"byte",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"':'",
")",
"\n",
"b",
"=",
"strconv",
".",
"AppendUint",
"(",
"b",
",",
"n",
",",
"10",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"'\\r'",
",",
"'\\n'",
")",
"\n",
"}"
] | // AppendUint appends a Redis protocol uint64 to the input bytes. | [
"AppendUint",
"appends",
"a",
"Redis",
"protocol",
"uint64",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L243-L247 |
149,460 | tidwall/redcon | append.go | AppendArray | func AppendArray(b []byte, n int) []byte {
return appendPrefix(b, '*', int64(n))
} | go | func AppendArray(b []byte, n int) []byte {
return appendPrefix(b, '*', int64(n))
} | [
"func",
"AppendArray",
"(",
"b",
"[",
"]",
"byte",
",",
"n",
"int",
")",
"[",
"]",
"byte",
"{",
"return",
"appendPrefix",
"(",
"b",
",",
"'*'",
",",
"int64",
"(",
"n",
")",
")",
"\n",
"}"
] | // AppendArray appends a Redis protocol array to the input bytes. | [
"AppendArray",
"appends",
"a",
"Redis",
"protocol",
"array",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L255-L257 |
149,461 | tidwall/redcon | append.go | AppendBulk | func AppendBulk(b []byte, bulk []byte) []byte {
b = appendPrefix(b, '$', int64(len(bulk)))
b = append(b, bulk...)
return append(b, '\r', '\n')
} | go | func AppendBulk(b []byte, bulk []byte) []byte {
b = appendPrefix(b, '$', int64(len(bulk)))
b = append(b, bulk...)
return append(b, '\r', '\n')
} | [
"func",
"AppendBulk",
"(",
"b",
"[",
"]",
"byte",
",",
"bulk",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"b",
"=",
"appendPrefix",
"(",
"b",
",",
"'$'",
",",
"int64",
"(",
"len",
"(",
"bulk",
")",
")",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"bulk",
"...",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"'\\r'",
",",
"'\\n'",
")",
"\n",
"}"
] | // AppendBulk appends a Redis protocol bulk byte slice to the input bytes. | [
"AppendBulk",
"appends",
"a",
"Redis",
"protocol",
"bulk",
"byte",
"slice",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L260-L264 |
149,462 | tidwall/redcon | append.go | AppendBulkString | func AppendBulkString(b []byte, bulk string) []byte {
b = appendPrefix(b, '$', int64(len(bulk)))
b = append(b, bulk...)
return append(b, '\r', '\n')
} | go | func AppendBulkString(b []byte, bulk string) []byte {
b = appendPrefix(b, '$', int64(len(bulk)))
b = append(b, bulk...)
return append(b, '\r', '\n')
} | [
"func",
"AppendBulkString",
"(",
"b",
"[",
"]",
"byte",
",",
"bulk",
"string",
")",
"[",
"]",
"byte",
"{",
"b",
"=",
"appendPrefix",
"(",
"b",
",",
"'$'",
",",
"int64",
"(",
"len",
"(",
"bulk",
")",
")",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"bulk",
"...",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"'\\r'",
",",
"'\\n'",
")",
"\n",
"}"
] | // AppendBulkString appends a Redis protocol bulk string to the input bytes. | [
"AppendBulkString",
"appends",
"a",
"Redis",
"protocol",
"bulk",
"string",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L267-L271 |
149,463 | tidwall/redcon | append.go | AppendString | func AppendString(b []byte, s string) []byte {
b = append(b, '+')
b = append(b, stripNewlines(s)...)
return append(b, '\r', '\n')
} | go | func AppendString(b []byte, s string) []byte {
b = append(b, '+')
b = append(b, stripNewlines(s)...)
return append(b, '\r', '\n')
} | [
"func",
"AppendString",
"(",
"b",
"[",
"]",
"byte",
",",
"s",
"string",
")",
"[",
"]",
"byte",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'+'",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"stripNewlines",
"(",
"s",
")",
"...",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"'\\r'",
",",
"'\\n'",
")",
"\n",
"}"
] | // AppendString appends a Redis protocol string to the input bytes. | [
"AppendString",
"appends",
"a",
"Redis",
"protocol",
"string",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L274-L278 |
149,464 | tidwall/redcon | append.go | AppendError | func AppendError(b []byte, s string) []byte {
b = append(b, '-')
b = append(b, stripNewlines(s)...)
return append(b, '\r', '\n')
} | go | func AppendError(b []byte, s string) []byte {
b = append(b, '-')
b = append(b, stripNewlines(s)...)
return append(b, '\r', '\n')
} | [
"func",
"AppendError",
"(",
"b",
"[",
"]",
"byte",
",",
"s",
"string",
")",
"[",
"]",
"byte",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'-'",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"stripNewlines",
"(",
"s",
")",
"...",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"'\\r'",
",",
"'\\n'",
")",
"\n",
"}"
] | // AppendError appends a Redis protocol error to the input bytes. | [
"AppendError",
"appends",
"a",
"Redis",
"protocol",
"error",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L281-L285 |
149,465 | tidwall/redcon | append.go | AppendTile38 | func AppendTile38(b []byte, data []byte) []byte {
b = append(b, '$')
b = strconv.AppendInt(b, int64(len(data)), 10)
b = append(b, ' ')
b = append(b, data...)
return append(b, '\r', '\n')
} | go | func AppendTile38(b []byte, data []byte) []byte {
b = append(b, '$')
b = strconv.AppendInt(b, int64(len(data)), 10)
b = append(b, ' ')
b = append(b, data...)
return append(b, '\r', '\n')
} | [
"func",
"AppendTile38",
"(",
"b",
"[",
"]",
"byte",
",",
"data",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'$'",
")",
"\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"len",
"(",
"data",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"' '",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"data",
"...",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"'\\r'",
",",
"'\\n'",
")",
"\n",
"}"
] | // AppendTile38 appends a Tile38 message to the input bytes. | [
"AppendTile38",
"appends",
"a",
"Tile38",
"message",
"to",
"the",
"input",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L303-L309 |
149,466 | tidwall/redcon | redcon.go | NewServer | func NewServer(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) *Server {
return NewServerNetwork("tcp", addr, handler, accept, closed)
} | go | func NewServer(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) *Server {
return NewServerNetwork("tcp", addr, handler, accept, closed)
} | [
"func",
"NewServer",
"(",
"addr",
"string",
",",
"handler",
"func",
"(",
"conn",
"Conn",
",",
"cmd",
"Command",
")",
",",
"accept",
"func",
"(",
"conn",
"Conn",
")",
"bool",
",",
"closed",
"func",
"(",
"conn",
"Conn",
",",
"err",
"error",
")",
",",
")",
"*",
"Server",
"{",
"return",
"NewServerNetwork",
"(",
"\"",
"\"",
",",
"addr",
",",
"handler",
",",
"accept",
",",
"closed",
")",
"\n",
"}"
] | // NewServer returns a new Redcon server configured on "tcp" network net. | [
"NewServer",
"returns",
"a",
"new",
"Redcon",
"server",
"configured",
"on",
"tcp",
"network",
"net",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L96-L102 |
149,467 | tidwall/redcon | redcon.go | NewServerTLS | func NewServerTLS(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
config *tls.Config,
) *TLSServer {
return NewServerNetworkTLS("tcp", addr, handler, accept, closed, config)
} | go | func NewServerTLS(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
config *tls.Config,
) *TLSServer {
return NewServerNetworkTLS("tcp", addr, handler, accept, closed, config)
} | [
"func",
"NewServerTLS",
"(",
"addr",
"string",
",",
"handler",
"func",
"(",
"conn",
"Conn",
",",
"cmd",
"Command",
")",
",",
"accept",
"func",
"(",
"conn",
"Conn",
")",
"bool",
",",
"closed",
"func",
"(",
"conn",
"Conn",
",",
"err",
"error",
")",
",",
"config",
"*",
"tls",
".",
"Config",
",",
")",
"*",
"TLSServer",
"{",
"return",
"NewServerNetworkTLS",
"(",
"\"",
"\"",
",",
"addr",
",",
"handler",
",",
"accept",
",",
"closed",
",",
"config",
")",
"\n",
"}"
] | // NewServerTLS returns a new Redcon TLS server configured on "tcp" network net. | [
"NewServerTLS",
"returns",
"a",
"new",
"Redcon",
"TLS",
"server",
"configured",
"on",
"tcp",
"network",
"net",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L105-L112 |
149,468 | tidwall/redcon | redcon.go | Close | func (s *Server) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.ln == nil {
return errors.New("not serving")
}
s.done = true
return s.ln.Close()
} | go | func (s *Server) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.ln == nil {
return errors.New("not serving")
}
s.done = true
return s.ln.Close()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Close",
"(",
")",
"error",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"ln",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
".",
"done",
"=",
"true",
"\n",
"return",
"s",
".",
"ln",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close stops listening on the TCP address.
// Already Accepted connections will be closed. | [
"Close",
"stops",
"listening",
"on",
"the",
"TCP",
"address",
".",
"Already",
"Accepted",
"connections",
"will",
"be",
"closed",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L166-L174 |
149,469 | tidwall/redcon | redcon.go | Serve | func Serve(ln net.Listener,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) error {
s := &Server{
net: ln.Addr().Network(),
laddr: ln.Addr().String(),
ln: ln,
handler: handler,
accept: accept,
closed: closed,
conns: make(map[*conn]bool),
}
return serve(s)
} | go | func Serve(ln net.Listener,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) error {
s := &Server{
net: ln.Addr().Network(),
laddr: ln.Addr().String(),
ln: ln,
handler: handler,
accept: accept,
closed: closed,
conns: make(map[*conn]bool),
}
return serve(s)
} | [
"func",
"Serve",
"(",
"ln",
"net",
".",
"Listener",
",",
"handler",
"func",
"(",
"conn",
"Conn",
",",
"cmd",
"Command",
")",
",",
"accept",
"func",
"(",
"conn",
"Conn",
")",
"bool",
",",
"closed",
"func",
"(",
"conn",
"Conn",
",",
"err",
"error",
")",
",",
")",
"error",
"{",
"s",
":=",
"&",
"Server",
"{",
"net",
":",
"ln",
".",
"Addr",
"(",
")",
".",
"Network",
"(",
")",
",",
"laddr",
":",
"ln",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
",",
"ln",
":",
"ln",
",",
"handler",
":",
"handler",
",",
"accept",
":",
"accept",
",",
"closed",
":",
"closed",
",",
"conns",
":",
"make",
"(",
"map",
"[",
"*",
"conn",
"]",
"bool",
")",
",",
"}",
"\n\n",
"return",
"serve",
"(",
"s",
")",
"\n",
"}"
] | // Serve creates a new server and serves with the given net.Listener. | [
"Serve",
"creates",
"a",
"new",
"server",
"and",
"serves",
"with",
"the",
"given",
"net",
".",
"Listener",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L204-L220 |
149,470 | tidwall/redcon | redcon.go | ListenAndServe | func ListenAndServe(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) error {
return ListenAndServeNetwork("tcp", addr, handler, accept, closed)
} | go | func ListenAndServe(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
) error {
return ListenAndServeNetwork("tcp", addr, handler, accept, closed)
} | [
"func",
"ListenAndServe",
"(",
"addr",
"string",
",",
"handler",
"func",
"(",
"conn",
"Conn",
",",
"cmd",
"Command",
")",
",",
"accept",
"func",
"(",
"conn",
"Conn",
")",
"bool",
",",
"closed",
"func",
"(",
"conn",
"Conn",
",",
"err",
"error",
")",
",",
")",
"error",
"{",
"return",
"ListenAndServeNetwork",
"(",
"\"",
"\"",
",",
"addr",
",",
"handler",
",",
"accept",
",",
"closed",
")",
"\n",
"}"
] | // ListenAndServe creates a new server and binds to addr configured on "tcp" network net. | [
"ListenAndServe",
"creates",
"a",
"new",
"server",
"and",
"binds",
"to",
"addr",
"configured",
"on",
"tcp",
"network",
"net",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L223-L229 |
149,471 | tidwall/redcon | redcon.go | ListenAndServeTLS | func ListenAndServeTLS(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
config *tls.Config,
) error {
return ListenAndServeNetworkTLS("tcp", addr, handler, accept, closed, config)
} | go | func ListenAndServeTLS(addr string,
handler func(conn Conn, cmd Command),
accept func(conn Conn) bool,
closed func(conn Conn, err error),
config *tls.Config,
) error {
return ListenAndServeNetworkTLS("tcp", addr, handler, accept, closed, config)
} | [
"func",
"ListenAndServeTLS",
"(",
"addr",
"string",
",",
"handler",
"func",
"(",
"conn",
"Conn",
",",
"cmd",
"Command",
")",
",",
"accept",
"func",
"(",
"conn",
"Conn",
")",
"bool",
",",
"closed",
"func",
"(",
"conn",
"Conn",
",",
"err",
"error",
")",
",",
"config",
"*",
"tls",
".",
"Config",
",",
")",
"error",
"{",
"return",
"ListenAndServeNetworkTLS",
"(",
"\"",
"\"",
",",
"addr",
",",
"handler",
",",
"accept",
",",
"closed",
",",
"config",
")",
"\n",
"}"
] | // ListenAndServeTLS creates a new TLS server and binds to addr configured on "tcp" network net. | [
"ListenAndServeTLS",
"creates",
"a",
"new",
"TLS",
"server",
"and",
"binds",
"to",
"addr",
"configured",
"on",
"tcp",
"network",
"net",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L232-L239 |
149,472 | tidwall/redcon | redcon.go | ListenServeAndSignal | func (s *Server) ListenServeAndSignal(signal chan error) error {
ln, err := net.Listen(s.net, s.laddr)
if err != nil {
if signal != nil {
signal <- err
}
return err
}
s.ln = ln
if signal != nil {
signal <- nil
}
return serve(s)
} | go | func (s *Server) ListenServeAndSignal(signal chan error) error {
ln, err := net.Listen(s.net, s.laddr)
if err != nil {
if signal != nil {
signal <- err
}
return err
}
s.ln = ln
if signal != nil {
signal <- nil
}
return serve(s)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ListenServeAndSignal",
"(",
"signal",
"chan",
"error",
")",
"error",
"{",
"ln",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"s",
".",
"net",
",",
"s",
".",
"laddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"signal",
"!=",
"nil",
"{",
"signal",
"<-",
"err",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"ln",
"=",
"ln",
"\n",
"if",
"signal",
"!=",
"nil",
"{",
"signal",
"<-",
"nil",
"\n",
"}",
"\n",
"return",
"serve",
"(",
"s",
")",
"\n",
"}"
] | // ListenServeAndSignal serves incoming connections and passes nil or error
// when listening. signal can be nil. | [
"ListenServeAndSignal",
"serves",
"incoming",
"connections",
"and",
"passes",
"nil",
"or",
"error",
"when",
"listening",
".",
"signal",
"can",
"be",
"nil",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L266-L279 |
149,473 | tidwall/redcon | redcon.go | Serve | func (s *Server) Serve(ln net.Listener) error {
s.ln = ln
s.net = ln.Addr().Network()
s.laddr = ln.Addr().String()
return serve(s)
} | go | func (s *Server) Serve(ln net.Listener) error {
s.ln = ln
s.net = ln.Addr().Network()
s.laddr = ln.Addr().String()
return serve(s)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Serve",
"(",
"ln",
"net",
".",
"Listener",
")",
"error",
"{",
"s",
".",
"ln",
"=",
"ln",
"\n",
"s",
".",
"net",
"=",
"ln",
".",
"Addr",
"(",
")",
".",
"Network",
"(",
")",
"\n",
"s",
".",
"laddr",
"=",
"ln",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"return",
"serve",
"(",
"s",
")",
"\n",
"}"
] | // Serve serves incoming connections with the given net.Listener. | [
"Serve",
"serves",
"incoming",
"connections",
"with",
"the",
"given",
"net",
".",
"Listener",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L282-L287 |
149,474 | tidwall/redcon | redcon.go | handle | func handle(s *Server, c *conn) {
var err error
defer func() {
if err != errDetached {
// do not close the connection when a detach is detected.
c.conn.Close()
}
func() {
// remove the conn from the server
s.mu.Lock()
defer s.mu.Unlock()
delete(s.conns, c)
if s.closed != nil {
if err == io.EOF {
err = nil
}
s.closed(c, err)
}
}()
}()
err = func() error {
// read commands and feed back to the client
for {
// read pipeline commands
cmds, err := c.rd.readCommands(nil)
if err != nil {
if err, ok := err.(*errProtocol); ok {
// All protocol errors should attempt a response to
// the client. Ignore write errors.
c.wr.WriteError("ERR " + err.Error())
c.wr.Flush()
}
return err
}
c.cmds = cmds
for len(c.cmds) > 0 {
cmd := c.cmds[0]
if len(c.cmds) == 1 {
c.cmds = nil
} else {
c.cmds = c.cmds[1:]
}
s.handler(c, cmd)
}
if c.detached {
// client has been detached
return errDetached
}
if c.closed {
return nil
}
if err := c.wr.Flush(); err != nil {
return err
}
}
}()
} | go | func handle(s *Server, c *conn) {
var err error
defer func() {
if err != errDetached {
// do not close the connection when a detach is detected.
c.conn.Close()
}
func() {
// remove the conn from the server
s.mu.Lock()
defer s.mu.Unlock()
delete(s.conns, c)
if s.closed != nil {
if err == io.EOF {
err = nil
}
s.closed(c, err)
}
}()
}()
err = func() error {
// read commands and feed back to the client
for {
// read pipeline commands
cmds, err := c.rd.readCommands(nil)
if err != nil {
if err, ok := err.(*errProtocol); ok {
// All protocol errors should attempt a response to
// the client. Ignore write errors.
c.wr.WriteError("ERR " + err.Error())
c.wr.Flush()
}
return err
}
c.cmds = cmds
for len(c.cmds) > 0 {
cmd := c.cmds[0]
if len(c.cmds) == 1 {
c.cmds = nil
} else {
c.cmds = c.cmds[1:]
}
s.handler(c, cmd)
}
if c.detached {
// client has been detached
return errDetached
}
if c.closed {
return nil
}
if err := c.wr.Flush(); err != nil {
return err
}
}
}()
} | [
"func",
"handle",
"(",
"s",
"*",
"Server",
",",
"c",
"*",
"conn",
")",
"{",
"var",
"err",
"error",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"errDetached",
"{",
"// do not close the connection when a detach is detected.",
"c",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"func",
"(",
")",
"{",
"// remove the conn from the server",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"conns",
",",
"c",
")",
"\n",
"if",
"s",
".",
"closed",
"!=",
"nil",
"{",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"s",
".",
"closed",
"(",
"c",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"err",
"=",
"func",
"(",
")",
"error",
"{",
"// read commands and feed back to the client",
"for",
"{",
"// read pipeline commands",
"cmds",
",",
"err",
":=",
"c",
".",
"rd",
".",
"readCommands",
"(",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"errProtocol",
")",
";",
"ok",
"{",
"// All protocol errors should attempt a response to",
"// the client. Ignore write errors.",
"c",
".",
"wr",
".",
"WriteError",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"c",
".",
"wr",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"cmds",
"=",
"cmds",
"\n",
"for",
"len",
"(",
"c",
".",
"cmds",
")",
">",
"0",
"{",
"cmd",
":=",
"c",
".",
"cmds",
"[",
"0",
"]",
"\n",
"if",
"len",
"(",
"c",
".",
"cmds",
")",
"==",
"1",
"{",
"c",
".",
"cmds",
"=",
"nil",
"\n",
"}",
"else",
"{",
"c",
".",
"cmds",
"=",
"c",
".",
"cmds",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"s",
".",
"handler",
"(",
"c",
",",
"cmd",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"detached",
"{",
"// client has been detached",
"return",
"errDetached",
"\n",
"}",
"\n",
"if",
"c",
".",
"closed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"wr",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // handle manages the server connection. | [
"handle",
"manages",
"the",
"server",
"connection",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L350-L407 |
149,475 | tidwall/redcon | redcon.go | BaseWriter | func BaseWriter(c Conn) *Writer {
if c, ok := c.(*conn); ok {
return c.wr
}
return nil
} | go | func BaseWriter(c Conn) *Writer {
if c, ok := c.(*conn); ok {
return c.wr
}
return nil
} | [
"func",
"BaseWriter",
"(",
"c",
"Conn",
")",
"*",
"Writer",
"{",
"if",
"c",
",",
"ok",
":=",
"c",
".",
"(",
"*",
"conn",
")",
";",
"ok",
"{",
"return",
"c",
".",
"wr",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // BaseWriter returns the underlying connection writer, if any | [
"BaseWriter",
"returns",
"the",
"underlying",
"connection",
"writer",
"if",
"any"
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L452-L457 |
149,476 | tidwall/redcon | redcon.go | ReadCommand | func (dc *detachedConn) ReadCommand() (Command, error) {
if dc.closed {
return Command{}, errors.New("closed")
}
if len(dc.cmds) > 0 {
cmd := dc.cmds[0]
if len(dc.cmds) == 1 {
dc.cmds = nil
} else {
dc.cmds = dc.cmds[1:]
}
return cmd, nil
}
cmd, err := dc.rd.ReadCommand()
if err != nil {
return Command{}, err
}
return cmd, nil
} | go | func (dc *detachedConn) ReadCommand() (Command, error) {
if dc.closed {
return Command{}, errors.New("closed")
}
if len(dc.cmds) > 0 {
cmd := dc.cmds[0]
if len(dc.cmds) == 1 {
dc.cmds = nil
} else {
dc.cmds = dc.cmds[1:]
}
return cmd, nil
}
cmd, err := dc.rd.ReadCommand()
if err != nil {
return Command{}, err
}
return cmd, nil
} | [
"func",
"(",
"dc",
"*",
"detachedConn",
")",
"ReadCommand",
"(",
")",
"(",
"Command",
",",
"error",
")",
"{",
"if",
"dc",
".",
"closed",
"{",
"return",
"Command",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"dc",
".",
"cmds",
")",
">",
"0",
"{",
"cmd",
":=",
"dc",
".",
"cmds",
"[",
"0",
"]",
"\n",
"if",
"len",
"(",
"dc",
".",
"cmds",
")",
"==",
"1",
"{",
"dc",
".",
"cmds",
"=",
"nil",
"\n",
"}",
"else",
"{",
"dc",
".",
"cmds",
"=",
"dc",
".",
"cmds",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"cmd",
",",
"nil",
"\n",
"}",
"\n",
"cmd",
",",
"err",
":=",
"dc",
".",
"rd",
".",
"ReadCommand",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Command",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"cmd",
",",
"nil",
"\n",
"}"
] | // ReadCommand read the next command from the client. | [
"ReadCommand",
"read",
"the",
"next",
"command",
"from",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L492-L510 |
149,477 | tidwall/redcon | redcon.go | WriteBulk | func (w *Writer) WriteBulk(bulk []byte) {
w.b = AppendBulk(w.b, bulk)
} | go | func (w *Writer) WriteBulk(bulk []byte) {
w.b = AppendBulk(w.b, bulk)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteBulk",
"(",
"bulk",
"[",
"]",
"byte",
")",
"{",
"w",
".",
"b",
"=",
"AppendBulk",
"(",
"w",
".",
"b",
",",
"bulk",
")",
"\n",
"}"
] | // WriteBulk writes bulk bytes to the client. | [
"WriteBulk",
"writes",
"bulk",
"bytes",
"to",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L569-L571 |
149,478 | tidwall/redcon | redcon.go | WriteBulkString | func (w *Writer) WriteBulkString(bulk string) {
w.b = AppendBulkString(w.b, bulk)
} | go | func (w *Writer) WriteBulkString(bulk string) {
w.b = AppendBulkString(w.b, bulk)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteBulkString",
"(",
"bulk",
"string",
")",
"{",
"w",
".",
"b",
"=",
"AppendBulkString",
"(",
"w",
".",
"b",
",",
"bulk",
")",
"\n",
"}"
] | // WriteBulkString writes a bulk string to the client. | [
"WriteBulkString",
"writes",
"a",
"bulk",
"string",
"to",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L574-L576 |
149,479 | tidwall/redcon | redcon.go | SetBuffer | func (w *Writer) SetBuffer(raw []byte) {
w.b = w.b[:0]
w.b = append(w.b, raw...)
} | go | func (w *Writer) SetBuffer(raw []byte) {
w.b = w.b[:0]
w.b = append(w.b, raw...)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"SetBuffer",
"(",
"raw",
"[",
"]",
"byte",
")",
"{",
"w",
".",
"b",
"=",
"w",
".",
"b",
"[",
":",
"0",
"]",
"\n",
"w",
".",
"b",
"=",
"append",
"(",
"w",
".",
"b",
",",
"raw",
"...",
")",
"\n",
"}"
] | // SetBuffer replaces the unflushed buffer with new bytes. | [
"SetBuffer",
"replaces",
"the",
"unflushed",
"buffer",
"with",
"new",
"bytes",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L585-L588 |
149,480 | tidwall/redcon | redcon.go | WriteError | func (w *Writer) WriteError(msg string) {
w.b = AppendError(w.b, msg)
} | go | func (w *Writer) WriteError(msg string) {
w.b = AppendError(w.b, msg)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteError",
"(",
"msg",
"string",
")",
"{",
"w",
".",
"b",
"=",
"AppendError",
"(",
"w",
".",
"b",
",",
"msg",
")",
"\n",
"}"
] | // WriteError writes an error to the client. | [
"WriteError",
"writes",
"an",
"error",
"to",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L600-L602 |
149,481 | tidwall/redcon | redcon.go | WriteString | func (w *Writer) WriteString(msg string) {
w.b = AppendString(w.b, msg)
} | go | func (w *Writer) WriteString(msg string) {
w.b = AppendString(w.b, msg)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteString",
"(",
"msg",
"string",
")",
"{",
"w",
".",
"b",
"=",
"AppendString",
"(",
"w",
".",
"b",
",",
"msg",
")",
"\n",
"}"
] | // WriteString writes a string to the client. | [
"WriteString",
"writes",
"a",
"string",
"to",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L605-L607 |
149,482 | tidwall/redcon | redcon.go | WriteInt64 | func (w *Writer) WriteInt64(num int64) {
w.b = AppendInt(w.b, num)
} | go | func (w *Writer) WriteInt64(num int64) {
w.b = AppendInt(w.b, num)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteInt64",
"(",
"num",
"int64",
")",
"{",
"w",
".",
"b",
"=",
"AppendInt",
"(",
"w",
".",
"b",
",",
"num",
")",
"\n",
"}"
] | // WriteInt64 writes a 64-bit signed integer to the client. | [
"WriteInt64",
"writes",
"a",
"64",
"-",
"bit",
"signed",
"integer",
"to",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L615-L617 |
149,483 | tidwall/redcon | redcon.go | WriteRaw | func (w *Writer) WriteRaw(data []byte) {
w.b = append(w.b, data...)
} | go | func (w *Writer) WriteRaw(data []byte) {
w.b = append(w.b, data...)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteRaw",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"w",
".",
"b",
"=",
"append",
"(",
"w",
".",
"b",
",",
"data",
"...",
")",
"\n",
"}"
] | // WriteRaw writes raw data to the client. | [
"WriteRaw",
"writes",
"raw",
"data",
"to",
"the",
"client",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L620-L622 |
149,484 | tidwall/redcon | redcon.go | NewReader | func NewReader(rd io.Reader) *Reader {
return &Reader{
rd: bufio.NewReader(rd),
buf: make([]byte, 4096),
}
} | go | func NewReader(rd io.Reader) *Reader {
return &Reader{
rd: bufio.NewReader(rd),
buf: make([]byte, 4096),
}
} | [
"func",
"NewReader",
"(",
"rd",
"io",
".",
"Reader",
")",
"*",
"Reader",
"{",
"return",
"&",
"Reader",
"{",
"rd",
":",
"bufio",
".",
"NewReader",
"(",
"rd",
")",
",",
"buf",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"4096",
")",
",",
"}",
"\n",
"}"
] | // NewReader returns a command reader which will read RESP or telnet commands. | [
"NewReader",
"returns",
"a",
"command",
"reader",
"which",
"will",
"read",
"RESP",
"or",
"telnet",
"commands",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L634-L639 |
149,485 | tidwall/redcon | redcon.go | ReadCommand | func (rd *Reader) ReadCommand() (Command, error) {
if len(rd.cmds) > 0 {
cmd := rd.cmds[0]
rd.cmds = rd.cmds[1:]
return cmd, nil
}
cmds, err := rd.readCommands(nil)
if err != nil {
return Command{}, err
}
rd.cmds = cmds
return rd.ReadCommand()
} | go | func (rd *Reader) ReadCommand() (Command, error) {
if len(rd.cmds) > 0 {
cmd := rd.cmds[0]
rd.cmds = rd.cmds[1:]
return cmd, nil
}
cmds, err := rd.readCommands(nil)
if err != nil {
return Command{}, err
}
rd.cmds = cmds
return rd.ReadCommand()
} | [
"func",
"(",
"rd",
"*",
"Reader",
")",
"ReadCommand",
"(",
")",
"(",
"Command",
",",
"error",
")",
"{",
"if",
"len",
"(",
"rd",
".",
"cmds",
")",
">",
"0",
"{",
"cmd",
":=",
"rd",
".",
"cmds",
"[",
"0",
"]",
"\n",
"rd",
".",
"cmds",
"=",
"rd",
".",
"cmds",
"[",
"1",
":",
"]",
"\n",
"return",
"cmd",
",",
"nil",
"\n",
"}",
"\n",
"cmds",
",",
"err",
":=",
"rd",
".",
"readCommands",
"(",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Command",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"rd",
".",
"cmds",
"=",
"cmds",
"\n",
"return",
"rd",
".",
"ReadCommand",
"(",
")",
"\n",
"}"
] | // ReadCommand reads the next command. | [
"ReadCommand",
"reads",
"the",
"next",
"command",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L875-L887 |
149,486 | tidwall/redcon | redcon.go | Parse | func Parse(raw []byte) (Command, error) {
rd := Reader{buf: raw, end: len(raw)}
var leftover int
cmds, err := rd.readCommands(&leftover)
if err != nil {
return Command{}, err
}
if leftover > 0 {
return Command{}, errTooMuchData
}
return cmds[0], nil
} | go | func Parse(raw []byte) (Command, error) {
rd := Reader{buf: raw, end: len(raw)}
var leftover int
cmds, err := rd.readCommands(&leftover)
if err != nil {
return Command{}, err
}
if leftover > 0 {
return Command{}, errTooMuchData
}
return cmds[0], nil
} | [
"func",
"Parse",
"(",
"raw",
"[",
"]",
"byte",
")",
"(",
"Command",
",",
"error",
")",
"{",
"rd",
":=",
"Reader",
"{",
"buf",
":",
"raw",
",",
"end",
":",
"len",
"(",
"raw",
")",
"}",
"\n",
"var",
"leftover",
"int",
"\n",
"cmds",
",",
"err",
":=",
"rd",
".",
"readCommands",
"(",
"&",
"leftover",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Command",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"leftover",
">",
"0",
"{",
"return",
"Command",
"{",
"}",
",",
"errTooMuchData",
"\n",
"}",
"\n",
"return",
"cmds",
"[",
"0",
"]",
",",
"nil",
"\n\n",
"}"
] | // Parse parses a raw RESP message and returns a command. | [
"Parse",
"parses",
"a",
"raw",
"RESP",
"message",
"and",
"returns",
"a",
"command",
"."
] | c964c660adb68a16a0f890ceb01d25e05d0ab49e | https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L890-L902 |
149,487 | sony/gobreaker | gobreaker.go | String | func (s State) String() string {
switch s {
case StateClosed:
return "closed"
case StateHalfOpen:
return "half-open"
case StateOpen:
return "open"
default:
return fmt.Sprintf("unknown state: %d", s)
}
} | go | func (s State) String() string {
switch s {
case StateClosed:
return "closed"
case StateHalfOpen:
return "half-open"
case StateOpen:
return "open"
default:
return fmt.Sprintf("unknown state: %d", s)
}
} | [
"func",
"(",
"s",
"State",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"s",
"{",
"case",
"StateClosed",
":",
"return",
"\"",
"\"",
"\n",
"case",
"StateHalfOpen",
":",
"return",
"\"",
"\"",
"\n",
"case",
"StateOpen",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"}"
] | // String implements stringer interface. | [
"String",
"implements",
"stringer",
"interface",
"."
] | a9b2a3fc7395bc2e784d8f4df34fa953ce115b78 | https://github.com/sony/gobreaker/blob/a9b2a3fc7395bc2e784d8f4df34fa953ce115b78/gobreaker.go#L30-L41 |
149,488 | sony/gobreaker | gobreaker.go | NewCircuitBreaker | func NewCircuitBreaker(st Settings) *CircuitBreaker {
cb := new(CircuitBreaker)
cb.name = st.Name
cb.interval = st.Interval
cb.onStateChange = st.OnStateChange
if st.MaxRequests == 0 {
cb.maxRequests = 1
} else {
cb.maxRequests = st.MaxRequests
}
if st.Timeout == 0 {
cb.timeout = defaultTimeout
} else {
cb.timeout = st.Timeout
}
if st.ReadyToTrip == nil {
cb.readyToTrip = defaultReadyToTrip
} else {
cb.readyToTrip = st.ReadyToTrip
}
cb.toNewGeneration(time.Now())
return cb
} | go | func NewCircuitBreaker(st Settings) *CircuitBreaker {
cb := new(CircuitBreaker)
cb.name = st.Name
cb.interval = st.Interval
cb.onStateChange = st.OnStateChange
if st.MaxRequests == 0 {
cb.maxRequests = 1
} else {
cb.maxRequests = st.MaxRequests
}
if st.Timeout == 0 {
cb.timeout = defaultTimeout
} else {
cb.timeout = st.Timeout
}
if st.ReadyToTrip == nil {
cb.readyToTrip = defaultReadyToTrip
} else {
cb.readyToTrip = st.ReadyToTrip
}
cb.toNewGeneration(time.Now())
return cb
} | [
"func",
"NewCircuitBreaker",
"(",
"st",
"Settings",
")",
"*",
"CircuitBreaker",
"{",
"cb",
":=",
"new",
"(",
"CircuitBreaker",
")",
"\n\n",
"cb",
".",
"name",
"=",
"st",
".",
"Name",
"\n",
"cb",
".",
"interval",
"=",
"st",
".",
"Interval",
"\n",
"cb",
".",
"onStateChange",
"=",
"st",
".",
"OnStateChange",
"\n\n",
"if",
"st",
".",
"MaxRequests",
"==",
"0",
"{",
"cb",
".",
"maxRequests",
"=",
"1",
"\n",
"}",
"else",
"{",
"cb",
".",
"maxRequests",
"=",
"st",
".",
"MaxRequests",
"\n",
"}",
"\n\n",
"if",
"st",
".",
"Timeout",
"==",
"0",
"{",
"cb",
".",
"timeout",
"=",
"defaultTimeout",
"\n",
"}",
"else",
"{",
"cb",
".",
"timeout",
"=",
"st",
".",
"Timeout",
"\n",
"}",
"\n\n",
"if",
"st",
".",
"ReadyToTrip",
"==",
"nil",
"{",
"cb",
".",
"readyToTrip",
"=",
"defaultReadyToTrip",
"\n",
"}",
"else",
"{",
"cb",
".",
"readyToTrip",
"=",
"st",
".",
"ReadyToTrip",
"\n",
"}",
"\n\n",
"cb",
".",
"toNewGeneration",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"return",
"cb",
"\n",
"}"
] | // NewCircuitBreaker returns a new CircuitBreaker configured with the given Settings. | [
"NewCircuitBreaker",
"returns",
"a",
"new",
"CircuitBreaker",
"configured",
"with",
"the",
"given",
"Settings",
"."
] | a9b2a3fc7395bc2e784d8f4df34fa953ce115b78 | https://github.com/sony/gobreaker/blob/a9b2a3fc7395bc2e784d8f4df34fa953ce115b78/gobreaker.go#L134-L162 |
149,489 | sony/gobreaker | gobreaker.go | State | func (cb *CircuitBreaker) State() State {
cb.mutex.Lock()
defer cb.mutex.Unlock()
now := time.Now()
state, _ := cb.currentState(now)
return state
} | go | func (cb *CircuitBreaker) State() State {
cb.mutex.Lock()
defer cb.mutex.Unlock()
now := time.Now()
state, _ := cb.currentState(now)
return state
} | [
"func",
"(",
"cb",
"*",
"CircuitBreaker",
")",
"State",
"(",
")",
"State",
"{",
"cb",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cb",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"state",
",",
"_",
":=",
"cb",
".",
"currentState",
"(",
"now",
")",
"\n",
"return",
"state",
"\n",
"}"
] | // State returns the current state of the CircuitBreaker. | [
"State",
"returns",
"the",
"current",
"state",
"of",
"the",
"CircuitBreaker",
"."
] | a9b2a3fc7395bc2e784d8f4df34fa953ce115b78 | https://github.com/sony/gobreaker/blob/a9b2a3fc7395bc2e784d8f4df34fa953ce115b78/gobreaker.go#L183-L190 |
149,490 | sony/gobreaker | gobreaker.go | Execute | func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, error) {
generation, err := cb.beforeRequest()
if err != nil {
return nil, err
}
defer func() {
e := recover()
if e != nil {
cb.afterRequest(generation, false)
panic(e)
}
}()
result, err := req()
cb.afterRequest(generation, err == nil)
return result, err
} | go | func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, error) {
generation, err := cb.beforeRequest()
if err != nil {
return nil, err
}
defer func() {
e := recover()
if e != nil {
cb.afterRequest(generation, false)
panic(e)
}
}()
result, err := req()
cb.afterRequest(generation, err == nil)
return result, err
} | [
"func",
"(",
"cb",
"*",
"CircuitBreaker",
")",
"Execute",
"(",
"req",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"generation",
",",
"err",
":=",
"cb",
".",
"beforeRequest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"e",
":=",
"recover",
"(",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"cb",
".",
"afterRequest",
"(",
"generation",
",",
"false",
")",
"\n",
"panic",
"(",
"e",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"result",
",",
"err",
":=",
"req",
"(",
")",
"\n",
"cb",
".",
"afterRequest",
"(",
"generation",
",",
"err",
"==",
"nil",
")",
"\n",
"return",
"result",
",",
"err",
"\n",
"}"
] | // Execute runs the given request if the CircuitBreaker accepts it.
// Execute returns an error instantly if the CircuitBreaker rejects the request.
// Otherwise, Execute returns the result of the request.
// If a panic occurs in the request, the CircuitBreaker handles it as an error
// and causes the same panic again. | [
"Execute",
"runs",
"the",
"given",
"request",
"if",
"the",
"CircuitBreaker",
"accepts",
"it",
".",
"Execute",
"returns",
"an",
"error",
"instantly",
"if",
"the",
"CircuitBreaker",
"rejects",
"the",
"request",
".",
"Otherwise",
"Execute",
"returns",
"the",
"result",
"of",
"the",
"request",
".",
"If",
"a",
"panic",
"occurs",
"in",
"the",
"request",
"the",
"CircuitBreaker",
"handles",
"it",
"as",
"an",
"error",
"and",
"causes",
"the",
"same",
"panic",
"again",
"."
] | a9b2a3fc7395bc2e784d8f4df34fa953ce115b78 | https://github.com/sony/gobreaker/blob/a9b2a3fc7395bc2e784d8f4df34fa953ce115b78/gobreaker.go#L197-L214 |
149,491 | sony/gobreaker | gobreaker.go | Allow | func (tscb *TwoStepCircuitBreaker) Allow() (done func(success bool), err error) {
generation, err := tscb.cb.beforeRequest()
if err != nil {
return nil, err
}
return func(success bool) {
tscb.cb.afterRequest(generation, success)
}, nil
} | go | func (tscb *TwoStepCircuitBreaker) Allow() (done func(success bool), err error) {
generation, err := tscb.cb.beforeRequest()
if err != nil {
return nil, err
}
return func(success bool) {
tscb.cb.afterRequest(generation, success)
}, nil
} | [
"func",
"(",
"tscb",
"*",
"TwoStepCircuitBreaker",
")",
"Allow",
"(",
")",
"(",
"done",
"func",
"(",
"success",
"bool",
")",
",",
"err",
"error",
")",
"{",
"generation",
",",
"err",
":=",
"tscb",
".",
"cb",
".",
"beforeRequest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
"success",
"bool",
")",
"{",
"tscb",
".",
"cb",
".",
"afterRequest",
"(",
"generation",
",",
"success",
")",
"\n",
"}",
",",
"nil",
"\n",
"}"
] | // Allow checks if a new request can proceed. It returns a callback that should be used to
// register the success or failure in a separate step. If the circuit breaker doesn't allow
// requests, it returns an error. | [
"Allow",
"checks",
"if",
"a",
"new",
"request",
"can",
"proceed",
".",
"It",
"returns",
"a",
"callback",
"that",
"should",
"be",
"used",
"to",
"register",
"the",
"success",
"or",
"failure",
"in",
"a",
"separate",
"step",
".",
"If",
"the",
"circuit",
"breaker",
"doesn",
"t",
"allow",
"requests",
"it",
"returns",
"an",
"error",
"."
] | a9b2a3fc7395bc2e784d8f4df34fa953ce115b78 | https://github.com/sony/gobreaker/blob/a9b2a3fc7395bc2e784d8f4df34fa953ce115b78/gobreaker.go#L229-L238 |
149,492 | sony/gobreaker | example/http_breaker.go | Get | func Get(url string) ([]byte, error) {
body, err := cb.Execute(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
})
if err != nil {
return nil, err
}
return body.([]byte), nil
} | go | func Get(url string) ([]byte, error) {
body, err := cb.Execute(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
})
if err != nil {
return nil, err
}
return body.([]byte), nil
} | [
"func",
"Get",
"(",
"url",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"body",
",",
"err",
":=",
"cb",
".",
"Execute",
"(",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"body",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"body",
".",
"(",
"[",
"]",
"byte",
")",
",",
"nil",
"\n",
"}"
] | // Get wraps http.Get in CircuitBreaker. | [
"Get",
"wraps",
"http",
".",
"Get",
"in",
"CircuitBreaker",
"."
] | a9b2a3fc7395bc2e784d8f4df34fa953ce115b78 | https://github.com/sony/gobreaker/blob/a9b2a3fc7395bc2e784d8f4df34fa953ce115b78/example/http_breaker.go#L26-L46 |
149,493 | ncabatoff/process-exporter | proc/tracker.go | NewTracker | func NewTracker(namer common.MatchNamer, trackChildren, trackThreads, alwaysRecheck, debug bool) *Tracker {
return &Tracker{
namer: namer,
tracked: make(map[ID]*trackedProc),
procIds: make(map[int]ID),
trackChildren: trackChildren,
trackThreads: trackThreads,
alwaysRecheck: alwaysRecheck,
username: make(map[int]string),
debug: debug,
}
} | go | func NewTracker(namer common.MatchNamer, trackChildren, trackThreads, alwaysRecheck, debug bool) *Tracker {
return &Tracker{
namer: namer,
tracked: make(map[ID]*trackedProc),
procIds: make(map[int]ID),
trackChildren: trackChildren,
trackThreads: trackThreads,
alwaysRecheck: alwaysRecheck,
username: make(map[int]string),
debug: debug,
}
} | [
"func",
"NewTracker",
"(",
"namer",
"common",
".",
"MatchNamer",
",",
"trackChildren",
",",
"trackThreads",
",",
"alwaysRecheck",
",",
"debug",
"bool",
")",
"*",
"Tracker",
"{",
"return",
"&",
"Tracker",
"{",
"namer",
":",
"namer",
",",
"tracked",
":",
"make",
"(",
"map",
"[",
"ID",
"]",
"*",
"trackedProc",
")",
",",
"procIds",
":",
"make",
"(",
"map",
"[",
"int",
"]",
"ID",
")",
",",
"trackChildren",
":",
"trackChildren",
",",
"trackThreads",
":",
"trackThreads",
",",
"alwaysRecheck",
":",
"alwaysRecheck",
",",
"username",
":",
"make",
"(",
"map",
"[",
"int",
"]",
"string",
")",
",",
"debug",
":",
"debug",
",",
"}",
"\n",
"}"
] | // NewTracker creates a Tracker. | [
"NewTracker",
"creates",
"a",
"Tracker",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/tracker.go#L141-L152 |
149,494 | ncabatoff/process-exporter | proc/tracker.go | update | func (t *Tracker) update(procs Iter) ([]IDInfo, CollectErrors, error) {
var newProcs []IDInfo
var colErrs CollectErrors
var now = time.Now()
for procs.Next() {
newProc, cerrs := t.handleProc(procs, now)
if newProc != nil {
newProcs = append(newProcs, *newProc)
}
colErrs.Read += cerrs.Read
colErrs.Partial += cerrs.Partial
}
err := procs.Close()
if err != nil {
return nil, colErrs, fmt.Errorf("Error reading procs: %v", err)
}
// Rather than allocating a new map each time to detect procs that have
// disappeared, we bump the last update time on those that are still
// present. Then as a second pass we traverse the map looking for
// stale procs and removing them.
for procID, pinfo := range t.tracked {
if pinfo == nil {
// TODO is this a bug? we're not tracking the proc so we don't see it go away so ProcIds
// and Tracked are leaking?
continue
}
if pinfo.lastUpdate != now {
delete(t.tracked, procID)
delete(t.procIds, procID.Pid)
}
}
return newProcs, colErrs, nil
} | go | func (t *Tracker) update(procs Iter) ([]IDInfo, CollectErrors, error) {
var newProcs []IDInfo
var colErrs CollectErrors
var now = time.Now()
for procs.Next() {
newProc, cerrs := t.handleProc(procs, now)
if newProc != nil {
newProcs = append(newProcs, *newProc)
}
colErrs.Read += cerrs.Read
colErrs.Partial += cerrs.Partial
}
err := procs.Close()
if err != nil {
return nil, colErrs, fmt.Errorf("Error reading procs: %v", err)
}
// Rather than allocating a new map each time to detect procs that have
// disappeared, we bump the last update time on those that are still
// present. Then as a second pass we traverse the map looking for
// stale procs and removing them.
for procID, pinfo := range t.tracked {
if pinfo == nil {
// TODO is this a bug? we're not tracking the proc so we don't see it go away so ProcIds
// and Tracked are leaking?
continue
}
if pinfo.lastUpdate != now {
delete(t.tracked, procID)
delete(t.procIds, procID.Pid)
}
}
return newProcs, colErrs, nil
} | [
"func",
"(",
"t",
"*",
"Tracker",
")",
"update",
"(",
"procs",
"Iter",
")",
"(",
"[",
"]",
"IDInfo",
",",
"CollectErrors",
",",
"error",
")",
"{",
"var",
"newProcs",
"[",
"]",
"IDInfo",
"\n",
"var",
"colErrs",
"CollectErrors",
"\n",
"var",
"now",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"for",
"procs",
".",
"Next",
"(",
")",
"{",
"newProc",
",",
"cerrs",
":=",
"t",
".",
"handleProc",
"(",
"procs",
",",
"now",
")",
"\n",
"if",
"newProc",
"!=",
"nil",
"{",
"newProcs",
"=",
"append",
"(",
"newProcs",
",",
"*",
"newProc",
")",
"\n",
"}",
"\n",
"colErrs",
".",
"Read",
"+=",
"cerrs",
".",
"Read",
"\n",
"colErrs",
".",
"Partial",
"+=",
"cerrs",
".",
"Partial",
"\n",
"}",
"\n\n",
"err",
":=",
"procs",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"colErrs",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Rather than allocating a new map each time to detect procs that have",
"// disappeared, we bump the last update time on those that are still",
"// present. Then as a second pass we traverse the map looking for",
"// stale procs and removing them.",
"for",
"procID",
",",
"pinfo",
":=",
"range",
"t",
".",
"tracked",
"{",
"if",
"pinfo",
"==",
"nil",
"{",
"// TODO is this a bug? we're not tracking the proc so we don't see it go away so ProcIds",
"// and Tracked are leaking?",
"continue",
"\n",
"}",
"\n",
"if",
"pinfo",
".",
"lastUpdate",
"!=",
"now",
"{",
"delete",
"(",
"t",
".",
"tracked",
",",
"procID",
")",
"\n",
"delete",
"(",
"t",
".",
"procIds",
",",
"procID",
".",
"Pid",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"newProcs",
",",
"colErrs",
",",
"nil",
"\n",
"}"
] | // update scans procs and updates metrics for those which are tracked. Processes
// that have gone away get removed from the Tracked map. New processes are
// returned, along with the count of nonfatal errors. | [
"update",
"scans",
"procs",
"and",
"updates",
"metrics",
"for",
"those",
"which",
"are",
"tracked",
".",
"Processes",
"that",
"have",
"gone",
"away",
"get",
"removed",
"from",
"the",
"Tracked",
"map",
".",
"New",
"processes",
"are",
"returned",
"along",
"with",
"the",
"count",
"of",
"nonfatal",
"errors",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/tracker.go#L287-L323 |
149,495 | ncabatoff/process-exporter | proc/tracker.go | checkAncestry | func (t *Tracker) checkAncestry(idinfo IDInfo, newprocs map[ID]IDInfo) string {
ppid := idinfo.ParentPid
pProcID := t.procIds[ppid]
if pProcID.Pid < 1 {
if t.debug {
log.Printf("ignoring unmatched proc with no matched parent: %+v", idinfo)
}
// Reached root of process tree without finding a tracked parent.
t.ignore(idinfo.ID)
return ""
}
// Is the parent already known to the tracker?
if ptproc, ok := t.tracked[pProcID]; ok {
if ptproc != nil {
if t.debug {
log.Printf("matched as %q because child of %+v: %+v",
ptproc.groupName, pProcID, idinfo)
}
// We've found a tracked parent.
t.track(ptproc.groupName, idinfo)
return ptproc.groupName
}
// We've found an untracked parent.
t.ignore(idinfo.ID)
return ""
}
// Is the parent another new process?
if pinfoid, ok := newprocs[pProcID]; ok {
if name := t.checkAncestry(pinfoid, newprocs); name != "" {
if t.debug {
log.Printf("matched as %q because child of %+v: %+v",
name, pProcID, idinfo)
}
// We've found a tracked parent, which implies this entire lineage should be tracked.
t.track(name, idinfo)
return name
}
}
// Parent is dead, i.e. we never saw it, or there's no tracked proc in our ancestry.
if t.debug {
log.Printf("ignoring unmatched proc with no matched parent: %+v", idinfo)
}
t.ignore(idinfo.ID)
return ""
} | go | func (t *Tracker) checkAncestry(idinfo IDInfo, newprocs map[ID]IDInfo) string {
ppid := idinfo.ParentPid
pProcID := t.procIds[ppid]
if pProcID.Pid < 1 {
if t.debug {
log.Printf("ignoring unmatched proc with no matched parent: %+v", idinfo)
}
// Reached root of process tree without finding a tracked parent.
t.ignore(idinfo.ID)
return ""
}
// Is the parent already known to the tracker?
if ptproc, ok := t.tracked[pProcID]; ok {
if ptproc != nil {
if t.debug {
log.Printf("matched as %q because child of %+v: %+v",
ptproc.groupName, pProcID, idinfo)
}
// We've found a tracked parent.
t.track(ptproc.groupName, idinfo)
return ptproc.groupName
}
// We've found an untracked parent.
t.ignore(idinfo.ID)
return ""
}
// Is the parent another new process?
if pinfoid, ok := newprocs[pProcID]; ok {
if name := t.checkAncestry(pinfoid, newprocs); name != "" {
if t.debug {
log.Printf("matched as %q because child of %+v: %+v",
name, pProcID, idinfo)
}
// We've found a tracked parent, which implies this entire lineage should be tracked.
t.track(name, idinfo)
return name
}
}
// Parent is dead, i.e. we never saw it, or there's no tracked proc in our ancestry.
if t.debug {
log.Printf("ignoring unmatched proc with no matched parent: %+v", idinfo)
}
t.ignore(idinfo.ID)
return ""
} | [
"func",
"(",
"t",
"*",
"Tracker",
")",
"checkAncestry",
"(",
"idinfo",
"IDInfo",
",",
"newprocs",
"map",
"[",
"ID",
"]",
"IDInfo",
")",
"string",
"{",
"ppid",
":=",
"idinfo",
".",
"ParentPid",
"\n",
"pProcID",
":=",
"t",
".",
"procIds",
"[",
"ppid",
"]",
"\n",
"if",
"pProcID",
".",
"Pid",
"<",
"1",
"{",
"if",
"t",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"idinfo",
")",
"\n",
"}",
"\n",
"// Reached root of process tree without finding a tracked parent.",
"t",
".",
"ignore",
"(",
"idinfo",
".",
"ID",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// Is the parent already known to the tracker?",
"if",
"ptproc",
",",
"ok",
":=",
"t",
".",
"tracked",
"[",
"pProcID",
"]",
";",
"ok",
"{",
"if",
"ptproc",
"!=",
"nil",
"{",
"if",
"t",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"ptproc",
".",
"groupName",
",",
"pProcID",
",",
"idinfo",
")",
"\n",
"}",
"\n",
"// We've found a tracked parent.",
"t",
".",
"track",
"(",
"ptproc",
".",
"groupName",
",",
"idinfo",
")",
"\n",
"return",
"ptproc",
".",
"groupName",
"\n",
"}",
"\n",
"// We've found an untracked parent.",
"t",
".",
"ignore",
"(",
"idinfo",
".",
"ID",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// Is the parent another new process?",
"if",
"pinfoid",
",",
"ok",
":=",
"newprocs",
"[",
"pProcID",
"]",
";",
"ok",
"{",
"if",
"name",
":=",
"t",
".",
"checkAncestry",
"(",
"pinfoid",
",",
"newprocs",
")",
";",
"name",
"!=",
"\"",
"\"",
"{",
"if",
"t",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
",",
"pProcID",
",",
"idinfo",
")",
"\n",
"}",
"\n",
"// We've found a tracked parent, which implies this entire lineage should be tracked.",
"t",
".",
"track",
"(",
"name",
",",
"idinfo",
")",
"\n",
"return",
"name",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Parent is dead, i.e. we never saw it, or there's no tracked proc in our ancestry.",
"if",
"t",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"idinfo",
")",
"\n",
"}",
"\n",
"t",
".",
"ignore",
"(",
"idinfo",
".",
"ID",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // checkAncestry walks the process tree recursively towards the root,
// stopping at pid 1 or upon finding a parent that's already tracked
// or ignored. If we find a tracked parent track this one too; if not,
// ignore this one. | [
"checkAncestry",
"walks",
"the",
"process",
"tree",
"recursively",
"towards",
"the",
"root",
"stopping",
"at",
"pid",
"1",
"or",
"upon",
"finding",
"a",
"parent",
"that",
"s",
"already",
"tracked",
"or",
"ignored",
".",
"If",
"we",
"find",
"a",
"tracked",
"parent",
"track",
"this",
"one",
"too",
";",
"if",
"not",
"ignore",
"this",
"one",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/tracker.go#L329-L376 |
149,496 | ncabatoff/process-exporter | proc/tracker.go | Update | func (t *Tracker) Update(iter Iter) (CollectErrors, []Update, error) {
newProcs, colErrs, err := t.update(iter)
if err != nil {
return colErrs, nil, err
}
// Step 1: track any new proc that should be tracked based on its name and cmdline.
untracked := make(map[ID]IDInfo)
for _, idinfo := range newProcs {
nacl := common.ProcAttributes{
Name: idinfo.Name,
Cmdline: idinfo.Cmdline,
Username: t.lookupUid(idinfo.EffectiveUID),
}
wanted, gname := t.namer.MatchAndName(nacl)
if wanted {
if t.debug {
log.Printf("matched as %q: %+v", gname, idinfo)
}
t.track(gname, idinfo)
} else {
untracked[idinfo.ID] = idinfo
}
}
// Step 2: track any untracked new proc that should be tracked because its parent is tracked.
if t.trackChildren {
for _, idinfo := range untracked {
if _, ok := t.tracked[idinfo.ID]; ok {
// Already tracked or ignored in an earlier iteration
continue
}
t.checkAncestry(idinfo, untracked)
}
}
tp := []Update{}
for _, tproc := range t.tracked {
if tproc != nil {
tp = append(tp, tproc.getUpdate())
}
}
return colErrs, tp, nil
} | go | func (t *Tracker) Update(iter Iter) (CollectErrors, []Update, error) {
newProcs, colErrs, err := t.update(iter)
if err != nil {
return colErrs, nil, err
}
// Step 1: track any new proc that should be tracked based on its name and cmdline.
untracked := make(map[ID]IDInfo)
for _, idinfo := range newProcs {
nacl := common.ProcAttributes{
Name: idinfo.Name,
Cmdline: idinfo.Cmdline,
Username: t.lookupUid(idinfo.EffectiveUID),
}
wanted, gname := t.namer.MatchAndName(nacl)
if wanted {
if t.debug {
log.Printf("matched as %q: %+v", gname, idinfo)
}
t.track(gname, idinfo)
} else {
untracked[idinfo.ID] = idinfo
}
}
// Step 2: track any untracked new proc that should be tracked because its parent is tracked.
if t.trackChildren {
for _, idinfo := range untracked {
if _, ok := t.tracked[idinfo.ID]; ok {
// Already tracked or ignored in an earlier iteration
continue
}
t.checkAncestry(idinfo, untracked)
}
}
tp := []Update{}
for _, tproc := range t.tracked {
if tproc != nil {
tp = append(tp, tproc.getUpdate())
}
}
return colErrs, tp, nil
} | [
"func",
"(",
"t",
"*",
"Tracker",
")",
"Update",
"(",
"iter",
"Iter",
")",
"(",
"CollectErrors",
",",
"[",
"]",
"Update",
",",
"error",
")",
"{",
"newProcs",
",",
"colErrs",
",",
"err",
":=",
"t",
".",
"update",
"(",
"iter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"colErrs",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Step 1: track any new proc that should be tracked based on its name and cmdline.",
"untracked",
":=",
"make",
"(",
"map",
"[",
"ID",
"]",
"IDInfo",
")",
"\n",
"for",
"_",
",",
"idinfo",
":=",
"range",
"newProcs",
"{",
"nacl",
":=",
"common",
".",
"ProcAttributes",
"{",
"Name",
":",
"idinfo",
".",
"Name",
",",
"Cmdline",
":",
"idinfo",
".",
"Cmdline",
",",
"Username",
":",
"t",
".",
"lookupUid",
"(",
"idinfo",
".",
"EffectiveUID",
")",
",",
"}",
"\n",
"wanted",
",",
"gname",
":=",
"t",
".",
"namer",
".",
"MatchAndName",
"(",
"nacl",
")",
"\n",
"if",
"wanted",
"{",
"if",
"t",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"gname",
",",
"idinfo",
")",
"\n",
"}",
"\n",
"t",
".",
"track",
"(",
"gname",
",",
"idinfo",
")",
"\n",
"}",
"else",
"{",
"untracked",
"[",
"idinfo",
".",
"ID",
"]",
"=",
"idinfo",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Step 2: track any untracked new proc that should be tracked because its parent is tracked.",
"if",
"t",
".",
"trackChildren",
"{",
"for",
"_",
",",
"idinfo",
":=",
"range",
"untracked",
"{",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"tracked",
"[",
"idinfo",
".",
"ID",
"]",
";",
"ok",
"{",
"// Already tracked or ignored in an earlier iteration",
"continue",
"\n",
"}",
"\n\n",
"t",
".",
"checkAncestry",
"(",
"idinfo",
",",
"untracked",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"tp",
":=",
"[",
"]",
"Update",
"{",
"}",
"\n",
"for",
"_",
",",
"tproc",
":=",
"range",
"t",
".",
"tracked",
"{",
"if",
"tproc",
"!=",
"nil",
"{",
"tp",
"=",
"append",
"(",
"tp",
",",
"tproc",
".",
"getUpdate",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"colErrs",
",",
"tp",
",",
"nil",
"\n",
"}"
] | // Update modifies the tracker's internal state based on what it reads from
// iter. Tracks any new procs the namer wants tracked, and updates
// its metrics for existing tracked procs. Returns nonfatal errors
// and the status of all tracked procs, or an error if fatal. | [
"Update",
"modifies",
"the",
"tracker",
"s",
"internal",
"state",
"based",
"on",
"what",
"it",
"reads",
"from",
"iter",
".",
"Tracks",
"any",
"new",
"procs",
"the",
"namer",
"wants",
"tracked",
"and",
"updates",
"its",
"metrics",
"for",
"existing",
"tracked",
"procs",
".",
"Returns",
"nonfatal",
"errors",
"and",
"the",
"status",
"of",
"all",
"tracked",
"procs",
"or",
"an",
"error",
"if",
"fatal",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/tracker.go#L399-L443 |
149,497 | ncabatoff/process-exporter | proc/read.go | Add | func (c *Counts) Add(c2 Delta) {
c.CPUUserTime += c2.CPUUserTime
c.CPUSystemTime += c2.CPUSystemTime
c.ReadBytes += c2.ReadBytes
c.WriteBytes += c2.WriteBytes
c.MajorPageFaults += c2.MajorPageFaults
c.MinorPageFaults += c2.MinorPageFaults
c.CtxSwitchVoluntary += c2.CtxSwitchVoluntary
c.CtxSwitchNonvoluntary += c2.CtxSwitchNonvoluntary
} | go | func (c *Counts) Add(c2 Delta) {
c.CPUUserTime += c2.CPUUserTime
c.CPUSystemTime += c2.CPUSystemTime
c.ReadBytes += c2.ReadBytes
c.WriteBytes += c2.WriteBytes
c.MajorPageFaults += c2.MajorPageFaults
c.MinorPageFaults += c2.MinorPageFaults
c.CtxSwitchVoluntary += c2.CtxSwitchVoluntary
c.CtxSwitchNonvoluntary += c2.CtxSwitchNonvoluntary
} | [
"func",
"(",
"c",
"*",
"Counts",
")",
"Add",
"(",
"c2",
"Delta",
")",
"{",
"c",
".",
"CPUUserTime",
"+=",
"c2",
".",
"CPUUserTime",
"\n",
"c",
".",
"CPUSystemTime",
"+=",
"c2",
".",
"CPUSystemTime",
"\n",
"c",
".",
"ReadBytes",
"+=",
"c2",
".",
"ReadBytes",
"\n",
"c",
".",
"WriteBytes",
"+=",
"c2",
".",
"WriteBytes",
"\n",
"c",
".",
"MajorPageFaults",
"+=",
"c2",
".",
"MajorPageFaults",
"\n",
"c",
".",
"MinorPageFaults",
"+=",
"c2",
".",
"MinorPageFaults",
"\n",
"c",
".",
"CtxSwitchVoluntary",
"+=",
"c2",
".",
"CtxSwitchVoluntary",
"\n",
"c",
".",
"CtxSwitchNonvoluntary",
"+=",
"c2",
".",
"CtxSwitchNonvoluntary",
"\n",
"}"
] | // Add adds c2 to the counts. | [
"Add",
"adds",
"c2",
"to",
"the",
"counts",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L201-L210 |
149,498 | ncabatoff/process-exporter | proc/read.go | GetCounts | func (p IDInfo) GetCounts() (Counts, int, error) {
return p.Metrics.Counts, 0, nil
} | go | func (p IDInfo) GetCounts() (Counts, int, error) {
return p.Metrics.Counts, 0, nil
} | [
"func",
"(",
"p",
"IDInfo",
")",
"GetCounts",
"(",
")",
"(",
"Counts",
",",
"int",
",",
"error",
")",
"{",
"return",
"p",
".",
"Metrics",
".",
"Counts",
",",
"0",
",",
"nil",
"\n",
"}"
] | // GetCounts implements Proc. | [
"GetCounts",
"implements",
"Proc",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L253-L255 |
149,499 | ncabatoff/process-exporter | proc/read.go | GetProcID | func (p *proccache) GetProcID() (ID, error) {
if p.procid == nil {
stat, err := p.getStat()
if err != nil {
return ID{}, err
}
p.procid = &ID{Pid: p.GetPid(), StartTimeRel: stat.Starttime}
}
return *p.procid, nil
} | go | func (p *proccache) GetProcID() (ID, error) {
if p.procid == nil {
stat, err := p.getStat()
if err != nil {
return ID{}, err
}
p.procid = &ID{Pid: p.GetPid(), StartTimeRel: stat.Starttime}
}
return *p.procid, nil
} | [
"func",
"(",
"p",
"*",
"proccache",
")",
"GetProcID",
"(",
")",
"(",
"ID",
",",
"error",
")",
"{",
"if",
"p",
".",
"procid",
"==",
"nil",
"{",
"stat",
",",
"err",
":=",
"p",
".",
"getStat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ID",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"p",
".",
"procid",
"=",
"&",
"ID",
"{",
"Pid",
":",
"p",
".",
"GetPid",
"(",
")",
",",
"StartTimeRel",
":",
"stat",
".",
"Starttime",
"}",
"\n",
"}",
"\n\n",
"return",
"*",
"p",
".",
"procid",
",",
"nil",
"\n",
"}"
] | // GetProcID implements Proc. | [
"GetProcID",
"implements",
"Proc",
"."
] | 0f1987d2db4f6fccdec912784031c966b066765d | https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L300-L310 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.