repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/graceful.go | Close | func (c gracefulConn) Close() error {
err := c.Conn.Close()
if err != nil {
return err
}
// close can fail on http2 connections (as of Oct. 2015, before http2 in std lib)
// so don't decrement count unless close succeeds
c.connWg.Done()
return nil
} | go | func (c gracefulConn) Close() error {
err := c.Conn.Close()
if err != nil {
return err
}
// close can fail on http2 connections (as of Oct. 2015, before http2 in std lib)
// so don't decrement count unless close succeeds
c.connWg.Done()
return nil
} | [
"func",
"(",
"c",
"gracefulConn",
")",
"Close",
"(",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Conn",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// close can fail on http2 connections (as of Oct. 2015, before http2 in std lib)",
"// so don't decrement count unless close succeeds",
"c",
".",
"connWg",
".",
"Done",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes c's underlying connection while updating the wg count. | [
"Close",
"closes",
"c",
"s",
"underlying",
"connection",
"while",
"updating",
"the",
"wg",
"count",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/graceful.go#L71-L80 | train |
inverse-inc/packetfence | go/caddy/caddy/controller.go | OnRestart | func (c *Controller) OnRestart(fn func() error) {
c.instance.onRestart = append(c.instance.onRestart, fn)
} | go | func (c *Controller) OnRestart(fn func() error) {
c.instance.onRestart = append(c.instance.onRestart, fn)
} | [
"func",
"(",
"c",
"*",
"Controller",
")",
"OnRestart",
"(",
"fn",
"func",
"(",
")",
"error",
")",
"{",
"c",
".",
"instance",
".",
"onRestart",
"=",
"append",
"(",
"c",
".",
"instance",
".",
"onRestart",
",",
"fn",
")",
"\n",
"}"
] | // OnRestart adds fn to the list of callback functions to execute
// when the server is about to be restarted. | [
"OnRestart",
"adds",
"fn",
"to",
"the",
"list",
"of",
"callback",
"functions",
"to",
"execute",
"when",
"the",
"server",
"is",
"about",
"to",
"be",
"restarted",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/controller.go#L71-L73 | train |
inverse-inc/packetfence | go/caddy/caddy/controller.go | OnFinalShutdown | func (c *Controller) OnFinalShutdown(fn func() error) {
c.instance.onFinalShutdown = append(c.instance.onFinalShutdown, fn)
} | go | func (c *Controller) OnFinalShutdown(fn func() error) {
c.instance.onFinalShutdown = append(c.instance.onFinalShutdown, fn)
} | [
"func",
"(",
"c",
"*",
"Controller",
")",
"OnFinalShutdown",
"(",
"fn",
"func",
"(",
")",
"error",
")",
"{",
"c",
".",
"instance",
".",
"onFinalShutdown",
"=",
"append",
"(",
"c",
".",
"instance",
".",
"onFinalShutdown",
",",
"fn",
")",
"\n",
"}"
] | // OnFinalShutdown adds fn to the list of callback functions to execute
// when the server is about to be shut down NOT as part of a restart. | [
"OnFinalShutdown",
"adds",
"fn",
"to",
"the",
"list",
"of",
"callback",
"functions",
"to",
"execute",
"when",
"the",
"server",
"is",
"about",
"to",
"be",
"shut",
"down",
"NOT",
"as",
"part",
"of",
"a",
"restart",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/controller.go#L83-L85 | train |
inverse-inc/packetfence | go/coredns/plugin/hosts/hostsfile.go | parse | func (h *Hostsfile) parse(r io.Reader, override *hostsMap) *hostsMap {
hmap := newHostsMap()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Bytes()
if i := bytes.Index(line, []byte{'#'}); i >= 0 {
// Discard comments.
line = line[0:i]
}
f := bytes.Fields(line)
if len(f) < 2 {
continue
}
addr := parseLiteralIP(string(f[0]))
if addr == nil {
continue
}
ver := ipVersion(string(f[0]))
for i := 1; i < len(f); i++ {
name := absDomainName(string(f[i]))
if plugin.Zones(h.Origins).Matches(name) == "" {
// name is not in Origins
continue
}
switch ver {
case 4:
hmap.byNameV4[name] = append(hmap.byNameV4[name], addr)
case 6:
hmap.byNameV6[name] = append(hmap.byNameV6[name], addr)
default:
continue
}
hmap.byAddr[addr.String()] = append(hmap.byAddr[addr.String()], name)
}
}
if override == nil {
return hmap
}
for name := range override.byNameV4 {
hmap.byNameV4[name] = append(hmap.byNameV4[name], override.byNameV4[name]...)
}
for name := range override.byNameV4 {
hmap.byNameV6[name] = append(hmap.byNameV6[name], override.byNameV6[name]...)
}
for addr := range override.byAddr {
hmap.byAddr[addr] = append(hmap.byAddr[addr], override.byAddr[addr]...)
}
return hmap
} | go | func (h *Hostsfile) parse(r io.Reader, override *hostsMap) *hostsMap {
hmap := newHostsMap()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Bytes()
if i := bytes.Index(line, []byte{'#'}); i >= 0 {
// Discard comments.
line = line[0:i]
}
f := bytes.Fields(line)
if len(f) < 2 {
continue
}
addr := parseLiteralIP(string(f[0]))
if addr == nil {
continue
}
ver := ipVersion(string(f[0]))
for i := 1; i < len(f); i++ {
name := absDomainName(string(f[i]))
if plugin.Zones(h.Origins).Matches(name) == "" {
// name is not in Origins
continue
}
switch ver {
case 4:
hmap.byNameV4[name] = append(hmap.byNameV4[name], addr)
case 6:
hmap.byNameV6[name] = append(hmap.byNameV6[name], addr)
default:
continue
}
hmap.byAddr[addr.String()] = append(hmap.byAddr[addr.String()], name)
}
}
if override == nil {
return hmap
}
for name := range override.byNameV4 {
hmap.byNameV4[name] = append(hmap.byNameV4[name], override.byNameV4[name]...)
}
for name := range override.byNameV4 {
hmap.byNameV6[name] = append(hmap.byNameV6[name], override.byNameV6[name]...)
}
for addr := range override.byAddr {
hmap.byAddr[addr] = append(hmap.byAddr[addr], override.byAddr[addr]...)
}
return hmap
} | [
"func",
"(",
"h",
"*",
"Hostsfile",
")",
"parse",
"(",
"r",
"io",
".",
"Reader",
",",
"override",
"*",
"hostsMap",
")",
"*",
"hostsMap",
"{",
"hmap",
":=",
"newHostsMap",
"(",
")",
"\n\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"r",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"line",
":=",
"scanner",
".",
"Bytes",
"(",
")",
"\n",
"if",
"i",
":=",
"bytes",
".",
"Index",
"(",
"line",
",",
"[",
"]",
"byte",
"{",
"'#'",
"}",
")",
";",
"i",
">=",
"0",
"{",
"// Discard comments.",
"line",
"=",
"line",
"[",
"0",
":",
"i",
"]",
"\n",
"}",
"\n",
"f",
":=",
"bytes",
".",
"Fields",
"(",
"line",
")",
"\n",
"if",
"len",
"(",
"f",
")",
"<",
"2",
"{",
"continue",
"\n",
"}",
"\n",
"addr",
":=",
"parseLiteralIP",
"(",
"string",
"(",
"f",
"[",
"0",
"]",
")",
")",
"\n",
"if",
"addr",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"ver",
":=",
"ipVersion",
"(",
"string",
"(",
"f",
"[",
"0",
"]",
")",
")",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"len",
"(",
"f",
")",
";",
"i",
"++",
"{",
"name",
":=",
"absDomainName",
"(",
"string",
"(",
"f",
"[",
"i",
"]",
")",
")",
"\n",
"if",
"plugin",
".",
"Zones",
"(",
"h",
".",
"Origins",
")",
".",
"Matches",
"(",
"name",
")",
"==",
"\"",
"\"",
"{",
"// name is not in Origins",
"continue",
"\n",
"}",
"\n",
"switch",
"ver",
"{",
"case",
"4",
":",
"hmap",
".",
"byNameV4",
"[",
"name",
"]",
"=",
"append",
"(",
"hmap",
".",
"byNameV4",
"[",
"name",
"]",
",",
"addr",
")",
"\n",
"case",
"6",
":",
"hmap",
".",
"byNameV6",
"[",
"name",
"]",
"=",
"append",
"(",
"hmap",
".",
"byNameV6",
"[",
"name",
"]",
",",
"addr",
")",
"\n",
"default",
":",
"continue",
"\n",
"}",
"\n",
"hmap",
".",
"byAddr",
"[",
"addr",
".",
"String",
"(",
")",
"]",
"=",
"append",
"(",
"hmap",
".",
"byAddr",
"[",
"addr",
".",
"String",
"(",
")",
"]",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"override",
"==",
"nil",
"{",
"return",
"hmap",
"\n",
"}",
"\n\n",
"for",
"name",
":=",
"range",
"override",
".",
"byNameV4",
"{",
"hmap",
".",
"byNameV4",
"[",
"name",
"]",
"=",
"append",
"(",
"hmap",
".",
"byNameV4",
"[",
"name",
"]",
",",
"override",
".",
"byNameV4",
"[",
"name",
"]",
"...",
")",
"\n",
"}",
"\n",
"for",
"name",
":=",
"range",
"override",
".",
"byNameV4",
"{",
"hmap",
".",
"byNameV6",
"[",
"name",
"]",
"=",
"append",
"(",
"hmap",
".",
"byNameV6",
"[",
"name",
"]",
",",
"override",
".",
"byNameV6",
"[",
"name",
"]",
"...",
")",
"\n",
"}",
"\n",
"for",
"addr",
":=",
"range",
"override",
".",
"byAddr",
"{",
"hmap",
".",
"byAddr",
"[",
"addr",
"]",
"=",
"append",
"(",
"hmap",
".",
"byAddr",
"[",
"addr",
"]",
",",
"override",
".",
"byAddr",
"[",
"addr",
"]",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"hmap",
"\n",
"}"
] | // Parse reads the hostsfile and populates the byName and byAddr maps. | [
"Parse",
"reads",
"the",
"hostsfile",
"and",
"populates",
"the",
"byName",
"and",
"byAddr",
"maps",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/hosts/hostsfile.go#L117-L169 | train |
inverse-inc/packetfence | go/coredns/plugin/hosts/hostsfile.go | LookupStaticAddr | func (h *Hostsfile) LookupStaticAddr(addr string) []string {
h.RLock()
defer h.RUnlock()
addr = parseLiteralIP(addr).String()
if addr == "" {
return nil
}
if len(h.hmap.byAddr) != 0 {
if hosts, ok := h.hmap.byAddr[addr]; ok {
hostsCp := make([]string, len(hosts))
copy(hostsCp, hosts)
return hostsCp
}
}
return nil
} | go | func (h *Hostsfile) LookupStaticAddr(addr string) []string {
h.RLock()
defer h.RUnlock()
addr = parseLiteralIP(addr).String()
if addr == "" {
return nil
}
if len(h.hmap.byAddr) != 0 {
if hosts, ok := h.hmap.byAddr[addr]; ok {
hostsCp := make([]string, len(hosts))
copy(hostsCp, hosts)
return hostsCp
}
}
return nil
} | [
"func",
"(",
"h",
"*",
"Hostsfile",
")",
"LookupStaticAddr",
"(",
"addr",
"string",
")",
"[",
"]",
"string",
"{",
"h",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"RUnlock",
"(",
")",
"\n",
"addr",
"=",
"parseLiteralIP",
"(",
"addr",
")",
".",
"String",
"(",
")",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"h",
".",
"hmap",
".",
"byAddr",
")",
"!=",
"0",
"{",
"if",
"hosts",
",",
"ok",
":=",
"h",
".",
"hmap",
".",
"byAddr",
"[",
"addr",
"]",
";",
"ok",
"{",
"hostsCp",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"hosts",
")",
")",
"\n",
"copy",
"(",
"hostsCp",
",",
"hosts",
")",
"\n",
"return",
"hostsCp",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // LookupStaticAddr looks up the hosts for the given address from the hosts file. | [
"LookupStaticAddr",
"looks",
"up",
"the",
"hosts",
"for",
"the",
"given",
"address",
"from",
"the",
"hosts",
"file",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/hosts/hostsfile.go#L213-L228 | train |
inverse-inc/packetfence | go/coredns/plugin/cache/cache.go | key | func key(m *dns.Msg, t response.Type, do bool) int {
// We don't store truncated responses.
if m.Truncated {
return -1
}
// Nor errors or Meta or Update
if t == response.OtherError || t == response.Meta || t == response.Update {
return -1
}
return int(hash(m.Question[0].Name, m.Question[0].Qtype, do))
} | go | func key(m *dns.Msg, t response.Type, do bool) int {
// We don't store truncated responses.
if m.Truncated {
return -1
}
// Nor errors or Meta or Update
if t == response.OtherError || t == response.Meta || t == response.Update {
return -1
}
return int(hash(m.Question[0].Name, m.Question[0].Qtype, do))
} | [
"func",
"key",
"(",
"m",
"*",
"dns",
".",
"Msg",
",",
"t",
"response",
".",
"Type",
",",
"do",
"bool",
")",
"int",
"{",
"// We don't store truncated responses.",
"if",
"m",
".",
"Truncated",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"// Nor errors or Meta or Update",
"if",
"t",
"==",
"response",
".",
"OtherError",
"||",
"t",
"==",
"response",
".",
"Meta",
"||",
"t",
"==",
"response",
".",
"Update",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n\n",
"return",
"int",
"(",
"hash",
"(",
"m",
".",
"Question",
"[",
"0",
"]",
".",
"Name",
",",
"m",
".",
"Question",
"[",
"0",
"]",
".",
"Qtype",
",",
"do",
")",
")",
"\n",
"}"
] | // Return key under which we store the item, -1 will be returned if we don't store the
// message.
// Currently we do not cache Truncated, errors zone transfers or dynamic update messages. | [
"Return",
"key",
"under",
"which",
"we",
"store",
"the",
"item",
"-",
"1",
"will",
"be",
"returned",
"if",
"we",
"don",
"t",
"store",
"the",
"message",
".",
"Currently",
"we",
"do",
"not",
"cache",
"Truncated",
"errors",
"zone",
"transfers",
"or",
"dynamic",
"update",
"messages",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/cache/cache.go#L40-L51 | train |
inverse-inc/packetfence | go/caddy/caddy/startupshutdown/startupshutdown.go | registerCallback | func registerCallback(c *caddy.Controller, registerFunc func(func() error)) error {
var funcs []func() error
for c.Next() {
args := c.RemainingArgs()
if len(args) == 0 {
return c.ArgErr()
}
nonblock := false
if len(args) > 1 && args[len(args)-1] == "&" {
// Run command in background; non-blocking
nonblock = true
args = args[:len(args)-1]
}
command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " "))
if err != nil {
return c.Err(err.Error())
}
fn := func() error {
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if nonblock {
log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Start()
}
log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Run()
}
funcs = append(funcs, fn)
}
return c.OncePerServerBlock(func() error {
for _, fn := range funcs {
registerFunc(fn)
}
return nil
})
} | go | func registerCallback(c *caddy.Controller, registerFunc func(func() error)) error {
var funcs []func() error
for c.Next() {
args := c.RemainingArgs()
if len(args) == 0 {
return c.ArgErr()
}
nonblock := false
if len(args) > 1 && args[len(args)-1] == "&" {
// Run command in background; non-blocking
nonblock = true
args = args[:len(args)-1]
}
command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " "))
if err != nil {
return c.Err(err.Error())
}
fn := func() error {
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if nonblock {
log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Start()
}
log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Run()
}
funcs = append(funcs, fn)
}
return c.OncePerServerBlock(func() error {
for _, fn := range funcs {
registerFunc(fn)
}
return nil
})
} | [
"func",
"registerCallback",
"(",
"c",
"*",
"caddy",
".",
"Controller",
",",
"registerFunc",
"func",
"(",
"func",
"(",
")",
"error",
")",
")",
"error",
"{",
"var",
"funcs",
"[",
"]",
"func",
"(",
")",
"error",
"\n\n",
"for",
"c",
".",
"Next",
"(",
")",
"{",
"args",
":=",
"c",
".",
"RemainingArgs",
"(",
")",
"\n",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"{",
"return",
"c",
".",
"ArgErr",
"(",
")",
"\n",
"}",
"\n\n",
"nonblock",
":=",
"false",
"\n",
"if",
"len",
"(",
"args",
")",
">",
"1",
"&&",
"args",
"[",
"len",
"(",
"args",
")",
"-",
"1",
"]",
"==",
"\"",
"\"",
"{",
"// Run command in background; non-blocking",
"nonblock",
"=",
"true",
"\n",
"args",
"=",
"args",
"[",
":",
"len",
"(",
"args",
")",
"-",
"1",
"]",
"\n",
"}",
"\n\n",
"command",
",",
"args",
",",
"err",
":=",
"caddy",
".",
"SplitCommandAndArgs",
"(",
"strings",
".",
"Join",
"(",
"args",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"c",
".",
"Err",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"fn",
":=",
"func",
"(",
")",
"error",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"command",
",",
"args",
"...",
")",
"\n",
"cmd",
".",
"Stdin",
"=",
"os",
".",
"Stdin",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"if",
"nonblock",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"command",
",",
"strings",
".",
"Join",
"(",
"args",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"cmd",
".",
"Start",
"(",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"command",
",",
"strings",
".",
"Join",
"(",
"args",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"cmd",
".",
"Run",
"(",
")",
"\n",
"}",
"\n\n",
"funcs",
"=",
"append",
"(",
"funcs",
",",
"fn",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"OncePerServerBlock",
"(",
"func",
"(",
")",
"error",
"{",
"for",
"_",
",",
"fn",
":=",
"range",
"funcs",
"{",
"registerFunc",
"(",
"fn",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // registerCallback registers a callback function to execute by
// using c to parse the directive. It registers the callback
// to be executed using registerFunc. | [
"registerCallback",
"registers",
"a",
"callback",
"function",
"to",
"execute",
"by",
"using",
"c",
"to",
"parse",
"the",
"directive",
".",
"It",
"registers",
"the",
"callback",
"to",
"be",
"executed",
"using",
"registerFunc",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/startupshutdown/startupshutdown.go#L30-L73 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/msg/msg.go | AddrMsg | func (b *Builder) AddrMsg(a net.Addr, m *dns.Msg) (err error) {
err = b.RemoteAddr(a)
if err != nil {
return
}
return b.Msg(m)
} | go | func (b *Builder) AddrMsg(a net.Addr, m *dns.Msg) (err error) {
err = b.RemoteAddr(a)
if err != nil {
return
}
return b.Msg(m)
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"AddrMsg",
"(",
"a",
"net",
".",
"Addr",
",",
"m",
"*",
"dns",
".",
"Msg",
")",
"(",
"err",
"error",
")",
"{",
"err",
"=",
"b",
".",
"RemoteAddr",
"(",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"b",
".",
"Msg",
"(",
"m",
")",
"\n",
"}"
] | // AddrMsg parses the info of net.Addr and dns.Msg. | [
"AddrMsg",
"parses",
"the",
"info",
"of",
"net",
".",
"Addr",
"and",
"dns",
".",
"Msg",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L20-L26 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/msg/msg.go | Msg | func (b *Builder) Msg(m *dns.Msg) (err error) {
if b.Full {
err = b.Pack(m)
}
return
} | go | func (b *Builder) Msg(m *dns.Msg) (err error) {
if b.Full {
err = b.Pack(m)
}
return
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Msg",
"(",
"m",
"*",
"dns",
".",
"Msg",
")",
"(",
"err",
"error",
")",
"{",
"if",
"b",
".",
"Full",
"{",
"err",
"=",
"b",
".",
"Pack",
"(",
"m",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Msg parses the info of dns.Msg. | [
"Msg",
"parses",
"the",
"info",
"of",
"dns",
".",
"Msg",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L29-L34 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/msg/msg.go | HostPort | func (d *Data) HostPort(addr string) error {
ip, port, err := net.SplitHostPort(addr)
if err != nil {
return err
}
p, err := strconv.ParseUint(port, 10, 32)
if err != nil {
return err
}
d.Port = uint32(p)
if ip := net.ParseIP(ip); ip != nil {
d.Address = []byte(ip)
if ip := ip.To4(); ip != nil {
d.SocketFam = tap.SocketFamily_INET
} else {
d.SocketFam = tap.SocketFamily_INET6
}
return nil
}
return errors.New("not an ip address")
} | go | func (d *Data) HostPort(addr string) error {
ip, port, err := net.SplitHostPort(addr)
if err != nil {
return err
}
p, err := strconv.ParseUint(port, 10, 32)
if err != nil {
return err
}
d.Port = uint32(p)
if ip := net.ParseIP(ip); ip != nil {
d.Address = []byte(ip)
if ip := ip.To4(); ip != nil {
d.SocketFam = tap.SocketFamily_INET
} else {
d.SocketFam = tap.SocketFamily_INET6
}
return nil
}
return errors.New("not an ip address")
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"HostPort",
"(",
"addr",
"string",
")",
"error",
"{",
"ip",
",",
"port",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"port",
",",
"10",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"d",
".",
"Port",
"=",
"uint32",
"(",
"p",
")",
"\n\n",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"ip",
")",
";",
"ip",
"!=",
"nil",
"{",
"d",
".",
"Address",
"=",
"[",
"]",
"byte",
"(",
"ip",
")",
"\n",
"if",
"ip",
":=",
"ip",
".",
"To4",
"(",
")",
";",
"ip",
"!=",
"nil",
"{",
"d",
".",
"SocketFam",
"=",
"tap",
".",
"SocketFamily_INET",
"\n",
"}",
"else",
"{",
"d",
".",
"SocketFam",
"=",
"tap",
".",
"SocketFamily_INET6",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // HostPort decodes into Data any string returned by dnsutil.ParseHostPortOrFile. | [
"HostPort",
"decodes",
"into",
"Data",
"any",
"string",
"returned",
"by",
"dnsutil",
".",
"ParseHostPortOrFile",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L48-L69 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/msg/msg.go | RemoteAddr | func (d *Data) RemoteAddr(remote net.Addr) error {
switch addr := remote.(type) {
case *net.TCPAddr:
d.Address = addr.IP
d.Port = uint32(addr.Port)
d.SocketProto = tap.SocketProtocol_TCP
case *net.UDPAddr:
d.Address = addr.IP
d.Port = uint32(addr.Port)
d.SocketProto = tap.SocketProtocol_UDP
default:
return errors.New("unknown remote address type")
}
if a := net.IP(d.Address); a.To4() != nil {
d.SocketFam = tap.SocketFamily_INET
} else {
d.SocketFam = tap.SocketFamily_INET6
}
return nil
} | go | func (d *Data) RemoteAddr(remote net.Addr) error {
switch addr := remote.(type) {
case *net.TCPAddr:
d.Address = addr.IP
d.Port = uint32(addr.Port)
d.SocketProto = tap.SocketProtocol_TCP
case *net.UDPAddr:
d.Address = addr.IP
d.Port = uint32(addr.Port)
d.SocketProto = tap.SocketProtocol_UDP
default:
return errors.New("unknown remote address type")
}
if a := net.IP(d.Address); a.To4() != nil {
d.SocketFam = tap.SocketFamily_INET
} else {
d.SocketFam = tap.SocketFamily_INET6
}
return nil
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"RemoteAddr",
"(",
"remote",
"net",
".",
"Addr",
")",
"error",
"{",
"switch",
"addr",
":=",
"remote",
".",
"(",
"type",
")",
"{",
"case",
"*",
"net",
".",
"TCPAddr",
":",
"d",
".",
"Address",
"=",
"addr",
".",
"IP",
"\n",
"d",
".",
"Port",
"=",
"uint32",
"(",
"addr",
".",
"Port",
")",
"\n",
"d",
".",
"SocketProto",
"=",
"tap",
".",
"SocketProtocol_TCP",
"\n",
"case",
"*",
"net",
".",
"UDPAddr",
":",
"d",
".",
"Address",
"=",
"addr",
".",
"IP",
"\n",
"d",
".",
"Port",
"=",
"uint32",
"(",
"addr",
".",
"Port",
")",
"\n",
"d",
".",
"SocketProto",
"=",
"tap",
".",
"SocketProtocol_UDP",
"\n",
"default",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"a",
":=",
"net",
".",
"IP",
"(",
"d",
".",
"Address",
")",
";",
"a",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"d",
".",
"SocketFam",
"=",
"tap",
".",
"SocketFamily_INET",
"\n",
"}",
"else",
"{",
"d",
".",
"SocketFam",
"=",
"tap",
".",
"SocketFamily_INET6",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // RemoteAddr parses the information about the remote address into Data. | [
"RemoteAddr",
"parses",
"the",
"information",
"about",
"the",
"remote",
"address",
"into",
"Data",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L72-L93 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/msg/msg.go | Pack | func (d *Data) Pack(m *dns.Msg) error {
packed, err := m.Pack()
if err != nil {
return err
}
d.Packed = packed
return nil
} | go | func (d *Data) Pack(m *dns.Msg) error {
packed, err := m.Pack()
if err != nil {
return err
}
d.Packed = packed
return nil
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Pack",
"(",
"m",
"*",
"dns",
".",
"Msg",
")",
"error",
"{",
"packed",
",",
"err",
":=",
"m",
".",
"Pack",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"d",
".",
"Packed",
"=",
"packed",
"\n",
"return",
"nil",
"\n",
"}"
] | // Pack encodes the DNS message into Data. | [
"Pack",
"encodes",
"the",
"DNS",
"message",
"into",
"Data",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L96-L103 | train |
inverse-inc/packetfence | go/coredns/plugin/proxy/google.go | newUpstream | func newUpstream(hosts []string, old *staticUpstream) Upstream {
upstream := &staticUpstream{
from: old.from,
HealthCheck: healthcheck.HealthCheck{
FailTimeout: 5 * time.Second,
MaxFails: 3,
},
ex: old.ex,
IgnoredSubDomains: old.IgnoredSubDomains,
}
upstream.Hosts = make([]*healthcheck.UpstreamHost, len(hosts))
for i, host := range hosts {
uh := &healthcheck.UpstreamHost{
Name: host,
Conns: 0,
Fails: 0,
FailTimeout: upstream.FailTimeout,
CheckDown: checkDownFunc(upstream),
}
upstream.Hosts[i] = uh
}
return upstream
} | go | func newUpstream(hosts []string, old *staticUpstream) Upstream {
upstream := &staticUpstream{
from: old.from,
HealthCheck: healthcheck.HealthCheck{
FailTimeout: 5 * time.Second,
MaxFails: 3,
},
ex: old.ex,
IgnoredSubDomains: old.IgnoredSubDomains,
}
upstream.Hosts = make([]*healthcheck.UpstreamHost, len(hosts))
for i, host := range hosts {
uh := &healthcheck.UpstreamHost{
Name: host,
Conns: 0,
Fails: 0,
FailTimeout: upstream.FailTimeout,
CheckDown: checkDownFunc(upstream),
}
upstream.Hosts[i] = uh
}
return upstream
} | [
"func",
"newUpstream",
"(",
"hosts",
"[",
"]",
"string",
",",
"old",
"*",
"staticUpstream",
")",
"Upstream",
"{",
"upstream",
":=",
"&",
"staticUpstream",
"{",
"from",
":",
"old",
".",
"from",
",",
"HealthCheck",
":",
"healthcheck",
".",
"HealthCheck",
"{",
"FailTimeout",
":",
"5",
"*",
"time",
".",
"Second",
",",
"MaxFails",
":",
"3",
",",
"}",
",",
"ex",
":",
"old",
".",
"ex",
",",
"IgnoredSubDomains",
":",
"old",
".",
"IgnoredSubDomains",
",",
"}",
"\n\n",
"upstream",
".",
"Hosts",
"=",
"make",
"(",
"[",
"]",
"*",
"healthcheck",
".",
"UpstreamHost",
",",
"len",
"(",
"hosts",
")",
")",
"\n",
"for",
"i",
",",
"host",
":=",
"range",
"hosts",
"{",
"uh",
":=",
"&",
"healthcheck",
".",
"UpstreamHost",
"{",
"Name",
":",
"host",
",",
"Conns",
":",
"0",
",",
"Fails",
":",
"0",
",",
"FailTimeout",
":",
"upstream",
".",
"FailTimeout",
",",
"CheckDown",
":",
"checkDownFunc",
"(",
"upstream",
")",
",",
"}",
"\n",
"upstream",
".",
"Hosts",
"[",
"i",
"]",
"=",
"uh",
"\n",
"}",
"\n",
"return",
"upstream",
"\n",
"}"
] | // newUpstream returns an upstream initialized with hosts. | [
"newUpstream",
"returns",
"an",
"upstream",
"initialized",
"with",
"hosts",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/google.go#L191-L214 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyfile/parse.go | replaceEnvReferences | func replaceEnvReferences(s, refStart, refEnd string) string {
index := strings.Index(s, refStart)
for index != -1 {
endIndex := strings.Index(s, refEnd)
if endIndex != -1 {
ref := s[index : endIndex+len(refEnd)]
s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1)
} else {
return s
}
index = strings.Index(s, refStart)
}
return s
} | go | func replaceEnvReferences(s, refStart, refEnd string) string {
index := strings.Index(s, refStart)
for index != -1 {
endIndex := strings.Index(s, refEnd)
if endIndex != -1 {
ref := s[index : endIndex+len(refEnd)]
s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1)
} else {
return s
}
index = strings.Index(s, refStart)
}
return s
} | [
"func",
"replaceEnvReferences",
"(",
"s",
",",
"refStart",
",",
"refEnd",
"string",
")",
"string",
"{",
"index",
":=",
"strings",
".",
"Index",
"(",
"s",
",",
"refStart",
")",
"\n",
"for",
"index",
"!=",
"-",
"1",
"{",
"endIndex",
":=",
"strings",
".",
"Index",
"(",
"s",
",",
"refEnd",
")",
"\n",
"if",
"endIndex",
"!=",
"-",
"1",
"{",
"ref",
":=",
"s",
"[",
"index",
":",
"endIndex",
"+",
"len",
"(",
"refEnd",
")",
"]",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"ref",
",",
"os",
".",
"Getenv",
"(",
"ref",
"[",
"len",
"(",
"refStart",
")",
":",
"len",
"(",
"ref",
")",
"-",
"len",
"(",
"refEnd",
")",
"]",
")",
",",
"-",
"1",
")",
"\n",
"}",
"else",
"{",
"return",
"s",
"\n",
"}",
"\n",
"index",
"=",
"strings",
".",
"Index",
"(",
"s",
",",
"refStart",
")",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // replaceEnvReferences performs the actual replacement of env variables
// in s, given the placeholder start and placeholder end strings. | [
"replaceEnvReferences",
"performs",
"the",
"actual",
"replacement",
"of",
"env",
"variables",
"in",
"s",
"given",
"the",
"placeholder",
"start",
"and",
"placeholder",
"end",
"strings",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyfile/parse.go#L396-L409 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/https.go | redirPlaintextHost | func redirPlaintextHost(cfg *SiteConfig) *SiteConfig {
redirPort := cfg.Addr.Port
if redirPort == "443" {
// default port is redundant
redirPort = ""
}
redirMiddleware := func(next Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
toURL := "https://" + r.Host
if redirPort != "" {
toURL += ":" + redirPort
}
toURL += r.URL.RequestURI()
w.Header().Set("Connection", "close")
http.Redirect(w, r, toURL, http.StatusMovedPermanently)
return 0, nil
})
}
host := cfg.Addr.Host
port := "80"
addr := net.JoinHostPort(host, port)
return &SiteConfig{
Addr: Address{Original: addr, Host: host, Port: port},
ListenHost: cfg.ListenHost,
middleware: []Middleware{redirMiddleware},
TLS: &caddytls.Config{AltHTTPPort: cfg.TLS.AltHTTPPort},
}
} | go | func redirPlaintextHost(cfg *SiteConfig) *SiteConfig {
redirPort := cfg.Addr.Port
if redirPort == "443" {
// default port is redundant
redirPort = ""
}
redirMiddleware := func(next Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
toURL := "https://" + r.Host
if redirPort != "" {
toURL += ":" + redirPort
}
toURL += r.URL.RequestURI()
w.Header().Set("Connection", "close")
http.Redirect(w, r, toURL, http.StatusMovedPermanently)
return 0, nil
})
}
host := cfg.Addr.Host
port := "80"
addr := net.JoinHostPort(host, port)
return &SiteConfig{
Addr: Address{Original: addr, Host: host, Port: port},
ListenHost: cfg.ListenHost,
middleware: []Middleware{redirMiddleware},
TLS: &caddytls.Config{AltHTTPPort: cfg.TLS.AltHTTPPort},
}
} | [
"func",
"redirPlaintextHost",
"(",
"cfg",
"*",
"SiteConfig",
")",
"*",
"SiteConfig",
"{",
"redirPort",
":=",
"cfg",
".",
"Addr",
".",
"Port",
"\n",
"if",
"redirPort",
"==",
"\"",
"\"",
"{",
"// default port is redundant",
"redirPort",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"redirMiddleware",
":=",
"func",
"(",
"next",
"Handler",
")",
"Handler",
"{",
"return",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"int",
",",
"error",
")",
"{",
"toURL",
":=",
"\"",
"\"",
"+",
"r",
".",
"Host",
"\n",
"if",
"redirPort",
"!=",
"\"",
"\"",
"{",
"toURL",
"+=",
"\"",
"\"",
"+",
"redirPort",
"\n",
"}",
"\n",
"toURL",
"+=",
"r",
".",
"URL",
".",
"RequestURI",
"(",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"toURL",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"0",
",",
"nil",
"\n",
"}",
")",
"\n",
"}",
"\n",
"host",
":=",
"cfg",
".",
"Addr",
".",
"Host",
"\n",
"port",
":=",
"\"",
"\"",
"\n",
"addr",
":=",
"net",
".",
"JoinHostPort",
"(",
"host",
",",
"port",
")",
"\n",
"return",
"&",
"SiteConfig",
"{",
"Addr",
":",
"Address",
"{",
"Original",
":",
"addr",
",",
"Host",
":",
"host",
",",
"Port",
":",
"port",
"}",
",",
"ListenHost",
":",
"cfg",
".",
"ListenHost",
",",
"middleware",
":",
"[",
"]",
"Middleware",
"{",
"redirMiddleware",
"}",
",",
"TLS",
":",
"&",
"caddytls",
".",
"Config",
"{",
"AltHTTPPort",
":",
"cfg",
".",
"TLS",
".",
"AltHTTPPort",
"}",
",",
"}",
"\n",
"}"
] | // redirPlaintextHost returns a new plaintext HTTP configuration for
// a virtualHost that simply redirects to cfg, which is assumed to
// be the HTTPS configuration. The returned configuration is set
// to listen on port 80. The TLS field of cfg must not be nil. | [
"redirPlaintextHost",
"returns",
"a",
"new",
"plaintext",
"HTTP",
"configuration",
"for",
"a",
"virtualHost",
"that",
"simply",
"redirects",
"to",
"cfg",
"which",
"is",
"assumed",
"to",
"be",
"the",
"HTTPS",
"configuration",
".",
"The",
"returned",
"configuration",
"is",
"set",
"to",
"listen",
"on",
"port",
"80",
".",
"The",
"TLS",
"field",
"of",
"cfg",
"must",
"not",
"be",
"nil",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/https.go#L139-L166 | train |
inverse-inc/packetfence | go/coredns/plugin/metrics/vars/report.go | Report | func Report(req request.Request, zone, rcode string, size int, start time.Time) {
// Proto and Family.
net := req.Proto()
fam := "1"
if req.Family() == 2 {
fam = "2"
}
typ := req.QType()
RequestCount.WithLabelValues(zone, net, fam).Inc()
RequestDuration.WithLabelValues(zone).Observe(float64(time.Since(start) / time.Millisecond))
if req.Do() {
RequestDo.WithLabelValues(zone).Inc()
}
if _, known := monitorType[typ]; known {
RequestType.WithLabelValues(zone, dns.Type(typ).String()).Inc()
} else {
RequestType.WithLabelValues(zone, other).Inc()
}
ResponseSize.WithLabelValues(zone, net).Observe(float64(size))
RequestSize.WithLabelValues(zone, net).Observe(float64(req.Len()))
ResponseRcode.WithLabelValues(zone, rcode).Inc()
} | go | func Report(req request.Request, zone, rcode string, size int, start time.Time) {
// Proto and Family.
net := req.Proto()
fam := "1"
if req.Family() == 2 {
fam = "2"
}
typ := req.QType()
RequestCount.WithLabelValues(zone, net, fam).Inc()
RequestDuration.WithLabelValues(zone).Observe(float64(time.Since(start) / time.Millisecond))
if req.Do() {
RequestDo.WithLabelValues(zone).Inc()
}
if _, known := monitorType[typ]; known {
RequestType.WithLabelValues(zone, dns.Type(typ).String()).Inc()
} else {
RequestType.WithLabelValues(zone, other).Inc()
}
ResponseSize.WithLabelValues(zone, net).Observe(float64(size))
RequestSize.WithLabelValues(zone, net).Observe(float64(req.Len()))
ResponseRcode.WithLabelValues(zone, rcode).Inc()
} | [
"func",
"Report",
"(",
"req",
"request",
".",
"Request",
",",
"zone",
",",
"rcode",
"string",
",",
"size",
"int",
",",
"start",
"time",
".",
"Time",
")",
"{",
"// Proto and Family.",
"net",
":=",
"req",
".",
"Proto",
"(",
")",
"\n",
"fam",
":=",
"\"",
"\"",
"\n",
"if",
"req",
".",
"Family",
"(",
")",
"==",
"2",
"{",
"fam",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"typ",
":=",
"req",
".",
"QType",
"(",
")",
"\n\n",
"RequestCount",
".",
"WithLabelValues",
"(",
"zone",
",",
"net",
",",
"fam",
")",
".",
"Inc",
"(",
")",
"\n",
"RequestDuration",
".",
"WithLabelValues",
"(",
"zone",
")",
".",
"Observe",
"(",
"float64",
"(",
"time",
".",
"Since",
"(",
"start",
")",
"/",
"time",
".",
"Millisecond",
")",
")",
"\n\n",
"if",
"req",
".",
"Do",
"(",
")",
"{",
"RequestDo",
".",
"WithLabelValues",
"(",
"zone",
")",
".",
"Inc",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"known",
":=",
"monitorType",
"[",
"typ",
"]",
";",
"known",
"{",
"RequestType",
".",
"WithLabelValues",
"(",
"zone",
",",
"dns",
".",
"Type",
"(",
"typ",
")",
".",
"String",
"(",
")",
")",
".",
"Inc",
"(",
")",
"\n",
"}",
"else",
"{",
"RequestType",
".",
"WithLabelValues",
"(",
"zone",
",",
"other",
")",
".",
"Inc",
"(",
")",
"\n",
"}",
"\n\n",
"ResponseSize",
".",
"WithLabelValues",
"(",
"zone",
",",
"net",
")",
".",
"Observe",
"(",
"float64",
"(",
"size",
")",
")",
"\n",
"RequestSize",
".",
"WithLabelValues",
"(",
"zone",
",",
"net",
")",
".",
"Observe",
"(",
"float64",
"(",
"req",
".",
"Len",
"(",
")",
")",
")",
"\n\n",
"ResponseRcode",
".",
"WithLabelValues",
"(",
"zone",
",",
"rcode",
")",
".",
"Inc",
"(",
")",
"\n",
"}"
] | // Report reports the metrics data associcated with request. | [
"Report",
"reports",
"the",
"metrics",
"data",
"associcated",
"with",
"request",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/metrics/vars/report.go#L12-L39 | train |
inverse-inc/packetfence | go/caddy/api-aaa/api-aaa.go | setup | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
apiAAA, err := buildApiAAAHandler(ctx)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
apiAAA.Next = next
return apiAAA
})
return nil
} | go | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
apiAAA, err := buildApiAAAHandler(ctx)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
apiAAA.Next = next
return apiAAA
})
return nil
} | [
"func",
"setup",
"(",
"c",
"*",
"caddy",
".",
"Controller",
")",
"error",
"{",
"ctx",
":=",
"log",
".",
"LoggerNewContext",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n\n",
"apiAAA",
",",
"err",
":=",
"buildApiAAAHandler",
"(",
"ctx",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"httpserver",
".",
"GetConfig",
"(",
"c",
")",
".",
"AddMiddleware",
"(",
"func",
"(",
"next",
"httpserver",
".",
"Handler",
")",
"httpserver",
".",
"Handler",
"{",
"apiAAA",
".",
"Next",
"=",
"next",
"\n",
"return",
"apiAAA",
"\n",
"}",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup the api-aaa middleware
// Also loads the pfconfig resources and registers them in the pool | [
"Setup",
"the",
"api",
"-",
"aaa",
"middleware",
"Also",
"loads",
"the",
"pfconfig",
"resources",
"and",
"registers",
"them",
"in",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L50-L65 | train |
inverse-inc/packetfence | go/caddy/api-aaa/api-aaa.go | buildApiAAAHandler | func buildApiAAAHandler(ctx context.Context) (ApiAAAHandler, error) {
apiAAA := ApiAAAHandler{}
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.PfConf.Webservices)
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.UnifiedApiSystemUser)
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.AdminRoles)
tokenBackend := aaa.NewMemTokenBackend(15*time.Minute, 12*time.Hour)
apiAAA.authentication = aaa.NewTokenAuthenticationMiddleware(tokenBackend)
// Backend for the system Unified API user
if pfconfigdriver.Config.UnifiedApiSystemUser.User != "" {
apiAAA.systemBackend = aaa.NewMemAuthenticationBackend(
map[string]string{},
map[string]bool{"ALL": true},
)
apiAAA.systemBackend.SetUser(pfconfigdriver.Config.UnifiedApiSystemUser.User, pfconfigdriver.Config.UnifiedApiSystemUser.Pass)
apiAAA.authentication.AddAuthenticationBackend(apiAAA.systemBackend)
}
// Backend for the pf.conf webservices user
apiAAA.webservicesBackend = aaa.NewMemAuthenticationBackend(
map[string]string{},
map[string]bool{"ALL": true},
)
apiAAA.authentication.AddAuthenticationBackend(apiAAA.webservicesBackend)
if pfconfigdriver.Config.PfConf.Webservices.User != "" {
apiAAA.webservicesBackend.SetUser(pfconfigdriver.Config.PfConf.Webservices.User, pfconfigdriver.Config.PfConf.Webservices.Pass)
}
url, err := url.Parse("http://127.0.0.1:8080/api/v1/authentication/admin_authentication")
sharedutils.CheckError(err)
apiAAA.authentication.AddAuthenticationBackend(aaa.NewPfAuthenticationBackend(ctx, url, false))
apiAAA.authorization = aaa.NewTokenAuthorizationMiddleware(tokenBackend)
router := httprouter.New()
router.POST("/api/v1/login", apiAAA.handleLogin)
router.GET("/api/v1/token_info", apiAAA.handleTokenInfo)
apiAAA.router = router
return apiAAA, nil
} | go | func buildApiAAAHandler(ctx context.Context) (ApiAAAHandler, error) {
apiAAA := ApiAAAHandler{}
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.PfConf.Webservices)
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.UnifiedApiSystemUser)
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.AdminRoles)
tokenBackend := aaa.NewMemTokenBackend(15*time.Minute, 12*time.Hour)
apiAAA.authentication = aaa.NewTokenAuthenticationMiddleware(tokenBackend)
// Backend for the system Unified API user
if pfconfigdriver.Config.UnifiedApiSystemUser.User != "" {
apiAAA.systemBackend = aaa.NewMemAuthenticationBackend(
map[string]string{},
map[string]bool{"ALL": true},
)
apiAAA.systemBackend.SetUser(pfconfigdriver.Config.UnifiedApiSystemUser.User, pfconfigdriver.Config.UnifiedApiSystemUser.Pass)
apiAAA.authentication.AddAuthenticationBackend(apiAAA.systemBackend)
}
// Backend for the pf.conf webservices user
apiAAA.webservicesBackend = aaa.NewMemAuthenticationBackend(
map[string]string{},
map[string]bool{"ALL": true},
)
apiAAA.authentication.AddAuthenticationBackend(apiAAA.webservicesBackend)
if pfconfigdriver.Config.PfConf.Webservices.User != "" {
apiAAA.webservicesBackend.SetUser(pfconfigdriver.Config.PfConf.Webservices.User, pfconfigdriver.Config.PfConf.Webservices.Pass)
}
url, err := url.Parse("http://127.0.0.1:8080/api/v1/authentication/admin_authentication")
sharedutils.CheckError(err)
apiAAA.authentication.AddAuthenticationBackend(aaa.NewPfAuthenticationBackend(ctx, url, false))
apiAAA.authorization = aaa.NewTokenAuthorizationMiddleware(tokenBackend)
router := httprouter.New()
router.POST("/api/v1/login", apiAAA.handleLogin)
router.GET("/api/v1/token_info", apiAAA.handleTokenInfo)
apiAAA.router = router
return apiAAA, nil
} | [
"func",
"buildApiAAAHandler",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"ApiAAAHandler",
",",
"error",
")",
"{",
"apiAAA",
":=",
"ApiAAAHandler",
"{",
"}",
"\n\n",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddStruct",
"(",
"ctx",
",",
"&",
"pfconfigdriver",
".",
"Config",
".",
"PfConf",
".",
"Webservices",
")",
"\n",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddStruct",
"(",
"ctx",
",",
"&",
"pfconfigdriver",
".",
"Config",
".",
"UnifiedApiSystemUser",
")",
"\n",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddStruct",
"(",
"ctx",
",",
"&",
"pfconfigdriver",
".",
"Config",
".",
"AdminRoles",
")",
"\n\n",
"tokenBackend",
":=",
"aaa",
".",
"NewMemTokenBackend",
"(",
"15",
"*",
"time",
".",
"Minute",
",",
"12",
"*",
"time",
".",
"Hour",
")",
"\n",
"apiAAA",
".",
"authentication",
"=",
"aaa",
".",
"NewTokenAuthenticationMiddleware",
"(",
"tokenBackend",
")",
"\n\n",
"// Backend for the system Unified API user",
"if",
"pfconfigdriver",
".",
"Config",
".",
"UnifiedApiSystemUser",
".",
"User",
"!=",
"\"",
"\"",
"{",
"apiAAA",
".",
"systemBackend",
"=",
"aaa",
".",
"NewMemAuthenticationBackend",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"map",
"[",
"string",
"]",
"bool",
"{",
"\"",
"\"",
":",
"true",
"}",
",",
")",
"\n",
"apiAAA",
".",
"systemBackend",
".",
"SetUser",
"(",
"pfconfigdriver",
".",
"Config",
".",
"UnifiedApiSystemUser",
".",
"User",
",",
"pfconfigdriver",
".",
"Config",
".",
"UnifiedApiSystemUser",
".",
"Pass",
")",
"\n",
"apiAAA",
".",
"authentication",
".",
"AddAuthenticationBackend",
"(",
"apiAAA",
".",
"systemBackend",
")",
"\n",
"}",
"\n\n",
"// Backend for the pf.conf webservices user",
"apiAAA",
".",
"webservicesBackend",
"=",
"aaa",
".",
"NewMemAuthenticationBackend",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"map",
"[",
"string",
"]",
"bool",
"{",
"\"",
"\"",
":",
"true",
"}",
",",
")",
"\n",
"apiAAA",
".",
"authentication",
".",
"AddAuthenticationBackend",
"(",
"apiAAA",
".",
"webservicesBackend",
")",
"\n\n",
"if",
"pfconfigdriver",
".",
"Config",
".",
"PfConf",
".",
"Webservices",
".",
"User",
"!=",
"\"",
"\"",
"{",
"apiAAA",
".",
"webservicesBackend",
".",
"SetUser",
"(",
"pfconfigdriver",
".",
"Config",
".",
"PfConf",
".",
"Webservices",
".",
"User",
",",
"pfconfigdriver",
".",
"Config",
".",
"PfConf",
".",
"Webservices",
".",
"Pass",
")",
"\n",
"}",
"\n\n",
"url",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"\"",
"\"",
")",
"\n",
"sharedutils",
".",
"CheckError",
"(",
"err",
")",
"\n",
"apiAAA",
".",
"authentication",
".",
"AddAuthenticationBackend",
"(",
"aaa",
".",
"NewPfAuthenticationBackend",
"(",
"ctx",
",",
"url",
",",
"false",
")",
")",
"\n\n",
"apiAAA",
".",
"authorization",
"=",
"aaa",
".",
"NewTokenAuthorizationMiddleware",
"(",
"tokenBackend",
")",
"\n\n",
"router",
":=",
"httprouter",
".",
"New",
"(",
")",
"\n",
"router",
".",
"POST",
"(",
"\"",
"\"",
",",
"apiAAA",
".",
"handleLogin",
")",
"\n",
"router",
".",
"GET",
"(",
"\"",
"\"",
",",
"apiAAA",
".",
"handleTokenInfo",
")",
"\n\n",
"apiAAA",
".",
"router",
"=",
"router",
"\n\n",
"return",
"apiAAA",
",",
"nil",
"\n",
"}"
] | // Build the ApiAAAHandler which will initialize the cache and instantiate the router along with its routes | [
"Build",
"the",
"ApiAAAHandler",
"which",
"will",
"initialize",
"the",
"cache",
"and",
"instantiate",
"the",
"router",
"along",
"with",
"its",
"routes"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L68-L113 | train |
inverse-inc/packetfence | go/caddy/api-aaa/api-aaa.go | handleLogin | func (h ApiAAAHandler) handleLogin(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("api-aaa.login")
var loginParams struct {
Username string
Password string
}
err := json.NewDecoder(r.Body).Decode(&loginParams)
if err != nil {
msg := fmt.Sprintf("Error while decoding payload: %s", err)
log.LoggerWContext(ctx).Error(msg)
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
auth, token, err := h.authentication.Login(ctx, loginParams.Username, loginParams.Password)
if auth {
w.WriteHeader(http.StatusOK)
res, _ := json.Marshal(map[string]string{
"token": token,
})
fmt.Fprintf(w, string(res))
} else {
w.WriteHeader(http.StatusUnauthorized)
res, _ := json.Marshal(map[string]string{
"message": err.Error(),
})
fmt.Fprintf(w, string(res))
}
} | go | func (h ApiAAAHandler) handleLogin(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("api-aaa.login")
var loginParams struct {
Username string
Password string
}
err := json.NewDecoder(r.Body).Decode(&loginParams)
if err != nil {
msg := fmt.Sprintf("Error while decoding payload: %s", err)
log.LoggerWContext(ctx).Error(msg)
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
auth, token, err := h.authentication.Login(ctx, loginParams.Username, loginParams.Password)
if auth {
w.WriteHeader(http.StatusOK)
res, _ := json.Marshal(map[string]string{
"token": token,
})
fmt.Fprintf(w, string(res))
} else {
w.WriteHeader(http.StatusUnauthorized)
res, _ := json.Marshal(map[string]string{
"message": err.Error(),
})
fmt.Fprintf(w, string(res))
}
} | [
"func",
"(",
"h",
"ApiAAAHandler",
")",
"handleLogin",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"p",
"httprouter",
".",
"Params",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"defer",
"statsd",
".",
"NewStatsDTiming",
"(",
"ctx",
")",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n\n",
"var",
"loginParams",
"struct",
"{",
"Username",
"string",
"\n",
"Password",
"string",
"\n",
"}",
"\n\n",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"loginParams",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"msg",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"auth",
",",
"token",
",",
"err",
":=",
"h",
".",
"authentication",
".",
"Login",
"(",
"ctx",
",",
"loginParams",
".",
"Username",
",",
"loginParams",
".",
"Password",
")",
"\n\n",
"if",
"auth",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"res",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"token",
",",
"}",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"string",
"(",
"res",
")",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"res",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
",",
"}",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"string",
"(",
"res",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Handle an API login | [
"Handle",
"an",
"API",
"login"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L116-L149 | train |
inverse-inc/packetfence | go/caddy/api-aaa/api-aaa.go | handleTokenInfo | func (h ApiAAAHandler) handleTokenInfo(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("api-aaa.token_info")
info, expiration := h.authorization.GetTokenInfoFromBearerRequest(ctx, r)
if info != nil {
// We'll want to render the roles as an array, not as a map
prettyInfo := PrettyTokenInfo{
AdminActions: make([]string, len(info.AdminActions())),
AdminRoles: make([]string, len(info.AdminRoles)),
TenantId: info.TenantId,
Username: info.Username,
ExpiresAt: expiration,
}
i := 0
for r, _ := range info.AdminActions() {
prettyInfo.AdminActions[i] = r
i++
}
i = 0
for r, _ := range info.AdminRoles {
prettyInfo.AdminRoles[i] = r
i++
}
w.WriteHeader(http.StatusOK)
res, _ := json.Marshal(map[string]interface{}{
"item": prettyInfo,
})
fmt.Fprintf(w, string(res))
} else {
w.WriteHeader(http.StatusNotFound)
res, _ := json.Marshal(map[string]string{
"message": "Couldn't find any information for the current token. Either it is invalid or it has expired.",
})
fmt.Fprintf(w, string(res))
}
} | go | func (h ApiAAAHandler) handleTokenInfo(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("api-aaa.token_info")
info, expiration := h.authorization.GetTokenInfoFromBearerRequest(ctx, r)
if info != nil {
// We'll want to render the roles as an array, not as a map
prettyInfo := PrettyTokenInfo{
AdminActions: make([]string, len(info.AdminActions())),
AdminRoles: make([]string, len(info.AdminRoles)),
TenantId: info.TenantId,
Username: info.Username,
ExpiresAt: expiration,
}
i := 0
for r, _ := range info.AdminActions() {
prettyInfo.AdminActions[i] = r
i++
}
i = 0
for r, _ := range info.AdminRoles {
prettyInfo.AdminRoles[i] = r
i++
}
w.WriteHeader(http.StatusOK)
res, _ := json.Marshal(map[string]interface{}{
"item": prettyInfo,
})
fmt.Fprintf(w, string(res))
} else {
w.WriteHeader(http.StatusNotFound)
res, _ := json.Marshal(map[string]string{
"message": "Couldn't find any information for the current token. Either it is invalid or it has expired.",
})
fmt.Fprintf(w, string(res))
}
} | [
"func",
"(",
"h",
"ApiAAAHandler",
")",
"handleTokenInfo",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"p",
"httprouter",
".",
"Params",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"defer",
"statsd",
".",
"NewStatsDTiming",
"(",
"ctx",
")",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n\n",
"info",
",",
"expiration",
":=",
"h",
".",
"authorization",
".",
"GetTokenInfoFromBearerRequest",
"(",
"ctx",
",",
"r",
")",
"\n\n",
"if",
"info",
"!=",
"nil",
"{",
"// We'll want to render the roles as an array, not as a map",
"prettyInfo",
":=",
"PrettyTokenInfo",
"{",
"AdminActions",
":",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"info",
".",
"AdminActions",
"(",
")",
")",
")",
",",
"AdminRoles",
":",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"info",
".",
"AdminRoles",
")",
")",
",",
"TenantId",
":",
"info",
".",
"TenantId",
",",
"Username",
":",
"info",
".",
"Username",
",",
"ExpiresAt",
":",
"expiration",
",",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"for",
"r",
",",
"_",
":=",
"range",
"info",
".",
"AdminActions",
"(",
")",
"{",
"prettyInfo",
".",
"AdminActions",
"[",
"i",
"]",
"=",
"r",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"i",
"=",
"0",
"\n",
"for",
"r",
",",
"_",
":=",
"range",
"info",
".",
"AdminRoles",
"{",
"prettyInfo",
".",
"AdminRoles",
"[",
"i",
"]",
"=",
"r",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"res",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"prettyInfo",
",",
"}",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"string",
"(",
"res",
")",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"res",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"string",
"(",
"res",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Handle getting the token info | [
"Handle",
"getting",
"the",
"token",
"info"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L152-L192 | train |
inverse-inc/packetfence | go/coredns/core/dnsserver/server-grpc.go | NewServergRPC | func NewServergRPC(addr string, group []*Config) (*ServergRPC, error) {
s, err := NewServer(addr, group)
if err != nil {
return nil, err
}
gs := &ServergRPC{Server: s}
return gs, nil
} | go | func NewServergRPC(addr string, group []*Config) (*ServergRPC, error) {
s, err := NewServer(addr, group)
if err != nil {
return nil, err
}
gs := &ServergRPC{Server: s}
return gs, nil
} | [
"func",
"NewServergRPC",
"(",
"addr",
"string",
",",
"group",
"[",
"]",
"*",
"Config",
")",
"(",
"*",
"ServergRPC",
",",
"error",
")",
"{",
"s",
",",
"err",
":=",
"NewServer",
"(",
"addr",
",",
"group",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"gs",
":=",
"&",
"ServergRPC",
"{",
"Server",
":",
"s",
"}",
"\n",
"return",
"gs",
",",
"nil",
"\n",
"}"
] | // NewServergRPC returns a new CoreDNS GRPC server and compiles all plugin in to it. | [
"NewServergRPC",
"returns",
"a",
"new",
"CoreDNS",
"GRPC",
"server",
"and",
"compiles",
"all",
"plugin",
"in",
"to",
"it",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/server-grpc.go#L28-L36 | train |
inverse-inc/packetfence | go/coredns/core/dnsserver/server-grpc.go | Query | func (s *ServergRPC) Query(ctx context.Context, in *pb.DnsPacket) (*pb.DnsPacket, error) {
msg := new(dns.Msg)
err := msg.Unpack(in.Msg)
if err != nil {
return nil, err
}
p, ok := peer.FromContext(ctx)
if !ok {
return nil, errors.New("no peer in gRPC context")
}
a, ok := p.Addr.(*net.TCPAddr)
if !ok {
return nil, fmt.Errorf("no TCP peer in gRPC context: %v", p.Addr)
}
r := &net.IPAddr{IP: a.IP}
w := &gRPCresponse{localAddr: s.listenAddr, remoteAddr: r, Msg: msg}
s.ServeDNS(ctx, w, msg)
packed, err := w.Msg.Pack()
if err != nil {
return nil, err
}
return &pb.DnsPacket{Msg: packed}, nil
} | go | func (s *ServergRPC) Query(ctx context.Context, in *pb.DnsPacket) (*pb.DnsPacket, error) {
msg := new(dns.Msg)
err := msg.Unpack(in.Msg)
if err != nil {
return nil, err
}
p, ok := peer.FromContext(ctx)
if !ok {
return nil, errors.New("no peer in gRPC context")
}
a, ok := p.Addr.(*net.TCPAddr)
if !ok {
return nil, fmt.Errorf("no TCP peer in gRPC context: %v", p.Addr)
}
r := &net.IPAddr{IP: a.IP}
w := &gRPCresponse{localAddr: s.listenAddr, remoteAddr: r, Msg: msg}
s.ServeDNS(ctx, w, msg)
packed, err := w.Msg.Pack()
if err != nil {
return nil, err
}
return &pb.DnsPacket{Msg: packed}, nil
} | [
"func",
"(",
"s",
"*",
"ServergRPC",
")",
"Query",
"(",
"ctx",
"context",
".",
"Context",
",",
"in",
"*",
"pb",
".",
"DnsPacket",
")",
"(",
"*",
"pb",
".",
"DnsPacket",
",",
"error",
")",
"{",
"msg",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"err",
":=",
"msg",
".",
"Unpack",
"(",
"in",
".",
"Msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"p",
",",
"ok",
":=",
"peer",
".",
"FromContext",
"(",
"ctx",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"a",
",",
"ok",
":=",
"p",
".",
"Addr",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"Addr",
")",
"\n",
"}",
"\n\n",
"r",
":=",
"&",
"net",
".",
"IPAddr",
"{",
"IP",
":",
"a",
".",
"IP",
"}",
"\n",
"w",
":=",
"&",
"gRPCresponse",
"{",
"localAddr",
":",
"s",
".",
"listenAddr",
",",
"remoteAddr",
":",
"r",
",",
"Msg",
":",
"msg",
"}",
"\n\n",
"s",
".",
"ServeDNS",
"(",
"ctx",
",",
"w",
",",
"msg",
")",
"\n\n",
"packed",
",",
"err",
":=",
"w",
".",
"Msg",
".",
"Pack",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"pb",
".",
"DnsPacket",
"{",
"Msg",
":",
"packed",
"}",
",",
"nil",
"\n",
"}"
] | // Query is the main entry-point into the gRPC server. From here we call ServeDNS like
// any normal server. We use a custom responseWriter to pick up the bytes we need to write
// back to the client as a protobuf. | [
"Query",
"is",
"the",
"main",
"entry",
"-",
"point",
"into",
"the",
"gRPC",
"server",
".",
"From",
"here",
"we",
"call",
"ServeDNS",
"like",
"any",
"normal",
"server",
".",
"We",
"use",
"a",
"custom",
"responseWriter",
"to",
"pick",
"up",
"the",
"bytes",
"we",
"need",
"to",
"write",
"back",
"to",
"the",
"client",
"as",
"a",
"protobuf",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/server-grpc.go#L119-L147 | train |
inverse-inc/packetfence | go/coredns/core/dnsserver/server.go | DefaultErrorFunc | func DefaultErrorFunc(w dns.ResponseWriter, r *dns.Msg, rc int) {
state := request.Request{W: w, Req: r}
answer := new(dns.Msg)
answer.SetRcode(r, rc)
state.SizeAndDo(answer)
vars.Report(state, vars.Dropped, rcode.ToString(rc), answer.Len(), time.Now())
w.WriteMsg(answer)
} | go | func DefaultErrorFunc(w dns.ResponseWriter, r *dns.Msg, rc int) {
state := request.Request{W: w, Req: r}
answer := new(dns.Msg)
answer.SetRcode(r, rc)
state.SizeAndDo(answer)
vars.Report(state, vars.Dropped, rcode.ToString(rc), answer.Len(), time.Now())
w.WriteMsg(answer)
} | [
"func",
"DefaultErrorFunc",
"(",
"w",
"dns",
".",
"ResponseWriter",
",",
"r",
"*",
"dns",
".",
"Msg",
",",
"rc",
"int",
")",
"{",
"state",
":=",
"request",
".",
"Request",
"{",
"W",
":",
"w",
",",
"Req",
":",
"r",
"}",
"\n\n",
"answer",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"answer",
".",
"SetRcode",
"(",
"r",
",",
"rc",
")",
"\n\n",
"state",
".",
"SizeAndDo",
"(",
"answer",
")",
"\n\n",
"vars",
".",
"Report",
"(",
"state",
",",
"vars",
".",
"Dropped",
",",
"rcode",
".",
"ToString",
"(",
"rc",
")",
",",
"answer",
".",
"Len",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"w",
".",
"WriteMsg",
"(",
"answer",
")",
"\n",
"}"
] | // DefaultErrorFunc responds to an DNS request with an error. | [
"DefaultErrorFunc",
"responds",
"to",
"an",
"DNS",
"request",
"with",
"an",
"error",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/server.go#L304-L315 | train |
inverse-inc/packetfence | go/coredns/plugin/file/reload.go | Reload | func (z *Zone) Reload() error {
if z.NoReload {
return nil
}
tick := time.NewTicker(TickTime)
go func() {
for {
select {
case <-tick.C:
reader, err := os.Open(z.file)
if err != nil {
log.Printf("[ERROR] Failed to open zone %q in %q: %v", z.origin, z.file, err)
continue
}
serial := z.SOASerialIfDefined()
zone, err := Parse(reader, z.origin, z.file, serial)
if err != nil {
if _, ok := err.(*serialErr); !ok {
log.Printf("[ERROR] Parsing zone %q: %v", z.origin, err)
}
continue
}
// copy elements we need
z.reloadMu.Lock()
z.Apex = zone.Apex
z.Tree = zone.Tree
z.reloadMu.Unlock()
log.Printf("[INFO] Successfully reloaded zone %q in %q with serial %d", z.origin, z.file, z.Apex.SOA.Serial)
z.Notify()
case <-z.ReloadShutdown:
tick.Stop()
return
}
}
}()
return nil
} | go | func (z *Zone) Reload() error {
if z.NoReload {
return nil
}
tick := time.NewTicker(TickTime)
go func() {
for {
select {
case <-tick.C:
reader, err := os.Open(z.file)
if err != nil {
log.Printf("[ERROR] Failed to open zone %q in %q: %v", z.origin, z.file, err)
continue
}
serial := z.SOASerialIfDefined()
zone, err := Parse(reader, z.origin, z.file, serial)
if err != nil {
if _, ok := err.(*serialErr); !ok {
log.Printf("[ERROR] Parsing zone %q: %v", z.origin, err)
}
continue
}
// copy elements we need
z.reloadMu.Lock()
z.Apex = zone.Apex
z.Tree = zone.Tree
z.reloadMu.Unlock()
log.Printf("[INFO] Successfully reloaded zone %q in %q with serial %d", z.origin, z.file, z.Apex.SOA.Serial)
z.Notify()
case <-z.ReloadShutdown:
tick.Stop()
return
}
}
}()
return nil
} | [
"func",
"(",
"z",
"*",
"Zone",
")",
"Reload",
"(",
")",
"error",
"{",
"if",
"z",
".",
"NoReload",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"tick",
":=",
"time",
".",
"NewTicker",
"(",
"TickTime",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"tick",
".",
"C",
":",
"reader",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"z",
".",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"z",
".",
"origin",
",",
"z",
".",
"file",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"serial",
":=",
"z",
".",
"SOASerialIfDefined",
"(",
")",
"\n",
"zone",
",",
"err",
":=",
"Parse",
"(",
"reader",
",",
"z",
".",
"origin",
",",
"z",
".",
"file",
",",
"serial",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"serialErr",
")",
";",
"!",
"ok",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"z",
".",
"origin",
",",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// copy elements we need",
"z",
".",
"reloadMu",
".",
"Lock",
"(",
")",
"\n",
"z",
".",
"Apex",
"=",
"zone",
".",
"Apex",
"\n",
"z",
".",
"Tree",
"=",
"zone",
".",
"Tree",
"\n",
"z",
".",
"reloadMu",
".",
"Unlock",
"(",
")",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"z",
".",
"origin",
",",
"z",
".",
"file",
",",
"z",
".",
"Apex",
".",
"SOA",
".",
"Serial",
")",
"\n",
"z",
".",
"Notify",
"(",
")",
"\n\n",
"case",
"<-",
"z",
".",
"ReloadShutdown",
":",
"tick",
".",
"Stop",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Reload reloads a zone when it is changed on disk. If z.NoRoload is true, no reloading will be done. | [
"Reload",
"reloads",
"a",
"zone",
"when",
"it",
"is",
"changed",
"on",
"disk",
".",
"If",
"z",
".",
"NoRoload",
"is",
"true",
"no",
"reloading",
"will",
"be",
"done",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/file/reload.go#L13-L57 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/proxy/upstream.go | NewStaticUpstreams | func NewStaticUpstreams(c caddyfile.Dispenser) ([]Upstream, error) {
var upstreams []Upstream
for c.Next() {
upstream := &staticUpstream{
from: "",
upstreamHeaders: make(http.Header),
downstreamHeaders: make(http.Header),
Hosts: nil,
Policy: &Random{},
MaxFails: 1,
TryInterval: 250 * time.Millisecond,
MaxConns: 0,
KeepAlive: http.DefaultMaxIdleConnsPerHost,
Timeout: 30 * time.Second,
}
if !c.Args(&upstream.from) {
return upstreams, c.ArgErr()
}
var to []string
for _, t := range c.RemainingArgs() {
parsed, err := parseUpstream(t)
if err != nil {
return upstreams, err
}
to = append(to, parsed...)
}
for c.NextBlock() {
switch c.Val() {
case "upstream":
if !c.NextArg() {
return upstreams, c.ArgErr()
}
parsed, err := parseUpstream(c.Val())
if err != nil {
return upstreams, err
}
to = append(to, parsed...)
default:
if err := parseBlock(&c, upstream); err != nil {
return upstreams, err
}
}
}
if len(to) == 0 {
return upstreams, c.ArgErr()
}
upstream.Hosts = make([]*UpstreamHost, len(to))
for i, host := range to {
uh, err := upstream.NewHost(host)
if err != nil {
return upstreams, err
}
upstream.Hosts[i] = uh
}
if upstream.HealthCheck.Path != "" {
upstream.HealthCheck.Client = http.Client{
Timeout: upstream.HealthCheck.Timeout,
}
go upstream.HealthCheckWorker(nil)
}
upstreams = append(upstreams, upstream)
}
return upstreams, nil
} | go | func NewStaticUpstreams(c caddyfile.Dispenser) ([]Upstream, error) {
var upstreams []Upstream
for c.Next() {
upstream := &staticUpstream{
from: "",
upstreamHeaders: make(http.Header),
downstreamHeaders: make(http.Header),
Hosts: nil,
Policy: &Random{},
MaxFails: 1,
TryInterval: 250 * time.Millisecond,
MaxConns: 0,
KeepAlive: http.DefaultMaxIdleConnsPerHost,
Timeout: 30 * time.Second,
}
if !c.Args(&upstream.from) {
return upstreams, c.ArgErr()
}
var to []string
for _, t := range c.RemainingArgs() {
parsed, err := parseUpstream(t)
if err != nil {
return upstreams, err
}
to = append(to, parsed...)
}
for c.NextBlock() {
switch c.Val() {
case "upstream":
if !c.NextArg() {
return upstreams, c.ArgErr()
}
parsed, err := parseUpstream(c.Val())
if err != nil {
return upstreams, err
}
to = append(to, parsed...)
default:
if err := parseBlock(&c, upstream); err != nil {
return upstreams, err
}
}
}
if len(to) == 0 {
return upstreams, c.ArgErr()
}
upstream.Hosts = make([]*UpstreamHost, len(to))
for i, host := range to {
uh, err := upstream.NewHost(host)
if err != nil {
return upstreams, err
}
upstream.Hosts[i] = uh
}
if upstream.HealthCheck.Path != "" {
upstream.HealthCheck.Client = http.Client{
Timeout: upstream.HealthCheck.Timeout,
}
go upstream.HealthCheckWorker(nil)
}
upstreams = append(upstreams, upstream)
}
return upstreams, nil
} | [
"func",
"NewStaticUpstreams",
"(",
"c",
"caddyfile",
".",
"Dispenser",
")",
"(",
"[",
"]",
"Upstream",
",",
"error",
")",
"{",
"var",
"upstreams",
"[",
"]",
"Upstream",
"\n",
"for",
"c",
".",
"Next",
"(",
")",
"{",
"upstream",
":=",
"&",
"staticUpstream",
"{",
"from",
":",
"\"",
"\"",
",",
"upstreamHeaders",
":",
"make",
"(",
"http",
".",
"Header",
")",
",",
"downstreamHeaders",
":",
"make",
"(",
"http",
".",
"Header",
")",
",",
"Hosts",
":",
"nil",
",",
"Policy",
":",
"&",
"Random",
"{",
"}",
",",
"MaxFails",
":",
"1",
",",
"TryInterval",
":",
"250",
"*",
"time",
".",
"Millisecond",
",",
"MaxConns",
":",
"0",
",",
"KeepAlive",
":",
"http",
".",
"DefaultMaxIdleConnsPerHost",
",",
"Timeout",
":",
"30",
"*",
"time",
".",
"Second",
",",
"}",
"\n\n",
"if",
"!",
"c",
".",
"Args",
"(",
"&",
"upstream",
".",
"from",
")",
"{",
"return",
"upstreams",
",",
"c",
".",
"ArgErr",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"to",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"c",
".",
"RemainingArgs",
"(",
")",
"{",
"parsed",
",",
"err",
":=",
"parseUpstream",
"(",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"upstreams",
",",
"err",
"\n",
"}",
"\n",
"to",
"=",
"append",
"(",
"to",
",",
"parsed",
"...",
")",
"\n",
"}",
"\n\n",
"for",
"c",
".",
"NextBlock",
"(",
")",
"{",
"switch",
"c",
".",
"Val",
"(",
")",
"{",
"case",
"\"",
"\"",
":",
"if",
"!",
"c",
".",
"NextArg",
"(",
")",
"{",
"return",
"upstreams",
",",
"c",
".",
"ArgErr",
"(",
")",
"\n",
"}",
"\n",
"parsed",
",",
"err",
":=",
"parseUpstream",
"(",
"c",
".",
"Val",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"upstreams",
",",
"err",
"\n",
"}",
"\n",
"to",
"=",
"append",
"(",
"to",
",",
"parsed",
"...",
")",
"\n",
"default",
":",
"if",
"err",
":=",
"parseBlock",
"(",
"&",
"c",
",",
"upstream",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"upstreams",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"to",
")",
"==",
"0",
"{",
"return",
"upstreams",
",",
"c",
".",
"ArgErr",
"(",
")",
"\n",
"}",
"\n\n",
"upstream",
".",
"Hosts",
"=",
"make",
"(",
"[",
"]",
"*",
"UpstreamHost",
",",
"len",
"(",
"to",
")",
")",
"\n",
"for",
"i",
",",
"host",
":=",
"range",
"to",
"{",
"uh",
",",
"err",
":=",
"upstream",
".",
"NewHost",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"upstreams",
",",
"err",
"\n",
"}",
"\n",
"upstream",
".",
"Hosts",
"[",
"i",
"]",
"=",
"uh",
"\n",
"}",
"\n\n",
"if",
"upstream",
".",
"HealthCheck",
".",
"Path",
"!=",
"\"",
"\"",
"{",
"upstream",
".",
"HealthCheck",
".",
"Client",
"=",
"http",
".",
"Client",
"{",
"Timeout",
":",
"upstream",
".",
"HealthCheck",
".",
"Timeout",
",",
"}",
"\n",
"go",
"upstream",
".",
"HealthCheckWorker",
"(",
"nil",
")",
"\n",
"}",
"\n",
"upstreams",
"=",
"append",
"(",
"upstreams",
",",
"upstream",
")",
"\n",
"}",
"\n",
"return",
"upstreams",
",",
"nil",
"\n",
"}"
] | // NewStaticUpstreams parses the configuration input and sets up
// static upstreams for the proxy middleware. | [
"NewStaticUpstreams",
"parses",
"the",
"configuration",
"input",
"and",
"sets",
"up",
"static",
"upstreams",
"for",
"the",
"proxy",
"middleware",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/proxy/upstream.go#L48-L117 | train |
inverse-inc/packetfence | go/coredns/plugin/pfdns/pfdns.go | WebservicesInit | func (pf *pfdns) WebservicesInit() error {
var ctx = context.Background()
var webservices pfconfigdriver.PfConfWebservices
webservices.PfconfigNS = "config::Pf"
webservices.PfconfigMethod = "hash_element"
webservices.PfconfigHashNS = "webservices"
pfconfigdriver.FetchDecodeSocket(ctx, &webservices)
pf.Webservices = webservices
return nil
} | go | func (pf *pfdns) WebservicesInit() error {
var ctx = context.Background()
var webservices pfconfigdriver.PfConfWebservices
webservices.PfconfigNS = "config::Pf"
webservices.PfconfigMethod = "hash_element"
webservices.PfconfigHashNS = "webservices"
pfconfigdriver.FetchDecodeSocket(ctx, &webservices)
pf.Webservices = webservices
return nil
} | [
"func",
"(",
"pf",
"*",
"pfdns",
")",
"WebservicesInit",
"(",
")",
"error",
"{",
"var",
"ctx",
"=",
"context",
".",
"Background",
"(",
")",
"\n",
"var",
"webservices",
"pfconfigdriver",
".",
"PfConfWebservices",
"\n",
"webservices",
".",
"PfconfigNS",
"=",
"\"",
"\"",
"\n",
"webservices",
".",
"PfconfigMethod",
"=",
"\"",
"\"",
"\n",
"webservices",
".",
"PfconfigHashNS",
"=",
"\"",
"\"",
"\n\n",
"pfconfigdriver",
".",
"FetchDecodeSocket",
"(",
"ctx",
",",
"&",
"webservices",
")",
"\n",
"pf",
".",
"Webservices",
"=",
"webservices",
"\n",
"return",
"nil",
"\n\n",
"}"
] | // WebservicesInit read pfconfig webservices configuration | [
"WebservicesInit",
"read",
"pfconfig",
"webservices",
"configuration"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pfdns/pfdns.go#L509-L520 | train |
inverse-inc/packetfence | go/coredns/plugin/pfdns/pfdns.go | addDetectionMechanismsToList | func (pf *pfdns) addDetectionMechanismsToList(ctx context.Context, r string) error {
rgx, err := regexp.Compile(r)
if err == nil {
pf.mutex.Lock()
pf.detectionMechanisms = append(pf.detectionMechanisms, rgx)
pf.mutex.Unlock()
} else {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to compile the regexp %s", err))
}
return err
} | go | func (pf *pfdns) addDetectionMechanismsToList(ctx context.Context, r string) error {
rgx, err := regexp.Compile(r)
if err == nil {
pf.mutex.Lock()
pf.detectionMechanisms = append(pf.detectionMechanisms, rgx)
pf.mutex.Unlock()
} else {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to compile the regexp %s", err))
}
return err
} | [
"func",
"(",
"pf",
"*",
"pfdns",
")",
"addDetectionMechanismsToList",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"string",
")",
"error",
"{",
"rgx",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"r",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"pf",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"pf",
".",
"detectionMechanisms",
"=",
"append",
"(",
"pf",
".",
"detectionMechanisms",
",",
"rgx",
")",
"\n",
"pf",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // addDetectionMechanismsToList add all detection mechanisms in a list | [
"addDetectionMechanismsToList",
"add",
"all",
"detection",
"mechanisms",
"in",
"a",
"list"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pfdns/pfdns.go#L736-L746 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/user.go | newUser | func newUser(email string) (User, error) {
user := User{Email: email}
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return user, errors.New("error generating private key: " + err.Error())
}
user.key = privateKey
return user, nil
} | go | func newUser(email string) (User, error) {
user := User{Email: email}
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return user, errors.New("error generating private key: " + err.Error())
}
user.key = privateKey
return user, nil
} | [
"func",
"newUser",
"(",
"email",
"string",
")",
"(",
"User",
",",
"error",
")",
"{",
"user",
":=",
"User",
"{",
"Email",
":",
"email",
"}",
"\n",
"privateKey",
",",
"err",
":=",
"ecdsa",
".",
"GenerateKey",
"(",
"elliptic",
".",
"P384",
"(",
")",
",",
"rand",
".",
"Reader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"user",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"user",
".",
"key",
"=",
"privateKey",
"\n",
"return",
"user",
",",
"nil",
"\n",
"}"
] | // newUser creates a new User for the given email address
// with a new private key. This function does NOT save the
// user to disk or register it via ACME. If you want to use
// a user account that might already exist, call getUser
// instead. It does NOT prompt the user. | [
"newUser",
"creates",
"a",
"new",
"User",
"for",
"the",
"given",
"email",
"address",
"with",
"a",
"new",
"private",
"key",
".",
"This",
"function",
"does",
"NOT",
"save",
"the",
"user",
"to",
"disk",
"or",
"register",
"it",
"via",
"ACME",
".",
"If",
"you",
"want",
"to",
"use",
"a",
"user",
"account",
"that",
"might",
"already",
"exist",
"call",
"getUser",
"instead",
".",
"It",
"does",
"NOT",
"prompt",
"the",
"user",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L46-L54 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/user.go | getUser | func getUser(storage Storage, email string) (User, error) {
var user User
// open user reg
userData, err := storage.LoadUser(email)
if err != nil {
if _, ok := err.(ErrNotExist); ok {
// create a new user
return newUser(email)
}
return user, err
}
// load user information
err = json.Unmarshal(userData.Reg, &user)
if err != nil {
return user, err
}
// load their private key
user.key, err = loadPrivateKey(userData.Key)
return user, err
} | go | func getUser(storage Storage, email string) (User, error) {
var user User
// open user reg
userData, err := storage.LoadUser(email)
if err != nil {
if _, ok := err.(ErrNotExist); ok {
// create a new user
return newUser(email)
}
return user, err
}
// load user information
err = json.Unmarshal(userData.Reg, &user)
if err != nil {
return user, err
}
// load their private key
user.key, err = loadPrivateKey(userData.Key)
return user, err
} | [
"func",
"getUser",
"(",
"storage",
"Storage",
",",
"email",
"string",
")",
"(",
"User",
",",
"error",
")",
"{",
"var",
"user",
"User",
"\n\n",
"// open user reg",
"userData",
",",
"err",
":=",
"storage",
".",
"LoadUser",
"(",
"email",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"ErrNotExist",
")",
";",
"ok",
"{",
"// create a new user",
"return",
"newUser",
"(",
"email",
")",
"\n",
"}",
"\n",
"return",
"user",
",",
"err",
"\n",
"}",
"\n\n",
"// load user information",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"userData",
".",
"Reg",
",",
"&",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"user",
",",
"err",
"\n",
"}",
"\n\n",
"// load their private key",
"user",
".",
"key",
",",
"err",
"=",
"loadPrivateKey",
"(",
"userData",
".",
"Key",
")",
"\n",
"return",
"user",
",",
"err",
"\n",
"}"
] | // getUser loads the user with the given email from disk
// using the provided storage. If the user does not exist,
// it will create a new one, but it does NOT save new
// users to the disk or register them via ACME. It does
// NOT prompt the user. | [
"getUser",
"loads",
"the",
"user",
"with",
"the",
"given",
"email",
"from",
"disk",
"using",
"the",
"provided",
"storage",
".",
"If",
"the",
"user",
"does",
"not",
"exist",
"it",
"will",
"create",
"a",
"new",
"one",
"but",
"it",
"does",
"NOT",
"save",
"new",
"users",
"to",
"the",
"disk",
"or",
"register",
"them",
"via",
"ACME",
".",
"It",
"does",
"NOT",
"prompt",
"the",
"user",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L100-L122 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/user.go | saveUser | func saveUser(storage Storage, user User) error {
// Save the private key and registration
userData := new(UserData)
var err error
userData.Key, err = savePrivateKey(user.key)
if err == nil {
userData.Reg, err = json.MarshalIndent(&user, "", "\t")
}
if err == nil {
err = storage.StoreUser(user.Email, userData)
}
return err
} | go | func saveUser(storage Storage, user User) error {
// Save the private key and registration
userData := new(UserData)
var err error
userData.Key, err = savePrivateKey(user.key)
if err == nil {
userData.Reg, err = json.MarshalIndent(&user, "", "\t")
}
if err == nil {
err = storage.StoreUser(user.Email, userData)
}
return err
} | [
"func",
"saveUser",
"(",
"storage",
"Storage",
",",
"user",
"User",
")",
"error",
"{",
"// Save the private key and registration",
"userData",
":=",
"new",
"(",
"UserData",
")",
"\n",
"var",
"err",
"error",
"\n",
"userData",
".",
"Key",
",",
"err",
"=",
"savePrivateKey",
"(",
"user",
".",
"key",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"userData",
".",
"Reg",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"&",
"user",
",",
"\"",
"\"",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"storage",
".",
"StoreUser",
"(",
"user",
".",
"Email",
",",
"userData",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // saveUser persists a user's key and account registration
// to the file system. It does NOT register the user via ACME
// or prompt the user. You must also pass in the storage
// wherein the user should be saved. It should be the storage
// for the CA with which user has an account. | [
"saveUser",
"persists",
"a",
"user",
"s",
"key",
"and",
"account",
"registration",
"to",
"the",
"file",
"system",
".",
"It",
"does",
"NOT",
"register",
"the",
"user",
"via",
"ACME",
"or",
"prompt",
"the",
"user",
".",
"You",
"must",
"also",
"pass",
"in",
"the",
"storage",
"wherein",
"the",
"user",
"should",
"be",
"saved",
".",
"It",
"should",
"be",
"the",
"storage",
"for",
"the",
"CA",
"with",
"which",
"user",
"has",
"an",
"account",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L129-L141 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/user.go | promptUserAgreement | func promptUserAgreement(agreementURL string, changed bool) bool {
if changed {
fmt.Printf("The Let's Encrypt Subscriber Agreement has changed:\n %s\n", agreementURL)
fmt.Print("Do you agree to the new terms? (y/n): ")
} else {
fmt.Printf("To continue, you must agree to the Let's Encrypt Subscriber Agreement:\n %s\n", agreementURL)
fmt.Print("Do you agree to the terms? (y/n): ")
}
reader := bufio.NewReader(stdin)
answer, err := reader.ReadString('\n')
if err != nil {
return false
}
answer = strings.ToLower(strings.TrimSpace(answer))
return answer == "y" || answer == "yes"
} | go | func promptUserAgreement(agreementURL string, changed bool) bool {
if changed {
fmt.Printf("The Let's Encrypt Subscriber Agreement has changed:\n %s\n", agreementURL)
fmt.Print("Do you agree to the new terms? (y/n): ")
} else {
fmt.Printf("To continue, you must agree to the Let's Encrypt Subscriber Agreement:\n %s\n", agreementURL)
fmt.Print("Do you agree to the terms? (y/n): ")
}
reader := bufio.NewReader(stdin)
answer, err := reader.ReadString('\n')
if err != nil {
return false
}
answer = strings.ToLower(strings.TrimSpace(answer))
return answer == "y" || answer == "yes"
} | [
"func",
"promptUserAgreement",
"(",
"agreementURL",
"string",
",",
"changed",
"bool",
")",
"bool",
"{",
"if",
"changed",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"agreementURL",
")",
"\n",
"fmt",
".",
"Print",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"agreementURL",
")",
"\n",
"fmt",
".",
"Print",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"reader",
":=",
"bufio",
".",
"NewReader",
"(",
"stdin",
")",
"\n",
"answer",
",",
"err",
":=",
"reader",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"answer",
"=",
"strings",
".",
"ToLower",
"(",
"strings",
".",
"TrimSpace",
"(",
"answer",
")",
")",
"\n\n",
"return",
"answer",
"==",
"\"",
"\"",
"||",
"answer",
"==",
"\"",
"\"",
"\n",
"}"
] | // promptUserAgreement prompts the user to agree to the agreement
// at agreementURL via stdin. If the agreement has changed, then pass
// true as the second argument. If this is the user's first time
// agreeing, pass false. It returns whether the user agreed or not. | [
"promptUserAgreement",
"prompts",
"the",
"user",
"to",
"agree",
"to",
"the",
"agreement",
"at",
"agreementURL",
"via",
"stdin",
".",
"If",
"the",
"agreement",
"has",
"changed",
"then",
"pass",
"true",
"as",
"the",
"second",
"argument",
".",
"If",
"this",
"is",
"the",
"user",
"s",
"first",
"time",
"agreeing",
"pass",
"false",
".",
"It",
"returns",
"whether",
"the",
"user",
"agreed",
"or",
"not",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L147-L164 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/out/socket.go | NewSocket | func NewSocket(path string) (s *Socket, err error) {
s = &Socket{path: path}
if err = openSocket(s); err != nil {
err = fmt.Errorf("open socket: %s", err)
s.err = err
return
}
return
} | go | func NewSocket(path string) (s *Socket, err error) {
s = &Socket{path: path}
if err = openSocket(s); err != nil {
err = fmt.Errorf("open socket: %s", err)
s.err = err
return
}
return
} | [
"func",
"NewSocket",
"(",
"path",
"string",
")",
"(",
"s",
"*",
"Socket",
",",
"err",
"error",
")",
"{",
"s",
"=",
"&",
"Socket",
"{",
"path",
":",
"path",
"}",
"\n",
"if",
"err",
"=",
"openSocket",
"(",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"s",
".",
"err",
"=",
"err",
"\n",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewSocket will always return a new Socket.
// err if nothing is listening to it, it will attempt to reconnect on the next Write. | [
"NewSocket",
"will",
"always",
"return",
"a",
"new",
"Socket",
".",
"err",
"if",
"nothing",
"is",
"listening",
"to",
"it",
"it",
"will",
"attempt",
"to",
"reconnect",
"on",
"the",
"next",
"Write",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/out/socket.go#L40-L48 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/out/socket.go | Close | func (s *Socket) Close() error {
if s.err != nil {
// nothing to close
return nil
}
defer s.conn.Close()
if err := s.enc.Flush(); err != nil {
return fmt.Errorf("flush: %s", err)
}
return s.enc.Close()
} | go | func (s *Socket) Close() error {
if s.err != nil {
// nothing to close
return nil
}
defer s.conn.Close()
if err := s.enc.Flush(); err != nil {
return fmt.Errorf("flush: %s", err)
}
return s.enc.Close()
} | [
"func",
"(",
"s",
"*",
"Socket",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"s",
".",
"err",
"!=",
"nil",
"{",
"// nothing to close",
"return",
"nil",
"\n",
"}",
"\n\n",
"defer",
"s",
".",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"if",
"err",
":=",
"s",
".",
"enc",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"enc",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close the socket and flush the remaining frames. | [
"Close",
"the",
"socket",
"and",
"flush",
"the",
"remaining",
"frames",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/out/socket.go#L70-L82 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/fastcgi/fcgiclient.go | DialTimeout | func DialTimeout(network string, address string, timeout time.Duration) (fcgi *FCGIClient, err error) {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return
}
fcgi = &FCGIClient{conn: conn, keepAlive: false, reqID: 1}
return fcgi, nil
} | go | func DialTimeout(network string, address string, timeout time.Duration) (fcgi *FCGIClient, err error) {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return
}
fcgi = &FCGIClient{conn: conn, keepAlive: false, reqID: 1}
return fcgi, nil
} | [
"func",
"DialTimeout",
"(",
"network",
"string",
",",
"address",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"fcgi",
"*",
"FCGIClient",
",",
"err",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(",
"network",
",",
"address",
",",
"timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"fcgi",
"=",
"&",
"FCGIClient",
"{",
"conn",
":",
"conn",
",",
"keepAlive",
":",
"false",
",",
"reqID",
":",
"1",
"}",
"\n\n",
"return",
"fcgi",
",",
"nil",
"\n",
"}"
] | // DialTimeout connects to the fcgi responder at the specified network address, using default net.Dialer.
// See func net.Dial for a description of the network and address parameters. | [
"DialTimeout",
"connects",
"to",
"the",
"fcgi",
"responder",
"at",
"the",
"specified",
"network",
"address",
"using",
"default",
"net",
".",
"Dialer",
".",
"See",
"func",
"net",
".",
"Dial",
"for",
"a",
"description",
"of",
"the",
"network",
"and",
"address",
"parameters",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/fastcgi/fcgiclient.go#L188-L197 | train |
inverse-inc/packetfence | go/requesthistory/request_history.go | UuidIndex | func (rh *RequestHistory) UuidIndex(uuid string) int {
rh.lock.RLock()
defer rh.lock.RUnlock()
return rh.uuidIndexNoLock(uuid)
} | go | func (rh *RequestHistory) UuidIndex(uuid string) int {
rh.lock.RLock()
defer rh.lock.RUnlock()
return rh.uuidIndexNoLock(uuid)
} | [
"func",
"(",
"rh",
"*",
"RequestHistory",
")",
"UuidIndex",
"(",
"uuid",
"string",
")",
"int",
"{",
"rh",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"rh",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"rh",
".",
"uuidIndexNoLock",
"(",
"uuid",
")",
"\n",
"}"
] | // Returns the index at which to find the request for the UUID
// Returns -1 if the UUID is unknown | [
"Returns",
"the",
"index",
"at",
"which",
"to",
"find",
"the",
"request",
"for",
"the",
"UUID",
"Returns",
"-",
"1",
"if",
"the",
"UUID",
"is",
"unknown"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/requesthistory/request_history.go#L74-L79 | train |
inverse-inc/packetfence | go/dhcp/utils.go | connectDB | func connectDB(configDatabase pfconfigdriver.PfConfDatabase) {
db, err := db.DbFromConfig(ctx)
sharedutils.CheckError(err)
MySQLdatabase = db
} | go | func connectDB(configDatabase pfconfigdriver.PfConfDatabase) {
db, err := db.DbFromConfig(ctx)
sharedutils.CheckError(err)
MySQLdatabase = db
} | [
"func",
"connectDB",
"(",
"configDatabase",
"pfconfigdriver",
".",
"PfConfDatabase",
")",
"{",
"db",
",",
"err",
":=",
"db",
".",
"DbFromConfig",
"(",
"ctx",
")",
"\n",
"sharedutils",
".",
"CheckError",
"(",
"err",
")",
"\n",
"MySQLdatabase",
"=",
"db",
"\n",
"}"
] | // connectDB connect to the database | [
"connectDB",
"connect",
"to",
"the",
"database"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L30-L34 | train |
inverse-inc/packetfence | go/dhcp/utils.go | initiaLease | func initiaLease(dhcpHandler *DHCPHandler, ConfNet pfconfigdriver.RessourseNetworkConf) {
// Need to calculate the end ip because of the ip per role feature
now := time.Now()
endip := binary.BigEndian.Uint32(dhcpHandler.start.To4()) + uint32(dhcpHandler.leaseRange) - uint32(1)
a := make([]byte, 4)
binary.BigEndian.PutUint32(a, endip)
ipend := net.IPv4(a[0], a[1], a[2], a[3])
rows, err := MySQLdatabase.Query("select ip,mac,end_time,start_time from ip4log i where inet_aton(ip) between inet_aton(?) and inet_aton(?) and (end_time = 0 OR end_time > NOW()) and end_time in (select MAX(end_time) from ip4log where mac = i.mac) ORDER BY mac,end_time desc", dhcpHandler.start.String(), ipend.String())
if err != nil {
log.LoggerWContext(ctx).Error(err.Error())
return
}
defer rows.Close()
var (
ipstr string
mac string
end_time time.Time
start_time time.Time
reservedIP []net.IP
found bool
)
found = false
excludeIP := ExcludeIP(dhcpHandler, ConfNet.IpReserved)
dhcpHandler.ipAssigned, reservedIP = AssignIP(dhcpHandler, ConfNet.IpAssigned)
dhcpHandler.ipReserved = ConfNet.IpReserved
for rows.Next() {
err := rows.Scan(&ipstr, &mac, &end_time, &start_time)
if err != nil {
log.LoggerWContext(ctx).Error(err.Error())
return
}
for _, ans := range append(excludeIP, reservedIP...) {
if net.ParseIP(ipstr).Equal(ans) {
found = true
break
}
}
if found == false {
// Calculate the leasetime from the date in the database
var leaseDuration time.Duration
if end_time.IsZero() {
leaseDuration = dhcpHandler.leaseDuration
} else {
leaseDuration = end_time.Sub(now)
}
ip := net.ParseIP(ipstr)
// Calculate the position for the roaring bitmap
position := uint32(binary.BigEndian.Uint32(ip.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4()))
// Remove the position in the roaming bitmap
dhcpHandler.available.ReserveIPIndex(uint64(position), mac)
// Add the mac in the cache
dhcpHandler.hwcache.Set(mac, int(position), leaseDuration)
GlobalIpCache.Set(ipstr, mac, leaseDuration)
GlobalMacCache.Set(mac, ipstr, leaseDuration)
}
}
} | go | func initiaLease(dhcpHandler *DHCPHandler, ConfNet pfconfigdriver.RessourseNetworkConf) {
// Need to calculate the end ip because of the ip per role feature
now := time.Now()
endip := binary.BigEndian.Uint32(dhcpHandler.start.To4()) + uint32(dhcpHandler.leaseRange) - uint32(1)
a := make([]byte, 4)
binary.BigEndian.PutUint32(a, endip)
ipend := net.IPv4(a[0], a[1], a[2], a[3])
rows, err := MySQLdatabase.Query("select ip,mac,end_time,start_time from ip4log i where inet_aton(ip) between inet_aton(?) and inet_aton(?) and (end_time = 0 OR end_time > NOW()) and end_time in (select MAX(end_time) from ip4log where mac = i.mac) ORDER BY mac,end_time desc", dhcpHandler.start.String(), ipend.String())
if err != nil {
log.LoggerWContext(ctx).Error(err.Error())
return
}
defer rows.Close()
var (
ipstr string
mac string
end_time time.Time
start_time time.Time
reservedIP []net.IP
found bool
)
found = false
excludeIP := ExcludeIP(dhcpHandler, ConfNet.IpReserved)
dhcpHandler.ipAssigned, reservedIP = AssignIP(dhcpHandler, ConfNet.IpAssigned)
dhcpHandler.ipReserved = ConfNet.IpReserved
for rows.Next() {
err := rows.Scan(&ipstr, &mac, &end_time, &start_time)
if err != nil {
log.LoggerWContext(ctx).Error(err.Error())
return
}
for _, ans := range append(excludeIP, reservedIP...) {
if net.ParseIP(ipstr).Equal(ans) {
found = true
break
}
}
if found == false {
// Calculate the leasetime from the date in the database
var leaseDuration time.Duration
if end_time.IsZero() {
leaseDuration = dhcpHandler.leaseDuration
} else {
leaseDuration = end_time.Sub(now)
}
ip := net.ParseIP(ipstr)
// Calculate the position for the roaring bitmap
position := uint32(binary.BigEndian.Uint32(ip.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4()))
// Remove the position in the roaming bitmap
dhcpHandler.available.ReserveIPIndex(uint64(position), mac)
// Add the mac in the cache
dhcpHandler.hwcache.Set(mac, int(position), leaseDuration)
GlobalIpCache.Set(ipstr, mac, leaseDuration)
GlobalMacCache.Set(mac, ipstr, leaseDuration)
}
}
} | [
"func",
"initiaLease",
"(",
"dhcpHandler",
"*",
"DHCPHandler",
",",
"ConfNet",
"pfconfigdriver",
".",
"RessourseNetworkConf",
")",
"{",
"// Need to calculate the end ip because of the ip per role feature",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"endip",
":=",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"dhcpHandler",
".",
"start",
".",
"To4",
"(",
")",
")",
"+",
"uint32",
"(",
"dhcpHandler",
".",
"leaseRange",
")",
"-",
"uint32",
"(",
"1",
")",
"\n",
"a",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"a",
",",
"endip",
")",
"\n",
"ipend",
":=",
"net",
".",
"IPv4",
"(",
"a",
"[",
"0",
"]",
",",
"a",
"[",
"1",
"]",
",",
"a",
"[",
"2",
"]",
",",
"a",
"[",
"3",
"]",
")",
"\n\n",
"rows",
",",
"err",
":=",
"MySQLdatabase",
".",
"Query",
"(",
"\"",
"\"",
",",
"dhcpHandler",
".",
"start",
".",
"String",
"(",
")",
",",
"ipend",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"var",
"(",
"ipstr",
"string",
"\n",
"mac",
"string",
"\n",
"end_time",
"time",
".",
"Time",
"\n",
"start_time",
"time",
".",
"Time",
"\n",
"reservedIP",
"[",
"]",
"net",
".",
"IP",
"\n",
"found",
"bool",
"\n",
")",
"\n",
"found",
"=",
"false",
"\n",
"excludeIP",
":=",
"ExcludeIP",
"(",
"dhcpHandler",
",",
"ConfNet",
".",
"IpReserved",
")",
"\n",
"dhcpHandler",
".",
"ipAssigned",
",",
"reservedIP",
"=",
"AssignIP",
"(",
"dhcpHandler",
",",
"ConfNet",
".",
"IpAssigned",
")",
"\n",
"dhcpHandler",
".",
"ipReserved",
"=",
"ConfNet",
".",
"IpReserved",
"\n\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"err",
":=",
"rows",
".",
"Scan",
"(",
"&",
"ipstr",
",",
"&",
"mac",
",",
"&",
"end_time",
",",
"&",
"start_time",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"ans",
":=",
"range",
"append",
"(",
"excludeIP",
",",
"reservedIP",
"...",
")",
"{",
"if",
"net",
".",
"ParseIP",
"(",
"ipstr",
")",
".",
"Equal",
"(",
"ans",
")",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"found",
"==",
"false",
"{",
"// Calculate the leasetime from the date in the database",
"var",
"leaseDuration",
"time",
".",
"Duration",
"\n",
"if",
"end_time",
".",
"IsZero",
"(",
")",
"{",
"leaseDuration",
"=",
"dhcpHandler",
".",
"leaseDuration",
"\n",
"}",
"else",
"{",
"leaseDuration",
"=",
"end_time",
".",
"Sub",
"(",
"now",
")",
"\n",
"}",
"\n",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"ipstr",
")",
"\n\n",
"// Calculate the position for the roaring bitmap",
"position",
":=",
"uint32",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"ip",
".",
"To4",
"(",
")",
")",
")",
"-",
"uint32",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"dhcpHandler",
".",
"start",
".",
"To4",
"(",
")",
")",
")",
"\n",
"// Remove the position in the roaming bitmap",
"dhcpHandler",
".",
"available",
".",
"ReserveIPIndex",
"(",
"uint64",
"(",
"position",
")",
",",
"mac",
")",
"\n",
"// Add the mac in the cache",
"dhcpHandler",
".",
"hwcache",
".",
"Set",
"(",
"mac",
",",
"int",
"(",
"position",
")",
",",
"leaseDuration",
")",
"\n",
"GlobalIpCache",
".",
"Set",
"(",
"ipstr",
",",
"mac",
",",
"leaseDuration",
")",
"\n",
"GlobalMacCache",
".",
"Set",
"(",
"mac",
",",
"ipstr",
",",
"leaseDuration",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // initiaLease fetch the database to remove already assigned ip addresses | [
"initiaLease",
"fetch",
"the",
"database",
"to",
"remove",
"already",
"assigned",
"ip",
"addresses"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L37-L96 | train |
inverse-inc/packetfence | go/dhcp/utils.go | ExcludeIP | func ExcludeIP(dhcpHandler *DHCPHandler, ipRange string) []net.IP {
excludeIPs, _ := IPsFromRange(ipRange)
for _, excludeIP := range excludeIPs {
if excludeIP != nil {
// Calculate the position for the dhcp pool
position := uint32(binary.BigEndian.Uint32(excludeIP.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4()))
dhcpHandler.available.ReserveIPIndex(uint64(position), FakeMac)
}
}
return excludeIPs
} | go | func ExcludeIP(dhcpHandler *DHCPHandler, ipRange string) []net.IP {
excludeIPs, _ := IPsFromRange(ipRange)
for _, excludeIP := range excludeIPs {
if excludeIP != nil {
// Calculate the position for the dhcp pool
position := uint32(binary.BigEndian.Uint32(excludeIP.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4()))
dhcpHandler.available.ReserveIPIndex(uint64(position), FakeMac)
}
}
return excludeIPs
} | [
"func",
"ExcludeIP",
"(",
"dhcpHandler",
"*",
"DHCPHandler",
",",
"ipRange",
"string",
")",
"[",
"]",
"net",
".",
"IP",
"{",
"excludeIPs",
",",
"_",
":=",
"IPsFromRange",
"(",
"ipRange",
")",
"\n\n",
"for",
"_",
",",
"excludeIP",
":=",
"range",
"excludeIPs",
"{",
"if",
"excludeIP",
"!=",
"nil",
"{",
"// Calculate the position for the dhcp pool",
"position",
":=",
"uint32",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"excludeIP",
".",
"To4",
"(",
")",
")",
")",
"-",
"uint32",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"dhcpHandler",
".",
"start",
".",
"To4",
"(",
")",
")",
")",
"\n\n",
"dhcpHandler",
".",
"available",
".",
"ReserveIPIndex",
"(",
"uint64",
"(",
"position",
")",
",",
"FakeMac",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"excludeIPs",
"\n",
"}"
] | // ExcludeIP remove IP from the pool | [
"ExcludeIP",
"remove",
"IP",
"from",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L293-L305 | train |
inverse-inc/packetfence | go/dhcp/utils.go | AssignIP | func AssignIP(dhcpHandler *DHCPHandler, ipRange string) (map[string]uint32, []net.IP) {
couple := make(map[string]uint32)
var iplist []net.IP
if ipRange != "" {
rgx, _ := regexp.Compile("((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}):((?:[0-9]{1,3}.){3}(?:[0-9]{1,3}))")
ipRangeArray := strings.Split(ipRange, ",")
if len(ipRangeArray) >= 1 {
for _, rangeip := range ipRangeArray {
result := rgx.FindStringSubmatch(rangeip)
position := uint32(binary.BigEndian.Uint32(net.ParseIP(result[2]).To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4()))
// Remove the position in the roaming bitmap
dhcpHandler.available.ReserveIPIndex(uint64(position), result[1])
couple[result[1]] = position
iplist = append(iplist, net.ParseIP(result[2]))
}
}
}
return couple, iplist
} | go | func AssignIP(dhcpHandler *DHCPHandler, ipRange string) (map[string]uint32, []net.IP) {
couple := make(map[string]uint32)
var iplist []net.IP
if ipRange != "" {
rgx, _ := regexp.Compile("((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}):((?:[0-9]{1,3}.){3}(?:[0-9]{1,3}))")
ipRangeArray := strings.Split(ipRange, ",")
if len(ipRangeArray) >= 1 {
for _, rangeip := range ipRangeArray {
result := rgx.FindStringSubmatch(rangeip)
position := uint32(binary.BigEndian.Uint32(net.ParseIP(result[2]).To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4()))
// Remove the position in the roaming bitmap
dhcpHandler.available.ReserveIPIndex(uint64(position), result[1])
couple[result[1]] = position
iplist = append(iplist, net.ParseIP(result[2]))
}
}
}
return couple, iplist
} | [
"func",
"AssignIP",
"(",
"dhcpHandler",
"*",
"DHCPHandler",
",",
"ipRange",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"uint32",
",",
"[",
"]",
"net",
".",
"IP",
")",
"{",
"couple",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"uint32",
")",
"\n",
"var",
"iplist",
"[",
"]",
"net",
".",
"IP",
"\n",
"if",
"ipRange",
"!=",
"\"",
"\"",
"{",
"rgx",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"\"",
"\"",
")",
"\n",
"ipRangeArray",
":=",
"strings",
".",
"Split",
"(",
"ipRange",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"ipRangeArray",
")",
">=",
"1",
"{",
"for",
"_",
",",
"rangeip",
":=",
"range",
"ipRangeArray",
"{",
"result",
":=",
"rgx",
".",
"FindStringSubmatch",
"(",
"rangeip",
")",
"\n",
"position",
":=",
"uint32",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"net",
".",
"ParseIP",
"(",
"result",
"[",
"2",
"]",
")",
".",
"To4",
"(",
")",
")",
")",
"-",
"uint32",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"dhcpHandler",
".",
"start",
".",
"To4",
"(",
")",
")",
")",
"\n",
"// Remove the position in the roaming bitmap",
"dhcpHandler",
".",
"available",
".",
"ReserveIPIndex",
"(",
"uint64",
"(",
"position",
")",
",",
"result",
"[",
"1",
"]",
")",
"\n",
"couple",
"[",
"result",
"[",
"1",
"]",
"]",
"=",
"position",
"\n",
"iplist",
"=",
"append",
"(",
"iplist",
",",
"net",
".",
"ParseIP",
"(",
"result",
"[",
"2",
"]",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"couple",
",",
"iplist",
"\n",
"}"
] | // Assign static IP address to a mac address and remove it from the pool | [
"Assign",
"static",
"IP",
"address",
"to",
"a",
"mac",
"address",
"and",
"remove",
"it",
"from",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L308-L326 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/handshake.go | GetCertificate | func (cg configGroup) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := cg.getCertDuringHandshake(strings.ToLower(clientHello.ServerName), true, true)
return &cert.Certificate, err
} | go | func (cg configGroup) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := cg.getCertDuringHandshake(strings.ToLower(clientHello.ServerName), true, true)
return &cert.Certificate, err
} | [
"func",
"(",
"cg",
"configGroup",
")",
"GetCertificate",
"(",
"clientHello",
"*",
"tls",
".",
"ClientHelloInfo",
")",
"(",
"*",
"tls",
".",
"Certificate",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"cg",
".",
"getCertDuringHandshake",
"(",
"strings",
".",
"ToLower",
"(",
"clientHello",
".",
"ServerName",
")",
",",
"true",
",",
"true",
")",
"\n",
"return",
"&",
"cert",
".",
"Certificate",
",",
"err",
"\n",
"}"
] | // GetCertificate gets a certificate to satisfy clientHello. In getting
// the certificate, it abides the rules and settings defined in the
// Config that matches clientHello.ServerName. It first checks the in-
// memory cache, then, if the config enables "OnDemand", it accesses
// disk, then accesses the network if it must obtain a new certificate
// via ACME.
//
// This method is safe for use as a tls.Config.GetCertificate callback. | [
"GetCertificate",
"gets",
"a",
"certificate",
"to",
"satisfy",
"clientHello",
".",
"In",
"getting",
"the",
"certificate",
"it",
"abides",
"the",
"rules",
"and",
"settings",
"defined",
"in",
"the",
"Config",
"that",
"matches",
"clientHello",
".",
"ServerName",
".",
"It",
"first",
"checks",
"the",
"in",
"-",
"memory",
"cache",
"then",
"if",
"the",
"config",
"enables",
"OnDemand",
"it",
"accesses",
"disk",
"then",
"accesses",
"the",
"network",
"if",
"it",
"must",
"obtain",
"a",
"new",
"certificate",
"via",
"ACME",
".",
"This",
"method",
"is",
"safe",
"for",
"use",
"as",
"a",
"tls",
".",
"Config",
".",
"GetCertificate",
"callback",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L61-L64 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/handshake.go | checkLimitsForObtainingNewCerts | func (cg configGroup) checkLimitsForObtainingNewCerts(name string, cfg *Config) error {
// User can set hard limit for number of certs for the process to issue
if cfg.OnDemandState.MaxObtain > 0 &&
atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= cfg.OnDemandState.MaxObtain {
return fmt.Errorf("%s: maximum certificates issued (%d)", name, cfg.OnDemandState.MaxObtain)
}
// Make sure name hasn't failed a challenge recently
failedIssuanceMu.RLock()
when, ok := failedIssuance[name]
failedIssuanceMu.RUnlock()
if ok {
return fmt.Errorf("%s: throttled; refusing to issue cert since last attempt on %s failed", name, when.String())
}
// Make sure, if we've issued a few certificates already, that we haven't
// issued any recently
lastIssueTimeMu.Lock()
since := time.Since(lastIssueTime)
lastIssueTimeMu.Unlock()
if atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= 10 && since < 10*time.Minute {
return fmt.Errorf("%s: throttled; last certificate was obtained %v ago", name, since)
}
// 👍Good to go
return nil
} | go | func (cg configGroup) checkLimitsForObtainingNewCerts(name string, cfg *Config) error {
// User can set hard limit for number of certs for the process to issue
if cfg.OnDemandState.MaxObtain > 0 &&
atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= cfg.OnDemandState.MaxObtain {
return fmt.Errorf("%s: maximum certificates issued (%d)", name, cfg.OnDemandState.MaxObtain)
}
// Make sure name hasn't failed a challenge recently
failedIssuanceMu.RLock()
when, ok := failedIssuance[name]
failedIssuanceMu.RUnlock()
if ok {
return fmt.Errorf("%s: throttled; refusing to issue cert since last attempt on %s failed", name, when.String())
}
// Make sure, if we've issued a few certificates already, that we haven't
// issued any recently
lastIssueTimeMu.Lock()
since := time.Since(lastIssueTime)
lastIssueTimeMu.Unlock()
if atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= 10 && since < 10*time.Minute {
return fmt.Errorf("%s: throttled; last certificate was obtained %v ago", name, since)
}
// 👍Good to go
return nil
} | [
"func",
"(",
"cg",
"configGroup",
")",
"checkLimitsForObtainingNewCerts",
"(",
"name",
"string",
",",
"cfg",
"*",
"Config",
")",
"error",
"{",
"// User can set hard limit for number of certs for the process to issue",
"if",
"cfg",
".",
"OnDemandState",
".",
"MaxObtain",
">",
"0",
"&&",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cfg",
".",
"OnDemandState",
".",
"ObtainedCount",
")",
">=",
"cfg",
".",
"OnDemandState",
".",
"MaxObtain",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"cfg",
".",
"OnDemandState",
".",
"MaxObtain",
")",
"\n",
"}",
"\n\n",
"// Make sure name hasn't failed a challenge recently",
"failedIssuanceMu",
".",
"RLock",
"(",
")",
"\n",
"when",
",",
"ok",
":=",
"failedIssuance",
"[",
"name",
"]",
"\n",
"failedIssuanceMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"when",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Make sure, if we've issued a few certificates already, that we haven't",
"// issued any recently",
"lastIssueTimeMu",
".",
"Lock",
"(",
")",
"\n",
"since",
":=",
"time",
".",
"Since",
"(",
"lastIssueTime",
")",
"\n",
"lastIssueTimeMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cfg",
".",
"OnDemandState",
".",
"ObtainedCount",
")",
">=",
"10",
"&&",
"since",
"<",
"10",
"*",
"time",
".",
"Minute",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"since",
")",
"\n",
"}",
"\n\n",
"// 👍Good to go",
"return",
"nil",
"\n",
"}"
] | // checkLimitsForObtainingNewCerts checks to see if name can be issued right
// now according to mitigating factors we keep track of and preferences the
// user has set. If a non-nil error is returned, do not issue a new certificate
// for name. | [
"checkLimitsForObtainingNewCerts",
"checks",
"to",
"see",
"if",
"name",
"can",
"be",
"issued",
"right",
"now",
"according",
"to",
"mitigating",
"factors",
"we",
"keep",
"track",
"of",
"and",
"preferences",
"the",
"user",
"has",
"set",
".",
"If",
"a",
"non",
"-",
"nil",
"error",
"is",
"returned",
"do",
"not",
"issue",
"a",
"new",
"certificate",
"for",
"name",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L130-L156 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/handshake.go | obtainOnDemandCertificate | func (cg configGroup) obtainOnDemandCertificate(name string, cfg *Config) (Certificate, error) {
// We must protect this process from happening concurrently, so synchronize.
obtainCertWaitChansMu.Lock()
wait, ok := obtainCertWaitChans[name]
if ok {
// lucky us -- another goroutine is already obtaining the certificate.
// wait for it to finish obtaining the cert and then we'll use it.
obtainCertWaitChansMu.Unlock()
<-wait
return cg.getCertDuringHandshake(name, true, false)
}
// looks like it's up to us to do all the work and obtain the cert.
// make a chan others can wait on if needed
wait = make(chan struct{})
obtainCertWaitChans[name] = wait
obtainCertWaitChansMu.Unlock()
// do the obtain
log.Printf("[INFO] Obtaining new certificate for %s", name)
err := cfg.ObtainCert(name, false)
// immediately unblock anyone waiting for it; doing this in
// a defer would risk deadlock because of the recursive call
// to getCertDuringHandshake below when we return!
obtainCertWaitChansMu.Lock()
close(wait)
delete(obtainCertWaitChans, name)
obtainCertWaitChansMu.Unlock()
if err != nil {
// Failed to solve challenge, so don't allow another on-demand
// issue for this name to be attempted for a little while.
failedIssuanceMu.Lock()
failedIssuance[name] = time.Now()
go func(name string) {
time.Sleep(5 * time.Minute)
failedIssuanceMu.Lock()
delete(failedIssuance, name)
failedIssuanceMu.Unlock()
}(name)
failedIssuanceMu.Unlock()
return Certificate{}, err
}
// Success - update counters and stuff
atomic.AddInt32(&cfg.OnDemandState.ObtainedCount, 1)
lastIssueTimeMu.Lock()
lastIssueTime = time.Now()
lastIssueTimeMu.Unlock()
// certificate is already on disk; now just start over to load it and serve it
return cg.getCertDuringHandshake(name, true, false)
} | go | func (cg configGroup) obtainOnDemandCertificate(name string, cfg *Config) (Certificate, error) {
// We must protect this process from happening concurrently, so synchronize.
obtainCertWaitChansMu.Lock()
wait, ok := obtainCertWaitChans[name]
if ok {
// lucky us -- another goroutine is already obtaining the certificate.
// wait for it to finish obtaining the cert and then we'll use it.
obtainCertWaitChansMu.Unlock()
<-wait
return cg.getCertDuringHandshake(name, true, false)
}
// looks like it's up to us to do all the work and obtain the cert.
// make a chan others can wait on if needed
wait = make(chan struct{})
obtainCertWaitChans[name] = wait
obtainCertWaitChansMu.Unlock()
// do the obtain
log.Printf("[INFO] Obtaining new certificate for %s", name)
err := cfg.ObtainCert(name, false)
// immediately unblock anyone waiting for it; doing this in
// a defer would risk deadlock because of the recursive call
// to getCertDuringHandshake below when we return!
obtainCertWaitChansMu.Lock()
close(wait)
delete(obtainCertWaitChans, name)
obtainCertWaitChansMu.Unlock()
if err != nil {
// Failed to solve challenge, so don't allow another on-demand
// issue for this name to be attempted for a little while.
failedIssuanceMu.Lock()
failedIssuance[name] = time.Now()
go func(name string) {
time.Sleep(5 * time.Minute)
failedIssuanceMu.Lock()
delete(failedIssuance, name)
failedIssuanceMu.Unlock()
}(name)
failedIssuanceMu.Unlock()
return Certificate{}, err
}
// Success - update counters and stuff
atomic.AddInt32(&cfg.OnDemandState.ObtainedCount, 1)
lastIssueTimeMu.Lock()
lastIssueTime = time.Now()
lastIssueTimeMu.Unlock()
// certificate is already on disk; now just start over to load it and serve it
return cg.getCertDuringHandshake(name, true, false)
} | [
"func",
"(",
"cg",
"configGroup",
")",
"obtainOnDemandCertificate",
"(",
"name",
"string",
",",
"cfg",
"*",
"Config",
")",
"(",
"Certificate",
",",
"error",
")",
"{",
"// We must protect this process from happening concurrently, so synchronize.",
"obtainCertWaitChansMu",
".",
"Lock",
"(",
")",
"\n",
"wait",
",",
"ok",
":=",
"obtainCertWaitChans",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"// lucky us -- another goroutine is already obtaining the certificate.",
"// wait for it to finish obtaining the cert and then we'll use it.",
"obtainCertWaitChansMu",
".",
"Unlock",
"(",
")",
"\n",
"<-",
"wait",
"\n",
"return",
"cg",
".",
"getCertDuringHandshake",
"(",
"name",
",",
"true",
",",
"false",
")",
"\n",
"}",
"\n\n",
"// looks like it's up to us to do all the work and obtain the cert.",
"// make a chan others can wait on if needed",
"wait",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"obtainCertWaitChans",
"[",
"name",
"]",
"=",
"wait",
"\n",
"obtainCertWaitChansMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// do the obtain",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"err",
":=",
"cfg",
".",
"ObtainCert",
"(",
"name",
",",
"false",
")",
"\n\n",
"// immediately unblock anyone waiting for it; doing this in",
"// a defer would risk deadlock because of the recursive call",
"// to getCertDuringHandshake below when we return!",
"obtainCertWaitChansMu",
".",
"Lock",
"(",
")",
"\n",
"close",
"(",
"wait",
")",
"\n",
"delete",
"(",
"obtainCertWaitChans",
",",
"name",
")",
"\n",
"obtainCertWaitChansMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// Failed to solve challenge, so don't allow another on-demand",
"// issue for this name to be attempted for a little while.",
"failedIssuanceMu",
".",
"Lock",
"(",
")",
"\n",
"failedIssuance",
"[",
"name",
"]",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"go",
"func",
"(",
"name",
"string",
")",
"{",
"time",
".",
"Sleep",
"(",
"5",
"*",
"time",
".",
"Minute",
")",
"\n",
"failedIssuanceMu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"failedIssuance",
",",
"name",
")",
"\n",
"failedIssuanceMu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
"name",
")",
"\n",
"failedIssuanceMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Success - update counters and stuff",
"atomic",
".",
"AddInt32",
"(",
"&",
"cfg",
".",
"OnDemandState",
".",
"ObtainedCount",
",",
"1",
")",
"\n",
"lastIssueTimeMu",
".",
"Lock",
"(",
")",
"\n",
"lastIssueTime",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"lastIssueTimeMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// certificate is already on disk; now just start over to load it and serve it",
"return",
"cg",
".",
"getCertDuringHandshake",
"(",
"name",
",",
"true",
",",
"false",
")",
"\n",
"}"
] | // obtainOnDemandCertificate obtains a certificate for name for the given
// name. If another goroutine has already started obtaining a cert for
// name, it will wait and use what the other goroutine obtained.
//
// This function is safe for use by multiple concurrent goroutines. | [
"obtainOnDemandCertificate",
"obtains",
"a",
"certificate",
"for",
"name",
"for",
"the",
"given",
"name",
".",
"If",
"another",
"goroutine",
"has",
"already",
"started",
"obtaining",
"a",
"cert",
"for",
"name",
"it",
"will",
"wait",
"and",
"use",
"what",
"the",
"other",
"goroutine",
"obtained",
".",
"This",
"function",
"is",
"safe",
"for",
"use",
"by",
"multiple",
"concurrent",
"goroutines",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L163-L216 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/handshake.go | handshakeMaintenance | func (cg configGroup) handshakeMaintenance(name string, cert Certificate) (Certificate, error) {
// Check cert expiration
timeLeft := cert.NotAfter.Sub(time.Now().UTC())
if timeLeft < RenewDurationBefore {
log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft)
return cg.renewDynamicCertificate(name, cert.Config)
}
// Check OCSP staple validity
if cert.OCSP != nil {
refreshTime := cert.OCSP.ThisUpdate.Add(cert.OCSP.NextUpdate.Sub(cert.OCSP.ThisUpdate) / 2)
if time.Now().After(refreshTime) {
err := stapleOCSP(&cert, nil)
if err != nil {
// An error with OCSP stapling is not the end of the world, and in fact, is
// quite common considering not all certs have issuer URLs that support it.
log.Printf("[ERROR] Getting OCSP for %s: %v", name, err)
}
certCacheMu.Lock()
certCache[name] = cert
certCacheMu.Unlock()
}
}
return cert, nil
} | go | func (cg configGroup) handshakeMaintenance(name string, cert Certificate) (Certificate, error) {
// Check cert expiration
timeLeft := cert.NotAfter.Sub(time.Now().UTC())
if timeLeft < RenewDurationBefore {
log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft)
return cg.renewDynamicCertificate(name, cert.Config)
}
// Check OCSP staple validity
if cert.OCSP != nil {
refreshTime := cert.OCSP.ThisUpdate.Add(cert.OCSP.NextUpdate.Sub(cert.OCSP.ThisUpdate) / 2)
if time.Now().After(refreshTime) {
err := stapleOCSP(&cert, nil)
if err != nil {
// An error with OCSP stapling is not the end of the world, and in fact, is
// quite common considering not all certs have issuer URLs that support it.
log.Printf("[ERROR] Getting OCSP for %s: %v", name, err)
}
certCacheMu.Lock()
certCache[name] = cert
certCacheMu.Unlock()
}
}
return cert, nil
} | [
"func",
"(",
"cg",
"configGroup",
")",
"handshakeMaintenance",
"(",
"name",
"string",
",",
"cert",
"Certificate",
")",
"(",
"Certificate",
",",
"error",
")",
"{",
"// Check cert expiration",
"timeLeft",
":=",
"cert",
".",
"NotAfter",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
")",
"\n",
"if",
"timeLeft",
"<",
"RenewDurationBefore",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"cert",
".",
"Names",
",",
"timeLeft",
")",
"\n",
"return",
"cg",
".",
"renewDynamicCertificate",
"(",
"name",
",",
"cert",
".",
"Config",
")",
"\n",
"}",
"\n\n",
"// Check OCSP staple validity",
"if",
"cert",
".",
"OCSP",
"!=",
"nil",
"{",
"refreshTime",
":=",
"cert",
".",
"OCSP",
".",
"ThisUpdate",
".",
"Add",
"(",
"cert",
".",
"OCSP",
".",
"NextUpdate",
".",
"Sub",
"(",
"cert",
".",
"OCSP",
".",
"ThisUpdate",
")",
"/",
"2",
")",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"After",
"(",
"refreshTime",
")",
"{",
"err",
":=",
"stapleOCSP",
"(",
"&",
"cert",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// An error with OCSP stapling is not the end of the world, and in fact, is",
"// quite common considering not all certs have issuer URLs that support it.",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"certCacheMu",
".",
"Lock",
"(",
")",
"\n",
"certCache",
"[",
"name",
"]",
"=",
"cert",
"\n",
"certCacheMu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"cert",
",",
"nil",
"\n",
"}"
] | // handshakeMaintenance performs a check on cert for expiration and OCSP
// validity.
//
// This function is safe for use by multiple concurrent goroutines. | [
"handshakeMaintenance",
"performs",
"a",
"check",
"on",
"cert",
"for",
"expiration",
"and",
"OCSP",
"validity",
".",
"This",
"function",
"is",
"safe",
"for",
"use",
"by",
"multiple",
"concurrent",
"goroutines",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L222-L247 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/handshake.go | renewDynamicCertificate | func (cg configGroup) renewDynamicCertificate(name string, cfg *Config) (Certificate, error) {
obtainCertWaitChansMu.Lock()
wait, ok := obtainCertWaitChans[name]
if ok {
// lucky us -- another goroutine is already renewing the certificate.
// wait for it to finish, then we'll use the new one.
obtainCertWaitChansMu.Unlock()
<-wait
return cg.getCertDuringHandshake(name, true, false)
}
// looks like it's up to us to do all the work and renew the cert
wait = make(chan struct{})
obtainCertWaitChans[name] = wait
obtainCertWaitChansMu.Unlock()
// do the renew
log.Printf("[INFO] Renewing certificate for %s", name)
err := cfg.RenewCert(name, false)
// immediately unblock anyone waiting for it; doing this in
// a defer would risk deadlock because of the recursive call
// to getCertDuringHandshake below when we return!
obtainCertWaitChansMu.Lock()
close(wait)
delete(obtainCertWaitChans, name)
obtainCertWaitChansMu.Unlock()
if err != nil {
return Certificate{}, err
}
return cg.getCertDuringHandshake(name, true, false)
} | go | func (cg configGroup) renewDynamicCertificate(name string, cfg *Config) (Certificate, error) {
obtainCertWaitChansMu.Lock()
wait, ok := obtainCertWaitChans[name]
if ok {
// lucky us -- another goroutine is already renewing the certificate.
// wait for it to finish, then we'll use the new one.
obtainCertWaitChansMu.Unlock()
<-wait
return cg.getCertDuringHandshake(name, true, false)
}
// looks like it's up to us to do all the work and renew the cert
wait = make(chan struct{})
obtainCertWaitChans[name] = wait
obtainCertWaitChansMu.Unlock()
// do the renew
log.Printf("[INFO] Renewing certificate for %s", name)
err := cfg.RenewCert(name, false)
// immediately unblock anyone waiting for it; doing this in
// a defer would risk deadlock because of the recursive call
// to getCertDuringHandshake below when we return!
obtainCertWaitChansMu.Lock()
close(wait)
delete(obtainCertWaitChans, name)
obtainCertWaitChansMu.Unlock()
if err != nil {
return Certificate{}, err
}
return cg.getCertDuringHandshake(name, true, false)
} | [
"func",
"(",
"cg",
"configGroup",
")",
"renewDynamicCertificate",
"(",
"name",
"string",
",",
"cfg",
"*",
"Config",
")",
"(",
"Certificate",
",",
"error",
")",
"{",
"obtainCertWaitChansMu",
".",
"Lock",
"(",
")",
"\n",
"wait",
",",
"ok",
":=",
"obtainCertWaitChans",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"// lucky us -- another goroutine is already renewing the certificate.",
"// wait for it to finish, then we'll use the new one.",
"obtainCertWaitChansMu",
".",
"Unlock",
"(",
")",
"\n",
"<-",
"wait",
"\n",
"return",
"cg",
".",
"getCertDuringHandshake",
"(",
"name",
",",
"true",
",",
"false",
")",
"\n",
"}",
"\n\n",
"// looks like it's up to us to do all the work and renew the cert",
"wait",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"obtainCertWaitChans",
"[",
"name",
"]",
"=",
"wait",
"\n",
"obtainCertWaitChansMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// do the renew",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"err",
":=",
"cfg",
".",
"RenewCert",
"(",
"name",
",",
"false",
")",
"\n\n",
"// immediately unblock anyone waiting for it; doing this in",
"// a defer would risk deadlock because of the recursive call",
"// to getCertDuringHandshake below when we return!",
"obtainCertWaitChansMu",
".",
"Lock",
"(",
")",
"\n",
"close",
"(",
"wait",
")",
"\n",
"delete",
"(",
"obtainCertWaitChans",
",",
"name",
")",
"\n",
"obtainCertWaitChansMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"cg",
".",
"getCertDuringHandshake",
"(",
"name",
",",
"true",
",",
"false",
")",
"\n",
"}"
] | // renewDynamicCertificate renews the certificate for name using cfg. It returns the
// certificate to use and an error, if any. currentCert may be returned even if an
// error occurs, since we perform renewals before they expire and it may still be
// usable. name should already be lower-cased before calling this function.
//
// This function is safe for use by multiple concurrent goroutines. | [
"renewDynamicCertificate",
"renews",
"the",
"certificate",
"for",
"name",
"using",
"cfg",
".",
"It",
"returns",
"the",
"certificate",
"to",
"use",
"and",
"an",
"error",
"if",
"any",
".",
"currentCert",
"may",
"be",
"returned",
"even",
"if",
"an",
"error",
"occurs",
"since",
"we",
"perform",
"renewals",
"before",
"they",
"expire",
"and",
"it",
"may",
"still",
"be",
"usable",
".",
"name",
"should",
"already",
"be",
"lower",
"-",
"cased",
"before",
"calling",
"this",
"function",
".",
"This",
"function",
"is",
"safe",
"for",
"use",
"by",
"multiple",
"concurrent",
"goroutines",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L255-L288 | train |
inverse-inc/packetfence | go/dhcp/rawClient.go | NewRawClient | func NewRawClient(ifi *net.Interface) (*RawClient, error) {
// Open raw socket to send Wake-on-LAN magic packets
var cfg raw.Config
p, err := raw.ListenPacket(ifi, 0x0806, &cfg)
if err != nil {
return nil, err
}
return &RawClient{
ifi: ifi,
p: p,
}, nil
} | go | func NewRawClient(ifi *net.Interface) (*RawClient, error) {
// Open raw socket to send Wake-on-LAN magic packets
var cfg raw.Config
p, err := raw.ListenPacket(ifi, 0x0806, &cfg)
if err != nil {
return nil, err
}
return &RawClient{
ifi: ifi,
p: p,
}, nil
} | [
"func",
"NewRawClient",
"(",
"ifi",
"*",
"net",
".",
"Interface",
")",
"(",
"*",
"RawClient",
",",
"error",
")",
"{",
"// Open raw socket to send Wake-on-LAN magic packets",
"var",
"cfg",
"raw",
".",
"Config",
"\n\n",
"p",
",",
"err",
":=",
"raw",
".",
"ListenPacket",
"(",
"ifi",
",",
"0x0806",
",",
"&",
"cfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"RawClient",
"{",
"ifi",
":",
"ifi",
",",
"p",
":",
"p",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewRawClient creates a new RawClient using the specified network interface.
//
// Note that raw sockets typically require elevated user privileges, such as
// the 'root' user on Linux, or the 'SET_CAP_RAW' capability.
//
// For this reason, it is typically recommended to use the regular Client type
// instead, which operates over UDP. | [
"NewRawClient",
"creates",
"a",
"new",
"RawClient",
"using",
"the",
"specified",
"network",
"interface",
".",
"Note",
"that",
"raw",
"sockets",
"typically",
"require",
"elevated",
"user",
"privileges",
"such",
"as",
"the",
"root",
"user",
"on",
"Linux",
"or",
"the",
"SET_CAP_RAW",
"capability",
".",
"For",
"this",
"reason",
"it",
"is",
"typically",
"recommended",
"to",
"use",
"the",
"regular",
"Client",
"type",
"instead",
"which",
"operates",
"over",
"UDP",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/rawClient.go#L62-L75 | train |
inverse-inc/packetfence | go/dhcp/rawClient.go | sendDHCP | func (c *RawClient) sendDHCP(target net.HardwareAddr, dhcp []byte, dstIP net.IP, srcIP net.IP) error {
proto := 17
udpsrc := uint(67)
udpdst := uint(68)
udp := udphdr{
src: uint16(udpsrc),
dst: uint16(udpdst),
}
udplen := 8 + len(dhcp)
ip := iphdr{
vhl: 0x45,
tos: 0,
id: 0x0000, // the kernel overwrites id if it is zero
off: 0,
ttl: 128,
proto: uint8(proto),
}
copy(ip.src[:], srcIP.To4())
copy(ip.dst[:], dstIP.To4())
udp.ulen = uint16(udplen)
udp.checksum(&ip, dhcp)
totalLen := 20 + udplen
ip.iplen = uint16(totalLen)
ip.checksum()
buf := bytes.NewBuffer([]byte{})
err := binary.Write(buf, binary.BigEndian, &udp)
if err != nil {
log.Fatal(err)
}
udpHeader := buf.Bytes()
dataWithHeader := append(udpHeader, dhcp...)
buff := bytes.NewBuffer([]byte{})
err = binary.Write(buff, binary.BigEndian, &ip)
if err != nil {
log.Fatal(err)
}
ipHeader := buff.Bytes()
packet := append(ipHeader, dataWithHeader...)
// Create Ethernet frame
f := ðernet.Frame{
Destination: target,
Source: c.ifi.HardwareAddr,
EtherType: ethernet.EtherTypeIPv4,
Payload: packet,
}
fb, err := f.MarshalBinary()
if err != nil {
return err
}
// Send packet to target
_, err = c.p.WriteTo(fb, &raw.Addr{
HardwareAddr: target,
})
return err
} | go | func (c *RawClient) sendDHCP(target net.HardwareAddr, dhcp []byte, dstIP net.IP, srcIP net.IP) error {
proto := 17
udpsrc := uint(67)
udpdst := uint(68)
udp := udphdr{
src: uint16(udpsrc),
dst: uint16(udpdst),
}
udplen := 8 + len(dhcp)
ip := iphdr{
vhl: 0x45,
tos: 0,
id: 0x0000, // the kernel overwrites id if it is zero
off: 0,
ttl: 128,
proto: uint8(proto),
}
copy(ip.src[:], srcIP.To4())
copy(ip.dst[:], dstIP.To4())
udp.ulen = uint16(udplen)
udp.checksum(&ip, dhcp)
totalLen := 20 + udplen
ip.iplen = uint16(totalLen)
ip.checksum()
buf := bytes.NewBuffer([]byte{})
err := binary.Write(buf, binary.BigEndian, &udp)
if err != nil {
log.Fatal(err)
}
udpHeader := buf.Bytes()
dataWithHeader := append(udpHeader, dhcp...)
buff := bytes.NewBuffer([]byte{})
err = binary.Write(buff, binary.BigEndian, &ip)
if err != nil {
log.Fatal(err)
}
ipHeader := buff.Bytes()
packet := append(ipHeader, dataWithHeader...)
// Create Ethernet frame
f := ðernet.Frame{
Destination: target,
Source: c.ifi.HardwareAddr,
EtherType: ethernet.EtherTypeIPv4,
Payload: packet,
}
fb, err := f.MarshalBinary()
if err != nil {
return err
}
// Send packet to target
_, err = c.p.WriteTo(fb, &raw.Addr{
HardwareAddr: target,
})
return err
} | [
"func",
"(",
"c",
"*",
"RawClient",
")",
"sendDHCP",
"(",
"target",
"net",
".",
"HardwareAddr",
",",
"dhcp",
"[",
"]",
"byte",
",",
"dstIP",
"net",
".",
"IP",
",",
"srcIP",
"net",
".",
"IP",
")",
"error",
"{",
"proto",
":=",
"17",
"\n\n",
"udpsrc",
":=",
"uint",
"(",
"67",
")",
"\n",
"udpdst",
":=",
"uint",
"(",
"68",
")",
"\n\n",
"udp",
":=",
"udphdr",
"{",
"src",
":",
"uint16",
"(",
"udpsrc",
")",
",",
"dst",
":",
"uint16",
"(",
"udpdst",
")",
",",
"}",
"\n\n",
"udplen",
":=",
"8",
"+",
"len",
"(",
"dhcp",
")",
"\n\n",
"ip",
":=",
"iphdr",
"{",
"vhl",
":",
"0x45",
",",
"tos",
":",
"0",
",",
"id",
":",
"0x0000",
",",
"// the kernel overwrites id if it is zero",
"off",
":",
"0",
",",
"ttl",
":",
"128",
",",
"proto",
":",
"uint8",
"(",
"proto",
")",
",",
"}",
"\n",
"copy",
"(",
"ip",
".",
"src",
"[",
":",
"]",
",",
"srcIP",
".",
"To4",
"(",
")",
")",
"\n",
"copy",
"(",
"ip",
".",
"dst",
"[",
":",
"]",
",",
"dstIP",
".",
"To4",
"(",
")",
")",
"\n\n",
"udp",
".",
"ulen",
"=",
"uint16",
"(",
"udplen",
")",
"\n",
"udp",
".",
"checksum",
"(",
"&",
"ip",
",",
"dhcp",
")",
"\n\n",
"totalLen",
":=",
"20",
"+",
"udplen",
"\n\n",
"ip",
".",
"iplen",
"=",
"uint16",
"(",
"totalLen",
")",
"\n",
"ip",
".",
"checksum",
"(",
")",
"\n\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"BigEndian",
",",
"&",
"udp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"udpHeader",
":=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"dataWithHeader",
":=",
"append",
"(",
"udpHeader",
",",
"dhcp",
"...",
")",
"\n\n",
"buff",
":=",
"bytes",
".",
"NewBuffer",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"err",
"=",
"binary",
".",
"Write",
"(",
"buff",
",",
"binary",
".",
"BigEndian",
",",
"&",
"ip",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"ipHeader",
":=",
"buff",
".",
"Bytes",
"(",
")",
"\n",
"packet",
":=",
"append",
"(",
"ipHeader",
",",
"dataWithHeader",
"...",
")",
"\n\n",
"// Create Ethernet frame",
"f",
":=",
"&",
"ethernet",
".",
"Frame",
"{",
"Destination",
":",
"target",
",",
"Source",
":",
"c",
".",
"ifi",
".",
"HardwareAddr",
",",
"EtherType",
":",
"ethernet",
".",
"EtherTypeIPv4",
",",
"Payload",
":",
"packet",
",",
"}",
"\n",
"fb",
",",
"err",
":=",
"f",
".",
"MarshalBinary",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Send packet to target",
"_",
",",
"err",
"=",
"c",
".",
"p",
".",
"WriteTo",
"(",
"fb",
",",
"&",
"raw",
".",
"Addr",
"{",
"HardwareAddr",
":",
"target",
",",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // sendDHCP create a udp packet and stores it in an
// Ethernet frame, and sends the frame over a raw socket to attempt to wake
// a machine. | [
"sendDHCP",
"create",
"a",
"udp",
"packet",
"and",
"stores",
"it",
"in",
"an",
"Ethernet",
"frame",
"and",
"sends",
"the",
"frame",
"over",
"a",
"raw",
"socket",
"to",
"attempt",
"to",
"wake",
"a",
"machine",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/rawClient.go#L85-L153 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | setupEdns0Opt | func setupEdns0Opt(r *dns.Msg) *dns.OPT {
o := r.IsEdns0()
if o == nil {
r.SetEdns0(4096, true)
o = r.IsEdns0()
}
return o
} | go | func setupEdns0Opt(r *dns.Msg) *dns.OPT {
o := r.IsEdns0()
if o == nil {
r.SetEdns0(4096, true)
o = r.IsEdns0()
}
return o
} | [
"func",
"setupEdns0Opt",
"(",
"r",
"*",
"dns",
".",
"Msg",
")",
"*",
"dns",
".",
"OPT",
"{",
"o",
":=",
"r",
".",
"IsEdns0",
"(",
")",
"\n",
"if",
"o",
"==",
"nil",
"{",
"r",
".",
"SetEdns0",
"(",
"4096",
",",
"true",
")",
"\n",
"o",
"=",
"r",
".",
"IsEdns0",
"(",
")",
"\n",
"}",
"\n",
"return",
"o",
"\n",
"}"
] | // setupEdns0Opt will retrieve the EDNS0 OPT or create it if it does not exist | [
"setupEdns0Opt",
"will",
"retrieve",
"the",
"EDNS0",
"OPT",
"or",
"create",
"it",
"if",
"it",
"does",
"not",
"exist"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L39-L46 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | Rewrite | func (rule *edns0LocalRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option {
switch e := s.(type) {
case *dns.EDNS0_LOCAL:
if rule.code == e.Code {
if rule.action == Replace || rule.action == Set {
e.Data = rule.data
result = RewriteDone
}
found = true
break
}
}
}
// add option if not found
if !found && (rule.action == Append || rule.action == Set) {
o.SetDo()
var opt dns.EDNS0_LOCAL
opt.Code = rule.code
opt.Data = rule.data
o.Option = append(o.Option, &opt)
result = RewriteDone
}
return result
} | go | func (rule *edns0LocalRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option {
switch e := s.(type) {
case *dns.EDNS0_LOCAL:
if rule.code == e.Code {
if rule.action == Replace || rule.action == Set {
e.Data = rule.data
result = RewriteDone
}
found = true
break
}
}
}
// add option if not found
if !found && (rule.action == Append || rule.action == Set) {
o.SetDo()
var opt dns.EDNS0_LOCAL
opt.Code = rule.code
opt.Data = rule.data
o.Option = append(o.Option, &opt)
result = RewriteDone
}
return result
} | [
"func",
"(",
"rule",
"*",
"edns0LocalRule",
")",
"Rewrite",
"(",
"w",
"dns",
".",
"ResponseWriter",
",",
"r",
"*",
"dns",
".",
"Msg",
")",
"Result",
"{",
"result",
":=",
"RewriteIgnored",
"\n",
"o",
":=",
"setupEdns0Opt",
"(",
"r",
")",
"\n",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"o",
".",
"Option",
"{",
"switch",
"e",
":=",
"s",
".",
"(",
"type",
")",
"{",
"case",
"*",
"dns",
".",
"EDNS0_LOCAL",
":",
"if",
"rule",
".",
"code",
"==",
"e",
".",
"Code",
"{",
"if",
"rule",
".",
"action",
"==",
"Replace",
"||",
"rule",
".",
"action",
"==",
"Set",
"{",
"e",
".",
"Data",
"=",
"rule",
".",
"data",
"\n",
"result",
"=",
"RewriteDone",
"\n",
"}",
"\n",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// add option if not found",
"if",
"!",
"found",
"&&",
"(",
"rule",
".",
"action",
"==",
"Append",
"||",
"rule",
".",
"action",
"==",
"Set",
")",
"{",
"o",
".",
"SetDo",
"(",
")",
"\n",
"var",
"opt",
"dns",
".",
"EDNS0_LOCAL",
"\n",
"opt",
".",
"Code",
"=",
"rule",
".",
"code",
"\n",
"opt",
".",
"Data",
"=",
"rule",
".",
"data",
"\n",
"o",
".",
"Option",
"=",
"append",
"(",
"o",
".",
"Option",
",",
"&",
"opt",
")",
"\n",
"result",
"=",
"RewriteDone",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // Rewrite will alter the request EDNS0 local options | [
"Rewrite",
"will",
"alter",
"the",
"request",
"EDNS0",
"local",
"options"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L82-L111 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | newEdns0Rule | func newEdns0Rule(mode string, args ...string) (Rule, error) {
if len(args) < 2 {
return nil, fmt.Errorf("too few arguments for an EDNS0 rule")
}
ruleType := strings.ToLower(args[0])
action := strings.ToLower(args[1])
switch action {
case Append:
case Replace:
case Set:
default:
return nil, fmt.Errorf("invalid action: %q", action)
}
switch ruleType {
case "local":
if len(args) != 4 {
return nil, fmt.Errorf("EDNS0 local rules require exactly three args")
}
//Check for variable option
if strings.HasPrefix(args[3], "{") && strings.HasSuffix(args[3], "}") {
return newEdns0VariableRule(mode, action, args[2], args[3])
}
return newEdns0LocalRule(mode, action, args[2], args[3])
case "nsid":
if len(args) != 2 {
return nil, fmt.Errorf("EDNS0 NSID rules do not accept args")
}
return &edns0NsidRule{mode: mode, action: action}, nil
case "subnet":
if len(args) != 4 {
return nil, fmt.Errorf("EDNS0 subnet rules require exactly three args")
}
return newEdns0SubnetRule(mode, action, args[2], args[3])
default:
return nil, fmt.Errorf("invalid rule type %q", ruleType)
}
} | go | func newEdns0Rule(mode string, args ...string) (Rule, error) {
if len(args) < 2 {
return nil, fmt.Errorf("too few arguments for an EDNS0 rule")
}
ruleType := strings.ToLower(args[0])
action := strings.ToLower(args[1])
switch action {
case Append:
case Replace:
case Set:
default:
return nil, fmt.Errorf("invalid action: %q", action)
}
switch ruleType {
case "local":
if len(args) != 4 {
return nil, fmt.Errorf("EDNS0 local rules require exactly three args")
}
//Check for variable option
if strings.HasPrefix(args[3], "{") && strings.HasSuffix(args[3], "}") {
return newEdns0VariableRule(mode, action, args[2], args[3])
}
return newEdns0LocalRule(mode, action, args[2], args[3])
case "nsid":
if len(args) != 2 {
return nil, fmt.Errorf("EDNS0 NSID rules do not accept args")
}
return &edns0NsidRule{mode: mode, action: action}, nil
case "subnet":
if len(args) != 4 {
return nil, fmt.Errorf("EDNS0 subnet rules require exactly three args")
}
return newEdns0SubnetRule(mode, action, args[2], args[3])
default:
return nil, fmt.Errorf("invalid rule type %q", ruleType)
}
} | [
"func",
"newEdns0Rule",
"(",
"mode",
"string",
",",
"args",
"...",
"string",
")",
"(",
"Rule",
",",
"error",
")",
"{",
"if",
"len",
"(",
"args",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ruleType",
":=",
"strings",
".",
"ToLower",
"(",
"args",
"[",
"0",
"]",
")",
"\n",
"action",
":=",
"strings",
".",
"ToLower",
"(",
"args",
"[",
"1",
"]",
")",
"\n",
"switch",
"action",
"{",
"case",
"Append",
":",
"case",
"Replace",
":",
"case",
"Set",
":",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"action",
")",
"\n",
"}",
"\n\n",
"switch",
"ruleType",
"{",
"case",
"\"",
"\"",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"4",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"//Check for variable option",
"if",
"strings",
".",
"HasPrefix",
"(",
"args",
"[",
"3",
"]",
",",
"\"",
"\"",
")",
"&&",
"strings",
".",
"HasSuffix",
"(",
"args",
"[",
"3",
"]",
",",
"\"",
"\"",
")",
"{",
"return",
"newEdns0VariableRule",
"(",
"mode",
",",
"action",
",",
"args",
"[",
"2",
"]",
",",
"args",
"[",
"3",
"]",
")",
"\n",
"}",
"\n",
"return",
"newEdns0LocalRule",
"(",
"mode",
",",
"action",
",",
"args",
"[",
"2",
"]",
",",
"args",
"[",
"3",
"]",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"edns0NsidRule",
"{",
"mode",
":",
"mode",
",",
"action",
":",
"action",
"}",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"4",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"newEdns0SubnetRule",
"(",
"mode",
",",
"action",
",",
"args",
"[",
"2",
"]",
",",
"args",
"[",
"3",
"]",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ruleType",
")",
"\n",
"}",
"\n",
"}"
] | // newEdns0Rule creates an EDNS0 rule of the appropriate type based on the args | [
"newEdns0Rule",
"creates",
"an",
"EDNS0",
"rule",
"of",
"the",
"appropriate",
"type",
"based",
"on",
"the",
"args"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L119-L157 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | newEdns0VariableRule | func newEdns0VariableRule(mode, action, code, variable string) (*edns0VariableRule, error) {
c, err := strconv.ParseUint(code, 0, 16)
if err != nil {
return nil, err
}
//Validate
if !isValidVariable(variable) {
return nil, fmt.Errorf("unsupported variable name %q", variable)
}
return &edns0VariableRule{mode: mode, action: action, code: uint16(c), variable: variable}, nil
} | go | func newEdns0VariableRule(mode, action, code, variable string) (*edns0VariableRule, error) {
c, err := strconv.ParseUint(code, 0, 16)
if err != nil {
return nil, err
}
//Validate
if !isValidVariable(variable) {
return nil, fmt.Errorf("unsupported variable name %q", variable)
}
return &edns0VariableRule{mode: mode, action: action, code: uint16(c), variable: variable}, nil
} | [
"func",
"newEdns0VariableRule",
"(",
"mode",
",",
"action",
",",
"code",
",",
"variable",
"string",
")",
"(",
"*",
"edns0VariableRule",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"code",
",",
"0",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"//Validate",
"if",
"!",
"isValidVariable",
"(",
"variable",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"variable",
")",
"\n",
"}",
"\n",
"return",
"&",
"edns0VariableRule",
"{",
"mode",
":",
"mode",
",",
"action",
":",
"action",
",",
"code",
":",
"uint16",
"(",
"c",
")",
",",
"variable",
":",
"variable",
"}",
",",
"nil",
"\n",
"}"
] | // newEdns0VariableRule creates an EDNS0 rule that handles variable substitution | [
"newEdns0VariableRule",
"creates",
"an",
"EDNS0",
"rule",
"that",
"handles",
"variable",
"substitution"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L176-L186 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | ruleData | func (rule *edns0VariableRule) ruleData(w dns.ResponseWriter, r *dns.Msg) ([]byte, error) {
req := request.Request{W: w, Req: r}
switch rule.variable {
case queryName:
//Query name is written as ascii string
return []byte(req.QName()), nil
case queryType:
return rule.uint16ToWire(req.QType()), nil
case clientIP:
return rule.ipToWire(req.Family(), req.IP())
case clientPort:
return rule.portToWire(req.Port())
case protocol:
// Proto is written as ascii string
return []byte(req.Proto()), nil
case serverIP:
ip, _, err := net.SplitHostPort(w.LocalAddr().String())
if err != nil {
ip = w.RemoteAddr().String()
}
return rule.ipToWire(rule.family(w.RemoteAddr()), ip)
case serverPort:
_, port, err := net.SplitHostPort(w.LocalAddr().String())
if err != nil {
port = "0"
}
return rule.portToWire(port)
}
return nil, fmt.Errorf("Unable to extract data for variable %s", rule.variable)
} | go | func (rule *edns0VariableRule) ruleData(w dns.ResponseWriter, r *dns.Msg) ([]byte, error) {
req := request.Request{W: w, Req: r}
switch rule.variable {
case queryName:
//Query name is written as ascii string
return []byte(req.QName()), nil
case queryType:
return rule.uint16ToWire(req.QType()), nil
case clientIP:
return rule.ipToWire(req.Family(), req.IP())
case clientPort:
return rule.portToWire(req.Port())
case protocol:
// Proto is written as ascii string
return []byte(req.Proto()), nil
case serverIP:
ip, _, err := net.SplitHostPort(w.LocalAddr().String())
if err != nil {
ip = w.RemoteAddr().String()
}
return rule.ipToWire(rule.family(w.RemoteAddr()), ip)
case serverPort:
_, port, err := net.SplitHostPort(w.LocalAddr().String())
if err != nil {
port = "0"
}
return rule.portToWire(port)
}
return nil, fmt.Errorf("Unable to extract data for variable %s", rule.variable)
} | [
"func",
"(",
"rule",
"*",
"edns0VariableRule",
")",
"ruleData",
"(",
"w",
"dns",
".",
"ResponseWriter",
",",
"r",
"*",
"dns",
".",
"Msg",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"req",
":=",
"request",
".",
"Request",
"{",
"W",
":",
"w",
",",
"Req",
":",
"r",
"}",
"\n",
"switch",
"rule",
".",
"variable",
"{",
"case",
"queryName",
":",
"//Query name is written as ascii string",
"return",
"[",
"]",
"byte",
"(",
"req",
".",
"QName",
"(",
")",
")",
",",
"nil",
"\n\n",
"case",
"queryType",
":",
"return",
"rule",
".",
"uint16ToWire",
"(",
"req",
".",
"QType",
"(",
")",
")",
",",
"nil",
"\n\n",
"case",
"clientIP",
":",
"return",
"rule",
".",
"ipToWire",
"(",
"req",
".",
"Family",
"(",
")",
",",
"req",
".",
"IP",
"(",
")",
")",
"\n\n",
"case",
"clientPort",
":",
"return",
"rule",
".",
"portToWire",
"(",
"req",
".",
"Port",
"(",
")",
")",
"\n\n",
"case",
"protocol",
":",
"// Proto is written as ascii string",
"return",
"[",
"]",
"byte",
"(",
"req",
".",
"Proto",
"(",
")",
")",
",",
"nil",
"\n\n",
"case",
"serverIP",
":",
"ip",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"w",
".",
"LocalAddr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ip",
"=",
"w",
".",
"RemoteAddr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"rule",
".",
"ipToWire",
"(",
"rule",
".",
"family",
"(",
"w",
".",
"RemoteAddr",
"(",
")",
")",
",",
"ip",
")",
"\n\n",
"case",
"serverPort",
":",
"_",
",",
"port",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"w",
".",
"LocalAddr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"port",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"rule",
".",
"portToWire",
"(",
"port",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rule",
".",
"variable",
")",
"\n",
"}"
] | // ruleData returns the data specified by the variable | [
"ruleData",
"returns",
"the",
"data",
"specified",
"by",
"the",
"variable"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L233-L270 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | fillEcsData | func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg,
ecs *dns.EDNS0_SUBNET) error {
req := request.Request{W: w, Req: r}
family := req.Family()
if (family != 1) && (family != 2) {
return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family")
}
ecs.Family = uint16(family)
ecs.SourceScope = 0
ipAddr := req.IP()
switch family {
case 1:
ipv4Mask := net.CIDRMask(int(rule.v4BitMaskLen), 32)
ipv4Addr := net.ParseIP(ipAddr)
ecs.SourceNetmask = rule.v4BitMaskLen
ecs.Address = ipv4Addr.Mask(ipv4Mask).To4()
case 2:
ipv6Mask := net.CIDRMask(int(rule.v6BitMaskLen), 128)
ipv6Addr := net.ParseIP(ipAddr)
ecs.SourceNetmask = rule.v6BitMaskLen
ecs.Address = ipv6Addr.Mask(ipv6Mask).To16()
}
return nil
} | go | func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg,
ecs *dns.EDNS0_SUBNET) error {
req := request.Request{W: w, Req: r}
family := req.Family()
if (family != 1) && (family != 2) {
return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family")
}
ecs.Family = uint16(family)
ecs.SourceScope = 0
ipAddr := req.IP()
switch family {
case 1:
ipv4Mask := net.CIDRMask(int(rule.v4BitMaskLen), 32)
ipv4Addr := net.ParseIP(ipAddr)
ecs.SourceNetmask = rule.v4BitMaskLen
ecs.Address = ipv4Addr.Mask(ipv4Mask).To4()
case 2:
ipv6Mask := net.CIDRMask(int(rule.v6BitMaskLen), 128)
ipv6Addr := net.ParseIP(ipAddr)
ecs.SourceNetmask = rule.v6BitMaskLen
ecs.Address = ipv6Addr.Mask(ipv6Mask).To16()
}
return nil
} | [
"func",
"(",
"rule",
"*",
"edns0SubnetRule",
")",
"fillEcsData",
"(",
"w",
"dns",
".",
"ResponseWriter",
",",
"r",
"*",
"dns",
".",
"Msg",
",",
"ecs",
"*",
"dns",
".",
"EDNS0_SUBNET",
")",
"error",
"{",
"req",
":=",
"request",
".",
"Request",
"{",
"W",
":",
"w",
",",
"Req",
":",
"r",
"}",
"\n",
"family",
":=",
"req",
".",
"Family",
"(",
")",
"\n",
"if",
"(",
"family",
"!=",
"1",
")",
"&&",
"(",
"family",
"!=",
"2",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ecs",
".",
"Family",
"=",
"uint16",
"(",
"family",
")",
"\n",
"ecs",
".",
"SourceScope",
"=",
"0",
"\n\n",
"ipAddr",
":=",
"req",
".",
"IP",
"(",
")",
"\n",
"switch",
"family",
"{",
"case",
"1",
":",
"ipv4Mask",
":=",
"net",
".",
"CIDRMask",
"(",
"int",
"(",
"rule",
".",
"v4BitMaskLen",
")",
",",
"32",
")",
"\n",
"ipv4Addr",
":=",
"net",
".",
"ParseIP",
"(",
"ipAddr",
")",
"\n",
"ecs",
".",
"SourceNetmask",
"=",
"rule",
".",
"v4BitMaskLen",
"\n",
"ecs",
".",
"Address",
"=",
"ipv4Addr",
".",
"Mask",
"(",
"ipv4Mask",
")",
".",
"To4",
"(",
")",
"\n",
"case",
"2",
":",
"ipv6Mask",
":=",
"net",
".",
"CIDRMask",
"(",
"int",
"(",
"rule",
".",
"v6BitMaskLen",
")",
",",
"128",
")",
"\n",
"ipv6Addr",
":=",
"net",
".",
"ParseIP",
"(",
"ipAddr",
")",
"\n",
"ecs",
".",
"SourceNetmask",
"=",
"rule",
".",
"v6BitMaskLen",
"\n",
"ecs",
".",
"Address",
"=",
"ipv6Addr",
".",
"Mask",
"(",
"ipv6Mask",
")",
".",
"To16",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // fillEcsData sets the subnet data into the ecs option | [
"fillEcsData",
"sets",
"the",
"subnet",
"data",
"into",
"the",
"ecs",
"option"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L362-L388 | train |
inverse-inc/packetfence | go/coredns/plugin/rewrite/edns0.go | Rewrite | func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option {
switch e := s.(type) {
case *dns.EDNS0_SUBNET:
if rule.action == Replace || rule.action == Set {
if rule.fillEcsData(w, r, e) == nil {
result = RewriteDone
}
}
found = true
break
}
}
// add option if not found
if !found && (rule.action == Append || rule.action == Set) {
o.SetDo()
opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET}
if rule.fillEcsData(w, r, &opt) == nil {
o.Option = append(o.Option, &opt)
result = RewriteDone
}
}
return result
} | go | func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option {
switch e := s.(type) {
case *dns.EDNS0_SUBNET:
if rule.action == Replace || rule.action == Set {
if rule.fillEcsData(w, r, e) == nil {
result = RewriteDone
}
}
found = true
break
}
}
// add option if not found
if !found && (rule.action == Append || rule.action == Set) {
o.SetDo()
opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET}
if rule.fillEcsData(w, r, &opt) == nil {
o.Option = append(o.Option, &opt)
result = RewriteDone
}
}
return result
} | [
"func",
"(",
"rule",
"*",
"edns0SubnetRule",
")",
"Rewrite",
"(",
"w",
"dns",
".",
"ResponseWriter",
",",
"r",
"*",
"dns",
".",
"Msg",
")",
"Result",
"{",
"result",
":=",
"RewriteIgnored",
"\n",
"o",
":=",
"setupEdns0Opt",
"(",
"r",
")",
"\n",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"o",
".",
"Option",
"{",
"switch",
"e",
":=",
"s",
".",
"(",
"type",
")",
"{",
"case",
"*",
"dns",
".",
"EDNS0_SUBNET",
":",
"if",
"rule",
".",
"action",
"==",
"Replace",
"||",
"rule",
".",
"action",
"==",
"Set",
"{",
"if",
"rule",
".",
"fillEcsData",
"(",
"w",
",",
"r",
",",
"e",
")",
"==",
"nil",
"{",
"result",
"=",
"RewriteDone",
"\n",
"}",
"\n",
"}",
"\n",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// add option if not found",
"if",
"!",
"found",
"&&",
"(",
"rule",
".",
"action",
"==",
"Append",
"||",
"rule",
".",
"action",
"==",
"Set",
")",
"{",
"o",
".",
"SetDo",
"(",
")",
"\n",
"opt",
":=",
"dns",
".",
"EDNS0_SUBNET",
"{",
"Code",
":",
"dns",
".",
"EDNS0SUBNET",
"}",
"\n",
"if",
"rule",
".",
"fillEcsData",
"(",
"w",
",",
"r",
",",
"&",
"opt",
")",
"==",
"nil",
"{",
"o",
".",
"Option",
"=",
"append",
"(",
"o",
".",
"Option",
",",
"&",
"opt",
")",
"\n",
"result",
"=",
"RewriteDone",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // Rewrite will alter the request EDNS0 subnet option | [
"Rewrite",
"will",
"alter",
"the",
"request",
"EDNS0",
"subnet",
"option"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L391-L419 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | setup | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
pfsso, err := buildPfssoHandler(ctx)
if err != nil {
return err
}
// Declare all pfconfig resources that will be necessary
pfconfigdriver.PfconfigPool.AddRefreshable(ctx, &firewallsso.Firewalls)
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Interfaces.ManagementNetwork)
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
pfsso.Next = next
return pfsso
})
return nil
} | go | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
pfsso, err := buildPfssoHandler(ctx)
if err != nil {
return err
}
// Declare all pfconfig resources that will be necessary
pfconfigdriver.PfconfigPool.AddRefreshable(ctx, &firewallsso.Firewalls)
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Interfaces.ManagementNetwork)
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
pfsso.Next = next
return pfsso
})
return nil
} | [
"func",
"setup",
"(",
"c",
"*",
"caddy",
".",
"Controller",
")",
"error",
"{",
"ctx",
":=",
"log",
".",
"LoggerNewContext",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n\n",
"pfsso",
",",
"err",
":=",
"buildPfssoHandler",
"(",
"ctx",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Declare all pfconfig resources that will be necessary",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddRefreshable",
"(",
"ctx",
",",
"&",
"firewallsso",
".",
"Firewalls",
")",
"\n",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddStruct",
"(",
"ctx",
",",
"&",
"pfconfigdriver",
".",
"Config",
".",
"Interfaces",
".",
"ManagementNetwork",
")",
"\n\n",
"httpserver",
".",
"GetConfig",
"(",
"c",
")",
".",
"AddMiddleware",
"(",
"func",
"(",
"next",
"httpserver",
".",
"Handler",
")",
"httpserver",
".",
"Handler",
"{",
"pfsso",
".",
"Next",
"=",
"next",
"\n",
"return",
"pfsso",
"\n",
"}",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup the pfsso middleware
// Also loads the pfconfig resources and registers them in the pool | [
"Setup",
"the",
"pfsso",
"middleware",
"Also",
"loads",
"the",
"pfconfig",
"resources",
"and",
"registers",
"them",
"in",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L41-L60 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | buildPfssoHandler | func buildPfssoHandler(ctx context.Context) (PfssoHandler, error) {
pfsso := PfssoHandler{}
pfsso.updateCache = cache.New(1*time.Hour, 30*time.Second)
router := httprouter.New()
router.POST("/api/v1/firewall_sso/update", pfsso.handleUpdate)
router.POST("/api/v1/firewall_sso/start", pfsso.handleStart)
router.POST("/api/v1/firewall_sso/stop", pfsso.handleStop)
pfsso.router = router
return pfsso, nil
} | go | func buildPfssoHandler(ctx context.Context) (PfssoHandler, error) {
pfsso := PfssoHandler{}
pfsso.updateCache = cache.New(1*time.Hour, 30*time.Second)
router := httprouter.New()
router.POST("/api/v1/firewall_sso/update", pfsso.handleUpdate)
router.POST("/api/v1/firewall_sso/start", pfsso.handleStart)
router.POST("/api/v1/firewall_sso/stop", pfsso.handleStop)
pfsso.router = router
return pfsso, nil
} | [
"func",
"buildPfssoHandler",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"PfssoHandler",
",",
"error",
")",
"{",
"pfsso",
":=",
"PfssoHandler",
"{",
"}",
"\n\n",
"pfsso",
".",
"updateCache",
"=",
"cache",
".",
"New",
"(",
"1",
"*",
"time",
".",
"Hour",
",",
"30",
"*",
"time",
".",
"Second",
")",
"\n\n",
"router",
":=",
"httprouter",
".",
"New",
"(",
")",
"\n",
"router",
".",
"POST",
"(",
"\"",
"\"",
",",
"pfsso",
".",
"handleUpdate",
")",
"\n",
"router",
".",
"POST",
"(",
"\"",
"\"",
",",
"pfsso",
".",
"handleStart",
")",
"\n",
"router",
".",
"POST",
"(",
"\"",
"\"",
",",
"pfsso",
".",
"handleStop",
")",
"\n\n",
"pfsso",
".",
"router",
"=",
"router",
"\n\n",
"return",
"pfsso",
",",
"nil",
"\n",
"}"
] | // Build the PfssoHandler which will initialize the cache and instantiate the router along with its routes | [
"Build",
"the",
"PfssoHandler",
"which",
"will",
"initialize",
"the",
"cache",
"and",
"instantiate",
"the",
"router",
"along",
"with",
"its",
"routes"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L63-L77 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | validateInfo | func (h PfssoHandler) validateInfo(ctx context.Context, info map[string]string) error {
required := []string{"ip", "mac", "username", "role"}
for _, k := range required {
if _, ok := info[k]; !ok {
return errors.New(fmt.Sprintf("Missing %s in request", k))
}
}
return nil
} | go | func (h PfssoHandler) validateInfo(ctx context.Context, info map[string]string) error {
required := []string{"ip", "mac", "username", "role"}
for _, k := range required {
if _, ok := info[k]; !ok {
return errors.New(fmt.Sprintf("Missing %s in request", k))
}
}
return nil
} | [
"func",
"(",
"h",
"PfssoHandler",
")",
"validateInfo",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"required",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"required",
"{",
"if",
"_",
",",
"ok",
":=",
"info",
"[",
"k",
"]",
";",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate that all the required fields are there in the request | [
"Validate",
"that",
"all",
"the",
"required",
"fields",
"are",
"there",
"in",
"the",
"request"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L110-L118 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | spawnSso | func (h PfssoHandler) spawnSso(ctx context.Context, firewall firewallsso.FirewallSSOInt, info map[string]string, f func(info map[string]string) (bool, error)) {
// Perform a copy of the information hash before spawning the goroutine
infoCopy := map[string]string{}
for k, v := range info {
infoCopy[k] = v
}
go func() {
defer panichandler.Standard(ctx)
sent, err := f(infoCopy)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Error while sending SSO to %s: %s"+firewall.GetFirewallSSO(ctx).PfconfigHashNS, err))
}
if sent {
log.LoggerWContext(ctx).Debug("Sent SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS)
} else {
log.LoggerWContext(ctx).Debug("Didn't send SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS)
}
}()
} | go | func (h PfssoHandler) spawnSso(ctx context.Context, firewall firewallsso.FirewallSSOInt, info map[string]string, f func(info map[string]string) (bool, error)) {
// Perform a copy of the information hash before spawning the goroutine
infoCopy := map[string]string{}
for k, v := range info {
infoCopy[k] = v
}
go func() {
defer panichandler.Standard(ctx)
sent, err := f(infoCopy)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Error while sending SSO to %s: %s"+firewall.GetFirewallSSO(ctx).PfconfigHashNS, err))
}
if sent {
log.LoggerWContext(ctx).Debug("Sent SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS)
} else {
log.LoggerWContext(ctx).Debug("Didn't send SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS)
}
}()
} | [
"func",
"(",
"h",
"PfssoHandler",
")",
"spawnSso",
"(",
"ctx",
"context",
".",
"Context",
",",
"firewall",
"firewallsso",
".",
"FirewallSSOInt",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"f",
"func",
"(",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
")",
"{",
"// Perform a copy of the information hash before spawning the goroutine",
"infoCopy",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"info",
"{",
"infoCopy",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"defer",
"panichandler",
".",
"Standard",
"(",
"ctx",
")",
"\n",
"sent",
",",
"err",
":=",
"f",
"(",
"infoCopy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
",",
"err",
")",
")",
"\n",
"}",
"\n\n",
"if",
"sent",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
"+",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
"+",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // Spawn an async SSO request for a specific firewall | [
"Spawn",
"an",
"async",
"SSO",
"request",
"for",
"a",
"specific",
"firewall"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L121-L141 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | addInfoToContext | func (h PfssoHandler) addInfoToContext(ctx context.Context, info map[string]string) context.Context {
return log.AddToLogContext(ctx, "username", info["username"], "ip", info["ip"], "mac", info["mac"], "role", info["role"])
} | go | func (h PfssoHandler) addInfoToContext(ctx context.Context, info map[string]string) context.Context {
return log.AddToLogContext(ctx, "username", info["username"], "ip", info["ip"], "mac", info["mac"], "role", info["role"])
} | [
"func",
"(",
"h",
"PfssoHandler",
")",
"addInfoToContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"log",
".",
"AddToLogContext",
"(",
"ctx",
",",
"\"",
"\"",
",",
"info",
"[",
"\"",
"\"",
"]",
",",
"\"",
"\"",
",",
"info",
"[",
"\"",
"\"",
"]",
",",
"\"",
"\"",
",",
"info",
"[",
"\"",
"\"",
"]",
",",
"\"",
"\"",
",",
"info",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}"
] | // Add the info in the request to the log context | [
"Add",
"the",
"info",
"in",
"the",
"request",
"to",
"the",
"log",
"context"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L144-L146 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | handleUpdate | func (h PfssoHandler) handleUpdate(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleUpdate")
info, timeout, err := h.parseSsoRequest(ctx, r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
ctx = h.addInfoToContext(ctx, info)
var shouldStart bool
for _, firewall := range firewallsso.Firewalls.Structs {
cacheKey := firewall.GetFirewallSSO(ctx).PfconfigHashNS + "|ip|" + info["ip"] + "|username|" + info["username"] + "|role|" + info["role"]
// Check whether or not this firewall has cache updates
// Then check if an entry in the cache exists
// If it does exist, we don't send a Start
// Otherwise, we add an entry in the cache
// Note that this has a race condition between the cache.Get and the cache.Set but it is acceptable since worst case will be that 2 SSO will be sent if both requests came in at that same nanosecond
if firewall.ShouldCacheUpdates(ctx) {
if _, found := h.updateCache.Get(cacheKey); !found {
var cacheTimeout int
if firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx) != 0 {
cacheTimeout = firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx)
} else if timeout != 0 {
cacheTimeout = timeout / 2
} else {
log.LoggerWContext(ctx).Error("Impossible to cache updates. There is no cache timeout in the firewall and no timeout defined in the request.")
}
if cacheTimeout != 0 {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Caching SSO for %d seconds", cacheTimeout))
h.updateCache.Set(cacheKey, 1, time.Duration(cacheTimeout)*time.Second)
}
shouldStart = true
}
} else {
shouldStart = true
}
if shouldStart {
//Creating a shallow copy here so the anonymous function has the right reference
firewall := firewall
h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) {
return firewallsso.ExecuteStart(ctx, firewall, info, timeout)
})
} else {
log.LoggerWContext(ctx).Debug("Determined that SSO start was not necessary for this update")
}
}
w.WriteHeader(http.StatusAccepted)
} | go | func (h PfssoHandler) handleUpdate(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleUpdate")
info, timeout, err := h.parseSsoRequest(ctx, r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
ctx = h.addInfoToContext(ctx, info)
var shouldStart bool
for _, firewall := range firewallsso.Firewalls.Structs {
cacheKey := firewall.GetFirewallSSO(ctx).PfconfigHashNS + "|ip|" + info["ip"] + "|username|" + info["username"] + "|role|" + info["role"]
// Check whether or not this firewall has cache updates
// Then check if an entry in the cache exists
// If it does exist, we don't send a Start
// Otherwise, we add an entry in the cache
// Note that this has a race condition between the cache.Get and the cache.Set but it is acceptable since worst case will be that 2 SSO will be sent if both requests came in at that same nanosecond
if firewall.ShouldCacheUpdates(ctx) {
if _, found := h.updateCache.Get(cacheKey); !found {
var cacheTimeout int
if firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx) != 0 {
cacheTimeout = firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx)
} else if timeout != 0 {
cacheTimeout = timeout / 2
} else {
log.LoggerWContext(ctx).Error("Impossible to cache updates. There is no cache timeout in the firewall and no timeout defined in the request.")
}
if cacheTimeout != 0 {
log.LoggerWContext(ctx).Debug(fmt.Sprintf("Caching SSO for %d seconds", cacheTimeout))
h.updateCache.Set(cacheKey, 1, time.Duration(cacheTimeout)*time.Second)
}
shouldStart = true
}
} else {
shouldStart = true
}
if shouldStart {
//Creating a shallow copy here so the anonymous function has the right reference
firewall := firewall
h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) {
return firewallsso.ExecuteStart(ctx, firewall, info, timeout)
})
} else {
log.LoggerWContext(ctx).Debug("Determined that SSO start was not necessary for this update")
}
}
w.WriteHeader(http.StatusAccepted)
} | [
"func",
"(",
"h",
"PfssoHandler",
")",
"handleUpdate",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"p",
"httprouter",
".",
"Params",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"defer",
"statsd",
".",
"NewStatsDTiming",
"(",
"ctx",
")",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n\n",
"info",
",",
"timeout",
",",
"err",
":=",
"h",
".",
"parseSsoRequest",
"(",
"ctx",
",",
"r",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ctx",
"=",
"h",
".",
"addInfoToContext",
"(",
"ctx",
",",
"info",
")",
"\n\n",
"var",
"shouldStart",
"bool",
"\n",
"for",
"_",
",",
"firewall",
":=",
"range",
"firewallsso",
".",
"Firewalls",
".",
"Structs",
"{",
"cacheKey",
":=",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"PfconfigHashNS",
"+",
"\"",
"\"",
"+",
"info",
"[",
"\"",
"\"",
"]",
"+",
"\"",
"\"",
"+",
"info",
"[",
"\"",
"\"",
"]",
"+",
"\"",
"\"",
"+",
"info",
"[",
"\"",
"\"",
"]",
"\n",
"// Check whether or not this firewall has cache updates",
"// Then check if an entry in the cache exists",
"// If it does exist, we don't send a Start",
"// Otherwise, we add an entry in the cache",
"// Note that this has a race condition between the cache.Get and the cache.Set but it is acceptable since worst case will be that 2 SSO will be sent if both requests came in at that same nanosecond",
"if",
"firewall",
".",
"ShouldCacheUpdates",
"(",
"ctx",
")",
"{",
"if",
"_",
",",
"found",
":=",
"h",
".",
"updateCache",
".",
"Get",
"(",
"cacheKey",
")",
";",
"!",
"found",
"{",
"var",
"cacheTimeout",
"int",
"\n",
"if",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"GetCacheTimeout",
"(",
"ctx",
")",
"!=",
"0",
"{",
"cacheTimeout",
"=",
"firewall",
".",
"GetFirewallSSO",
"(",
"ctx",
")",
".",
"GetCacheTimeout",
"(",
"ctx",
")",
"\n",
"}",
"else",
"if",
"timeout",
"!=",
"0",
"{",
"cacheTimeout",
"=",
"timeout",
"/",
"2",
"\n",
"}",
"else",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"cacheTimeout",
"!=",
"0",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cacheTimeout",
")",
")",
"\n",
"h",
".",
"updateCache",
".",
"Set",
"(",
"cacheKey",
",",
"1",
",",
"time",
".",
"Duration",
"(",
"cacheTimeout",
")",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n\n",
"shouldStart",
"=",
"true",
"\n",
"}",
"\n",
"}",
"else",
"{",
"shouldStart",
"=",
"true",
"\n",
"}",
"\n\n",
"if",
"shouldStart",
"{",
"//Creating a shallow copy here so the anonymous function has the right reference",
"firewall",
":=",
"firewall",
"\n",
"h",
".",
"spawnSso",
"(",
"ctx",
",",
"firewall",
",",
"info",
",",
"func",
"(",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"firewallsso",
".",
"ExecuteStart",
"(",
"ctx",
",",
"firewall",
",",
"info",
",",
"timeout",
")",
"\n",
"}",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusAccepted",
")",
"\n",
"}"
] | // Handle an update action for pfsso
// If the firewall has cached updates enabled, it will handle it here
// The cache is in-memory so that means that a restart of the process will clear the cached updates cache | [
"Handle",
"an",
"update",
"action",
"for",
"pfsso",
"If",
"the",
"firewall",
"has",
"cached",
"updates",
"enabled",
"it",
"will",
"handle",
"it",
"here",
"The",
"cache",
"is",
"in",
"-",
"memory",
"so",
"that",
"means",
"that",
"a",
"restart",
"of",
"the",
"process",
"will",
"clear",
"the",
"cached",
"updates",
"cache"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L151-L207 | train |
inverse-inc/packetfence | go/caddy/pfsso/pfsso.go | handleStop | func (h PfssoHandler) handleStop(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleStop")
info, _, err := h.parseSsoRequest(ctx, r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
ctx = h.addInfoToContext(ctx, info)
for _, firewall := range firewallsso.Firewalls.Structs {
//Creating a shallow copy here so the anonymous function has the right reference
firewall := firewall
h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) {
return firewallsso.ExecuteStop(ctx, firewall, info)
})
}
w.WriteHeader(http.StatusAccepted)
} | go | func (h PfssoHandler) handleStop(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleStop")
info, _, err := h.parseSsoRequest(ctx, r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
ctx = h.addInfoToContext(ctx, info)
for _, firewall := range firewallsso.Firewalls.Structs {
//Creating a shallow copy here so the anonymous function has the right reference
firewall := firewall
h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) {
return firewallsso.ExecuteStop(ctx, firewall, info)
})
}
w.WriteHeader(http.StatusAccepted)
} | [
"func",
"(",
"h",
"PfssoHandler",
")",
"handleStop",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"p",
"httprouter",
".",
"Params",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"defer",
"statsd",
".",
"NewStatsDTiming",
"(",
"ctx",
")",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n\n",
"info",
",",
"_",
",",
"err",
":=",
"h",
".",
"parseSsoRequest",
"(",
"ctx",
",",
"r",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ctx",
"=",
"h",
".",
"addInfoToContext",
"(",
"ctx",
",",
"info",
")",
"\n\n",
"for",
"_",
",",
"firewall",
":=",
"range",
"firewallsso",
".",
"Firewalls",
".",
"Structs",
"{",
"//Creating a shallow copy here so the anonymous function has the right reference",
"firewall",
":=",
"firewall",
"\n",
"h",
".",
"spawnSso",
"(",
"ctx",
",",
"firewall",
",",
"info",
",",
"func",
"(",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"firewallsso",
".",
"ExecuteStop",
"(",
"ctx",
",",
"firewall",
",",
"info",
")",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusAccepted",
")",
"\n",
"}"
] | // Handle an SSO stop | [
"Handle",
"an",
"SSO",
"stop"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L234-L255 | train |
inverse-inc/packetfence | go/coredns/plugin/hosts/hosts.go | a | func a(zone string, ips []net.IP) []dns.RR {
answers := []dns.RR{}
for _, ip := range ips {
r := new(dns.A)
r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeA,
Class: dns.ClassINET, Ttl: 3600}
r.A = ip
answers = append(answers, r)
}
return answers
} | go | func a(zone string, ips []net.IP) []dns.RR {
answers := []dns.RR{}
for _, ip := range ips {
r := new(dns.A)
r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeA,
Class: dns.ClassINET, Ttl: 3600}
r.A = ip
answers = append(answers, r)
}
return answers
} | [
"func",
"a",
"(",
"zone",
"string",
",",
"ips",
"[",
"]",
"net",
".",
"IP",
")",
"[",
"]",
"dns",
".",
"RR",
"{",
"answers",
":=",
"[",
"]",
"dns",
".",
"RR",
"{",
"}",
"\n",
"for",
"_",
",",
"ip",
":=",
"range",
"ips",
"{",
"r",
":=",
"new",
"(",
"dns",
".",
"A",
")",
"\n",
"r",
".",
"Hdr",
"=",
"dns",
".",
"RR_Header",
"{",
"Name",
":",
"zone",
",",
"Rrtype",
":",
"dns",
".",
"TypeA",
",",
"Class",
":",
"dns",
".",
"ClassINET",
",",
"Ttl",
":",
"3600",
"}",
"\n",
"r",
".",
"A",
"=",
"ip",
"\n",
"answers",
"=",
"append",
"(",
"answers",
",",
"r",
")",
"\n",
"}",
"\n",
"return",
"answers",
"\n",
"}"
] | // a takes a slice of net.IPs and returns a slice of A RRs. | [
"a",
"takes",
"a",
"slice",
"of",
"net",
".",
"IPs",
"and",
"returns",
"a",
"slice",
"of",
"A",
"RRs",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/hosts/hosts.go#L100-L110 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | NewFileStorage | func NewFileStorage(caURL *url.URL) (Storage, error) {
return &FileStorage{
Path: filepath.Join(storageBasePath, caURL.Host),
nameLocks: make(map[string]*sync.WaitGroup),
}, nil
} | go | func NewFileStorage(caURL *url.URL) (Storage, error) {
return &FileStorage{
Path: filepath.Join(storageBasePath, caURL.Host),
nameLocks: make(map[string]*sync.WaitGroup),
}, nil
} | [
"func",
"NewFileStorage",
"(",
"caURL",
"*",
"url",
".",
"URL",
")",
"(",
"Storage",
",",
"error",
")",
"{",
"return",
"&",
"FileStorage",
"{",
"Path",
":",
"filepath",
".",
"Join",
"(",
"storageBasePath",
",",
"caURL",
".",
"Host",
")",
",",
"nameLocks",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"sync",
".",
"WaitGroup",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewFileStorage is a StorageConstructor function that creates a new
// Storage instance backed by the local disk. The resulting Storage
// instance is guaranteed to be non-nil if there is no error. | [
"NewFileStorage",
"is",
"a",
"StorageConstructor",
"function",
"that",
"creates",
"a",
"new",
"Storage",
"instance",
"backed",
"by",
"the",
"local",
"disk",
".",
"The",
"resulting",
"Storage",
"instance",
"is",
"guaranteed",
"to",
"be",
"non",
"-",
"nil",
"if",
"there",
"is",
"no",
"error",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L26-L31 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | site | func (s *FileStorage) site(domain string) string {
domain = strings.ToLower(domain)
return filepath.Join(s.sites(), domain)
} | go | func (s *FileStorage) site(domain string) string {
domain = strings.ToLower(domain)
return filepath.Join(s.sites(), domain)
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"site",
"(",
"domain",
"string",
")",
"string",
"{",
"domain",
"=",
"strings",
".",
"ToLower",
"(",
"domain",
")",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"s",
".",
"sites",
"(",
")",
",",
"domain",
")",
"\n",
"}"
] | // site returns the path to the folder containing assets for domain. | [
"site",
"returns",
"the",
"path",
"to",
"the",
"folder",
"containing",
"assets",
"for",
"domain",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L48-L51 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | user | func (s *FileStorage) user(email string) string {
if email == "" {
email = emptyEmail
}
email = strings.ToLower(email)
return filepath.Join(s.users(), email)
} | go | func (s *FileStorage) user(email string) string {
if email == "" {
email = emptyEmail
}
email = strings.ToLower(email)
return filepath.Join(s.users(), email)
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"user",
"(",
"email",
"string",
")",
"string",
"{",
"if",
"email",
"==",
"\"",
"\"",
"{",
"email",
"=",
"emptyEmail",
"\n",
"}",
"\n",
"email",
"=",
"strings",
".",
"ToLower",
"(",
"email",
")",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"s",
".",
"users",
"(",
")",
",",
"email",
")",
"\n",
"}"
] | // user gets the account folder for the user with email | [
"user",
"gets",
"the",
"account",
"folder",
"for",
"the",
"user",
"with",
"email"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L77-L83 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | emailUsername | func emailUsername(email string) string {
at := strings.Index(email, "@")
if at == -1 {
return email
} else if at == 0 {
return email[1:]
}
return email[:at]
} | go | func emailUsername(email string) string {
at := strings.Index(email, "@")
if at == -1 {
return email
} else if at == 0 {
return email[1:]
}
return email[:at]
} | [
"func",
"emailUsername",
"(",
"email",
"string",
")",
"string",
"{",
"at",
":=",
"strings",
".",
"Index",
"(",
"email",
",",
"\"",
"\"",
")",
"\n",
"if",
"at",
"==",
"-",
"1",
"{",
"return",
"email",
"\n",
"}",
"else",
"if",
"at",
"==",
"0",
"{",
"return",
"email",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"email",
"[",
":",
"at",
"]",
"\n",
"}"
] | // emailUsername returns the username portion of an email address (part before
// '@') or the original input if it can't find the "@" symbol. | [
"emailUsername",
"returns",
"the",
"username",
"portion",
"of",
"an",
"email",
"address",
"(",
"part",
"before"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L87-L95 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | userRegFile | func (s *FileStorage) userRegFile(email string) string {
if email == "" {
email = emptyEmail
}
email = strings.ToLower(email)
fileName := emailUsername(email)
if fileName == "" {
fileName = "registration"
}
return filepath.Join(s.user(email), fileName+".json")
} | go | func (s *FileStorage) userRegFile(email string) string {
if email == "" {
email = emptyEmail
}
email = strings.ToLower(email)
fileName := emailUsername(email)
if fileName == "" {
fileName = "registration"
}
return filepath.Join(s.user(email), fileName+".json")
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"userRegFile",
"(",
"email",
"string",
")",
"string",
"{",
"if",
"email",
"==",
"\"",
"\"",
"{",
"email",
"=",
"emptyEmail",
"\n",
"}",
"\n",
"email",
"=",
"strings",
".",
"ToLower",
"(",
"email",
")",
"\n",
"fileName",
":=",
"emailUsername",
"(",
"email",
")",
"\n",
"if",
"fileName",
"==",
"\"",
"\"",
"{",
"fileName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"s",
".",
"user",
"(",
"email",
")",
",",
"fileName",
"+",
"\"",
"\"",
")",
"\n",
"}"
] | // userRegFile gets the path to the registration file for the user with the
// given email address. | [
"userRegFile",
"gets",
"the",
"path",
"to",
"the",
"registration",
"file",
"for",
"the",
"user",
"with",
"the",
"given",
"email",
"address",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L99-L109 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | readFile | func (s *FileStorage) readFile(file string) ([]byte, error) {
b, err := ioutil.ReadFile(file)
if os.IsNotExist(err) {
return nil, ErrNotExist(err)
}
return b, err
} | go | func (s *FileStorage) readFile(file string) ([]byte, error) {
b, err := ioutil.ReadFile(file)
if os.IsNotExist(err) {
return nil, ErrNotExist(err)
}
return b, err
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"readFile",
"(",
"file",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"file",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"ErrNotExist",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"b",
",",
"err",
"\n",
"}"
] | // readFile abstracts a simple ioutil.ReadFile, making sure to return an
// ErrNotExist instance when the file is not found. | [
"readFile",
"abstracts",
"a",
"simple",
"ioutil",
".",
"ReadFile",
"making",
"sure",
"to",
"return",
"an",
"ErrNotExist",
"instance",
"when",
"the",
"file",
"is",
"not",
"found",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L127-L133 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | SiteExists | func (s *FileStorage) SiteExists(domain string) (bool, error) {
_, err := os.Stat(s.siteCertFile(domain))
if os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
_, err = os.Stat(s.siteKeyFile(domain))
if err != nil {
return false, err
}
return true, nil
} | go | func (s *FileStorage) SiteExists(domain string) (bool, error) {
_, err := os.Stat(s.siteCertFile(domain))
if os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
_, err = os.Stat(s.siteKeyFile(domain))
if err != nil {
return false, err
}
return true, nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"SiteExists",
"(",
"domain",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"s",
".",
"siteCertFile",
"(",
"domain",
")",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"s",
".",
"siteKeyFile",
"(",
"domain",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // SiteExists implements Storage.SiteExists by checking for the presence of
// cert and key files. | [
"SiteExists",
"implements",
"Storage",
".",
"SiteExists",
"by",
"checking",
"for",
"the",
"presence",
"of",
"cert",
"and",
"key",
"files",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L137-L150 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | LoadSite | func (s *FileStorage) LoadSite(domain string) (*SiteData, error) {
var err error
siteData := new(SiteData)
siteData.Cert, err = s.readFile(s.siteCertFile(domain))
if err != nil {
return nil, err
}
siteData.Key, err = s.readFile(s.siteKeyFile(domain))
if err != nil {
return nil, err
}
siteData.Meta, err = s.readFile(s.siteMetaFile(domain))
if err != nil {
return nil, err
}
return siteData, nil
} | go | func (s *FileStorage) LoadSite(domain string) (*SiteData, error) {
var err error
siteData := new(SiteData)
siteData.Cert, err = s.readFile(s.siteCertFile(domain))
if err != nil {
return nil, err
}
siteData.Key, err = s.readFile(s.siteKeyFile(domain))
if err != nil {
return nil, err
}
siteData.Meta, err = s.readFile(s.siteMetaFile(domain))
if err != nil {
return nil, err
}
return siteData, nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"LoadSite",
"(",
"domain",
"string",
")",
"(",
"*",
"SiteData",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"siteData",
":=",
"new",
"(",
"SiteData",
")",
"\n",
"siteData",
".",
"Cert",
",",
"err",
"=",
"s",
".",
"readFile",
"(",
"s",
".",
"siteCertFile",
"(",
"domain",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"siteData",
".",
"Key",
",",
"err",
"=",
"s",
".",
"readFile",
"(",
"s",
".",
"siteKeyFile",
"(",
"domain",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"siteData",
".",
"Meta",
",",
"err",
"=",
"s",
".",
"readFile",
"(",
"s",
".",
"siteMetaFile",
"(",
"domain",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"siteData",
",",
"nil",
"\n",
"}"
] | // LoadSite implements Storage.LoadSite by loading it from disk. If it is not
// present, an instance of ErrNotExist is returned. | [
"LoadSite",
"implements",
"Storage",
".",
"LoadSite",
"by",
"loading",
"it",
"from",
"disk",
".",
"If",
"it",
"is",
"not",
"present",
"an",
"instance",
"of",
"ErrNotExist",
"is",
"returned",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L154-L170 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | StoreSite | func (s *FileStorage) StoreSite(domain string, data *SiteData) error {
err := os.MkdirAll(s.site(domain), 0700)
if err != nil {
return fmt.Errorf("making site directory: %v", err)
}
err = ioutil.WriteFile(s.siteCertFile(domain), data.Cert, 0600)
if err != nil {
return fmt.Errorf("writing certificate file: %v", err)
}
err = ioutil.WriteFile(s.siteKeyFile(domain), data.Key, 0600)
if err != nil {
return fmt.Errorf("writing key file: %v", err)
}
err = ioutil.WriteFile(s.siteMetaFile(domain), data.Meta, 0600)
if err != nil {
return fmt.Errorf("writing cert meta file: %v", err)
}
return nil
} | go | func (s *FileStorage) StoreSite(domain string, data *SiteData) error {
err := os.MkdirAll(s.site(domain), 0700)
if err != nil {
return fmt.Errorf("making site directory: %v", err)
}
err = ioutil.WriteFile(s.siteCertFile(domain), data.Cert, 0600)
if err != nil {
return fmt.Errorf("writing certificate file: %v", err)
}
err = ioutil.WriteFile(s.siteKeyFile(domain), data.Key, 0600)
if err != nil {
return fmt.Errorf("writing key file: %v", err)
}
err = ioutil.WriteFile(s.siteMetaFile(domain), data.Meta, 0600)
if err != nil {
return fmt.Errorf("writing cert meta file: %v", err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"StoreSite",
"(",
"domain",
"string",
",",
"data",
"*",
"SiteData",
")",
"error",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"s",
".",
"site",
"(",
"domain",
")",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"s",
".",
"siteCertFile",
"(",
"domain",
")",
",",
"data",
".",
"Cert",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"s",
".",
"siteKeyFile",
"(",
"domain",
")",
",",
"data",
".",
"Key",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"s",
".",
"siteMetaFile",
"(",
"domain",
")",
",",
"data",
".",
"Meta",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // StoreSite implements Storage.StoreSite by writing it to disk. The base
// directories needed for the file are automatically created as needed. | [
"StoreSite",
"implements",
"Storage",
".",
"StoreSite",
"by",
"writing",
"it",
"to",
"disk",
".",
"The",
"base",
"directories",
"needed",
"for",
"the",
"file",
"are",
"automatically",
"created",
"as",
"needed",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L174-L192 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | DeleteSite | func (s *FileStorage) DeleteSite(domain string) error {
err := os.Remove(s.siteCertFile(domain))
if err != nil {
if os.IsNotExist(err) {
return ErrNotExist(err)
}
return err
}
return nil
} | go | func (s *FileStorage) DeleteSite(domain string) error {
err := os.Remove(s.siteCertFile(domain))
if err != nil {
if os.IsNotExist(err) {
return ErrNotExist(err)
}
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"DeleteSite",
"(",
"domain",
"string",
")",
"error",
"{",
"err",
":=",
"os",
".",
"Remove",
"(",
"s",
".",
"siteCertFile",
"(",
"domain",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"ErrNotExist",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteSite implements Storage.DeleteSite by deleting just the cert from
// disk. If it is not present, an instance of ErrNotExist is returned. | [
"DeleteSite",
"implements",
"Storage",
".",
"DeleteSite",
"by",
"deleting",
"just",
"the",
"cert",
"from",
"disk",
".",
"If",
"it",
"is",
"not",
"present",
"an",
"instance",
"of",
"ErrNotExist",
"is",
"returned",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L196-L205 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | LoadUser | func (s *FileStorage) LoadUser(email string) (*UserData, error) {
var err error
userData := new(UserData)
userData.Reg, err = s.readFile(s.userRegFile(email))
if err != nil {
return nil, err
}
userData.Key, err = s.readFile(s.userKeyFile(email))
if err != nil {
return nil, err
}
return userData, nil
} | go | func (s *FileStorage) LoadUser(email string) (*UserData, error) {
var err error
userData := new(UserData)
userData.Reg, err = s.readFile(s.userRegFile(email))
if err != nil {
return nil, err
}
userData.Key, err = s.readFile(s.userKeyFile(email))
if err != nil {
return nil, err
}
return userData, nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"LoadUser",
"(",
"email",
"string",
")",
"(",
"*",
"UserData",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"userData",
":=",
"new",
"(",
"UserData",
")",
"\n",
"userData",
".",
"Reg",
",",
"err",
"=",
"s",
".",
"readFile",
"(",
"s",
".",
"userRegFile",
"(",
"email",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"userData",
".",
"Key",
",",
"err",
"=",
"s",
".",
"readFile",
"(",
"s",
".",
"userKeyFile",
"(",
"email",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"userData",
",",
"nil",
"\n",
"}"
] | // LoadUser implements Storage.LoadUser by loading it from disk. If it is not
// present, an instance of ErrNotExist is returned. | [
"LoadUser",
"implements",
"Storage",
".",
"LoadUser",
"by",
"loading",
"it",
"from",
"disk",
".",
"If",
"it",
"is",
"not",
"present",
"an",
"instance",
"of",
"ErrNotExist",
"is",
"returned",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L209-L221 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | StoreUser | func (s *FileStorage) StoreUser(email string, data *UserData) error {
err := os.MkdirAll(s.user(email), 0700)
if err != nil {
return fmt.Errorf("making user directory: %v", err)
}
err = ioutil.WriteFile(s.userRegFile(email), data.Reg, 0600)
if err != nil {
return fmt.Errorf("writing user registration file: %v", err)
}
err = ioutil.WriteFile(s.userKeyFile(email), data.Key, 0600)
if err != nil {
return fmt.Errorf("writing user key file: %v", err)
}
return nil
} | go | func (s *FileStorage) StoreUser(email string, data *UserData) error {
err := os.MkdirAll(s.user(email), 0700)
if err != nil {
return fmt.Errorf("making user directory: %v", err)
}
err = ioutil.WriteFile(s.userRegFile(email), data.Reg, 0600)
if err != nil {
return fmt.Errorf("writing user registration file: %v", err)
}
err = ioutil.WriteFile(s.userKeyFile(email), data.Key, 0600)
if err != nil {
return fmt.Errorf("writing user key file: %v", err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"StoreUser",
"(",
"email",
"string",
",",
"data",
"*",
"UserData",
")",
"error",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"s",
".",
"user",
"(",
"email",
")",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"s",
".",
"userRegFile",
"(",
"email",
")",
",",
"data",
".",
"Reg",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"s",
".",
"userKeyFile",
"(",
"email",
")",
",",
"data",
".",
"Key",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // StoreUser implements Storage.StoreUser by writing it to disk. The base
// directories needed for the file are automatically created as needed. | [
"StoreUser",
"implements",
"Storage",
".",
"StoreUser",
"by",
"writing",
"it",
"to",
"disk",
".",
"The",
"base",
"directories",
"needed",
"for",
"the",
"file",
"are",
"automatically",
"created",
"as",
"needed",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L225-L239 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | TryLock | func (s *FileStorage) TryLock(name string) (Waiter, error) {
s.nameLocksMu.Lock()
defer s.nameLocksMu.Unlock()
wg, ok := s.nameLocks[name]
if ok {
// lock already obtained, let caller wait on it
return wg, nil
}
// caller gets lock
wg = new(sync.WaitGroup)
wg.Add(1)
s.nameLocks[name] = wg
return nil, nil
} | go | func (s *FileStorage) TryLock(name string) (Waiter, error) {
s.nameLocksMu.Lock()
defer s.nameLocksMu.Unlock()
wg, ok := s.nameLocks[name]
if ok {
// lock already obtained, let caller wait on it
return wg, nil
}
// caller gets lock
wg = new(sync.WaitGroup)
wg.Add(1)
s.nameLocks[name] = wg
return nil, nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"TryLock",
"(",
"name",
"string",
")",
"(",
"Waiter",
",",
"error",
")",
"{",
"s",
".",
"nameLocksMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"nameLocksMu",
".",
"Unlock",
"(",
")",
"\n",
"wg",
",",
"ok",
":=",
"s",
".",
"nameLocks",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"// lock already obtained, let caller wait on it",
"return",
"wg",
",",
"nil",
"\n",
"}",
"\n",
"// caller gets lock",
"wg",
"=",
"new",
"(",
"sync",
".",
"WaitGroup",
")",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"s",
".",
"nameLocks",
"[",
"name",
"]",
"=",
"wg",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // TryLock attempts to get a lock for name, otherwise it returns
// a Waiter value to wait until the other process is finished. | [
"TryLock",
"attempts",
"to",
"get",
"a",
"lock",
"for",
"name",
"otherwise",
"it",
"returns",
"a",
"Waiter",
"value",
"to",
"wait",
"until",
"the",
"other",
"process",
"is",
"finished",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L243-L256 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | Unlock | func (s *FileStorage) Unlock(name string) error {
s.nameLocksMu.Lock()
defer s.nameLocksMu.Unlock()
wg, ok := s.nameLocks[name]
if !ok {
return fmt.Errorf("FileStorage: no lock to release for %s", name)
}
wg.Done()
delete(s.nameLocks, name)
return nil
} | go | func (s *FileStorage) Unlock(name string) error {
s.nameLocksMu.Lock()
defer s.nameLocksMu.Unlock()
wg, ok := s.nameLocks[name]
if !ok {
return fmt.Errorf("FileStorage: no lock to release for %s", name)
}
wg.Done()
delete(s.nameLocks, name)
return nil
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"Unlock",
"(",
"name",
"string",
")",
"error",
"{",
"s",
".",
"nameLocksMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"nameLocksMu",
".",
"Unlock",
"(",
")",
"\n",
"wg",
",",
"ok",
":=",
"s",
".",
"nameLocks",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"nameLocks",
",",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Unlock unlocks name. | [
"Unlock",
"unlocks",
"name",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L259-L269 | train |
inverse-inc/packetfence | go/caddy/caddy/caddytls/filestorage.go | MostRecentUserEmail | func (s *FileStorage) MostRecentUserEmail() string {
userDirs, err := ioutil.ReadDir(s.users())
if err != nil {
return ""
}
var mostRecent os.FileInfo
for _, dir := range userDirs {
if !dir.IsDir() {
continue
}
if mostRecent == nil || dir.ModTime().After(mostRecent.ModTime()) {
mostRecent = dir
}
}
if mostRecent != nil {
return mostRecent.Name()
}
return ""
} | go | func (s *FileStorage) MostRecentUserEmail() string {
userDirs, err := ioutil.ReadDir(s.users())
if err != nil {
return ""
}
var mostRecent os.FileInfo
for _, dir := range userDirs {
if !dir.IsDir() {
continue
}
if mostRecent == nil || dir.ModTime().After(mostRecent.ModTime()) {
mostRecent = dir
}
}
if mostRecent != nil {
return mostRecent.Name()
}
return ""
} | [
"func",
"(",
"s",
"*",
"FileStorage",
")",
"MostRecentUserEmail",
"(",
")",
"string",
"{",
"userDirs",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"s",
".",
"users",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"var",
"mostRecent",
"os",
".",
"FileInfo",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"userDirs",
"{",
"if",
"!",
"dir",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"mostRecent",
"==",
"nil",
"||",
"dir",
".",
"ModTime",
"(",
")",
".",
"After",
"(",
"mostRecent",
".",
"ModTime",
"(",
")",
")",
"{",
"mostRecent",
"=",
"dir",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"mostRecent",
"!=",
"nil",
"{",
"return",
"mostRecent",
".",
"Name",
"(",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // MostRecentUserEmail implements Storage.MostRecentUserEmail by finding the
// most recently written sub directory in the users' directory. It is named
// after the email address. This corresponds to the most recent call to
// StoreUser. | [
"MostRecentUserEmail",
"implements",
"Storage",
".",
"MostRecentUserEmail",
"by",
"finding",
"the",
"most",
"recently",
"written",
"sub",
"directory",
"in",
"the",
"users",
"directory",
".",
"It",
"is",
"named",
"after",
"the",
"email",
"address",
".",
"This",
"corresponds",
"to",
"the",
"most",
"recent",
"call",
"to",
"StoreUser",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L275-L293 | train |
inverse-inc/packetfence | go/caddy/pfipset/pfipset.go | setup | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Cluster.HostsIp)
pfipset, err := buildPfipsetHandler(ctx)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
pfipset.Next = next
return pfipset
})
return nil
} | go | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Cluster.HostsIp)
pfipset, err := buildPfipsetHandler(ctx)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
pfipset.Next = next
return pfipset
})
return nil
} | [
"func",
"setup",
"(",
"c",
"*",
"caddy",
".",
"Controller",
")",
"error",
"{",
"ctx",
":=",
"log",
".",
"LoggerNewContext",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n\n",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddStruct",
"(",
"ctx",
",",
"&",
"pfconfigdriver",
".",
"Config",
".",
"Cluster",
".",
"HostsIp",
")",
"\n\n",
"pfipset",
",",
"err",
":=",
"buildPfipsetHandler",
"(",
"ctx",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"httpserver",
".",
"GetConfig",
"(",
"c",
")",
".",
"AddMiddleware",
"(",
"func",
"(",
"next",
"httpserver",
".",
"Handler",
")",
"httpserver",
".",
"Handler",
"{",
"pfipset",
".",
"Next",
"=",
"next",
"\n",
"return",
"pfipset",
"\n",
"}",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup the pfipset middleware
// Also loads the pfconfig resources and registers them in the pool | [
"Setup",
"the",
"pfipset",
"middleware",
"Also",
"loads",
"the",
"pfconfig",
"resources",
"and",
"registers",
"them",
"in",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfipset/pfipset.go#L44-L61 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/extensions/ext.go | resourceExists | func resourceExists(root, path string) bool {
_, err := os.Stat(root + path)
// technically we should use os.IsNotExist(err)
// but we don't handle any other kinds of errors anyway
return err == nil
} | go | func resourceExists(root, path string) bool {
_, err := os.Stat(root + path)
// technically we should use os.IsNotExist(err)
// but we don't handle any other kinds of errors anyway
return err == nil
} | [
"func",
"resourceExists",
"(",
"root",
",",
"path",
"string",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"root",
"+",
"path",
")",
"\n",
"// technically we should use os.IsNotExist(err)",
"// but we don't handle any other kinds of errors anyway",
"return",
"err",
"==",
"nil",
"\n",
"}"
] | // resourceExists returns true if the file specified at
// root + path exists; false otherwise. | [
"resourceExists",
"returns",
"true",
"if",
"the",
"file",
"specified",
"at",
"root",
"+",
"path",
"exists",
";",
"false",
"otherwise",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/extensions/ext.go#L47-L52 | train |
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\n",
"f",
".",
"ids",
".",
"PfconfigNS",
"=",
"\"",
"\"",
"\n\n",
"// If ids changed, we want to reload",
"if",
"!",
"pfconfigdriver",
".",
"IsValid",
"(",
"ctx",
",",
"&",
"f",
".",
"ids",
")",
"{",
"reload",
"=",
"true",
"\n",
"}",
"\n\n",
"pfconfigdriver",
".",
"FetchDecodeSocketCache",
"(",
"ctx",
",",
"&",
"f",
".",
"ids",
")",
"\n\n",
"fssoFactory",
":=",
"NewFactory",
"(",
"ctx",
")",
"\n\n",
"if",
"f",
".",
"Structs",
"!=",
"nil",
"{",
"for",
"_",
",",
"firewallId",
":=",
"range",
"f",
".",
"ids",
".",
"Keys",
"{",
"firewall",
",",
"ok",
":=",
"f",
".",
"Structs",
"[",
"firewallId",
"]",
"\n\n",
"if",
"!",
"ok",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"reload",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"!",
"pfconfigdriver",
".",
"IsValid",
"(",
"ctx",
",",
"firewall",
")",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"firewallId",
")",
")",
"\n",
"reload",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"reload",
"=",
"true",
"\n",
"}",
"\n\n",
"if",
"reload",
"{",
"newFirewalls",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"FirewallSSOInt",
")",
"\n\n",
"for",
"_",
",",
"firewallId",
":=",
"range",
"f",
".",
"ids",
".",
"Keys",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"firewallId",
")",
")",
"\n\n",
"firewall",
",",
"err",
":=",
"fssoFactory",
".",
"Instantiate",
"(",
"ctx",
",",
"firewallId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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",
"!=",
"\"",
"\"",
"{",
"// Do nothing, cache is populated, will be returned below",
"}",
"else",
"if",
"sharedutils",
".",
"EnvOrDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"pfconfigSocketPathCache",
"=",
"pfconfigSocketPath",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\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",
"(",
"\"",
"\"",
",",
"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\n",
"var",
"c",
"net",
".",
"Conn",
"\n",
"err",
":=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"for",
"err",
"!=",
"nil",
"{",
"select",
"{",
"case",
"<-",
"timeoutChan",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"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",
"(",
"\"",
"\"",
",",
"getPfconfigSocketPath",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"time",
".",
"Sleep",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\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\n",
"// Send our query in the socket",
"fmt",
".",
"Fprintf",
"(",
"c",
",",
"payload",
")",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"ReadFrom",
"(",
"c",
")",
"\n\n",
"// First 4 bytes are a little-endian representing the length of the payload",
"var",
"length",
"uint32",
"\n",
"binary",
".",
"Read",
"(",
"&",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"length",
")",
"\n\n",
"// Read the response given the length provided by pfconfig",
"response",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
"\n",
"buf",
".",
"Read",
"(",
"response",
")",
"\n\n",
"// Validate the response has the length that was declared by pfconfig",
"if",
"uint32",
"(",
"len",
"(",
"response",
")",
")",
"!=",
"length",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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\n",
"ov",
"=",
"reflect",
".",
"ValueOf",
"(",
"param",
")",
"\n",
"for",
"ov",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"||",
"ov",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"ov",
"=",
"ov",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n\n",
"// 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",
")",
")",
"\n",
"if",
"!",
"field",
".",
"IsValid",
"(",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"userVal",
":=",
"field",
".",
"Interface",
"(",
")",
"\n",
"if",
"userVal",
"!=",
"\"",
"\"",
"{",
"return",
"userVal",
".",
"(",
"string",
")",
"\n",
"}",
"\n\n",
"ot",
":=",
"ov",
".",
"Type",
"(",
")",
"\n",
"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",
"(",
"\"",
"\"",
")",
"\n",
"if",
"val",
"!=",
"\"",
"\"",
"{",
"return",
"val",
"\n",
"}",
"else",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"fieldName",
",",
"ot",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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",
"\"",
"\"",
":",
"decodeJsonInterface",
"(",
"ctx",
",",
"b",
",",
"o",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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",
",",
"\"",
"\"",
",",
"query",
".",
"GetIdentifier",
"(",
")",
")",
"\n\n",
"// If the resource is still valid and is already loaded",
"if",
"IsValid",
"(",
"ctx",
",",
"o",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\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\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\n",
"transferMetadata",
"(",
"ctx",
",",
"&",
"o",
",",
"&",
"newo",
")",
"\n\n",
"reflect",
".",
"ValueOf",
"(",
"o",
")",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"newo",
")",
".",
"Elem",
"(",
")",
")",
"\n\n",
"query",
":=",
"createQuery",
"(",
"ctx",
",",
"o",
")",
"\n\n",
"jsonResponse",
":=",
"FetchSocket",
"(",
"ctx",
",",
"query",
".",
"GetPayload",
"(",
")",
")",
"\n\n",
"if",
"query",
".",
"method",
"==",
"\"",
"\"",
"{",
"if",
"cs",
",",
"ok",
":=",
"o",
".",
"(",
"PfconfigKeysInt",
")",
";",
"ok",
"{",
"decodeInterface",
"(",
"ctx",
",",
"query",
".",
"encoding",
",",
"jsonResponse",
",",
"cs",
".",
"GetKeys",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"metadataFromField",
"(",
"ctx",
",",
"o",
",",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"||",
"metadataFromField",
"(",
"ctx",
",",
"o",
",",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"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",
"(",
"\"",
"\"",
",",
"jsonResponse",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"o",
".",
"SetLoadedAt",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\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\n",
"for",
"_",
",",
"serv",
":=",
"range",
"services",
"{",
"what",
",",
"ip",
":=",
"serv",
".",
"HostType",
"(",
")",
"\n\n",
"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",
"\n",
"}",
"\n\n",
"newRecord",
":=",
"serv",
".",
"NewCNAME",
"(",
"state",
".",
"QName",
"(",
")",
",",
"serv",
".",
"Host",
")",
"\n",
"if",
"len",
"(",
"previousRecords",
")",
">",
"7",
"{",
"// don't add it, and just continue",
"continue",
"\n",
"}",
"\n",
"if",
"dnsutil",
".",
"DuplicateCNAME",
"(",
"newRecord",
",",
"previousRecords",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"state1",
":=",
"state",
".",
"NewWithQuestion",
"(",
"serv",
".",
"Host",
",",
"state",
".",
"QType",
"(",
")",
")",
"\n",
"nextRecords",
",",
"err",
":=",
"AAAA",
"(",
"b",
",",
"zone",
",",
"state1",
",",
"append",
"(",
"previousRecords",
",",
"newRecord",
")",
",",
"opt",
")",
"\n\n",
"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",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"nextRecords",
"...",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"// This means we can not complete the CNAME, try to look else where.",
"target",
":=",
"newRecord",
".",
"Target",
"\n",
"if",
"dns",
".",
"IsSubDomain",
"(",
"zone",
",",
"target",
")",
"{",
"// We should already have found it",
"continue",
"\n",
"}",
"\n",
"m1",
",",
"e1",
":=",
"b",
".",
"Lookup",
"(",
"state",
",",
"target",
",",
"state",
".",
"QType",
"(",
")",
")",
"\n",
"if",
"e1",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"// Len(m1.Answer) > 0 here is well?",
"records",
"=",
"append",
"(",
"records",
",",
"newRecord",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"m1",
".",
"Answer",
"...",
")",
"\n",
"continue",
"\n",
"// both here again",
"case",
"dns",
".",
"TypeA",
":",
"// nada?",
"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\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\n",
"lookup",
"[",
"mx",
".",
"Mx",
"]",
"=",
"true",
"\n\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\n",
"m1",
",",
"e1",
"=",
"b",
".",
"Lookup",
"(",
"state",
",",
"mx",
".",
"Mx",
",",
"dns",
".",
"TypeAAAA",
")",
"\n",
"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",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"// Internal name",
"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",
"// e.AAAA as well",
"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\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\n",
"state",
".",
"SizeAndDo",
"(",
"m",
")",
"\n",
"state",
".",
"W",
".",
"WriteMsg",
"(",
"m",
")",
"\n",
"// Return success as the rcode to signal we have written to the client.",
"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\n",
"match",
":=",
"network",
".",
"RegexMatchIP",
".",
"FindStringSubmatch",
"(",
"rname",
")",
"\n",
"if",
"len",
"(",
"match",
")",
"!=",
"2",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"network",
".",
"IPnet",
".",
"IP",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"matchedIP",
"=",
"net",
".",
"ParseIP",
"(",
"match",
"[",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"// TODO: can probably just allocate a []byte and use that.",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"// convert back to an valid ipv6 string with colons",
"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\n",
"// No valid ip or it does not belong to this network",
"if",
"matchedIP",
"==",
"nil",
"||",
"!",
"network",
".",
"IPnet",
".",
"Contains",
"(",
"matchedIP",
")",
"{",
"return",
"nil",
"\n",
"}",
"\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",
"{",
"// replace . to -",
"name",
"=",
"ipv4",
".",
"String",
"(",
")",
"\n",
"}",
"else",
"{",
"// assume v6",
"// ensure zeros are present in string",
"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",
"// inject the converted ip into the fqdn template",
"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\n",
"// 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",
")",
",",
"}",
"\n",
"upstream",
".",
"Hosts",
"=",
"make",
"(",
"[",
"]",
"*",
"healthcheck",
".",
"UpstreamHost",
",",
"len",
"(",
"hosts",
")",
")",
"\n\n",
"for",
"i",
",",
"host",
":=",
"range",
"hosts",
"{",
"uh",
":=",
"&",
"healthcheck",
".",
"UpstreamHost",
"{",
"Name",
":",
"host",
",",
"FailTimeout",
":",
"upstream",
".",
"FailTimeout",
",",
"CheckDown",
":",
"checkDownFunc",
"(",
"upstream",
")",
",",
"}",
"\n\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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.