repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
inverse-inc/packetfence | go/firewallsso/firewalls.go | Refresh | func (f *FirewallsContainer) Refresh(ctx context.Context) {
reload := false
f.ids.PfconfigNS = "config::Firewall_SSO"
// If ids changed, we want to reload
if !pfconfigdriver.IsValid(ctx, &f.ids) {
reload = true
}
pfconfigdriver.FetchDecodeSocketCache(ctx, &f.ids)
fssoFactory := NewFactory(ctx)
if f.Structs != nil {
for _, firewallId := range f.ids.Keys {
firewall, ok := f.Structs[firewallId]
if !ok {
log.LoggerWContext(ctx).Info("A firewall was added. Will read the firewalls again.")
reload = true
break
}
if !pfconfigdriver.IsValid(ctx, firewall) {
log.LoggerWContext(ctx).Info(fmt.Sprintf("Firewall %s has been detected as expired in pfconfig. Reloading.", firewallId))
reload = true
}
}
} else {
reload = true
}
if reload {
newFirewalls := make(map[string]FirewallSSOInt)
for _, firewallId := range f.ids.Keys {
log.LoggerWContext(ctx).Info(fmt.Sprintf("Adding firewall %s", firewallId))
firewall, err := fssoFactory.Instantiate(ctx, firewallId)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot instantiate firewall %s because of an error (%s). Ignoring it.", firewallId, err))
} else {
newFirewalls[firewall.GetFirewallSSO(ctx).PfconfigHashNS] = firewall
}
}
f.Structs = newFirewalls
}
} | go | func (f *FirewallsContainer) Refresh(ctx context.Context) {
reload := false
f.ids.PfconfigNS = "config::Firewall_SSO"
// If ids changed, we want to reload
if !pfconfigdriver.IsValid(ctx, &f.ids) {
reload = true
}
pfconfigdriver.FetchDecodeSocketCache(ctx, &f.ids)
fssoFactory := NewFactory(ctx)
if f.Structs != nil {
for _, firewallId := range f.ids.Keys {
firewall, ok := f.Structs[firewallId]
if !ok {
log.LoggerWContext(ctx).Info("A firewall was added. Will read the firewalls again.")
reload = true
break
}
if !pfconfigdriver.IsValid(ctx, firewall) {
log.LoggerWContext(ctx).Info(fmt.Sprintf("Firewall %s has been detected as expired in pfconfig. Reloading.", firewallId))
reload = true
}
}
} else {
reload = true
}
if reload {
newFirewalls := make(map[string]FirewallSSOInt)
for _, firewallId := range f.ids.Keys {
log.LoggerWContext(ctx).Info(fmt.Sprintf("Adding firewall %s", firewallId))
firewall, err := fssoFactory.Instantiate(ctx, firewallId)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot instantiate firewall %s because of an error (%s). Ignoring it.", firewallId, err))
} else {
newFirewalls[firewall.GetFirewallSSO(ctx).PfconfigHashNS] = firewall
}
}
f.Structs = newFirewalls
}
} | [
"func",
"(",
"f",
"*",
"FirewallsContainer",
")",
"Refresh",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"reload",
":=",
"false",
"\n",
"f",
".",
"ids",
".",
"PfconfigNS",
"=",
"\"config::Firewall_SSO\"",
"\n",
"if",
"!",
"pfconfigdriver",
".",
"IsValid",
"(",
"ctx",
",",
"&",
"f",
".",
"ids",
")",
"{",
"reload",
"=",
"true",
"\n",
"}",
"\n",
"pfconfigdriver",
".",
"FetchDecodeSocketCache",
"(",
"ctx",
",",
"&",
"f",
".",
"ids",
")",
"\n",
"fssoFactory",
":=",
"NewFactory",
"(",
"ctx",
")",
"\n",
"if",
"f",
".",
"Structs",
"!=",
"nil",
"{",
"for",
"_",
",",
"firewallId",
":=",
"range",
"f",
".",
"ids",
".",
"Keys",
"{",
"firewall",
",",
"ok",
":=",
"f",
".",
"Structs",
"[",
"firewallId",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"A firewall was added. Will read the firewalls again.\"",
")",
"\n",
"reload",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"!",
"pfconfigdriver",
".",
"IsValid",
"(",
"ctx",
",",
"firewall",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Firewall %s has been detected as expired in pfconfig. Reloading.\"",
",",
"firewallId",
")",
")",
"\n",
"reload",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"reload",
"=",
"true",
"\n",
"}",
"\n",
"if",
"reload",
"{",
"newFirewalls",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"FirewallSSOInt",
")",
"\n",
"for",
"_",
",",
"firewallId",
":=",
"range",
"f",
".",
"ids",
".",
"Keys",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Adding firewall %s\"",
",",
"firewallId",
")",
")",
"\n",
"firewall",
",",
"err",
":=",
"fssoFactory",
".",
"Instantiate",
"(",
"ctx",
",",
"firewallId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Cannot instantiate firewall %s because of an error (%s). Ignoring it.\"",
",",
"firewallId",
",",
"err",
")",
")",
"\n",
"}",
"else",
"{",
"newFirewalls",
"[",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
"]",
"=",
"firewall",
"\n",
"}",
"\n",
"}",
"\n",
"f",
".",
"Structs",
"=",
"newFirewalls",
"\n",
"}",
"\n",
"}"
] | // Refresh the FirewallsContainer struct
// Will first check if the IDs have changed in pfconfig and reload if they did
// Then it will check if all the IDs in pfconfig are loaded and valid and reload otherwise | [
"Refresh",
"the",
"FirewallsContainer",
"struct",
"Will",
"first",
"check",
"if",
"the",
"IDs",
"have",
"changed",
"in",
"pfconfig",
"and",
"reload",
"if",
"they",
"did",
"Then",
"it",
"will",
"check",
"if",
"all",
"the",
"IDs",
"in",
"pfconfig",
"are",
"loaded",
"and",
"valid",
"and",
"reload",
"otherwise"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/firewalls.go#L24-L72 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | getPfconfigSocketPath | func getPfconfigSocketPath() string {
if pfconfigSocketPathCache != "" {
// Do nothing, cache is populated, will be returned below
} else if sharedutils.EnvOrDefault("PFCONFIG_TESTING", "") == "" {
pfconfigSocketPathCache = pfconfigSocketPath
} else {
fmt.Println("Test flag is on. Using pfconfig test socket path.")
pfconfigSocketPathCache = pfconfigTestSocketPath
}
return pfconfigSocketPathCache
} | go | func getPfconfigSocketPath() string {
if pfconfigSocketPathCache != "" {
// Do nothing, cache is populated, will be returned below
} else if sharedutils.EnvOrDefault("PFCONFIG_TESTING", "") == "" {
pfconfigSocketPathCache = pfconfigSocketPath
} else {
fmt.Println("Test flag is on. Using pfconfig test socket path.")
pfconfigSocketPathCache = pfconfigTestSocketPath
}
return pfconfigSocketPathCache
} | [
"func",
"getPfconfigSocketPath",
"(",
")",
"string",
"{",
"if",
"pfconfigSocketPathCache",
"!=",
"\"\"",
"{",
"}",
"else",
"if",
"sharedutils",
".",
"EnvOrDefault",
"(",
"\"PFCONFIG_TESTING\"",
",",
"\"\"",
")",
"==",
"\"\"",
"{",
"pfconfigSocketPathCache",
"=",
"pfconfigSocketPath",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Println",
"(",
"\"Test flag is on. Using pfconfig test socket path.\"",
")",
"\n",
"pfconfigSocketPathCache",
"=",
"pfconfigTestSocketPath",
"\n",
"}",
"\n",
"return",
"pfconfigSocketPathCache",
"\n",
"}"
] | // Get the pfconfig socket path depending on whether or not we're in testing
// Since the environment is not bound to change at runtime, the socket path is computed once and cached in pfconfigSocketPathCache
// If the socket should be re-computed, empty out pfconfigSocketPathCache and run this function | [
"Get",
"the",
"pfconfig",
"socket",
"path",
"depending",
"on",
"whether",
"or",
"not",
"we",
"re",
"in",
"testing",
"Since",
"the",
"environment",
"is",
"not",
"bound",
"to",
"change",
"at",
"runtime",
"the",
"socket",
"path",
"is",
"computed",
"once",
"and",
"cached",
"in",
"pfconfigSocketPathCache",
"If",
"the",
"socket",
"should",
"be",
"re",
"-",
"computed",
"empty",
"out",
"pfconfigSocketPathCache",
"and",
"run",
"this",
"function"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L50-L60 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | GetPayload | func (q *Query) GetPayload() string {
j, err := json.Marshal(struct {
Encoding string `json:"encoding"`
Method string `json:"method"`
NS string `json:"key"`
}{
Encoding: q.encoding,
Method: q.method,
NS: q.ns,
})
sharedutils.CheckError(err)
return string(j) + "\n"
} | go | func (q *Query) GetPayload() string {
j, err := json.Marshal(struct {
Encoding string `json:"encoding"`
Method string `json:"method"`
NS string `json:"key"`
}{
Encoding: q.encoding,
Method: q.method,
NS: q.ns,
})
sharedutils.CheckError(err)
return string(j) + "\n"
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"GetPayload",
"(",
")",
"string",
"{",
"j",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"struct",
"{",
"Encoding",
"string",
"`json:\"encoding\"`",
"\n",
"Method",
"string",
"`json:\"method\"`",
"\n",
"NS",
"string",
"`json:\"key\"`",
"\n",
"}",
"{",
"Encoding",
":",
"q",
".",
"encoding",
",",
"Method",
":",
"q",
".",
"method",
",",
"NS",
":",
"q",
".",
"ns",
",",
"}",
")",
"\n",
"sharedutils",
".",
"CheckError",
"(",
"err",
")",
"\n",
"return",
"string",
"(",
"j",
")",
"+",
"\"\\n\"",
"\n",
"}"
] | // Get the payload to send to pfconfig based on the Query attributes
// Also sets the payload attribute at the same time | [
"Get",
"the",
"payload",
"to",
"send",
"to",
"pfconfig",
"based",
"on",
"the",
"Query",
"attributes",
"Also",
"sets",
"the",
"payload",
"attribute",
"at",
"the",
"same",
"time"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L71-L83 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | GetIdentifier | func (q *Query) GetIdentifier() string {
return fmt.Sprintf("%s|%s", q.method, q.ns)
} | go | func (q *Query) GetIdentifier() string {
return fmt.Sprintf("%s|%s", q.method, q.ns)
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"GetIdentifier",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s|%s\"",
",",
"q",
".",
"method",
",",
"q",
".",
"ns",
")",
"\n",
"}"
] | // Get a string identifier of the query | [
"Get",
"a",
"string",
"identifier",
"of",
"the",
"query"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L86-L88 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | connectSocket | func connectSocket(ctx context.Context) net.Conn {
timeoutChan := time.After(SocketTimeout)
var c net.Conn
err := errors.New("Not yet connected")
for err != nil {
select {
case <-timeoutChan:
panic("Can't connect to pfconfig socket")
default:
// We try to connect to the pfconfig socket
// If we fail, we will wait a second before leaving this scope
// Otherwise, we continue and the for loop will detect the connection is valid since err will be nil
c, err = net.Dial("unix", getPfconfigSocketPath())
if err != nil {
log.LoggerWContext(ctx).Error("Cannot connect to pfconfig socket...")
time.Sleep(1 * time.Second)
}
}
}
return c
} | go | func connectSocket(ctx context.Context) net.Conn {
timeoutChan := time.After(SocketTimeout)
var c net.Conn
err := errors.New("Not yet connected")
for err != nil {
select {
case <-timeoutChan:
panic("Can't connect to pfconfig socket")
default:
// We try to connect to the pfconfig socket
// If we fail, we will wait a second before leaving this scope
// Otherwise, we continue and the for loop will detect the connection is valid since err will be nil
c, err = net.Dial("unix", getPfconfigSocketPath())
if err != nil {
log.LoggerWContext(ctx).Error("Cannot connect to pfconfig socket...")
time.Sleep(1 * time.Second)
}
}
}
return c
} | [
"func",
"connectSocket",
"(",
"ctx",
"context",
".",
"Context",
")",
"net",
".",
"Conn",
"{",
"timeoutChan",
":=",
"time",
".",
"After",
"(",
"SocketTimeout",
")",
"\n",
"var",
"c",
"net",
".",
"Conn",
"\n",
"err",
":=",
"errors",
".",
"New",
"(",
"\"Not yet connected\"",
")",
"\n",
"for",
"err",
"!=",
"nil",
"{",
"select",
"{",
"case",
"<-",
"timeoutChan",
":",
"panic",
"(",
"\"Can't connect to pfconfig socket\"",
")",
"\n",
"default",
":",
"c",
",",
"err",
"=",
"net",
".",
"Dial",
"(",
"\"unix\"",
",",
"getPfconfigSocketPath",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"\"Cannot connect to pfconfig socket...\"",
")",
"\n",
"time",
".",
"Sleep",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // Connect to the pfconfig socket
// If it fails to connect, it will try it every second up to the time defined in SocketTimeout
// After SocketTimeout is reached, this will panic | [
"Connect",
"to",
"the",
"pfconfig",
"socket",
"If",
"it",
"fails",
"to",
"connect",
"it",
"will",
"try",
"it",
"every",
"second",
"up",
"to",
"the",
"time",
"defined",
"in",
"SocketTimeout",
"After",
"SocketTimeout",
"is",
"reached",
"this",
"will",
"panic"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L93-L116 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | FetchSocket | func FetchSocket(ctx context.Context, payload string) []byte {
c := connectSocket(ctx)
// Send our query in the socket
fmt.Fprintf(c, payload)
var buf bytes.Buffer
buf.ReadFrom(c)
// First 4 bytes are a little-endian representing the length of the payload
var length uint32
binary.Read(&buf, binary.LittleEndian, &length)
// Read the response given the length provided by pfconfig
response := make([]byte, length)
buf.Read(response)
// Validate the response has the length that was declared by pfconfig
if uint32(len(response)) != length {
panic(fmt.Sprintf("Got invalid length response from pfconfig %d expected, received %d", length, len(response)))
}
c.Close()
return response
} | go | func FetchSocket(ctx context.Context, payload string) []byte {
c := connectSocket(ctx)
// Send our query in the socket
fmt.Fprintf(c, payload)
var buf bytes.Buffer
buf.ReadFrom(c)
// First 4 bytes are a little-endian representing the length of the payload
var length uint32
binary.Read(&buf, binary.LittleEndian, &length)
// Read the response given the length provided by pfconfig
response := make([]byte, length)
buf.Read(response)
// Validate the response has the length that was declared by pfconfig
if uint32(len(response)) != length {
panic(fmt.Sprintf("Got invalid length response from pfconfig %d expected, received %d", length, len(response)))
}
c.Close()
return response
} | [
"func",
"FetchSocket",
"(",
"ctx",
"context",
".",
"Context",
",",
"payload",
"string",
")",
"[",
"]",
"byte",
"{",
"c",
":=",
"connectSocket",
"(",
"ctx",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"c",
",",
"payload",
")",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"ReadFrom",
"(",
"c",
")",
"\n",
"var",
"length",
"uint32",
"\n",
"binary",
".",
"Read",
"(",
"&",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"length",
")",
"\n",
"response",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
"\n",
"buf",
".",
"Read",
"(",
"response",
")",
"\n",
"if",
"uint32",
"(",
"len",
"(",
"response",
")",
")",
"!=",
"length",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Got invalid length response from pfconfig %d expected, received %d\"",
",",
"length",
",",
"len",
"(",
"response",
")",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"Close",
"(",
")",
"\n",
"return",
"response",
"\n",
"}"
] | // Fetch data from the pfconfig socket for a string payload
// Returns the bytes received from the socket | [
"Fetch",
"data",
"from",
"the",
"pfconfig",
"socket",
"for",
"a",
"string",
"payload",
"Returns",
"the",
"bytes",
"received",
"from",
"the",
"socket"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L120-L143 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | metadataFromField | func metadataFromField(ctx context.Context, param interface{}, fieldName string) string {
var ov reflect.Value
ov = reflect.ValueOf(param)
for ov.Kind() == reflect.Ptr || ov.Kind() == reflect.Interface {
ov = ov.Elem()
}
// We check if the field was set to a value as this will overide the value in the tag
// At the same time, we check if the field exists and early exit with the empty string if it doesn't
field := reflect.Value(ov.FieldByName(fieldName))
if !field.IsValid() {
return ""
}
userVal := field.Interface()
if userVal != "" {
return userVal.(string)
}
ot := ov.Type()
if field, ok := ot.FieldByName(fieldName); ok {
// The val tag defines the «default» value the metadata field should have
// If the val tag has a value of "-", then a user value was expected and this will panic
val := field.Tag.Get("val")
if val != "-" {
return val
} else {
panic(fmt.Sprintf("No default value defined for %s on %s. User specified value is required.", fieldName, ot.String()))
}
} else {
panic(fmt.Sprintf("Missing %s for %s", fieldName, ot.String()))
}
} | go | func metadataFromField(ctx context.Context, param interface{}, fieldName string) string {
var ov reflect.Value
ov = reflect.ValueOf(param)
for ov.Kind() == reflect.Ptr || ov.Kind() == reflect.Interface {
ov = ov.Elem()
}
// We check if the field was set to a value as this will overide the value in the tag
// At the same time, we check if the field exists and early exit with the empty string if it doesn't
field := reflect.Value(ov.FieldByName(fieldName))
if !field.IsValid() {
return ""
}
userVal := field.Interface()
if userVal != "" {
return userVal.(string)
}
ot := ov.Type()
if field, ok := ot.FieldByName(fieldName); ok {
// The val tag defines the «default» value the metadata field should have
// If the val tag has a value of "-", then a user value was expected and this will panic
val := field.Tag.Get("val")
if val != "-" {
return val
} else {
panic(fmt.Sprintf("No default value defined for %s on %s. User specified value is required.", fieldName, ot.String()))
}
} else {
panic(fmt.Sprintf("Missing %s for %s", fieldName, ot.String()))
}
} | [
"func",
"metadataFromField",
"(",
"ctx",
"context",
".",
"Context",
",",
"param",
"interface",
"{",
"}",
",",
"fieldName",
"string",
")",
"string",
"{",
"var",
"ov",
"reflect",
".",
"Value",
"\n",
"ov",
"=",
"reflect",
".",
"ValueOf",
"(",
"param",
")",
"\n",
"for",
"ov",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"||",
"ov",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"ov",
"=",
"ov",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"field",
":=",
"reflect",
".",
"Value",
"(",
"ov",
".",
"FieldByName",
"(",
"fieldName",
")",
")",
"\n",
"if",
"!",
"field",
".",
"IsValid",
"(",
")",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"userVal",
":=",
"field",
".",
"Interface",
"(",
")",
"\n",
"if",
"userVal",
"!=",
"\"\"",
"{",
"return",
"userVal",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"ot",
":=",
"ov",
".",
"Type",
"(",
")",
"\n",
"if",
"field",
",",
"ok",
":=",
"ot",
".",
"FieldByName",
"(",
"fieldName",
")",
";",
"ok",
"{",
"val",
":=",
"field",
".",
"Tag",
".",
"Get",
"(",
"\"val\"",
")",
"\n",
"if",
"val",
"!=",
"\"-\"",
"{",
"return",
"val",
"\n",
"}",
"else",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"No default value defined for %s on %s. User specified value is required.\"",
",",
"fieldName",
",",
"ot",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Missing %s for %s\"",
",",
"fieldName",
",",
"ot",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Lookup the pfconfig metadata for a specific field
// If there is a non-zero value in the field, it will be taken
// Otherwise it will take the value in the val tag of the field | [
"Lookup",
"the",
"pfconfig",
"metadata",
"for",
"a",
"specific",
"field",
"If",
"there",
"is",
"a",
"non",
"-",
"zero",
"value",
"in",
"the",
"field",
"it",
"will",
"be",
"taken",
"Otherwise",
"it",
"will",
"take",
"the",
"value",
"in",
"the",
"val",
"tag",
"of",
"the",
"field"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L148-L181 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | decodeInterface | func decodeInterface(ctx context.Context, encoding string, b []byte, o interface{}) {
switch encoding {
case "json":
decodeJsonInterface(ctx, b, o)
default:
panic(fmt.Sprintf("Unknown encoding %s", encoding))
}
} | go | func decodeInterface(ctx context.Context, encoding string, b []byte, o interface{}) {
switch encoding {
case "json":
decodeJsonInterface(ctx, b, o)
default:
panic(fmt.Sprintf("Unknown encoding %s", encoding))
}
} | [
"func",
"decodeInterface",
"(",
"ctx",
"context",
".",
"Context",
",",
"encoding",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"o",
"interface",
"{",
"}",
")",
"{",
"switch",
"encoding",
"{",
"case",
"\"json\"",
":",
"decodeJsonInterface",
"(",
"ctx",
",",
"b",
",",
"o",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Unknown encoding %s\"",
",",
"encoding",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Decode the struct from bytes given an encoding
// For now only JSON is supported | [
"Decode",
"the",
"struct",
"from",
"bytes",
"given",
"an",
"encoding",
"For",
"now",
"only",
"JSON",
"is",
"supported"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L194-L201 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | decodeJsonInterface | func decodeJsonInterface(ctx context.Context, b []byte, o interface{}) {
decoder := json.NewDecoder(bytes.NewReader(b))
for {
if err := decoder.Decode(&o); err == io.EOF {
break
} else if err != nil {
panic(err)
}
}
} | go | func decodeJsonInterface(ctx context.Context, b []byte, o interface{}) {
decoder := json.NewDecoder(bytes.NewReader(b))
for {
if err := decoder.Decode(&o); err == io.EOF {
break
} else if err != nil {
panic(err)
}
}
} | [
"func",
"decodeJsonInterface",
"(",
"ctx",
"context",
".",
"Context",
",",
"b",
"[",
"]",
"byte",
",",
"o",
"interface",
"{",
"}",
")",
"{",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
"\n",
"for",
"{",
"if",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"o",
")",
";",
"err",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Decode an array of bytes representing a json string into interface
// Panics if there is an error decoding the JSON data | [
"Decode",
"an",
"array",
"of",
"bytes",
"representing",
"a",
"json",
"string",
"into",
"interface",
"Panics",
"if",
"there",
"is",
"an",
"error",
"decoding",
"the",
"JSON",
"data"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L205-L214 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | FetchDecodeSocketCache | func FetchDecodeSocketCache(ctx context.Context, o PfconfigObject) (bool, error) {
query := createQuery(ctx, o)
ctx = log.AddToLogContext(ctx, "PfconfigObject", query.GetIdentifier())
// If the resource is still valid and is already loaded
if IsValid(ctx, o) {
return false, nil
}
err := FetchDecodeSocket(ctx, o)
return true, err
} | go | func FetchDecodeSocketCache(ctx context.Context, o PfconfigObject) (bool, error) {
query := createQuery(ctx, o)
ctx = log.AddToLogContext(ctx, "PfconfigObject", query.GetIdentifier())
// If the resource is still valid and is already loaded
if IsValid(ctx, o) {
return false, nil
}
err := FetchDecodeSocket(ctx, o)
return true, err
} | [
"func",
"FetchDecodeSocketCache",
"(",
"ctx",
"context",
".",
"Context",
",",
"o",
"PfconfigObject",
")",
"(",
"bool",
",",
"error",
")",
"{",
"query",
":=",
"createQuery",
"(",
"ctx",
",",
"o",
")",
"\n",
"ctx",
"=",
"log",
".",
"AddToLogContext",
"(",
"ctx",
",",
"\"PfconfigObject\"",
",",
"query",
".",
"GetIdentifier",
"(",
")",
")",
"\n",
"if",
"IsValid",
"(",
"ctx",
",",
"o",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"FetchDecodeSocket",
"(",
"ctx",
",",
"o",
")",
"\n",
"return",
"true",
",",
"err",
"\n",
"}"
] | // Fetch and decode from the socket but only if the PfconfigObject is not valid anymore | [
"Fetch",
"and",
"decode",
"from",
"the",
"socket",
"but",
"only",
"if",
"the",
"PfconfigObject",
"is",
"not",
"valid",
"anymore"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L335-L346 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | FetchKeys | func FetchKeys(ctx context.Context, name string) ([]string, error) {
keys := PfconfigKeys{PfconfigNS: name}
err := FetchDecodeSocket(ctx, &keys)
if err != nil {
return nil, err
}
return keys.Keys, nil
} | go | func FetchKeys(ctx context.Context, name string) ([]string, error) {
keys := PfconfigKeys{PfconfigNS: name}
err := FetchDecodeSocket(ctx, &keys)
if err != nil {
return nil, err
}
return keys.Keys, nil
} | [
"func",
"FetchKeys",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"keys",
":=",
"PfconfigKeys",
"{",
"PfconfigNS",
":",
"name",
"}",
"\n",
"err",
":=",
"FetchDecodeSocket",
"(",
"ctx",
",",
"&",
"keys",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"keys",
".",
"Keys",
",",
"nil",
"\n",
"}"
] | // Fetch the keys of a namespace | [
"Fetch",
"the",
"keys",
"of",
"a",
"namespace"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L349-L357 | train |
inverse-inc/packetfence | go/pfconfigdriver/fetch.go | FetchDecodeSocket | func FetchDecodeSocket(ctx context.Context, o PfconfigObject) error {
ptrT := reflect.TypeOf(o)
new := reflect.New(ptrT.Elem())
newo := new.Interface().(PfconfigObject)
transferMetadata(ctx, &o, &newo)
reflect.ValueOf(o).Elem().Set(reflect.ValueOf(newo).Elem())
query := createQuery(ctx, o)
jsonResponse := FetchSocket(ctx, query.GetPayload())
if query.method == "keys" {
if cs, ok := o.(PfconfigKeysInt); ok {
decodeInterface(ctx, query.encoding, jsonResponse, cs.GetKeys())
} else {
panic("Wrong struct type for keys. Required PfconfigKeysInt")
}
} else if metadataFromField(ctx, o, "PfconfigArray") == "yes" || metadataFromField(ctx, o, "PfconfigDecodeInElement") == "yes" {
decodeInterface(ctx, query.encoding, jsonResponse, &o)
} else {
receiver := &PfconfigElementResponse{}
decodeInterface(ctx, query.encoding, jsonResponse, receiver)
if receiver.Element != nil {
b, _ := receiver.Element.MarshalJSON()
decodeInterface(ctx, query.encoding, b, &o)
} else {
return errors.New(fmt.Sprintf("Element in response was invalid. Response was: %s", jsonResponse))
}
}
o.SetLoadedAt(time.Now())
return nil
} | go | func FetchDecodeSocket(ctx context.Context, o PfconfigObject) error {
ptrT := reflect.TypeOf(o)
new := reflect.New(ptrT.Elem())
newo := new.Interface().(PfconfigObject)
transferMetadata(ctx, &o, &newo)
reflect.ValueOf(o).Elem().Set(reflect.ValueOf(newo).Elem())
query := createQuery(ctx, o)
jsonResponse := FetchSocket(ctx, query.GetPayload())
if query.method == "keys" {
if cs, ok := o.(PfconfigKeysInt); ok {
decodeInterface(ctx, query.encoding, jsonResponse, cs.GetKeys())
} else {
panic("Wrong struct type for keys. Required PfconfigKeysInt")
}
} else if metadataFromField(ctx, o, "PfconfigArray") == "yes" || metadataFromField(ctx, o, "PfconfigDecodeInElement") == "yes" {
decodeInterface(ctx, query.encoding, jsonResponse, &o)
} else {
receiver := &PfconfigElementResponse{}
decodeInterface(ctx, query.encoding, jsonResponse, receiver)
if receiver.Element != nil {
b, _ := receiver.Element.MarshalJSON()
decodeInterface(ctx, query.encoding, b, &o)
} else {
return errors.New(fmt.Sprintf("Element in response was invalid. Response was: %s", jsonResponse))
}
}
o.SetLoadedAt(time.Now())
return nil
} | [
"func",
"FetchDecodeSocket",
"(",
"ctx",
"context",
".",
"Context",
",",
"o",
"PfconfigObject",
")",
"error",
"{",
"ptrT",
":=",
"reflect",
".",
"TypeOf",
"(",
"o",
")",
"\n",
"new",
":=",
"reflect",
".",
"New",
"(",
"ptrT",
".",
"Elem",
"(",
")",
")",
"\n",
"newo",
":=",
"new",
".",
"Interface",
"(",
")",
".",
"(",
"PfconfigObject",
")",
"\n",
"transferMetadata",
"(",
"ctx",
",",
"&",
"o",
",",
"&",
"newo",
")",
"\n",
"reflect",
".",
"ValueOf",
"(",
"o",
")",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"newo",
")",
".",
"Elem",
"(",
")",
")",
"\n",
"query",
":=",
"createQuery",
"(",
"ctx",
",",
"o",
")",
"\n",
"jsonResponse",
":=",
"FetchSocket",
"(",
"ctx",
",",
"query",
".",
"GetPayload",
"(",
")",
")",
"\n",
"if",
"query",
".",
"method",
"==",
"\"keys\"",
"{",
"if",
"cs",
",",
"ok",
":=",
"o",
".",
"(",
"PfconfigKeysInt",
")",
";",
"ok",
"{",
"decodeInterface",
"(",
"ctx",
",",
"query",
".",
"encoding",
",",
"jsonResponse",
",",
"cs",
".",
"GetKeys",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"panic",
"(",
"\"Wrong struct type for keys. Required PfconfigKeysInt\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"metadataFromField",
"(",
"ctx",
",",
"o",
",",
"\"PfconfigArray\"",
")",
"==",
"\"yes\"",
"||",
"metadataFromField",
"(",
"ctx",
",",
"o",
",",
"\"PfconfigDecodeInElement\"",
")",
"==",
"\"yes\"",
"{",
"decodeInterface",
"(",
"ctx",
",",
"query",
".",
"encoding",
",",
"jsonResponse",
",",
"&",
"o",
")",
"\n",
"}",
"else",
"{",
"receiver",
":=",
"&",
"PfconfigElementResponse",
"{",
"}",
"\n",
"decodeInterface",
"(",
"ctx",
",",
"query",
".",
"encoding",
",",
"jsonResponse",
",",
"receiver",
")",
"\n",
"if",
"receiver",
".",
"Element",
"!=",
"nil",
"{",
"b",
",",
"_",
":=",
"receiver",
".",
"Element",
".",
"MarshalJSON",
"(",
")",
"\n",
"decodeInterface",
"(",
"ctx",
",",
"query",
".",
"encoding",
",",
"b",
",",
"&",
"o",
")",
"\n",
"}",
"else",
"{",
"return",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Element in response was invalid. Response was: %s\"",
",",
"jsonResponse",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"o",
".",
"SetLoadedAt",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Fetch and decode a namespace from pfconfig given a pfconfig compatible struct
// This will fetch the json representation from pfconfig and decode it into o
// o must be a pointer to the struct as this should be used by reference | [
"Fetch",
"and",
"decode",
"a",
"namespace",
"from",
"pfconfig",
"given",
"a",
"pfconfig",
"compatible",
"struct",
"This",
"will",
"fetch",
"the",
"json",
"representation",
"from",
"pfconfig",
"and",
"decode",
"it",
"into",
"o",
"o",
"must",
"be",
"a",
"pointer",
"to",
"the",
"struct",
"as",
"this",
"should",
"be",
"used",
"by",
"reference"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/fetch.go#L362-L397 | train |
inverse-inc/packetfence | go/coredns/plugin/backend_lookup.go | AAAA | func AAAA(b ServiceBackend, zone string, state request.Request, previousRecords []dns.RR, opt Options) (records []dns.RR, err error) {
services, err := b.Services(state, false, opt)
if err != nil {
return nil, err
}
for _, serv := range services {
what, ip := serv.HostType()
switch what {
case dns.TypeCNAME:
// Try to resolve as CNAME if it's not an IP, but only if we don't create loops.
if Name(state.Name()).Matches(dns.Fqdn(serv.Host)) {
// x CNAME x is a direct loop, don't add those
continue
}
newRecord := serv.NewCNAME(state.QName(), serv.Host)
if len(previousRecords) > 7 {
// don't add it, and just continue
continue
}
if dnsutil.DuplicateCNAME(newRecord, previousRecords) {
continue
}
state1 := state.NewWithQuestion(serv.Host, state.QType())
nextRecords, err := AAAA(b, zone, state1, append(previousRecords, newRecord), opt)
if err == nil {
// Not only have we found something we should add the CNAME and the IP addresses.
if len(nextRecords) > 0 {
records = append(records, newRecord)
records = append(records, nextRecords...)
}
continue
}
// This means we can not complete the CNAME, try to look else where.
target := newRecord.Target
if dns.IsSubDomain(zone, target) {
// We should already have found it
continue
}
m1, e1 := b.Lookup(state, target, state.QType())
if e1 != nil {
continue
}
// Len(m1.Answer) > 0 here is well?
records = append(records, newRecord)
records = append(records, m1.Answer...)
continue
// both here again
case dns.TypeA:
// nada?
case dns.TypeAAAA:
records = append(records, serv.NewAAAA(state.QName(), ip))
}
}
return records, nil
} | go | func AAAA(b ServiceBackend, zone string, state request.Request, previousRecords []dns.RR, opt Options) (records []dns.RR, err error) {
services, err := b.Services(state, false, opt)
if err != nil {
return nil, err
}
for _, serv := range services {
what, ip := serv.HostType()
switch what {
case dns.TypeCNAME:
// Try to resolve as CNAME if it's not an IP, but only if we don't create loops.
if Name(state.Name()).Matches(dns.Fqdn(serv.Host)) {
// x CNAME x is a direct loop, don't add those
continue
}
newRecord := serv.NewCNAME(state.QName(), serv.Host)
if len(previousRecords) > 7 {
// don't add it, and just continue
continue
}
if dnsutil.DuplicateCNAME(newRecord, previousRecords) {
continue
}
state1 := state.NewWithQuestion(serv.Host, state.QType())
nextRecords, err := AAAA(b, zone, state1, append(previousRecords, newRecord), opt)
if err == nil {
// Not only have we found something we should add the CNAME and the IP addresses.
if len(nextRecords) > 0 {
records = append(records, newRecord)
records = append(records, nextRecords...)
}
continue
}
// This means we can not complete the CNAME, try to look else where.
target := newRecord.Target
if dns.IsSubDomain(zone, target) {
// We should already have found it
continue
}
m1, e1 := b.Lookup(state, target, state.QType())
if e1 != nil {
continue
}
// Len(m1.Answer) > 0 here is well?
records = append(records, newRecord)
records = append(records, m1.Answer...)
continue
// both here again
case dns.TypeA:
// nada?
case dns.TypeAAAA:
records = append(records, serv.NewAAAA(state.QName(), ip))
}
}
return records, nil
} | [
"func",
"AAAA",
"(",
"b",
"ServiceBackend",
",",
"zone",
"string",
",",
"state",
"request",
".",
"Request",
",",
"previousRecords",
"[",
"]",
"dns",
".",
"RR",
",",
"opt",
"Options",
")",
"(",
"records",
"[",
"]",
"dns",
".",
"RR",
",",
"err",
"error",
")",
"{",
"services",
",",
"err",
":=",
"b",
".",
"Services",
"(",
"state",
",",
"false",
",",
"opt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"serv",
":=",
"range",
"services",
"{",
"what",
",",
"ip",
":=",
"serv",
".",
"HostType",
"(",
")",
"\n",
"switch",
"what",
"{",
"case",
"dns",
".",
"TypeCNAME",
":",
"if",
"Name",
"(",
"state",
".",
"Name",
"(",
")",
")",
".",
"Matches",
"(",
"dns",
".",
"Fqdn",
"(",
"serv",
".",
"Host",
")",
")",
"{",
"continue",
"\n",
"}",
"\n",
"newRecord",
":=",
"serv",
".",
"NewCNAME",
"(",
"state",
".",
"QName",
"(",
")",
",",
"serv",
".",
"Host",
")",
"\n",
"if",
"len",
"(",
"previousRecords",
")",
">",
"7",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"dnsutil",
".",
"DuplicateCNAME",
"(",
"newRecord",
",",
"previousRecords",
")",
"{",
"continue",
"\n",
"}",
"\n",
"state1",
":=",
"state",
".",
"NewWithQuestion",
"(",
"serv",
".",
"Host",
",",
"state",
".",
"QType",
"(",
")",
")",
"\n",
"nextRecords",
",",
"err",
":=",
"AAAA",
"(",
"b",
",",
"zone",
",",
"state1",
",",
"append",
"(",
"previousRecords",
",",
"newRecord",
")",
",",
"opt",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"len",
"(",
"nextRecords",
")",
">",
"0",
"{",
"records",
"=",
"append",
"(",
"records",
",",
"newRecord",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"nextRecords",
"...",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"target",
":=",
"newRecord",
".",
"Target",
"\n",
"if",
"dns",
".",
"IsSubDomain",
"(",
"zone",
",",
"target",
")",
"{",
"continue",
"\n",
"}",
"\n",
"m1",
",",
"e1",
":=",
"b",
".",
"Lookup",
"(",
"state",
",",
"target",
",",
"state",
".",
"QType",
"(",
")",
")",
"\n",
"if",
"e1",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"newRecord",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"m1",
".",
"Answer",
"...",
")",
"\n",
"continue",
"\n",
"case",
"dns",
".",
"TypeA",
":",
"case",
"dns",
".",
"TypeAAAA",
":",
"records",
"=",
"append",
"(",
"records",
",",
"serv",
".",
"NewAAAA",
"(",
"state",
".",
"QName",
"(",
")",
",",
"ip",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"records",
",",
"nil",
"\n",
"}"
] | // AAAA returns AAAA records from Backend or an error. | [
"AAAA",
"returns",
"AAAA",
"records",
"from",
"Backend",
"or",
"an",
"error",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/backend_lookup.go#L80-L142 | train |
inverse-inc/packetfence | go/coredns/plugin/backend_lookup.go | MX | func MX(b ServiceBackend, zone string, state request.Request, opt Options) (records, extra []dns.RR, err error) {
services, err := b.Services(state, false, opt)
if err != nil {
return nil, nil, err
}
lookup := make(map[string]bool)
for _, serv := range services {
if !serv.Mail {
continue
}
what, ip := serv.HostType()
switch what {
case dns.TypeCNAME:
mx := serv.NewMX(state.QName())
records = append(records, mx)
if _, ok := lookup[mx.Mx]; ok {
break
}
lookup[mx.Mx] = true
if !dns.IsSubDomain(zone, mx.Mx) {
m1, e1 := b.Lookup(state, mx.Mx, dns.TypeA)
if e1 == nil {
extra = append(extra, m1.Answer...)
}
m1, e1 = b.Lookup(state, mx.Mx, dns.TypeAAAA)
if e1 == nil {
// If we have seen CNAME's we *assume* that they are already added.
for _, a := range m1.Answer {
if _, ok := a.(*dns.CNAME); !ok {
extra = append(extra, a)
}
}
}
break
}
// Internal name
state1 := state.NewWithQuestion(mx.Mx, dns.TypeA)
addr, e1 := A(b, zone, state1, nil, opt)
if e1 == nil {
extra = append(extra, addr...)
}
// e.AAAA as well
case dns.TypeA, dns.TypeAAAA:
serv.Host = msg.Domain(serv.Key)
records = append(records, serv.NewMX(state.QName()))
extra = append(extra, newAddress(serv, serv.Host, ip, what))
}
}
return records, extra, nil
} | go | func MX(b ServiceBackend, zone string, state request.Request, opt Options) (records, extra []dns.RR, err error) {
services, err := b.Services(state, false, opt)
if err != nil {
return nil, nil, err
}
lookup := make(map[string]bool)
for _, serv := range services {
if !serv.Mail {
continue
}
what, ip := serv.HostType()
switch what {
case dns.TypeCNAME:
mx := serv.NewMX(state.QName())
records = append(records, mx)
if _, ok := lookup[mx.Mx]; ok {
break
}
lookup[mx.Mx] = true
if !dns.IsSubDomain(zone, mx.Mx) {
m1, e1 := b.Lookup(state, mx.Mx, dns.TypeA)
if e1 == nil {
extra = append(extra, m1.Answer...)
}
m1, e1 = b.Lookup(state, mx.Mx, dns.TypeAAAA)
if e1 == nil {
// If we have seen CNAME's we *assume* that they are already added.
for _, a := range m1.Answer {
if _, ok := a.(*dns.CNAME); !ok {
extra = append(extra, a)
}
}
}
break
}
// Internal name
state1 := state.NewWithQuestion(mx.Mx, dns.TypeA)
addr, e1 := A(b, zone, state1, nil, opt)
if e1 == nil {
extra = append(extra, addr...)
}
// e.AAAA as well
case dns.TypeA, dns.TypeAAAA:
serv.Host = msg.Domain(serv.Key)
records = append(records, serv.NewMX(state.QName()))
extra = append(extra, newAddress(serv, serv.Host, ip, what))
}
}
return records, extra, nil
} | [
"func",
"MX",
"(",
"b",
"ServiceBackend",
",",
"zone",
"string",
",",
"state",
"request",
".",
"Request",
",",
"opt",
"Options",
")",
"(",
"records",
",",
"extra",
"[",
"]",
"dns",
".",
"RR",
",",
"err",
"error",
")",
"{",
"services",
",",
"err",
":=",
"b",
".",
"Services",
"(",
"state",
",",
"false",
",",
"opt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"lookup",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"serv",
":=",
"range",
"services",
"{",
"if",
"!",
"serv",
".",
"Mail",
"{",
"continue",
"\n",
"}",
"\n",
"what",
",",
"ip",
":=",
"serv",
".",
"HostType",
"(",
")",
"\n",
"switch",
"what",
"{",
"case",
"dns",
".",
"TypeCNAME",
":",
"mx",
":=",
"serv",
".",
"NewMX",
"(",
"state",
".",
"QName",
"(",
")",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"mx",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"lookup",
"[",
"mx",
".",
"Mx",
"]",
";",
"ok",
"{",
"break",
"\n",
"}",
"\n",
"lookup",
"[",
"mx",
".",
"Mx",
"]",
"=",
"true",
"\n",
"if",
"!",
"dns",
".",
"IsSubDomain",
"(",
"zone",
",",
"mx",
".",
"Mx",
")",
"{",
"m1",
",",
"e1",
":=",
"b",
".",
"Lookup",
"(",
"state",
",",
"mx",
".",
"Mx",
",",
"dns",
".",
"TypeA",
")",
"\n",
"if",
"e1",
"==",
"nil",
"{",
"extra",
"=",
"append",
"(",
"extra",
",",
"m1",
".",
"Answer",
"...",
")",
"\n",
"}",
"\n",
"m1",
",",
"e1",
"=",
"b",
".",
"Lookup",
"(",
"state",
",",
"mx",
".",
"Mx",
",",
"dns",
".",
"TypeAAAA",
")",
"\n",
"if",
"e1",
"==",
"nil",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"m1",
".",
"Answer",
"{",
"if",
"_",
",",
"ok",
":=",
"a",
".",
"(",
"*",
"dns",
".",
"CNAME",
")",
";",
"!",
"ok",
"{",
"extra",
"=",
"append",
"(",
"extra",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"state1",
":=",
"state",
".",
"NewWithQuestion",
"(",
"mx",
".",
"Mx",
",",
"dns",
".",
"TypeA",
")",
"\n",
"addr",
",",
"e1",
":=",
"A",
"(",
"b",
",",
"zone",
",",
"state1",
",",
"nil",
",",
"opt",
")",
"\n",
"if",
"e1",
"==",
"nil",
"{",
"extra",
"=",
"append",
"(",
"extra",
",",
"addr",
"...",
")",
"\n",
"}",
"\n",
"case",
"dns",
".",
"TypeA",
",",
"dns",
".",
"TypeAAAA",
":",
"serv",
".",
"Host",
"=",
"msg",
".",
"Domain",
"(",
"serv",
".",
"Key",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"serv",
".",
"NewMX",
"(",
"state",
".",
"QName",
"(",
")",
")",
")",
"\n",
"extra",
"=",
"append",
"(",
"extra",
",",
"newAddress",
"(",
"serv",
",",
"serv",
".",
"Host",
",",
"ip",
",",
"what",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"records",
",",
"extra",
",",
"nil",
"\n",
"}"
] | // MX returns MX records from the Backend. If the Target is not a name but an IP address, a name is created on the fly. | [
"MX",
"returns",
"MX",
"records",
"from",
"the",
"Backend",
".",
"If",
"the",
"Target",
"is",
"not",
"a",
"name",
"but",
"an",
"IP",
"address",
"a",
"name",
"is",
"created",
"on",
"the",
"fly",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/backend_lookup.go#L226-L280 | train |
inverse-inc/packetfence | go/coredns/plugin/backend_lookup.go | CNAME | func CNAME(b ServiceBackend, zone string, state request.Request, opt Options) (records []dns.RR, err error) {
services, err := b.Services(state, true, opt)
if err != nil {
return nil, err
}
if len(services) > 0 {
serv := services[0]
if ip := net.ParseIP(serv.Host); ip == nil {
records = append(records, serv.NewCNAME(state.QName(), serv.Host))
}
}
return records, nil
} | go | func CNAME(b ServiceBackend, zone string, state request.Request, opt Options) (records []dns.RR, err error) {
services, err := b.Services(state, true, opt)
if err != nil {
return nil, err
}
if len(services) > 0 {
serv := services[0]
if ip := net.ParseIP(serv.Host); ip == nil {
records = append(records, serv.NewCNAME(state.QName(), serv.Host))
}
}
return records, nil
} | [
"func",
"CNAME",
"(",
"b",
"ServiceBackend",
",",
"zone",
"string",
",",
"state",
"request",
".",
"Request",
",",
"opt",
"Options",
")",
"(",
"records",
"[",
"]",
"dns",
".",
"RR",
",",
"err",
"error",
")",
"{",
"services",
",",
"err",
":=",
"b",
".",
"Services",
"(",
"state",
",",
"true",
",",
"opt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"services",
")",
">",
"0",
"{",
"serv",
":=",
"services",
"[",
"0",
"]",
"\n",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"serv",
".",
"Host",
")",
";",
"ip",
"==",
"nil",
"{",
"records",
"=",
"append",
"(",
"records",
",",
"serv",
".",
"NewCNAME",
"(",
"state",
".",
"QName",
"(",
")",
",",
"serv",
".",
"Host",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"records",
",",
"nil",
"\n",
"}"
] | // CNAME returns CNAME records from the backend or an error. | [
"CNAME",
"returns",
"CNAME",
"records",
"from",
"the",
"backend",
"or",
"an",
"error",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/backend_lookup.go#L283-L296 | train |
inverse-inc/packetfence | go/coredns/plugin/backend_lookup.go | BackendError | func BackendError(b ServiceBackend, zone string, rcode int, state request.Request, err error, opt Options) (int, error) {
m := new(dns.Msg)
m.SetRcode(state.Req, rcode)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Ns, _ = SOA(b, zone, state, opt)
state.SizeAndDo(m)
state.W.WriteMsg(m)
// Return success as the rcode to signal we have written to the client.
return dns.RcodeSuccess, err
} | go | func BackendError(b ServiceBackend, zone string, rcode int, state request.Request, err error, opt Options) (int, error) {
m := new(dns.Msg)
m.SetRcode(state.Req, rcode)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Ns, _ = SOA(b, zone, state, opt)
state.SizeAndDo(m)
state.W.WriteMsg(m)
// Return success as the rcode to signal we have written to the client.
return dns.RcodeSuccess, err
} | [
"func",
"BackendError",
"(",
"b",
"ServiceBackend",
",",
"zone",
"string",
",",
"rcode",
"int",
",",
"state",
"request",
".",
"Request",
",",
"err",
"error",
",",
"opt",
"Options",
")",
"(",
"int",
",",
"error",
")",
"{",
"m",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"m",
".",
"SetRcode",
"(",
"state",
".",
"Req",
",",
"rcode",
")",
"\n",
"m",
".",
"Authoritative",
",",
"m",
".",
"RecursionAvailable",
",",
"m",
".",
"Compress",
"=",
"true",
",",
"true",
",",
"true",
"\n",
"m",
".",
"Ns",
",",
"_",
"=",
"SOA",
"(",
"b",
",",
"zone",
",",
"state",
",",
"opt",
")",
"\n",
"state",
".",
"SizeAndDo",
"(",
"m",
")",
"\n",
"state",
".",
"W",
".",
"WriteMsg",
"(",
"m",
")",
"\n",
"return",
"dns",
".",
"RcodeSuccess",
",",
"err",
"\n",
"}"
] | // BackendError writes an error response to the client. | [
"BackendError",
"writes",
"an",
"error",
"response",
"to",
"the",
"client",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/backend_lookup.go#L383-L393 | train |
inverse-inc/packetfence | go/coredns/plugin/reverse/network.go | hostnameToIP | func (network *network) hostnameToIP(rname string) net.IP {
var matchedIP net.IP
match := network.RegexMatchIP.FindStringSubmatch(rname)
if len(match) != 2 {
return nil
}
if network.IPnet.IP.To4() != nil {
matchedIP = net.ParseIP(match[1])
} else {
// TODO: can probably just allocate a []byte and use that.
var buf bytes.Buffer
// convert back to an valid ipv6 string with colons
for i := 0; i < 8*4; i += 4 {
buf.WriteString(match[1][i : i+4])
if i < 28 {
buf.WriteString(":")
}
}
matchedIP = net.ParseIP(buf.String())
}
// No valid ip or it does not belong to this network
if matchedIP == nil || !network.IPnet.Contains(matchedIP) {
return nil
}
return matchedIP
} | go | func (network *network) hostnameToIP(rname string) net.IP {
var matchedIP net.IP
match := network.RegexMatchIP.FindStringSubmatch(rname)
if len(match) != 2 {
return nil
}
if network.IPnet.IP.To4() != nil {
matchedIP = net.ParseIP(match[1])
} else {
// TODO: can probably just allocate a []byte and use that.
var buf bytes.Buffer
// convert back to an valid ipv6 string with colons
for i := 0; i < 8*4; i += 4 {
buf.WriteString(match[1][i : i+4])
if i < 28 {
buf.WriteString(":")
}
}
matchedIP = net.ParseIP(buf.String())
}
// No valid ip or it does not belong to this network
if matchedIP == nil || !network.IPnet.Contains(matchedIP) {
return nil
}
return matchedIP
} | [
"func",
"(",
"network",
"*",
"network",
")",
"hostnameToIP",
"(",
"rname",
"string",
")",
"net",
".",
"IP",
"{",
"var",
"matchedIP",
"net",
".",
"IP",
"\n",
"match",
":=",
"network",
".",
"RegexMatchIP",
".",
"FindStringSubmatch",
"(",
"rname",
")",
"\n",
"if",
"len",
"(",
"match",
")",
"!=",
"2",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"network",
".",
"IPnet",
".",
"IP",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"matchedIP",
"=",
"net",
".",
"ParseIP",
"(",
"match",
"[",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"8",
"*",
"4",
";",
"i",
"+=",
"4",
"{",
"buf",
".",
"WriteString",
"(",
"match",
"[",
"1",
"]",
"[",
"i",
":",
"i",
"+",
"4",
"]",
")",
"\n",
"if",
"i",
"<",
"28",
"{",
"buf",
".",
"WriteString",
"(",
"\":\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"matchedIP",
"=",
"net",
".",
"ParseIP",
"(",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"matchedIP",
"==",
"nil",
"||",
"!",
"network",
".",
"IPnet",
".",
"Contains",
"(",
"matchedIP",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"matchedIP",
"\n",
"}"
] | // hostnameToIP converts the hostname back to an ip, based on the template
// returns nil if there is no IP found. | [
"hostnameToIP",
"converts",
"the",
"hostname",
"back",
"to",
"an",
"ip",
"based",
"on",
"the",
"template",
"returns",
"nil",
"if",
"there",
"is",
"no",
"IP",
"found",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/reverse/network.go#L26-L55 | train |
inverse-inc/packetfence | go/coredns/plugin/reverse/network.go | ipToHostname | func (network *network) ipToHostname(ip net.IP) (name string) {
if ipv4 := ip.To4(); ipv4 != nil {
// replace . to -
name = ipv4.String()
} else {
// assume v6
// ensure zeros are present in string
buf := make([]byte, 0, len(ip)*4)
for i := 0; i < len(ip); i++ {
v := ip[i]
buf = append(buf, hexDigit[v>>4])
buf = append(buf, hexDigit[v&0xF])
}
name = string(buf)
}
// inject the converted ip into the fqdn template
return strings.Replace(network.Template, templateNameIP, name, 1)
} | go | func (network *network) ipToHostname(ip net.IP) (name string) {
if ipv4 := ip.To4(); ipv4 != nil {
// replace . to -
name = ipv4.String()
} else {
// assume v6
// ensure zeros are present in string
buf := make([]byte, 0, len(ip)*4)
for i := 0; i < len(ip); i++ {
v := ip[i]
buf = append(buf, hexDigit[v>>4])
buf = append(buf, hexDigit[v&0xF])
}
name = string(buf)
}
// inject the converted ip into the fqdn template
return strings.Replace(network.Template, templateNameIP, name, 1)
} | [
"func",
"(",
"network",
"*",
"network",
")",
"ipToHostname",
"(",
"ip",
"net",
".",
"IP",
")",
"(",
"name",
"string",
")",
"{",
"if",
"ipv4",
":=",
"ip",
".",
"To4",
"(",
")",
";",
"ipv4",
"!=",
"nil",
"{",
"name",
"=",
"ipv4",
".",
"String",
"(",
")",
"\n",
"}",
"else",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"ip",
")",
"*",
"4",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ip",
")",
";",
"i",
"++",
"{",
"v",
":=",
"ip",
"[",
"i",
"]",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"hexDigit",
"[",
"v",
">>",
"4",
"]",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"hexDigit",
"[",
"v",
"&",
"0xF",
"]",
")",
"\n",
"}",
"\n",
"name",
"=",
"string",
"(",
"buf",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Replace",
"(",
"network",
".",
"Template",
",",
"templateNameIP",
",",
"name",
",",
"1",
")",
"\n",
"}"
] | // ipToHostname converts an IP to an DNS compatible hostname and injects it into the template.domain. | [
"ipToHostname",
"converts",
"an",
"IP",
"to",
"an",
"DNS",
"compatible",
"hostname",
"and",
"injects",
"it",
"into",
"the",
"template",
".",
"domain",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/reverse/network.go#L58-L75 | train |
inverse-inc/packetfence | go/coredns/plugin/health/healther.go | Ok | func (h *health) Ok() bool {
h.RLock()
defer h.RUnlock()
return h.ok
} | go | func (h *health) Ok() bool {
h.RLock()
defer h.RUnlock()
return h.ok
} | [
"func",
"(",
"h",
"*",
"health",
")",
"Ok",
"(",
")",
"bool",
"{",
"h",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"h",
".",
"ok",
"\n",
"}"
] | // Ok returns the global health status of all plugin configured in this server. | [
"Ok",
"returns",
"the",
"global",
"health",
"status",
"of",
"all",
"plugin",
"configured",
"in",
"this",
"server",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/health/healther.go#L16-L20 | train |
inverse-inc/packetfence | go/coredns/plugin/health/healther.go | SetOk | func (h *health) SetOk(ok bool) {
h.Lock()
defer h.Unlock()
h.ok = ok
} | go | func (h *health) SetOk(ok bool) {
h.Lock()
defer h.Unlock()
h.ok = ok
} | [
"func",
"(",
"h",
"*",
"health",
")",
"SetOk",
"(",
"ok",
"bool",
")",
"{",
"h",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"Unlock",
"(",
")",
"\n",
"h",
".",
"ok",
"=",
"ok",
"\n",
"}"
] | // SetOk sets the global health status of all plugin configured in this server. | [
"SetOk",
"sets",
"the",
"global",
"health",
"status",
"of",
"all",
"plugin",
"configured",
"in",
"this",
"server",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/health/healther.go#L23-L27 | train |
inverse-inc/packetfence | go/coredns/plugin/health/healther.go | poll | func (h *health) poll() {
for _, m := range h.h {
if !m.Health() {
h.SetOk(false)
return
}
}
h.SetOk(true)
} | go | func (h *health) poll() {
for _, m := range h.h {
if !m.Health() {
h.SetOk(false)
return
}
}
h.SetOk(true)
} | [
"func",
"(",
"h",
"*",
"health",
")",
"poll",
"(",
")",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"h",
".",
"h",
"{",
"if",
"!",
"m",
".",
"Health",
"(",
")",
"{",
"h",
".",
"SetOk",
"(",
"false",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"h",
".",
"SetOk",
"(",
"true",
")",
"\n",
"}"
] | // poll polls all healthers and sets the global state. | [
"poll",
"polls",
"all",
"healthers",
"and",
"sets",
"the",
"global",
"state",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/health/healther.go#L30-L38 | train |
inverse-inc/packetfence | go/coredns/plugin/proxy/lookup.go | NewLookupWithOption | func NewLookupWithOption(hosts []string, opts Options) Proxy {
p := Proxy{Next: nil}
// TODO(miek): this needs to be unified with upstream.go's NewStaticUpstreams, caddy uses NewHost
// we should copy/make something similar.
upstream := &staticUpstream{
from: ".",
HealthCheck: healthcheck.HealthCheck{
FailTimeout: 5 * time.Second,
MaxFails: 3,
},
ex: newDNSExWithOption(opts),
}
upstream.Hosts = make([]*healthcheck.UpstreamHost, len(hosts))
for i, host := range hosts {
uh := &healthcheck.UpstreamHost{
Name: host,
FailTimeout: upstream.FailTimeout,
CheckDown: checkDownFunc(upstream),
}
upstream.Hosts[i] = uh
}
p.Upstreams = &[]Upstream{upstream}
return p
} | go | func NewLookupWithOption(hosts []string, opts Options) Proxy {
p := Proxy{Next: nil}
// TODO(miek): this needs to be unified with upstream.go's NewStaticUpstreams, caddy uses NewHost
// we should copy/make something similar.
upstream := &staticUpstream{
from: ".",
HealthCheck: healthcheck.HealthCheck{
FailTimeout: 5 * time.Second,
MaxFails: 3,
},
ex: newDNSExWithOption(opts),
}
upstream.Hosts = make([]*healthcheck.UpstreamHost, len(hosts))
for i, host := range hosts {
uh := &healthcheck.UpstreamHost{
Name: host,
FailTimeout: upstream.FailTimeout,
CheckDown: checkDownFunc(upstream),
}
upstream.Hosts[i] = uh
}
p.Upstreams = &[]Upstream{upstream}
return p
} | [
"func",
"NewLookupWithOption",
"(",
"hosts",
"[",
"]",
"string",
",",
"opts",
"Options",
")",
"Proxy",
"{",
"p",
":=",
"Proxy",
"{",
"Next",
":",
"nil",
"}",
"\n",
"upstream",
":=",
"&",
"staticUpstream",
"{",
"from",
":",
"\".\"",
",",
"HealthCheck",
":",
"healthcheck",
".",
"HealthCheck",
"{",
"FailTimeout",
":",
"5",
"*",
"time",
".",
"Second",
",",
"MaxFails",
":",
"3",
",",
"}",
",",
"ex",
":",
"newDNSExWithOption",
"(",
"opts",
")",
",",
"}",
"\n",
"upstream",
".",
"Hosts",
"=",
"make",
"(",
"[",
"]",
"*",
"healthcheck",
".",
"UpstreamHost",
",",
"len",
"(",
"hosts",
")",
")",
"\n",
"for",
"i",
",",
"host",
":=",
"range",
"hosts",
"{",
"uh",
":=",
"&",
"healthcheck",
".",
"UpstreamHost",
"{",
"Name",
":",
"host",
",",
"FailTimeout",
":",
"upstream",
".",
"FailTimeout",
",",
"CheckDown",
":",
"checkDownFunc",
"(",
"upstream",
")",
",",
"}",
"\n",
"upstream",
".",
"Hosts",
"[",
"i",
"]",
"=",
"uh",
"\n",
"}",
"\n",
"p",
".",
"Upstreams",
"=",
"&",
"[",
"]",
"Upstream",
"{",
"upstream",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // NewLookupWithOption process creates a simple round robin forward with potentially forced proto for upstream. | [
"NewLookupWithOption",
"process",
"creates",
"a",
"simple",
"round",
"robin",
"forward",
"with",
"potentially",
"forced",
"proto",
"for",
"upstream",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/lookup.go#L22-L48 | train |
inverse-inc/packetfence | go/coredns/plugin/proxy/lookup.go | Lookup | func (p Proxy) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) {
req := new(dns.Msg)
req.SetQuestion(name, typ)
state.SizeAndDo(req)
state2 := request.Request{W: state.W, Req: req}
return p.lookup(state2)
} | go | func (p Proxy) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) {
req := new(dns.Msg)
req.SetQuestion(name, typ)
state.SizeAndDo(req)
state2 := request.Request{W: state.W, Req: req}
return p.lookup(state2)
} | [
"func",
"(",
"p",
"Proxy",
")",
"Lookup",
"(",
"state",
"request",
".",
"Request",
",",
"name",
"string",
",",
"typ",
"uint16",
")",
"(",
"*",
"dns",
".",
"Msg",
",",
"error",
")",
"{",
"req",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"req",
".",
"SetQuestion",
"(",
"name",
",",
"typ",
")",
"\n",
"state",
".",
"SizeAndDo",
"(",
"req",
")",
"\n",
"state2",
":=",
"request",
".",
"Request",
"{",
"W",
":",
"state",
".",
"W",
",",
"Req",
":",
"req",
"}",
"\n",
"return",
"p",
".",
"lookup",
"(",
"state2",
")",
"\n",
"}"
] | // Lookup will use name and type to forge a new message and will send that upstream. It will
// set any EDNS0 options correctly so that downstream will be able to process the reply. | [
"Lookup",
"will",
"use",
"name",
"and",
"type",
"to",
"forge",
"a",
"new",
"message",
"and",
"will",
"send",
"that",
"upstream",
".",
"It",
"will",
"set",
"any",
"EDNS0",
"options",
"correctly",
"so",
"that",
"downstream",
"will",
"be",
"able",
"to",
"process",
"the",
"reply",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/lookup.go#L52-L60 | train |
inverse-inc/packetfence | go/coredns/plugin/proxy/lookup.go | Forward | func (p Proxy) Forward(state request.Request) (*dns.Msg, error) {
return p.lookup(state)
} | go | func (p Proxy) Forward(state request.Request) (*dns.Msg, error) {
return p.lookup(state)
} | [
"func",
"(",
"p",
"Proxy",
")",
"Forward",
"(",
"state",
"request",
".",
"Request",
")",
"(",
"*",
"dns",
".",
"Msg",
",",
"error",
")",
"{",
"return",
"p",
".",
"lookup",
"(",
"state",
")",
"\n",
"}"
] | // Forward forward the request in state as-is. Unlike Lookup that adds EDNS0 suffix to the message. | [
"Forward",
"forward",
"the",
"request",
"in",
"state",
"as",
"-",
"is",
".",
"Unlike",
"Lookup",
"that",
"adds",
"EDNS0",
"suffix",
"to",
"the",
"message",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/lookup.go#L63-L65 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/internalsrv/internal.go | Write | func (w internalResponseWriter) Write(b []byte) (int, error) {
if isInternalRedirect(w) {
return 0, nil
}
return w.ResponseWriter.Write(b)
} | go | func (w internalResponseWriter) Write(b []byte) (int, error) {
if isInternalRedirect(w) {
return 0, nil
}
return w.ResponseWriter.Write(b)
} | [
"func",
"(",
"w",
"internalResponseWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"isInternalRedirect",
"(",
"w",
")",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"return",
"w",
".",
"ResponseWriter",
".",
"Write",
"(",
"b",
")",
"\n",
"}"
] | // Write ignores the call if the response should be redirected to an internal
// location. | [
"Write",
"ignores",
"the",
"call",
"if",
"the",
"response",
"should",
"be",
"redirected",
"to",
"an",
"internal",
"location",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/internalsrv/internal.go#L91-L96 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/replacer/replacer.go | Set | func (r replacer) Set(key, value string) {
r.replacements["{"+key+"}"] = value
} | go | func (r replacer) Set(key, value string) {
r.replacements["{"+key+"}"] = value
} | [
"func",
"(",
"r",
"replacer",
")",
"Set",
"(",
"key",
",",
"value",
"string",
")",
"{",
"r",
".",
"replacements",
"[",
"\"{\"",
"+",
"key",
"+",
"\"}\"",
"]",
"=",
"value",
"\n",
"}"
] | // Set sets key to value in the replacements map. | [
"Set",
"sets",
"key",
"to",
"value",
"in",
"the",
"replacements",
"map",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/replacer/replacer.go#L105-L107 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | NewPool | func NewPool() Pool {
p := Pool{}
p.lock = timedlock.NewRWLock()
p.lock.Timeout = 1 * time.Second
p.lock.RTimeout = 3 * time.Second
p.lock.PrintErrors = false
p.lock.Panic = false
p.structs = make(map[string]interface{})
return p
} | go | func NewPool() Pool {
p := Pool{}
p.lock = timedlock.NewRWLock()
p.lock.Timeout = 1 * time.Second
p.lock.RTimeout = 3 * time.Second
p.lock.PrintErrors = false
p.lock.Panic = false
p.structs = make(map[string]interface{})
return p
} | [
"func",
"NewPool",
"(",
")",
"Pool",
"{",
"p",
":=",
"Pool",
"{",
"}",
"\n",
"p",
".",
"lock",
"=",
"timedlock",
".",
"NewRWLock",
"(",
")",
"\n",
"p",
".",
"lock",
".",
"Timeout",
"=",
"1",
"*",
"time",
".",
"Second",
"\n",
"p",
".",
"lock",
".",
"RTimeout",
"=",
"3",
"*",
"time",
".",
"Second",
"\n",
"p",
".",
"lock",
".",
"PrintErrors",
"=",
"false",
"\n",
"p",
".",
"lock",
".",
"Panic",
"=",
"false",
"\n",
"p",
".",
"structs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // Create a new Pool with a 1 second refresh timeout and initialize the lock | [
"Create",
"a",
"new",
"Pool",
"with",
"a",
"1",
"second",
"refresh",
"timeout",
"and",
"initialize",
"the",
"lock"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L36-L45 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | ReadLock | func (p *Pool) ReadLock(ctx context.Context) (uint64, error) {
return p.lock.RLock()
} | go | func (p *Pool) ReadLock(ctx context.Context) (uint64, error) {
return p.lock.RLock()
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"ReadLock",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"return",
"p",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"}"
] | // Acquire a read lock on the pool
// All the goroutines that use resources from the pool should call this and release it when they are done
// Long running processes should aim to retain this lock for the smallest time possible since Refresh will need a RW lock to refresh the resources
// This lock can be acquired multiple times given its a read lock | [
"Acquire",
"a",
"read",
"lock",
"on",
"the",
"pool",
"All",
"the",
"goroutines",
"that",
"use",
"resources",
"from",
"the",
"pool",
"should",
"call",
"this",
"and",
"release",
"it",
"when",
"they",
"are",
"done",
"Long",
"running",
"processes",
"should",
"aim",
"to",
"retain",
"this",
"lock",
"for",
"the",
"smallest",
"time",
"possible",
"since",
"Refresh",
"will",
"need",
"a",
"RW",
"lock",
"to",
"refresh",
"the",
"resources",
"This",
"lock",
"can",
"be",
"acquired",
"multiple",
"times",
"given",
"its",
"a",
"read",
"lock"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L51-L53 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | ReadUnlock | func (p *Pool) ReadUnlock(ctx context.Context, id uint64) {
p.lock.RUnlock(id)
} | go | func (p *Pool) ReadUnlock(ctx context.Context, id uint64) {
p.lock.RUnlock(id)
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"ReadUnlock",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"uint64",
")",
"{",
"p",
".",
"lock",
".",
"RUnlock",
"(",
"id",
")",
"\n",
"}"
] | // Unlock the read lock | [
"Unlock",
"the",
"read",
"lock"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L56-L58 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | AddRefreshable | func (p *Pool) AddRefreshable(ctx context.Context, r Refreshable) {
id, err := p.lock.Lock()
if err == nil {
defer p.lock.Unlock(id)
p.refreshables = append(p.refreshables, r)
r.Refresh(ctx)
}
} | go | func (p *Pool) AddRefreshable(ctx context.Context, r Refreshable) {
id, err := p.lock.Lock()
if err == nil {
defer p.lock.Unlock(id)
p.refreshables = append(p.refreshables, r)
r.Refresh(ctx)
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"AddRefreshable",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"Refreshable",
")",
"{",
"id",
",",
"err",
":=",
"p",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"defer",
"p",
".",
"lock",
".",
"Unlock",
"(",
"id",
")",
"\n",
"p",
".",
"refreshables",
"=",
"append",
"(",
"p",
".",
"refreshables",
",",
"r",
")",
"\n",
"r",
".",
"Refresh",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"}"
] | // Add a refreshable resource to the pool
// Requires the RW lock and will not timeout like Refresh does | [
"Add",
"a",
"refreshable",
"resource",
"to",
"the",
"pool",
"Requires",
"the",
"RW",
"lock",
"and",
"will",
"not",
"timeout",
"like",
"Refresh",
"does"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L62-L69 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | AddStruct | func (p *Pool) AddStruct(ctx context.Context, s interface{}) {
id, err := p.lock.Lock()
if err == nil {
defer p.lock.Unlock(id)
addr := fmt.Sprintf("%p", s)
log.LoggerWContext(ctx).Debug("Adding struct with address " + addr + " to the pool")
p.structs[addr] = s
p.refreshStruct(ctx, s)
}
} | go | func (p *Pool) AddStruct(ctx context.Context, s interface{}) {
id, err := p.lock.Lock()
if err == nil {
defer p.lock.Unlock(id)
addr := fmt.Sprintf("%p", s)
log.LoggerWContext(ctx).Debug("Adding struct with address " + addr + " to the pool")
p.structs[addr] = s
p.refreshStruct(ctx, s)
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"AddStruct",
"(",
"ctx",
"context",
".",
"Context",
",",
"s",
"interface",
"{",
"}",
")",
"{",
"id",
",",
"err",
":=",
"p",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"defer",
"p",
".",
"lock",
".",
"Unlock",
"(",
"id",
")",
"\n",
"addr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%p\"",
",",
"s",
")",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Adding struct with address \"",
"+",
"addr",
"+",
"\" to the pool\"",
")",
"\n",
"p",
".",
"structs",
"[",
"addr",
"]",
"=",
"s",
"\n",
"p",
".",
"refreshStruct",
"(",
"ctx",
",",
"s",
")",
"\n",
"}",
"\n",
"}"
] | // Add a struct to the pool
// Requires the RW lock and will not timeout like Refresh does | [
"Add",
"a",
"struct",
"to",
"the",
"pool",
"Requires",
"the",
"RW",
"lock",
"and",
"will",
"not",
"timeout",
"like",
"Refresh",
"does"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L73-L84 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | refreshRefreshables | func (p *Pool) refreshRefreshables(ctx context.Context) {
for _, r := range p.refreshables {
r.Refresh(ctx)
}
} | go | func (p *Pool) refreshRefreshables(ctx context.Context) {
for _, r := range p.refreshables {
r.Refresh(ctx)
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"refreshRefreshables",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"p",
".",
"refreshables",
"{",
"r",
".",
"Refresh",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"}"
] | // Refresh all the refreshables of the pool | [
"Refresh",
"all",
"the",
"refreshables",
"of",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L87-L91 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | refreshStruct | func (p *Pool) refreshStruct(ctx context.Context, s interface{}) {
v := reflect.ValueOf(s)
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
// Check if s itself is a PfconfigObject, otherwise, we cycle though its fields and process them
if o, ok := v.Addr().Interface().(PfconfigObject); ok {
FetchDecodeSocketCache(ctx, o)
} else {
for i := 0; i < v.NumField(); i++ {
field := v.Field(i).Addr()
if o, ok := field.Interface().(PfconfigObject); ok {
FetchDecodeSocketCache(ctx, o)
} else {
p.refreshStruct(ctx, field.Interface())
}
}
}
} | go | func (p *Pool) refreshStruct(ctx context.Context, s interface{}) {
v := reflect.ValueOf(s)
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
// Check if s itself is a PfconfigObject, otherwise, we cycle though its fields and process them
if o, ok := v.Addr().Interface().(PfconfigObject); ok {
FetchDecodeSocketCache(ctx, o)
} else {
for i := 0; i < v.NumField(); i++ {
field := v.Field(i).Addr()
if o, ok := field.Interface().(PfconfigObject); ok {
FetchDecodeSocketCache(ctx, o)
} else {
p.refreshStruct(ctx, field.Interface())
}
}
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"refreshStruct",
"(",
"ctx",
"context",
".",
"Context",
",",
"s",
"interface",
"{",
"}",
")",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"s",
")",
"\n",
"for",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"||",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"o",
",",
"ok",
":=",
"v",
".",
"Addr",
"(",
")",
".",
"Interface",
"(",
")",
".",
"(",
"PfconfigObject",
")",
";",
"ok",
"{",
"FetchDecodeSocketCache",
"(",
"ctx",
",",
"o",
")",
"\n",
"}",
"else",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"v",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"field",
":=",
"v",
".",
"Field",
"(",
"i",
")",
".",
"Addr",
"(",
")",
"\n",
"if",
"o",
",",
"ok",
":=",
"field",
".",
"Interface",
"(",
")",
".",
"(",
"PfconfigObject",
")",
";",
"ok",
"{",
"FetchDecodeSocketCache",
"(",
"ctx",
",",
"o",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"refreshStruct",
"(",
"ctx",
",",
"field",
".",
"Interface",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Refresh a struct
// If this struct is a PfconfigObject, it will be sent directly to FetchDecodeSocketCache
// Otherwise, the struct fields and sub-fields will be analyzed to find all the PfconfigObjects and these will be sent to FetchDecodeSocketCache | [
"Refresh",
"a",
"struct",
"If",
"this",
"struct",
"is",
"a",
"PfconfigObject",
"it",
"will",
"be",
"sent",
"directly",
"to",
"FetchDecodeSocketCache",
"Otherwise",
"the",
"struct",
"fields",
"and",
"sub",
"-",
"fields",
"will",
"be",
"analyzed",
"to",
"find",
"all",
"the",
"PfconfigObjects",
"and",
"these",
"will",
"be",
"sent",
"to",
"FetchDecodeSocketCache"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L96-L115 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | refreshStructs | func (p *Pool) refreshStructs(ctx context.Context) {
for _, o := range p.structs {
p.refreshStruct(ctx, o)
}
} | go | func (p *Pool) refreshStructs(ctx context.Context) {
for _, o := range p.structs {
p.refreshStruct(ctx, o)
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"refreshStructs",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"for",
"_",
",",
"o",
":=",
"range",
"p",
".",
"structs",
"{",
"p",
".",
"refreshStruct",
"(",
"ctx",
",",
"o",
")",
"\n",
"}",
"\n",
"}"
] | // Refresh all the structs of the pool | [
"Refresh",
"all",
"the",
"structs",
"of",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L118-L122 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | acquireWriteLock | func (p *Pool) acquireWriteLock(ctx context.Context) (bool, uint64) {
defer func() {
if r := recover(); r != nil {
log.LoggerWContext(ctx).Warn("Couldn't acquire lock for pfconfig pool")
}
}()
id, err := p.lock.Lock()
if err != nil {
panic("Couldn't acquire lock for pfconfig pool")
}
log.LoggerWContext(ctx).Debug("Acquired lock for pfconfig pool")
return err == nil, id
} | go | func (p *Pool) acquireWriteLock(ctx context.Context) (bool, uint64) {
defer func() {
if r := recover(); r != nil {
log.LoggerWContext(ctx).Warn("Couldn't acquire lock for pfconfig pool")
}
}()
id, err := p.lock.Lock()
if err != nil {
panic("Couldn't acquire lock for pfconfig pool")
}
log.LoggerWContext(ctx).Debug("Acquired lock for pfconfig pool")
return err == nil, id
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"acquireWriteLock",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"bool",
",",
"uint64",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"r",
":=",
"recover",
"(",
")",
";",
"r",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Warn",
"(",
"\"Couldn't acquire lock for pfconfig pool\"",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"id",
",",
"err",
":=",
"p",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"Couldn't acquire lock for pfconfig pool\"",
")",
"\n",
"}",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Acquired lock for pfconfig pool\"",
")",
"\n",
"return",
"err",
"==",
"nil",
",",
"id",
"\n",
"}"
] | // Attempts to obtain a RW lock with the timeout set in RefreshLockTimeout
// Even if the timeout gets reached, the lock will still be acquired when available but it will be immediately released
// This is done by sending a message twice in the timeoutChan, one will be caught by the main waiting goroutine, the other one by the lock-waiting goroutine
// When the lock-waiting goroutine is able to get something out of the timeoutChan channel, it knows it must release the lock immediately | [
"Attempts",
"to",
"obtain",
"a",
"RW",
"lock",
"with",
"the",
"timeout",
"set",
"in",
"RefreshLockTimeout",
"Even",
"if",
"the",
"timeout",
"gets",
"reached",
"the",
"lock",
"will",
"still",
"be",
"acquired",
"when",
"available",
"but",
"it",
"will",
"be",
"immediately",
"released",
"This",
"is",
"done",
"by",
"sending",
"a",
"message",
"twice",
"in",
"the",
"timeoutChan",
"one",
"will",
"be",
"caught",
"by",
"the",
"main",
"waiting",
"goroutine",
"the",
"other",
"one",
"by",
"the",
"lock",
"-",
"waiting",
"goroutine",
"When",
"the",
"lock",
"-",
"waiting",
"goroutine",
"is",
"able",
"to",
"get",
"something",
"out",
"of",
"the",
"timeoutChan",
"channel",
"it",
"knows",
"it",
"must",
"release",
"the",
"lock",
"immediately"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L128-L142 | train |
inverse-inc/packetfence | go/pfconfigdriver/pool.go | Refresh | func (p *Pool) Refresh(ctx context.Context) bool {
log.LoggerWContext(ctx).Debug("Refreshing pfconfig pool")
var locked bool
var id uint64
if locked, id = p.acquireWriteLock(ctx); !locked {
return false
}
log.LoggerWContext(ctx).Debug("Refresh got lock ID", id)
defer func(ctx context.Context) {
log.LoggerWContext(ctx).Debug("Refresh is releasing lock ID", id)
p.lock.Unlock(id)
}(ctx)
p.refreshStructs(ctx)
p.refreshRefreshables(ctx)
log.LoggerWContext(ctx).Debug("Finished refresh of pfconfig pool")
return true
} | go | func (p *Pool) Refresh(ctx context.Context) bool {
log.LoggerWContext(ctx).Debug("Refreshing pfconfig pool")
var locked bool
var id uint64
if locked, id = p.acquireWriteLock(ctx); !locked {
return false
}
log.LoggerWContext(ctx).Debug("Refresh got lock ID", id)
defer func(ctx context.Context) {
log.LoggerWContext(ctx).Debug("Refresh is releasing lock ID", id)
p.lock.Unlock(id)
}(ctx)
p.refreshStructs(ctx)
p.refreshRefreshables(ctx)
log.LoggerWContext(ctx).Debug("Finished refresh of pfconfig pool")
return true
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"Refresh",
"(",
"ctx",
"context",
".",
"Context",
")",
"bool",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Refreshing pfconfig pool\"",
")",
"\n",
"var",
"locked",
"bool",
"\n",
"var",
"id",
"uint64",
"\n",
"if",
"locked",
",",
"id",
"=",
"p",
".",
"acquireWriteLock",
"(",
"ctx",
")",
";",
"!",
"locked",
"{",
"return",
"false",
"\n",
"}",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Refresh got lock ID\"",
",",
"id",
")",
"\n",
"defer",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Refresh is releasing lock ID\"",
",",
"id",
")",
"\n",
"p",
".",
"lock",
".",
"Unlock",
"(",
"id",
")",
"\n",
"}",
"(",
"ctx",
")",
"\n",
"p",
".",
"refreshStructs",
"(",
"ctx",
")",
"\n",
"p",
".",
"refreshRefreshables",
"(",
"ctx",
")",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Finished refresh of pfconfig pool\"",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // Refresh all the structs and resources of the pool using the RW lock
// An attempt to get the RW lock will be done for up to RefreshLockTimeout | [
"Refresh",
"all",
"the",
"structs",
"and",
"resources",
"of",
"the",
"pool",
"using",
"the",
"RW",
"lock",
"An",
"attempt",
"to",
"get",
"the",
"RW",
"lock",
"will",
"be",
"done",
"for",
"up",
"to",
"RefreshLockTimeout"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L146-L164 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/rewrite/rewrite.go | Match | func (r *ComplexRule) Match(req *http.Request) bool {
// validate RequestMatcher
// includes if and path
if !r.RequestMatcher.Match(req) {
return false
}
// validate extensions
if !r.matchExt(req.URL.Path) {
return false
}
// if regex is nil, ignore
if r.Regexp == nil {
return true
}
// otherwise validate regex
return r.regexpMatches(req.URL.Path) != nil
} | go | func (r *ComplexRule) Match(req *http.Request) bool {
// validate RequestMatcher
// includes if and path
if !r.RequestMatcher.Match(req) {
return false
}
// validate extensions
if !r.matchExt(req.URL.Path) {
return false
}
// if regex is nil, ignore
if r.Regexp == nil {
return true
}
// otherwise validate regex
return r.regexpMatches(req.URL.Path) != nil
} | [
"func",
"(",
"r",
"*",
"ComplexRule",
")",
"Match",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"if",
"!",
"r",
".",
"RequestMatcher",
".",
"Match",
"(",
"req",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"r",
".",
"matchExt",
"(",
"req",
".",
"URL",
".",
"Path",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"r",
".",
"Regexp",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"r",
".",
"regexpMatches",
"(",
"req",
".",
"URL",
".",
"Path",
")",
"!=",
"nil",
"\n",
"}"
] | // Match satisfies httpserver.Config.
//
// Though ComplexRule embeds a RequestMatcher, additional
// checks are needed which requires a custom implementation. | [
"Match",
"satisfies",
"httpserver",
".",
"Config",
".",
"Though",
"ComplexRule",
"embeds",
"a",
"RequestMatcher",
"additional",
"checks",
"are",
"needed",
"which",
"requires",
"a",
"custom",
"implementation",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/rewrite/rewrite.go#L140-L158 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/response/typify.go | Typify | func Typify(m *dns.Msg, t time.Time) (Type, *dns.OPT) {
if m == nil {
return OtherError, nil
}
opt := m.IsEdns0()
do := false
if opt != nil {
do = opt.Do()
}
if m.Opcode == dns.OpcodeUpdate {
return Update, opt
}
// Check transfer and update first
if m.Opcode == dns.OpcodeNotify {
return Meta, opt
}
if len(m.Question) > 0 {
if m.Question[0].Qtype == dns.TypeAXFR || m.Question[0].Qtype == dns.TypeIXFR {
return Meta, opt
}
}
// If our message contains any expired sigs and we care about that, we should return expired
if do {
if expired := typifyExpired(m, t); expired {
return OtherError, opt
}
}
if len(m.Answer) > 0 && m.Rcode == dns.RcodeSuccess {
return NoError, opt
}
soa := false
ns := 0
for _, r := range m.Ns {
if r.Header().Rrtype == dns.TypeSOA {
soa = true
continue
}
if r.Header().Rrtype == dns.TypeNS {
ns++
}
}
if soa && m.Rcode == dns.RcodeSuccess {
return NoData, opt
}
if soa && m.Rcode == dns.RcodeNameError {
return NameError, opt
}
if ns > 0 && m.Rcode == dns.RcodeSuccess {
return Delegation, opt
}
if m.Rcode == dns.RcodeSuccess {
return NoError, opt
}
return OtherError, opt
} | go | func Typify(m *dns.Msg, t time.Time) (Type, *dns.OPT) {
if m == nil {
return OtherError, nil
}
opt := m.IsEdns0()
do := false
if opt != nil {
do = opt.Do()
}
if m.Opcode == dns.OpcodeUpdate {
return Update, opt
}
// Check transfer and update first
if m.Opcode == dns.OpcodeNotify {
return Meta, opt
}
if len(m.Question) > 0 {
if m.Question[0].Qtype == dns.TypeAXFR || m.Question[0].Qtype == dns.TypeIXFR {
return Meta, opt
}
}
// If our message contains any expired sigs and we care about that, we should return expired
if do {
if expired := typifyExpired(m, t); expired {
return OtherError, opt
}
}
if len(m.Answer) > 0 && m.Rcode == dns.RcodeSuccess {
return NoError, opt
}
soa := false
ns := 0
for _, r := range m.Ns {
if r.Header().Rrtype == dns.TypeSOA {
soa = true
continue
}
if r.Header().Rrtype == dns.TypeNS {
ns++
}
}
if soa && m.Rcode == dns.RcodeSuccess {
return NoData, opt
}
if soa && m.Rcode == dns.RcodeNameError {
return NameError, opt
}
if ns > 0 && m.Rcode == dns.RcodeSuccess {
return Delegation, opt
}
if m.Rcode == dns.RcodeSuccess {
return NoError, opt
}
return OtherError, opt
} | [
"func",
"Typify",
"(",
"m",
"*",
"dns",
".",
"Msg",
",",
"t",
"time",
".",
"Time",
")",
"(",
"Type",
",",
"*",
"dns",
".",
"OPT",
")",
"{",
"if",
"m",
"==",
"nil",
"{",
"return",
"OtherError",
",",
"nil",
"\n",
"}",
"\n",
"opt",
":=",
"m",
".",
"IsEdns0",
"(",
")",
"\n",
"do",
":=",
"false",
"\n",
"if",
"opt",
"!=",
"nil",
"{",
"do",
"=",
"opt",
".",
"Do",
"(",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"Opcode",
"==",
"dns",
".",
"OpcodeUpdate",
"{",
"return",
"Update",
",",
"opt",
"\n",
"}",
"\n",
"if",
"m",
".",
"Opcode",
"==",
"dns",
".",
"OpcodeNotify",
"{",
"return",
"Meta",
",",
"opt",
"\n",
"}",
"\n",
"if",
"len",
"(",
"m",
".",
"Question",
")",
">",
"0",
"{",
"if",
"m",
".",
"Question",
"[",
"0",
"]",
".",
"Qtype",
"==",
"dns",
".",
"TypeAXFR",
"||",
"m",
".",
"Question",
"[",
"0",
"]",
".",
"Qtype",
"==",
"dns",
".",
"TypeIXFR",
"{",
"return",
"Meta",
",",
"opt",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"do",
"{",
"if",
"expired",
":=",
"typifyExpired",
"(",
"m",
",",
"t",
")",
";",
"expired",
"{",
"return",
"OtherError",
",",
"opt",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"m",
".",
"Answer",
")",
">",
"0",
"&&",
"m",
".",
"Rcode",
"==",
"dns",
".",
"RcodeSuccess",
"{",
"return",
"NoError",
",",
"opt",
"\n",
"}",
"\n",
"soa",
":=",
"false",
"\n",
"ns",
":=",
"0",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"m",
".",
"Ns",
"{",
"if",
"r",
".",
"Header",
"(",
")",
".",
"Rrtype",
"==",
"dns",
".",
"TypeSOA",
"{",
"soa",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"r",
".",
"Header",
"(",
")",
".",
"Rrtype",
"==",
"dns",
".",
"TypeNS",
"{",
"ns",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"soa",
"&&",
"m",
".",
"Rcode",
"==",
"dns",
".",
"RcodeSuccess",
"{",
"return",
"NoData",
",",
"opt",
"\n",
"}",
"\n",
"if",
"soa",
"&&",
"m",
".",
"Rcode",
"==",
"dns",
".",
"RcodeNameError",
"{",
"return",
"NameError",
",",
"opt",
"\n",
"}",
"\n",
"if",
"ns",
">",
"0",
"&&",
"m",
".",
"Rcode",
"==",
"dns",
".",
"RcodeSuccess",
"{",
"return",
"Delegation",
",",
"opt",
"\n",
"}",
"\n",
"if",
"m",
".",
"Rcode",
"==",
"dns",
".",
"RcodeSuccess",
"{",
"return",
"NoError",
",",
"opt",
"\n",
"}",
"\n",
"return",
"OtherError",
",",
"opt",
"\n",
"}"
] | // Typify classifies a message, it returns the Type. | [
"Typify",
"classifies",
"a",
"message",
"it",
"returns",
"the",
"Type",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/response/typify.go#L54-L118 | train |
inverse-inc/packetfence | go/caddy/caddy/caddy.go | HasListenerWithAddress | func HasListenerWithAddress(addr string) bool {
instancesMu.Lock()
defer instancesMu.Unlock()
for _, inst := range instances {
for _, sln := range inst.servers {
if listenerAddrEqual(sln.listener, addr) {
return true
}
}
}
return false
} | go | func HasListenerWithAddress(addr string) bool {
instancesMu.Lock()
defer instancesMu.Unlock()
for _, inst := range instances {
for _, sln := range inst.servers {
if listenerAddrEqual(sln.listener, addr) {
return true
}
}
}
return false
} | [
"func",
"HasListenerWithAddress",
"(",
"addr",
"string",
")",
"bool",
"{",
"instancesMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"instancesMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"inst",
":=",
"range",
"instances",
"{",
"for",
"_",
",",
"sln",
":=",
"range",
"inst",
".",
"servers",
"{",
"if",
"listenerAddrEqual",
"(",
"sln",
".",
"listener",
",",
"addr",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasListenerWithAddress returns whether this package is
// tracking a server using a listener with the address
// addr. | [
"HasListenerWithAddress",
"returns",
"whether",
"this",
"package",
"is",
"tracking",
"a",
"server",
"using",
"a",
"listener",
"with",
"the",
"address",
"addr",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddy.go#L223-L234 | train |
inverse-inc/packetfence | go/caddy/caddy/caddy.go | ValidateAndExecuteDirectives | func ValidateAndExecuteDirectives(cdyfile Input, inst *Instance, justValidate bool) error {
// If parsing only inst will be nil, create an instance for this function call only.
if justValidate {
inst = &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)}
}
stypeName := cdyfile.ServerType()
stype, err := getServerType(stypeName)
if err != nil {
return err
}
inst.caddyfileInput = cdyfile
sblocks, err := loadServerBlocks(stypeName, cdyfile.Path(), bytes.NewReader(cdyfile.Body()))
if err != nil {
return err
}
inst.context = stype.NewContext()
if inst.context == nil {
return fmt.Errorf("server type %s produced a nil Context", stypeName)
}
sblocks, err = inst.context.InspectServerBlocks(cdyfile.Path(), sblocks)
if err != nil {
return err
}
err = executeDirectives(inst, cdyfile.Path(), stype.Directives(), sblocks, justValidate)
if err != nil {
return err
}
return nil
} | go | func ValidateAndExecuteDirectives(cdyfile Input, inst *Instance, justValidate bool) error {
// If parsing only inst will be nil, create an instance for this function call only.
if justValidate {
inst = &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)}
}
stypeName := cdyfile.ServerType()
stype, err := getServerType(stypeName)
if err != nil {
return err
}
inst.caddyfileInput = cdyfile
sblocks, err := loadServerBlocks(stypeName, cdyfile.Path(), bytes.NewReader(cdyfile.Body()))
if err != nil {
return err
}
inst.context = stype.NewContext()
if inst.context == nil {
return fmt.Errorf("server type %s produced a nil Context", stypeName)
}
sblocks, err = inst.context.InspectServerBlocks(cdyfile.Path(), sblocks)
if err != nil {
return err
}
err = executeDirectives(inst, cdyfile.Path(), stype.Directives(), sblocks, justValidate)
if err != nil {
return err
}
return nil
} | [
"func",
"ValidateAndExecuteDirectives",
"(",
"cdyfile",
"Input",
",",
"inst",
"*",
"Instance",
",",
"justValidate",
"bool",
")",
"error",
"{",
"if",
"justValidate",
"{",
"inst",
"=",
"&",
"Instance",
"{",
"serverType",
":",
"cdyfile",
".",
"ServerType",
"(",
")",
",",
"wg",
":",
"new",
"(",
"sync",
".",
"WaitGroup",
")",
"}",
"\n",
"}",
"\n",
"stypeName",
":=",
"cdyfile",
".",
"ServerType",
"(",
")",
"\n",
"stype",
",",
"err",
":=",
"getServerType",
"(",
"stypeName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"inst",
".",
"caddyfileInput",
"=",
"cdyfile",
"\n",
"sblocks",
",",
"err",
":=",
"loadServerBlocks",
"(",
"stypeName",
",",
"cdyfile",
".",
"Path",
"(",
")",
",",
"bytes",
".",
"NewReader",
"(",
"cdyfile",
".",
"Body",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"inst",
".",
"context",
"=",
"stype",
".",
"NewContext",
"(",
")",
"\n",
"if",
"inst",
".",
"context",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"server type %s produced a nil Context\"",
",",
"stypeName",
")",
"\n",
"}",
"\n",
"sblocks",
",",
"err",
"=",
"inst",
".",
"context",
".",
"InspectServerBlocks",
"(",
"cdyfile",
".",
"Path",
"(",
")",
",",
"sblocks",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"executeDirectives",
"(",
"inst",
",",
"cdyfile",
".",
"Path",
"(",
")",
",",
"stype",
".",
"Directives",
"(",
")",
",",
"sblocks",
",",
"justValidate",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateAndExecuteDirectives will load the server blocks from cdyfile
// by parsing it, then execute the directives configured by it and store
// the resulting server blocks into inst. If justValidate is true, parse
// callbacks will not be executed between directives, since the purpose
// is only to check the input for valid syntax. | [
"ValidateAndExecuteDirectives",
"will",
"load",
"the",
"server",
"blocks",
"from",
"cdyfile",
"by",
"parsing",
"it",
"then",
"execute",
"the",
"directives",
"configured",
"by",
"it",
"and",
"store",
"the",
"resulting",
"server",
"blocks",
"into",
"inst",
".",
"If",
"justValidate",
"is",
"true",
"parse",
"callbacks",
"will",
"not",
"be",
"executed",
"between",
"directives",
"since",
"the",
"purpose",
"is",
"only",
"to",
"check",
"the",
"input",
"for",
"valid",
"syntax",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddy.go#L516-L554 | train |
inverse-inc/packetfence | go/coredns/plugin/file/secondary.go | TransferIn | func (z *Zone) TransferIn() error {
if len(z.TransferFrom) == 0 {
return nil
}
m := new(dns.Msg)
m.SetAxfr(z.origin)
z1 := z.Copy()
var (
Err error
tr string
)
Transfer:
for _, tr = range z.TransferFrom {
t := new(dns.Transfer)
c, err := t.In(m, tr)
if err != nil {
log.Printf("[ERROR] Failed to setup transfer `%s' with `%q': %v", z.origin, tr, err)
Err = err
continue Transfer
}
for env := range c {
if env.Error != nil {
log.Printf("[ERROR] Failed to transfer `%s' from %q: %v", z.origin, tr, env.Error)
Err = env.Error
continue Transfer
}
for _, rr := range env.RR {
if err := z1.Insert(rr); err != nil {
log.Printf("[ERROR] Failed to parse transfer `%s' from: %q: %v", z.origin, tr, err)
Err = err
continue Transfer
}
}
}
Err = nil
break
}
if Err != nil {
return Err
}
z.Tree = z1.Tree
z.Apex = z1.Apex
*z.Expired = false
log.Printf("[INFO] Transferred: %s from %s", z.origin, tr)
return nil
} | go | func (z *Zone) TransferIn() error {
if len(z.TransferFrom) == 0 {
return nil
}
m := new(dns.Msg)
m.SetAxfr(z.origin)
z1 := z.Copy()
var (
Err error
tr string
)
Transfer:
for _, tr = range z.TransferFrom {
t := new(dns.Transfer)
c, err := t.In(m, tr)
if err != nil {
log.Printf("[ERROR] Failed to setup transfer `%s' with `%q': %v", z.origin, tr, err)
Err = err
continue Transfer
}
for env := range c {
if env.Error != nil {
log.Printf("[ERROR] Failed to transfer `%s' from %q: %v", z.origin, tr, env.Error)
Err = env.Error
continue Transfer
}
for _, rr := range env.RR {
if err := z1.Insert(rr); err != nil {
log.Printf("[ERROR] Failed to parse transfer `%s' from: %q: %v", z.origin, tr, err)
Err = err
continue Transfer
}
}
}
Err = nil
break
}
if Err != nil {
return Err
}
z.Tree = z1.Tree
z.Apex = z1.Apex
*z.Expired = false
log.Printf("[INFO] Transferred: %s from %s", z.origin, tr)
return nil
} | [
"func",
"(",
"z",
"*",
"Zone",
")",
"TransferIn",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"z",
".",
"TransferFrom",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"m",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"m",
".",
"SetAxfr",
"(",
"z",
".",
"origin",
")",
"\n",
"z1",
":=",
"z",
".",
"Copy",
"(",
")",
"\n",
"var",
"(",
"Err",
"error",
"\n",
"tr",
"string",
"\n",
")",
"\n",
"Transfer",
":",
"for",
"_",
",",
"tr",
"=",
"range",
"z",
".",
"TransferFrom",
"{",
"t",
":=",
"new",
"(",
"dns",
".",
"Transfer",
")",
"\n",
"c",
",",
"err",
":=",
"t",
".",
"In",
"(",
"m",
",",
"tr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[ERROR] Failed to setup transfer `%s' with `%q': %v\"",
",",
"z",
".",
"origin",
",",
"tr",
",",
"err",
")",
"\n",
"Err",
"=",
"err",
"\n",
"continue",
"Transfer",
"\n",
"}",
"\n",
"for",
"env",
":=",
"range",
"c",
"{",
"if",
"env",
".",
"Error",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[ERROR] Failed to transfer `%s' from %q: %v\"",
",",
"z",
".",
"origin",
",",
"tr",
",",
"env",
".",
"Error",
")",
"\n",
"Err",
"=",
"env",
".",
"Error",
"\n",
"continue",
"Transfer",
"\n",
"}",
"\n",
"for",
"_",
",",
"rr",
":=",
"range",
"env",
".",
"RR",
"{",
"if",
"err",
":=",
"z1",
".",
"Insert",
"(",
"rr",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[ERROR] Failed to parse transfer `%s' from: %q: %v\"",
",",
"z",
".",
"origin",
",",
"tr",
",",
"err",
")",
"\n",
"Err",
"=",
"err",
"\n",
"continue",
"Transfer",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"Err",
"=",
"nil",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"Err",
"!=",
"nil",
"{",
"return",
"Err",
"\n",
"}",
"\n",
"z",
".",
"Tree",
"=",
"z1",
".",
"Tree",
"\n",
"z",
".",
"Apex",
"=",
"z1",
".",
"Apex",
"\n",
"*",
"z",
".",
"Expired",
"=",
"false",
"\n",
"log",
".",
"Printf",
"(",
"\"[INFO] Transferred: %s from %s\"",
",",
"z",
".",
"origin",
",",
"tr",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // TransferIn retrieves the zone from the masters, parses it and sets it live. | [
"TransferIn",
"retrieves",
"the",
"zone",
"from",
"the",
"masters",
"parses",
"it",
"and",
"sets",
"it",
"live",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/file/secondary.go#L12-L60 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/recorder.go | NewResponseRecorder | func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
return &ResponseRecorder{
ResponseWriter: w,
status: http.StatusOK,
start: time.Now(),
}
} | go | func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
return &ResponseRecorder{
ResponseWriter: w,
status: http.StatusOK,
start: time.Now(),
}
} | [
"func",
"NewResponseRecorder",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"*",
"ResponseRecorder",
"{",
"return",
"&",
"ResponseRecorder",
"{",
"ResponseWriter",
":",
"w",
",",
"status",
":",
"http",
".",
"StatusOK",
",",
"start",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
"\n",
"}"
] | // NewResponseRecorder makes and returns a new responseRecorder,
// which captures the HTTP Status code from the ResponseWriter
// and also the length of the response body written through it.
// Because a status is not set unless WriteHeader is called
// explicitly, this constructor initializes with a status code
// of 200 to cover the default case. | [
"NewResponseRecorder",
"makes",
"and",
"returns",
"a",
"new",
"responseRecorder",
"which",
"captures",
"the",
"HTTP",
"Status",
"code",
"from",
"the",
"ResponseWriter",
"and",
"also",
"the",
"length",
"of",
"the",
"response",
"body",
"written",
"through",
"it",
".",
"Because",
"a",
"status",
"is",
"not",
"set",
"unless",
"WriteHeader",
"is",
"called",
"explicitly",
"this",
"constructor",
"initializes",
"with",
"a",
"status",
"code",
"of",
"200",
"to",
"cover",
"the",
"default",
"case",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/recorder.go#L36-L42 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/recorder.go | Flush | func (r *ResponseRecorder) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
} else {
panic(NonFlusherError{Underlying: r.ResponseWriter}) // should be recovered at the beginning of middleware stack
}
} | go | func (r *ResponseRecorder) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
} else {
panic(NonFlusherError{Underlying: r.ResponseWriter}) // should be recovered at the beginning of middleware stack
}
} | [
"func",
"(",
"r",
"*",
"ResponseRecorder",
")",
"Flush",
"(",
")",
"{",
"if",
"f",
",",
"ok",
":=",
"r",
".",
"ResponseWriter",
".",
"(",
"http",
".",
"Flusher",
")",
";",
"ok",
"{",
"f",
".",
"Flush",
"(",
")",
"\n",
"}",
"else",
"{",
"panic",
"(",
"NonFlusherError",
"{",
"Underlying",
":",
"r",
".",
"ResponseWriter",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // Flush implements http.Flusher. It simply wraps the underlying
// ResponseWriter's Flush method if there is one, or does nothing. | [
"Flush",
"implements",
"http",
".",
"Flusher",
".",
"It",
"simply",
"wraps",
"the",
"underlying",
"ResponseWriter",
"s",
"Flush",
"method",
"if",
"there",
"is",
"one",
"or",
"does",
"nothing",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/recorder.go#L82-L88 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/markdown/setup.go | setup | func setup(c *caddy.Controller) error {
mdconfigs, err := markdownParse(c)
if err != nil {
return err
}
cfg := httpserver.GetConfig(c)
md := Markdown{
Root: cfg.Root,
FileSys: http.Dir(cfg.Root),
Configs: mdconfigs,
IndexFiles: []string{"index.md"},
}
cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
md.Next = next
return md
})
return nil
} | go | func setup(c *caddy.Controller) error {
mdconfigs, err := markdownParse(c)
if err != nil {
return err
}
cfg := httpserver.GetConfig(c)
md := Markdown{
Root: cfg.Root,
FileSys: http.Dir(cfg.Root),
Configs: mdconfigs,
IndexFiles: []string{"index.md"},
}
cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
md.Next = next
return md
})
return nil
} | [
"func",
"setup",
"(",
"c",
"*",
"caddy",
".",
"Controller",
")",
"error",
"{",
"mdconfigs",
",",
"err",
":=",
"markdownParse",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cfg",
":=",
"httpserver",
".",
"GetConfig",
"(",
"c",
")",
"\n",
"md",
":=",
"Markdown",
"{",
"Root",
":",
"cfg",
".",
"Root",
",",
"FileSys",
":",
"http",
".",
"Dir",
"(",
"cfg",
".",
"Root",
")",
",",
"Configs",
":",
"mdconfigs",
",",
"IndexFiles",
":",
"[",
"]",
"string",
"{",
"\"index.md\"",
"}",
",",
"}",
"\n",
"cfg",
".",
"AddMiddleware",
"(",
"func",
"(",
"next",
"httpserver",
".",
"Handler",
")",
"httpserver",
".",
"Handler",
"{",
"md",
".",
"Next",
"=",
"next",
"\n",
"return",
"md",
"\n",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // setup configures a new Markdown middleware instance. | [
"setup",
"configures",
"a",
"new",
"Markdown",
"middleware",
"instance",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/markdown/setup.go#L20-L41 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/tls.go | HostQualifies | func HostQualifies(hostname string) bool {
return hostname != "localhost" && // localhost is ineligible
// hostname must not be empty
strings.TrimSpace(hostname) != "" &&
// must not contain wildcard (*) characters (until CA supports it)
!strings.Contains(hostname, "*") &&
// must not start or end with a dot
!strings.HasPrefix(hostname, ".") &&
!strings.HasSuffix(hostname, ".") &&
// cannot be an IP address, see
// https://community.letsencrypt.org/t/certificate-for-static-ip/84/2?u=mholt
net.ParseIP(hostname) == nil
} | go | func HostQualifies(hostname string) bool {
return hostname != "localhost" && // localhost is ineligible
// hostname must not be empty
strings.TrimSpace(hostname) != "" &&
// must not contain wildcard (*) characters (until CA supports it)
!strings.Contains(hostname, "*") &&
// must not start or end with a dot
!strings.HasPrefix(hostname, ".") &&
!strings.HasSuffix(hostname, ".") &&
// cannot be an IP address, see
// https://community.letsencrypt.org/t/certificate-for-static-ip/84/2?u=mholt
net.ParseIP(hostname) == nil
} | [
"func",
"HostQualifies",
"(",
"hostname",
"string",
")",
"bool",
"{",
"return",
"hostname",
"!=",
"\"localhost\"",
"&&",
"strings",
".",
"TrimSpace",
"(",
"hostname",
")",
"!=",
"\"\"",
"&&",
"!",
"strings",
".",
"Contains",
"(",
"hostname",
",",
"\"*\"",
")",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"hostname",
",",
"\".\"",
")",
"&&",
"!",
"strings",
".",
"HasSuffix",
"(",
"hostname",
",",
"\".\"",
")",
"&&",
"net",
".",
"ParseIP",
"(",
"hostname",
")",
"==",
"nil",
"\n",
"}"
] | // HostQualifies returns true if the hostname alone
// appears eligible for automatic HTTPS. For example,
// localhost, empty hostname, and IP addresses are
// not eligible because we cannot obtain certificates
// for those names. | [
"HostQualifies",
"returns",
"true",
"if",
"the",
"hostname",
"alone",
"appears",
"eligible",
"for",
"automatic",
"HTTPS",
".",
"For",
"example",
"localhost",
"empty",
"hostname",
"and",
"IP",
"addresses",
"are",
"not",
"eligible",
"because",
"we",
"cannot",
"obtain",
"certificates",
"for",
"those",
"names",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L31-L47 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/tls.go | saveCertResource | func saveCertResource(storage Storage, cert acme.CertificateResource) error {
// Save cert, private key, and metadata
siteData := &SiteData{
Cert: cert.Certificate,
Key: cert.PrivateKey,
}
var err error
siteData.Meta, err = json.MarshalIndent(&cert, "", "\t")
if err == nil {
err = storage.StoreSite(cert.Domain, siteData)
}
return err
} | go | func saveCertResource(storage Storage, cert acme.CertificateResource) error {
// Save cert, private key, and metadata
siteData := &SiteData{
Cert: cert.Certificate,
Key: cert.PrivateKey,
}
var err error
siteData.Meta, err = json.MarshalIndent(&cert, "", "\t")
if err == nil {
err = storage.StoreSite(cert.Domain, siteData)
}
return err
} | [
"func",
"saveCertResource",
"(",
"storage",
"Storage",
",",
"cert",
"acme",
".",
"CertificateResource",
")",
"error",
"{",
"siteData",
":=",
"&",
"SiteData",
"{",
"Cert",
":",
"cert",
".",
"Certificate",
",",
"Key",
":",
"cert",
".",
"PrivateKey",
",",
"}",
"\n",
"var",
"err",
"error",
"\n",
"siteData",
".",
"Meta",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"&",
"cert",
",",
"\"\"",
",",
"\"\\t\"",
")",
"\n",
"\\t",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"storage",
".",
"StoreSite",
"(",
"cert",
".",
"Domain",
",",
"siteData",
")",
"\n",
"}",
"\n",
"}"
] | // saveCertResource saves the certificate resource to disk. This
// includes the certificate file itself, the private key, and the
// metadata file. | [
"saveCertResource",
"saves",
"the",
"certificate",
"resource",
"to",
"disk",
".",
"This",
"includes",
"the",
"certificate",
"file",
"itself",
"the",
"private",
"key",
"and",
"the",
"metadata",
"file",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L52-L64 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/tls.go | Revoke | func Revoke(host string) error {
client, err := newACMEClient(new(Config), true)
if err != nil {
return err
}
return client.Revoke(host)
} | go | func Revoke(host string) error {
client, err := newACMEClient(new(Config), true)
if err != nil {
return err
}
return client.Revoke(host)
} | [
"func",
"Revoke",
"(",
"host",
"string",
")",
"error",
"{",
"client",
",",
"err",
":=",
"newACMEClient",
"(",
"new",
"(",
"Config",
")",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"client",
".",
"Revoke",
"(",
"host",
")",
"\n",
"}"
] | // Revoke revokes the certificate for host via ACME protocol.
// It assumes the certificate was obtained from the
// CA at DefaultCAUrl. | [
"Revoke",
"revokes",
"the",
"certificate",
"for",
"host",
"via",
"ACME",
"protocol",
".",
"It",
"assumes",
"the",
"certificate",
"was",
"obtained",
"from",
"the",
"CA",
"at",
"DefaultCAUrl",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L69-L75 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/tls.go | Present | func (s tlsSniSolver) Present(domain, token, keyAuth string) error {
cert, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth)
if err != nil {
return err
}
cacheCertificate(Certificate{
Certificate: cert,
Names: []string{acmeDomain},
})
return nil
} | go | func (s tlsSniSolver) Present(domain, token, keyAuth string) error {
cert, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth)
if err != nil {
return err
}
cacheCertificate(Certificate{
Certificate: cert,
Names: []string{acmeDomain},
})
return nil
} | [
"func",
"(",
"s",
"tlsSniSolver",
")",
"Present",
"(",
"domain",
",",
"token",
",",
"keyAuth",
"string",
")",
"error",
"{",
"cert",
",",
"acmeDomain",
",",
"err",
":=",
"acme",
".",
"TLSSNI01ChallengeCert",
"(",
"keyAuth",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cacheCertificate",
"(",
"Certificate",
"{",
"Certificate",
":",
"cert",
",",
"Names",
":",
"[",
"]",
"string",
"{",
"acmeDomain",
"}",
",",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Present adds the challenge certificate to the cache. | [
"Present",
"adds",
"the",
"challenge",
"certificate",
"to",
"the",
"cache",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L82-L92 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/tls.go | CleanUp | func (s tlsSniSolver) CleanUp(domain, token, keyAuth string) error {
_, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth)
if err != nil {
return err
}
uncacheCertificate(acmeDomain)
return nil
} | go | func (s tlsSniSolver) CleanUp(domain, token, keyAuth string) error {
_, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth)
if err != nil {
return err
}
uncacheCertificate(acmeDomain)
return nil
} | [
"func",
"(",
"s",
"tlsSniSolver",
")",
"CleanUp",
"(",
"domain",
",",
"token",
",",
"keyAuth",
"string",
")",
"error",
"{",
"_",
",",
"acmeDomain",
",",
"err",
":=",
"acme",
".",
"TLSSNI01ChallengeCert",
"(",
"keyAuth",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"uncacheCertificate",
"(",
"acmeDomain",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // CleanUp removes the challenge certificate from the cache. | [
"CleanUp",
"removes",
"the",
"challenge",
"certificate",
"from",
"the",
"cache",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L95-L102 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/tls.go | RegisterStorageProvider | func RegisterStorageProvider(name string, provider StorageConstructor) {
storageProviders[name] = provider
caddy.RegisterPlugin("tls.storage."+name, caddy.Plugin{})
} | go | func RegisterStorageProvider(name string, provider StorageConstructor) {
storageProviders[name] = provider
caddy.RegisterPlugin("tls.storage."+name, caddy.Plugin{})
} | [
"func",
"RegisterStorageProvider",
"(",
"name",
"string",
",",
"provider",
"StorageConstructor",
")",
"{",
"storageProviders",
"[",
"name",
"]",
"=",
"provider",
"\n",
"caddy",
".",
"RegisterPlugin",
"(",
"\"tls.storage.\"",
"+",
"name",
",",
"caddy",
".",
"Plugin",
"{",
"}",
")",
"\n",
"}"
] | // RegisterStorageProvider registers provider by name for storing tls data | [
"RegisterStorageProvider",
"registers",
"provider",
"by",
"name",
"for",
"storing",
"tls",
"data"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L175-L178 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/httphandler.go | HTTPChallengeHandler | func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool {
if !strings.HasPrefix(r.URL.Path, challengeBasePath) {
return false
}
if !namesObtaining.Has(r.Host) {
return false
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if listenHost == "" {
listenHost = "localhost"
}
upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("[ERROR] ACME proxy handler: %v", err)
return true
}
proxy := httputil.NewSingleHostReverseProxy(upstream)
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
proxy.ServeHTTP(w, r)
return true
} | go | func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool {
if !strings.HasPrefix(r.URL.Path, challengeBasePath) {
return false
}
if !namesObtaining.Has(r.Host) {
return false
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if listenHost == "" {
listenHost = "localhost"
}
upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("[ERROR] ACME proxy handler: %v", err)
return true
}
proxy := httputil.NewSingleHostReverseProxy(upstream)
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
proxy.ServeHTTP(w, r)
return true
} | [
"func",
"HTTPChallengeHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"listenHost",
",",
"altPort",
"string",
")",
"bool",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"challengeBasePath",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"namesObtaining",
".",
"Has",
"(",
"r",
".",
"Host",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"scheme",
":=",
"\"http\"",
"\n",
"if",
"r",
".",
"TLS",
"!=",
"nil",
"{",
"scheme",
"=",
"\"https\"",
"\n",
"}",
"\n",
"if",
"listenHost",
"==",
"\"\"",
"{",
"listenHost",
"=",
"\"localhost\"",
"\n",
"}",
"\n",
"upstream",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s:%s\"",
",",
"scheme",
",",
"listenHost",
",",
"altPort",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"[ERROR] ACME proxy handler: %v\"",
",",
"err",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"proxy",
":=",
"httputil",
".",
"NewSingleHostReverseProxy",
"(",
"upstream",
")",
"\n",
"proxy",
".",
"Transport",
"=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"true",
"}",
",",
"}",
"\n",
"proxy",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // HTTPChallengeHandler proxies challenge requests to ACME client if the
// request path starts with challengeBasePath. It returns true if it
// handled the request and no more needs to be done; it returns false
// if this call was a no-op and the request still needs handling. | [
"HTTPChallengeHandler",
"proxies",
"challenge",
"requests",
"to",
"ACME",
"client",
"if",
"the",
"request",
"path",
"starts",
"with",
"challengeBasePath",
".",
"It",
"returns",
"true",
"if",
"it",
"handled",
"the",
"request",
"and",
"no",
"more",
"needs",
"to",
"be",
"done",
";",
"it",
"returns",
"false",
"if",
"this",
"call",
"was",
"a",
"no",
"-",
"op",
"and",
"the",
"request",
"still",
"needs",
"handling",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/httphandler.go#L19-L50 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | FilterProfile | func (c *Client) FilterProfile(data interface{}) (interface{}, error) {
socket, err := net.Dial("unix", c.SocketPath)
if err != nil {
return nil, err
}
defer socket.Close()
return c.SendRequest("filter_profile", data, socket)
} | go | func (c *Client) FilterProfile(data interface{}) (interface{}, error) {
socket, err := net.Dial("unix", c.SocketPath)
if err != nil {
return nil, err
}
defer socket.Close()
return c.SendRequest("filter_profile", data, socket)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"FilterProfile",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"socket",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"unix\"",
",",
"c",
".",
"SocketPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"socket",
".",
"Close",
"(",
")",
"\n",
"return",
"c",
".",
"SendRequest",
"(",
"\"filter_profile\"",
",",
"data",
",",
"socket",
")",
"\n",
"}"
] | // Sends a filter_profile message to the pffilter service | [
"Sends",
"a",
"filter_profile",
"message",
"to",
"the",
"pffilter",
"service"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L47-L54 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | AccessFilter | func (c *Client) AccessFilter(filter string, scope string, data interface{}) (interface{}, error) {
socket, err := net.Dial("unix", c.SocketPath)
if err != nil {
return nil, err
}
defer socket.Close()
return c.SendRequest(filter, []interface{}{scope, data}, socket)
} | go | func (c *Client) AccessFilter(filter string, scope string, data interface{}) (interface{}, error) {
socket, err := net.Dial("unix", c.SocketPath)
if err != nil {
return nil, err
}
defer socket.Close()
return c.SendRequest(filter, []interface{}{scope, data}, socket)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AccessFilter",
"(",
"filter",
"string",
",",
"scope",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"socket",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"unix\"",
",",
"c",
".",
"SocketPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"socket",
".",
"Close",
"(",
")",
"\n",
"return",
"c",
".",
"SendRequest",
"(",
"filter",
",",
"[",
"]",
"interface",
"{",
"}",
"{",
"scope",
",",
"data",
"}",
",",
"socket",
")",
"\n",
"}"
] | // A generalize function for sending access filter messages | [
"A",
"generalize",
"function",
"for",
"sending",
"access",
"filter",
"messages"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L57-L64 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | FilterVlan | func (c *Client) FilterVlan(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_vlan", scope, data)
} | go | func (c *Client) FilterVlan(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_vlan", scope, data)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"FilterVlan",
"(",
"scope",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"c",
".",
"AccessFilter",
"(",
"\"filter_vlan\"",
",",
"scope",
",",
"data",
")",
"\n",
"}"
] | // Sends a filter_vlan message to the pffilter service | [
"Sends",
"a",
"filter_vlan",
"message",
"to",
"the",
"pffilter",
"service"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L67-L69 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | FilterDhcp | func (c *Client) FilterDhcp(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_dhcp", scope, data)
} | go | func (c *Client) FilterDhcp(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_dhcp", scope, data)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"FilterDhcp",
"(",
"scope",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"c",
".",
"AccessFilter",
"(",
"\"filter_dhcp\"",
",",
"scope",
",",
"data",
")",
"\n",
"}"
] | // Sends a filter_dhcp message to the pffilter service | [
"Sends",
"a",
"filter_dhcp",
"message",
"to",
"the",
"pffilter",
"service"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L72-L74 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | FilterDns | func (c *Client) FilterDns(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_dns", scope, data)
} | go | func (c *Client) FilterDns(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_dns", scope, data)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"FilterDns",
"(",
"scope",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"c",
".",
"AccessFilter",
"(",
"\"filter_dns\"",
",",
"scope",
",",
"data",
")",
"\n",
"}"
] | // Sends a filter_dns message to the pffilter service | [
"Sends",
"a",
"filter_dns",
"message",
"to",
"the",
"pffilter",
"service"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L77-L79 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | FilterRadius | func (c *Client) FilterRadius(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_radius", scope, data)
} | go | func (c *Client) FilterRadius(scope string, data interface{}) (interface{}, error) {
return c.AccessFilter("filter_radius", scope, data)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"FilterRadius",
"(",
"scope",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"c",
".",
"AccessFilter",
"(",
"\"filter_radius\"",
",",
"scope",
",",
"data",
")",
"\n",
"}"
] | // Sends a filter_radius message to the pffilter service | [
"Sends",
"a",
"filter_radius",
"message",
"to",
"the",
"pffilter",
"service"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L82-L84 | train |
inverse-inc/packetfence | go/filter_client/filter_client.go | SendRequest | func (c *Client) SendRequest(method string, params interface{}, conn net.Conn) (interface{}, error) {
request := Request{Method: method, Params: params}
b, err := json.Marshal(request)
if err != nil {
return nil, err
}
b = append(b, '\n')
_, err = conn.Write(b)
if err != nil {
return nil, err
}
reader := bufio.NewReader(conn)
b2, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}
var response Response
err = json.Unmarshal(b2, &response)
if err != nil {
return nil, err
}
if response.Error != nil {
return nil, fmt.Errorf("%s", response.Error.Message)
}
if response.Result == nil {
return nil, fmt.Errorf("No valid result returned")
}
return *response.Result, nil
} | go | func (c *Client) SendRequest(method string, params interface{}, conn net.Conn) (interface{}, error) {
request := Request{Method: method, Params: params}
b, err := json.Marshal(request)
if err != nil {
return nil, err
}
b = append(b, '\n')
_, err = conn.Write(b)
if err != nil {
return nil, err
}
reader := bufio.NewReader(conn)
b2, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}
var response Response
err = json.Unmarshal(b2, &response)
if err != nil {
return nil, err
}
if response.Error != nil {
return nil, fmt.Errorf("%s", response.Error.Message)
}
if response.Result == nil {
return nil, fmt.Errorf("No valid result returned")
}
return *response.Result, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendRequest",
"(",
"method",
"string",
",",
"params",
"interface",
"{",
"}",
",",
"conn",
"net",
".",
"Conn",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"request",
":=",
"Request",
"{",
"Method",
":",
"method",
",",
"Params",
":",
"params",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"'\\n'",
")",
"\n",
"_",
",",
"err",
"=",
"conn",
".",
"Write",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"reader",
":=",
"bufio",
".",
"NewReader",
"(",
"conn",
")",
"\n",
"b2",
",",
"err",
":=",
"reader",
".",
"ReadBytes",
"(",
"'\\n'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"response",
"Response",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"b2",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"response",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s\"",
",",
"response",
".",
"Error",
".",
"Message",
")",
"\n",
"}",
"\n",
"if",
"response",
".",
"Result",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"No valid result returned\"",
")",
"\n",
"}",
"\n",
"return",
"*",
"response",
".",
"Result",
",",
"nil",
"\n",
"}"
] | // Send a request to the pffilter service | [
"Send",
"a",
"request",
"to",
"the",
"pffilter",
"service"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L87-L117 | train |
inverse-inc/packetfence | go/firewallsso/checkpoint.go | Start | func (fw *Checkpoint) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) {
p := fw.startRadiusPacket(ctx, info, timeout)
client := fw.getRadiusClient(ctx)
// Use the background context since we don't want the lib to use our context
ctx2, cancel := fw.RadiusContextWithTimeout()
defer cancel()
_, err := client.Exchange(ctx2, p, fw.PfconfigHashNS+":"+fw.Port)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Couldn't SSO to the Checkpoint, got the following error: %s", err))
return false, err
} else {
return true, nil
}
} | go | func (fw *Checkpoint) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) {
p := fw.startRadiusPacket(ctx, info, timeout)
client := fw.getRadiusClient(ctx)
// Use the background context since we don't want the lib to use our context
ctx2, cancel := fw.RadiusContextWithTimeout()
defer cancel()
_, err := client.Exchange(ctx2, p, fw.PfconfigHashNS+":"+fw.Port)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Couldn't SSO to the Checkpoint, got the following error: %s", err))
return false, err
} else {
return true, nil
}
} | [
"func",
"(",
"fw",
"*",
"Checkpoint",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"p",
":=",
"fw",
".",
"startRadiusPacket",
"(",
"ctx",
",",
"info",
",",
"timeout",
")",
"\n",
"client",
":=",
"fw",
".",
"getRadiusClient",
"(",
"ctx",
")",
"\n",
"ctx2",
",",
"cancel",
":=",
"fw",
".",
"RadiusContextWithTimeout",
"(",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"client",
".",
"Exchange",
"(",
"ctx2",
",",
"p",
",",
"fw",
".",
"PfconfigHashNS",
"+",
"\":\"",
"+",
"fw",
".",
"Port",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Couldn't SSO to the Checkpoint, got the following error: %s\"",
",",
"err",
")",
")",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"else",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // Send an SSO start to the Checkpoint firewall
// Returns an error unless there is a valid reply from the firewall | [
"Send",
"an",
"SSO",
"start",
"to",
"the",
"Checkpoint",
"firewall",
"Returns",
"an",
"error",
"unless",
"there",
"is",
"a",
"valid",
"reply",
"from",
"the",
"firewall"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/checkpoint.go#L22-L35 | train |
inverse-inc/packetfence | go/firewallsso/checkpoint.go | startRadiusPacket | func (fw *Checkpoint) startRadiusPacket(ctx context.Context, info map[string]string, timeout int) *radius.Packet {
r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password))
rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Start)
rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"])
rfc2865.UserName_AddString(r, info["username"])
rfc2865.SessionTimeout_Add(r, rfc2865.SessionTimeout(timeout))
rfc2865.CalledStationID_AddString(r, "00:11:22:33:44:55")
rfc2865.FramedIPAddress_Add(r, net.ParseIP(info["ip"]))
rfc2865.CallingStationID_AddString(r, info["mac"])
return r
} | go | func (fw *Checkpoint) startRadiusPacket(ctx context.Context, info map[string]string, timeout int) *radius.Packet {
r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password))
rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Start)
rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"])
rfc2865.UserName_AddString(r, info["username"])
rfc2865.SessionTimeout_Add(r, rfc2865.SessionTimeout(timeout))
rfc2865.CalledStationID_AddString(r, "00:11:22:33:44:55")
rfc2865.FramedIPAddress_Add(r, net.ParseIP(info["ip"]))
rfc2865.CallingStationID_AddString(r, info["mac"])
return r
} | [
"func",
"(",
"fw",
"*",
"Checkpoint",
")",
"startRadiusPacket",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"*",
"radius",
".",
"Packet",
"{",
"r",
":=",
"radius",
".",
"New",
"(",
"radius",
".",
"CodeAccountingRequest",
",",
"[",
"]",
"byte",
"(",
"fw",
".",
"Password",
")",
")",
"\n",
"rfc2866",
".",
"AcctStatusType_Add",
"(",
"r",
",",
"rfc2866",
".",
"AcctStatusType_Value_Start",
")",
"\n",
"rfc2866",
".",
"AcctSessionID_AddString",
"(",
"r",
",",
"\"acct_pf-\"",
"+",
"info",
"[",
"\"mac\"",
"]",
")",
"\n",
"rfc2865",
".",
"UserName_AddString",
"(",
"r",
",",
"info",
"[",
"\"username\"",
"]",
")",
"\n",
"rfc2865",
".",
"SessionTimeout_Add",
"(",
"r",
",",
"rfc2865",
".",
"SessionTimeout",
"(",
"timeout",
")",
")",
"\n",
"rfc2865",
".",
"CalledStationID_AddString",
"(",
"r",
",",
"\"00:11:22:33:44:55\"",
")",
"\n",
"rfc2865",
".",
"FramedIPAddress_Add",
"(",
"r",
",",
"net",
".",
"ParseIP",
"(",
"info",
"[",
"\"ip\"",
"]",
")",
")",
"\n",
"rfc2865",
".",
"CallingStationID_AddString",
"(",
"r",
",",
"info",
"[",
"\"mac\"",
"]",
")",
"\n",
"return",
"r",
"\n",
"}"
] | // Build the RADIUS packet for an SSO start | [
"Build",
"the",
"RADIUS",
"packet",
"for",
"an",
"SSO",
"start"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/checkpoint.go#L38-L49 | train |
inverse-inc/packetfence | go/firewallsso/checkpoint.go | Stop | func (fw *Checkpoint) Stop(ctx context.Context, info map[string]string) (bool, error) {
log.LoggerWContext(ctx).Warn("SSO Stop is not available for this firewall")
return false, nil
} | go | func (fw *Checkpoint) Stop(ctx context.Context, info map[string]string) (bool, error) {
log.LoggerWContext(ctx).Warn("SSO Stop is not available for this firewall")
return false, nil
} | [
"func",
"(",
"fw",
"*",
"Checkpoint",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Warn",
"(",
"\"SSO Stop is not available for this firewall\"",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // SSO stop handler which does nothing other than printing a warning since the SSO stop is unimplemented for this firewall | [
"SSO",
"stop",
"handler",
"which",
"does",
"nothing",
"other",
"than",
"printing",
"a",
"warning",
"since",
"the",
"SSO",
"stop",
"is",
"unimplemented",
"for",
"this",
"firewall"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/checkpoint.go#L52-L55 | train |
inverse-inc/packetfence | go/coredns/coremain/run.go | setVersion | func setVersion() {
// A development build is one that's not at a tag or has uncommitted changes
devBuild = gitTag == "" || gitShortStat != ""
// Only set the appVersion if -ldflags was used
if gitNearestTag != "" || gitTag != "" {
if devBuild && gitNearestTag != "" {
appVersion = fmt.Sprintf("%s (+%s %s)",
strings.TrimPrefix(gitNearestTag, "v"), gitCommit, buildDate)
} else if gitTag != "" {
appVersion = strings.TrimPrefix(gitTag, "v")
}
}
} | go | func setVersion() {
// A development build is one that's not at a tag or has uncommitted changes
devBuild = gitTag == "" || gitShortStat != ""
// Only set the appVersion if -ldflags was used
if gitNearestTag != "" || gitTag != "" {
if devBuild && gitNearestTag != "" {
appVersion = fmt.Sprintf("%s (+%s %s)",
strings.TrimPrefix(gitNearestTag, "v"), gitCommit, buildDate)
} else if gitTag != "" {
appVersion = strings.TrimPrefix(gitTag, "v")
}
}
} | [
"func",
"setVersion",
"(",
")",
"{",
"devBuild",
"=",
"gitTag",
"==",
"\"\"",
"||",
"gitShortStat",
"!=",
"\"\"",
"\n",
"if",
"gitNearestTag",
"!=",
"\"\"",
"||",
"gitTag",
"!=",
"\"\"",
"{",
"if",
"devBuild",
"&&",
"gitNearestTag",
"!=",
"\"\"",
"{",
"appVersion",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s (+%s %s)\"",
",",
"strings",
".",
"TrimPrefix",
"(",
"gitNearestTag",
",",
"\"v\"",
")",
",",
"gitCommit",
",",
"buildDate",
")",
"\n",
"}",
"else",
"if",
"gitTag",
"!=",
"\"\"",
"{",
"appVersion",
"=",
"strings",
".",
"TrimPrefix",
"(",
"gitTag",
",",
"\"v\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // setVersion figures out the version information
// based on variables set by -ldflags. | [
"setVersion",
"figures",
"out",
"the",
"version",
"information",
"based",
"on",
"variables",
"set",
"by",
"-",
"ldflags",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/coremain/run.go#L188-L201 | train |
inverse-inc/packetfence | go/coredns/plugin/proxy/metrics.go | OnStartupMetrics | func OnStartupMetrics() error {
metricsOnce.Do(func() {
prometheus.MustRegister(RequestCount)
prometheus.MustRegister(RequestDuration)
})
return nil
} | go | func OnStartupMetrics() error {
metricsOnce.Do(func() {
prometheus.MustRegister(RequestCount)
prometheus.MustRegister(RequestDuration)
})
return nil
} | [
"func",
"OnStartupMetrics",
"(",
")",
"error",
"{",
"metricsOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"prometheus",
".",
"MustRegister",
"(",
"RequestCount",
")",
"\n",
"prometheus",
".",
"MustRegister",
"(",
"RequestDuration",
")",
"\n",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // OnStartupMetrics sets up the metrics on startup. This is done for all proxy protocols. | [
"OnStartupMetrics",
"sets",
"up",
"the",
"metrics",
"on",
"startup",
".",
"This",
"is",
"done",
"for",
"all",
"proxy",
"protocols",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/metrics.go#L29-L35 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/crypto.go | stapleOCSP | func stapleOCSP(cert *Certificate, pemBundle []byte) error {
if pemBundle == nil {
// The function in the acme package that gets OCSP requires a PEM-encoded cert
bundle := new(bytes.Buffer)
for _, derBytes := range cert.Certificate.Certificate {
pem.Encode(bundle, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
}
pemBundle = bundle.Bytes()
}
var ocspBytes []byte
var ocspResp *ocsp.Response
var ocspErr error
var gotNewOCSP bool
// First try to load OCSP staple from storage and see if
// we can still use it.
// TODO: Use Storage interface instead of disk directly
var ocspFileNamePrefix string
if len(cert.Names) > 0 {
ocspFileNamePrefix = cert.Names[0] + "-"
}
ocspFileName := ocspFileNamePrefix + fastHash(pemBundle)
ocspCachePath := filepath.Join(ocspFolder, ocspFileName)
cachedOCSP, err := ioutil.ReadFile(ocspCachePath)
if err == nil {
resp, err := ocsp.ParseResponse(cachedOCSP, nil)
if err == nil {
if freshOCSP(resp) {
// staple is still fresh; use it
ocspBytes = cachedOCSP
ocspResp = resp
}
} else {
// invalid contents; delete the file
// (we do this independently of the maintenance routine because
// in this case we know for sure this should be a staple file
// because we loaded it by name, whereas the maintenance routine
// just iterates the list of files, even if somehow a non-staple
// file gets in the folder. in this case we are sure it is corrupt.)
err := os.Remove(ocspCachePath)
if err != nil {
log.Printf("[WARNING] Unable to delete invalid OCSP staple file: %v", err)
}
}
}
// If we couldn't get a fresh staple by reading the cache,
// then we need to request it from the OCSP responder
if ocspResp == nil || len(ocspBytes) == 0 {
ocspBytes, ocspResp, ocspErr = acme.GetOCSPForCert(pemBundle)
if ocspErr != nil {
// An error here is not a problem because a certificate may simply
// not contain a link to an OCSP server. But we should log it anyway.
// There's nothing else we can do to get OCSP for this certificate,
// so we can return here with the error.
return fmt.Errorf("no OCSP stapling for %v: %v", cert.Names, ocspErr)
}
gotNewOCSP = true
}
// By now, we should have a response. If good, staple it to
// the certificate. If the OCSP response was not loaded from
// storage, we persist it for next time.
if ocspResp.Status == ocsp.Good {
cert.Certificate.OCSPStaple = ocspBytes
cert.OCSP = ocspResp
if gotNewOCSP {
err := os.MkdirAll(filepath.Join(caddy.AssetsPath(), "ocsp"), 0700)
if err != nil {
return fmt.Errorf("unable to make OCSP staple path for %v: %v", cert.Names, err)
}
err = ioutil.WriteFile(ocspCachePath, ocspBytes, 0644)
if err != nil {
return fmt.Errorf("unable to write OCSP staple file for %v: %v", cert.Names, err)
}
}
}
return nil
} | go | func stapleOCSP(cert *Certificate, pemBundle []byte) error {
if pemBundle == nil {
// The function in the acme package that gets OCSP requires a PEM-encoded cert
bundle := new(bytes.Buffer)
for _, derBytes := range cert.Certificate.Certificate {
pem.Encode(bundle, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
}
pemBundle = bundle.Bytes()
}
var ocspBytes []byte
var ocspResp *ocsp.Response
var ocspErr error
var gotNewOCSP bool
// First try to load OCSP staple from storage and see if
// we can still use it.
// TODO: Use Storage interface instead of disk directly
var ocspFileNamePrefix string
if len(cert.Names) > 0 {
ocspFileNamePrefix = cert.Names[0] + "-"
}
ocspFileName := ocspFileNamePrefix + fastHash(pemBundle)
ocspCachePath := filepath.Join(ocspFolder, ocspFileName)
cachedOCSP, err := ioutil.ReadFile(ocspCachePath)
if err == nil {
resp, err := ocsp.ParseResponse(cachedOCSP, nil)
if err == nil {
if freshOCSP(resp) {
// staple is still fresh; use it
ocspBytes = cachedOCSP
ocspResp = resp
}
} else {
// invalid contents; delete the file
// (we do this independently of the maintenance routine because
// in this case we know for sure this should be a staple file
// because we loaded it by name, whereas the maintenance routine
// just iterates the list of files, even if somehow a non-staple
// file gets in the folder. in this case we are sure it is corrupt.)
err := os.Remove(ocspCachePath)
if err != nil {
log.Printf("[WARNING] Unable to delete invalid OCSP staple file: %v", err)
}
}
}
// If we couldn't get a fresh staple by reading the cache,
// then we need to request it from the OCSP responder
if ocspResp == nil || len(ocspBytes) == 0 {
ocspBytes, ocspResp, ocspErr = acme.GetOCSPForCert(pemBundle)
if ocspErr != nil {
// An error here is not a problem because a certificate may simply
// not contain a link to an OCSP server. But we should log it anyway.
// There's nothing else we can do to get OCSP for this certificate,
// so we can return here with the error.
return fmt.Errorf("no OCSP stapling for %v: %v", cert.Names, ocspErr)
}
gotNewOCSP = true
}
// By now, we should have a response. If good, staple it to
// the certificate. If the OCSP response was not loaded from
// storage, we persist it for next time.
if ocspResp.Status == ocsp.Good {
cert.Certificate.OCSPStaple = ocspBytes
cert.OCSP = ocspResp
if gotNewOCSP {
err := os.MkdirAll(filepath.Join(caddy.AssetsPath(), "ocsp"), 0700)
if err != nil {
return fmt.Errorf("unable to make OCSP staple path for %v: %v", cert.Names, err)
}
err = ioutil.WriteFile(ocspCachePath, ocspBytes, 0644)
if err != nil {
return fmt.Errorf("unable to write OCSP staple file for %v: %v", cert.Names, err)
}
}
}
return nil
} | [
"func",
"stapleOCSP",
"(",
"cert",
"*",
"Certificate",
",",
"pemBundle",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"pemBundle",
"==",
"nil",
"{",
"bundle",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"for",
"_",
",",
"derBytes",
":=",
"range",
"cert",
".",
"Certificate",
".",
"Certificate",
"{",
"pem",
".",
"Encode",
"(",
"bundle",
",",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"CERTIFICATE\"",
",",
"Bytes",
":",
"derBytes",
"}",
")",
"\n",
"}",
"\n",
"pemBundle",
"=",
"bundle",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"var",
"ocspBytes",
"[",
"]",
"byte",
"\n",
"var",
"ocspResp",
"*",
"ocsp",
".",
"Response",
"\n",
"var",
"ocspErr",
"error",
"\n",
"var",
"gotNewOCSP",
"bool",
"\n",
"var",
"ocspFileNamePrefix",
"string",
"\n",
"if",
"len",
"(",
"cert",
".",
"Names",
")",
">",
"0",
"{",
"ocspFileNamePrefix",
"=",
"cert",
".",
"Names",
"[",
"0",
"]",
"+",
"\"-\"",
"\n",
"}",
"\n",
"ocspFileName",
":=",
"ocspFileNamePrefix",
"+",
"fastHash",
"(",
"pemBundle",
")",
"\n",
"ocspCachePath",
":=",
"filepath",
".",
"Join",
"(",
"ocspFolder",
",",
"ocspFileName",
")",
"\n",
"cachedOCSP",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"ocspCachePath",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"resp",
",",
"err",
":=",
"ocsp",
".",
"ParseResponse",
"(",
"cachedOCSP",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"freshOCSP",
"(",
"resp",
")",
"{",
"ocspBytes",
"=",
"cachedOCSP",
"\n",
"ocspResp",
"=",
"resp",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
":=",
"os",
".",
"Remove",
"(",
"ocspCachePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[WARNING] Unable to delete invalid OCSP staple file: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"ocspResp",
"==",
"nil",
"||",
"len",
"(",
"ocspBytes",
")",
"==",
"0",
"{",
"ocspBytes",
",",
"ocspResp",
",",
"ocspErr",
"=",
"acme",
".",
"GetOCSPForCert",
"(",
"pemBundle",
")",
"\n",
"if",
"ocspErr",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"no OCSP stapling for %v: %v\"",
",",
"cert",
".",
"Names",
",",
"ocspErr",
")",
"\n",
"}",
"\n",
"gotNewOCSP",
"=",
"true",
"\n",
"}",
"\n",
"if",
"ocspResp",
".",
"Status",
"==",
"ocsp",
".",
"Good",
"{",
"cert",
".",
"Certificate",
".",
"OCSPStaple",
"=",
"ocspBytes",
"\n",
"cert",
".",
"OCSP",
"=",
"ocspResp",
"\n",
"if",
"gotNewOCSP",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Join",
"(",
"caddy",
".",
"AssetsPath",
"(",
")",
",",
"\"ocsp\"",
")",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unable to make OCSP staple path for %v: %v\"",
",",
"cert",
".",
"Names",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"ocspCachePath",
",",
"ocspBytes",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unable to write OCSP staple file for %v: %v\"",
",",
"cert",
".",
"Names",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // stapleOCSP staples OCSP information to cert for hostname name.
// If you have it handy, you should pass in the PEM-encoded certificate
// bundle; otherwise the DER-encoded cert will have to be PEM-encoded.
// If you don't have the PEM blocks already, just pass in nil.
//
// Errors here are not necessarily fatal, it could just be that the
// certificate doesn't have an issuer URL. | [
"stapleOCSP",
"staples",
"OCSP",
"information",
"to",
"cert",
"for",
"hostname",
"name",
".",
"If",
"you",
"have",
"it",
"handy",
"you",
"should",
"pass",
"in",
"the",
"PEM",
"-",
"encoded",
"certificate",
"bundle",
";",
"otherwise",
"the",
"DER",
"-",
"encoded",
"cert",
"will",
"have",
"to",
"be",
"PEM",
"-",
"encoded",
".",
"If",
"you",
"don",
"t",
"have",
"the",
"PEM",
"blocks",
"already",
"just",
"pass",
"in",
"nil",
".",
"Errors",
"here",
"are",
"not",
"necessarily",
"fatal",
"it",
"could",
"just",
"be",
"that",
"the",
"certificate",
"doesn",
"t",
"have",
"an",
"issuer",
"URL",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/crypto.go#L74-L154 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/crypto.go | makeSelfSignedCert | func makeSelfSignedCert(config *Config) error {
// start by generating private key
var privKey interface{}
var err error
switch config.KeyType {
case "", acme.EC256:
privKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case acme.EC384:
privKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case acme.RSA2048:
privKey, err = rsa.GenerateKey(rand.Reader, 2048)
case acme.RSA4096:
privKey, err = rsa.GenerateKey(rand.Reader, 4096)
case acme.RSA8192:
privKey, err = rsa.GenerateKey(rand.Reader, 8192)
default:
return fmt.Errorf("cannot generate private key; unknown key type %v", config.KeyType)
}
if err != nil {
return fmt.Errorf("failed to generate private key: %v", err)
}
// create certificate structure with proper values
notBefore := time.Now()
notAfter := notBefore.Add(24 * time.Hour * 7)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number: %v", err)
}
cert := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{Organization: []string{"Caddy Self-Signed"}},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
if ip := net.ParseIP(config.Hostname); ip != nil {
cert.IPAddresses = append(cert.IPAddresses, ip)
} else {
cert.DNSNames = append(cert.DNSNames, config.Hostname)
}
publicKey := func(privKey interface{}) interface{} {
switch k := privKey.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return errors.New("unknown key type")
}
}
derBytes, err := x509.CreateCertificate(rand.Reader, cert, cert, publicKey(privKey), privKey)
if err != nil {
return fmt.Errorf("could not create certificate: %v", err)
}
cacheCertificate(Certificate{
Certificate: tls.Certificate{
Certificate: [][]byte{derBytes},
PrivateKey: privKey,
Leaf: cert,
},
Names: cert.DNSNames,
NotAfter: cert.NotAfter,
Config: config,
})
return nil
} | go | func makeSelfSignedCert(config *Config) error {
// start by generating private key
var privKey interface{}
var err error
switch config.KeyType {
case "", acme.EC256:
privKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case acme.EC384:
privKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case acme.RSA2048:
privKey, err = rsa.GenerateKey(rand.Reader, 2048)
case acme.RSA4096:
privKey, err = rsa.GenerateKey(rand.Reader, 4096)
case acme.RSA8192:
privKey, err = rsa.GenerateKey(rand.Reader, 8192)
default:
return fmt.Errorf("cannot generate private key; unknown key type %v", config.KeyType)
}
if err != nil {
return fmt.Errorf("failed to generate private key: %v", err)
}
// create certificate structure with proper values
notBefore := time.Now()
notAfter := notBefore.Add(24 * time.Hour * 7)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number: %v", err)
}
cert := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{Organization: []string{"Caddy Self-Signed"}},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
if ip := net.ParseIP(config.Hostname); ip != nil {
cert.IPAddresses = append(cert.IPAddresses, ip)
} else {
cert.DNSNames = append(cert.DNSNames, config.Hostname)
}
publicKey := func(privKey interface{}) interface{} {
switch k := privKey.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return errors.New("unknown key type")
}
}
derBytes, err := x509.CreateCertificate(rand.Reader, cert, cert, publicKey(privKey), privKey)
if err != nil {
return fmt.Errorf("could not create certificate: %v", err)
}
cacheCertificate(Certificate{
Certificate: tls.Certificate{
Certificate: [][]byte{derBytes},
PrivateKey: privKey,
Leaf: cert,
},
Names: cert.DNSNames,
NotAfter: cert.NotAfter,
Config: config,
})
return nil
} | [
"func",
"makeSelfSignedCert",
"(",
"config",
"*",
"Config",
")",
"error",
"{",
"var",
"privKey",
"interface",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"switch",
"config",
".",
"KeyType",
"{",
"case",
"\"\"",
",",
"acme",
".",
"EC256",
":",
"privKey",
",",
"err",
"=",
"ecdsa",
".",
"GenerateKey",
"(",
"elliptic",
".",
"P256",
"(",
")",
",",
"rand",
".",
"Reader",
")",
"\n",
"case",
"acme",
".",
"EC384",
":",
"privKey",
",",
"err",
"=",
"ecdsa",
".",
"GenerateKey",
"(",
"elliptic",
".",
"P384",
"(",
")",
",",
"rand",
".",
"Reader",
")",
"\n",
"case",
"acme",
".",
"RSA2048",
":",
"privKey",
",",
"err",
"=",
"rsa",
".",
"GenerateKey",
"(",
"rand",
".",
"Reader",
",",
"2048",
")",
"\n",
"case",
"acme",
".",
"RSA4096",
":",
"privKey",
",",
"err",
"=",
"rsa",
".",
"GenerateKey",
"(",
"rand",
".",
"Reader",
",",
"4096",
")",
"\n",
"case",
"acme",
".",
"RSA8192",
":",
"privKey",
",",
"err",
"=",
"rsa",
".",
"GenerateKey",
"(",
"rand",
".",
"Reader",
",",
"8192",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cannot generate private key; unknown key type %v\"",
",",
"config",
".",
"KeyType",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to generate private key: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"notBefore",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"notAfter",
":=",
"notBefore",
".",
"Add",
"(",
"24",
"*",
"time",
".",
"Hour",
"*",
"7",
")",
"\n",
"serialNumberLimit",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Lsh",
"(",
"big",
".",
"NewInt",
"(",
"1",
")",
",",
"128",
")",
"\n",
"serialNumber",
",",
"err",
":=",
"rand",
".",
"Int",
"(",
"rand",
".",
"Reader",
",",
"serialNumberLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to generate serial number: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cert",
":=",
"&",
"x509",
".",
"Certificate",
"{",
"SerialNumber",
":",
"serialNumber",
",",
"Subject",
":",
"pkix",
".",
"Name",
"{",
"Organization",
":",
"[",
"]",
"string",
"{",
"\"Caddy Self-Signed\"",
"}",
"}",
",",
"NotBefore",
":",
"notBefore",
",",
"NotAfter",
":",
"notAfter",
",",
"KeyUsage",
":",
"x509",
".",
"KeyUsageKeyEncipherment",
"|",
"x509",
".",
"KeyUsageDigitalSignature",
",",
"ExtKeyUsage",
":",
"[",
"]",
"x509",
".",
"ExtKeyUsage",
"{",
"x509",
".",
"ExtKeyUsageServerAuth",
"}",
",",
"}",
"\n",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"config",
".",
"Hostname",
")",
";",
"ip",
"!=",
"nil",
"{",
"cert",
".",
"IPAddresses",
"=",
"append",
"(",
"cert",
".",
"IPAddresses",
",",
"ip",
")",
"\n",
"}",
"else",
"{",
"cert",
".",
"DNSNames",
"=",
"append",
"(",
"cert",
".",
"DNSNames",
",",
"config",
".",
"Hostname",
")",
"\n",
"}",
"\n",
"publicKey",
":=",
"func",
"(",
"privKey",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"switch",
"k",
":=",
"privKey",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PrivateKey",
":",
"return",
"&",
"k",
".",
"PublicKey",
"\n",
"case",
"*",
"ecdsa",
".",
"PrivateKey",
":",
"return",
"&",
"k",
".",
"PublicKey",
"\n",
"default",
":",
"return",
"errors",
".",
"New",
"(",
"\"unknown key type\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"derBytes",
",",
"err",
":=",
"x509",
".",
"CreateCertificate",
"(",
"rand",
".",
"Reader",
",",
"cert",
",",
"cert",
",",
"publicKey",
"(",
"privKey",
")",
",",
"privKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not create certificate: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cacheCertificate",
"(",
"Certificate",
"{",
"Certificate",
":",
"tls",
".",
"Certificate",
"{",
"Certificate",
":",
"[",
"]",
"[",
"]",
"byte",
"{",
"derBytes",
"}",
",",
"PrivateKey",
":",
"privKey",
",",
"Leaf",
":",
"cert",
",",
"}",
",",
"Names",
":",
"cert",
".",
"DNSNames",
",",
"NotAfter",
":",
"cert",
".",
"NotAfter",
",",
"Config",
":",
"config",
",",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // makeSelfSignedCert makes a self-signed certificate according
// to the parameters in config. It then caches the certificate
// in our cache. | [
"makeSelfSignedCert",
"makes",
"a",
"self",
"-",
"signed",
"certificate",
"according",
"to",
"the",
"parameters",
"in",
"config",
".",
"It",
"then",
"caches",
"the",
"certificate",
"in",
"our",
"cache",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/crypto.go#L159-L230 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/crypto.go | fastHash | func fastHash(input []byte) string {
h := fnv.New32a()
h.Write([]byte(input))
return fmt.Sprintf("%x", h.Sum32())
} | go | func fastHash(input []byte) string {
h := fnv.New32a()
h.Write([]byte(input))
return fmt.Sprintf("%x", h.Sum32())
} | [
"func",
"fastHash",
"(",
"input",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"fnv",
".",
"New32a",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"input",
")",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%x\"",
",",
"h",
".",
"Sum32",
"(",
")",
")",
"\n",
"}"
] | // fastHash hashes input using a hashing algorithm that
// is fast, and returns the hash as a hex-encoded string.
// Do not use this for cryptographic purposes. | [
"fastHash",
"hashes",
"input",
"using",
"a",
"hashing",
"algorithm",
"that",
"is",
"fast",
"and",
"returns",
"the",
"hash",
"as",
"a",
"hex",
"-",
"encoded",
"string",
".",
"Do",
"not",
"use",
"this",
"for",
"cryptographic",
"purposes",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/crypto.go#L310-L314 | train |
inverse-inc/packetfence | go/coredns/request/request.go | ErrorMessage | func (r *Request) ErrorMessage(rcode int) *dns.Msg {
m := new(dns.Msg)
m.SetRcode(r.Req, rcode)
return m
} | go | func (r *Request) ErrorMessage(rcode int) *dns.Msg {
m := new(dns.Msg)
m.SetRcode(r.Req, rcode)
return m
} | [
"func",
"(",
"r",
"*",
"Request",
")",
"ErrorMessage",
"(",
"rcode",
"int",
")",
"*",
"dns",
".",
"Msg",
"{",
"m",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"m",
".",
"SetRcode",
"(",
"r",
".",
"Req",
",",
"rcode",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // ErrorMessage returns an error message suitable for sending
// back to the client. | [
"ErrorMessage",
"returns",
"an",
"error",
"message",
"suitable",
"for",
"sending",
"back",
"to",
"the",
"client",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/request/request.go#L298-L302 | train |
inverse-inc/packetfence | go/firewallsso/factory.go | NewFactory | func NewFactory(ctx context.Context) Factory {
f := Factory{}
f.typeRegistry = make(map[string]reflect.Type)
f.typeRegistry["BarracudaNG"] = reflect.TypeOf(&BarracudaNG{}).Elem()
f.typeRegistry["Iboss"] = reflect.TypeOf(&Iboss{}).Elem()
f.typeRegistry["PaloAlto"] = reflect.TypeOf(&PaloAlto{}).Elem()
f.typeRegistry["FortiGate"] = reflect.TypeOf(&FortiGate{}).Elem()
f.typeRegistry["Checkpoint"] = reflect.TypeOf(&Checkpoint{}).Elem()
f.typeRegistry["WatchGuard"] = reflect.TypeOf(&WatchGuard{}).Elem()
f.typeRegistry["JSONRPC"] = reflect.TypeOf(&JSONRPC{}).Elem()
f.typeRegistry["JuniperSRX"] = reflect.TypeOf(&JuniperSRX{}).Elem()
return f
} | go | func NewFactory(ctx context.Context) Factory {
f := Factory{}
f.typeRegistry = make(map[string]reflect.Type)
f.typeRegistry["BarracudaNG"] = reflect.TypeOf(&BarracudaNG{}).Elem()
f.typeRegistry["Iboss"] = reflect.TypeOf(&Iboss{}).Elem()
f.typeRegistry["PaloAlto"] = reflect.TypeOf(&PaloAlto{}).Elem()
f.typeRegistry["FortiGate"] = reflect.TypeOf(&FortiGate{}).Elem()
f.typeRegistry["Checkpoint"] = reflect.TypeOf(&Checkpoint{}).Elem()
f.typeRegistry["WatchGuard"] = reflect.TypeOf(&WatchGuard{}).Elem()
f.typeRegistry["JSONRPC"] = reflect.TypeOf(&JSONRPC{}).Elem()
f.typeRegistry["JuniperSRX"] = reflect.TypeOf(&JuniperSRX{}).Elem()
return f
} | [
"func",
"NewFactory",
"(",
"ctx",
"context",
".",
"Context",
")",
"Factory",
"{",
"f",
":=",
"Factory",
"{",
"}",
"\n",
"f",
".",
"typeRegistry",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"reflect",
".",
"Type",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"BarracudaNG\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"BarracudaNG",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"Iboss\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"Iboss",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"PaloAlto\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"PaloAlto",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"FortiGate\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"FortiGate",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"Checkpoint\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"Checkpoint",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"WatchGuard\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"WatchGuard",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"JSONRPC\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"JSONRPC",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"f",
".",
"typeRegistry",
"[",
"\"JuniperSRX\"",
"]",
"=",
"reflect",
".",
"TypeOf",
"(",
"&",
"JuniperSRX",
"{",
"}",
")",
".",
"Elem",
"(",
")",
"\n",
"return",
"f",
"\n",
"}"
] | // Create a new FirewallSSO factory containing all the valid types | [
"Create",
"a",
"new",
"FirewallSSO",
"factory",
"containing",
"all",
"the",
"valid",
"types"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/factory.go#L16-L28 | train |
inverse-inc/packetfence | go/firewallsso/factory.go | Instantiate | func (f *Factory) Instantiate(ctx context.Context, id string) (FirewallSSOInt, error) {
firewall := FirewallSSO{}
firewall.PfconfigHashNS = id
_, err := pfconfigdriver.FetchDecodeSocketCache(ctx, &firewall)
if err != nil {
return nil, err
}
if oType, ok := f.typeRegistry[firewall.Type]; ok {
or := reflect.New(oType)
or.Elem().FieldByName("PfconfigHashNS").SetString(id)
firewall2 := or.Interface().(pfconfigdriver.PfconfigObject)
_, err = pfconfigdriver.FetchDecodeSocketCache(ctx, firewall2)
if err != nil {
return nil, err
}
fwint := firewall2.(FirewallSSOInt)
err = fwint.init(ctx)
if err != nil {
return nil, err
}
err = fwint.initChild(ctx)
if err != nil {
return nil, err
}
return fwint, nil
} else {
return nil, errors.New("Cannot find the type of the object")
}
} | go | func (f *Factory) Instantiate(ctx context.Context, id string) (FirewallSSOInt, error) {
firewall := FirewallSSO{}
firewall.PfconfigHashNS = id
_, err := pfconfigdriver.FetchDecodeSocketCache(ctx, &firewall)
if err != nil {
return nil, err
}
if oType, ok := f.typeRegistry[firewall.Type]; ok {
or := reflect.New(oType)
or.Elem().FieldByName("PfconfigHashNS").SetString(id)
firewall2 := or.Interface().(pfconfigdriver.PfconfigObject)
_, err = pfconfigdriver.FetchDecodeSocketCache(ctx, firewall2)
if err != nil {
return nil, err
}
fwint := firewall2.(FirewallSSOInt)
err = fwint.init(ctx)
if err != nil {
return nil, err
}
err = fwint.initChild(ctx)
if err != nil {
return nil, err
}
return fwint, nil
} else {
return nil, errors.New("Cannot find the type of the object")
}
} | [
"func",
"(",
"f",
"*",
"Factory",
")",
"Instantiate",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"string",
")",
"(",
"FirewallSSOInt",
",",
"error",
")",
"{",
"firewall",
":=",
"FirewallSSO",
"{",
"}",
"\n",
"firewall",
".",
"PfconfigHashNS",
"=",
"id",
"\n",
"_",
",",
"err",
":=",
"pfconfigdriver",
".",
"FetchDecodeSocketCache",
"(",
"ctx",
",",
"&",
"firewall",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"oType",
",",
"ok",
":=",
"f",
".",
"typeRegistry",
"[",
"firewall",
".",
"Type",
"]",
";",
"ok",
"{",
"or",
":=",
"reflect",
".",
"New",
"(",
"oType",
")",
"\n",
"or",
".",
"Elem",
"(",
")",
".",
"FieldByName",
"(",
"\"PfconfigHashNS\"",
")",
".",
"SetString",
"(",
"id",
")",
"\n",
"firewall2",
":=",
"or",
".",
"Interface",
"(",
")",
".",
"(",
"pfconfigdriver",
".",
"PfconfigObject",
")",
"\n",
"_",
",",
"err",
"=",
"pfconfigdriver",
".",
"FetchDecodeSocketCache",
"(",
"ctx",
",",
"firewall2",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fwint",
":=",
"firewall2",
".",
"(",
"FirewallSSOInt",
")",
"\n",
"err",
"=",
"fwint",
".",
"init",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"fwint",
".",
"initChild",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"fwint",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"Cannot find the type of the object\"",
")",
"\n",
"}",
"\n",
"}"
] | // Instantiate a new FirewallSSO given its configuration ID in PacketFence | [
"Instantiate",
"a",
"new",
"FirewallSSO",
"given",
"its",
"configuration",
"ID",
"in",
"PacketFence"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/factory.go#L31-L63 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/client.go | Renew | func (c *ACMEClient) Renew(name string) error {
// Get access to ACME storage
storage, err := c.config.StorageFor(c.config.CAUrl)
if err != nil {
return err
}
waiter, err := storage.TryLock(name)
if err != nil {
return err
}
if waiter != nil {
log.Printf("[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting", name)
waiter.Wait()
return nil // we assume the process with the lock succeeded, rather than hammering this execution path again
}
defer func() {
if err := storage.Unlock(name); err != nil {
log.Printf("[ERROR] Unable to unlock renew call for %s: %v", name, err)
}
}()
// Prepare for renewal (load PEM cert, key, and meta)
siteData, err := storage.LoadSite(name)
if err != nil {
return err
}
var certMeta acme.CertificateResource
err = json.Unmarshal(siteData.Meta, &certMeta)
certMeta.Certificate = siteData.Cert
certMeta.PrivateKey = siteData.Key
// Perform renewal and retry if necessary, but not too many times.
var newCertMeta acme.CertificateResource
var success bool
for attempts := 0; attempts < 2; attempts++ {
namesObtaining.Add([]string{name})
acmeMu.Lock()
newCertMeta, err = c.acmeClient.RenewCertificate(certMeta, true, c.config.MustStaple)
acmeMu.Unlock()
namesObtaining.Remove([]string{name})
if err == nil {
success = true
break
}
// If the legal terms were updated and need to be
// agreed to again, we can handle that.
if _, ok := err.(acme.TOSError); ok {
err := c.acmeClient.AgreeToTOS()
if err != nil {
return err
}
continue
}
// For any other kind of error, wait 10s and try again.
wait := 10 * time.Second
log.Printf("[ERROR] Renewing: %v; trying again in %s", err, wait)
time.Sleep(wait)
}
if !success {
return errors.New("too many renewal attempts; last error: " + err.Error())
}
return saveCertResource(storage, newCertMeta)
} | go | func (c *ACMEClient) Renew(name string) error {
// Get access to ACME storage
storage, err := c.config.StorageFor(c.config.CAUrl)
if err != nil {
return err
}
waiter, err := storage.TryLock(name)
if err != nil {
return err
}
if waiter != nil {
log.Printf("[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting", name)
waiter.Wait()
return nil // we assume the process with the lock succeeded, rather than hammering this execution path again
}
defer func() {
if err := storage.Unlock(name); err != nil {
log.Printf("[ERROR] Unable to unlock renew call for %s: %v", name, err)
}
}()
// Prepare for renewal (load PEM cert, key, and meta)
siteData, err := storage.LoadSite(name)
if err != nil {
return err
}
var certMeta acme.CertificateResource
err = json.Unmarshal(siteData.Meta, &certMeta)
certMeta.Certificate = siteData.Cert
certMeta.PrivateKey = siteData.Key
// Perform renewal and retry if necessary, but not too many times.
var newCertMeta acme.CertificateResource
var success bool
for attempts := 0; attempts < 2; attempts++ {
namesObtaining.Add([]string{name})
acmeMu.Lock()
newCertMeta, err = c.acmeClient.RenewCertificate(certMeta, true, c.config.MustStaple)
acmeMu.Unlock()
namesObtaining.Remove([]string{name})
if err == nil {
success = true
break
}
// If the legal terms were updated and need to be
// agreed to again, we can handle that.
if _, ok := err.(acme.TOSError); ok {
err := c.acmeClient.AgreeToTOS()
if err != nil {
return err
}
continue
}
// For any other kind of error, wait 10s and try again.
wait := 10 * time.Second
log.Printf("[ERROR] Renewing: %v; trying again in %s", err, wait)
time.Sleep(wait)
}
if !success {
return errors.New("too many renewal attempts; last error: " + err.Error())
}
return saveCertResource(storage, newCertMeta)
} | [
"func",
"(",
"c",
"*",
"ACMEClient",
")",
"Renew",
"(",
"name",
"string",
")",
"error",
"{",
"storage",
",",
"err",
":=",
"c",
".",
"config",
".",
"StorageFor",
"(",
"c",
".",
"config",
".",
"CAUrl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"waiter",
",",
"err",
":=",
"storage",
".",
"TryLock",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"waiter",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting\"",
",",
"name",
")",
"\n",
"waiter",
".",
"Wait",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"storage",
".",
"Unlock",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[ERROR] Unable to unlock renew call for %s: %v\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"siteData",
",",
"err",
":=",
"storage",
".",
"LoadSite",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"certMeta",
"acme",
".",
"CertificateResource",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"siteData",
".",
"Meta",
",",
"&",
"certMeta",
")",
"\n",
"certMeta",
".",
"Certificate",
"=",
"siteData",
".",
"Cert",
"\n",
"certMeta",
".",
"PrivateKey",
"=",
"siteData",
".",
"Key",
"\n",
"var",
"newCertMeta",
"acme",
".",
"CertificateResource",
"\n",
"var",
"success",
"bool",
"\n",
"for",
"attempts",
":=",
"0",
";",
"attempts",
"<",
"2",
";",
"attempts",
"++",
"{",
"namesObtaining",
".",
"Add",
"(",
"[",
"]",
"string",
"{",
"name",
"}",
")",
"\n",
"acmeMu",
".",
"Lock",
"(",
")",
"\n",
"newCertMeta",
",",
"err",
"=",
"c",
".",
"acmeClient",
".",
"RenewCertificate",
"(",
"certMeta",
",",
"true",
",",
"c",
".",
"config",
".",
"MustStaple",
")",
"\n",
"acmeMu",
".",
"Unlock",
"(",
")",
"\n",
"namesObtaining",
".",
"Remove",
"(",
"[",
"]",
"string",
"{",
"name",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"success",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"acme",
".",
"TOSError",
")",
";",
"ok",
"{",
"err",
":=",
"c",
".",
"acmeClient",
".",
"AgreeToTOS",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"wait",
":=",
"10",
"*",
"time",
".",
"Second",
"\n",
"log",
".",
"Printf",
"(",
"\"[ERROR] Renewing: %v; trying again in %s\"",
",",
"err",
",",
"wait",
")",
"\n",
"time",
".",
"Sleep",
"(",
"wait",
")",
"\n",
"}",
"\n",
"if",
"!",
"success",
"{",
"return",
"errors",
".",
"New",
"(",
"\"too many renewal attempts; last error: \"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"saveCertResource",
"(",
"storage",
",",
"newCertMeta",
")",
"\n",
"}"
] | // Renew renews the managed certificate for name. This function is
// safe for concurrent use.
//
// Callers who have access to a Config value should use the RenewCert
// method on that instead of this lower-level method. | [
"Renew",
"renews",
"the",
"managed",
"certificate",
"for",
"name",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"use",
".",
"Callers",
"who",
"have",
"access",
"to",
"a",
"Config",
"value",
"should",
"use",
"the",
"RenewCert",
"method",
"on",
"that",
"instead",
"of",
"this",
"lower",
"-",
"level",
"method",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L250-L317 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/client.go | Revoke | func (c *ACMEClient) Revoke(name string) error {
storage, err := c.config.StorageFor(c.config.CAUrl)
if err != nil {
return err
}
siteExists, err := storage.SiteExists(name)
if err != nil {
return err
}
if !siteExists {
return errors.New("no certificate and key for " + name)
}
siteData, err := storage.LoadSite(name)
if err != nil {
return err
}
err = c.acmeClient.RevokeCertificate(siteData.Cert)
if err != nil {
return err
}
err = storage.DeleteSite(name)
if err != nil {
return errors.New("certificate revoked, but unable to delete certificate file: " + err.Error())
}
return nil
} | go | func (c *ACMEClient) Revoke(name string) error {
storage, err := c.config.StorageFor(c.config.CAUrl)
if err != nil {
return err
}
siteExists, err := storage.SiteExists(name)
if err != nil {
return err
}
if !siteExists {
return errors.New("no certificate and key for " + name)
}
siteData, err := storage.LoadSite(name)
if err != nil {
return err
}
err = c.acmeClient.RevokeCertificate(siteData.Cert)
if err != nil {
return err
}
err = storage.DeleteSite(name)
if err != nil {
return errors.New("certificate revoked, but unable to delete certificate file: " + err.Error())
}
return nil
} | [
"func",
"(",
"c",
"*",
"ACMEClient",
")",
"Revoke",
"(",
"name",
"string",
")",
"error",
"{",
"storage",
",",
"err",
":=",
"c",
".",
"config",
".",
"StorageFor",
"(",
"c",
".",
"config",
".",
"CAUrl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"siteExists",
",",
"err",
":=",
"storage",
".",
"SiteExists",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"siteExists",
"{",
"return",
"errors",
".",
"New",
"(",
"\"no certificate and key for \"",
"+",
"name",
")",
"\n",
"}",
"\n",
"siteData",
",",
"err",
":=",
"storage",
".",
"LoadSite",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"c",
".",
"acmeClient",
".",
"RevokeCertificate",
"(",
"siteData",
".",
"Cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"storage",
".",
"DeleteSite",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"certificate revoked, but unable to delete certificate file: \"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Revoke revokes the certificate for name and deltes
// it from storage. | [
"Revoke",
"revokes",
"the",
"certificate",
"for",
"name",
"and",
"deltes",
"it",
"from",
"storage",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L321-L352 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/client.go | Add | func (c *nameCoordinator) Add(names []string) {
c.mu.Lock()
for _, name := range names {
c.names[strings.ToLower(name)] = struct{}{}
}
c.mu.Unlock()
} | go | func (c *nameCoordinator) Add(names []string) {
c.mu.Lock()
for _, name := range names {
c.names[strings.ToLower(name)] = struct{}{}
}
c.mu.Unlock()
} | [
"func",
"(",
"c",
"*",
"nameCoordinator",
")",
"Add",
"(",
"names",
"[",
"]",
"string",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"c",
".",
"names",
"[",
"strings",
".",
"ToLower",
"(",
"name",
")",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Add adds names to c. It is safe for concurrent use. | [
"Add",
"adds",
"names",
"to",
"c",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"use",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L369-L375 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/client.go | Remove | func (c *nameCoordinator) Remove(names []string) {
c.mu.Lock()
for _, name := range names {
delete(c.names, strings.ToLower(name))
}
c.mu.Unlock()
} | go | func (c *nameCoordinator) Remove(names []string) {
c.mu.Lock()
for _, name := range names {
delete(c.names, strings.ToLower(name))
}
c.mu.Unlock()
} | [
"func",
"(",
"c",
"*",
"nameCoordinator",
")",
"Remove",
"(",
"names",
"[",
"]",
"string",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"delete",
"(",
"c",
".",
"names",
",",
"strings",
".",
"ToLower",
"(",
"name",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Remove removes names from c. It is safe for concurrent use. | [
"Remove",
"removes",
"names",
"from",
"c",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"use",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L378-L384 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/client.go | Has | func (c *nameCoordinator) Has(name string) bool {
hostname, _, err := net.SplitHostPort(name)
if err != nil {
hostname = name
}
c.mu.RLock()
_, ok := c.names[strings.ToLower(hostname)]
c.mu.RUnlock()
return ok
} | go | func (c *nameCoordinator) Has(name string) bool {
hostname, _, err := net.SplitHostPort(name)
if err != nil {
hostname = name
}
c.mu.RLock()
_, ok := c.names[strings.ToLower(hostname)]
c.mu.RUnlock()
return ok
} | [
"func",
"(",
"c",
"*",
"nameCoordinator",
")",
"Has",
"(",
"name",
"string",
")",
"bool",
"{",
"hostname",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"hostname",
"=",
"name",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"_",
",",
"ok",
":=",
"c",
".",
"names",
"[",
"strings",
".",
"ToLower",
"(",
"hostname",
")",
"]",
"\n",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // Has returns true if c has name. It is safe for concurrent use. | [
"Has",
"returns",
"true",
"if",
"c",
"has",
"name",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"use",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L387-L396 | train |
inverse-inc/packetfence | go/coredns/plugin/metrics/metrics.go | OnShutdown | func (m *Metrics) OnShutdown() error {
if m.ln != nil {
return m.ln.Close()
}
return nil
} | go | func (m *Metrics) OnShutdown() error {
if m.ln != nil {
return m.ln.Close()
}
return nil
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"OnShutdown",
"(",
")",
"error",
"{",
"if",
"m",
".",
"ln",
"!=",
"nil",
"{",
"return",
"m",
".",
"ln",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // OnShutdown tears down the metrics on shutdown and restart. | [
"OnShutdown",
"tears",
"down",
"the",
"metrics",
"on",
"shutdown",
"and",
"restart",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/metrics/metrics.go#L84-L89 | train |
inverse-inc/packetfence | go/sharedutils/util.go | Inc | func Inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
} | go | func Inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
} | [
"func",
"Inc",
"(",
"ip",
"net",
".",
"IP",
")",
"{",
"for",
"j",
":=",
"len",
"(",
"ip",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"ip",
"[",
"j",
"]",
"++",
"\n",
"if",
"ip",
"[",
"j",
"]",
">",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Inc function use to increment an ip | [
"Inc",
"function",
"use",
"to",
"increment",
"an",
"ip"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L172-L179 | train |
inverse-inc/packetfence | go/sharedutils/util.go | Dec | func Dec(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]--
if ip[j] == 255 {
continue
}
if ip[j] > 0 {
break
}
}
} | go | func Dec(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]--
if ip[j] == 255 {
continue
}
if ip[j] > 0 {
break
}
}
} | [
"func",
"Dec",
"(",
"ip",
"net",
".",
"IP",
")",
"{",
"for",
"j",
":=",
"len",
"(",
"ip",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"ip",
"[",
"j",
"]",
"--",
"\n",
"if",
"ip",
"[",
"j",
"]",
"==",
"255",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"ip",
"[",
"j",
"]",
">",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Dec function use to decrement an ip | [
"Dec",
"function",
"use",
"to",
"decrement",
"an",
"ip"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L182-L192 | train |
inverse-inc/packetfence | go/sharedutils/util.go | ConvertToString | func ConvertToString(b []byte) string {
s := make([]string, len(b))
for i := range b {
s[i] = strconv.Itoa(int(b[i]))
}
return strings.Join(s, ",")
} | go | func ConvertToString(b []byte) string {
s := make([]string, len(b))
for i := range b {
s[i] = strconv.Itoa(int(b[i]))
}
return strings.Join(s, ",")
} | [
"func",
"ConvertToString",
"(",
"b",
"[",
"]",
"byte",
")",
"string",
"{",
"s",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"b",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"b",
"{",
"s",
"[",
"i",
"]",
"=",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"b",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"s",
",",
"\",\"",
")",
"\n",
"}"
] | // ConvertToSting convert byte to string | [
"ConvertToSting",
"convert",
"byte",
"to",
"string"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L195-L201 | train |
inverse-inc/packetfence | go/sharedutils/util.go | ConvertToByte | func ConvertToByte(b string) []byte {
s := strings.Split(b, ",")
var result []byte
for i := range s {
value, _ := strconv.Atoi(s[i])
result = append(result, byte(value))
}
return result
} | go | func ConvertToByte(b string) []byte {
s := strings.Split(b, ",")
var result []byte
for i := range s {
value, _ := strconv.Atoi(s[i])
result = append(result, byte(value))
}
return result
} | [
"func",
"ConvertToByte",
"(",
"b",
"string",
")",
"[",
"]",
"byte",
"{",
"s",
":=",
"strings",
".",
"Split",
"(",
"b",
",",
"\",\"",
")",
"\n",
"var",
"result",
"[",
"]",
"byte",
"\n",
"for",
"i",
":=",
"range",
"s",
"{",
"value",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
"[",
"i",
"]",
")",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"byte",
"(",
"value",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // ConvertToByte convert string to byte | [
"ConvertToByte",
"convert",
"string",
"to",
"byte"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L204-L213 | train |
inverse-inc/packetfence | go/sharedutils/util.go | ByteToString | func ByteToString(a []byte) string {
const hexDigit = "0123456789abcdef"
if len(a) == 0 {
return ""
}
buf := make([]byte, 0, len(a)*3-1)
for i, b := range a {
if i > 0 {
buf = append(buf, ':')
}
buf = append(buf, hexDigit[b>>4])
buf = append(buf, hexDigit[b&0xF])
}
return string(buf)
} | go | func ByteToString(a []byte) string {
const hexDigit = "0123456789abcdef"
if len(a) == 0 {
return ""
}
buf := make([]byte, 0, len(a)*3-1)
for i, b := range a {
if i > 0 {
buf = append(buf, ':')
}
buf = append(buf, hexDigit[b>>4])
buf = append(buf, hexDigit[b&0xF])
}
return string(buf)
} | [
"func",
"ByteToString",
"(",
"a",
"[",
"]",
"byte",
")",
"string",
"{",
"const",
"hexDigit",
"=",
"\"0123456789abcdef\"",
"\n",
"if",
"len",
"(",
"a",
")",
"==",
"0",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"a",
")",
"*",
"3",
"-",
"1",
")",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"a",
"{",
"if",
"i",
">",
"0",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"':'",
")",
"\n",
"}",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"hexDigit",
"[",
"b",
">>",
"4",
"]",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"hexDigit",
"[",
"b",
"&",
"0xF",
"]",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"buf",
")",
"\n",
"}"
] | // ByteToString return a human readeable string of the byte | [
"ByteToString",
"return",
"a",
"human",
"readeable",
"string",
"of",
"the",
"byte"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L216-L230 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/config.go | RenewCert | func (c *Config) RenewCert(name string, allowPrompts bool) error {
client, err := newACMEClient(c, allowPrompts)
if err != nil {
return err
}
return client.Renew(name)
} | go | func (c *Config) RenewCert(name string, allowPrompts bool) error {
client, err := newACMEClient(c, allowPrompts)
if err != nil {
return err
}
return client.Renew(name)
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"RenewCert",
"(",
"name",
"string",
",",
"allowPrompts",
"bool",
")",
"error",
"{",
"client",
",",
"err",
":=",
"newACMEClient",
"(",
"c",
",",
"allowPrompts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"client",
".",
"Renew",
"(",
"name",
")",
"\n",
"}"
] | // RenewCert renews the certificate for name using c. It stows the
// renewed certificate and its assets in storage if successful. | [
"RenewCert",
"renews",
"the",
"certificate",
"for",
"name",
"using",
"c",
".",
"It",
"stows",
"the",
"renewed",
"certificate",
"and",
"its",
"assets",
"in",
"storage",
"if",
"successful",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/config.go#L164-L170 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/config.go | StorageFor | func (c *Config) StorageFor(caURL string) (Storage, error) {
// Validate CA URL
if caURL == "" {
caURL = DefaultCAUrl
}
if caURL == "" {
return nil, fmt.Errorf("cannot create storage without CA URL")
}
caURL = strings.ToLower(caURL)
// scheme required or host will be parsed as path (as of Go 1.6)
if !strings.Contains(caURL, "://") {
caURL = "https://" + caURL
}
u, err := url.Parse(caURL)
if err != nil {
return nil, fmt.Errorf("%s: unable to parse CA URL: %v", caURL, err)
}
if u.Host == "" {
return nil, fmt.Errorf("%s: no host in CA URL", caURL)
}
// Create the storage based on the URL
var s Storage
if c.StorageProvider == "" {
c.StorageProvider = "file"
}
creator, ok := storageProviders[c.StorageProvider]
if !ok {
return nil, fmt.Errorf("%s: Unknown storage: %v", caURL, c.StorageProvider)
}
s, err = creator(u)
if err != nil {
return nil, fmt.Errorf("%s: unable to create custom storage '%v': %v", caURL, c.StorageProvider, err)
}
return s, nil
} | go | func (c *Config) StorageFor(caURL string) (Storage, error) {
// Validate CA URL
if caURL == "" {
caURL = DefaultCAUrl
}
if caURL == "" {
return nil, fmt.Errorf("cannot create storage without CA URL")
}
caURL = strings.ToLower(caURL)
// scheme required or host will be parsed as path (as of Go 1.6)
if !strings.Contains(caURL, "://") {
caURL = "https://" + caURL
}
u, err := url.Parse(caURL)
if err != nil {
return nil, fmt.Errorf("%s: unable to parse CA URL: %v", caURL, err)
}
if u.Host == "" {
return nil, fmt.Errorf("%s: no host in CA URL", caURL)
}
// Create the storage based on the URL
var s Storage
if c.StorageProvider == "" {
c.StorageProvider = "file"
}
creator, ok := storageProviders[c.StorageProvider]
if !ok {
return nil, fmt.Errorf("%s: Unknown storage: %v", caURL, c.StorageProvider)
}
s, err = creator(u)
if err != nil {
return nil, fmt.Errorf("%s: unable to create custom storage '%v': %v", caURL, c.StorageProvider, err)
}
return s, nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"StorageFor",
"(",
"caURL",
"string",
")",
"(",
"Storage",
",",
"error",
")",
"{",
"if",
"caURL",
"==",
"\"\"",
"{",
"caURL",
"=",
"DefaultCAUrl",
"\n",
"}",
"\n",
"if",
"caURL",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"cannot create storage without CA URL\"",
")",
"\n",
"}",
"\n",
"caURL",
"=",
"strings",
".",
"ToLower",
"(",
"caURL",
")",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"caURL",
",",
"\"://\"",
")",
"{",
"caURL",
"=",
"\"https://\"",
"+",
"caURL",
"\n",
"}",
"\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"caURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s: unable to parse CA URL: %v\"",
",",
"caURL",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"u",
".",
"Host",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s: no host in CA URL\"",
",",
"caURL",
")",
"\n",
"}",
"\n",
"var",
"s",
"Storage",
"\n",
"if",
"c",
".",
"StorageProvider",
"==",
"\"\"",
"{",
"c",
".",
"StorageProvider",
"=",
"\"file\"",
"\n",
"}",
"\n",
"creator",
",",
"ok",
":=",
"storageProviders",
"[",
"c",
".",
"StorageProvider",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s: Unknown storage: %v\"",
",",
"caURL",
",",
"c",
".",
"StorageProvider",
")",
"\n",
"}",
"\n",
"s",
",",
"err",
"=",
"creator",
"(",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s: unable to create custom storage '%v': %v\"",
",",
"caURL",
",",
"c",
".",
"StorageProvider",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // StorageFor obtains a TLS Storage instance for the given CA URL which should
// be unique for every different ACME CA. If a StorageCreator is set on this
// Config, it will be used. Otherwise the default file storage implementation
// is used. When the error is nil, this is guaranteed to return a non-nil
// Storage instance. | [
"StorageFor",
"obtains",
"a",
"TLS",
"Storage",
"instance",
"for",
"the",
"given",
"CA",
"URL",
"which",
"should",
"be",
"unique",
"for",
"every",
"different",
"ACME",
"CA",
".",
"If",
"a",
"StorageCreator",
"is",
"set",
"on",
"this",
"Config",
"it",
"will",
"be",
"used",
".",
"Otherwise",
"the",
"default",
"file",
"storage",
"implementation",
"is",
"used",
".",
"When",
"the",
"error",
"is",
"nil",
"this",
"is",
"guaranteed",
"to",
"return",
"a",
"non",
"-",
"nil",
"Storage",
"instance",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/config.go#L177-L218 | train |
inverse-inc/packetfence | go/coredns/plugin/auto/zone.go | Remove | func (z *Zones) Remove(name string) {
z.Lock()
if zo, ok := z.Z[name]; ok && !zo.NoReload {
zo.ReloadShutdown <- true
}
delete(z.Z, name)
// TODO(miek): just regenerate Names (might be bad if you have a lot of zones...)
z.names = []string{}
for n := range z.Z {
z.names = append(z.names, n)
}
z.Unlock()
} | go | func (z *Zones) Remove(name string) {
z.Lock()
if zo, ok := z.Z[name]; ok && !zo.NoReload {
zo.ReloadShutdown <- true
}
delete(z.Z, name)
// TODO(miek): just regenerate Names (might be bad if you have a lot of zones...)
z.names = []string{}
for n := range z.Z {
z.names = append(z.names, n)
}
z.Unlock()
} | [
"func",
"(",
"z",
"*",
"Zones",
")",
"Remove",
"(",
"name",
"string",
")",
"{",
"z",
".",
"Lock",
"(",
")",
"\n",
"if",
"zo",
",",
"ok",
":=",
"z",
".",
"Z",
"[",
"name",
"]",
";",
"ok",
"&&",
"!",
"zo",
".",
"NoReload",
"{",
"zo",
".",
"ReloadShutdown",
"<-",
"true",
"\n",
"}",
"\n",
"delete",
"(",
"z",
".",
"Z",
",",
"name",
")",
"\n",
"z",
".",
"names",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"n",
":=",
"range",
"z",
".",
"Z",
"{",
"z",
".",
"names",
"=",
"append",
"(",
"z",
".",
"names",
",",
"n",
")",
"\n",
"}",
"\n",
"z",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Remove removes the zone named name from z. It also stop the the zone's reload goroutine. | [
"Remove",
"removes",
"the",
"zone",
"named",
"name",
"from",
"z",
".",
"It",
"also",
"stop",
"the",
"the",
"zone",
"s",
"reload",
"goroutine",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/auto/zone.go#L60-L76 | train |
inverse-inc/packetfence | go/firewallsso/base.go | init | func (fw *FirewallSSO) init(ctx context.Context) error {
for _, net := range fw.Networks {
err := net.init(ctx)
if err != nil {
return err
}
}
return nil
} | go | func (fw *FirewallSSO) init(ctx context.Context) error {
for _, net := range fw.Networks {
err := net.init(ctx)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"init",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"for",
"_",
",",
"net",
":=",
"range",
"fw",
".",
"Networks",
"{",
"err",
":=",
"net",
".",
"init",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Builds all networks, meant to be called after the data is loaded into the struct attributes | [
"Builds",
"all",
"networks",
"meant",
"to",
"be",
"called",
"after",
"the",
"data",
"is",
"loaded",
"into",
"the",
"struct",
"attributes"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L61-L69 | train |
inverse-inc/packetfence | go/firewallsso/base.go | init | func (fwn *FirewallSSONetwork) init(ctx context.Context) error {
var err error
fwn.Ip, fwn.IpNet, err = net.ParseCIDR(fwn.Cidr)
return err
} | go | func (fwn *FirewallSSONetwork) init(ctx context.Context) error {
var err error
fwn.Ip, fwn.IpNet, err = net.ParseCIDR(fwn.Cidr)
return err
} | [
"func",
"(",
"fwn",
"*",
"FirewallSSONetwork",
")",
"init",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"fwn",
".",
"Ip",
",",
"fwn",
".",
"IpNet",
",",
"err",
"=",
"net",
".",
"ParseCIDR",
"(",
"fwn",
".",
"Cidr",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Builds Ip and IpNet based on the Cidr in the struct | [
"Builds",
"Ip",
"and",
"IpNet",
"based",
"on",
"the",
"Cidr",
"in",
"the",
"struct"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L84-L88 | train |
inverse-inc/packetfence | go/firewallsso/base.go | GetCacheTimeout | func (fw *FirewallSSO) GetCacheTimeout(ctx context.Context) int {
timeout, err := strconv.ParseInt(fw.CacheTimeout, 10, 32)
if err != nil {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Can't parse timeout '%s' into an int (%s).", fw.CacheTimeout, err))
return 0
} else {
return int(timeout)
}
} | go | func (fw *FirewallSSO) GetCacheTimeout(ctx context.Context) int {
timeout, err := strconv.ParseInt(fw.CacheTimeout, 10, 32)
if err != nil {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Can't parse timeout '%s' into an int (%s).", fw.CacheTimeout, err))
return 0
} else {
return int(timeout)
}
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"GetCacheTimeout",
"(",
"ctx",
"context",
".",
"Context",
")",
"int",
"{",
"timeout",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"fw",
".",
"CacheTimeout",
",",
"10",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Can't parse timeout '%s' into an int (%s).\"",
",",
"fw",
".",
"CacheTimeout",
",",
"err",
")",
")",
"\n",
"return",
"0",
"\n",
"}",
"else",
"{",
"return",
"int",
"(",
"timeout",
")",
"\n",
"}",
"\n",
"}"
] | // Get the cache_timeout configured in the firewall as an int
// Will return 0 if its not there or not a valid int | [
"Get",
"the",
"cache_timeout",
"configured",
"in",
"the",
"firewall",
"as",
"an",
"int",
"Will",
"return",
"0",
"if",
"its",
"not",
"there",
"or",
"not",
"a",
"valid",
"int"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L103-L111 | train |
inverse-inc/packetfence | go/firewallsso/base.go | Start | func (fw *FirewallSSO) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) {
log.LoggerWContext(ctx).Debug("Sending SSO start")
return true, nil
} | go | func (fw *FirewallSSO) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) {
log.LoggerWContext(ctx).Debug("Sending SSO start")
return true, nil
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Sending SSO start\"",
")",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // Start method that will be called on every SSO called via ExecuteStart | [
"Start",
"method",
"that",
"will",
"be",
"called",
"on",
"every",
"SSO",
"called",
"via",
"ExecuteStart"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L153-L156 | train |
inverse-inc/packetfence | go/firewallsso/base.go | Stop | func (fw *FirewallSSO) Stop(ctx context.Context, info map[string]string) (bool, error) {
log.LoggerWContext(ctx).Debug("Sending SSO stop")
return true, nil
} | go | func (fw *FirewallSSO) Stop(ctx context.Context, info map[string]string) (bool, error) {
log.LoggerWContext(ctx).Debug("Sending SSO stop")
return true, nil
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"Sending SSO stop\"",
")",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // Stop method that will be called on every SSO called via ExecuteStop | [
"Stop",
"method",
"that",
"will",
"be",
"called",
"on",
"every",
"SSO",
"called",
"via",
"ExecuteStop"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L159-L162 | train |
inverse-inc/packetfence | go/firewallsso/base.go | getSourceIp | func (fw *FirewallSSO) getSourceIp(ctx context.Context) net.IP {
managementNetwork := pfconfigdriver.Config.Interfaces.ManagementNetwork
if managementNetwork.Vip != "" {
return net.ParseIP(managementNetwork.Vip)
} else {
return net.ParseIP(managementNetwork.Ip)
}
} | go | func (fw *FirewallSSO) getSourceIp(ctx context.Context) net.IP {
managementNetwork := pfconfigdriver.Config.Interfaces.ManagementNetwork
if managementNetwork.Vip != "" {
return net.ParseIP(managementNetwork.Vip)
} else {
return net.ParseIP(managementNetwork.Ip)
}
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"getSourceIp",
"(",
"ctx",
"context",
".",
"Context",
")",
"net",
".",
"IP",
"{",
"managementNetwork",
":=",
"pfconfigdriver",
".",
"Config",
".",
"Interfaces",
".",
"ManagementNetwork",
"\n",
"if",
"managementNetwork",
".",
"Vip",
"!=",
"\"\"",
"{",
"return",
"net",
".",
"ParseIP",
"(",
"managementNetwork",
".",
"Vip",
")",
"\n",
"}",
"else",
"{",
"return",
"net",
".",
"ParseIP",
"(",
"managementNetwork",
".",
"Ip",
")",
"\n",
"}",
"\n",
"}"
] | // Get the source IP address for the SSO packets
// Will return either the management VIP if there is one of the IP of the management network | [
"Get",
"the",
"source",
"IP",
"address",
"for",
"the",
"SSO",
"packets",
"Will",
"return",
"either",
"the",
"management",
"VIP",
"if",
"there",
"is",
"one",
"of",
"the",
"IP",
"of",
"the",
"management",
"network"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L170-L178 | train |
inverse-inc/packetfence | go/firewallsso/base.go | getHttpClient | func (fw *FirewallSSO) getHttpClient(ctx context.Context) *http.Client {
// We don't check the TLS certificate if applicable
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
return &http.Client{Transport: transport}
} | go | func (fw *FirewallSSO) getHttpClient(ctx context.Context) *http.Client {
// We don't check the TLS certificate if applicable
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
return &http.Client{Transport: transport}
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"getHttpClient",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"http",
".",
"Client",
"{",
"transport",
":=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"true",
"}",
",",
"}",
"\n",
"return",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
"}",
"\n",
"}"
] | // Get the default SSO HTTP client that doesn't check for valid certificates | [
"Get",
"the",
"default",
"SSO",
"HTTP",
"client",
"that",
"doesn",
"t",
"check",
"for",
"valid",
"certificates"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L181-L187 | train |
inverse-inc/packetfence | go/firewallsso/base.go | getRadiusClient | func (fw *FirewallSSO) getRadiusClient(ctx context.Context) *radius.Client {
return &radius.Client{}
} | go | func (fw *FirewallSSO) getRadiusClient(ctx context.Context) *radius.Client {
return &radius.Client{}
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"getRadiusClient",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"radius",
".",
"Client",
"{",
"return",
"&",
"radius",
".",
"Client",
"{",
"}",
"\n",
"}"
] | // Get the default RADIUS client | [
"Get",
"the",
"default",
"RADIUS",
"client"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L190-L192 | train |
inverse-inc/packetfence | go/firewallsso/base.go | logger | func (fw *FirewallSSO) logger(ctx context.Context) log15.Logger {
ctx = log.AddToLogContext(ctx, "firewall-id", fw.PfconfigHashNS)
return log.LoggerWContext(ctx)
} | go | func (fw *FirewallSSO) logger(ctx context.Context) log15.Logger {
ctx = log.AddToLogContext(ctx, "firewall-id", fw.PfconfigHashNS)
return log.LoggerWContext(ctx)
} | [
"func",
"(",
"fw",
"*",
"FirewallSSO",
")",
"logger",
"(",
"ctx",
"context",
".",
"Context",
")",
"log15",
".",
"Logger",
"{",
"ctx",
"=",
"log",
".",
"AddToLogContext",
"(",
"ctx",
",",
"\"firewall-id\"",
",",
"fw",
".",
"PfconfigHashNS",
")",
"\n",
"return",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
"\n",
"}"
] | // Get the logger for a firewall | [
"Get",
"the",
"logger",
"for",
"a",
"firewall"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L237-L240 | train |
inverse-inc/packetfence | go/firewallsso/base.go | ExecuteStart | func ExecuteStart(ctx context.Context, fw FirewallSSOInt, info map[string]string, timeout int) (bool, error) {
ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS)
if !fw.CheckStatus(ctx, info) {
return false, nil
}
log.LoggerWContext(ctx).Info("Processing SSO Start")
if !fw.MatchesRole(ctx, info) {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for user device %s since it doesn't match the role", info["role"]))
return false, nil
}
if !fw.MatchesNetwork(ctx, info) {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"]))
return false, nil
}
// We change the username with the way it is expected given the format of this firewall
info["username"] = fw.FormatUsername(ctx, info)
parentResult, err := fw.GetFirewallSSO(ctx).Start(ctx, info, timeout)
if err != nil {
return false, err
}
childResult, err := fw.Start(ctx, info, timeout)
return parentResult && childResult, err
} | go | func ExecuteStart(ctx context.Context, fw FirewallSSOInt, info map[string]string, timeout int) (bool, error) {
ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS)
if !fw.CheckStatus(ctx, info) {
return false, nil
}
log.LoggerWContext(ctx).Info("Processing SSO Start")
if !fw.MatchesRole(ctx, info) {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for user device %s since it doesn't match the role", info["role"]))
return false, nil
}
if !fw.MatchesNetwork(ctx, info) {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"]))
return false, nil
}
// We change the username with the way it is expected given the format of this firewall
info["username"] = fw.FormatUsername(ctx, info)
parentResult, err := fw.GetFirewallSSO(ctx).Start(ctx, info, timeout)
if err != nil {
return false, err
}
childResult, err := fw.Start(ctx, info, timeout)
return parentResult && childResult, err
} | [
"func",
"ExecuteStart",
"(",
"ctx",
"context",
".",
"Context",
",",
"fw",
"FirewallSSOInt",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ctx",
"=",
"log",
".",
"AddToLogContext",
"(",
"ctx",
",",
"\"firewall-id\"",
",",
"fw",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
")",
"\n",
"if",
"!",
"fw",
".",
"CheckStatus",
"(",
"ctx",
",",
"info",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"Processing SSO Start\"",
")",
"\n",
"if",
"!",
"fw",
".",
"MatchesRole",
"(",
"ctx",
",",
"info",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Not sending SSO for user device %s since it doesn't match the role\"",
",",
"info",
"[",
"\"role\"",
"]",
")",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"fw",
".",
"MatchesNetwork",
"(",
"ctx",
",",
"info",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Not sending SSO for IP %s since it doesn't match any configured network\"",
",",
"info",
"[",
"\"ip\"",
"]",
")",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"info",
"[",
"\"username\"",
"]",
"=",
"fw",
".",
"FormatUsername",
"(",
"ctx",
",",
"info",
")",
"\n",
"parentResult",
",",
"err",
":=",
"fw",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"Start",
"(",
"ctx",
",",
"info",
",",
"timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"childResult",
",",
"err",
":=",
"fw",
".",
"Start",
"(",
"ctx",
",",
"info",
",",
"timeout",
")",
"\n",
"return",
"parentResult",
"&&",
"childResult",
",",
"err",
"\n",
"}"
] | // Execute an SSO Start request on the specified firewall
// Makes sure to call FirewallSSO.Start and to validate the network and role if necessary | [
"Execute",
"an",
"SSO",
"Start",
"request",
"on",
"the",
"specified",
"firewall",
"Makes",
"sure",
"to",
"call",
"FirewallSSO",
".",
"Start",
"and",
"to",
"validate",
"the",
"network",
"and",
"role",
"if",
"necessary"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L244-L272 | train |
inverse-inc/packetfence | go/firewallsso/base.go | ExecuteStop | func ExecuteStop(ctx context.Context, fw FirewallSSOInt, info map[string]string) (bool, error) {
ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS)
log.LoggerWContext(ctx).Info("Processing SSO Stop")
if !fw.MatchesNetwork(ctx, info) {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"]))
return false, nil
}
// We change the username with the way it is expected given the format of this firewall
info["username"] = fw.FormatUsername(ctx, info)
parentResult, err := fw.GetFirewallSSO(ctx).Stop(ctx, info)
if err != nil {
return false, err
}
childResult, err := fw.Stop(ctx, info)
return parentResult && childResult, err
} | go | func ExecuteStop(ctx context.Context, fw FirewallSSOInt, info map[string]string) (bool, error) {
ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS)
log.LoggerWContext(ctx).Info("Processing SSO Stop")
if !fw.MatchesNetwork(ctx, info) {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"]))
return false, nil
}
// We change the username with the way it is expected given the format of this firewall
info["username"] = fw.FormatUsername(ctx, info)
parentResult, err := fw.GetFirewallSSO(ctx).Stop(ctx, info)
if err != nil {
return false, err
}
childResult, err := fw.Stop(ctx, info)
return parentResult && childResult, err
} | [
"func",
"ExecuteStop",
"(",
"ctx",
"context",
".",
"Context",
",",
"fw",
"FirewallSSOInt",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ctx",
"=",
"log",
".",
"AddToLogContext",
"(",
"ctx",
",",
"\"firewall-id\"",
",",
"fw",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
")",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"Processing SSO Stop\"",
")",
"\n",
"if",
"!",
"fw",
".",
"MatchesNetwork",
"(",
"ctx",
",",
"info",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Not sending SSO for IP %s since it doesn't match any configured network\"",
",",
"info",
"[",
"\"ip\"",
"]",
")",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"info",
"[",
"\"username\"",
"]",
"=",
"fw",
".",
"FormatUsername",
"(",
"ctx",
",",
"info",
")",
"\n",
"parentResult",
",",
"err",
":=",
"fw",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"Stop",
"(",
"ctx",
",",
"info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"childResult",
",",
"err",
":=",
"fw",
".",
"Stop",
"(",
"ctx",
",",
"info",
")",
"\n",
"return",
"parentResult",
"&&",
"childResult",
",",
"err",
"\n",
"}"
] | // Execute an SSO Stop request on the specified firewall
// Makes sure to call FirewallSSO.Start and to validate the network if necessary | [
"Execute",
"an",
"SSO",
"Stop",
"request",
"on",
"the",
"specified",
"firewall",
"Makes",
"sure",
"to",
"call",
"FirewallSSO",
".",
"Start",
"and",
"to",
"validate",
"the",
"network",
"if",
"necessary"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L276-L297 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/cache/cache.go | New | func New(size int) *Cache {
ssize := size / shardSize
if ssize < 512 {
ssize = 512
}
c := &Cache{}
// Initialize all the shards
for i := 0; i < shardSize; i++ {
c.shards[i] = newShard(ssize)
}
return c
} | go | func New(size int) *Cache {
ssize := size / shardSize
if ssize < 512 {
ssize = 512
}
c := &Cache{}
// Initialize all the shards
for i := 0; i < shardSize; i++ {
c.shards[i] = newShard(ssize)
}
return c
} | [
"func",
"New",
"(",
"size",
"int",
")",
"*",
"Cache",
"{",
"ssize",
":=",
"size",
"/",
"shardSize",
"\n",
"if",
"ssize",
"<",
"512",
"{",
"ssize",
"=",
"512",
"\n",
"}",
"\n",
"c",
":=",
"&",
"Cache",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"shardSize",
";",
"i",
"++",
"{",
"c",
".",
"shards",
"[",
"i",
"]",
"=",
"newShard",
"(",
"ssize",
")",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // New returns a new cache. | [
"New",
"returns",
"a",
"new",
"cache",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L32-L45 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/cache/cache.go | Get | func (c *Cache) Get(key uint32) (interface{}, bool) {
shard := key & (shardSize - 1)
return c.shards[shard].Get(key)
} | go | func (c *Cache) Get(key uint32) (interface{}, bool) {
shard := key & (shardSize - 1)
return c.shards[shard].Get(key)
} | [
"func",
"(",
"c",
"*",
"Cache",
")",
"Get",
"(",
"key",
"uint32",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"shard",
":=",
"key",
"&",
"(",
"shardSize",
"-",
"1",
")",
"\n",
"return",
"c",
".",
"shards",
"[",
"shard",
"]",
".",
"Get",
"(",
"key",
")",
"\n",
"}"
] | // Get looks up element index under key. | [
"Get",
"looks",
"up",
"element",
"index",
"under",
"key",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L54-L57 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/cache/cache.go | Add | func (s *shard) Add(key uint32, el interface{}) {
l := s.Len()
if l+1 > s.size {
s.Evict()
}
s.Lock()
s.items[key] = el
s.Unlock()
} | go | func (s *shard) Add(key uint32, el interface{}) {
l := s.Len()
if l+1 > s.size {
s.Evict()
}
s.Lock()
s.items[key] = el
s.Unlock()
} | [
"func",
"(",
"s",
"*",
"shard",
")",
"Add",
"(",
"key",
"uint32",
",",
"el",
"interface",
"{",
"}",
")",
"{",
"l",
":=",
"s",
".",
"Len",
"(",
")",
"\n",
"if",
"l",
"+",
"1",
">",
"s",
".",
"size",
"{",
"s",
".",
"Evict",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"items",
"[",
"key",
"]",
"=",
"el",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Add adds element indexed by key into the cache. Any existing element is overwritten | [
"Add",
"adds",
"element",
"indexed",
"by",
"key",
"into",
"the",
"cache",
".",
"Any",
"existing",
"element",
"is",
"overwritten"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L78-L87 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/cache/cache.go | Remove | func (s *shard) Remove(key uint32) {
s.Lock()
delete(s.items, key)
s.Unlock()
} | go | func (s *shard) Remove(key uint32) {
s.Lock()
delete(s.items, key)
s.Unlock()
} | [
"func",
"(",
"s",
"*",
"shard",
")",
"Remove",
"(",
"key",
"uint32",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"items",
",",
"key",
")",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Remove removes the element indexed by key from the cache. | [
"Remove",
"removes",
"the",
"element",
"indexed",
"by",
"key",
"from",
"the",
"cache",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L90-L94 | train |
inverse-inc/packetfence | go/coredns/plugin/pkg/cache/cache.go | Get | func (s *shard) Get(key uint32) (interface{}, bool) {
s.RLock()
el, found := s.items[key]
s.RUnlock()
return el, found
} | go | func (s *shard) Get(key uint32) (interface{}, bool) {
s.RLock()
el, found := s.items[key]
s.RUnlock()
return el, found
} | [
"func",
"(",
"s",
"*",
"shard",
")",
"Get",
"(",
"key",
"uint32",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"el",
",",
"found",
":=",
"s",
".",
"items",
"[",
"key",
"]",
"\n",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"el",
",",
"found",
"\n",
"}"
] | // Get looks up the element indexed under key. | [
"Get",
"looks",
"up",
"the",
"element",
"indexed",
"under",
"key",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L117-L122 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/server.go | ServePacket | func (s *Server) ServePacket(pc net.PacketConn) error {
if QUIC {
err := s.quicServer.Serve(pc.(*net.UDPConn))
return fmt.Errorf("serving QUIC connections: %v", err)
}
return nil
} | go | func (s *Server) ServePacket(pc net.PacketConn) error {
if QUIC {
err := s.quicServer.Serve(pc.(*net.UDPConn))
return fmt.Errorf("serving QUIC connections: %v", err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ServePacket",
"(",
"pc",
"net",
".",
"PacketConn",
")",
"error",
"{",
"if",
"QUIC",
"{",
"err",
":=",
"s",
".",
"quicServer",
".",
"Serve",
"(",
"pc",
".",
"(",
"*",
"net",
".",
"UDPConn",
")",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"serving QUIC connections: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ServePacket serves QUIC requests on pc until it is closed. | [
"ServePacket",
"serves",
"QUIC",
"requests",
"on",
"pc",
"until",
"it",
"is",
"closed",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/server.go#L193-L199 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.