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/coredns/plugin/proxy/lookup.go
Lookup
func (p Proxy) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) { req := new(dns.Msg) req.SetQuestion(name, typ) state.SizeAndDo(req) state2 := request.Request{W: state.W, Req: req} return p.lookup(state2) }
go
func (p Proxy) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) { req := new(dns.Msg) req.SetQuestion(name, typ) state.SizeAndDo(req) state2 := request.Request{W: state.W, Req: req} return p.lookup(state2) }
[ "func", "(", "p", "Proxy", ")", "Lookup", "(", "state", "request", ".", "Request", ",", "name", "string", ",", "typ", "uint16", ")", "(", "*", "dns", ".", "Msg", ",", "error", ")", "{", "req", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "req", ".", "SetQuestion", "(", "name", ",", "typ", ")", "\n", "state", ".", "SizeAndDo", "(", "req", ")", "\n\n", "state2", ":=", "request", ".", "Request", "{", "W", ":", "state", ".", "W", ",", "Req", ":", "req", "}", "\n\n", "return", "p", ".", "lookup", "(", "state2", ")", "\n", "}" ]
// Lookup will use name and type to forge a new message and will send that upstream. It will // set any EDNS0 options correctly so that downstream will be able to process the reply.
[ "Lookup", "will", "use", "name", "and", "type", "to", "forge", "a", "new", "message", "and", "will", "send", "that", "upstream", ".", "It", "will", "set", "any", "EDNS0", "options", "correctly", "so", "that", "downstream", "will", "be", "able", "to", "process", "the", "reply", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/lookup.go#L52-L60
train
inverse-inc/packetfence
go/coredns/plugin/proxy/lookup.go
Forward
func (p Proxy) Forward(state request.Request) (*dns.Msg, error) { return p.lookup(state) }
go
func (p Proxy) Forward(state request.Request) (*dns.Msg, error) { return p.lookup(state) }
[ "func", "(", "p", "Proxy", ")", "Forward", "(", "state", "request", ".", "Request", ")", "(", "*", "dns", ".", "Msg", ",", "error", ")", "{", "return", "p", ".", "lookup", "(", "state", ")", "\n", "}" ]
// Forward forward the request in state as-is. Unlike Lookup that adds EDNS0 suffix to the message.
[ "Forward", "forward", "the", "request", "in", "state", "as", "-", "is", ".", "Unlike", "Lookup", "that", "adds", "EDNS0", "suffix", "to", "the", "message", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/lookup.go#L63-L65
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/internalsrv/internal.go
Write
func (w internalResponseWriter) Write(b []byte) (int, error) { if isInternalRedirect(w) { return 0, nil } return w.ResponseWriter.Write(b) }
go
func (w internalResponseWriter) Write(b []byte) (int, error) { if isInternalRedirect(w) { return 0, nil } return w.ResponseWriter.Write(b) }
[ "func", "(", "w", "internalResponseWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "isInternalRedirect", "(", "w", ")", "{", "return", "0", ",", "nil", "\n", "}", "\n", "return", "w", ".", "ResponseWriter", ".", "Write", "(", "b", ")", "\n", "}" ]
// Write ignores the call if the response should be redirected to an internal // location.
[ "Write", "ignores", "the", "call", "if", "the", "response", "should", "be", "redirected", "to", "an", "internal", "location", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/internalsrv/internal.go#L91-L96
train
inverse-inc/packetfence
go/coredns/plugin/pkg/replacer/replacer.go
Set
func (r replacer) Set(key, value string) { r.replacements["{"+key+"}"] = value }
go
func (r replacer) Set(key, value string) { r.replacements["{"+key+"}"] = value }
[ "func", "(", "r", "replacer", ")", "Set", "(", "key", ",", "value", "string", ")", "{", "r", ".", "replacements", "[", "\"", "\"", "+", "key", "+", "\"", "\"", "]", "=", "value", "\n", "}" ]
// Set sets key to value in the replacements map.
[ "Set", "sets", "key", "to", "value", "in", "the", "replacements", "map", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/replacer/replacer.go#L105-L107
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
NewPool
func NewPool() Pool { p := Pool{} p.lock = timedlock.NewRWLock() p.lock.Timeout = 1 * time.Second p.lock.RTimeout = 3 * time.Second p.lock.PrintErrors = false p.lock.Panic = false p.structs = make(map[string]interface{}) return p }
go
func NewPool() Pool { p := Pool{} p.lock = timedlock.NewRWLock() p.lock.Timeout = 1 * time.Second p.lock.RTimeout = 3 * time.Second p.lock.PrintErrors = false p.lock.Panic = false p.structs = make(map[string]interface{}) return p }
[ "func", "NewPool", "(", ")", "Pool", "{", "p", ":=", "Pool", "{", "}", "\n", "p", ".", "lock", "=", "timedlock", ".", "NewRWLock", "(", ")", "\n", "p", ".", "lock", ".", "Timeout", "=", "1", "*", "time", ".", "Second", "\n", "p", ".", "lock", ".", "RTimeout", "=", "3", "*", "time", ".", "Second", "\n", "p", ".", "lock", ".", "PrintErrors", "=", "false", "\n", "p", ".", "lock", ".", "Panic", "=", "false", "\n", "p", ".", "structs", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "return", "p", "\n", "}" ]
// Create a new Pool with a 1 second refresh timeout and initialize the lock
[ "Create", "a", "new", "Pool", "with", "a", "1", "second", "refresh", "timeout", "and", "initialize", "the", "lock" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L36-L45
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
ReadLock
func (p *Pool) ReadLock(ctx context.Context) (uint64, error) { return p.lock.RLock() }
go
func (p *Pool) ReadLock(ctx context.Context) (uint64, error) { return p.lock.RLock() }
[ "func", "(", "p", "*", "Pool", ")", "ReadLock", "(", "ctx", "context", ".", "Context", ")", "(", "uint64", ",", "error", ")", "{", "return", "p", ".", "lock", ".", "RLock", "(", ")", "\n", "}" ]
// Acquire a read lock on the pool // All the goroutines that use resources from the pool should call this and release it when they are done // Long running processes should aim to retain this lock for the smallest time possible since Refresh will need a RW lock to refresh the resources // This lock can be acquired multiple times given its a read lock
[ "Acquire", "a", "read", "lock", "on", "the", "pool", "All", "the", "goroutines", "that", "use", "resources", "from", "the", "pool", "should", "call", "this", "and", "release", "it", "when", "they", "are", "done", "Long", "running", "processes", "should", "aim", "to", "retain", "this", "lock", "for", "the", "smallest", "time", "possible", "since", "Refresh", "will", "need", "a", "RW", "lock", "to", "refresh", "the", "resources", "This", "lock", "can", "be", "acquired", "multiple", "times", "given", "its", "a", "read", "lock" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L51-L53
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
ReadUnlock
func (p *Pool) ReadUnlock(ctx context.Context, id uint64) { p.lock.RUnlock(id) }
go
func (p *Pool) ReadUnlock(ctx context.Context, id uint64) { p.lock.RUnlock(id) }
[ "func", "(", "p", "*", "Pool", ")", "ReadUnlock", "(", "ctx", "context", ".", "Context", ",", "id", "uint64", ")", "{", "p", ".", "lock", ".", "RUnlock", "(", "id", ")", "\n", "}" ]
// Unlock the read lock
[ "Unlock", "the", "read", "lock" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L56-L58
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
AddRefreshable
func (p *Pool) AddRefreshable(ctx context.Context, r Refreshable) { id, err := p.lock.Lock() if err == nil { defer p.lock.Unlock(id) p.refreshables = append(p.refreshables, r) r.Refresh(ctx) } }
go
func (p *Pool) AddRefreshable(ctx context.Context, r Refreshable) { id, err := p.lock.Lock() if err == nil { defer p.lock.Unlock(id) p.refreshables = append(p.refreshables, r) r.Refresh(ctx) } }
[ "func", "(", "p", "*", "Pool", ")", "AddRefreshable", "(", "ctx", "context", ".", "Context", ",", "r", "Refreshable", ")", "{", "id", ",", "err", ":=", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "err", "==", "nil", "{", "defer", "p", ".", "lock", ".", "Unlock", "(", "id", ")", "\n", "p", ".", "refreshables", "=", "append", "(", "p", ".", "refreshables", ",", "r", ")", "\n", "r", ".", "Refresh", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// Add a refreshable resource to the pool // Requires the RW lock and will not timeout like Refresh does
[ "Add", "a", "refreshable", "resource", "to", "the", "pool", "Requires", "the", "RW", "lock", "and", "will", "not", "timeout", "like", "Refresh", "does" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L62-L69
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
AddStruct
func (p *Pool) AddStruct(ctx context.Context, s interface{}) { id, err := p.lock.Lock() if err == nil { defer p.lock.Unlock(id) addr := fmt.Sprintf("%p", s) log.LoggerWContext(ctx).Debug("Adding struct with address " + addr + " to the pool") p.structs[addr] = s p.refreshStruct(ctx, s) } }
go
func (p *Pool) AddStruct(ctx context.Context, s interface{}) { id, err := p.lock.Lock() if err == nil { defer p.lock.Unlock(id) addr := fmt.Sprintf("%p", s) log.LoggerWContext(ctx).Debug("Adding struct with address " + addr + " to the pool") p.structs[addr] = s p.refreshStruct(ctx, s) } }
[ "func", "(", "p", "*", "Pool", ")", "AddStruct", "(", "ctx", "context", ".", "Context", ",", "s", "interface", "{", "}", ")", "{", "id", ",", "err", ":=", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "err", "==", "nil", "{", "defer", "p", ".", "lock", ".", "Unlock", "(", "id", ")", "\n\n", "addr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ")", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", "+", "addr", "+", "\"", "\"", ")", "\n\n", "p", ".", "structs", "[", "addr", "]", "=", "s", "\n", "p", ".", "refreshStruct", "(", "ctx", ",", "s", ")", "\n", "}", "\n", "}" ]
// Add a struct to the pool // Requires the RW lock and will not timeout like Refresh does
[ "Add", "a", "struct", "to", "the", "pool", "Requires", "the", "RW", "lock", "and", "will", "not", "timeout", "like", "Refresh", "does" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L73-L84
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
refreshRefreshables
func (p *Pool) refreshRefreshables(ctx context.Context) { for _, r := range p.refreshables { r.Refresh(ctx) } }
go
func (p *Pool) refreshRefreshables(ctx context.Context) { for _, r := range p.refreshables { r.Refresh(ctx) } }
[ "func", "(", "p", "*", "Pool", ")", "refreshRefreshables", "(", "ctx", "context", ".", "Context", ")", "{", "for", "_", ",", "r", ":=", "range", "p", ".", "refreshables", "{", "r", ".", "Refresh", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// Refresh all the refreshables of the pool
[ "Refresh", "all", "the", "refreshables", "of", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L87-L91
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
refreshStruct
func (p *Pool) refreshStruct(ctx context.Context, s interface{}) { v := reflect.ValueOf(s) for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { v = v.Elem() } // Check if s itself is a PfconfigObject, otherwise, we cycle though its fields and process them if o, ok := v.Addr().Interface().(PfconfigObject); ok { FetchDecodeSocketCache(ctx, o) } else { for i := 0; i < v.NumField(); i++ { field := v.Field(i).Addr() if o, ok := field.Interface().(PfconfigObject); ok { FetchDecodeSocketCache(ctx, o) } else { p.refreshStruct(ctx, field.Interface()) } } } }
go
func (p *Pool) refreshStruct(ctx context.Context, s interface{}) { v := reflect.ValueOf(s) for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { v = v.Elem() } // Check if s itself is a PfconfigObject, otherwise, we cycle though its fields and process them if o, ok := v.Addr().Interface().(PfconfigObject); ok { FetchDecodeSocketCache(ctx, o) } else { for i := 0; i < v.NumField(); i++ { field := v.Field(i).Addr() if o, ok := field.Interface().(PfconfigObject); ok { FetchDecodeSocketCache(ctx, o) } else { p.refreshStruct(ctx, field.Interface()) } } } }
[ "func", "(", "p", "*", "Pool", ")", "refreshStruct", "(", "ctx", "context", ".", "Context", ",", "s", "interface", "{", "}", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "s", ")", "\n", "for", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "||", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n\n", "// Check if s itself is a PfconfigObject, otherwise, we cycle though its fields and process them", "if", "o", ",", "ok", ":=", "v", ".", "Addr", "(", ")", ".", "Interface", "(", ")", ".", "(", "PfconfigObject", ")", ";", "ok", "{", "FetchDecodeSocketCache", "(", "ctx", ",", "o", ")", "\n", "}", "else", "{", "for", "i", ":=", "0", ";", "i", "<", "v", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "v", ".", "Field", "(", "i", ")", ".", "Addr", "(", ")", "\n", "if", "o", ",", "ok", ":=", "field", ".", "Interface", "(", ")", ".", "(", "PfconfigObject", ")", ";", "ok", "{", "FetchDecodeSocketCache", "(", "ctx", ",", "o", ")", "\n", "}", "else", "{", "p", ".", "refreshStruct", "(", "ctx", ",", "field", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Refresh a struct // If this struct is a PfconfigObject, it will be sent directly to FetchDecodeSocketCache // Otherwise, the struct fields and sub-fields will be analyzed to find all the PfconfigObjects and these will be sent to FetchDecodeSocketCache
[ "Refresh", "a", "struct", "If", "this", "struct", "is", "a", "PfconfigObject", "it", "will", "be", "sent", "directly", "to", "FetchDecodeSocketCache", "Otherwise", "the", "struct", "fields", "and", "sub", "-", "fields", "will", "be", "analyzed", "to", "find", "all", "the", "PfconfigObjects", "and", "these", "will", "be", "sent", "to", "FetchDecodeSocketCache" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L96-L115
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
refreshStructs
func (p *Pool) refreshStructs(ctx context.Context) { for _, o := range p.structs { p.refreshStruct(ctx, o) } }
go
func (p *Pool) refreshStructs(ctx context.Context) { for _, o := range p.structs { p.refreshStruct(ctx, o) } }
[ "func", "(", "p", "*", "Pool", ")", "refreshStructs", "(", "ctx", "context", ".", "Context", ")", "{", "for", "_", ",", "o", ":=", "range", "p", ".", "structs", "{", "p", ".", "refreshStruct", "(", "ctx", ",", "o", ")", "\n", "}", "\n", "}" ]
// Refresh all the structs of the pool
[ "Refresh", "all", "the", "structs", "of", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L118-L122
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
acquireWriteLock
func (p *Pool) acquireWriteLock(ctx context.Context) (bool, uint64) { defer func() { if r := recover(); r != nil { log.LoggerWContext(ctx).Warn("Couldn't acquire lock for pfconfig pool") } }() id, err := p.lock.Lock() if err != nil { panic("Couldn't acquire lock for pfconfig pool") } log.LoggerWContext(ctx).Debug("Acquired lock for pfconfig pool") return err == nil, id }
go
func (p *Pool) acquireWriteLock(ctx context.Context) (bool, uint64) { defer func() { if r := recover(); r != nil { log.LoggerWContext(ctx).Warn("Couldn't acquire lock for pfconfig pool") } }() id, err := p.lock.Lock() if err != nil { panic("Couldn't acquire lock for pfconfig pool") } log.LoggerWContext(ctx).Debug("Acquired lock for pfconfig pool") return err == nil, id }
[ "func", "(", "p", "*", "Pool", ")", "acquireWriteLock", "(", "ctx", "context", ".", "Context", ")", "(", "bool", ",", "uint64", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "id", ",", "err", ":=", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "err", "==", "nil", ",", "id", "\n", "}" ]
// Attempts to obtain a RW lock with the timeout set in RefreshLockTimeout // Even if the timeout gets reached, the lock will still be acquired when available but it will be immediately released // This is done by sending a message twice in the timeoutChan, one will be caught by the main waiting goroutine, the other one by the lock-waiting goroutine // When the lock-waiting goroutine is able to get something out of the timeoutChan channel, it knows it must release the lock immediately
[ "Attempts", "to", "obtain", "a", "RW", "lock", "with", "the", "timeout", "set", "in", "RefreshLockTimeout", "Even", "if", "the", "timeout", "gets", "reached", "the", "lock", "will", "still", "be", "acquired", "when", "available", "but", "it", "will", "be", "immediately", "released", "This", "is", "done", "by", "sending", "a", "message", "twice", "in", "the", "timeoutChan", "one", "will", "be", "caught", "by", "the", "main", "waiting", "goroutine", "the", "other", "one", "by", "the", "lock", "-", "waiting", "goroutine", "When", "the", "lock", "-", "waiting", "goroutine", "is", "able", "to", "get", "something", "out", "of", "the", "timeoutChan", "channel", "it", "knows", "it", "must", "release", "the", "lock", "immediately" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L128-L142
train
inverse-inc/packetfence
go/pfconfigdriver/pool.go
Refresh
func (p *Pool) Refresh(ctx context.Context) bool { log.LoggerWContext(ctx).Debug("Refreshing pfconfig pool") var locked bool var id uint64 if locked, id = p.acquireWriteLock(ctx); !locked { return false } log.LoggerWContext(ctx).Debug("Refresh got lock ID", id) defer func(ctx context.Context) { log.LoggerWContext(ctx).Debug("Refresh is releasing lock ID", id) p.lock.Unlock(id) }(ctx) p.refreshStructs(ctx) p.refreshRefreshables(ctx) log.LoggerWContext(ctx).Debug("Finished refresh of pfconfig pool") return true }
go
func (p *Pool) Refresh(ctx context.Context) bool { log.LoggerWContext(ctx).Debug("Refreshing pfconfig pool") var locked bool var id uint64 if locked, id = p.acquireWriteLock(ctx); !locked { return false } log.LoggerWContext(ctx).Debug("Refresh got lock ID", id) defer func(ctx context.Context) { log.LoggerWContext(ctx).Debug("Refresh is releasing lock ID", id) p.lock.Unlock(id) }(ctx) p.refreshStructs(ctx) p.refreshRefreshables(ctx) log.LoggerWContext(ctx).Debug("Finished refresh of pfconfig pool") return true }
[ "func", "(", "p", "*", "Pool", ")", "Refresh", "(", "ctx", "context", ".", "Context", ")", "bool", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "var", "locked", "bool", "\n", "var", "id", "uint64", "\n", "if", "locked", ",", "id", "=", "p", ".", "acquireWriteLock", "(", "ctx", ")", ";", "!", "locked", "{", "return", "false", "\n", "}", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ",", "id", ")", "\n", "defer", "func", "(", "ctx", "context", ".", "Context", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ",", "id", ")", "\n", "p", ".", "lock", ".", "Unlock", "(", "id", ")", "\n", "}", "(", "ctx", ")", "\n\n", "p", ".", "refreshStructs", "(", "ctx", ")", "\n", "p", ".", "refreshRefreshables", "(", "ctx", ")", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "true", "\n", "}" ]
// Refresh all the structs and resources of the pool using the RW lock // An attempt to get the RW lock will be done for up to RefreshLockTimeout
[ "Refresh", "all", "the", "structs", "and", "resources", "of", "the", "pool", "using", "the", "RW", "lock", "An", "attempt", "to", "get", "the", "RW", "lock", "will", "be", "done", "for", "up", "to", "RefreshLockTimeout" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/pfconfigdriver/pool.go#L146-L164
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/rewrite/rewrite.go
Match
func (r *ComplexRule) Match(req *http.Request) bool { // validate RequestMatcher // includes if and path if !r.RequestMatcher.Match(req) { return false } // validate extensions if !r.matchExt(req.URL.Path) { return false } // if regex is nil, ignore if r.Regexp == nil { return true } // otherwise validate regex return r.regexpMatches(req.URL.Path) != nil }
go
func (r *ComplexRule) Match(req *http.Request) bool { // validate RequestMatcher // includes if and path if !r.RequestMatcher.Match(req) { return false } // validate extensions if !r.matchExt(req.URL.Path) { return false } // if regex is nil, ignore if r.Regexp == nil { return true } // otherwise validate regex return r.regexpMatches(req.URL.Path) != nil }
[ "func", "(", "r", "*", "ComplexRule", ")", "Match", "(", "req", "*", "http", ".", "Request", ")", "bool", "{", "// validate RequestMatcher", "// includes if and path", "if", "!", "r", ".", "RequestMatcher", ".", "Match", "(", "req", ")", "{", "return", "false", "\n", "}", "\n\n", "// validate extensions", "if", "!", "r", ".", "matchExt", "(", "req", ".", "URL", ".", "Path", ")", "{", "return", "false", "\n", "}", "\n\n", "// if regex is nil, ignore", "if", "r", ".", "Regexp", "==", "nil", "{", "return", "true", "\n", "}", "\n", "// otherwise validate regex", "return", "r", ".", "regexpMatches", "(", "req", ".", "URL", ".", "Path", ")", "!=", "nil", "\n", "}" ]
// Match satisfies httpserver.Config. // // Though ComplexRule embeds a RequestMatcher, additional // checks are needed which requires a custom implementation.
[ "Match", "satisfies", "httpserver", ".", "Config", ".", "Though", "ComplexRule", "embeds", "a", "RequestMatcher", "additional", "checks", "are", "needed", "which", "requires", "a", "custom", "implementation", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/rewrite/rewrite.go#L140-L158
train
inverse-inc/packetfence
go/coredns/plugin/pkg/response/typify.go
Typify
func Typify(m *dns.Msg, t time.Time) (Type, *dns.OPT) { if m == nil { return OtherError, nil } opt := m.IsEdns0() do := false if opt != nil { do = opt.Do() } if m.Opcode == dns.OpcodeUpdate { return Update, opt } // Check transfer and update first if m.Opcode == dns.OpcodeNotify { return Meta, opt } if len(m.Question) > 0 { if m.Question[0].Qtype == dns.TypeAXFR || m.Question[0].Qtype == dns.TypeIXFR { return Meta, opt } } // If our message contains any expired sigs and we care about that, we should return expired if do { if expired := typifyExpired(m, t); expired { return OtherError, opt } } if len(m.Answer) > 0 && m.Rcode == dns.RcodeSuccess { return NoError, opt } soa := false ns := 0 for _, r := range m.Ns { if r.Header().Rrtype == dns.TypeSOA { soa = true continue } if r.Header().Rrtype == dns.TypeNS { ns++ } } if soa && m.Rcode == dns.RcodeSuccess { return NoData, opt } if soa && m.Rcode == dns.RcodeNameError { return NameError, opt } if ns > 0 && m.Rcode == dns.RcodeSuccess { return Delegation, opt } if m.Rcode == dns.RcodeSuccess { return NoError, opt } return OtherError, opt }
go
func Typify(m *dns.Msg, t time.Time) (Type, *dns.OPT) { if m == nil { return OtherError, nil } opt := m.IsEdns0() do := false if opt != nil { do = opt.Do() } if m.Opcode == dns.OpcodeUpdate { return Update, opt } // Check transfer and update first if m.Opcode == dns.OpcodeNotify { return Meta, opt } if len(m.Question) > 0 { if m.Question[0].Qtype == dns.TypeAXFR || m.Question[0].Qtype == dns.TypeIXFR { return Meta, opt } } // If our message contains any expired sigs and we care about that, we should return expired if do { if expired := typifyExpired(m, t); expired { return OtherError, opt } } if len(m.Answer) > 0 && m.Rcode == dns.RcodeSuccess { return NoError, opt } soa := false ns := 0 for _, r := range m.Ns { if r.Header().Rrtype == dns.TypeSOA { soa = true continue } if r.Header().Rrtype == dns.TypeNS { ns++ } } if soa && m.Rcode == dns.RcodeSuccess { return NoData, opt } if soa && m.Rcode == dns.RcodeNameError { return NameError, opt } if ns > 0 && m.Rcode == dns.RcodeSuccess { return Delegation, opt } if m.Rcode == dns.RcodeSuccess { return NoError, opt } return OtherError, opt }
[ "func", "Typify", "(", "m", "*", "dns", ".", "Msg", ",", "t", "time", ".", "Time", ")", "(", "Type", ",", "*", "dns", ".", "OPT", ")", "{", "if", "m", "==", "nil", "{", "return", "OtherError", ",", "nil", "\n", "}", "\n", "opt", ":=", "m", ".", "IsEdns0", "(", ")", "\n", "do", ":=", "false", "\n", "if", "opt", "!=", "nil", "{", "do", "=", "opt", ".", "Do", "(", ")", "\n", "}", "\n\n", "if", "m", ".", "Opcode", "==", "dns", ".", "OpcodeUpdate", "{", "return", "Update", ",", "opt", "\n", "}", "\n\n", "// Check transfer and update first", "if", "m", ".", "Opcode", "==", "dns", ".", "OpcodeNotify", "{", "return", "Meta", ",", "opt", "\n", "}", "\n\n", "if", "len", "(", "m", ".", "Question", ")", ">", "0", "{", "if", "m", ".", "Question", "[", "0", "]", ".", "Qtype", "==", "dns", ".", "TypeAXFR", "||", "m", ".", "Question", "[", "0", "]", ".", "Qtype", "==", "dns", ".", "TypeIXFR", "{", "return", "Meta", ",", "opt", "\n", "}", "\n", "}", "\n\n", "// If our message contains any expired sigs and we care about that, we should return expired", "if", "do", "{", "if", "expired", ":=", "typifyExpired", "(", "m", ",", "t", ")", ";", "expired", "{", "return", "OtherError", ",", "opt", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "m", ".", "Answer", ")", ">", "0", "&&", "m", ".", "Rcode", "==", "dns", ".", "RcodeSuccess", "{", "return", "NoError", ",", "opt", "\n", "}", "\n\n", "soa", ":=", "false", "\n", "ns", ":=", "0", "\n", "for", "_", ",", "r", ":=", "range", "m", ".", "Ns", "{", "if", "r", ".", "Header", "(", ")", ".", "Rrtype", "==", "dns", ".", "TypeSOA", "{", "soa", "=", "true", "\n", "continue", "\n", "}", "\n", "if", "r", ".", "Header", "(", ")", ".", "Rrtype", "==", "dns", ".", "TypeNS", "{", "ns", "++", "\n", "}", "\n", "}", "\n\n", "if", "soa", "&&", "m", ".", "Rcode", "==", "dns", ".", "RcodeSuccess", "{", "return", "NoData", ",", "opt", "\n", "}", "\n", "if", "soa", "&&", "m", ".", "Rcode", "==", "dns", ".", "RcodeNameError", "{", "return", "NameError", ",", "opt", "\n", "}", "\n\n", "if", "ns", ">", "0", "&&", "m", ".", "Rcode", "==", "dns", ".", "RcodeSuccess", "{", "return", "Delegation", ",", "opt", "\n", "}", "\n\n", "if", "m", ".", "Rcode", "==", "dns", ".", "RcodeSuccess", "{", "return", "NoError", ",", "opt", "\n", "}", "\n\n", "return", "OtherError", ",", "opt", "\n", "}" ]
// Typify classifies a message, it returns the Type.
[ "Typify", "classifies", "a", "message", "it", "returns", "the", "Type", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/response/typify.go#L54-L118
train
inverse-inc/packetfence
go/caddy/caddy/caddy.go
HasListenerWithAddress
func HasListenerWithAddress(addr string) bool { instancesMu.Lock() defer instancesMu.Unlock() for _, inst := range instances { for _, sln := range inst.servers { if listenerAddrEqual(sln.listener, addr) { return true } } } return false }
go
func HasListenerWithAddress(addr string) bool { instancesMu.Lock() defer instancesMu.Unlock() for _, inst := range instances { for _, sln := range inst.servers { if listenerAddrEqual(sln.listener, addr) { return true } } } return false }
[ "func", "HasListenerWithAddress", "(", "addr", "string", ")", "bool", "{", "instancesMu", ".", "Lock", "(", ")", "\n", "defer", "instancesMu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "inst", ":=", "range", "instances", "{", "for", "_", ",", "sln", ":=", "range", "inst", ".", "servers", "{", "if", "listenerAddrEqual", "(", "sln", ".", "listener", ",", "addr", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasListenerWithAddress returns whether this package is // tracking a server using a listener with the address // addr.
[ "HasListenerWithAddress", "returns", "whether", "this", "package", "is", "tracking", "a", "server", "using", "a", "listener", "with", "the", "address", "addr", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddy.go#L223-L234
train
inverse-inc/packetfence
go/caddy/caddy/caddy.go
ValidateAndExecuteDirectives
func ValidateAndExecuteDirectives(cdyfile Input, inst *Instance, justValidate bool) error { // If parsing only inst will be nil, create an instance for this function call only. if justValidate { inst = &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)} } stypeName := cdyfile.ServerType() stype, err := getServerType(stypeName) if err != nil { return err } inst.caddyfileInput = cdyfile sblocks, err := loadServerBlocks(stypeName, cdyfile.Path(), bytes.NewReader(cdyfile.Body())) if err != nil { return err } inst.context = stype.NewContext() if inst.context == nil { return fmt.Errorf("server type %s produced a nil Context", stypeName) } sblocks, err = inst.context.InspectServerBlocks(cdyfile.Path(), sblocks) if err != nil { return err } err = executeDirectives(inst, cdyfile.Path(), stype.Directives(), sblocks, justValidate) if err != nil { return err } return nil }
go
func ValidateAndExecuteDirectives(cdyfile Input, inst *Instance, justValidate bool) error { // If parsing only inst will be nil, create an instance for this function call only. if justValidate { inst = &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)} } stypeName := cdyfile.ServerType() stype, err := getServerType(stypeName) if err != nil { return err } inst.caddyfileInput = cdyfile sblocks, err := loadServerBlocks(stypeName, cdyfile.Path(), bytes.NewReader(cdyfile.Body())) if err != nil { return err } inst.context = stype.NewContext() if inst.context == nil { return fmt.Errorf("server type %s produced a nil Context", stypeName) } sblocks, err = inst.context.InspectServerBlocks(cdyfile.Path(), sblocks) if err != nil { return err } err = executeDirectives(inst, cdyfile.Path(), stype.Directives(), sblocks, justValidate) if err != nil { return err } return nil }
[ "func", "ValidateAndExecuteDirectives", "(", "cdyfile", "Input", ",", "inst", "*", "Instance", ",", "justValidate", "bool", ")", "error", "{", "// If parsing only inst will be nil, create an instance for this function call only.", "if", "justValidate", "{", "inst", "=", "&", "Instance", "{", "serverType", ":", "cdyfile", ".", "ServerType", "(", ")", ",", "wg", ":", "new", "(", "sync", ".", "WaitGroup", ")", "}", "\n", "}", "\n\n", "stypeName", ":=", "cdyfile", ".", "ServerType", "(", ")", "\n\n", "stype", ",", "err", ":=", "getServerType", "(", "stypeName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "inst", ".", "caddyfileInput", "=", "cdyfile", "\n\n", "sblocks", ",", "err", ":=", "loadServerBlocks", "(", "stypeName", ",", "cdyfile", ".", "Path", "(", ")", ",", "bytes", ".", "NewReader", "(", "cdyfile", ".", "Body", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "inst", ".", "context", "=", "stype", ".", "NewContext", "(", ")", "\n", "if", "inst", ".", "context", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "stypeName", ")", "\n", "}", "\n\n", "sblocks", ",", "err", "=", "inst", ".", "context", ".", "InspectServerBlocks", "(", "cdyfile", ".", "Path", "(", ")", ",", "sblocks", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "executeDirectives", "(", "inst", ",", "cdyfile", ".", "Path", "(", ")", ",", "stype", ".", "Directives", "(", ")", ",", "sblocks", ",", "justValidate", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n\n", "}" ]
// ValidateAndExecuteDirectives will load the server blocks from cdyfile // by parsing it, then execute the directives configured by it and store // the resulting server blocks into inst. If justValidate is true, parse // callbacks will not be executed between directives, since the purpose // is only to check the input for valid syntax.
[ "ValidateAndExecuteDirectives", "will", "load", "the", "server", "blocks", "from", "cdyfile", "by", "parsing", "it", "then", "execute", "the", "directives", "configured", "by", "it", "and", "store", "the", "resulting", "server", "blocks", "into", "inst", ".", "If", "justValidate", "is", "true", "parse", "callbacks", "will", "not", "be", "executed", "between", "directives", "since", "the", "purpose", "is", "only", "to", "check", "the", "input", "for", "valid", "syntax", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddy.go#L516-L554
train
inverse-inc/packetfence
go/coredns/plugin/file/secondary.go
TransferIn
func (z *Zone) TransferIn() error { if len(z.TransferFrom) == 0 { return nil } m := new(dns.Msg) m.SetAxfr(z.origin) z1 := z.Copy() var ( Err error tr string ) Transfer: for _, tr = range z.TransferFrom { t := new(dns.Transfer) c, err := t.In(m, tr) if err != nil { log.Printf("[ERROR] Failed to setup transfer `%s' with `%q': %v", z.origin, tr, err) Err = err continue Transfer } for env := range c { if env.Error != nil { log.Printf("[ERROR] Failed to transfer `%s' from %q: %v", z.origin, tr, env.Error) Err = env.Error continue Transfer } for _, rr := range env.RR { if err := z1.Insert(rr); err != nil { log.Printf("[ERROR] Failed to parse transfer `%s' from: %q: %v", z.origin, tr, err) Err = err continue Transfer } } } Err = nil break } if Err != nil { return Err } z.Tree = z1.Tree z.Apex = z1.Apex *z.Expired = false log.Printf("[INFO] Transferred: %s from %s", z.origin, tr) return nil }
go
func (z *Zone) TransferIn() error { if len(z.TransferFrom) == 0 { return nil } m := new(dns.Msg) m.SetAxfr(z.origin) z1 := z.Copy() var ( Err error tr string ) Transfer: for _, tr = range z.TransferFrom { t := new(dns.Transfer) c, err := t.In(m, tr) if err != nil { log.Printf("[ERROR] Failed to setup transfer `%s' with `%q': %v", z.origin, tr, err) Err = err continue Transfer } for env := range c { if env.Error != nil { log.Printf("[ERROR] Failed to transfer `%s' from %q: %v", z.origin, tr, env.Error) Err = env.Error continue Transfer } for _, rr := range env.RR { if err := z1.Insert(rr); err != nil { log.Printf("[ERROR] Failed to parse transfer `%s' from: %q: %v", z.origin, tr, err) Err = err continue Transfer } } } Err = nil break } if Err != nil { return Err } z.Tree = z1.Tree z.Apex = z1.Apex *z.Expired = false log.Printf("[INFO] Transferred: %s from %s", z.origin, tr) return nil }
[ "func", "(", "z", "*", "Zone", ")", "TransferIn", "(", ")", "error", "{", "if", "len", "(", "z", ".", "TransferFrom", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "m", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "m", ".", "SetAxfr", "(", "z", ".", "origin", ")", "\n\n", "z1", ":=", "z", ".", "Copy", "(", ")", "\n", "var", "(", "Err", "error", "\n", "tr", "string", "\n", ")", "\n\n", "Transfer", ":", "for", "_", ",", "tr", "=", "range", "z", ".", "TransferFrom", "{", "t", ":=", "new", "(", "dns", ".", "Transfer", ")", "\n", "c", ",", "err", ":=", "t", ".", "In", "(", "m", ",", "tr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "z", ".", "origin", ",", "tr", ",", "err", ")", "\n", "Err", "=", "err", "\n", "continue", "Transfer", "\n", "}", "\n", "for", "env", ":=", "range", "c", "{", "if", "env", ".", "Error", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "z", ".", "origin", ",", "tr", ",", "env", ".", "Error", ")", "\n", "Err", "=", "env", ".", "Error", "\n", "continue", "Transfer", "\n", "}", "\n", "for", "_", ",", "rr", ":=", "range", "env", ".", "RR", "{", "if", "err", ":=", "z1", ".", "Insert", "(", "rr", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "z", ".", "origin", ",", "tr", ",", "err", ")", "\n", "Err", "=", "err", "\n", "continue", "Transfer", "\n", "}", "\n", "}", "\n", "}", "\n", "Err", "=", "nil", "\n", "break", "\n", "}", "\n", "if", "Err", "!=", "nil", "{", "return", "Err", "\n", "}", "\n\n", "z", ".", "Tree", "=", "z1", ".", "Tree", "\n", "z", ".", "Apex", "=", "z1", ".", "Apex", "\n", "*", "z", ".", "Expired", "=", "false", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "z", ".", "origin", ",", "tr", ")", "\n", "return", "nil", "\n", "}" ]
// TransferIn retrieves the zone from the masters, parses it and sets it live.
[ "TransferIn", "retrieves", "the", "zone", "from", "the", "masters", "parses", "it", "and", "sets", "it", "live", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/file/secondary.go#L12-L60
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/recorder.go
NewResponseRecorder
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder { return &ResponseRecorder{ ResponseWriter: w, status: http.StatusOK, start: time.Now(), } }
go
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder { return &ResponseRecorder{ ResponseWriter: w, status: http.StatusOK, start: time.Now(), } }
[ "func", "NewResponseRecorder", "(", "w", "http", ".", "ResponseWriter", ")", "*", "ResponseRecorder", "{", "return", "&", "ResponseRecorder", "{", "ResponseWriter", ":", "w", ",", "status", ":", "http", ".", "StatusOK", ",", "start", ":", "time", ".", "Now", "(", ")", ",", "}", "\n", "}" ]
// NewResponseRecorder makes and returns a new responseRecorder, // which captures the HTTP Status code from the ResponseWriter // and also the length of the response body written through it. // Because a status is not set unless WriteHeader is called // explicitly, this constructor initializes with a status code // of 200 to cover the default case.
[ "NewResponseRecorder", "makes", "and", "returns", "a", "new", "responseRecorder", "which", "captures", "the", "HTTP", "Status", "code", "from", "the", "ResponseWriter", "and", "also", "the", "length", "of", "the", "response", "body", "written", "through", "it", ".", "Because", "a", "status", "is", "not", "set", "unless", "WriteHeader", "is", "called", "explicitly", "this", "constructor", "initializes", "with", "a", "status", "code", "of", "200", "to", "cover", "the", "default", "case", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/recorder.go#L36-L42
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/recorder.go
Flush
func (r *ResponseRecorder) Flush() { if f, ok := r.ResponseWriter.(http.Flusher); ok { f.Flush() } else { panic(NonFlusherError{Underlying: r.ResponseWriter}) // should be recovered at the beginning of middleware stack } }
go
func (r *ResponseRecorder) Flush() { if f, ok := r.ResponseWriter.(http.Flusher); ok { f.Flush() } else { panic(NonFlusherError{Underlying: r.ResponseWriter}) // should be recovered at the beginning of middleware stack } }
[ "func", "(", "r", "*", "ResponseRecorder", ")", "Flush", "(", ")", "{", "if", "f", ",", "ok", ":=", "r", ".", "ResponseWriter", ".", "(", "http", ".", "Flusher", ")", ";", "ok", "{", "f", ".", "Flush", "(", ")", "\n", "}", "else", "{", "panic", "(", "NonFlusherError", "{", "Underlying", ":", "r", ".", "ResponseWriter", "}", ")", "// should be recovered at the beginning of middleware stack", "\n", "}", "\n", "}" ]
// Flush implements http.Flusher. It simply wraps the underlying // ResponseWriter's Flush method if there is one, or does nothing.
[ "Flush", "implements", "http", ".", "Flusher", ".", "It", "simply", "wraps", "the", "underlying", "ResponseWriter", "s", "Flush", "method", "if", "there", "is", "one", "or", "does", "nothing", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/recorder.go#L82-L88
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/markdown/setup.go
setup
func setup(c *caddy.Controller) error { mdconfigs, err := markdownParse(c) if err != nil { return err } cfg := httpserver.GetConfig(c) md := Markdown{ Root: cfg.Root, FileSys: http.Dir(cfg.Root), Configs: mdconfigs, IndexFiles: []string{"index.md"}, } cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler { md.Next = next return md }) return nil }
go
func setup(c *caddy.Controller) error { mdconfigs, err := markdownParse(c) if err != nil { return err } cfg := httpserver.GetConfig(c) md := Markdown{ Root: cfg.Root, FileSys: http.Dir(cfg.Root), Configs: mdconfigs, IndexFiles: []string{"index.md"}, } cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler { md.Next = next return md }) return nil }
[ "func", "setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "mdconfigs", ",", "err", ":=", "markdownParse", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cfg", ":=", "httpserver", ".", "GetConfig", "(", "c", ")", "\n\n", "md", ":=", "Markdown", "{", "Root", ":", "cfg", ".", "Root", ",", "FileSys", ":", "http", ".", "Dir", "(", "cfg", ".", "Root", ")", ",", "Configs", ":", "mdconfigs", ",", "IndexFiles", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "}", "\n\n", "cfg", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "md", ".", "Next", "=", "next", "\n", "return", "md", "\n", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// setup configures a new Markdown middleware instance.
[ "setup", "configures", "a", "new", "Markdown", "middleware", "instance", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/markdown/setup.go#L20-L41
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/tls.go
HostQualifies
func HostQualifies(hostname string) bool { return hostname != "localhost" && // localhost is ineligible // hostname must not be empty strings.TrimSpace(hostname) != "" && // must not contain wildcard (*) characters (until CA supports it) !strings.Contains(hostname, "*") && // must not start or end with a dot !strings.HasPrefix(hostname, ".") && !strings.HasSuffix(hostname, ".") && // cannot be an IP address, see // https://community.letsencrypt.org/t/certificate-for-static-ip/84/2?u=mholt net.ParseIP(hostname) == nil }
go
func HostQualifies(hostname string) bool { return hostname != "localhost" && // localhost is ineligible // hostname must not be empty strings.TrimSpace(hostname) != "" && // must not contain wildcard (*) characters (until CA supports it) !strings.Contains(hostname, "*") && // must not start or end with a dot !strings.HasPrefix(hostname, ".") && !strings.HasSuffix(hostname, ".") && // cannot be an IP address, see // https://community.letsencrypt.org/t/certificate-for-static-ip/84/2?u=mholt net.ParseIP(hostname) == nil }
[ "func", "HostQualifies", "(", "hostname", "string", ")", "bool", "{", "return", "hostname", "!=", "\"", "\"", "&&", "// localhost is ineligible", "// hostname must not be empty", "strings", ".", "TrimSpace", "(", "hostname", ")", "!=", "\"", "\"", "&&", "// must not contain wildcard (*) characters (until CA supports it)", "!", "strings", ".", "Contains", "(", "hostname", ",", "\"", "\"", ")", "&&", "// must not start or end with a dot", "!", "strings", ".", "HasPrefix", "(", "hostname", ",", "\"", "\"", ")", "&&", "!", "strings", ".", "HasSuffix", "(", "hostname", ",", "\"", "\"", ")", "&&", "// cannot be an IP address, see", "// https://community.letsencrypt.org/t/certificate-for-static-ip/84/2?u=mholt", "net", ".", "ParseIP", "(", "hostname", ")", "==", "nil", "\n", "}" ]
// HostQualifies returns true if the hostname alone // appears eligible for automatic HTTPS. For example, // localhost, empty hostname, and IP addresses are // not eligible because we cannot obtain certificates // for those names.
[ "HostQualifies", "returns", "true", "if", "the", "hostname", "alone", "appears", "eligible", "for", "automatic", "HTTPS", ".", "For", "example", "localhost", "empty", "hostname", "and", "IP", "addresses", "are", "not", "eligible", "because", "we", "cannot", "obtain", "certificates", "for", "those", "names", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L31-L47
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/tls.go
saveCertResource
func saveCertResource(storage Storage, cert acme.CertificateResource) error { // Save cert, private key, and metadata siteData := &SiteData{ Cert: cert.Certificate, Key: cert.PrivateKey, } var err error siteData.Meta, err = json.MarshalIndent(&cert, "", "\t") if err == nil { err = storage.StoreSite(cert.Domain, siteData) } return err }
go
func saveCertResource(storage Storage, cert acme.CertificateResource) error { // Save cert, private key, and metadata siteData := &SiteData{ Cert: cert.Certificate, Key: cert.PrivateKey, } var err error siteData.Meta, err = json.MarshalIndent(&cert, "", "\t") if err == nil { err = storage.StoreSite(cert.Domain, siteData) } return err }
[ "func", "saveCertResource", "(", "storage", "Storage", ",", "cert", "acme", ".", "CertificateResource", ")", "error", "{", "// Save cert, private key, and metadata", "siteData", ":=", "&", "SiteData", "{", "Cert", ":", "cert", ".", "Certificate", ",", "Key", ":", "cert", ".", "PrivateKey", ",", "}", "\n", "var", "err", "error", "\n", "siteData", ".", "Meta", ",", "err", "=", "json", ".", "MarshalIndent", "(", "&", "cert", ",", "\"", "\"", ",", "\"", "\\t", "\"", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "storage", ".", "StoreSite", "(", "cert", ".", "Domain", ",", "siteData", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// saveCertResource saves the certificate resource to disk. This // includes the certificate file itself, the private key, and the // metadata file.
[ "saveCertResource", "saves", "the", "certificate", "resource", "to", "disk", ".", "This", "includes", "the", "certificate", "file", "itself", "the", "private", "key", "and", "the", "metadata", "file", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L52-L64
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/tls.go
Revoke
func Revoke(host string) error { client, err := newACMEClient(new(Config), true) if err != nil { return err } return client.Revoke(host) }
go
func Revoke(host string) error { client, err := newACMEClient(new(Config), true) if err != nil { return err } return client.Revoke(host) }
[ "func", "Revoke", "(", "host", "string", ")", "error", "{", "client", ",", "err", ":=", "newACMEClient", "(", "new", "(", "Config", ")", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "client", ".", "Revoke", "(", "host", ")", "\n", "}" ]
// Revoke revokes the certificate for host via ACME protocol. // It assumes the certificate was obtained from the // CA at DefaultCAUrl.
[ "Revoke", "revokes", "the", "certificate", "for", "host", "via", "ACME", "protocol", ".", "It", "assumes", "the", "certificate", "was", "obtained", "from", "the", "CA", "at", "DefaultCAUrl", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L69-L75
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/tls.go
Present
func (s tlsSniSolver) Present(domain, token, keyAuth string) error { cert, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth) if err != nil { return err } cacheCertificate(Certificate{ Certificate: cert, Names: []string{acmeDomain}, }) return nil }
go
func (s tlsSniSolver) Present(domain, token, keyAuth string) error { cert, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth) if err != nil { return err } cacheCertificate(Certificate{ Certificate: cert, Names: []string{acmeDomain}, }) return nil }
[ "func", "(", "s", "tlsSniSolver", ")", "Present", "(", "domain", ",", "token", ",", "keyAuth", "string", ")", "error", "{", "cert", ",", "acmeDomain", ",", "err", ":=", "acme", ".", "TLSSNI01ChallengeCert", "(", "keyAuth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacheCertificate", "(", "Certificate", "{", "Certificate", ":", "cert", ",", "Names", ":", "[", "]", "string", "{", "acmeDomain", "}", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Present adds the challenge certificate to the cache.
[ "Present", "adds", "the", "challenge", "certificate", "to", "the", "cache", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L82-L92
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/tls.go
CleanUp
func (s tlsSniSolver) CleanUp(domain, token, keyAuth string) error { _, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth) if err != nil { return err } uncacheCertificate(acmeDomain) return nil }
go
func (s tlsSniSolver) CleanUp(domain, token, keyAuth string) error { _, acmeDomain, err := acme.TLSSNI01ChallengeCert(keyAuth) if err != nil { return err } uncacheCertificate(acmeDomain) return nil }
[ "func", "(", "s", "tlsSniSolver", ")", "CleanUp", "(", "domain", ",", "token", ",", "keyAuth", "string", ")", "error", "{", "_", ",", "acmeDomain", ",", "err", ":=", "acme", ".", "TLSSNI01ChallengeCert", "(", "keyAuth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "uncacheCertificate", "(", "acmeDomain", ")", "\n", "return", "nil", "\n", "}" ]
// CleanUp removes the challenge certificate from the cache.
[ "CleanUp", "removes", "the", "challenge", "certificate", "from", "the", "cache", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L95-L102
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/tls.go
RegisterStorageProvider
func RegisterStorageProvider(name string, provider StorageConstructor) { storageProviders[name] = provider caddy.RegisterPlugin("tls.storage."+name, caddy.Plugin{}) }
go
func RegisterStorageProvider(name string, provider StorageConstructor) { storageProviders[name] = provider caddy.RegisterPlugin("tls.storage."+name, caddy.Plugin{}) }
[ "func", "RegisterStorageProvider", "(", "name", "string", ",", "provider", "StorageConstructor", ")", "{", "storageProviders", "[", "name", "]", "=", "provider", "\n", "caddy", ".", "RegisterPlugin", "(", "\"", "\"", "+", "name", ",", "caddy", ".", "Plugin", "{", "}", ")", "\n", "}" ]
// RegisterStorageProvider registers provider by name for storing tls data
[ "RegisterStorageProvider", "registers", "provider", "by", "name", "for", "storing", "tls", "data" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/tls.go#L175-L178
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/httphandler.go
HTTPChallengeHandler
func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool { if !strings.HasPrefix(r.URL.Path, challengeBasePath) { return false } if !namesObtaining.Has(r.Host) { return false } scheme := "http" if r.TLS != nil { scheme = "https" } if listenHost == "" { listenHost = "localhost" } upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort)) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("[ERROR] ACME proxy handler: %v", err) return true } proxy := httputil.NewSingleHostReverseProxy(upstream) proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } proxy.ServeHTTP(w, r) return true }
go
func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool { if !strings.HasPrefix(r.URL.Path, challengeBasePath) { return false } if !namesObtaining.Has(r.Host) { return false } scheme := "http" if r.TLS != nil { scheme = "https" } if listenHost == "" { listenHost = "localhost" } upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort)) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("[ERROR] ACME proxy handler: %v", err) return true } proxy := httputil.NewSingleHostReverseProxy(upstream) proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } proxy.ServeHTTP(w, r) return true }
[ "func", "HTTPChallengeHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "listenHost", ",", "altPort", "string", ")", "bool", "{", "if", "!", "strings", ".", "HasPrefix", "(", "r", ".", "URL", ".", "Path", ",", "challengeBasePath", ")", "{", "return", "false", "\n", "}", "\n", "if", "!", "namesObtaining", ".", "Has", "(", "r", ".", "Host", ")", "{", "return", "false", "\n", "}", "\n\n", "scheme", ":=", "\"", "\"", "\n", "if", "r", ".", "TLS", "!=", "nil", "{", "scheme", "=", "\"", "\"", "\n", "}", "\n\n", "if", "listenHost", "==", "\"", "\"", "{", "listenHost", "=", "\"", "\"", "\n", "}", "\n\n", "upstream", ",", "err", ":=", "url", ".", "Parse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scheme", ",", "listenHost", ",", "altPort", ")", ")", "\n", "if", "err", "!=", "nil", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "true", "\n", "}", "\n\n", "proxy", ":=", "httputil", ".", "NewSingleHostReverseProxy", "(", "upstream", ")", "\n", "proxy", ".", "Transport", "=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ",", "}", "\n", "proxy", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n\n", "return", "true", "\n", "}" ]
// HTTPChallengeHandler proxies challenge requests to ACME client if the // request path starts with challengeBasePath. It returns true if it // handled the request and no more needs to be done; it returns false // if this call was a no-op and the request still needs handling.
[ "HTTPChallengeHandler", "proxies", "challenge", "requests", "to", "ACME", "client", "if", "the", "request", "path", "starts", "with", "challengeBasePath", ".", "It", "returns", "true", "if", "it", "handled", "the", "request", "and", "no", "more", "needs", "to", "be", "done", ";", "it", "returns", "false", "if", "this", "call", "was", "a", "no", "-", "op", "and", "the", "request", "still", "needs", "handling", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/httphandler.go#L19-L50
train
inverse-inc/packetfence
go/filter_client/filter_client.go
FilterProfile
func (c *Client) FilterProfile(data interface{}) (interface{}, error) { socket, err := net.Dial("unix", c.SocketPath) if err != nil { return nil, err } defer socket.Close() return c.SendRequest("filter_profile", data, socket) }
go
func (c *Client) FilterProfile(data interface{}) (interface{}, error) { socket, err := net.Dial("unix", c.SocketPath) if err != nil { return nil, err } defer socket.Close() return c.SendRequest("filter_profile", data, socket) }
[ "func", "(", "c", "*", "Client", ")", "FilterProfile", "(", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "socket", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "c", ".", "SocketPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "socket", ".", "Close", "(", ")", "\n", "return", "c", ".", "SendRequest", "(", "\"", "\"", ",", "data", ",", "socket", ")", "\n", "}" ]
// Sends a filter_profile message to the pffilter service
[ "Sends", "a", "filter_profile", "message", "to", "the", "pffilter", "service" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L47-L54
train
inverse-inc/packetfence
go/filter_client/filter_client.go
AccessFilter
func (c *Client) AccessFilter(filter string, scope string, data interface{}) (interface{}, error) { socket, err := net.Dial("unix", c.SocketPath) if err != nil { return nil, err } defer socket.Close() return c.SendRequest(filter, []interface{}{scope, data}, socket) }
go
func (c *Client) AccessFilter(filter string, scope string, data interface{}) (interface{}, error) { socket, err := net.Dial("unix", c.SocketPath) if err != nil { return nil, err } defer socket.Close() return c.SendRequest(filter, []interface{}{scope, data}, socket) }
[ "func", "(", "c", "*", "Client", ")", "AccessFilter", "(", "filter", "string", ",", "scope", "string", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "socket", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "c", ".", "SocketPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "socket", ".", "Close", "(", ")", "\n", "return", "c", ".", "SendRequest", "(", "filter", ",", "[", "]", "interface", "{", "}", "{", "scope", ",", "data", "}", ",", "socket", ")", "\n", "}" ]
// A generalize function for sending access filter messages
[ "A", "generalize", "function", "for", "sending", "access", "filter", "messages" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L57-L64
train
inverse-inc/packetfence
go/filter_client/filter_client.go
FilterVlan
func (c *Client) FilterVlan(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_vlan", scope, data) }
go
func (c *Client) FilterVlan(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_vlan", scope, data) }
[ "func", "(", "c", "*", "Client", ")", "FilterVlan", "(", "scope", "string", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "c", ".", "AccessFilter", "(", "\"", "\"", ",", "scope", ",", "data", ")", "\n", "}" ]
// Sends a filter_vlan message to the pffilter service
[ "Sends", "a", "filter_vlan", "message", "to", "the", "pffilter", "service" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L67-L69
train
inverse-inc/packetfence
go/filter_client/filter_client.go
FilterDhcp
func (c *Client) FilterDhcp(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_dhcp", scope, data) }
go
func (c *Client) FilterDhcp(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_dhcp", scope, data) }
[ "func", "(", "c", "*", "Client", ")", "FilterDhcp", "(", "scope", "string", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "c", ".", "AccessFilter", "(", "\"", "\"", ",", "scope", ",", "data", ")", "\n", "}" ]
// Sends a filter_dhcp message to the pffilter service
[ "Sends", "a", "filter_dhcp", "message", "to", "the", "pffilter", "service" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L72-L74
train
inverse-inc/packetfence
go/filter_client/filter_client.go
FilterDns
func (c *Client) FilterDns(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_dns", scope, data) }
go
func (c *Client) FilterDns(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_dns", scope, data) }
[ "func", "(", "c", "*", "Client", ")", "FilterDns", "(", "scope", "string", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "c", ".", "AccessFilter", "(", "\"", "\"", ",", "scope", ",", "data", ")", "\n", "}" ]
// Sends a filter_dns message to the pffilter service
[ "Sends", "a", "filter_dns", "message", "to", "the", "pffilter", "service" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L77-L79
train
inverse-inc/packetfence
go/filter_client/filter_client.go
FilterRadius
func (c *Client) FilterRadius(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_radius", scope, data) }
go
func (c *Client) FilterRadius(scope string, data interface{}) (interface{}, error) { return c.AccessFilter("filter_radius", scope, data) }
[ "func", "(", "c", "*", "Client", ")", "FilterRadius", "(", "scope", "string", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "c", ".", "AccessFilter", "(", "\"", "\"", ",", "scope", ",", "data", ")", "\n", "}" ]
// Sends a filter_radius message to the pffilter service
[ "Sends", "a", "filter_radius", "message", "to", "the", "pffilter", "service" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L82-L84
train
inverse-inc/packetfence
go/filter_client/filter_client.go
SendRequest
func (c *Client) SendRequest(method string, params interface{}, conn net.Conn) (interface{}, error) { request := Request{Method: method, Params: params} b, err := json.Marshal(request) if err != nil { return nil, err } b = append(b, '\n') _, err = conn.Write(b) if err != nil { return nil, err } reader := bufio.NewReader(conn) b2, err := reader.ReadBytes('\n') if err != nil { return nil, err } var response Response err = json.Unmarshal(b2, &response) if err != nil { return nil, err } if response.Error != nil { return nil, fmt.Errorf("%s", response.Error.Message) } if response.Result == nil { return nil, fmt.Errorf("No valid result returned") } return *response.Result, nil }
go
func (c *Client) SendRequest(method string, params interface{}, conn net.Conn) (interface{}, error) { request := Request{Method: method, Params: params} b, err := json.Marshal(request) if err != nil { return nil, err } b = append(b, '\n') _, err = conn.Write(b) if err != nil { return nil, err } reader := bufio.NewReader(conn) b2, err := reader.ReadBytes('\n') if err != nil { return nil, err } var response Response err = json.Unmarshal(b2, &response) if err != nil { return nil, err } if response.Error != nil { return nil, fmt.Errorf("%s", response.Error.Message) } if response.Result == nil { return nil, fmt.Errorf("No valid result returned") } return *response.Result, nil }
[ "func", "(", "c", "*", "Client", ")", "SendRequest", "(", "method", "string", ",", "params", "interface", "{", "}", ",", "conn", "net", ".", "Conn", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "request", ":=", "Request", "{", "Method", ":", "method", ",", "Params", ":", "params", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", "=", "append", "(", "b", ",", "'\\n'", ")", "\n", "_", ",", "err", "=", "conn", ".", "Write", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reader", ":=", "bufio", ".", "NewReader", "(", "conn", ")", "\n", "b2", ",", "err", ":=", "reader", ".", "ReadBytes", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "response", "Response", "\n", "err", "=", "json", ".", "Unmarshal", "(", "b2", ",", "&", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "response", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "response", ".", "Error", ".", "Message", ")", "\n", "}", "\n\n", "if", "response", ".", "Result", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "*", "response", ".", "Result", ",", "nil", "\n", "}" ]
// Send a request to the pffilter service
[ "Send", "a", "request", "to", "the", "pffilter", "service" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/filter_client/filter_client.go#L87-L117
train
inverse-inc/packetfence
go/firewallsso/checkpoint.go
Start
func (fw *Checkpoint) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { p := fw.startRadiusPacket(ctx, info, timeout) client := fw.getRadiusClient(ctx) // Use the background context since we don't want the lib to use our context ctx2, cancel := fw.RadiusContextWithTimeout() defer cancel() _, err := client.Exchange(ctx2, p, fw.PfconfigHashNS+":"+fw.Port) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Couldn't SSO to the Checkpoint, got the following error: %s", err)) return false, err } else { return true, nil } }
go
func (fw *Checkpoint) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { p := fw.startRadiusPacket(ctx, info, timeout) client := fw.getRadiusClient(ctx) // Use the background context since we don't want the lib to use our context ctx2, cancel := fw.RadiusContextWithTimeout() defer cancel() _, err := client.Exchange(ctx2, p, fw.PfconfigHashNS+":"+fw.Port) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Couldn't SSO to the Checkpoint, got the following error: %s", err)) return false, err } else { return true, nil } }
[ "func", "(", "fw", "*", "Checkpoint", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "p", ":=", "fw", ".", "startRadiusPacket", "(", "ctx", ",", "info", ",", "timeout", ")", "\n", "client", ":=", "fw", ".", "getRadiusClient", "(", "ctx", ")", "\n", "// Use the background context since we don't want the lib to use our context", "ctx2", ",", "cancel", ":=", "fw", ".", "RadiusContextWithTimeout", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "err", ":=", "client", ".", "Exchange", "(", "ctx2", ",", "p", ",", "fw", ".", "PfconfigHashNS", "+", "\"", "\"", "+", "fw", ".", "Port", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", ",", "err", "\n", "}", "else", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}" ]
// Send an SSO start to the Checkpoint firewall // Returns an error unless there is a valid reply from the firewall
[ "Send", "an", "SSO", "start", "to", "the", "Checkpoint", "firewall", "Returns", "an", "error", "unless", "there", "is", "a", "valid", "reply", "from", "the", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/checkpoint.go#L22-L35
train
inverse-inc/packetfence
go/firewallsso/checkpoint.go
startRadiusPacket
func (fw *Checkpoint) startRadiusPacket(ctx context.Context, info map[string]string, timeout int) *radius.Packet { r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password)) rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Start) rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"]) rfc2865.UserName_AddString(r, info["username"]) rfc2865.SessionTimeout_Add(r, rfc2865.SessionTimeout(timeout)) rfc2865.CalledStationID_AddString(r, "00:11:22:33:44:55") rfc2865.FramedIPAddress_Add(r, net.ParseIP(info["ip"])) rfc2865.CallingStationID_AddString(r, info["mac"]) return r }
go
func (fw *Checkpoint) startRadiusPacket(ctx context.Context, info map[string]string, timeout int) *radius.Packet { r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password)) rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Start) rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"]) rfc2865.UserName_AddString(r, info["username"]) rfc2865.SessionTimeout_Add(r, rfc2865.SessionTimeout(timeout)) rfc2865.CalledStationID_AddString(r, "00:11:22:33:44:55") rfc2865.FramedIPAddress_Add(r, net.ParseIP(info["ip"])) rfc2865.CallingStationID_AddString(r, info["mac"]) return r }
[ "func", "(", "fw", "*", "Checkpoint", ")", "startRadiusPacket", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "*", "radius", ".", "Packet", "{", "r", ":=", "radius", ".", "New", "(", "radius", ".", "CodeAccountingRequest", ",", "[", "]", "byte", "(", "fw", ".", "Password", ")", ")", "\n", "rfc2866", ".", "AcctStatusType_Add", "(", "r", ",", "rfc2866", ".", "AcctStatusType_Value_Start", ")", "\n", "rfc2866", ".", "AcctSessionID_AddString", "(", "r", ",", "\"", "\"", "+", "info", "[", "\"", "\"", "]", ")", "\n", "rfc2865", ".", "UserName_AddString", "(", "r", ",", "info", "[", "\"", "\"", "]", ")", "\n", "rfc2865", ".", "SessionTimeout_Add", "(", "r", ",", "rfc2865", ".", "SessionTimeout", "(", "timeout", ")", ")", "\n", "rfc2865", ".", "CalledStationID_AddString", "(", "r", ",", "\"", "\"", ")", "\n", "rfc2865", ".", "FramedIPAddress_Add", "(", "r", ",", "net", ".", "ParseIP", "(", "info", "[", "\"", "\"", "]", ")", ")", "\n", "rfc2865", ".", "CallingStationID_AddString", "(", "r", ",", "info", "[", "\"", "\"", "]", ")", "\n\n", "return", "r", "\n", "}" ]
// Build the RADIUS packet for an SSO start
[ "Build", "the", "RADIUS", "packet", "for", "an", "SSO", "start" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/checkpoint.go#L38-L49
train
inverse-inc/packetfence
go/firewallsso/checkpoint.go
Stop
func (fw *Checkpoint) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Warn("SSO Stop is not available for this firewall") return false, nil }
go
func (fw *Checkpoint) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Warn("SSO Stop is not available for this firewall") return false, nil }
[ "func", "(", "fw", "*", "Checkpoint", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "false", ",", "nil", "\n", "}" ]
// SSO stop handler which does nothing other than printing a warning since the SSO stop is unimplemented for this firewall
[ "SSO", "stop", "handler", "which", "does", "nothing", "other", "than", "printing", "a", "warning", "since", "the", "SSO", "stop", "is", "unimplemented", "for", "this", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/checkpoint.go#L52-L55
train
inverse-inc/packetfence
go/coredns/coremain/run.go
setVersion
func setVersion() { // A development build is one that's not at a tag or has uncommitted changes devBuild = gitTag == "" || gitShortStat != "" // Only set the appVersion if -ldflags was used if gitNearestTag != "" || gitTag != "" { if devBuild && gitNearestTag != "" { appVersion = fmt.Sprintf("%s (+%s %s)", strings.TrimPrefix(gitNearestTag, "v"), gitCommit, buildDate) } else if gitTag != "" { appVersion = strings.TrimPrefix(gitTag, "v") } } }
go
func setVersion() { // A development build is one that's not at a tag or has uncommitted changes devBuild = gitTag == "" || gitShortStat != "" // Only set the appVersion if -ldflags was used if gitNearestTag != "" || gitTag != "" { if devBuild && gitNearestTag != "" { appVersion = fmt.Sprintf("%s (+%s %s)", strings.TrimPrefix(gitNearestTag, "v"), gitCommit, buildDate) } else if gitTag != "" { appVersion = strings.TrimPrefix(gitTag, "v") } } }
[ "func", "setVersion", "(", ")", "{", "// A development build is one that's not at a tag or has uncommitted changes", "devBuild", "=", "gitTag", "==", "\"", "\"", "||", "gitShortStat", "!=", "\"", "\"", "\n\n", "// Only set the appVersion if -ldflags was used", "if", "gitNearestTag", "!=", "\"", "\"", "||", "gitTag", "!=", "\"", "\"", "{", "if", "devBuild", "&&", "gitNearestTag", "!=", "\"", "\"", "{", "appVersion", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "TrimPrefix", "(", "gitNearestTag", ",", "\"", "\"", ")", ",", "gitCommit", ",", "buildDate", ")", "\n", "}", "else", "if", "gitTag", "!=", "\"", "\"", "{", "appVersion", "=", "strings", ".", "TrimPrefix", "(", "gitTag", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// setVersion figures out the version information // based on variables set by -ldflags.
[ "setVersion", "figures", "out", "the", "version", "information", "based", "on", "variables", "set", "by", "-", "ldflags", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/coremain/run.go#L188-L201
train
inverse-inc/packetfence
go/coredns/plugin/proxy/metrics.go
OnStartupMetrics
func OnStartupMetrics() error { metricsOnce.Do(func() { prometheus.MustRegister(RequestCount) prometheus.MustRegister(RequestDuration) }) return nil }
go
func OnStartupMetrics() error { metricsOnce.Do(func() { prometheus.MustRegister(RequestCount) prometheus.MustRegister(RequestDuration) }) return nil }
[ "func", "OnStartupMetrics", "(", ")", "error", "{", "metricsOnce", ".", "Do", "(", "func", "(", ")", "{", "prometheus", ".", "MustRegister", "(", "RequestCount", ")", "\n", "prometheus", ".", "MustRegister", "(", "RequestDuration", ")", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// OnStartupMetrics sets up the metrics on startup. This is done for all proxy protocols.
[ "OnStartupMetrics", "sets", "up", "the", "metrics", "on", "startup", ".", "This", "is", "done", "for", "all", "proxy", "protocols", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/metrics.go#L29-L35
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/crypto.go
stapleOCSP
func stapleOCSP(cert *Certificate, pemBundle []byte) error { if pemBundle == nil { // The function in the acme package that gets OCSP requires a PEM-encoded cert bundle := new(bytes.Buffer) for _, derBytes := range cert.Certificate.Certificate { pem.Encode(bundle, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) } pemBundle = bundle.Bytes() } var ocspBytes []byte var ocspResp *ocsp.Response var ocspErr error var gotNewOCSP bool // First try to load OCSP staple from storage and see if // we can still use it. // TODO: Use Storage interface instead of disk directly var ocspFileNamePrefix string if len(cert.Names) > 0 { ocspFileNamePrefix = cert.Names[0] + "-" } ocspFileName := ocspFileNamePrefix + fastHash(pemBundle) ocspCachePath := filepath.Join(ocspFolder, ocspFileName) cachedOCSP, err := ioutil.ReadFile(ocspCachePath) if err == nil { resp, err := ocsp.ParseResponse(cachedOCSP, nil) if err == nil { if freshOCSP(resp) { // staple is still fresh; use it ocspBytes = cachedOCSP ocspResp = resp } } else { // invalid contents; delete the file // (we do this independently of the maintenance routine because // in this case we know for sure this should be a staple file // because we loaded it by name, whereas the maintenance routine // just iterates the list of files, even if somehow a non-staple // file gets in the folder. in this case we are sure it is corrupt.) err := os.Remove(ocspCachePath) if err != nil { log.Printf("[WARNING] Unable to delete invalid OCSP staple file: %v", err) } } } // If we couldn't get a fresh staple by reading the cache, // then we need to request it from the OCSP responder if ocspResp == nil || len(ocspBytes) == 0 { ocspBytes, ocspResp, ocspErr = acme.GetOCSPForCert(pemBundle) if ocspErr != nil { // An error here is not a problem because a certificate may simply // not contain a link to an OCSP server. But we should log it anyway. // There's nothing else we can do to get OCSP for this certificate, // so we can return here with the error. return fmt.Errorf("no OCSP stapling for %v: %v", cert.Names, ocspErr) } gotNewOCSP = true } // By now, we should have a response. If good, staple it to // the certificate. If the OCSP response was not loaded from // storage, we persist it for next time. if ocspResp.Status == ocsp.Good { cert.Certificate.OCSPStaple = ocspBytes cert.OCSP = ocspResp if gotNewOCSP { err := os.MkdirAll(filepath.Join(caddy.AssetsPath(), "ocsp"), 0700) if err != nil { return fmt.Errorf("unable to make OCSP staple path for %v: %v", cert.Names, err) } err = ioutil.WriteFile(ocspCachePath, ocspBytes, 0644) if err != nil { return fmt.Errorf("unable to write OCSP staple file for %v: %v", cert.Names, err) } } } return nil }
go
func stapleOCSP(cert *Certificate, pemBundle []byte) error { if pemBundle == nil { // The function in the acme package that gets OCSP requires a PEM-encoded cert bundle := new(bytes.Buffer) for _, derBytes := range cert.Certificate.Certificate { pem.Encode(bundle, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) } pemBundle = bundle.Bytes() } var ocspBytes []byte var ocspResp *ocsp.Response var ocspErr error var gotNewOCSP bool // First try to load OCSP staple from storage and see if // we can still use it. // TODO: Use Storage interface instead of disk directly var ocspFileNamePrefix string if len(cert.Names) > 0 { ocspFileNamePrefix = cert.Names[0] + "-" } ocspFileName := ocspFileNamePrefix + fastHash(pemBundle) ocspCachePath := filepath.Join(ocspFolder, ocspFileName) cachedOCSP, err := ioutil.ReadFile(ocspCachePath) if err == nil { resp, err := ocsp.ParseResponse(cachedOCSP, nil) if err == nil { if freshOCSP(resp) { // staple is still fresh; use it ocspBytes = cachedOCSP ocspResp = resp } } else { // invalid contents; delete the file // (we do this independently of the maintenance routine because // in this case we know for sure this should be a staple file // because we loaded it by name, whereas the maintenance routine // just iterates the list of files, even if somehow a non-staple // file gets in the folder. in this case we are sure it is corrupt.) err := os.Remove(ocspCachePath) if err != nil { log.Printf("[WARNING] Unable to delete invalid OCSP staple file: %v", err) } } } // If we couldn't get a fresh staple by reading the cache, // then we need to request it from the OCSP responder if ocspResp == nil || len(ocspBytes) == 0 { ocspBytes, ocspResp, ocspErr = acme.GetOCSPForCert(pemBundle) if ocspErr != nil { // An error here is not a problem because a certificate may simply // not contain a link to an OCSP server. But we should log it anyway. // There's nothing else we can do to get OCSP for this certificate, // so we can return here with the error. return fmt.Errorf("no OCSP stapling for %v: %v", cert.Names, ocspErr) } gotNewOCSP = true } // By now, we should have a response. If good, staple it to // the certificate. If the OCSP response was not loaded from // storage, we persist it for next time. if ocspResp.Status == ocsp.Good { cert.Certificate.OCSPStaple = ocspBytes cert.OCSP = ocspResp if gotNewOCSP { err := os.MkdirAll(filepath.Join(caddy.AssetsPath(), "ocsp"), 0700) if err != nil { return fmt.Errorf("unable to make OCSP staple path for %v: %v", cert.Names, err) } err = ioutil.WriteFile(ocspCachePath, ocspBytes, 0644) if err != nil { return fmt.Errorf("unable to write OCSP staple file for %v: %v", cert.Names, err) } } } return nil }
[ "func", "stapleOCSP", "(", "cert", "*", "Certificate", ",", "pemBundle", "[", "]", "byte", ")", "error", "{", "if", "pemBundle", "==", "nil", "{", "// The function in the acme package that gets OCSP requires a PEM-encoded cert", "bundle", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "for", "_", ",", "derBytes", ":=", "range", "cert", ".", "Certificate", ".", "Certificate", "{", "pem", ".", "Encode", "(", "bundle", ",", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "derBytes", "}", ")", "\n", "}", "\n", "pemBundle", "=", "bundle", ".", "Bytes", "(", ")", "\n", "}", "\n\n", "var", "ocspBytes", "[", "]", "byte", "\n", "var", "ocspResp", "*", "ocsp", ".", "Response", "\n", "var", "ocspErr", "error", "\n", "var", "gotNewOCSP", "bool", "\n\n", "// First try to load OCSP staple from storage and see if", "// we can still use it.", "// TODO: Use Storage interface instead of disk directly", "var", "ocspFileNamePrefix", "string", "\n", "if", "len", "(", "cert", ".", "Names", ")", ">", "0", "{", "ocspFileNamePrefix", "=", "cert", ".", "Names", "[", "0", "]", "+", "\"", "\"", "\n", "}", "\n", "ocspFileName", ":=", "ocspFileNamePrefix", "+", "fastHash", "(", "pemBundle", ")", "\n", "ocspCachePath", ":=", "filepath", ".", "Join", "(", "ocspFolder", ",", "ocspFileName", ")", "\n", "cachedOCSP", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "ocspCachePath", ")", "\n", "if", "err", "==", "nil", "{", "resp", ",", "err", ":=", "ocsp", ".", "ParseResponse", "(", "cachedOCSP", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "if", "freshOCSP", "(", "resp", ")", "{", "// staple is still fresh; use it", "ocspBytes", "=", "cachedOCSP", "\n", "ocspResp", "=", "resp", "\n", "}", "\n", "}", "else", "{", "// invalid contents; delete the file", "// (we do this independently of the maintenance routine because", "// in this case we know for sure this should be a staple file", "// because we loaded it by name, whereas the maintenance routine", "// just iterates the list of files, even if somehow a non-staple", "// file gets in the folder. in this case we are sure it is corrupt.)", "err", ":=", "os", ".", "Remove", "(", "ocspCachePath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// If we couldn't get a fresh staple by reading the cache,", "// then we need to request it from the OCSP responder", "if", "ocspResp", "==", "nil", "||", "len", "(", "ocspBytes", ")", "==", "0", "{", "ocspBytes", ",", "ocspResp", ",", "ocspErr", "=", "acme", ".", "GetOCSPForCert", "(", "pemBundle", ")", "\n", "if", "ocspErr", "!=", "nil", "{", "// An error here is not a problem because a certificate may simply", "// not contain a link to an OCSP server. But we should log it anyway.", "// There's nothing else we can do to get OCSP for this certificate,", "// so we can return here with the error.", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cert", ".", "Names", ",", "ocspErr", ")", "\n", "}", "\n", "gotNewOCSP", "=", "true", "\n", "}", "\n\n", "// By now, we should have a response. If good, staple it to", "// the certificate. If the OCSP response was not loaded from", "// storage, we persist it for next time.", "if", "ocspResp", ".", "Status", "==", "ocsp", ".", "Good", "{", "cert", ".", "Certificate", ".", "OCSPStaple", "=", "ocspBytes", "\n", "cert", ".", "OCSP", "=", "ocspResp", "\n", "if", "gotNewOCSP", "{", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Join", "(", "caddy", ".", "AssetsPath", "(", ")", ",", "\"", "\"", ")", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cert", ".", "Names", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "ocspCachePath", ",", "ocspBytes", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cert", ".", "Names", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// stapleOCSP staples OCSP information to cert for hostname name. // If you have it handy, you should pass in the PEM-encoded certificate // bundle; otherwise the DER-encoded cert will have to be PEM-encoded. // If you don't have the PEM blocks already, just pass in nil. // // Errors here are not necessarily fatal, it could just be that the // certificate doesn't have an issuer URL.
[ "stapleOCSP", "staples", "OCSP", "information", "to", "cert", "for", "hostname", "name", ".", "If", "you", "have", "it", "handy", "you", "should", "pass", "in", "the", "PEM", "-", "encoded", "certificate", "bundle", ";", "otherwise", "the", "DER", "-", "encoded", "cert", "will", "have", "to", "be", "PEM", "-", "encoded", ".", "If", "you", "don", "t", "have", "the", "PEM", "blocks", "already", "just", "pass", "in", "nil", ".", "Errors", "here", "are", "not", "necessarily", "fatal", "it", "could", "just", "be", "that", "the", "certificate", "doesn", "t", "have", "an", "issuer", "URL", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/crypto.go#L74-L154
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/crypto.go
makeSelfSignedCert
func makeSelfSignedCert(config *Config) error { // start by generating private key var privKey interface{} var err error switch config.KeyType { case "", acme.EC256: privKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) case acme.EC384: privKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) case acme.RSA2048: privKey, err = rsa.GenerateKey(rand.Reader, 2048) case acme.RSA4096: privKey, err = rsa.GenerateKey(rand.Reader, 4096) case acme.RSA8192: privKey, err = rsa.GenerateKey(rand.Reader, 8192) default: return fmt.Errorf("cannot generate private key; unknown key type %v", config.KeyType) } if err != nil { return fmt.Errorf("failed to generate private key: %v", err) } // create certificate structure with proper values notBefore := time.Now() notAfter := notBefore.Add(24 * time.Hour * 7) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return fmt.Errorf("failed to generate serial number: %v", err) } cert := &x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{Organization: []string{"Caddy Self-Signed"}}, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, } if ip := net.ParseIP(config.Hostname); ip != nil { cert.IPAddresses = append(cert.IPAddresses, ip) } else { cert.DNSNames = append(cert.DNSNames, config.Hostname) } publicKey := func(privKey interface{}) interface{} { switch k := privKey.(type) { case *rsa.PrivateKey: return &k.PublicKey case *ecdsa.PrivateKey: return &k.PublicKey default: return errors.New("unknown key type") } } derBytes, err := x509.CreateCertificate(rand.Reader, cert, cert, publicKey(privKey), privKey) if err != nil { return fmt.Errorf("could not create certificate: %v", err) } cacheCertificate(Certificate{ Certificate: tls.Certificate{ Certificate: [][]byte{derBytes}, PrivateKey: privKey, Leaf: cert, }, Names: cert.DNSNames, NotAfter: cert.NotAfter, Config: config, }) return nil }
go
func makeSelfSignedCert(config *Config) error { // start by generating private key var privKey interface{} var err error switch config.KeyType { case "", acme.EC256: privKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) case acme.EC384: privKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) case acme.RSA2048: privKey, err = rsa.GenerateKey(rand.Reader, 2048) case acme.RSA4096: privKey, err = rsa.GenerateKey(rand.Reader, 4096) case acme.RSA8192: privKey, err = rsa.GenerateKey(rand.Reader, 8192) default: return fmt.Errorf("cannot generate private key; unknown key type %v", config.KeyType) } if err != nil { return fmt.Errorf("failed to generate private key: %v", err) } // create certificate structure with proper values notBefore := time.Now() notAfter := notBefore.Add(24 * time.Hour * 7) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return fmt.Errorf("failed to generate serial number: %v", err) } cert := &x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{Organization: []string{"Caddy Self-Signed"}}, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, } if ip := net.ParseIP(config.Hostname); ip != nil { cert.IPAddresses = append(cert.IPAddresses, ip) } else { cert.DNSNames = append(cert.DNSNames, config.Hostname) } publicKey := func(privKey interface{}) interface{} { switch k := privKey.(type) { case *rsa.PrivateKey: return &k.PublicKey case *ecdsa.PrivateKey: return &k.PublicKey default: return errors.New("unknown key type") } } derBytes, err := x509.CreateCertificate(rand.Reader, cert, cert, publicKey(privKey), privKey) if err != nil { return fmt.Errorf("could not create certificate: %v", err) } cacheCertificate(Certificate{ Certificate: tls.Certificate{ Certificate: [][]byte{derBytes}, PrivateKey: privKey, Leaf: cert, }, Names: cert.DNSNames, NotAfter: cert.NotAfter, Config: config, }) return nil }
[ "func", "makeSelfSignedCert", "(", "config", "*", "Config", ")", "error", "{", "// start by generating private key", "var", "privKey", "interface", "{", "}", "\n", "var", "err", "error", "\n", "switch", "config", ".", "KeyType", "{", "case", "\"", "\"", ",", "acme", ".", "EC256", ":", "privKey", ",", "err", "=", "ecdsa", ".", "GenerateKey", "(", "elliptic", ".", "P256", "(", ")", ",", "rand", ".", "Reader", ")", "\n", "case", "acme", ".", "EC384", ":", "privKey", ",", "err", "=", "ecdsa", ".", "GenerateKey", "(", "elliptic", ".", "P384", "(", ")", ",", "rand", ".", "Reader", ")", "\n", "case", "acme", ".", "RSA2048", ":", "privKey", ",", "err", "=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "2048", ")", "\n", "case", "acme", ".", "RSA4096", ":", "privKey", ",", "err", "=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "4096", ")", "\n", "case", "acme", ".", "RSA8192", ":", "privKey", ",", "err", "=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "8192", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "KeyType", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// create certificate structure with proper values", "notBefore", ":=", "time", ".", "Now", "(", ")", "\n", "notAfter", ":=", "notBefore", ".", "Add", "(", "24", "*", "time", ".", "Hour", "*", "7", ")", "\n", "serialNumberLimit", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "big", ".", "NewInt", "(", "1", ")", ",", "128", ")", "\n", "serialNumber", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "serialNumberLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "cert", ":=", "&", "x509", ".", "Certificate", "{", "SerialNumber", ":", "serialNumber", ",", "Subject", ":", "pkix", ".", "Name", "{", "Organization", ":", "[", "]", "string", "{", "\"", "\"", "}", "}", ",", "NotBefore", ":", "notBefore", ",", "NotAfter", ":", "notAfter", ",", "KeyUsage", ":", "x509", ".", "KeyUsageKeyEncipherment", "|", "x509", ".", "KeyUsageDigitalSignature", ",", "ExtKeyUsage", ":", "[", "]", "x509", ".", "ExtKeyUsage", "{", "x509", ".", "ExtKeyUsageServerAuth", "}", ",", "}", "\n", "if", "ip", ":=", "net", ".", "ParseIP", "(", "config", ".", "Hostname", ")", ";", "ip", "!=", "nil", "{", "cert", ".", "IPAddresses", "=", "append", "(", "cert", ".", "IPAddresses", ",", "ip", ")", "\n", "}", "else", "{", "cert", ".", "DNSNames", "=", "append", "(", "cert", ".", "DNSNames", ",", "config", ".", "Hostname", ")", "\n", "}", "\n\n", "publicKey", ":=", "func", "(", "privKey", "interface", "{", "}", ")", "interface", "{", "}", "{", "switch", "k", ":=", "privKey", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PrivateKey", ":", "return", "&", "k", ".", "PublicKey", "\n", "case", "*", "ecdsa", ".", "PrivateKey", ":", "return", "&", "k", ".", "PublicKey", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "derBytes", ",", "err", ":=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "cert", ",", "cert", ",", "publicKey", "(", "privKey", ")", ",", "privKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "cacheCertificate", "(", "Certificate", "{", "Certificate", ":", "tls", ".", "Certificate", "{", "Certificate", ":", "[", "]", "[", "]", "byte", "{", "derBytes", "}", ",", "PrivateKey", ":", "privKey", ",", "Leaf", ":", "cert", ",", "}", ",", "Names", ":", "cert", ".", "DNSNames", ",", "NotAfter", ":", "cert", ".", "NotAfter", ",", "Config", ":", "config", ",", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// makeSelfSignedCert makes a self-signed certificate according // to the parameters in config. It then caches the certificate // in our cache.
[ "makeSelfSignedCert", "makes", "a", "self", "-", "signed", "certificate", "according", "to", "the", "parameters", "in", "config", ".", "It", "then", "caches", "the", "certificate", "in", "our", "cache", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/crypto.go#L159-L230
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/crypto.go
fastHash
func fastHash(input []byte) string { h := fnv.New32a() h.Write([]byte(input)) return fmt.Sprintf("%x", h.Sum32()) }
go
func fastHash(input []byte) string { h := fnv.New32a() h.Write([]byte(input)) return fmt.Sprintf("%x", h.Sum32()) }
[ "func", "fastHash", "(", "input", "[", "]", "byte", ")", "string", "{", "h", ":=", "fnv", ".", "New32a", "(", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "input", ")", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "h", ".", "Sum32", "(", ")", ")", "\n", "}" ]
// fastHash hashes input using a hashing algorithm that // is fast, and returns the hash as a hex-encoded string. // Do not use this for cryptographic purposes.
[ "fastHash", "hashes", "input", "using", "a", "hashing", "algorithm", "that", "is", "fast", "and", "returns", "the", "hash", "as", "a", "hex", "-", "encoded", "string", ".", "Do", "not", "use", "this", "for", "cryptographic", "purposes", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/crypto.go#L310-L314
train
inverse-inc/packetfence
go/coredns/request/request.go
ErrorMessage
func (r *Request) ErrorMessage(rcode int) *dns.Msg { m := new(dns.Msg) m.SetRcode(r.Req, rcode) return m }
go
func (r *Request) ErrorMessage(rcode int) *dns.Msg { m := new(dns.Msg) m.SetRcode(r.Req, rcode) return m }
[ "func", "(", "r", "*", "Request", ")", "ErrorMessage", "(", "rcode", "int", ")", "*", "dns", ".", "Msg", "{", "m", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "m", ".", "SetRcode", "(", "r", ".", "Req", ",", "rcode", ")", "\n", "return", "m", "\n", "}" ]
// ErrorMessage returns an error message suitable for sending // back to the client.
[ "ErrorMessage", "returns", "an", "error", "message", "suitable", "for", "sending", "back", "to", "the", "client", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/request/request.go#L298-L302
train
inverse-inc/packetfence
go/firewallsso/factory.go
NewFactory
func NewFactory(ctx context.Context) Factory { f := Factory{} f.typeRegistry = make(map[string]reflect.Type) f.typeRegistry["BarracudaNG"] = reflect.TypeOf(&BarracudaNG{}).Elem() f.typeRegistry["Iboss"] = reflect.TypeOf(&Iboss{}).Elem() f.typeRegistry["PaloAlto"] = reflect.TypeOf(&PaloAlto{}).Elem() f.typeRegistry["FortiGate"] = reflect.TypeOf(&FortiGate{}).Elem() f.typeRegistry["Checkpoint"] = reflect.TypeOf(&Checkpoint{}).Elem() f.typeRegistry["WatchGuard"] = reflect.TypeOf(&WatchGuard{}).Elem() f.typeRegistry["JSONRPC"] = reflect.TypeOf(&JSONRPC{}).Elem() f.typeRegistry["JuniperSRX"] = reflect.TypeOf(&JuniperSRX{}).Elem() return f }
go
func NewFactory(ctx context.Context) Factory { f := Factory{} f.typeRegistry = make(map[string]reflect.Type) f.typeRegistry["BarracudaNG"] = reflect.TypeOf(&BarracudaNG{}).Elem() f.typeRegistry["Iboss"] = reflect.TypeOf(&Iboss{}).Elem() f.typeRegistry["PaloAlto"] = reflect.TypeOf(&PaloAlto{}).Elem() f.typeRegistry["FortiGate"] = reflect.TypeOf(&FortiGate{}).Elem() f.typeRegistry["Checkpoint"] = reflect.TypeOf(&Checkpoint{}).Elem() f.typeRegistry["WatchGuard"] = reflect.TypeOf(&WatchGuard{}).Elem() f.typeRegistry["JSONRPC"] = reflect.TypeOf(&JSONRPC{}).Elem() f.typeRegistry["JuniperSRX"] = reflect.TypeOf(&JuniperSRX{}).Elem() return f }
[ "func", "NewFactory", "(", "ctx", "context", ".", "Context", ")", "Factory", "{", "f", ":=", "Factory", "{", "}", "\n", "f", ".", "typeRegistry", "=", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "BarracudaNG", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "Iboss", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "PaloAlto", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "FortiGate", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "Checkpoint", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "WatchGuard", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "JSONRPC", "{", "}", ")", ".", "Elem", "(", ")", "\n", "f", ".", "typeRegistry", "[", "\"", "\"", "]", "=", "reflect", ".", "TypeOf", "(", "&", "JuniperSRX", "{", "}", ")", ".", "Elem", "(", ")", "\n", "return", "f", "\n", "}" ]
// Create a new FirewallSSO factory containing all the valid types
[ "Create", "a", "new", "FirewallSSO", "factory", "containing", "all", "the", "valid", "types" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/factory.go#L16-L28
train
inverse-inc/packetfence
go/firewallsso/factory.go
Instantiate
func (f *Factory) Instantiate(ctx context.Context, id string) (FirewallSSOInt, error) { firewall := FirewallSSO{} firewall.PfconfigHashNS = id _, err := pfconfigdriver.FetchDecodeSocketCache(ctx, &firewall) if err != nil { return nil, err } if oType, ok := f.typeRegistry[firewall.Type]; ok { or := reflect.New(oType) or.Elem().FieldByName("PfconfigHashNS").SetString(id) firewall2 := or.Interface().(pfconfigdriver.PfconfigObject) _, err = pfconfigdriver.FetchDecodeSocketCache(ctx, firewall2) if err != nil { return nil, err } fwint := firewall2.(FirewallSSOInt) err = fwint.init(ctx) if err != nil { return nil, err } err = fwint.initChild(ctx) if err != nil { return nil, err } return fwint, nil } else { return nil, errors.New("Cannot find the type of the object") } }
go
func (f *Factory) Instantiate(ctx context.Context, id string) (FirewallSSOInt, error) { firewall := FirewallSSO{} firewall.PfconfigHashNS = id _, err := pfconfigdriver.FetchDecodeSocketCache(ctx, &firewall) if err != nil { return nil, err } if oType, ok := f.typeRegistry[firewall.Type]; ok { or := reflect.New(oType) or.Elem().FieldByName("PfconfigHashNS").SetString(id) firewall2 := or.Interface().(pfconfigdriver.PfconfigObject) _, err = pfconfigdriver.FetchDecodeSocketCache(ctx, firewall2) if err != nil { return nil, err } fwint := firewall2.(FirewallSSOInt) err = fwint.init(ctx) if err != nil { return nil, err } err = fwint.initChild(ctx) if err != nil { return nil, err } return fwint, nil } else { return nil, errors.New("Cannot find the type of the object") } }
[ "func", "(", "f", "*", "Factory", ")", "Instantiate", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "FirewallSSOInt", ",", "error", ")", "{", "firewall", ":=", "FirewallSSO", "{", "}", "\n", "firewall", ".", "PfconfigHashNS", "=", "id", "\n", "_", ",", "err", ":=", "pfconfigdriver", ".", "FetchDecodeSocketCache", "(", "ctx", ",", "&", "firewall", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "oType", ",", "ok", ":=", "f", ".", "typeRegistry", "[", "firewall", ".", "Type", "]", ";", "ok", "{", "or", ":=", "reflect", ".", "New", "(", "oType", ")", "\n", "or", ".", "Elem", "(", ")", ".", "FieldByName", "(", "\"", "\"", ")", ".", "SetString", "(", "id", ")", "\n", "firewall2", ":=", "or", ".", "Interface", "(", ")", ".", "(", "pfconfigdriver", ".", "PfconfigObject", ")", "\n", "_", ",", "err", "=", "pfconfigdriver", ".", "FetchDecodeSocketCache", "(", "ctx", ",", "firewall2", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fwint", ":=", "firewall2", ".", "(", "FirewallSSOInt", ")", "\n\n", "err", "=", "fwint", ".", "init", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "fwint", ".", "initChild", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "fwint", ",", "nil", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Instantiate a new FirewallSSO given its configuration ID in PacketFence
[ "Instantiate", "a", "new", "FirewallSSO", "given", "its", "configuration", "ID", "in", "PacketFence" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/factory.go#L31-L63
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/client.go
Renew
func (c *ACMEClient) Renew(name string) error { // Get access to ACME storage storage, err := c.config.StorageFor(c.config.CAUrl) if err != nil { return err } waiter, err := storage.TryLock(name) if err != nil { return err } if waiter != nil { log.Printf("[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting", name) waiter.Wait() return nil // we assume the process with the lock succeeded, rather than hammering this execution path again } defer func() { if err := storage.Unlock(name); err != nil { log.Printf("[ERROR] Unable to unlock renew call for %s: %v", name, err) } }() // Prepare for renewal (load PEM cert, key, and meta) siteData, err := storage.LoadSite(name) if err != nil { return err } var certMeta acme.CertificateResource err = json.Unmarshal(siteData.Meta, &certMeta) certMeta.Certificate = siteData.Cert certMeta.PrivateKey = siteData.Key // Perform renewal and retry if necessary, but not too many times. var newCertMeta acme.CertificateResource var success bool for attempts := 0; attempts < 2; attempts++ { namesObtaining.Add([]string{name}) acmeMu.Lock() newCertMeta, err = c.acmeClient.RenewCertificate(certMeta, true, c.config.MustStaple) acmeMu.Unlock() namesObtaining.Remove([]string{name}) if err == nil { success = true break } // If the legal terms were updated and need to be // agreed to again, we can handle that. if _, ok := err.(acme.TOSError); ok { err := c.acmeClient.AgreeToTOS() if err != nil { return err } continue } // For any other kind of error, wait 10s and try again. wait := 10 * time.Second log.Printf("[ERROR] Renewing: %v; trying again in %s", err, wait) time.Sleep(wait) } if !success { return errors.New("too many renewal attempts; last error: " + err.Error()) } return saveCertResource(storage, newCertMeta) }
go
func (c *ACMEClient) Renew(name string) error { // Get access to ACME storage storage, err := c.config.StorageFor(c.config.CAUrl) if err != nil { return err } waiter, err := storage.TryLock(name) if err != nil { return err } if waiter != nil { log.Printf("[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting", name) waiter.Wait() return nil // we assume the process with the lock succeeded, rather than hammering this execution path again } defer func() { if err := storage.Unlock(name); err != nil { log.Printf("[ERROR] Unable to unlock renew call for %s: %v", name, err) } }() // Prepare for renewal (load PEM cert, key, and meta) siteData, err := storage.LoadSite(name) if err != nil { return err } var certMeta acme.CertificateResource err = json.Unmarshal(siteData.Meta, &certMeta) certMeta.Certificate = siteData.Cert certMeta.PrivateKey = siteData.Key // Perform renewal and retry if necessary, but not too many times. var newCertMeta acme.CertificateResource var success bool for attempts := 0; attempts < 2; attempts++ { namesObtaining.Add([]string{name}) acmeMu.Lock() newCertMeta, err = c.acmeClient.RenewCertificate(certMeta, true, c.config.MustStaple) acmeMu.Unlock() namesObtaining.Remove([]string{name}) if err == nil { success = true break } // If the legal terms were updated and need to be // agreed to again, we can handle that. if _, ok := err.(acme.TOSError); ok { err := c.acmeClient.AgreeToTOS() if err != nil { return err } continue } // For any other kind of error, wait 10s and try again. wait := 10 * time.Second log.Printf("[ERROR] Renewing: %v; trying again in %s", err, wait) time.Sleep(wait) } if !success { return errors.New("too many renewal attempts; last error: " + err.Error()) } return saveCertResource(storage, newCertMeta) }
[ "func", "(", "c", "*", "ACMEClient", ")", "Renew", "(", "name", "string", ")", "error", "{", "// Get access to ACME storage", "storage", ",", "err", ":=", "c", ".", "config", ".", "StorageFor", "(", "c", ".", "config", ".", "CAUrl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "waiter", ",", "err", ":=", "storage", ".", "TryLock", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "waiter", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "name", ")", "\n", "waiter", ".", "Wait", "(", ")", "\n", "return", "nil", "// we assume the process with the lock succeeded, rather than hammering this execution path again", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", ":=", "storage", ".", "Unlock", "(", "name", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Prepare for renewal (load PEM cert, key, and meta)", "siteData", ",", "err", ":=", "storage", ".", "LoadSite", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "certMeta", "acme", ".", "CertificateResource", "\n", "err", "=", "json", ".", "Unmarshal", "(", "siteData", ".", "Meta", ",", "&", "certMeta", ")", "\n", "certMeta", ".", "Certificate", "=", "siteData", ".", "Cert", "\n", "certMeta", ".", "PrivateKey", "=", "siteData", ".", "Key", "\n\n", "// Perform renewal and retry if necessary, but not too many times.", "var", "newCertMeta", "acme", ".", "CertificateResource", "\n", "var", "success", "bool", "\n", "for", "attempts", ":=", "0", ";", "attempts", "<", "2", ";", "attempts", "++", "{", "namesObtaining", ".", "Add", "(", "[", "]", "string", "{", "name", "}", ")", "\n", "acmeMu", ".", "Lock", "(", ")", "\n", "newCertMeta", ",", "err", "=", "c", ".", "acmeClient", ".", "RenewCertificate", "(", "certMeta", ",", "true", ",", "c", ".", "config", ".", "MustStaple", ")", "\n", "acmeMu", ".", "Unlock", "(", ")", "\n", "namesObtaining", ".", "Remove", "(", "[", "]", "string", "{", "name", "}", ")", "\n", "if", "err", "==", "nil", "{", "success", "=", "true", "\n", "break", "\n", "}", "\n\n", "// If the legal terms were updated and need to be", "// agreed to again, we can handle that.", "if", "_", ",", "ok", ":=", "err", ".", "(", "acme", ".", "TOSError", ")", ";", "ok", "{", "err", ":=", "c", ".", "acmeClient", ".", "AgreeToTOS", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// For any other kind of error, wait 10s and try again.", "wait", ":=", "10", "*", "time", ".", "Second", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ",", "wait", ")", "\n", "time", ".", "Sleep", "(", "wait", ")", "\n", "}", "\n\n", "if", "!", "success", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "saveCertResource", "(", "storage", ",", "newCertMeta", ")", "\n", "}" ]
// Renew renews the managed certificate for name. This function is // safe for concurrent use. // // Callers who have access to a Config value should use the RenewCert // method on that instead of this lower-level method.
[ "Renew", "renews", "the", "managed", "certificate", "for", "name", ".", "This", "function", "is", "safe", "for", "concurrent", "use", ".", "Callers", "who", "have", "access", "to", "a", "Config", "value", "should", "use", "the", "RenewCert", "method", "on", "that", "instead", "of", "this", "lower", "-", "level", "method", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L250-L317
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/client.go
Revoke
func (c *ACMEClient) Revoke(name string) error { storage, err := c.config.StorageFor(c.config.CAUrl) if err != nil { return err } siteExists, err := storage.SiteExists(name) if err != nil { return err } if !siteExists { return errors.New("no certificate and key for " + name) } siteData, err := storage.LoadSite(name) if err != nil { return err } err = c.acmeClient.RevokeCertificate(siteData.Cert) if err != nil { return err } err = storage.DeleteSite(name) if err != nil { return errors.New("certificate revoked, but unable to delete certificate file: " + err.Error()) } return nil }
go
func (c *ACMEClient) Revoke(name string) error { storage, err := c.config.StorageFor(c.config.CAUrl) if err != nil { return err } siteExists, err := storage.SiteExists(name) if err != nil { return err } if !siteExists { return errors.New("no certificate and key for " + name) } siteData, err := storage.LoadSite(name) if err != nil { return err } err = c.acmeClient.RevokeCertificate(siteData.Cert) if err != nil { return err } err = storage.DeleteSite(name) if err != nil { return errors.New("certificate revoked, but unable to delete certificate file: " + err.Error()) } return nil }
[ "func", "(", "c", "*", "ACMEClient", ")", "Revoke", "(", "name", "string", ")", "error", "{", "storage", ",", "err", ":=", "c", ".", "config", ".", "StorageFor", "(", "c", ".", "config", ".", "CAUrl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "siteExists", ",", "err", ":=", "storage", ".", "SiteExists", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "siteExists", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "name", ")", "\n", "}", "\n\n", "siteData", ",", "err", ":=", "storage", ".", "LoadSite", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "c", ".", "acmeClient", ".", "RevokeCertificate", "(", "siteData", ".", "Cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "storage", ".", "DeleteSite", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Revoke revokes the certificate for name and deltes // it from storage.
[ "Revoke", "revokes", "the", "certificate", "for", "name", "and", "deltes", "it", "from", "storage", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L321-L352
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/client.go
Add
func (c *nameCoordinator) Add(names []string) { c.mu.Lock() for _, name := range names { c.names[strings.ToLower(name)] = struct{}{} } c.mu.Unlock() }
go
func (c *nameCoordinator) Add(names []string) { c.mu.Lock() for _, name := range names { c.names[strings.ToLower(name)] = struct{}{} } c.mu.Unlock() }
[ "func", "(", "c", "*", "nameCoordinator", ")", "Add", "(", "names", "[", "]", "string", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "c", ".", "names", "[", "strings", ".", "ToLower", "(", "name", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Add adds names to c. It is safe for concurrent use.
[ "Add", "adds", "names", "to", "c", ".", "It", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L369-L375
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/client.go
Remove
func (c *nameCoordinator) Remove(names []string) { c.mu.Lock() for _, name := range names { delete(c.names, strings.ToLower(name)) } c.mu.Unlock() }
go
func (c *nameCoordinator) Remove(names []string) { c.mu.Lock() for _, name := range names { delete(c.names, strings.ToLower(name)) } c.mu.Unlock() }
[ "func", "(", "c", "*", "nameCoordinator", ")", "Remove", "(", "names", "[", "]", "string", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "delete", "(", "c", ".", "names", ",", "strings", ".", "ToLower", "(", "name", ")", ")", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove removes names from c. It is safe for concurrent use.
[ "Remove", "removes", "names", "from", "c", ".", "It", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L378-L384
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/client.go
Has
func (c *nameCoordinator) Has(name string) bool { hostname, _, err := net.SplitHostPort(name) if err != nil { hostname = name } c.mu.RLock() _, ok := c.names[strings.ToLower(hostname)] c.mu.RUnlock() return ok }
go
func (c *nameCoordinator) Has(name string) bool { hostname, _, err := net.SplitHostPort(name) if err != nil { hostname = name } c.mu.RLock() _, ok := c.names[strings.ToLower(hostname)] c.mu.RUnlock() return ok }
[ "func", "(", "c", "*", "nameCoordinator", ")", "Has", "(", "name", "string", ")", "bool", "{", "hostname", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "hostname", "=", "name", "\n", "}", "\n", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "_", ",", "ok", ":=", "c", ".", "names", "[", "strings", ".", "ToLower", "(", "hostname", ")", "]", "\n", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "ok", "\n", "}" ]
// Has returns true if c has name. It is safe for concurrent use.
[ "Has", "returns", "true", "if", "c", "has", "name", ".", "It", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/client.go#L387-L396
train
inverse-inc/packetfence
go/coredns/plugin/metrics/metrics.go
OnShutdown
func (m *Metrics) OnShutdown() error { if m.ln != nil { return m.ln.Close() } return nil }
go
func (m *Metrics) OnShutdown() error { if m.ln != nil { return m.ln.Close() } return nil }
[ "func", "(", "m", "*", "Metrics", ")", "OnShutdown", "(", ")", "error", "{", "if", "m", ".", "ln", "!=", "nil", "{", "return", "m", ".", "ln", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// OnShutdown tears down the metrics on shutdown and restart.
[ "OnShutdown", "tears", "down", "the", "metrics", "on", "shutdown", "and", "restart", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/metrics/metrics.go#L84-L89
train
inverse-inc/packetfence
go/sharedutils/util.go
Inc
func Inc(ip net.IP) { for j := len(ip) - 1; j >= 0; j-- { ip[j]++ if ip[j] > 0 { break } } }
go
func Inc(ip net.IP) { for j := len(ip) - 1; j >= 0; j-- { ip[j]++ if ip[j] > 0 { break } } }
[ "func", "Inc", "(", "ip", "net", ".", "IP", ")", "{", "for", "j", ":=", "len", "(", "ip", ")", "-", "1", ";", "j", ">=", "0", ";", "j", "--", "{", "ip", "[", "j", "]", "++", "\n", "if", "ip", "[", "j", "]", ">", "0", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Inc function use to increment an ip
[ "Inc", "function", "use", "to", "increment", "an", "ip" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L172-L179
train
inverse-inc/packetfence
go/sharedutils/util.go
Dec
func Dec(ip net.IP) { for j := len(ip) - 1; j >= 0; j-- { ip[j]-- if ip[j] == 255 { continue } if ip[j] > 0 { break } } }
go
func Dec(ip net.IP) { for j := len(ip) - 1; j >= 0; j-- { ip[j]-- if ip[j] == 255 { continue } if ip[j] > 0 { break } } }
[ "func", "Dec", "(", "ip", "net", ".", "IP", ")", "{", "for", "j", ":=", "len", "(", "ip", ")", "-", "1", ";", "j", ">=", "0", ";", "j", "--", "{", "ip", "[", "j", "]", "--", "\n", "if", "ip", "[", "j", "]", "==", "255", "{", "continue", "\n", "}", "\n", "if", "ip", "[", "j", "]", ">", "0", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Dec function use to decrement an ip
[ "Dec", "function", "use", "to", "decrement", "an", "ip" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L182-L192
train
inverse-inc/packetfence
go/sharedutils/util.go
ConvertToString
func ConvertToString(b []byte) string { s := make([]string, len(b)) for i := range b { s[i] = strconv.Itoa(int(b[i])) } return strings.Join(s, ",") }
go
func ConvertToString(b []byte) string { s := make([]string, len(b)) for i := range b { s[i] = strconv.Itoa(int(b[i])) } return strings.Join(s, ",") }
[ "func", "ConvertToString", "(", "b", "[", "]", "byte", ")", "string", "{", "s", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "b", ")", ")", "\n", "for", "i", ":=", "range", "b", "{", "s", "[", "i", "]", "=", "strconv", ".", "Itoa", "(", "int", "(", "b", "[", "i", "]", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "s", ",", "\"", "\"", ")", "\n", "}" ]
// ConvertToSting convert byte to string
[ "ConvertToSting", "convert", "byte", "to", "string" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L195-L201
train
inverse-inc/packetfence
go/sharedutils/util.go
ConvertToByte
func ConvertToByte(b string) []byte { s := strings.Split(b, ",") var result []byte for i := range s { value, _ := strconv.Atoi(s[i]) result = append(result, byte(value)) } return result }
go
func ConvertToByte(b string) []byte { s := strings.Split(b, ",") var result []byte for i := range s { value, _ := strconv.Atoi(s[i]) result = append(result, byte(value)) } return result }
[ "func", "ConvertToByte", "(", "b", "string", ")", "[", "]", "byte", "{", "s", ":=", "strings", ".", "Split", "(", "b", ",", "\"", "\"", ")", "\n", "var", "result", "[", "]", "byte", "\n", "for", "i", ":=", "range", "s", "{", "value", ",", "_", ":=", "strconv", ".", "Atoi", "(", "s", "[", "i", "]", ")", "\n", "result", "=", "append", "(", "result", ",", "byte", "(", "value", ")", ")", "\n\n", "}", "\n", "return", "result", "\n", "}" ]
// ConvertToByte convert string to byte
[ "ConvertToByte", "convert", "string", "to", "byte" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L204-L213
train
inverse-inc/packetfence
go/sharedutils/util.go
ByteToString
func ByteToString(a []byte) string { const hexDigit = "0123456789abcdef" if len(a) == 0 { return "" } buf := make([]byte, 0, len(a)*3-1) for i, b := range a { if i > 0 { buf = append(buf, ':') } buf = append(buf, hexDigit[b>>4]) buf = append(buf, hexDigit[b&0xF]) } return string(buf) }
go
func ByteToString(a []byte) string { const hexDigit = "0123456789abcdef" if len(a) == 0 { return "" } buf := make([]byte, 0, len(a)*3-1) for i, b := range a { if i > 0 { buf = append(buf, ':') } buf = append(buf, hexDigit[b>>4]) buf = append(buf, hexDigit[b&0xF]) } return string(buf) }
[ "func", "ByteToString", "(", "a", "[", "]", "byte", ")", "string", "{", "const", "hexDigit", "=", "\"", "\"", "\n", "if", "len", "(", "a", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "a", ")", "*", "3", "-", "1", ")", "\n", "for", "i", ",", "b", ":=", "range", "a", "{", "if", "i", ">", "0", "{", "buf", "=", "append", "(", "buf", ",", "':'", ")", "\n", "}", "\n", "buf", "=", "append", "(", "buf", ",", "hexDigit", "[", "b", ">>", "4", "]", ")", "\n", "buf", "=", "append", "(", "buf", ",", "hexDigit", "[", "b", "&", "0xF", "]", ")", "\n", "}", "\n", "return", "string", "(", "buf", ")", "\n", "}" ]
// ByteToString return a human readeable string of the byte
[ "ByteToString", "return", "a", "human", "readeable", "string", "of", "the", "byte" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/sharedutils/util.go#L216-L230
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/config.go
RenewCert
func (c *Config) RenewCert(name string, allowPrompts bool) error { client, err := newACMEClient(c, allowPrompts) if err != nil { return err } return client.Renew(name) }
go
func (c *Config) RenewCert(name string, allowPrompts bool) error { client, err := newACMEClient(c, allowPrompts) if err != nil { return err } return client.Renew(name) }
[ "func", "(", "c", "*", "Config", ")", "RenewCert", "(", "name", "string", ",", "allowPrompts", "bool", ")", "error", "{", "client", ",", "err", ":=", "newACMEClient", "(", "c", ",", "allowPrompts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "client", ".", "Renew", "(", "name", ")", "\n", "}" ]
// RenewCert renews the certificate for name using c. It stows the // renewed certificate and its assets in storage if successful.
[ "RenewCert", "renews", "the", "certificate", "for", "name", "using", "c", ".", "It", "stows", "the", "renewed", "certificate", "and", "its", "assets", "in", "storage", "if", "successful", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/config.go#L164-L170
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/config.go
StorageFor
func (c *Config) StorageFor(caURL string) (Storage, error) { // Validate CA URL if caURL == "" { caURL = DefaultCAUrl } if caURL == "" { return nil, fmt.Errorf("cannot create storage without CA URL") } caURL = strings.ToLower(caURL) // scheme required or host will be parsed as path (as of Go 1.6) if !strings.Contains(caURL, "://") { caURL = "https://" + caURL } u, err := url.Parse(caURL) if err != nil { return nil, fmt.Errorf("%s: unable to parse CA URL: %v", caURL, err) } if u.Host == "" { return nil, fmt.Errorf("%s: no host in CA URL", caURL) } // Create the storage based on the URL var s Storage if c.StorageProvider == "" { c.StorageProvider = "file" } creator, ok := storageProviders[c.StorageProvider] if !ok { return nil, fmt.Errorf("%s: Unknown storage: %v", caURL, c.StorageProvider) } s, err = creator(u) if err != nil { return nil, fmt.Errorf("%s: unable to create custom storage '%v': %v", caURL, c.StorageProvider, err) } return s, nil }
go
func (c *Config) StorageFor(caURL string) (Storage, error) { // Validate CA URL if caURL == "" { caURL = DefaultCAUrl } if caURL == "" { return nil, fmt.Errorf("cannot create storage without CA URL") } caURL = strings.ToLower(caURL) // scheme required or host will be parsed as path (as of Go 1.6) if !strings.Contains(caURL, "://") { caURL = "https://" + caURL } u, err := url.Parse(caURL) if err != nil { return nil, fmt.Errorf("%s: unable to parse CA URL: %v", caURL, err) } if u.Host == "" { return nil, fmt.Errorf("%s: no host in CA URL", caURL) } // Create the storage based on the URL var s Storage if c.StorageProvider == "" { c.StorageProvider = "file" } creator, ok := storageProviders[c.StorageProvider] if !ok { return nil, fmt.Errorf("%s: Unknown storage: %v", caURL, c.StorageProvider) } s, err = creator(u) if err != nil { return nil, fmt.Errorf("%s: unable to create custom storage '%v': %v", caURL, c.StorageProvider, err) } return s, nil }
[ "func", "(", "c", "*", "Config", ")", "StorageFor", "(", "caURL", "string", ")", "(", "Storage", ",", "error", ")", "{", "// Validate CA URL", "if", "caURL", "==", "\"", "\"", "{", "caURL", "=", "DefaultCAUrl", "\n", "}", "\n", "if", "caURL", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "caURL", "=", "strings", ".", "ToLower", "(", "caURL", ")", "\n\n", "// scheme required or host will be parsed as path (as of Go 1.6)", "if", "!", "strings", ".", "Contains", "(", "caURL", ",", "\"", "\"", ")", "{", "caURL", "=", "\"", "\"", "+", "caURL", "\n", "}", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "caURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caURL", ",", "err", ")", "\n", "}", "\n\n", "if", "u", ".", "Host", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caURL", ")", "\n", "}", "\n\n", "// Create the storage based on the URL", "var", "s", "Storage", "\n", "if", "c", ".", "StorageProvider", "==", "\"", "\"", "{", "c", ".", "StorageProvider", "=", "\"", "\"", "\n", "}", "\n\n", "creator", ",", "ok", ":=", "storageProviders", "[", "c", ".", "StorageProvider", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caURL", ",", "c", ".", "StorageProvider", ")", "\n", "}", "\n\n", "s", ",", "err", "=", "creator", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caURL", ",", "c", ".", "StorageProvider", ",", "err", ")", "\n", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// StorageFor obtains a TLS Storage instance for the given CA URL which should // be unique for every different ACME CA. If a StorageCreator is set on this // Config, it will be used. Otherwise the default file storage implementation // is used. When the error is nil, this is guaranteed to return a non-nil // Storage instance.
[ "StorageFor", "obtains", "a", "TLS", "Storage", "instance", "for", "the", "given", "CA", "URL", "which", "should", "be", "unique", "for", "every", "different", "ACME", "CA", ".", "If", "a", "StorageCreator", "is", "set", "on", "this", "Config", "it", "will", "be", "used", ".", "Otherwise", "the", "default", "file", "storage", "implementation", "is", "used", ".", "When", "the", "error", "is", "nil", "this", "is", "guaranteed", "to", "return", "a", "non", "-", "nil", "Storage", "instance", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/config.go#L177-L218
train
inverse-inc/packetfence
go/coredns/plugin/auto/zone.go
Remove
func (z *Zones) Remove(name string) { z.Lock() if zo, ok := z.Z[name]; ok && !zo.NoReload { zo.ReloadShutdown <- true } delete(z.Z, name) // TODO(miek): just regenerate Names (might be bad if you have a lot of zones...) z.names = []string{} for n := range z.Z { z.names = append(z.names, n) } z.Unlock() }
go
func (z *Zones) Remove(name string) { z.Lock() if zo, ok := z.Z[name]; ok && !zo.NoReload { zo.ReloadShutdown <- true } delete(z.Z, name) // TODO(miek): just regenerate Names (might be bad if you have a lot of zones...) z.names = []string{} for n := range z.Z { z.names = append(z.names, n) } z.Unlock() }
[ "func", "(", "z", "*", "Zones", ")", "Remove", "(", "name", "string", ")", "{", "z", ".", "Lock", "(", ")", "\n\n", "if", "zo", ",", "ok", ":=", "z", ".", "Z", "[", "name", "]", ";", "ok", "&&", "!", "zo", ".", "NoReload", "{", "zo", ".", "ReloadShutdown", "<-", "true", "\n", "}", "\n\n", "delete", "(", "z", ".", "Z", ",", "name", ")", "\n\n", "// TODO(miek): just regenerate Names (might be bad if you have a lot of zones...)", "z", ".", "names", "=", "[", "]", "string", "{", "}", "\n", "for", "n", ":=", "range", "z", ".", "Z", "{", "z", ".", "names", "=", "append", "(", "z", ".", "names", ",", "n", ")", "\n", "}", "\n\n", "z", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove removes the zone named name from z. It also stop the the zone's reload goroutine.
[ "Remove", "removes", "the", "zone", "named", "name", "from", "z", ".", "It", "also", "stop", "the", "the", "zone", "s", "reload", "goroutine", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/auto/zone.go#L60-L76
train
inverse-inc/packetfence
go/firewallsso/base.go
init
func (fw *FirewallSSO) init(ctx context.Context) error { for _, net := range fw.Networks { err := net.init(ctx) if err != nil { return err } } return nil }
go
func (fw *FirewallSSO) init(ctx context.Context) error { for _, net := range fw.Networks { err := net.init(ctx) if err != nil { return err } } return nil }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "init", "(", "ctx", "context", ".", "Context", ")", "error", "{", "for", "_", ",", "net", ":=", "range", "fw", ".", "Networks", "{", "err", ":=", "net", ".", "init", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Builds all networks, meant to be called after the data is loaded into the struct attributes
[ "Builds", "all", "networks", "meant", "to", "be", "called", "after", "the", "data", "is", "loaded", "into", "the", "struct", "attributes" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L61-L69
train
inverse-inc/packetfence
go/firewallsso/base.go
init
func (fwn *FirewallSSONetwork) init(ctx context.Context) error { var err error fwn.Ip, fwn.IpNet, err = net.ParseCIDR(fwn.Cidr) return err }
go
func (fwn *FirewallSSONetwork) init(ctx context.Context) error { var err error fwn.Ip, fwn.IpNet, err = net.ParseCIDR(fwn.Cidr) return err }
[ "func", "(", "fwn", "*", "FirewallSSONetwork", ")", "init", "(", "ctx", "context", ".", "Context", ")", "error", "{", "var", "err", "error", "\n", "fwn", ".", "Ip", ",", "fwn", ".", "IpNet", ",", "err", "=", "net", ".", "ParseCIDR", "(", "fwn", ".", "Cidr", ")", "\n", "return", "err", "\n", "}" ]
// Builds Ip and IpNet based on the Cidr in the struct
[ "Builds", "Ip", "and", "IpNet", "based", "on", "the", "Cidr", "in", "the", "struct" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L84-L88
train
inverse-inc/packetfence
go/firewallsso/base.go
GetCacheTimeout
func (fw *FirewallSSO) GetCacheTimeout(ctx context.Context) int { timeout, err := strconv.ParseInt(fw.CacheTimeout, 10, 32) if err != nil { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Can't parse timeout '%s' into an int (%s).", fw.CacheTimeout, err)) return 0 } else { return int(timeout) } }
go
func (fw *FirewallSSO) GetCacheTimeout(ctx context.Context) int { timeout, err := strconv.ParseInt(fw.CacheTimeout, 10, 32) if err != nil { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Can't parse timeout '%s' into an int (%s).", fw.CacheTimeout, err)) return 0 } else { return int(timeout) } }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "GetCacheTimeout", "(", "ctx", "context", ".", "Context", ")", "int", "{", "timeout", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fw", ".", "CacheTimeout", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fw", ".", "CacheTimeout", ",", "err", ")", ")", "\n", "return", "0", "\n", "}", "else", "{", "return", "int", "(", "timeout", ")", "\n", "}", "\n", "}" ]
// Get the cache_timeout configured in the firewall as an int // Will return 0 if its not there or not a valid int
[ "Get", "the", "cache_timeout", "configured", "in", "the", "firewall", "as", "an", "int", "Will", "return", "0", "if", "its", "not", "there", "or", "not", "a", "valid", "int" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L103-L111
train
inverse-inc/packetfence
go/firewallsso/base.go
Start
func (fw *FirewallSSO) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Debug("Sending SSO start") return true, nil }
go
func (fw *FirewallSSO) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Debug("Sending SSO start") return true, nil }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "\n", "}" ]
// Start method that will be called on every SSO called via ExecuteStart
[ "Start", "method", "that", "will", "be", "called", "on", "every", "SSO", "called", "via", "ExecuteStart" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L153-L156
train
inverse-inc/packetfence
go/firewallsso/base.go
Stop
func (fw *FirewallSSO) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Debug("Sending SSO stop") return true, nil }
go
func (fw *FirewallSSO) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Debug("Sending SSO stop") return true, nil }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "\n", "}" ]
// Stop method that will be called on every SSO called via ExecuteStop
[ "Stop", "method", "that", "will", "be", "called", "on", "every", "SSO", "called", "via", "ExecuteStop" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L159-L162
train
inverse-inc/packetfence
go/firewallsso/base.go
getSourceIp
func (fw *FirewallSSO) getSourceIp(ctx context.Context) net.IP { managementNetwork := pfconfigdriver.Config.Interfaces.ManagementNetwork if managementNetwork.Vip != "" { return net.ParseIP(managementNetwork.Vip) } else { return net.ParseIP(managementNetwork.Ip) } }
go
func (fw *FirewallSSO) getSourceIp(ctx context.Context) net.IP { managementNetwork := pfconfigdriver.Config.Interfaces.ManagementNetwork if managementNetwork.Vip != "" { return net.ParseIP(managementNetwork.Vip) } else { return net.ParseIP(managementNetwork.Ip) } }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "getSourceIp", "(", "ctx", "context", ".", "Context", ")", "net", ".", "IP", "{", "managementNetwork", ":=", "pfconfigdriver", ".", "Config", ".", "Interfaces", ".", "ManagementNetwork", "\n\n", "if", "managementNetwork", ".", "Vip", "!=", "\"", "\"", "{", "return", "net", ".", "ParseIP", "(", "managementNetwork", ".", "Vip", ")", "\n", "}", "else", "{", "return", "net", ".", "ParseIP", "(", "managementNetwork", ".", "Ip", ")", "\n", "}", "\n", "}" ]
// Get the source IP address for the SSO packets // Will return either the management VIP if there is one of the IP of the management network
[ "Get", "the", "source", "IP", "address", "for", "the", "SSO", "packets", "Will", "return", "either", "the", "management", "VIP", "if", "there", "is", "one", "of", "the", "IP", "of", "the", "management", "network" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L170-L178
train
inverse-inc/packetfence
go/firewallsso/base.go
getHttpClient
func (fw *FirewallSSO) getHttpClient(ctx context.Context) *http.Client { // We don't check the TLS certificate if applicable transport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } return &http.Client{Transport: transport} }
go
func (fw *FirewallSSO) getHttpClient(ctx context.Context) *http.Client { // We don't check the TLS certificate if applicable transport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } return &http.Client{Transport: transport} }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "getHttpClient", "(", "ctx", "context", ".", "Context", ")", "*", "http", ".", "Client", "{", "// We don't check the TLS certificate if applicable", "transport", ":=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ",", "}", "\n", "return", "&", "http", ".", "Client", "{", "Transport", ":", "transport", "}", "\n", "}" ]
// Get the default SSO HTTP client that doesn't check for valid certificates
[ "Get", "the", "default", "SSO", "HTTP", "client", "that", "doesn", "t", "check", "for", "valid", "certificates" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L181-L187
train
inverse-inc/packetfence
go/firewallsso/base.go
getRadiusClient
func (fw *FirewallSSO) getRadiusClient(ctx context.Context) *radius.Client { return &radius.Client{} }
go
func (fw *FirewallSSO) getRadiusClient(ctx context.Context) *radius.Client { return &radius.Client{} }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "getRadiusClient", "(", "ctx", "context", ".", "Context", ")", "*", "radius", ".", "Client", "{", "return", "&", "radius", ".", "Client", "{", "}", "\n", "}" ]
// Get the default RADIUS client
[ "Get", "the", "default", "RADIUS", "client" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L190-L192
train
inverse-inc/packetfence
go/firewallsso/base.go
logger
func (fw *FirewallSSO) logger(ctx context.Context) log15.Logger { ctx = log.AddToLogContext(ctx, "firewall-id", fw.PfconfigHashNS) return log.LoggerWContext(ctx) }
go
func (fw *FirewallSSO) logger(ctx context.Context) log15.Logger { ctx = log.AddToLogContext(ctx, "firewall-id", fw.PfconfigHashNS) return log.LoggerWContext(ctx) }
[ "func", "(", "fw", "*", "FirewallSSO", ")", "logger", "(", "ctx", "context", ".", "Context", ")", "log15", ".", "Logger", "{", "ctx", "=", "log", ".", "AddToLogContext", "(", "ctx", ",", "\"", "\"", ",", "fw", ".", "PfconfigHashNS", ")", "\n", "return", "log", ".", "LoggerWContext", "(", "ctx", ")", "\n", "}" ]
// Get the logger for a firewall
[ "Get", "the", "logger", "for", "a", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L237-L240
train
inverse-inc/packetfence
go/firewallsso/base.go
ExecuteStart
func ExecuteStart(ctx context.Context, fw FirewallSSOInt, info map[string]string, timeout int) (bool, error) { ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS) if !fw.CheckStatus(ctx, info) { return false, nil } log.LoggerWContext(ctx).Info("Processing SSO Start") if !fw.MatchesRole(ctx, info) { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for user device %s since it doesn't match the role", info["role"])) return false, nil } if !fw.MatchesNetwork(ctx, info) { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"])) return false, nil } // We change the username with the way it is expected given the format of this firewall info["username"] = fw.FormatUsername(ctx, info) parentResult, err := fw.GetFirewallSSO(ctx).Start(ctx, info, timeout) if err != nil { return false, err } childResult, err := fw.Start(ctx, info, timeout) return parentResult && childResult, err }
go
func ExecuteStart(ctx context.Context, fw FirewallSSOInt, info map[string]string, timeout int) (bool, error) { ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS) if !fw.CheckStatus(ctx, info) { return false, nil } log.LoggerWContext(ctx).Info("Processing SSO Start") if !fw.MatchesRole(ctx, info) { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for user device %s since it doesn't match the role", info["role"])) return false, nil } if !fw.MatchesNetwork(ctx, info) { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"])) return false, nil } // We change the username with the way it is expected given the format of this firewall info["username"] = fw.FormatUsername(ctx, info) parentResult, err := fw.GetFirewallSSO(ctx).Start(ctx, info, timeout) if err != nil { return false, err } childResult, err := fw.Start(ctx, info, timeout) return parentResult && childResult, err }
[ "func", "ExecuteStart", "(", "ctx", "context", ".", "Context", ",", "fw", "FirewallSSOInt", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "ctx", "=", "log", ".", "AddToLogContext", "(", "ctx", ",", "\"", "\"", ",", "fw", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "PfconfigHashNS", ")", "\n\n", "if", "!", "fw", ".", "CheckStatus", "(", "ctx", ",", "info", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "!", "fw", ".", "MatchesRole", "(", "ctx", ",", "info", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "info", "[", "\"", "\"", "]", ")", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "if", "!", "fw", ".", "MatchesNetwork", "(", "ctx", ",", "info", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "info", "[", "\"", "\"", "]", ")", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "// We change the username with the way it is expected given the format of this firewall", "info", "[", "\"", "\"", "]", "=", "fw", ".", "FormatUsername", "(", "ctx", ",", "info", ")", "\n\n", "parentResult", ",", "err", ":=", "fw", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "Start", "(", "ctx", ",", "info", ",", "timeout", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "childResult", ",", "err", ":=", "fw", ".", "Start", "(", "ctx", ",", "info", ",", "timeout", ")", "\n", "return", "parentResult", "&&", "childResult", ",", "err", "\n", "}" ]
// Execute an SSO Start request on the specified firewall // Makes sure to call FirewallSSO.Start and to validate the network and role if necessary
[ "Execute", "an", "SSO", "Start", "request", "on", "the", "specified", "firewall", "Makes", "sure", "to", "call", "FirewallSSO", ".", "Start", "and", "to", "validate", "the", "network", "and", "role", "if", "necessary" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L244-L272
train
inverse-inc/packetfence
go/firewallsso/base.go
ExecuteStop
func ExecuteStop(ctx context.Context, fw FirewallSSOInt, info map[string]string) (bool, error) { ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS) log.LoggerWContext(ctx).Info("Processing SSO Stop") if !fw.MatchesNetwork(ctx, info) { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"])) return false, nil } // We change the username with the way it is expected given the format of this firewall info["username"] = fw.FormatUsername(ctx, info) parentResult, err := fw.GetFirewallSSO(ctx).Stop(ctx, info) if err != nil { return false, err } childResult, err := fw.Stop(ctx, info) return parentResult && childResult, err }
go
func ExecuteStop(ctx context.Context, fw FirewallSSOInt, info map[string]string) (bool, error) { ctx = log.AddToLogContext(ctx, "firewall-id", fw.GetFirewallSSO(ctx).PfconfigHashNS) log.LoggerWContext(ctx).Info("Processing SSO Stop") if !fw.MatchesNetwork(ctx, info) { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Not sending SSO for IP %s since it doesn't match any configured network", info["ip"])) return false, nil } // We change the username with the way it is expected given the format of this firewall info["username"] = fw.FormatUsername(ctx, info) parentResult, err := fw.GetFirewallSSO(ctx).Stop(ctx, info) if err != nil { return false, err } childResult, err := fw.Stop(ctx, info) return parentResult && childResult, err }
[ "func", "ExecuteStop", "(", "ctx", "context", ".", "Context", ",", "fw", "FirewallSSOInt", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "ctx", "=", "log", ".", "AddToLogContext", "(", "ctx", ",", "\"", "\"", ",", "fw", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "PfconfigHashNS", ")", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "if", "!", "fw", ".", "MatchesNetwork", "(", "ctx", ",", "info", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "info", "[", "\"", "\"", "]", ")", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "// We change the username with the way it is expected given the format of this firewall", "info", "[", "\"", "\"", "]", "=", "fw", ".", "FormatUsername", "(", "ctx", ",", "info", ")", "\n\n", "parentResult", ",", "err", ":=", "fw", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "Stop", "(", "ctx", ",", "info", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "childResult", ",", "err", ":=", "fw", ".", "Stop", "(", "ctx", ",", "info", ")", "\n\n", "return", "parentResult", "&&", "childResult", ",", "err", "\n", "}" ]
// Execute an SSO Stop request on the specified firewall // Makes sure to call FirewallSSO.Start and to validate the network if necessary
[ "Execute", "an", "SSO", "Stop", "request", "on", "the", "specified", "firewall", "Makes", "sure", "to", "call", "FirewallSSO", ".", "Start", "and", "to", "validate", "the", "network", "if", "necessary" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/base.go#L276-L297
train
inverse-inc/packetfence
go/coredns/plugin/pkg/cache/cache.go
New
func New(size int) *Cache { ssize := size / shardSize if ssize < 512 { ssize = 512 } c := &Cache{} // Initialize all the shards for i := 0; i < shardSize; i++ { c.shards[i] = newShard(ssize) } return c }
go
func New(size int) *Cache { ssize := size / shardSize if ssize < 512 { ssize = 512 } c := &Cache{} // Initialize all the shards for i := 0; i < shardSize; i++ { c.shards[i] = newShard(ssize) } return c }
[ "func", "New", "(", "size", "int", ")", "*", "Cache", "{", "ssize", ":=", "size", "/", "shardSize", "\n", "if", "ssize", "<", "512", "{", "ssize", "=", "512", "\n", "}", "\n\n", "c", ":=", "&", "Cache", "{", "}", "\n\n", "// Initialize all the shards", "for", "i", ":=", "0", ";", "i", "<", "shardSize", ";", "i", "++", "{", "c", ".", "shards", "[", "i", "]", "=", "newShard", "(", "ssize", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// New returns a new cache.
[ "New", "returns", "a", "new", "cache", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L32-L45
train
inverse-inc/packetfence
go/coredns/plugin/pkg/cache/cache.go
Get
func (c *Cache) Get(key uint32) (interface{}, bool) { shard := key & (shardSize - 1) return c.shards[shard].Get(key) }
go
func (c *Cache) Get(key uint32) (interface{}, bool) { shard := key & (shardSize - 1) return c.shards[shard].Get(key) }
[ "func", "(", "c", "*", "Cache", ")", "Get", "(", "key", "uint32", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "shard", ":=", "key", "&", "(", "shardSize", "-", "1", ")", "\n", "return", "c", ".", "shards", "[", "shard", "]", ".", "Get", "(", "key", ")", "\n", "}" ]
// Get looks up element index under key.
[ "Get", "looks", "up", "element", "index", "under", "key", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L54-L57
train
inverse-inc/packetfence
go/coredns/plugin/pkg/cache/cache.go
Add
func (s *shard) Add(key uint32, el interface{}) { l := s.Len() if l+1 > s.size { s.Evict() } s.Lock() s.items[key] = el s.Unlock() }
go
func (s *shard) Add(key uint32, el interface{}) { l := s.Len() if l+1 > s.size { s.Evict() } s.Lock() s.items[key] = el s.Unlock() }
[ "func", "(", "s", "*", "shard", ")", "Add", "(", "key", "uint32", ",", "el", "interface", "{", "}", ")", "{", "l", ":=", "s", ".", "Len", "(", ")", "\n", "if", "l", "+", "1", ">", "s", ".", "size", "{", "s", ".", "Evict", "(", ")", "\n", "}", "\n\n", "s", ".", "Lock", "(", ")", "\n", "s", ".", "items", "[", "key", "]", "=", "el", "\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// Add adds element indexed by key into the cache. Any existing element is overwritten
[ "Add", "adds", "element", "indexed", "by", "key", "into", "the", "cache", ".", "Any", "existing", "element", "is", "overwritten" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L78-L87
train
inverse-inc/packetfence
go/coredns/plugin/pkg/cache/cache.go
Remove
func (s *shard) Remove(key uint32) { s.Lock() delete(s.items, key) s.Unlock() }
go
func (s *shard) Remove(key uint32) { s.Lock() delete(s.items, key) s.Unlock() }
[ "func", "(", "s", "*", "shard", ")", "Remove", "(", "key", "uint32", ")", "{", "s", ".", "Lock", "(", ")", "\n", "delete", "(", "s", ".", "items", ",", "key", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove removes the element indexed by key from the cache.
[ "Remove", "removes", "the", "element", "indexed", "by", "key", "from", "the", "cache", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L90-L94
train
inverse-inc/packetfence
go/coredns/plugin/pkg/cache/cache.go
Get
func (s *shard) Get(key uint32) (interface{}, bool) { s.RLock() el, found := s.items[key] s.RUnlock() return el, found }
go
func (s *shard) Get(key uint32) (interface{}, bool) { s.RLock() el, found := s.items[key] s.RUnlock() return el, found }
[ "func", "(", "s", "*", "shard", ")", "Get", "(", "key", "uint32", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "s", ".", "RLock", "(", ")", "\n", "el", ",", "found", ":=", "s", ".", "items", "[", "key", "]", "\n", "s", ".", "RUnlock", "(", ")", "\n", "return", "el", ",", "found", "\n", "}" ]
// Get looks up the element indexed under key.
[ "Get", "looks", "up", "the", "element", "indexed", "under", "key", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/cache/cache.go#L117-L122
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/server.go
ServePacket
func (s *Server) ServePacket(pc net.PacketConn) error { if QUIC { err := s.quicServer.Serve(pc.(*net.UDPConn)) return fmt.Errorf("serving QUIC connections: %v", err) } return nil }
go
func (s *Server) ServePacket(pc net.PacketConn) error { if QUIC { err := s.quicServer.Serve(pc.(*net.UDPConn)) return fmt.Errorf("serving QUIC connections: %v", err) } return nil }
[ "func", "(", "s", "*", "Server", ")", "ServePacket", "(", "pc", "net", ".", "PacketConn", ")", "error", "{", "if", "QUIC", "{", "err", ":=", "s", ".", "quicServer", ".", "Serve", "(", "pc", ".", "(", "*", "net", ".", "UDPConn", ")", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ServePacket serves QUIC requests on pc until it is closed.
[ "ServePacket", "serves", "QUIC", "requests", "on", "pc", "until", "it", "is", "closed", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/server.go#L193-L199
train
inverse-inc/packetfence
go/firewallsso/junipersrx.go
Start
func (fw *JuniperSRX) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.startHttp(ctx, info, timeout) }
go
func (fw *JuniperSRX) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.startHttp(ctx, info, timeout) }
[ "func", "(", "fw", "*", "JuniperSRX", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "fw", ".", "startHttp", "(", "ctx", ",", "info", ",", "timeout", ")", "\n\n", "}" ]
// Send an SSO start to the JuniperSRX using HTTP // This will return any value from startSyslog or startHttp depending on the type of the transport
[ "Send", "an", "SSO", "start", "to", "the", "JuniperSRX", "using", "HTTP", "This", "will", "return", "any", "value", "from", "startSyslog", "or", "startHttp", "depending", "on", "the", "type", "of", "the", "transport" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/junipersrx.go#L23-L27
train
inverse-inc/packetfence
go/firewallsso/junipersrx.go
startHttp
func (fw *JuniperSRX) startHttp(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := http.NewRequest("POST", "https://"+fw.PfconfigHashNS+":"+fw.Port+"/api/userfw/v1/post-entry", bytes.NewBuffer([]byte(fw.startHttpPayload(ctx, info)))) req.SetBasicAuth(fw.Username, fw.Password) client := fw.getHttpClient(ctx) resp, err := client.Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting JuniperSRX: %s", err)) //Not returning now so that body closes below } if resp != nil && resp.Body != nil { resp.Body.Close() } return err == nil, err }
go
func (fw *JuniperSRX) startHttp(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := http.NewRequest("POST", "https://"+fw.PfconfigHashNS+":"+fw.Port+"/api/userfw/v1/post-entry", bytes.NewBuffer([]byte(fw.startHttpPayload(ctx, info)))) req.SetBasicAuth(fw.Username, fw.Password) client := fw.getHttpClient(ctx) resp, err := client.Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting JuniperSRX: %s", err)) //Not returning now so that body closes below } if resp != nil && resp.Body != nil { resp.Body.Close() } return err == nil, err }
[ "func", "(", "fw", "*", "JuniperSRX", ")", "startHttp", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "\"", "\"", "+", "fw", ".", "PfconfigHashNS", "+", "\"", "\"", "+", "fw", ".", "Port", "+", "\"", "\"", ",", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "fw", ".", "startHttpPayload", "(", "ctx", ",", "info", ")", ")", ")", ")", "\n", "req", ".", "SetBasicAuth", "(", "fw", ".", "Username", ",", "fw", ".", "Password", ")", "\n", "client", ":=", "fw", ".", "getHttpClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "//Not returning now so that body closes below", "}", "\n\n", "if", "resp", "!=", "nil", "&&", "resp", ".", "Body", "!=", "nil", "{", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "err", "==", "nil", ",", "err", "\n", "}" ]
// Send a start to the JuniperSRX using the HTTP transport // Will return an error if it fails to get a valid reply from it
[ "Send", "a", "start", "to", "the", "JuniperSRX", "using", "the", "HTTP", "transport", "Will", "return", "an", "error", "if", "it", "fails", "to", "get", "a", "valid", "reply", "from", "it" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/junipersrx.go#L31-L48
train
inverse-inc/packetfence
go/firewallsso/junipersrx.go
Stop
func (fw *JuniperSRX) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.stopHttp(ctx, info) }
go
func (fw *JuniperSRX) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.stopHttp(ctx, info) }
[ "func", "(", "fw", "*", "JuniperSRX", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "fw", ".", "stopHttp", "(", "ctx", ",", "info", ")", "\n\n", "}" ]
// Send an SSO stop to the firewall by using HTTP transport.
[ "Send", "an", "SSO", "stop", "to", "the", "firewall", "by", "using", "HTTP", "transport", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/junipersrx.go#L103-L107
train
inverse-inc/packetfence
go/firewallsso/barracudang.go
getSshSession
func (fw *BarracudaNG) getSshSession(ctx context.Context) (*ssh.Session, error) { sshConfig := &ssh.ClientConfig{ User: fw.Username, Auth: []ssh.AuthMethod{ ssh.Password(fw.Password), }, } connection, err := ssh.Dial("tcp", fw.PfconfigHashNS+":"+fw.Port, sshConfig) if err != nil { return nil, err } session, err := connection.NewSession() return session, err }
go
func (fw *BarracudaNG) getSshSession(ctx context.Context) (*ssh.Session, error) { sshConfig := &ssh.ClientConfig{ User: fw.Username, Auth: []ssh.AuthMethod{ ssh.Password(fw.Password), }, } connection, err := ssh.Dial("tcp", fw.PfconfigHashNS+":"+fw.Port, sshConfig) if err != nil { return nil, err } session, err := connection.NewSession() return session, err }
[ "func", "(", "fw", "*", "BarracudaNG", ")", "getSshSession", "(", "ctx", "context", ".", "Context", ")", "(", "*", "ssh", ".", "Session", ",", "error", ")", "{", "sshConfig", ":=", "&", "ssh", ".", "ClientConfig", "{", "User", ":", "fw", ".", "Username", ",", "Auth", ":", "[", "]", "ssh", ".", "AuthMethod", "{", "ssh", ".", "Password", "(", "fw", ".", "Password", ")", ",", "}", ",", "}", "\n", "connection", ",", "err", ":=", "ssh", ".", "Dial", "(", "\"", "\"", ",", "fw", ".", "PfconfigHashNS", "+", "\"", "\"", "+", "fw", ".", "Port", ",", "sshConfig", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "session", ",", "err", ":=", "connection", ".", "NewSession", "(", ")", "\n\n", "return", "session", ",", "err", "\n", "}" ]
// Get an SSH session to the firewall
[ "Get", "an", "SSH", "session", "to", "the", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/barracudang.go#L18-L34
train
inverse-inc/packetfence
go/firewallsso/barracudang.go
Start
func (fw *BarracudaNG) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { session, err := fw.getSshSession(ctx) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot connect to BarracudaNG: %s", err)) return false, err } cmd := "phibstest 127.0.0.1 l peer=" + info["ip"] + " origin=PacketFence service=PacketFence user=" + info["username"] session.Run(cmd) return true, nil }
go
func (fw *BarracudaNG) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { session, err := fw.getSshSession(ctx) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot connect to BarracudaNG: %s", err)) return false, err } cmd := "phibstest 127.0.0.1 l peer=" + info["ip"] + " origin=PacketFence service=PacketFence user=" + info["username"] session.Run(cmd) return true, nil }
[ "func", "(", "fw", "*", "BarracudaNG", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "session", ",", "err", ":=", "fw", ".", "getSshSession", "(", "ctx", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", ",", "err", "\n", "}", "\n\n", "cmd", ":=", "\"", "\"", "+", "info", "[", "\"", "\"", "]", "+", "\"", "\"", "+", "info", "[", "\"", "\"", "]", "\n", "session", ".", "Run", "(", "cmd", ")", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// Send an SSO start to the BarracudaNG Firewall // Will return an error if it can't connect
[ "Send", "an", "SSO", "start", "to", "the", "BarracudaNG", "Firewall", "Will", "return", "an", "error", "if", "it", "can", "t", "connect" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/barracudang.go#L38-L50
train
inverse-inc/packetfence
go/stats/main.go
detectVIP
func detectVIP(management pfconfigdriver.ManagementNetwork) { if pfconfigdriver.GetClusterSummary(ctx).ClusterEnabled == 1 { var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" keyConfCluster.PfconfigHashNS = "interface " + management.Int pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode if keyConfCluster.Ip == "" { VIP[management.Int] = true return } eth, _ := net.InterfaceByName(management.Int) adresses, _ := eth.Addrs() for _, adresse := range adresses { IP, _, _ := net.ParseCIDR(adresse.String()) VIPIp[management.Int] = net.ParseIP(keyConfCluster.Ip) if IP.Equal(VIPIp[management.Int]) { VIP[management.Int] = true return } } VIP[management.Int] = false return } else { VIP[management.Int] = true } }
go
func detectVIP(management pfconfigdriver.ManagementNetwork) { if pfconfigdriver.GetClusterSummary(ctx).ClusterEnabled == 1 { var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" keyConfCluster.PfconfigHashNS = "interface " + management.Int pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode if keyConfCluster.Ip == "" { VIP[management.Int] = true return } eth, _ := net.InterfaceByName(management.Int) adresses, _ := eth.Addrs() for _, adresse := range adresses { IP, _, _ := net.ParseCIDR(adresse.String()) VIPIp[management.Int] = net.ParseIP(keyConfCluster.Ip) if IP.Equal(VIPIp[management.Int]) { VIP[management.Int] = true return } } VIP[management.Int] = false return } else { VIP[management.Int] = true } }
[ "func", "detectVIP", "(", "management", "pfconfigdriver", ".", "ManagementNetwork", ")", "{", "if", "pfconfigdriver", ".", "GetClusterSummary", "(", "ctx", ")", ".", "ClusterEnabled", "==", "1", "{", "var", "keyConfCluster", "pfconfigdriver", ".", "NetInterface", "\n", "keyConfCluster", ".", "PfconfigNS", "=", "\"", "\"", "+", "pfconfigdriver", ".", "FindClusterName", "(", "ctx", ")", "+", "\"", "\"", "\n\n", "keyConfCluster", ".", "PfconfigHashNS", "=", "\"", "\"", "+", "management", ".", "Int", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "keyConfCluster", ")", "\n", "// Nothing in keyConfCluster.Ip so we are not in cluster mode", "if", "keyConfCluster", ".", "Ip", "==", "\"", "\"", "{", "VIP", "[", "management", ".", "Int", "]", "=", "true", "\n", "return", "\n", "}", "\n\n", "eth", ",", "_", ":=", "net", ".", "InterfaceByName", "(", "management", ".", "Int", ")", "\n", "adresses", ",", "_", ":=", "eth", ".", "Addrs", "(", ")", "\n\n", "for", "_", ",", "adresse", ":=", "range", "adresses", "{", "IP", ",", "_", ",", "_", ":=", "net", ".", "ParseCIDR", "(", "adresse", ".", "String", "(", ")", ")", "\n", "VIPIp", "[", "management", ".", "Int", "]", "=", "net", ".", "ParseIP", "(", "keyConfCluster", ".", "Ip", ")", "\n", "if", "IP", ".", "Equal", "(", "VIPIp", "[", "management", ".", "Int", "]", ")", "{", "VIP", "[", "management", ".", "Int", "]", "=", "true", "\n", "return", "\n", "}", "\n", "}", "\n", "VIP", "[", "management", ".", "Int", "]", "=", "false", "\n", "return", "\n", "}", "else", "{", "VIP", "[", "management", ".", "Int", "]", "=", "true", "\n", "}", "\n", "}" ]
// Detect the vip on management
[ "Detect", "the", "vip", "on", "management" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/stats/main.go#L1791-L1820
train
inverse-inc/packetfence
go/coredns/plugin/proxy/upstream.go
NewStaticUpstreams
func NewStaticUpstreams(c *caddyfile.Dispenser) ([]Upstream, error) { var upstreams []Upstream for c.Next() { upstream := &staticUpstream{ from: ".", HealthCheck: healthcheck.HealthCheck{ FailTimeout: 5 * time.Second, MaxFails: 3, }, ex: newDNSEx(), } if !c.Args(&upstream.netsource) { return upstreams, c.ArgErr() } _, _, err := net.ParseCIDR(upstream.netsource) if err != nil { upstream.from = upstream.netsource upstream.netsource = "" } upstream.from = plugin.Host(upstream.from).Normalize() to := c.RemainingArgs() if len(to) == 0 { return upstreams, c.ArgErr() } // process the host list, substituting in any nameservers in files toHosts, err := dnsutil.ParseHostPortOrFile(to...) if err != nil { return upstreams, err } for c.NextBlock() { if err := parseBlock(c, upstream); err != nil { return upstreams, err } } upstream.Hosts = make([]*healthcheck.UpstreamHost, len(toHosts)) for i, host := range toHosts { uh := &healthcheck.UpstreamHost{ Name: host, FailTimeout: upstream.FailTimeout, CheckDown: checkDownFunc(upstream), } upstream.Hosts[i] = uh } upstream.Start() upstreams = append(upstreams, upstream) } return upstreams, nil }
go
func NewStaticUpstreams(c *caddyfile.Dispenser) ([]Upstream, error) { var upstreams []Upstream for c.Next() { upstream := &staticUpstream{ from: ".", HealthCheck: healthcheck.HealthCheck{ FailTimeout: 5 * time.Second, MaxFails: 3, }, ex: newDNSEx(), } if !c.Args(&upstream.netsource) { return upstreams, c.ArgErr() } _, _, err := net.ParseCIDR(upstream.netsource) if err != nil { upstream.from = upstream.netsource upstream.netsource = "" } upstream.from = plugin.Host(upstream.from).Normalize() to := c.RemainingArgs() if len(to) == 0 { return upstreams, c.ArgErr() } // process the host list, substituting in any nameservers in files toHosts, err := dnsutil.ParseHostPortOrFile(to...) if err != nil { return upstreams, err } for c.NextBlock() { if err := parseBlock(c, upstream); err != nil { return upstreams, err } } upstream.Hosts = make([]*healthcheck.UpstreamHost, len(toHosts)) for i, host := range toHosts { uh := &healthcheck.UpstreamHost{ Name: host, FailTimeout: upstream.FailTimeout, CheckDown: checkDownFunc(upstream), } upstream.Hosts[i] = uh } upstream.Start() upstreams = append(upstreams, upstream) } return upstreams, nil }
[ "func", "NewStaticUpstreams", "(", "c", "*", "caddyfile", ".", "Dispenser", ")", "(", "[", "]", "Upstream", ",", "error", ")", "{", "var", "upstreams", "[", "]", "Upstream", "\n", "for", "c", ".", "Next", "(", ")", "{", "upstream", ":=", "&", "staticUpstream", "{", "from", ":", "\"", "\"", ",", "HealthCheck", ":", "healthcheck", ".", "HealthCheck", "{", "FailTimeout", ":", "5", "*", "time", ".", "Second", ",", "MaxFails", ":", "3", ",", "}", ",", "ex", ":", "newDNSEx", "(", ")", ",", "}", "\n\n", "if", "!", "c", ".", "Args", "(", "&", "upstream", ".", "netsource", ")", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n\n", "_", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "upstream", ".", "netsource", ")", "\n\n", "if", "err", "!=", "nil", "{", "upstream", ".", "from", "=", "upstream", ".", "netsource", "\n", "upstream", ".", "netsource", "=", "\"", "\"", "\n", "}", "\n\n", "upstream", ".", "from", "=", "plugin", ".", "Host", "(", "upstream", ".", "from", ")", ".", "Normalize", "(", ")", "\n\n", "to", ":=", "c", ".", "RemainingArgs", "(", ")", "\n", "if", "len", "(", "to", ")", "==", "0", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n\n", "// process the host list, substituting in any nameservers in files", "toHosts", ",", "err", ":=", "dnsutil", ".", "ParseHostPortOrFile", "(", "to", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n\n", "for", "c", ".", "NextBlock", "(", ")", "{", "if", "err", ":=", "parseBlock", "(", "c", ",", "upstream", ")", ";", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "}", "\n\n", "upstream", ".", "Hosts", "=", "make", "(", "[", "]", "*", "healthcheck", ".", "UpstreamHost", ",", "len", "(", "toHosts", ")", ")", "\n\n", "for", "i", ",", "host", ":=", "range", "toHosts", "{", "uh", ":=", "&", "healthcheck", ".", "UpstreamHost", "{", "Name", ":", "host", ",", "FailTimeout", ":", "upstream", ".", "FailTimeout", ",", "CheckDown", ":", "checkDownFunc", "(", "upstream", ")", ",", "}", "\n", "upstream", ".", "Hosts", "[", "i", "]", "=", "uh", "\n", "}", "\n", "upstream", ".", "Start", "(", ")", "\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 plugin.
[ "NewStaticUpstreams", "parses", "the", "configuration", "input", "and", "sets", "up", "static", "upstreams", "for", "the", "proxy", "plugin", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/upstream.go#L29-L86
train
inverse-inc/packetfence
go/coredns/plugin/proxy/fuzz.go
Fuzz
func Fuzz(data []byte) int { c := caddy.NewTestController("dns", "proxy . 8.8.8.8:53") up, err := NewStaticUpstreams(&c.Dispenser) if err != nil { return 0 } p := &Proxy{Upstreams: &up} return fuzz.Do(p, data) }
go
func Fuzz(data []byte) int { c := caddy.NewTestController("dns", "proxy . 8.8.8.8:53") up, err := NewStaticUpstreams(&c.Dispenser) if err != nil { return 0 } p := &Proxy{Upstreams: &up} return fuzz.Do(p, data) }
[ "func", "Fuzz", "(", "data", "[", "]", "byte", ")", "int", "{", "c", ":=", "caddy", ".", "NewTestController", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "up", ",", "err", ":=", "NewStaticUpstreams", "(", "&", "c", ".", "Dispenser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n", "p", ":=", "&", "Proxy", "{", "Upstreams", ":", "&", "up", "}", "\n\n", "return", "fuzz", ".", "Do", "(", "p", ",", "data", ")", "\n", "}" ]
// Fuzz fuzzes proxy.
[ "Fuzz", "fuzzes", "proxy", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/fuzz.go#L10-L19
train
inverse-inc/packetfence
go/unifiedapiclient/client.go
ensureRequestComplete
func (c *Client) ensureRequestComplete(ctx context.Context, resp *http.Response) { if resp == nil { return } defer resp.Body.Close() io.Copy(ioutil.Discard, resp.Body) }
go
func (c *Client) ensureRequestComplete(ctx context.Context, resp *http.Response) { if resp == nil { return } defer resp.Body.Close() io.Copy(ioutil.Discard, resp.Body) }
[ "func", "(", "c", "*", "Client", ")", "ensureRequestComplete", "(", "ctx", "context", ".", "Context", ",", "resp", "*", "http", ".", "Response", ")", "{", "if", "resp", "==", "nil", "{", "return", "\n", "}", "\n\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "resp", ".", "Body", ")", "\n", "}" ]
// Ensures that the full body is read and closes the reader so that the connection can be reused
[ "Ensures", "that", "the", "full", "body", "is", "read", "and", "closes", "the", "reader", "so", "that", "the", "connection", "can", "be", "reused" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/unifiedapiclient/client.go#L128-L135
train
inverse-inc/packetfence
go/coredns/plugin/proxy/google_rr.go
toMsg
func toMsg(g *googleMsg) (*dns.Msg, error) { m := new(dns.Msg) m.Response = true m.Rcode = g.Status m.Truncated = g.TC m.RecursionDesired = g.RD m.RecursionAvailable = g.RA m.AuthenticatedData = g.AD m.CheckingDisabled = g.CD m.Question = make([]dns.Question, 1) m.Answer = make([]dns.RR, len(g.Answer)) m.Ns = make([]dns.RR, len(g.Authority)) m.Extra = make([]dns.RR, len(g.Additional)) m.Question[0] = dns.Question{Name: g.Question[0].Name, Qtype: g.Question[0].Type, Qclass: dns.ClassINET} var err error for i := 0; i < len(m.Answer); i++ { m.Answer[i], err = toRR(g.Answer[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Ns); i++ { m.Ns[i], err = toRR(g.Authority[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Extra); i++ { m.Extra[i], err = toRR(g.Additional[i]) if err != nil { return nil, err } } return m, nil }
go
func toMsg(g *googleMsg) (*dns.Msg, error) { m := new(dns.Msg) m.Response = true m.Rcode = g.Status m.Truncated = g.TC m.RecursionDesired = g.RD m.RecursionAvailable = g.RA m.AuthenticatedData = g.AD m.CheckingDisabled = g.CD m.Question = make([]dns.Question, 1) m.Answer = make([]dns.RR, len(g.Answer)) m.Ns = make([]dns.RR, len(g.Authority)) m.Extra = make([]dns.RR, len(g.Additional)) m.Question[0] = dns.Question{Name: g.Question[0].Name, Qtype: g.Question[0].Type, Qclass: dns.ClassINET} var err error for i := 0; i < len(m.Answer); i++ { m.Answer[i], err = toRR(g.Answer[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Ns); i++ { m.Ns[i], err = toRR(g.Authority[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Extra); i++ { m.Extra[i], err = toRR(g.Additional[i]) if err != nil { return nil, err } } return m, nil }
[ "func", "toMsg", "(", "g", "*", "googleMsg", ")", "(", "*", "dns", ".", "Msg", ",", "error", ")", "{", "m", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "m", ".", "Response", "=", "true", "\n", "m", ".", "Rcode", "=", "g", ".", "Status", "\n", "m", ".", "Truncated", "=", "g", ".", "TC", "\n", "m", ".", "RecursionDesired", "=", "g", ".", "RD", "\n", "m", ".", "RecursionAvailable", "=", "g", ".", "RA", "\n", "m", ".", "AuthenticatedData", "=", "g", ".", "AD", "\n", "m", ".", "CheckingDisabled", "=", "g", ".", "CD", "\n\n", "m", ".", "Question", "=", "make", "(", "[", "]", "dns", ".", "Question", ",", "1", ")", "\n", "m", ".", "Answer", "=", "make", "(", "[", "]", "dns", ".", "RR", ",", "len", "(", "g", ".", "Answer", ")", ")", "\n", "m", ".", "Ns", "=", "make", "(", "[", "]", "dns", ".", "RR", ",", "len", "(", "g", ".", "Authority", ")", ")", "\n", "m", ".", "Extra", "=", "make", "(", "[", "]", "dns", ".", "RR", ",", "len", "(", "g", ".", "Additional", ")", ")", "\n\n", "m", ".", "Question", "[", "0", "]", "=", "dns", ".", "Question", "{", "Name", ":", "g", ".", "Question", "[", "0", "]", ".", "Name", ",", "Qtype", ":", "g", ".", "Question", "[", "0", "]", ".", "Type", ",", "Qclass", ":", "dns", ".", "ClassINET", "}", "\n\n", "var", "err", "error", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "m", ".", "Answer", ")", ";", "i", "++", "{", "m", ".", "Answer", "[", "i", "]", ",", "err", "=", "toRR", "(", "g", ".", "Answer", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "m", ".", "Ns", ")", ";", "i", "++", "{", "m", ".", "Ns", "[", "i", "]", ",", "err", "=", "toRR", "(", "g", ".", "Authority", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "m", ".", "Extra", ")", ";", "i", "++", "{", "m", ".", "Extra", "[", "i", "]", ",", "err", "=", "toRR", "(", "g", ".", "Additional", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// toMsg converts a googleMsg into the dns message.
[ "toMsg", "converts", "a", "googleMsg", "into", "the", "dns", "message", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/google_rr.go#L10-L48
train
inverse-inc/packetfence
go/coredns/plugin/proxy/google_rr.go
toRR
func toRR(g googleRR) (dns.RR, error) { typ, ok := dns.TypeToString[g.Type] if !ok { return nil, fmt.Errorf("failed to convert type %q", g.Type) } str := fmt.Sprintf("%s %d %s %s", g.Name, g.TTL, typ, g.Data) rr, err := dns.NewRR(str) if err != nil { return nil, fmt.Errorf("failed to parse %q: %s", str, err) } return rr, nil }
go
func toRR(g googleRR) (dns.RR, error) { typ, ok := dns.TypeToString[g.Type] if !ok { return nil, fmt.Errorf("failed to convert type %q", g.Type) } str := fmt.Sprintf("%s %d %s %s", g.Name, g.TTL, typ, g.Data) rr, err := dns.NewRR(str) if err != nil { return nil, fmt.Errorf("failed to parse %q: %s", str, err) } return rr, nil }
[ "func", "toRR", "(", "g", "googleRR", ")", "(", "dns", ".", "RR", ",", "error", ")", "{", "typ", ",", "ok", ":=", "dns", ".", "TypeToString", "[", "g", ".", "Type", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "g", ".", "Type", ")", "\n", "}", "\n\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "g", ".", "Name", ",", "g", ".", "TTL", ",", "typ", ",", "g", ".", "Data", ")", "\n", "rr", ",", "err", ":=", "dns", ".", "NewRR", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "rr", ",", "nil", "\n", "}" ]
// toRR transforms a "google" RR to a dns.RR.
[ "toRR", "transforms", "a", "google", "RR", "to", "a", "dns", ".", "RR", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/google_rr.go#L51-L63
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/taprw/writer.go
WriteMsg
func (w *ResponseWriter) WriteMsg(resp *dns.Msg) (writeErr error) { writeErr = w.ResponseWriter.WriteMsg(resp) writeEpoch := uint64(time.Now().Unix()) b := w.TapBuilder() b.TimeSec = w.queryEpoch if w.Send == nil || w.Send.Cq { if err := func() (err error) { err = b.AddrMsg(w.ResponseWriter.RemoteAddr(), w.Query) if err != nil { return } return w.TapMessage(b.ToClientQuery()) }(); err != nil { w.err = fmt.Errorf("client query: %s", err) // don't forget to call DnstapError later } } if w.Send == nil || w.Send.Cr { if writeErr == nil { if err := func() (err error) { b.TimeSec = writeEpoch if err = b.Msg(resp); err != nil { return } return w.TapMessage(b.ToClientResponse()) }(); err != nil { w.err = fmt.Errorf("client response: %s", err) } } } return }
go
func (w *ResponseWriter) WriteMsg(resp *dns.Msg) (writeErr error) { writeErr = w.ResponseWriter.WriteMsg(resp) writeEpoch := uint64(time.Now().Unix()) b := w.TapBuilder() b.TimeSec = w.queryEpoch if w.Send == nil || w.Send.Cq { if err := func() (err error) { err = b.AddrMsg(w.ResponseWriter.RemoteAddr(), w.Query) if err != nil { return } return w.TapMessage(b.ToClientQuery()) }(); err != nil { w.err = fmt.Errorf("client query: %s", err) // don't forget to call DnstapError later } } if w.Send == nil || w.Send.Cr { if writeErr == nil { if err := func() (err error) { b.TimeSec = writeEpoch if err = b.Msg(resp); err != nil { return } return w.TapMessage(b.ToClientResponse()) }(); err != nil { w.err = fmt.Errorf("client response: %s", err) } } } return }
[ "func", "(", "w", "*", "ResponseWriter", ")", "WriteMsg", "(", "resp", "*", "dns", ".", "Msg", ")", "(", "writeErr", "error", ")", "{", "writeErr", "=", "w", ".", "ResponseWriter", ".", "WriteMsg", "(", "resp", ")", "\n", "writeEpoch", ":=", "uint64", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n\n", "b", ":=", "w", ".", "TapBuilder", "(", ")", "\n", "b", ".", "TimeSec", "=", "w", ".", "queryEpoch", "\n\n", "if", "w", ".", "Send", "==", "nil", "||", "w", ".", "Send", ".", "Cq", "{", "if", "err", ":=", "func", "(", ")", "(", "err", "error", ")", "{", "err", "=", "b", ".", "AddrMsg", "(", "w", ".", "ResponseWriter", ".", "RemoteAddr", "(", ")", ",", "w", ".", "Query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "w", ".", "TapMessage", "(", "b", ".", "ToClientQuery", "(", ")", ")", "\n", "}", "(", ")", ";", "err", "!=", "nil", "{", "w", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "// don't forget to call DnstapError later", "}", "\n", "}", "\n\n", "if", "w", ".", "Send", "==", "nil", "||", "w", ".", "Send", ".", "Cr", "{", "if", "writeErr", "==", "nil", "{", "if", "err", ":=", "func", "(", ")", "(", "err", "error", ")", "{", "b", ".", "TimeSec", "=", "writeEpoch", "\n", "if", "err", "=", "b", ".", "Msg", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "w", ".", "TapMessage", "(", "b", ".", "ToClientResponse", "(", ")", ")", "\n", "}", "(", ")", ";", "err", "!=", "nil", "{", "w", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// WriteMsg writes back the response to the client and THEN works on logging the request // and response to dnstap. // Dnstap errors are to be checked by DnstapError.
[ "WriteMsg", "writes", "back", "the", "response", "to", "the", "client", "and", "THEN", "works", "on", "logging", "the", "request", "and", "response", "to", "dnstap", ".", "Dnstap", "errors", "are", "to", "be", "checked", "by", "DnstapError", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/taprw/writer.go#L53-L87
train
inverse-inc/packetfence
go/firewallsso/iboss.go
Start
func (fw *Iboss) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := fw.getRequest(ctx, "login", info) if err != nil { return false, err } resp, err := fw.getHttpClient(ctx).Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting Iboss: %s", err)) //Not returning now so that body can be closed if necessary } if resp != nil && resp.Body != nil { resp.Body.Close() } return err == nil, err }
go
func (fw *Iboss) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := fw.getRequest(ctx, "login", info) if err != nil { return false, err } resp, err := fw.getHttpClient(ctx).Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting Iboss: %s", err)) //Not returning now so that body can be closed if necessary } if resp != nil && resp.Body != nil { resp.Body.Close() } return err == nil, err }
[ "func", "(", "fw", "*", "Iboss", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "req", ",", "err", ":=", "fw", ".", "getRequest", "(", "ctx", ",", "\"", "\"", ",", "info", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "fw", ".", "getHttpClient", "(", "ctx", ")", ".", "Do", "(", "req", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "//Not returning now so that body can be closed if necessary", "}", "\n\n", "if", "resp", "!=", "nil", "&&", "resp", ".", "Body", "!=", "nil", "{", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "err", "==", "nil", ",", "err", "\n", "}" ]
// Send an SSO start to the Iboss firewall // Returns an error unless there is a valid reply from the firewall or if the HTTP request fails to be built
[ "Send", "an", "SSO", "start", "to", "the", "Iboss", "firewall", "Returns", "an", "error", "unless", "there", "is", "a", "valid", "reply", "from", "the", "firewall", "or", "if", "the", "HTTP", "request", "fails", "to", "be", "built" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/iboss.go#L20-L39
train
inverse-inc/packetfence
go/firewallsso/iboss.go
getRequest
func (fw *Iboss) getRequest(ctx context.Context, action string, info map[string]string) (*http.Request, error) { req, err := http.NewRequest( "GET", fmt.Sprintf( "http://%s:%s/nacAgent?action=%s&user=%s&dc=%s&key=%s&ip=%s&cn=%s&g=%s", fw.PfconfigHashNS, fw.Port, action, info["username"], fw.NacName, fw.Password, info["ip"], info["username"], info["role"], ), bytes.NewBufferString("query=libwww-perl&mode=dist"), ) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") if err != nil { return nil, err } return req, nil }
go
func (fw *Iboss) getRequest(ctx context.Context, action string, info map[string]string) (*http.Request, error) { req, err := http.NewRequest( "GET", fmt.Sprintf( "http://%s:%s/nacAgent?action=%s&user=%s&dc=%s&key=%s&ip=%s&cn=%s&g=%s", fw.PfconfigHashNS, fw.Port, action, info["username"], fw.NacName, fw.Password, info["ip"], info["username"], info["role"], ), bytes.NewBufferString("query=libwww-perl&mode=dist"), ) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") if err != nil { return nil, err } return req, nil }
[ "func", "(", "fw", "*", "Iboss", ")", "getRequest", "(", "ctx", "context", ".", "Context", ",", "action", "string", ",", "info", "map", "[", "string", "]", "string", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fw", ".", "PfconfigHashNS", ",", "fw", ".", "Port", ",", "action", ",", "info", "[", "\"", "\"", "]", ",", "fw", ".", "NacName", ",", "fw", ".", "Password", ",", "info", "[", "\"", "\"", "]", ",", "info", "[", "\"", "\"", "]", ",", "info", "[", "\"", "\"", "]", ",", ")", ",", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", ",", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "req", ",", "nil", "\n", "}" ]
// Build an HTTP request to send to the Iboss firewall // This builds the request for start+stop and is controlled by the action parameter // This will return an error if the request cannot be built
[ "Build", "an", "HTTP", "request", "to", "send", "to", "the", "Iboss", "firewall", "This", "builds", "the", "request", "for", "start", "+", "stop", "and", "is", "controlled", "by", "the", "action", "parameter", "This", "will", "return", "an", "error", "if", "the", "request", "cannot", "be", "built" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/iboss.go#L67-L90
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/maintain.go
RenewManagedCertificates
func RenewManagedCertificates(allowPrompts bool) (err error) { var renewQueue, deleteQueue []Certificate visitedNames := make(map[string]struct{}) certCacheMu.RLock() for name, cert := range certCache { if !cert.Config.Managed || cert.Config.SelfSigned { continue } // the list of names on this cert should never be empty... if cert.Names == nil || len(cert.Names) == 0 { log.Printf("[WARNING] Certificate keyed by '%s' has no names: %v - removing from cache", name, cert.Names) deleteQueue = append(deleteQueue, cert) continue } // skip names whose certificate we've already renewed if _, ok := visitedNames[name]; ok { continue } for _, name := range cert.Names { visitedNames[name] = struct{}{} } // if its time is up or ending soon, we need to try to renew it timeLeft := cert.NotAfter.Sub(time.Now().UTC()) if timeLeft < RenewDurationBefore { log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft) if cert.Config == nil { log.Printf("[ERROR] %s: No associated TLS config; unable to renew", name) continue } // queue for renewal when we aren't in a read lock anymore // (the TLS-SNI challenge will need a write lock in order to // present the certificate, so we renew outside of read lock) renewQueue = append(renewQueue, cert) } } certCacheMu.RUnlock() // Perform renewals that are queued for _, cert := range renewQueue { // Get the name which we should use to renew this certificate; // we only support managing certificates with one name per cert, // so this should be easy. We can't rely on cert.Config.Hostname // because it may be a wildcard value from the Caddyfile (e.g. // *.something.com) which, as of Jan. 2017, is not supported by ACME. var renewName string for _, name := range cert.Names { if name != "" { renewName = name break } } // perform renewal err := cert.Config.RenewCert(renewName, allowPrompts) if err != nil { if allowPrompts { // Certificate renewal failed and the operator is present; we should stop // immediately and return the error. See a discussion in issue 642 // about this. For a while, we only stopped if the certificate was // expired, but in reality, there is no difference between reporting // it now versus later, except that there's somebody present to deal // with it now, so require it. return err } log.Printf("[ERROR] %v", err) if cert.Config.OnDemand { deleteQueue = append(deleteQueue, cert) } } else { // successful renewal, so update in-memory cache by loading // renewed certificate so it will be used with handshakes // TODO: Not until CA has valid OCSP response ready for the new cert... sigh. if cert.Names[len(cert.Names)-1] == "" { // Special case: This is the default certificate. We must // flush it out of the cache so that we no longer point to // the old, un-renewed certificate. Otherwise it will be // renewed on every scan, which is too often. The next cert // to be cached (probably this one) will become the default. certCacheMu.Lock() delete(certCache, "") certCacheMu.Unlock() } _, err := CacheManagedCertificate(cert.Names[0], cert.Config) if err != nil { if allowPrompts { return err // operator is present, so report error immediately } log.Printf("[ERROR] %v", err) } } } // Apply queued deletion changes to the cache for _, cert := range deleteQueue { certCacheMu.Lock() for _, name := range cert.Names { delete(certCache, name) } certCacheMu.Unlock() } return nil }
go
func RenewManagedCertificates(allowPrompts bool) (err error) { var renewQueue, deleteQueue []Certificate visitedNames := make(map[string]struct{}) certCacheMu.RLock() for name, cert := range certCache { if !cert.Config.Managed || cert.Config.SelfSigned { continue } // the list of names on this cert should never be empty... if cert.Names == nil || len(cert.Names) == 0 { log.Printf("[WARNING] Certificate keyed by '%s' has no names: %v - removing from cache", name, cert.Names) deleteQueue = append(deleteQueue, cert) continue } // skip names whose certificate we've already renewed if _, ok := visitedNames[name]; ok { continue } for _, name := range cert.Names { visitedNames[name] = struct{}{} } // if its time is up or ending soon, we need to try to renew it timeLeft := cert.NotAfter.Sub(time.Now().UTC()) if timeLeft < RenewDurationBefore { log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft) if cert.Config == nil { log.Printf("[ERROR] %s: No associated TLS config; unable to renew", name) continue } // queue for renewal when we aren't in a read lock anymore // (the TLS-SNI challenge will need a write lock in order to // present the certificate, so we renew outside of read lock) renewQueue = append(renewQueue, cert) } } certCacheMu.RUnlock() // Perform renewals that are queued for _, cert := range renewQueue { // Get the name which we should use to renew this certificate; // we only support managing certificates with one name per cert, // so this should be easy. We can't rely on cert.Config.Hostname // because it may be a wildcard value from the Caddyfile (e.g. // *.something.com) which, as of Jan. 2017, is not supported by ACME. var renewName string for _, name := range cert.Names { if name != "" { renewName = name break } } // perform renewal err := cert.Config.RenewCert(renewName, allowPrompts) if err != nil { if allowPrompts { // Certificate renewal failed and the operator is present; we should stop // immediately and return the error. See a discussion in issue 642 // about this. For a while, we only stopped if the certificate was // expired, but in reality, there is no difference between reporting // it now versus later, except that there's somebody present to deal // with it now, so require it. return err } log.Printf("[ERROR] %v", err) if cert.Config.OnDemand { deleteQueue = append(deleteQueue, cert) } } else { // successful renewal, so update in-memory cache by loading // renewed certificate so it will be used with handshakes // TODO: Not until CA has valid OCSP response ready for the new cert... sigh. if cert.Names[len(cert.Names)-1] == "" { // Special case: This is the default certificate. We must // flush it out of the cache so that we no longer point to // the old, un-renewed certificate. Otherwise it will be // renewed on every scan, which is too often. The next cert // to be cached (probably this one) will become the default. certCacheMu.Lock() delete(certCache, "") certCacheMu.Unlock() } _, err := CacheManagedCertificate(cert.Names[0], cert.Config) if err != nil { if allowPrompts { return err // operator is present, so report error immediately } log.Printf("[ERROR] %v", err) } } } // Apply queued deletion changes to the cache for _, cert := range deleteQueue { certCacheMu.Lock() for _, name := range cert.Names { delete(certCache, name) } certCacheMu.Unlock() } return nil }
[ "func", "RenewManagedCertificates", "(", "allowPrompts", "bool", ")", "(", "err", "error", ")", "{", "var", "renewQueue", ",", "deleteQueue", "[", "]", "Certificate", "\n", "visitedNames", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n\n", "certCacheMu", ".", "RLock", "(", ")", "\n", "for", "name", ",", "cert", ":=", "range", "certCache", "{", "if", "!", "cert", ".", "Config", ".", "Managed", "||", "cert", ".", "Config", ".", "SelfSigned", "{", "continue", "\n", "}", "\n\n", "// the list of names on this cert should never be empty...", "if", "cert", ".", "Names", "==", "nil", "||", "len", "(", "cert", ".", "Names", ")", "==", "0", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "name", ",", "cert", ".", "Names", ")", "\n", "deleteQueue", "=", "append", "(", "deleteQueue", ",", "cert", ")", "\n", "continue", "\n", "}", "\n\n", "// skip names whose certificate we've already renewed", "if", "_", ",", "ok", ":=", "visitedNames", "[", "name", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "cert", ".", "Names", "{", "visitedNames", "[", "name", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// if its time is up or ending soon, we need to try to renew it", "timeLeft", ":=", "cert", ".", "NotAfter", ".", "Sub", "(", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ")", "\n", "if", "timeLeft", "<", "RenewDurationBefore", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "cert", ".", "Names", ",", "timeLeft", ")", "\n\n", "if", "cert", ".", "Config", "==", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "name", ")", "\n", "continue", "\n", "}", "\n\n", "// queue for renewal when we aren't in a read lock anymore", "// (the TLS-SNI challenge will need a write lock in order to", "// present the certificate, so we renew outside of read lock)", "renewQueue", "=", "append", "(", "renewQueue", ",", "cert", ")", "\n", "}", "\n", "}", "\n", "certCacheMu", ".", "RUnlock", "(", ")", "\n\n", "// Perform renewals that are queued", "for", "_", ",", "cert", ":=", "range", "renewQueue", "{", "// Get the name which we should use to renew this certificate;", "// we only support managing certificates with one name per cert,", "// so this should be easy. We can't rely on cert.Config.Hostname", "// because it may be a wildcard value from the Caddyfile (e.g.", "// *.something.com) which, as of Jan. 2017, is not supported by ACME.", "var", "renewName", "string", "\n", "for", "_", ",", "name", ":=", "range", "cert", ".", "Names", "{", "if", "name", "!=", "\"", "\"", "{", "renewName", "=", "name", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// perform renewal", "err", ":=", "cert", ".", "Config", ".", "RenewCert", "(", "renewName", ",", "allowPrompts", ")", "\n", "if", "err", "!=", "nil", "{", "if", "allowPrompts", "{", "// Certificate renewal failed and the operator is present; we should stop", "// immediately and return the error. See a discussion in issue 642", "// about this. For a while, we only stopped if the certificate was", "// expired, but in reality, there is no difference between reporting", "// it now versus later, except that there's somebody present to deal", "// with it now, so require it.", "return", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "if", "cert", ".", "Config", ".", "OnDemand", "{", "deleteQueue", "=", "append", "(", "deleteQueue", ",", "cert", ")", "\n", "}", "\n", "}", "else", "{", "// successful renewal, so update in-memory cache by loading", "// renewed certificate so it will be used with handshakes", "// TODO: Not until CA has valid OCSP response ready for the new cert... sigh.", "if", "cert", ".", "Names", "[", "len", "(", "cert", ".", "Names", ")", "-", "1", "]", "==", "\"", "\"", "{", "// Special case: This is the default certificate. We must", "// flush it out of the cache so that we no longer point to", "// the old, un-renewed certificate. Otherwise it will be", "// renewed on every scan, which is too often. The next cert", "// to be cached (probably this one) will become the default.", "certCacheMu", ".", "Lock", "(", ")", "\n", "delete", "(", "certCache", ",", "\"", "\"", ")", "\n", "certCacheMu", ".", "Unlock", "(", ")", "\n", "}", "\n", "_", ",", "err", ":=", "CacheManagedCertificate", "(", "cert", ".", "Names", "[", "0", "]", ",", "cert", ".", "Config", ")", "\n", "if", "err", "!=", "nil", "{", "if", "allowPrompts", "{", "return", "err", "// operator is present, so report error immediately", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Apply queued deletion changes to the cache", "for", "_", ",", "cert", ":=", "range", "deleteQueue", "{", "certCacheMu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "cert", ".", "Names", "{", "delete", "(", "certCache", ",", "name", ")", "\n", "}", "\n", "certCacheMu", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// RenewManagedCertificates renews managed certificates.
[ "RenewManagedCertificates", "renews", "managed", "certificates", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/maintain.go#L67-L175
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/maintain.go
freshOCSP
func freshOCSP(resp *ocsp.Response) bool { // start checking OCSP staple about halfway through validity period for good measure refreshTime := resp.ThisUpdate.Add(resp.NextUpdate.Sub(resp.ThisUpdate) / 2) return time.Now().Before(refreshTime) }
go
func freshOCSP(resp *ocsp.Response) bool { // start checking OCSP staple about halfway through validity period for good measure refreshTime := resp.ThisUpdate.Add(resp.NextUpdate.Sub(resp.ThisUpdate) / 2) return time.Now().Before(refreshTime) }
[ "func", "freshOCSP", "(", "resp", "*", "ocsp", ".", "Response", ")", "bool", "{", "// start checking OCSP staple about halfway through validity period for good measure", "refreshTime", ":=", "resp", ".", "ThisUpdate", ".", "Add", "(", "resp", ".", "NextUpdate", ".", "Sub", "(", "resp", ".", "ThisUpdate", ")", "/", "2", ")", "\n", "return", "time", ".", "Now", "(", ")", ".", "Before", "(", "refreshTime", ")", "\n", "}" ]
// freshOCSP returns true if resp is still fresh, // meaning that it is not expedient to get an // updated response from the OCSP server.
[ "freshOCSP", "returns", "true", "if", "resp", "is", "still", "fresh", "meaning", "that", "it", "is", "not", "expedient", "to", "get", "an", "updated", "response", "from", "the", "OCSP", "server", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/maintain.go#L295-L299
train
inverse-inc/packetfence
go/caddy/pfipset/utils.go
initIPSet
func (IPSET *pfIPSET) initIPSet(ctx context.Context, db *sql.DB) { logger := log.LoggerWContext(ctx) IPSET.ListALL, _ = ipset.ListAll() rows, err := db.Query("select distinct n.mac, i.ip, n.category_id as node_id from node as n left join locationlog as l on n.mac=l.mac left join ip4log as i on n.mac=i.mac where l.connection_type = \"inline\" and n.status=\"reg\" and n.mac=i.mac and i.end_time > NOW()") if err != nil { // Log here logger.Error("Error while fetching the inline nodes in the database: " + err.Error()) return } defer rows.Close() var ( IpStr string Mac string NodeId string ) for rows.Next() { err := rows.Scan(&Mac, &IpStr, &NodeId) if err != nil { // Log here logger.Error(err.Error()) return } for k, v := range IPSET.Network { if k.Contains(net.ParseIP(IpStr)) { if v == "inlinel2" { IPSET.IPSEThandleLayer2(ctx, IpStr, Mac, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL2(ctx, IpStr, k.IP.String(), NodeId) } if v == "inlinel3" { IPSET.IPSEThandleLayer3(ctx, IpStr, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL3(ctx, IpStr, k.IP.String(), NodeId) } break } } } }
go
func (IPSET *pfIPSET) initIPSet(ctx context.Context, db *sql.DB) { logger := log.LoggerWContext(ctx) IPSET.ListALL, _ = ipset.ListAll() rows, err := db.Query("select distinct n.mac, i.ip, n.category_id as node_id from node as n left join locationlog as l on n.mac=l.mac left join ip4log as i on n.mac=i.mac where l.connection_type = \"inline\" and n.status=\"reg\" and n.mac=i.mac and i.end_time > NOW()") if err != nil { // Log here logger.Error("Error while fetching the inline nodes in the database: " + err.Error()) return } defer rows.Close() var ( IpStr string Mac string NodeId string ) for rows.Next() { err := rows.Scan(&Mac, &IpStr, &NodeId) if err != nil { // Log here logger.Error(err.Error()) return } for k, v := range IPSET.Network { if k.Contains(net.ParseIP(IpStr)) { if v == "inlinel2" { IPSET.IPSEThandleLayer2(ctx, IpStr, Mac, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL2(ctx, IpStr, k.IP.String(), NodeId) } if v == "inlinel3" { IPSET.IPSEThandleLayer3(ctx, IpStr, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL3(ctx, IpStr, k.IP.String(), NodeId) } break } } } }
[ "func", "(", "IPSET", "*", "pfIPSET", ")", "initIPSet", "(", "ctx", "context", ".", "Context", ",", "db", "*", "sql", ".", "DB", ")", "{", "logger", ":=", "log", ".", "LoggerWContext", "(", "ctx", ")", "\n\n", "IPSET", ".", "ListALL", ",", "_", "=", "ipset", ".", "ListAll", "(", ")", "\n", "rows", ",", "err", ":=", "db", ".", "Query", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "// Log here", "logger", ".", "Error", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "var", "(", "IpStr", "string", "\n", "Mac", "string", "\n", "NodeId", "string", "\n", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "err", ":=", "rows", ".", "Scan", "(", "&", "Mac", ",", "&", "IpStr", ",", "&", "NodeId", ")", "\n", "if", "err", "!=", "nil", "{", "// Log here", "logger", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "IPSET", ".", "Network", "{", "if", "k", ".", "Contains", "(", "net", ".", "ParseIP", "(", "IpStr", ")", ")", "{", "if", "v", "==", "\"", "\"", "{", "IPSET", ".", "IPSEThandleLayer2", "(", "ctx", ",", "IpStr", ",", "Mac", ",", "k", ".", "IP", ".", "String", "(", ")", ",", "\"", "\"", ",", "NodeId", ")", "\n", "IPSET", ".", "IPSEThandleMarkIpL2", "(", "ctx", ",", "IpStr", ",", "k", ".", "IP", ".", "String", "(", ")", ",", "NodeId", ")", "\n", "}", "\n", "if", "v", "==", "\"", "\"", "{", "IPSET", ".", "IPSEThandleLayer3", "(", "ctx", ",", "IpStr", ",", "k", ".", "IP", ".", "String", "(", ")", ",", "\"", "\"", ",", "NodeId", ")", "\n", "IPSET", ".", "IPSEThandleMarkIpL3", "(", "ctx", ",", "IpStr", ",", "k", ".", "IP", ".", "String", "(", ")", ",", "NodeId", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// initIPSet fetch the database to remove already assigned ip addresses
[ "initIPSet", "fetch", "the", "database", "to", "remove", "already", "assigned", "ip", "addresses" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfipset/utils.go#L124-L161
train
inverse-inc/packetfence
go/caddy/pfipset/utils.go
detectType
func (IPSET *pfIPSET) detectType(ctx context.Context) error { IPSET.ListALL, _ = ipset.ListAll() var NetIndex net.IPNet IPSET.Network = make(map[*net.IPNet]string) var interfaces pfconfigdriver.ListenInts pfconfigdriver.FetchDecodeSocket(ctx, &interfaces) var keyConfNet pfconfigdriver.PfconfigKeys keyConfNet.PfconfigNS = "config::Network" keyConfNet.PfconfigHostnameOverlay = "yes" pfconfigdriver.FetchDecodeSocket(ctx, &keyConfNet) var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" for _, v := range interfaces.Element { keyConfCluster.PfconfigHashNS = "interface " + v pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode eth, _ := net.InterfaceByName(v) adresses, _ := eth.Addrs() for _, adresse := range adresses { var NetIP *net.IPNet var IP net.IP IP, NetIP, _ = net.ParseCIDR(adresse.String()) if IP.To4() == nil { continue } a, b := NetIP.Mask.Size() if a == b { continue } for _, key := range keyConfNet.Keys { var ConfNet pfconfigdriver.NetworkConf ConfNet.PfconfigHashNS = key pfconfigdriver.FetchDecodeSocket(ctx, &ConfNet) if (NetIP.Contains(net.ParseIP(ConfNet.DhcpStart)) && NetIP.Contains(net.ParseIP(ConfNet.DhcpEnd))) || NetIP.Contains(net.ParseIP(ConfNet.NextHop)) { NetIndex.Mask = net.IPMask(net.ParseIP(ConfNet.Netmask)) NetIndex.IP = net.ParseIP(key) Index := NetIndex IPSET.Network[&Index] = ConfNet.Type } } } } return nil }
go
func (IPSET *pfIPSET) detectType(ctx context.Context) error { IPSET.ListALL, _ = ipset.ListAll() var NetIndex net.IPNet IPSET.Network = make(map[*net.IPNet]string) var interfaces pfconfigdriver.ListenInts pfconfigdriver.FetchDecodeSocket(ctx, &interfaces) var keyConfNet pfconfigdriver.PfconfigKeys keyConfNet.PfconfigNS = "config::Network" keyConfNet.PfconfigHostnameOverlay = "yes" pfconfigdriver.FetchDecodeSocket(ctx, &keyConfNet) var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" for _, v := range interfaces.Element { keyConfCluster.PfconfigHashNS = "interface " + v pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode eth, _ := net.InterfaceByName(v) adresses, _ := eth.Addrs() for _, adresse := range adresses { var NetIP *net.IPNet var IP net.IP IP, NetIP, _ = net.ParseCIDR(adresse.String()) if IP.To4() == nil { continue } a, b := NetIP.Mask.Size() if a == b { continue } for _, key := range keyConfNet.Keys { var ConfNet pfconfigdriver.NetworkConf ConfNet.PfconfigHashNS = key pfconfigdriver.FetchDecodeSocket(ctx, &ConfNet) if (NetIP.Contains(net.ParseIP(ConfNet.DhcpStart)) && NetIP.Contains(net.ParseIP(ConfNet.DhcpEnd))) || NetIP.Contains(net.ParseIP(ConfNet.NextHop)) { NetIndex.Mask = net.IPMask(net.ParseIP(ConfNet.Netmask)) NetIndex.IP = net.ParseIP(key) Index := NetIndex IPSET.Network[&Index] = ConfNet.Type } } } } return nil }
[ "func", "(", "IPSET", "*", "pfIPSET", ")", "detectType", "(", "ctx", "context", ".", "Context", ")", "error", "{", "IPSET", ".", "ListALL", ",", "_", "=", "ipset", ".", "ListAll", "(", ")", "\n", "var", "NetIndex", "net", ".", "IPNet", "\n", "IPSET", ".", "Network", "=", "make", "(", "map", "[", "*", "net", ".", "IPNet", "]", "string", ")", "\n\n", "var", "interfaces", "pfconfigdriver", ".", "ListenInts", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "interfaces", ")", "\n\n", "var", "keyConfNet", "pfconfigdriver", ".", "PfconfigKeys", "\n", "keyConfNet", ".", "PfconfigNS", "=", "\"", "\"", "\n", "keyConfNet", ".", "PfconfigHostnameOverlay", "=", "\"", "\"", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "keyConfNet", ")", "\n\n", "var", "keyConfCluster", "pfconfigdriver", ".", "NetInterface", "\n", "keyConfCluster", ".", "PfconfigNS", "=", "\"", "\"", "+", "pfconfigdriver", ".", "FindClusterName", "(", "ctx", ")", "+", "\"", "\"", "\n\n", "for", "_", ",", "v", ":=", "range", "interfaces", ".", "Element", "{", "keyConfCluster", ".", "PfconfigHashNS", "=", "\"", "\"", "+", "v", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "keyConfCluster", ")", "\n", "// Nothing in keyConfCluster.Ip so we are not in cluster mode", "eth", ",", "_", ":=", "net", ".", "InterfaceByName", "(", "v", ")", "\n", "adresses", ",", "_", ":=", "eth", ".", "Addrs", "(", ")", "\n", "for", "_", ",", "adresse", ":=", "range", "adresses", "{", "var", "NetIP", "*", "net", ".", "IPNet", "\n", "var", "IP", "net", ".", "IP", "\n", "IP", ",", "NetIP", ",", "_", "=", "net", ".", "ParseCIDR", "(", "adresse", ".", "String", "(", ")", ")", "\n", "if", "IP", ".", "To4", "(", ")", "==", "nil", "{", "continue", "\n", "}", "\n", "a", ",", "b", ":=", "NetIP", ".", "Mask", ".", "Size", "(", ")", "\n", "if", "a", "==", "b", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "key", ":=", "range", "keyConfNet", ".", "Keys", "{", "var", "ConfNet", "pfconfigdriver", ".", "NetworkConf", "\n", "ConfNet", ".", "PfconfigHashNS", "=", "key", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "ConfNet", ")", "\n", "if", "(", "NetIP", ".", "Contains", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "DhcpStart", ")", ")", "&&", "NetIP", ".", "Contains", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "DhcpEnd", ")", ")", ")", "||", "NetIP", ".", "Contains", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "NextHop", ")", ")", "{", "NetIndex", ".", "Mask", "=", "net", ".", "IPMask", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "Netmask", ")", ")", "\n", "NetIndex", ".", "IP", "=", "net", ".", "ParseIP", "(", "key", ")", "\n", "Index", ":=", "NetIndex", "\n", "IPSET", ".", "Network", "[", "&", "Index", "]", "=", "ConfNet", ".", "Type", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// detectType of each network
[ "detectType", "of", "each", "network" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfipset/utils.go#L164-L215
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
cacheUnmanagedCertificatePEMFile
func cacheUnmanagedCertificatePEMFile(certFile, keyFile string) error { cert, err := makeCertificateFromDisk(certFile, keyFile) if err != nil { return err } cacheCertificate(cert) return nil }
go
func cacheUnmanagedCertificatePEMFile(certFile, keyFile string) error { cert, err := makeCertificateFromDisk(certFile, keyFile) if err != nil { return err } cacheCertificate(cert) return nil }
[ "func", "cacheUnmanagedCertificatePEMFile", "(", "certFile", ",", "keyFile", "string", ")", "error", "{", "cert", ",", "err", ":=", "makeCertificateFromDisk", "(", "certFile", ",", "keyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacheCertificate", "(", "cert", ")", "\n", "return", "nil", "\n", "}" ]
// cacheUnmanagedCertificatePEMFile loads a certificate for host using certFile // and keyFile, which must be in PEM format. It stores the certificate in // memory. The Managed and OnDemand flags of the certificate will be set to // false. // // This function is safe for concurrent use.
[ "cacheUnmanagedCertificatePEMFile", "loads", "a", "certificate", "for", "host", "using", "certFile", "and", "keyFile", "which", "must", "be", "in", "PEM", "format", ".", "It", "stores", "the", "certificate", "in", "memory", ".", "The", "Managed", "and", "OnDemand", "flags", "of", "the", "certificate", "will", "be", "set", "to", "false", ".", "This", "function", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L117-L124
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
cacheUnmanagedCertificatePEMBytes
func cacheUnmanagedCertificatePEMBytes(certBytes, keyBytes []byte) error { cert, err := makeCertificate(certBytes, keyBytes) if err != nil { return err } cacheCertificate(cert) return nil }
go
func cacheUnmanagedCertificatePEMBytes(certBytes, keyBytes []byte) error { cert, err := makeCertificate(certBytes, keyBytes) if err != nil { return err } cacheCertificate(cert) return nil }
[ "func", "cacheUnmanagedCertificatePEMBytes", "(", "certBytes", ",", "keyBytes", "[", "]", "byte", ")", "error", "{", "cert", ",", "err", ":=", "makeCertificate", "(", "certBytes", ",", "keyBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacheCertificate", "(", "cert", ")", "\n", "return", "nil", "\n", "}" ]
// cacheUnmanagedCertificatePEMBytes makes a certificate out of the PEM bytes // of the certificate and key, then caches it in memory. // // This function is safe for concurrent use.
[ "cacheUnmanagedCertificatePEMBytes", "makes", "a", "certificate", "out", "of", "the", "PEM", "bytes", "of", "the", "certificate", "and", "key", "then", "caches", "it", "in", "memory", ".", "This", "function", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L130-L137
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
makeCertificate
func makeCertificate(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { var cert Certificate // Convert to a tls.Certificate tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { return cert, err } if len(tlsCert.Certificate) == 0 { return cert, errors.New("certificate is empty") } cert.Certificate = tlsCert // Parse leaf certificate, extract relevant metadata, and staple OCSP leaf, err := x509.ParseCertificate(tlsCert.Certificate[0]) if err != nil { return cert, err } err = fillCertFromLeaf(&cert, leaf) if err != nil { return cert, err } err = stapleOCSP(&cert, certPEMBlock) if err != nil { log.Printf("[WARNING] Stapling OCSP: %v", err) } return cert, nil }
go
func makeCertificate(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { var cert Certificate // Convert to a tls.Certificate tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { return cert, err } if len(tlsCert.Certificate) == 0 { return cert, errors.New("certificate is empty") } cert.Certificate = tlsCert // Parse leaf certificate, extract relevant metadata, and staple OCSP leaf, err := x509.ParseCertificate(tlsCert.Certificate[0]) if err != nil { return cert, err } err = fillCertFromLeaf(&cert, leaf) if err != nil { return cert, err } err = stapleOCSP(&cert, certPEMBlock) if err != nil { log.Printf("[WARNING] Stapling OCSP: %v", err) } return cert, nil }
[ "func", "makeCertificate", "(", "certPEMBlock", ",", "keyPEMBlock", "[", "]", "byte", ")", "(", "Certificate", ",", "error", ")", "{", "var", "cert", "Certificate", "\n\n", "// Convert to a tls.Certificate", "tlsCert", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "certPEMBlock", ",", "keyPEMBlock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cert", ",", "err", "\n", "}", "\n", "if", "len", "(", "tlsCert", ".", "Certificate", ")", "==", "0", "{", "return", "cert", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "cert", ".", "Certificate", "=", "tlsCert", "\n\n", "// Parse leaf certificate, extract relevant metadata, and staple OCSP", "leaf", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "tlsCert", ".", "Certificate", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cert", ",", "err", "\n", "}", "\n", "err", "=", "fillCertFromLeaf", "(", "&", "cert", ",", "leaf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cert", ",", "err", "\n", "}", "\n", "err", "=", "stapleOCSP", "(", "&", "cert", ",", "certPEMBlock", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "cert", ",", "nil", "\n", "}" ]
// makeCertificate turns a certificate PEM bundle and a key PEM block into // a Certificate, with OCSP and other relevant metadata tagged with it, // except for the OnDemand and Managed flags. It is up to the caller to // set those properties.
[ "makeCertificate", "turns", "a", "certificate", "PEM", "bundle", "and", "a", "key", "PEM", "block", "into", "a", "Certificate", "with", "OCSP", "and", "other", "relevant", "metadata", "tagged", "with", "it", "except", "for", "the", "OnDemand", "and", "Managed", "flags", ".", "It", "is", "up", "to", "the", "caller", "to", "set", "those", "properties", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L159-L187
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
fillCertFromLeaf
func fillCertFromLeaf(cert *Certificate, leaf *x509.Certificate) error { if leaf.Subject.CommonName != "" { cert.Names = []string{strings.ToLower(leaf.Subject.CommonName)} } for _, name := range leaf.DNSNames { if name != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(name)) } } for _, ip := range leaf.IPAddresses { if ipStr := ip.String(); ipStr != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(ipStr)) } } for _, email := range leaf.EmailAddresses { if email != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(email)) } } if len(cert.Names) == 0 { return errors.New("certificate has no names") } cert.NotAfter = leaf.NotAfter return nil }
go
func fillCertFromLeaf(cert *Certificate, leaf *x509.Certificate) error { if leaf.Subject.CommonName != "" { cert.Names = []string{strings.ToLower(leaf.Subject.CommonName)} } for _, name := range leaf.DNSNames { if name != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(name)) } } for _, ip := range leaf.IPAddresses { if ipStr := ip.String(); ipStr != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(ipStr)) } } for _, email := range leaf.EmailAddresses { if email != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(email)) } } if len(cert.Names) == 0 { return errors.New("certificate has no names") } cert.NotAfter = leaf.NotAfter return nil }
[ "func", "fillCertFromLeaf", "(", "cert", "*", "Certificate", ",", "leaf", "*", "x509", ".", "Certificate", ")", "error", "{", "if", "leaf", ".", "Subject", ".", "CommonName", "!=", "\"", "\"", "{", "cert", ".", "Names", "=", "[", "]", "string", "{", "strings", ".", "ToLower", "(", "leaf", ".", "Subject", ".", "CommonName", ")", "}", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "leaf", ".", "DNSNames", "{", "if", "name", "!=", "leaf", ".", "Subject", ".", "CommonName", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "strings", ".", "ToLower", "(", "name", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "ip", ":=", "range", "leaf", ".", "IPAddresses", "{", "if", "ipStr", ":=", "ip", ".", "String", "(", ")", ";", "ipStr", "!=", "leaf", ".", "Subject", ".", "CommonName", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "strings", ".", "ToLower", "(", "ipStr", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "email", ":=", "range", "leaf", ".", "EmailAddresses", "{", "if", "email", "!=", "leaf", ".", "Subject", ".", "CommonName", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "strings", ".", "ToLower", "(", "email", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "cert", ".", "Names", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "cert", ".", "NotAfter", "=", "leaf", ".", "NotAfter", "\n", "return", "nil", "\n", "}" ]
// fillCertFromLeaf populates cert.Names and cert.NotAfter // using data in leaf.
[ "fillCertFromLeaf", "populates", "cert", ".", "Names", "and", "cert", ".", "NotAfter", "using", "data", "in", "leaf", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L191-L215
train