repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
inverse-inc/packetfence
go/caddy/requestlimit/requestlimit.go
ServeHTTP
func (h RequestLimitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { // Limit the concurrent requests that can run through the sem channel h.sem <- 1 defer func() { <-h.sem }() return h.Next.ServeHTTP(w, r) }
go
func (h RequestLimitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { // Limit the concurrent requests that can run through the sem channel h.sem <- 1 defer func() { <-h.sem }() return h.Next.ServeHTTP(w, r) }
[ "func", "(", "h", "RequestLimitHandler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "int", ",", "error", ")", "{", "h", ".", "sem", "<-", "1", "\n", "defer", "func", "(", ")", "{", "<-", "h", ".", "sem", "\n", "}", "(", ")", "\n", "return", "h", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}" ]
// Middleware that will rate limit the amount of concurrent requests the webserver can do at once // Controlled via the sem channel which has a capacity defined by the limit that is in the Caddyfile
[ "Middleware", "that", "will", "rate", "limit", "the", "amount", "of", "concurrent", "requests", "the", "webserver", "can", "do", "at", "once", "Controlled", "via", "the", "sem", "channel", "which", "has", "a", "capacity", "defined", "by", "the", "limit", "that", "is", "in", "the", "Caddyfile" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/requestlimit/requestlimit.go#L64-L72
train
inverse-inc/packetfence
go/logging/logging.go
NewContext
func NewContext(ctx context.Context) context.Context { u, _ := uuid.NewV4() uStr := u.String() ctx = context.WithValue(ctx, requestUuidKey, uStr) ctx = context.WithValue(ctx, processPidKey, strconv.Itoa(os.Getpid())) ctx = context.WithValue(ctx, additionnalLogElementsKey, make(map[interface{}]interface{})) return ctx }
go
func NewContext(ctx context.Context) context.Context { u, _ := uuid.NewV4() uStr := u.String() ctx = context.WithValue(ctx, requestUuidKey, uStr) ctx = context.WithValue(ctx, processPidKey, strconv.Itoa(os.Getpid())) ctx = context.WithValue(ctx, additionnalLogElementsKey, make(map[interface{}]interface{})) return ctx }
[ "func", "NewContext", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "u", ",", "_", ":=", "uuid", ".", "NewV4", "(", ")", "\n", "uStr", ":=", "u", ".", "String", "(", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "requestUuidKey", ",", "uStr", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "processPidKey", ",", "strconv", ".", "Itoa", "(", "os", ".", "Getpid", "(", ")", ")", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "additionnalLogElementsKey", ",", "make", "(", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ")", ")", "\n", "return", "ctx", "\n", "}" ]
// Grab a context that includes a UUID of the request for logging purposes
[ "Grab", "a", "context", "that", "includes", "a", "UUID", "of", "the", "request", "for", "logging", "purposes" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/logging/logging.go#L38-L45
train
inverse-inc/packetfence
go/caddy/forwardproxy/forwardproxy.go
dualStream
func dualStream(w1 io.Writer, r1 io.Reader, w2 io.Writer, r2 io.Reader) error { errChan := make(chan error) stream := func(w io.Writer, r io.Reader) { buf := bufferPool.Get().([]byte) buf = buf[0:cap(buf)] _, _err := flushingIoCopy(w, r, buf) errChan <- _err } go stream(w1, r1) go stream(w2, r2) err1 := <-errChan err2 := <-errChan if err1 != nil { return err1 } return err2 }
go
func dualStream(w1 io.Writer, r1 io.Reader, w2 io.Writer, r2 io.Reader) error { errChan := make(chan error) stream := func(w io.Writer, r io.Reader) { buf := bufferPool.Get().([]byte) buf = buf[0:cap(buf)] _, _err := flushingIoCopy(w, r, buf) errChan <- _err } go stream(w1, r1) go stream(w2, r2) err1 := <-errChan err2 := <-errChan if err1 != nil { return err1 } return err2 }
[ "func", "dualStream", "(", "w1", "io", ".", "Writer", ",", "r1", "io", ".", "Reader", ",", "w2", "io", ".", "Writer", ",", "r2", "io", ".", "Reader", ")", "error", "{", "errChan", ":=", "make", "(", "chan", "error", ")", "\n", "stream", ":=", "func", "(", "w", "io", ".", "Writer", ",", "r", "io", ".", "Reader", ")", "{", "buf", ":=", "bufferPool", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "\n", "buf", "=", "buf", "[", "0", ":", "cap", "(", "buf", ")", "]", "\n", "_", ",", "_err", ":=", "flushingIoCopy", "(", "w", ",", "r", ",", "buf", ")", "\n", "errChan", "<-", "_err", "\n", "}", "\n", "go", "stream", "(", "w1", ",", "r1", ")", "\n", "go", "stream", "(", "w2", ",", "r2", ")", "\n", "err1", ":=", "<-", "errChan", "\n", "err2", ":=", "<-", "errChan", "\n", "if", "err1", "!=", "nil", "{", "return", "err1", "\n", "}", "\n", "return", "err2", "\n", "}" ]
// Copies data r1->w1 and r2->w2, flushes as needed, and returns when both streams are done.
[ "Copies", "data", "r1", "-", ">", "w1", "and", "r2", "-", ">", "w2", "flushes", "as", "needed", "and", "returns", "when", "both", "streams", "are", "done", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L75-L93
train
inverse-inc/packetfence
go/caddy/forwardproxy/forwardproxy.go
serveHijack
func serveHijack(w http.ResponseWriter, targetConn net.Conn) (int, error) { hijacker, ok := w.(http.Hijacker) if !ok { return http.StatusInternalServerError, errors.New("ResponseWriter does not implement Hijacker") } clientConn, bufReader, err := hijacker.Hijack() if err != nil { return http.StatusInternalServerError, errors.New("failed to hijack: " + err.Error()) } defer clientConn.Close() // bufReader may contain unprocessed buffered data from the client. if bufReader != nil { // snippet borrowed from `proxy` plugin if n := bufReader.Reader.Buffered(); n > 0 { rbuf, err := bufReader.Reader.Peek(n) if err != nil { return http.StatusBadGateway, err } targetConn.Write(rbuf) } } // Since we hijacked the connection, we lost the ability to write and flush headers via w. // Let's handcraft the response and send it manually. res := &http.Response{StatusCode: http.StatusOK, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), } res.Header.Set("Server", "Caddy") err = res.Write(clientConn) if err != nil { return http.StatusInternalServerError, errors.New("failed to send response to client: " + err.Error()) } return 0, dualStream(targetConn, clientConn, clientConn, targetConn) }
go
func serveHijack(w http.ResponseWriter, targetConn net.Conn) (int, error) { hijacker, ok := w.(http.Hijacker) if !ok { return http.StatusInternalServerError, errors.New("ResponseWriter does not implement Hijacker") } clientConn, bufReader, err := hijacker.Hijack() if err != nil { return http.StatusInternalServerError, errors.New("failed to hijack: " + err.Error()) } defer clientConn.Close() // bufReader may contain unprocessed buffered data from the client. if bufReader != nil { // snippet borrowed from `proxy` plugin if n := bufReader.Reader.Buffered(); n > 0 { rbuf, err := bufReader.Reader.Peek(n) if err != nil { return http.StatusBadGateway, err } targetConn.Write(rbuf) } } // Since we hijacked the connection, we lost the ability to write and flush headers via w. // Let's handcraft the response and send it manually. res := &http.Response{StatusCode: http.StatusOK, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), } res.Header.Set("Server", "Caddy") err = res.Write(clientConn) if err != nil { return http.StatusInternalServerError, errors.New("failed to send response to client: " + err.Error()) } return 0, dualStream(targetConn, clientConn, clientConn, targetConn) }
[ "func", "serveHijack", "(", "w", "http", ".", "ResponseWriter", ",", "targetConn", "net", ".", "Conn", ")", "(", "int", ",", "error", ")", "{", "hijacker", ",", "ok", ":=", "w", ".", "(", "http", ".", "Hijacker", ")", "\n", "if", "!", "ok", "{", "return", "http", ".", "StatusInternalServerError", ",", "errors", ".", "New", "(", "\"ResponseWriter does not implement Hijacker\"", ")", "\n", "}", "\n", "clientConn", ",", "bufReader", ",", "err", ":=", "hijacker", ".", "Hijack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "http", ".", "StatusInternalServerError", ",", "errors", ".", "New", "(", "\"failed to hijack: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "defer", "clientConn", ".", "Close", "(", ")", "\n", "if", "bufReader", "!=", "nil", "{", "if", "n", ":=", "bufReader", ".", "Reader", ".", "Buffered", "(", ")", ";", "n", ">", "0", "{", "rbuf", ",", "err", ":=", "bufReader", ".", "Reader", ".", "Peek", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "http", ".", "StatusBadGateway", ",", "err", "\n", "}", "\n", "targetConn", ".", "Write", "(", "rbuf", ")", "\n", "}", "\n", "}", "\n", "res", ":=", "&", "http", ".", "Response", "{", "StatusCode", ":", "http", ".", "StatusOK", ",", "Proto", ":", "\"HTTP/1.1\"", ",", "ProtoMajor", ":", "1", ",", "ProtoMinor", ":", "1", ",", "Header", ":", "make", "(", "http", ".", "Header", ")", ",", "}", "\n", "res", ".", "Header", ".", "Set", "(", "\"Server\"", ",", "\"Caddy\"", ")", "\n", "err", "=", "res", ".", "Write", "(", "clientConn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "http", ".", "StatusInternalServerError", ",", "errors", ".", "New", "(", "\"failed to send response to client: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "0", ",", "dualStream", "(", "targetConn", ",", "clientConn", ",", "clientConn", ",", "targetConn", ")", "\n", "}" ]
// Hijacks the connection from ResponseWriter, writes the response and proxies data between targetConn // and hijacked connection.
[ "Hijacks", "the", "connection", "from", "ResponseWriter", "writes", "the", "response", "and", "proxies", "data", "between", "targetConn", "and", "hijacked", "connection", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L97-L134
train
inverse-inc/packetfence
go/caddy/forwardproxy/forwardproxy.go
checkCredentials
func (fp *ForwardProxy) checkCredentials(r *http.Request) error { pa := strings.Split(r.Header.Get("Proxy-Authorization"), " ") if len(pa) != 2 { return errors.New("Proxy-Authorization is required! Expected format: <type> <credentials>") } if strings.ToLower(pa[0]) != "basic" { return errors.New("Auth type is not supported") } for _, creds := range fp.authCredentials { if subtle.ConstantTimeCompare(creds, []byte(pa[1])) == 1 { // Please do not consider this to be timing-attack-safe code. Simple equality is almost // mindlessly substituted with constant time algo and there ARE known issues with this code, // e.g. size of smallest credentials is guessable. TODO: protect from all the attacks! Hash? return nil } } return errors.New("Invalid credentials") }
go
func (fp *ForwardProxy) checkCredentials(r *http.Request) error { pa := strings.Split(r.Header.Get("Proxy-Authorization"), " ") if len(pa) != 2 { return errors.New("Proxy-Authorization is required! Expected format: <type> <credentials>") } if strings.ToLower(pa[0]) != "basic" { return errors.New("Auth type is not supported") } for _, creds := range fp.authCredentials { if subtle.ConstantTimeCompare(creds, []byte(pa[1])) == 1 { // Please do not consider this to be timing-attack-safe code. Simple equality is almost // mindlessly substituted with constant time algo and there ARE known issues with this code, // e.g. size of smallest credentials is guessable. TODO: protect from all the attacks! Hash? return nil } } return errors.New("Invalid credentials") }
[ "func", "(", "fp", "*", "ForwardProxy", ")", "checkCredentials", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "pa", ":=", "strings", ".", "Split", "(", "r", ".", "Header", ".", "Get", "(", "\"Proxy-Authorization\"", ")", ",", "\" \"", ")", "\n", "if", "len", "(", "pa", ")", "!=", "2", "{", "return", "errors", ".", "New", "(", "\"Proxy-Authorization is required! Expected format: <type> <credentials>\"", ")", "\n", "}", "\n", "if", "strings", ".", "ToLower", "(", "pa", "[", "0", "]", ")", "!=", "\"basic\"", "{", "return", "errors", ".", "New", "(", "\"Auth type is not supported\"", ")", "\n", "}", "\n", "for", "_", ",", "creds", ":=", "range", "fp", ".", "authCredentials", "{", "if", "subtle", ".", "ConstantTimeCompare", "(", "creds", ",", "[", "]", "byte", "(", "pa", "[", "1", "]", ")", ")", "==", "1", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"Invalid credentials\"", ")", "\n", "}" ]
// Returns nil error on successful credentials check.
[ "Returns", "nil", "error", "on", "successful", "credentials", "check", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L137-L154
train
inverse-inc/packetfence
go/caddy/forwardproxy/forwardproxy.go
isSubdomain
func isSubdomain(s, domain string) bool { if s == domain { return true } if strings.HasSuffix(s, "."+domain) { return true } return false }
go
func isSubdomain(s, domain string) bool { if s == domain { return true } if strings.HasSuffix(s, "."+domain) { return true } return false }
[ "func", "isSubdomain", "(", "s", ",", "domain", "string", ")", "bool", "{", "if", "s", "==", "domain", "{", "return", "true", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "s", ",", "\".\"", "+", "domain", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// returns true if `s` is `domain` or subdomain of `domain`. Inputs are expected to be sanitized.
[ "returns", "true", "if", "s", "is", "domain", "or", "subdomain", "of", "domain", ".", "Inputs", "are", "expected", "to", "be", "sanitized", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L157-L165
train
inverse-inc/packetfence
go/caddy/forwardproxy/forwardproxy.go
forwardResponse
func forwardResponse(w http.ResponseWriter, response *http.Response) error { w.Header().Del("Server") // remove Server: Caddy, append via instead w.Header().Add("Via", strconv.Itoa(response.ProtoMajor)+"."+strconv.Itoa(response.ProtoMinor)+" caddy") for header, values := range response.Header { for _, val := range values { w.Header().Add(header, val) } } removeHopByHop(w.Header()) w.WriteHeader(response.StatusCode) buf := bufferPool.Get().([]byte) buf = buf[0:cap(buf)] _, err := io.CopyBuffer(w, response.Body, buf) response.Body.Close() return err }
go
func forwardResponse(w http.ResponseWriter, response *http.Response) error { w.Header().Del("Server") // remove Server: Caddy, append via instead w.Header().Add("Via", strconv.Itoa(response.ProtoMajor)+"."+strconv.Itoa(response.ProtoMinor)+" caddy") for header, values := range response.Header { for _, val := range values { w.Header().Add(header, val) } } removeHopByHop(w.Header()) w.WriteHeader(response.StatusCode) buf := bufferPool.Get().([]byte) buf = buf[0:cap(buf)] _, err := io.CopyBuffer(w, response.Body, buf) response.Body.Close() return err }
[ "func", "forwardResponse", "(", "w", "http", ".", "ResponseWriter", ",", "response", "*", "http", ".", "Response", ")", "error", "{", "w", ".", "Header", "(", ")", ".", "Del", "(", "\"Server\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"Via\"", ",", "strconv", ".", "Itoa", "(", "response", ".", "ProtoMajor", ")", "+", "\".\"", "+", "strconv", ".", "Itoa", "(", "response", ".", "ProtoMinor", ")", "+", "\" caddy\"", ")", "\n", "for", "header", ",", "values", ":=", "range", "response", ".", "Header", "{", "for", "_", ",", "val", ":=", "range", "values", "{", "w", ".", "Header", "(", ")", ".", "Add", "(", "header", ",", "val", ")", "\n", "}", "\n", "}", "\n", "removeHopByHop", "(", "w", ".", "Header", "(", ")", ")", "\n", "w", ".", "WriteHeader", "(", "response", ".", "StatusCode", ")", "\n", "buf", ":=", "bufferPool", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "\n", "buf", "=", "buf", "[", "0", ":", "cap", "(", "buf", ")", "]", "\n", "_", ",", "err", ":=", "io", ".", "CopyBuffer", "(", "w", ",", "response", ".", "Body", ",", "buf", ")", "\n", "response", ".", "Body", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}" ]
// Removes hop-by-hop headers, and writes response into ResponseWriter.
[ "Removes", "hop", "-", "by", "-", "hop", "headers", "and", "writes", "response", "into", "ResponseWriter", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L304-L320
train
inverse-inc/packetfence
go/caddy/forwardproxy/forwardproxy.go
generateForwardRequest
func (fp *ForwardProxy) generateForwardRequest(inReq *http.Request) (*http.Request, error) { // Scheme has to be appended to avoid `unsupported protocol scheme ""` error. // `http://` is used, since this initial request itself is always HTTP, regardless of what client and server // may speak afterwards. if len(inReq.RequestURI) == 0 { return nil, errors.New("malformed request: empty URI") } strUrl := inReq.RequestURI if strUrl[0] == '/' { strUrl = inReq.Host + strUrl } if !strings.Contains(strUrl, "://") { strUrl = "http://" + strUrl } outReq, err := http.NewRequest(inReq.Method, strUrl, inReq.Body) if err != nil { return outReq, errors.New("failed to create NewRequest: " + err.Error()) } for key, values := range inReq.Header { for _, value := range values { outReq.Header.Add(key, value) } } removeHopByHop(outReq.Header) if !fp.hideIP { outReq.Header.Add("Forwarded", "for=\""+inReq.RemoteAddr+"\"") } // https://tools.ietf.org/html/rfc7230#section-5.7.1 outReq.Header.Add("Via", strconv.Itoa(inReq.ProtoMajor)+"."+strconv.Itoa(inReq.ProtoMinor)+" caddy") return outReq, nil }
go
func (fp *ForwardProxy) generateForwardRequest(inReq *http.Request) (*http.Request, error) { // Scheme has to be appended to avoid `unsupported protocol scheme ""` error. // `http://` is used, since this initial request itself is always HTTP, regardless of what client and server // may speak afterwards. if len(inReq.RequestURI) == 0 { return nil, errors.New("malformed request: empty URI") } strUrl := inReq.RequestURI if strUrl[0] == '/' { strUrl = inReq.Host + strUrl } if !strings.Contains(strUrl, "://") { strUrl = "http://" + strUrl } outReq, err := http.NewRequest(inReq.Method, strUrl, inReq.Body) if err != nil { return outReq, errors.New("failed to create NewRequest: " + err.Error()) } for key, values := range inReq.Header { for _, value := range values { outReq.Header.Add(key, value) } } removeHopByHop(outReq.Header) if !fp.hideIP { outReq.Header.Add("Forwarded", "for=\""+inReq.RemoteAddr+"\"") } // https://tools.ietf.org/html/rfc7230#section-5.7.1 outReq.Header.Add("Via", strconv.Itoa(inReq.ProtoMajor)+"."+strconv.Itoa(inReq.ProtoMinor)+" caddy") return outReq, nil }
[ "func", "(", "fp", "*", "ForwardProxy", ")", "generateForwardRequest", "(", "inReq", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "if", "len", "(", "inReq", ".", "RequestURI", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"malformed request: empty URI\"", ")", "\n", "}", "\n", "strUrl", ":=", "inReq", ".", "RequestURI", "\n", "if", "strUrl", "[", "0", "]", "==", "'/'", "{", "strUrl", "=", "inReq", ".", "Host", "+", "strUrl", "\n", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "strUrl", ",", "\"://\"", ")", "{", "strUrl", "=", "\"http://\"", "+", "strUrl", "\n", "}", "\n", "outReq", ",", "err", ":=", "http", ".", "NewRequest", "(", "inReq", ".", "Method", ",", "strUrl", ",", "inReq", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "outReq", ",", "errors", ".", "New", "(", "\"failed to create NewRequest: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "for", "key", ",", "values", ":=", "range", "inReq", ".", "Header", "{", "for", "_", ",", "value", ":=", "range", "values", "{", "outReq", ".", "Header", ".", "Add", "(", "key", ",", "value", ")", "\n", "}", "\n", "}", "\n", "removeHopByHop", "(", "outReq", ".", "Header", ")", "\n", "if", "!", "fp", ".", "hideIP", "{", "outReq", ".", "Header", ".", "Add", "(", "\"Forwarded\"", ",", "\"for=\\\"\"", "+", "\\\"", "+", "inReq", ".", "RemoteAddr", ")", "\n", "}", "\n", "\"\\\"\"", "\n", "\\\"", "\n", "}" ]
// Based on http Request from client, generates new request to be forwarded to target server. // Some fields are shallow-copied, thus genOutReq will mutate original request. // If error is not nil - http.StatusBadRequest is to be sent to client.
[ "Based", "on", "http", "Request", "from", "client", "generates", "new", "request", "to", "be", "forwarded", "to", "target", "server", ".", "Some", "fields", "are", "shallow", "-", "copied", "thus", "genOutReq", "will", "mutate", "original", "request", ".", "If", "error", "is", "not", "nil", "-", "http", ".", "StatusBadRequest", "is", "to", "be", "sent", "to", "client", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L325-L357
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/proxy/proxy.go
createUpstreamRequest
func createUpstreamRequest(r *http.Request) *http.Request { outreq := new(http.Request) *outreq = *r // includes shallow copies of maps, but okay // We should set body to nil explicitly if request body is empty. // For server requests the Request Body is always non-nil. if r.ContentLength == 0 { outreq.Body = nil } // Restore URL Path if it has been modified if outreq.URL.RawPath != "" { outreq.URL.Opaque = outreq.URL.RawPath } // We are modifying the same underlying map from req (shallow // copied above) so we only copy it if necessary. copiedHeaders := false // Remove hop-by-hop headers listed in the "Connection" header. // See RFC 2616, section 14.10. if c := outreq.Header.Get("Connection"); c != "" { for _, f := range strings.Split(c, ",") { if f = strings.TrimSpace(f); f != "" { if !copiedHeaders { outreq.Header = make(http.Header) copyHeader(outreq.Header, r.Header) copiedHeaders = true } outreq.Header.Del(f) } } } // Remove hop-by-hop headers to the backend. Especially // important is "Connection" because we want a persistent // connection, regardless of what the client sent to us. for _, h := range hopHeaders { if outreq.Header.Get(h) != "" { if !copiedHeaders { outreq.Header = make(http.Header) copyHeader(outreq.Header, r.Header) copiedHeaders = true } outreq.Header.Del(h) } } if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { // If we aren't the first proxy, retain prior // X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. if prior, ok := outreq.Header["X-Forwarded-For"]; ok { clientIP = strings.Join(prior, ", ") + ", " + clientIP } outreq.Header.Set("X-Forwarded-For", clientIP) } return outreq }
go
func createUpstreamRequest(r *http.Request) *http.Request { outreq := new(http.Request) *outreq = *r // includes shallow copies of maps, but okay // We should set body to nil explicitly if request body is empty. // For server requests the Request Body is always non-nil. if r.ContentLength == 0 { outreq.Body = nil } // Restore URL Path if it has been modified if outreq.URL.RawPath != "" { outreq.URL.Opaque = outreq.URL.RawPath } // We are modifying the same underlying map from req (shallow // copied above) so we only copy it if necessary. copiedHeaders := false // Remove hop-by-hop headers listed in the "Connection" header. // See RFC 2616, section 14.10. if c := outreq.Header.Get("Connection"); c != "" { for _, f := range strings.Split(c, ",") { if f = strings.TrimSpace(f); f != "" { if !copiedHeaders { outreq.Header = make(http.Header) copyHeader(outreq.Header, r.Header) copiedHeaders = true } outreq.Header.Del(f) } } } // Remove hop-by-hop headers to the backend. Especially // important is "Connection" because we want a persistent // connection, regardless of what the client sent to us. for _, h := range hopHeaders { if outreq.Header.Get(h) != "" { if !copiedHeaders { outreq.Header = make(http.Header) copyHeader(outreq.Header, r.Header) copiedHeaders = true } outreq.Header.Del(h) } } if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { // If we aren't the first proxy, retain prior // X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. if prior, ok := outreq.Header["X-Forwarded-For"]; ok { clientIP = strings.Join(prior, ", ") + ", " + clientIP } outreq.Header.Set("X-Forwarded-For", clientIP) } return outreq }
[ "func", "createUpstreamRequest", "(", "r", "*", "http", ".", "Request", ")", "*", "http", ".", "Request", "{", "outreq", ":=", "new", "(", "http", ".", "Request", ")", "\n", "*", "outreq", "=", "*", "r", "\n", "if", "r", ".", "ContentLength", "==", "0", "{", "outreq", ".", "Body", "=", "nil", "\n", "}", "\n", "if", "outreq", ".", "URL", ".", "RawPath", "!=", "\"\"", "{", "outreq", ".", "URL", ".", "Opaque", "=", "outreq", ".", "URL", ".", "RawPath", "\n", "}", "\n", "copiedHeaders", ":=", "false", "\n", "if", "c", ":=", "outreq", ".", "Header", ".", "Get", "(", "\"Connection\"", ")", ";", "c", "!=", "\"\"", "{", "for", "_", ",", "f", ":=", "range", "strings", ".", "Split", "(", "c", ",", "\",\"", ")", "{", "if", "f", "=", "strings", ".", "TrimSpace", "(", "f", ")", ";", "f", "!=", "\"\"", "{", "if", "!", "copiedHeaders", "{", "outreq", ".", "Header", "=", "make", "(", "http", ".", "Header", ")", "\n", "copyHeader", "(", "outreq", ".", "Header", ",", "r", ".", "Header", ")", "\n", "copiedHeaders", "=", "true", "\n", "}", "\n", "outreq", ".", "Header", ".", "Del", "(", "f", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "h", ":=", "range", "hopHeaders", "{", "if", "outreq", ".", "Header", ".", "Get", "(", "h", ")", "!=", "\"\"", "{", "if", "!", "copiedHeaders", "{", "outreq", ".", "Header", "=", "make", "(", "http", ".", "Header", ")", "\n", "copyHeader", "(", "outreq", ".", "Header", ",", "r", ".", "Header", ")", "\n", "copiedHeaders", "=", "true", "\n", "}", "\n", "outreq", ".", "Header", ".", "Del", "(", "h", ")", "\n", "}", "\n", "}", "\n", "if", "clientIP", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "r", ".", "RemoteAddr", ")", ";", "err", "==", "nil", "{", "if", "prior", ",", "ok", ":=", "outreq", ".", "Header", "[", "\"X-Forwarded-For\"", "]", ";", "ok", "{", "clientIP", "=", "strings", ".", "Join", "(", "prior", ",", "\", \"", ")", "+", "\", \"", "+", "clientIP", "\n", "}", "\n", "outreq", ".", "Header", ".", "Set", "(", "\"X-Forwarded-For\"", ",", "clientIP", ")", "\n", "}", "\n", "return", "outreq", "\n", "}" ]
// createUpstremRequest shallow-copies r into a new request // that can be sent upstream. // // Derived from reverseproxy.go in the standard Go httputil package.
[ "createUpstremRequest", "shallow", "-", "copies", "r", "into", "a", "new", "request", "that", "can", "be", "sent", "upstream", ".", "Derived", "from", "reverseproxy", ".", "go", "in", "the", "standard", "Go", "httputil", "package", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/proxy/proxy.go#L270-L328
train
inverse-inc/packetfence
go/caddy/caddy/plugins.go
StartupHooks
func StartupHooks(serverType string) error { for stype, stypePlugins := range plugins { if stype != "" && stype != serverType { continue } for name := range stypePlugins { if stypePlugins[name].StartupHook == nil { continue } err := stypePlugins[name].StartupHook() if err != nil { return err } } } return nil }
go
func StartupHooks(serverType string) error { for stype, stypePlugins := range plugins { if stype != "" && stype != serverType { continue } for name := range stypePlugins { if stypePlugins[name].StartupHook == nil { continue } err := stypePlugins[name].StartupHook() if err != nil { return err } } } return nil }
[ "func", "StartupHooks", "(", "serverType", "string", ")", "error", "{", "for", "stype", ",", "stypePlugins", ":=", "range", "plugins", "{", "if", "stype", "!=", "\"\"", "&&", "stype", "!=", "serverType", "{", "continue", "\n", "}", "\n", "for", "name", ":=", "range", "stypePlugins", "{", "if", "stypePlugins", "[", "name", "]", ".", "StartupHook", "==", "nil", "{", "continue", "\n", "}", "\n", "err", ":=", "stypePlugins", "[", "name", "]", ".", "StartupHook", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StartupHooks executes the startup hooks defined when the // plugins were registered and returns the first error // it encounters.
[ "StartupHooks", "executes", "the", "startup", "hooks", "defined", "when", "the", "plugins", "were", "registered", "and", "returns", "the", "first", "error", "it", "encounters", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/plugins.go#L75-L94
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/browse/browse.go
BreadcrumbMap
func (l Listing) BreadcrumbMap() map[string]string { result := map[string]string{} if len(l.Path) == 0 { return result } // skip trailing slash lpath := l.Path if lpath[len(lpath)-1] == '/' { lpath = lpath[:len(lpath)-1] } parts := strings.Split(lpath, "/") for i, part := range parts { if i == 0 && part == "" { // Leading slash (root) result["/"] = "/" continue } result[strings.Join(parts[:i+1], "/")] = part } return result }
go
func (l Listing) BreadcrumbMap() map[string]string { result := map[string]string{} if len(l.Path) == 0 { return result } // skip trailing slash lpath := l.Path if lpath[len(lpath)-1] == '/' { lpath = lpath[:len(lpath)-1] } parts := strings.Split(lpath, "/") for i, part := range parts { if i == 0 && part == "" { // Leading slash (root) result["/"] = "/" continue } result[strings.Join(parts[:i+1], "/")] = part } return result }
[ "func", "(", "l", "Listing", ")", "BreadcrumbMap", "(", ")", "map", "[", "string", "]", "string", "{", "result", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "if", "len", "(", "l", ".", "Path", ")", "==", "0", "{", "return", "result", "\n", "}", "\n", "lpath", ":=", "l", ".", "Path", "\n", "if", "lpath", "[", "len", "(", "lpath", ")", "-", "1", "]", "==", "'/'", "{", "lpath", "=", "lpath", "[", ":", "len", "(", "lpath", ")", "-", "1", "]", "\n", "}", "\n", "parts", ":=", "strings", ".", "Split", "(", "lpath", ",", "\"/\"", ")", "\n", "for", "i", ",", "part", ":=", "range", "parts", "{", "if", "i", "==", "0", "&&", "part", "==", "\"\"", "{", "result", "[", "\"/\"", "]", "=", "\"/\"", "\n", "continue", "\n", "}", "\n", "result", "[", "strings", ".", "Join", "(", "parts", "[", ":", "i", "+", "1", "]", ",", "\"/\"", ")", "]", "=", "part", "\n", "}", "\n", "return", "result", "\n", "}" ]
// BreadcrumbMap returns l.Path where every element is a map // of URLs and path segment names.
[ "BreadcrumbMap", "returns", "l", ".", "Path", "where", "every", "element", "is", "a", "map", "of", "URLs", "and", "path", "segment", "names", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/browse/browse.go#L82-L106
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/browse/browse.go
applySort
func (l Listing) applySort() { // Check '.Order' to know how to sort if l.Order == "desc" { switch l.Sort { case sortByName: sort.Sort(sort.Reverse(byName(l))) case sortBySize: sort.Sort(sort.Reverse(bySize(l))) case sortByTime: sort.Sort(sort.Reverse(byTime(l))) default: // If not one of the above, do nothing return } } else { // If we had more Orderings we could add them here switch l.Sort { case sortByName: sort.Sort(byName(l)) case sortBySize: sort.Sort(bySize(l)) case sortByTime: sort.Sort(byTime(l)) default: // If not one of the above, do nothing return } } }
go
func (l Listing) applySort() { // Check '.Order' to know how to sort if l.Order == "desc" { switch l.Sort { case sortByName: sort.Sort(sort.Reverse(byName(l))) case sortBySize: sort.Sort(sort.Reverse(bySize(l))) case sortByTime: sort.Sort(sort.Reverse(byTime(l))) default: // If not one of the above, do nothing return } } else { // If we had more Orderings we could add them here switch l.Sort { case sortByName: sort.Sort(byName(l)) case sortBySize: sort.Sort(bySize(l)) case sortByTime: sort.Sort(byTime(l)) default: // If not one of the above, do nothing return } } }
[ "func", "(", "l", "Listing", ")", "applySort", "(", ")", "{", "if", "l", ".", "Order", "==", "\"desc\"", "{", "switch", "l", ".", "Sort", "{", "case", "sortByName", ":", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byName", "(", "l", ")", ")", ")", "\n", "case", "sortBySize", ":", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "bySize", "(", "l", ")", ")", ")", "\n", "case", "sortByTime", ":", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byTime", "(", "l", ")", ")", ")", "\n", "default", ":", "return", "\n", "}", "\n", "}", "else", "{", "switch", "l", ".", "Sort", "{", "case", "sortByName", ":", "sort", ".", "Sort", "(", "byName", "(", "l", ")", ")", "\n", "case", "sortBySize", ":", "sort", ".", "Sort", "(", "bySize", "(", "l", ")", ")", "\n", "case", "sortByTime", ":", "sort", ".", "Sort", "(", "byTime", "(", "l", ")", ")", "\n", "default", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Add sorting method to "Listing" // it will apply what's in ".Sort" and ".Order"
[ "Add", "sorting", "method", "to", "Listing", "it", "will", "apply", "what", "s", "in", ".", "Sort", "and", ".", "Order" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/browse/browse.go#L166-L193
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/browse/browse.go
ServeHTTP
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { // See if there's a browse configuration to match the path var bc *Config for i := range b.Configs { if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) { bc = &b.Configs[i] break } } if bc == nil { return b.Next.ServeHTTP(w, r) } // Browse works on existing directories; delegate everything else requestedFilepath, err := bc.Fs.Root.Open(r.URL.Path) if err != nil { switch { case os.IsPermission(err): return http.StatusForbidden, err case os.IsExist(err): return http.StatusNotFound, err default: return b.Next.ServeHTTP(w, r) } } defer requestedFilepath.Close() info, err := requestedFilepath.Stat() if err != nil { switch { case os.IsPermission(err): return http.StatusForbidden, err case os.IsExist(err): return http.StatusGone, err default: return b.Next.ServeHTTP(w, r) } } if !info.IsDir() { return b.Next.ServeHTTP(w, r) } // Do not reply to anything else because it might be nonsensical switch r.Method { case http.MethodGet, http.MethodHead: // proceed, noop case "PROPFIND", http.MethodOptions: return http.StatusNotImplemented, nil default: return b.Next.ServeHTTP(w, r) } // Browsing navigation gets messed up if browsing a directory // that doesn't end in "/" (which it should, anyway) if !strings.HasSuffix(r.URL.Path, "/") { staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect) return 0, nil } return b.ServeListing(w, r, requestedFilepath, bc) }
go
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { // See if there's a browse configuration to match the path var bc *Config for i := range b.Configs { if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) { bc = &b.Configs[i] break } } if bc == nil { return b.Next.ServeHTTP(w, r) } // Browse works on existing directories; delegate everything else requestedFilepath, err := bc.Fs.Root.Open(r.URL.Path) if err != nil { switch { case os.IsPermission(err): return http.StatusForbidden, err case os.IsExist(err): return http.StatusNotFound, err default: return b.Next.ServeHTTP(w, r) } } defer requestedFilepath.Close() info, err := requestedFilepath.Stat() if err != nil { switch { case os.IsPermission(err): return http.StatusForbidden, err case os.IsExist(err): return http.StatusGone, err default: return b.Next.ServeHTTP(w, r) } } if !info.IsDir() { return b.Next.ServeHTTP(w, r) } // Do not reply to anything else because it might be nonsensical switch r.Method { case http.MethodGet, http.MethodHead: // proceed, noop case "PROPFIND", http.MethodOptions: return http.StatusNotImplemented, nil default: return b.Next.ServeHTTP(w, r) } // Browsing navigation gets messed up if browsing a directory // that doesn't end in "/" (which it should, anyway) if !strings.HasSuffix(r.URL.Path, "/") { staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect) return 0, nil } return b.ServeListing(w, r, requestedFilepath, bc) }
[ "func", "(", "b", "Browse", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "int", ",", "error", ")", "{", "var", "bc", "*", "Config", "\n", "for", "i", ":=", "range", "b", ".", "Configs", "{", "if", "httpserver", ".", "Path", "(", "r", ".", "URL", ".", "Path", ")", ".", "Matches", "(", "b", ".", "Configs", "[", "i", "]", ".", "PathScope", ")", "{", "bc", "=", "&", "b", ".", "Configs", "[", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "bc", "==", "nil", "{", "return", "b", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "requestedFilepath", ",", "err", ":=", "bc", ".", "Fs", ".", "Root", ".", "Open", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "{", "case", "os", ".", "IsPermission", "(", "err", ")", ":", "return", "http", ".", "StatusForbidden", ",", "err", "\n", "case", "os", ".", "IsExist", "(", "err", ")", ":", "return", "http", ".", "StatusNotFound", ",", "err", "\n", "default", ":", "return", "b", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "}", "\n", "defer", "requestedFilepath", ".", "Close", "(", ")", "\n", "info", ",", "err", ":=", "requestedFilepath", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "{", "case", "os", ".", "IsPermission", "(", "err", ")", ":", "return", "http", ".", "StatusForbidden", ",", "err", "\n", "case", "os", ".", "IsExist", "(", "err", ")", ":", "return", "http", ".", "StatusGone", ",", "err", "\n", "default", ":", "return", "b", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "}", "\n", "if", "!", "info", ".", "IsDir", "(", ")", "{", "return", "b", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "switch", "r", ".", "Method", "{", "case", "http", ".", "MethodGet", ",", "http", ".", "MethodHead", ":", "case", "\"PROPFIND\"", ",", "http", ".", "MethodOptions", ":", "return", "http", ".", "StatusNotImplemented", ",", "nil", "\n", "default", ":", "return", "b", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "r", ".", "URL", ".", "Path", ",", "\"/\"", ")", "{", "staticfiles", ".", "Redirect", "(", "w", ",", "r", ",", "r", ".", "URL", ".", "Path", "+", "\"/\"", ",", "http", ".", "StatusTemporaryRedirect", ")", "\n", "return", "0", ",", "nil", "\n", "}", "\n", "return", "b", ".", "ServeListing", "(", "w", ",", "r", ",", "requestedFilepath", ",", "bc", ")", "\n", "}" ]
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met. // If so, control is handed over to ServeListing.
[ "ServeHTTP", "determines", "if", "the", "request", "is", "for", "this", "plugin", "and", "if", "all", "prerequisites", "are", "met", ".", "If", "so", "control", "is", "handed", "over", "to", "ServeListing", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/browse/browse.go#L247-L307
train
inverse-inc/packetfence
go/caddy/caddy/sigtrap.go
executeShutdownCallbacks
func executeShutdownCallbacks(signame string) (exitCode int) { shutdownCallbacksOnce.Do(func() { errs := allShutdownCallbacks() if len(errs) > 0 { for _, err := range errs { log.Printf("[ERROR] %s shutdown: %v", signame, err) } exitCode = 1 } }) return }
go
func executeShutdownCallbacks(signame string) (exitCode int) { shutdownCallbacksOnce.Do(func() { errs := allShutdownCallbacks() if len(errs) > 0 { for _, err := range errs { log.Printf("[ERROR] %s shutdown: %v", signame, err) } exitCode = 1 } }) return }
[ "func", "executeShutdownCallbacks", "(", "signame", "string", ")", "(", "exitCode", "int", ")", "{", "shutdownCallbacksOnce", ".", "Do", "(", "func", "(", ")", "{", "errs", ":=", "allShutdownCallbacks", "(", ")", "\n", "if", "len", "(", "errs", ")", ">", "0", "{", "for", "_", ",", "err", ":=", "range", "errs", "{", "log", ".", "Printf", "(", "\"[ERROR] %s shutdown: %v\"", ",", "signame", ",", "err", ")", "\n", "}", "\n", "exitCode", "=", "1", "\n", "}", "\n", "}", ")", "\n", "return", "\n", "}" ]
// executeShutdownCallbacks executes the shutdown callbacks as initiated // by signame. It logs any errors and returns the recommended exit status. // This function is idempotent; subsequent invocations always return 0.
[ "executeShutdownCallbacks", "executes", "the", "shutdown", "callbacks", "as", "initiated", "by", "signame", ".", "It", "logs", "any", "errors", "and", "returns", "the", "recommended", "exit", "status", ".", "This", "function", "is", "idempotent", ";", "subsequent", "invocations", "always", "return", "0", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/sigtrap.go#L53-L64
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/plugin.go
standardizeAddress
func standardizeAddress(str string) (Address, error) { input := str // Split input into components (prepend with // to assert host by default) if !strings.Contains(str, "//") && !strings.HasPrefix(str, "/") { str = "//" + str } u, err := url.Parse(str) if err != nil { return Address{}, err } // separate host and port host, port, err := net.SplitHostPort(u.Host) if err != nil { host, port, err = net.SplitHostPort(u.Host + ":") if err != nil { host = u.Host } } // see if we can set port based off scheme if port == "" { if u.Scheme == "http" { port = "80" } else if u.Scheme == "https" { port = "443" } } // repeated or conflicting scheme is confusing, so error if u.Scheme != "" && (port == "http" || port == "https") { return Address{}, fmt.Errorf("[%s] scheme specified twice in address", input) } // error if scheme and port combination violate convention if (u.Scheme == "http" && port == "443") || (u.Scheme == "https" && port == "80") { return Address{}, fmt.Errorf("[%s] scheme and port violate convention", input) } // standardize http and https ports to their respective port numbers if port == "http" { u.Scheme = "http" port = "80" } else if port == "https" { u.Scheme = "https" port = "443" } return Address{Original: input, Scheme: u.Scheme, Host: host, Port: port, Path: u.Path}, err }
go
func standardizeAddress(str string) (Address, error) { input := str // Split input into components (prepend with // to assert host by default) if !strings.Contains(str, "//") && !strings.HasPrefix(str, "/") { str = "//" + str } u, err := url.Parse(str) if err != nil { return Address{}, err } // separate host and port host, port, err := net.SplitHostPort(u.Host) if err != nil { host, port, err = net.SplitHostPort(u.Host + ":") if err != nil { host = u.Host } } // see if we can set port based off scheme if port == "" { if u.Scheme == "http" { port = "80" } else if u.Scheme == "https" { port = "443" } } // repeated or conflicting scheme is confusing, so error if u.Scheme != "" && (port == "http" || port == "https") { return Address{}, fmt.Errorf("[%s] scheme specified twice in address", input) } // error if scheme and port combination violate convention if (u.Scheme == "http" && port == "443") || (u.Scheme == "https" && port == "80") { return Address{}, fmt.Errorf("[%s] scheme and port violate convention", input) } // standardize http and https ports to their respective port numbers if port == "http" { u.Scheme = "http" port = "80" } else if port == "https" { u.Scheme = "https" port = "443" } return Address{Original: input, Scheme: u.Scheme, Host: host, Port: port, Path: u.Path}, err }
[ "func", "standardizeAddress", "(", "str", "string", ")", "(", "Address", ",", "error", ")", "{", "input", ":=", "str", "\n", "if", "!", "strings", ".", "Contains", "(", "str", ",", "\"//\"", ")", "&&", "!", "strings", ".", "HasPrefix", "(", "str", ",", "\"/\"", ")", "{", "str", "=", "\"//\"", "+", "str", "\n", "}", "\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Address", "{", "}", ",", "err", "\n", "}", "\n", "host", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "u", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "host", ",", "port", ",", "err", "=", "net", ".", "SplitHostPort", "(", "u", ".", "Host", "+", "\":\"", ")", "\n", "if", "err", "!=", "nil", "{", "host", "=", "u", ".", "Host", "\n", "}", "\n", "}", "\n", "if", "port", "==", "\"\"", "{", "if", "u", ".", "Scheme", "==", "\"http\"", "{", "port", "=", "\"80\"", "\n", "}", "else", "if", "u", ".", "Scheme", "==", "\"https\"", "{", "port", "=", "\"443\"", "\n", "}", "\n", "}", "\n", "if", "u", ".", "Scheme", "!=", "\"\"", "&&", "(", "port", "==", "\"http\"", "||", "port", "==", "\"https\"", ")", "{", "return", "Address", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"[%s] scheme specified twice in address\"", ",", "input", ")", "\n", "}", "\n", "if", "(", "u", ".", "Scheme", "==", "\"http\"", "&&", "port", "==", "\"443\"", ")", "||", "(", "u", ".", "Scheme", "==", "\"https\"", "&&", "port", "==", "\"80\"", ")", "{", "return", "Address", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"[%s] scheme and port violate convention\"", ",", "input", ")", "\n", "}", "\n", "if", "port", "==", "\"http\"", "{", "u", ".", "Scheme", "=", "\"http\"", "\n", "port", "=", "\"80\"", "\n", "}", "else", "if", "port", "==", "\"https\"", "{", "u", ".", "Scheme", "=", "\"https\"", "\n", "port", "=", "\"443\"", "\n", "}", "\n", "return", "Address", "{", "Original", ":", "input", ",", "Scheme", ":", "u", ".", "Scheme", ",", "Host", ":", "host", ",", "Port", ":", "port", ",", "Path", ":", "u", ".", "Path", "}", ",", "err", "\n", "}" ]
// standardizeAddress parses an address string into a structured format with separate // scheme, host, port, and path portions, as well as the original input string.
[ "standardizeAddress", "parses", "an", "address", "string", "into", "a", "structured", "format", "with", "separate", "scheme", "host", "port", "and", "path", "portions", "as", "well", "as", "the", "original", "input", "string", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/plugin.go#L306-L356
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/logger.go
Close
func (l *Logger) Close() error { // Will close local/remote syslog connections too :) if closer, ok := l.writer.(io.WriteCloser); ok { l.fileMu.Lock() err := closer.Close() l.fileMu.Unlock() return err } return nil }
go
func (l *Logger) Close() error { // Will close local/remote syslog connections too :) if closer, ok := l.writer.(io.WriteCloser); ok { l.fileMu.Lock() err := closer.Close() l.fileMu.Unlock() return err } return nil }
[ "func", "(", "l", "*", "Logger", ")", "Close", "(", ")", "error", "{", "if", "closer", ",", "ok", ":=", "l", ".", "writer", ".", "(", "io", ".", "WriteCloser", ")", ";", "ok", "{", "l", ".", "fileMu", ".", "Lock", "(", ")", "\n", "err", ":=", "closer", ".", "Close", "(", ")", "\n", "l", ".", "fileMu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes open log files or connections to syslog.
[ "Close", "closes", "open", "log", "files", "or", "connections", "to", "syslog", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/logger.go#L138-L148
train
inverse-inc/packetfence
go/coredns/core/dnsserver/address.go
Transport
func Transport(s string) string { switch { case strings.HasPrefix(s, TransportTLS+"://"): return TransportTLS case strings.HasPrefix(s, TransportDNS+"://"): return TransportDNS case strings.HasPrefix(s, TransportGRPC+"://"): return TransportGRPC } return TransportDNS }
go
func Transport(s string) string { switch { case strings.HasPrefix(s, TransportTLS+"://"): return TransportTLS case strings.HasPrefix(s, TransportDNS+"://"): return TransportDNS case strings.HasPrefix(s, TransportGRPC+"://"): return TransportGRPC } return TransportDNS }
[ "func", "Transport", "(", "s", "string", ")", "string", "{", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "s", ",", "TransportTLS", "+", "\"://\"", ")", ":", "return", "TransportTLS", "\n", "case", "strings", ".", "HasPrefix", "(", "s", ",", "TransportDNS", "+", "\"://\"", ")", ":", "return", "TransportDNS", "\n", "case", "strings", ".", "HasPrefix", "(", "s", ",", "TransportGRPC", "+", "\"://\"", ")", ":", "return", "TransportGRPC", "\n", "}", "\n", "return", "TransportDNS", "\n", "}" ]
// Transport returns the protocol of the string s
[ "Transport", "returns", "the", "protocol", "of", "the", "string", "s" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/address.go#L23-L33
train
inverse-inc/packetfence
go/coredns/core/dnsserver/address.go
normalizeZone
func normalizeZone(str string) (zoneAddr, error) { var err error // Default to DNS if there isn't a transport protocol prefix. trans := TransportDNS switch { case strings.HasPrefix(str, TransportTLS+"://"): trans = TransportTLS str = str[len(TransportTLS+"://"):] case strings.HasPrefix(str, TransportDNS+"://"): trans = TransportDNS str = str[len(TransportDNS+"://"):] case strings.HasPrefix(str, TransportGRPC+"://"): trans = TransportGRPC str = str[len(TransportGRPC+"://"):] } host, port, ipnet, err := plugin.SplitHostPort(str) if err != nil { return zoneAddr{}, err } if port == "" { if trans == TransportDNS { port = Port } if trans == TransportTLS { port = TLSPort } if trans == TransportGRPC { port = GRPCPort } } return zoneAddr{Zone: dns.Fqdn(host), Port: port, Transport: trans, IPNet: ipnet}, nil }
go
func normalizeZone(str string) (zoneAddr, error) { var err error // Default to DNS if there isn't a transport protocol prefix. trans := TransportDNS switch { case strings.HasPrefix(str, TransportTLS+"://"): trans = TransportTLS str = str[len(TransportTLS+"://"):] case strings.HasPrefix(str, TransportDNS+"://"): trans = TransportDNS str = str[len(TransportDNS+"://"):] case strings.HasPrefix(str, TransportGRPC+"://"): trans = TransportGRPC str = str[len(TransportGRPC+"://"):] } host, port, ipnet, err := plugin.SplitHostPort(str) if err != nil { return zoneAddr{}, err } if port == "" { if trans == TransportDNS { port = Port } if trans == TransportTLS { port = TLSPort } if trans == TransportGRPC { port = GRPCPort } } return zoneAddr{Zone: dns.Fqdn(host), Port: port, Transport: trans, IPNet: ipnet}, nil }
[ "func", "normalizeZone", "(", "str", "string", ")", "(", "zoneAddr", ",", "error", ")", "{", "var", "err", "error", "\n", "trans", ":=", "TransportDNS", "\n", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "str", ",", "TransportTLS", "+", "\"://\"", ")", ":", "trans", "=", "TransportTLS", "\n", "str", "=", "str", "[", "len", "(", "TransportTLS", "+", "\"://\"", ")", ":", "]", "\n", "case", "strings", ".", "HasPrefix", "(", "str", ",", "TransportDNS", "+", "\"://\"", ")", ":", "trans", "=", "TransportDNS", "\n", "str", "=", "str", "[", "len", "(", "TransportDNS", "+", "\"://\"", ")", ":", "]", "\n", "case", "strings", ".", "HasPrefix", "(", "str", ",", "TransportGRPC", "+", "\"://\"", ")", ":", "trans", "=", "TransportGRPC", "\n", "str", "=", "str", "[", "len", "(", "TransportGRPC", "+", "\"://\"", ")", ":", "]", "\n", "}", "\n", "host", ",", "port", ",", "ipnet", ",", "err", ":=", "plugin", ".", "SplitHostPort", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "zoneAddr", "{", "}", ",", "err", "\n", "}", "\n", "if", "port", "==", "\"\"", "{", "if", "trans", "==", "TransportDNS", "{", "port", "=", "Port", "\n", "}", "\n", "if", "trans", "==", "TransportTLS", "{", "port", "=", "TLSPort", "\n", "}", "\n", "if", "trans", "==", "TransportGRPC", "{", "port", "=", "GRPCPort", "\n", "}", "\n", "}", "\n", "return", "zoneAddr", "{", "Zone", ":", "dns", ".", "Fqdn", "(", "host", ")", ",", "Port", ":", "port", ",", "Transport", ":", "trans", ",", "IPNet", ":", "ipnet", "}", ",", "nil", "\n", "}" ]
// normalizeZone parses an zone string into a structured format with separate // host, and port portions, as well as the original input string.
[ "normalizeZone", "parses", "an", "zone", "string", "into", "a", "structured", "format", "with", "separate", "host", "and", "port", "portions", "as", "well", "as", "the", "original", "input", "string", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/address.go#L37-L73
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/proxy/reverseproxy.go
cloneTLSClientConfig
func cloneTLSClientConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return &tls.Config{ Rand: cfg.Rand, Time: cfg.Time, Certificates: cfg.Certificates, NameToCertificate: cfg.NameToCertificate, GetCertificate: cfg.GetCertificate, RootCAs: cfg.RootCAs, NextProtos: cfg.NextProtos, ServerName: cfg.ServerName, ClientAuth: cfg.ClientAuth, ClientCAs: cfg.ClientCAs, InsecureSkipVerify: cfg.InsecureSkipVerify, CipherSuites: cfg.CipherSuites, PreferServerCipherSuites: cfg.PreferServerCipherSuites, ClientSessionCache: cfg.ClientSessionCache, MinVersion: cfg.MinVersion, MaxVersion: cfg.MaxVersion, CurvePreferences: cfg.CurvePreferences, DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled, Renegotiation: cfg.Renegotiation, } }
go
func cloneTLSClientConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return &tls.Config{ Rand: cfg.Rand, Time: cfg.Time, Certificates: cfg.Certificates, NameToCertificate: cfg.NameToCertificate, GetCertificate: cfg.GetCertificate, RootCAs: cfg.RootCAs, NextProtos: cfg.NextProtos, ServerName: cfg.ServerName, ClientAuth: cfg.ClientAuth, ClientCAs: cfg.ClientCAs, InsecureSkipVerify: cfg.InsecureSkipVerify, CipherSuites: cfg.CipherSuites, PreferServerCipherSuites: cfg.PreferServerCipherSuites, ClientSessionCache: cfg.ClientSessionCache, MinVersion: cfg.MinVersion, MaxVersion: cfg.MaxVersion, CurvePreferences: cfg.CurvePreferences, DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled, Renegotiation: cfg.Renegotiation, } }
[ "func", "cloneTLSClientConfig", "(", "cfg", "*", "tls", ".", "Config", ")", "*", "tls", ".", "Config", "{", "if", "cfg", "==", "nil", "{", "return", "&", "tls", ".", "Config", "{", "}", "\n", "}", "\n", "return", "&", "tls", ".", "Config", "{", "Rand", ":", "cfg", ".", "Rand", ",", "Time", ":", "cfg", ".", "Time", ",", "Certificates", ":", "cfg", ".", "Certificates", ",", "NameToCertificate", ":", "cfg", ".", "NameToCertificate", ",", "GetCertificate", ":", "cfg", ".", "GetCertificate", ",", "RootCAs", ":", "cfg", ".", "RootCAs", ",", "NextProtos", ":", "cfg", ".", "NextProtos", ",", "ServerName", ":", "cfg", ".", "ServerName", ",", "ClientAuth", ":", "cfg", ".", "ClientAuth", ",", "ClientCAs", ":", "cfg", ".", "ClientCAs", ",", "InsecureSkipVerify", ":", "cfg", ".", "InsecureSkipVerify", ",", "CipherSuites", ":", "cfg", ".", "CipherSuites", ",", "PreferServerCipherSuites", ":", "cfg", ".", "PreferServerCipherSuites", ",", "ClientSessionCache", ":", "cfg", ".", "ClientSessionCache", ",", "MinVersion", ":", "cfg", ".", "MinVersion", ",", "MaxVersion", ":", "cfg", ".", "MaxVersion", ",", "CurvePreferences", ":", "cfg", ".", "CurvePreferences", ",", "DynamicRecordSizingDisabled", ":", "cfg", ".", "DynamicRecordSizingDisabled", ",", "Renegotiation", ":", "cfg", ".", "Renegotiation", ",", "}", "\n", "}" ]
// cloneTLSClientConfig is like cloneTLSConfig but omits // the fields SessionTicketsDisabled and SessionTicketKey. // This makes it safe to call cloneTLSClientConfig on a config // in active use by a server.
[ "cloneTLSClientConfig", "is", "like", "cloneTLSConfig", "but", "omits", "the", "fields", "SessionTicketsDisabled", "and", "SessionTicketKey", ".", "This", "makes", "it", "safe", "to", "call", "cloneTLSClientConfig", "on", "a", "config", "in", "active", "use", "by", "a", "server", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/proxy/reverseproxy.go#L555-L580
train
inverse-inc/packetfence
go/coredns/plugin/auto/walk.go
matches
func matches(re *regexp.Regexp, filename, template string) (match bool, origin string) { base := path.Base(filename) matches := re.FindStringSubmatchIndex(base) if matches == nil { return false, "" } by := re.ExpandString(nil, template, base, matches) if by == nil { return false, "" } origin = dns.Fqdn(string(by)) return true, origin }
go
func matches(re *regexp.Regexp, filename, template string) (match bool, origin string) { base := path.Base(filename) matches := re.FindStringSubmatchIndex(base) if matches == nil { return false, "" } by := re.ExpandString(nil, template, base, matches) if by == nil { return false, "" } origin = dns.Fqdn(string(by)) return true, origin }
[ "func", "matches", "(", "re", "*", "regexp", ".", "Regexp", ",", "filename", ",", "template", "string", ")", "(", "match", "bool", ",", "origin", "string", ")", "{", "base", ":=", "path", ".", "Base", "(", "filename", ")", "\n", "matches", ":=", "re", ".", "FindStringSubmatchIndex", "(", "base", ")", "\n", "if", "matches", "==", "nil", "{", "return", "false", ",", "\"\"", "\n", "}", "\n", "by", ":=", "re", ".", "ExpandString", "(", "nil", ",", "template", ",", "base", ",", "matches", ")", "\n", "if", "by", "==", "nil", "{", "return", "false", ",", "\"\"", "\n", "}", "\n", "origin", "=", "dns", ".", "Fqdn", "(", "string", "(", "by", ")", ")", "\n", "return", "true", ",", "origin", "\n", "}" ]
// matches matches re to filename, if is is a match, the subexpression will be used to expand // template to an origin. When match is true that origin is returned. Origin is fully qualified.
[ "matches", "matches", "re", "to", "filename", "if", "is", "is", "a", "match", "the", "subexpression", "will", "be", "used", "to", "expand", "template", "to", "an", "origin", ".", "When", "match", "is", "true", "that", "origin", "is", "returned", ".", "Origin", "is", "fully", "qualified", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/auto/walk.go#L93-L109
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/graceful.go
Accept
func (gl *gracefulListener) Accept() (c net.Conn, err error) { c, err = gl.Listener.Accept() if err != nil { return } c = gracefulConn{Conn: c, connWg: gl.connWg} gl.connWg.Add(1) return }
go
func (gl *gracefulListener) Accept() (c net.Conn, err error) { c, err = gl.Listener.Accept() if err != nil { return } c = gracefulConn{Conn: c, connWg: gl.connWg} gl.connWg.Add(1) return }
[ "func", "(", "gl", "*", "gracefulListener", ")", "Accept", "(", ")", "(", "c", "net", ".", "Conn", ",", "err", "error", ")", "{", "c", ",", "err", "=", "gl", ".", "Listener", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "c", "=", "gracefulConn", "{", "Conn", ":", "c", ",", "connWg", ":", "gl", ".", "connWg", "}", "\n", "gl", ".", "connWg", ".", "Add", "(", "1", ")", "\n", "return", "\n", "}" ]
// Accept accepts a connection.
[ "Accept", "accepts", "a", "connection", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/graceful.go#L39-L47
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/graceful.go
Close
func (gl *gracefulListener) Close() error { gl.Lock() if gl.stopped { gl.Unlock() return syscall.EINVAL } gl.Unlock() gl.stop <- nil return <-gl.stop }
go
func (gl *gracefulListener) Close() error { gl.Lock() if gl.stopped { gl.Unlock() return syscall.EINVAL } gl.Unlock() gl.stop <- nil return <-gl.stop }
[ "func", "(", "gl", "*", "gracefulListener", ")", "Close", "(", ")", "error", "{", "gl", ".", "Lock", "(", ")", "\n", "if", "gl", ".", "stopped", "{", "gl", ".", "Unlock", "(", ")", "\n", "return", "syscall", ".", "EINVAL", "\n", "}", "\n", "gl", ".", "Unlock", "(", ")", "\n", "gl", ".", "stop", "<-", "nil", "\n", "return", "<-", "gl", ".", "stop", "\n", "}" ]
// Close immediately closes the listener.
[ "Close", "immediately", "closes", "the", "listener", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/graceful.go#L50-L59
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/graceful.go
Close
func (c gracefulConn) Close() error { err := c.Conn.Close() if err != nil { return err } // close can fail on http2 connections (as of Oct. 2015, before http2 in std lib) // so don't decrement count unless close succeeds c.connWg.Done() return nil }
go
func (c gracefulConn) Close() error { err := c.Conn.Close() if err != nil { return err } // close can fail on http2 connections (as of Oct. 2015, before http2 in std lib) // so don't decrement count unless close succeeds c.connWg.Done() return nil }
[ "func", "(", "c", "gracefulConn", ")", "Close", "(", ")", "error", "{", "err", ":=", "c", ".", "Conn", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "connWg", ".", "Done", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Close closes c's underlying connection while updating the wg count.
[ "Close", "closes", "c", "s", "underlying", "connection", "while", "updating", "the", "wg", "count", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/graceful.go#L71-L80
train
inverse-inc/packetfence
go/caddy/caddy/controller.go
OnRestart
func (c *Controller) OnRestart(fn func() error) { c.instance.onRestart = append(c.instance.onRestart, fn) }
go
func (c *Controller) OnRestart(fn func() error) { c.instance.onRestart = append(c.instance.onRestart, fn) }
[ "func", "(", "c", "*", "Controller", ")", "OnRestart", "(", "fn", "func", "(", ")", "error", ")", "{", "c", ".", "instance", ".", "onRestart", "=", "append", "(", "c", ".", "instance", ".", "onRestart", ",", "fn", ")", "\n", "}" ]
// OnRestart adds fn to the list of callback functions to execute // when the server is about to be restarted.
[ "OnRestart", "adds", "fn", "to", "the", "list", "of", "callback", "functions", "to", "execute", "when", "the", "server", "is", "about", "to", "be", "restarted", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/controller.go#L71-L73
train
inverse-inc/packetfence
go/caddy/caddy/controller.go
OnFinalShutdown
func (c *Controller) OnFinalShutdown(fn func() error) { c.instance.onFinalShutdown = append(c.instance.onFinalShutdown, fn) }
go
func (c *Controller) OnFinalShutdown(fn func() error) { c.instance.onFinalShutdown = append(c.instance.onFinalShutdown, fn) }
[ "func", "(", "c", "*", "Controller", ")", "OnFinalShutdown", "(", "fn", "func", "(", ")", "error", ")", "{", "c", ".", "instance", ".", "onFinalShutdown", "=", "append", "(", "c", ".", "instance", ".", "onFinalShutdown", ",", "fn", ")", "\n", "}" ]
// OnFinalShutdown adds fn to the list of callback functions to execute // when the server is about to be shut down NOT as part of a restart.
[ "OnFinalShutdown", "adds", "fn", "to", "the", "list", "of", "callback", "functions", "to", "execute", "when", "the", "server", "is", "about", "to", "be", "shut", "down", "NOT", "as", "part", "of", "a", "restart", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/controller.go#L83-L85
train
inverse-inc/packetfence
go/coredns/plugin/hosts/hostsfile.go
parse
func (h *Hostsfile) parse(r io.Reader, override *hostsMap) *hostsMap { hmap := newHostsMap() scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Bytes() if i := bytes.Index(line, []byte{'#'}); i >= 0 { // Discard comments. line = line[0:i] } f := bytes.Fields(line) if len(f) < 2 { continue } addr := parseLiteralIP(string(f[0])) if addr == nil { continue } ver := ipVersion(string(f[0])) for i := 1; i < len(f); i++ { name := absDomainName(string(f[i])) if plugin.Zones(h.Origins).Matches(name) == "" { // name is not in Origins continue } switch ver { case 4: hmap.byNameV4[name] = append(hmap.byNameV4[name], addr) case 6: hmap.byNameV6[name] = append(hmap.byNameV6[name], addr) default: continue } hmap.byAddr[addr.String()] = append(hmap.byAddr[addr.String()], name) } } if override == nil { return hmap } for name := range override.byNameV4 { hmap.byNameV4[name] = append(hmap.byNameV4[name], override.byNameV4[name]...) } for name := range override.byNameV4 { hmap.byNameV6[name] = append(hmap.byNameV6[name], override.byNameV6[name]...) } for addr := range override.byAddr { hmap.byAddr[addr] = append(hmap.byAddr[addr], override.byAddr[addr]...) } return hmap }
go
func (h *Hostsfile) parse(r io.Reader, override *hostsMap) *hostsMap { hmap := newHostsMap() scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Bytes() if i := bytes.Index(line, []byte{'#'}); i >= 0 { // Discard comments. line = line[0:i] } f := bytes.Fields(line) if len(f) < 2 { continue } addr := parseLiteralIP(string(f[0])) if addr == nil { continue } ver := ipVersion(string(f[0])) for i := 1; i < len(f); i++ { name := absDomainName(string(f[i])) if plugin.Zones(h.Origins).Matches(name) == "" { // name is not in Origins continue } switch ver { case 4: hmap.byNameV4[name] = append(hmap.byNameV4[name], addr) case 6: hmap.byNameV6[name] = append(hmap.byNameV6[name], addr) default: continue } hmap.byAddr[addr.String()] = append(hmap.byAddr[addr.String()], name) } } if override == nil { return hmap } for name := range override.byNameV4 { hmap.byNameV4[name] = append(hmap.byNameV4[name], override.byNameV4[name]...) } for name := range override.byNameV4 { hmap.byNameV6[name] = append(hmap.byNameV6[name], override.byNameV6[name]...) } for addr := range override.byAddr { hmap.byAddr[addr] = append(hmap.byAddr[addr], override.byAddr[addr]...) } return hmap }
[ "func", "(", "h", "*", "Hostsfile", ")", "parse", "(", "r", "io", ".", "Reader", ",", "override", "*", "hostsMap", ")", "*", "hostsMap", "{", "hmap", ":=", "newHostsMap", "(", ")", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", ":=", "scanner", ".", "Bytes", "(", ")", "\n", "if", "i", ":=", "bytes", ".", "Index", "(", "line", ",", "[", "]", "byte", "{", "'#'", "}", ")", ";", "i", ">=", "0", "{", "line", "=", "line", "[", "0", ":", "i", "]", "\n", "}", "\n", "f", ":=", "bytes", ".", "Fields", "(", "line", ")", "\n", "if", "len", "(", "f", ")", "<", "2", "{", "continue", "\n", "}", "\n", "addr", ":=", "parseLiteralIP", "(", "string", "(", "f", "[", "0", "]", ")", ")", "\n", "if", "addr", "==", "nil", "{", "continue", "\n", "}", "\n", "ver", ":=", "ipVersion", "(", "string", "(", "f", "[", "0", "]", ")", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "f", ")", ";", "i", "++", "{", "name", ":=", "absDomainName", "(", "string", "(", "f", "[", "i", "]", ")", ")", "\n", "if", "plugin", ".", "Zones", "(", "h", ".", "Origins", ")", ".", "Matches", "(", "name", ")", "==", "\"\"", "{", "continue", "\n", "}", "\n", "switch", "ver", "{", "case", "4", ":", "hmap", ".", "byNameV4", "[", "name", "]", "=", "append", "(", "hmap", ".", "byNameV4", "[", "name", "]", ",", "addr", ")", "\n", "case", "6", ":", "hmap", ".", "byNameV6", "[", "name", "]", "=", "append", "(", "hmap", ".", "byNameV6", "[", "name", "]", ",", "addr", ")", "\n", "default", ":", "continue", "\n", "}", "\n", "hmap", ".", "byAddr", "[", "addr", ".", "String", "(", ")", "]", "=", "append", "(", "hmap", ".", "byAddr", "[", "addr", ".", "String", "(", ")", "]", ",", "name", ")", "\n", "}", "\n", "}", "\n", "if", "override", "==", "nil", "{", "return", "hmap", "\n", "}", "\n", "for", "name", ":=", "range", "override", ".", "byNameV4", "{", "hmap", ".", "byNameV4", "[", "name", "]", "=", "append", "(", "hmap", ".", "byNameV4", "[", "name", "]", ",", "override", ".", "byNameV4", "[", "name", "]", "...", ")", "\n", "}", "\n", "for", "name", ":=", "range", "override", ".", "byNameV4", "{", "hmap", ".", "byNameV6", "[", "name", "]", "=", "append", "(", "hmap", ".", "byNameV6", "[", "name", "]", ",", "override", ".", "byNameV6", "[", "name", "]", "...", ")", "\n", "}", "\n", "for", "addr", ":=", "range", "override", ".", "byAddr", "{", "hmap", ".", "byAddr", "[", "addr", "]", "=", "append", "(", "hmap", ".", "byAddr", "[", "addr", "]", ",", "override", ".", "byAddr", "[", "addr", "]", "...", ")", "\n", "}", "\n", "return", "hmap", "\n", "}" ]
// Parse reads the hostsfile and populates the byName and byAddr maps.
[ "Parse", "reads", "the", "hostsfile", "and", "populates", "the", "byName", "and", "byAddr", "maps", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/hosts/hostsfile.go#L117-L169
train
inverse-inc/packetfence
go/coredns/plugin/hosts/hostsfile.go
LookupStaticAddr
func (h *Hostsfile) LookupStaticAddr(addr string) []string { h.RLock() defer h.RUnlock() addr = parseLiteralIP(addr).String() if addr == "" { return nil } if len(h.hmap.byAddr) != 0 { if hosts, ok := h.hmap.byAddr[addr]; ok { hostsCp := make([]string, len(hosts)) copy(hostsCp, hosts) return hostsCp } } return nil }
go
func (h *Hostsfile) LookupStaticAddr(addr string) []string { h.RLock() defer h.RUnlock() addr = parseLiteralIP(addr).String() if addr == "" { return nil } if len(h.hmap.byAddr) != 0 { if hosts, ok := h.hmap.byAddr[addr]; ok { hostsCp := make([]string, len(hosts)) copy(hostsCp, hosts) return hostsCp } } return nil }
[ "func", "(", "h", "*", "Hostsfile", ")", "LookupStaticAddr", "(", "addr", "string", ")", "[", "]", "string", "{", "h", ".", "RLock", "(", ")", "\n", "defer", "h", ".", "RUnlock", "(", ")", "\n", "addr", "=", "parseLiteralIP", "(", "addr", ")", ".", "String", "(", ")", "\n", "if", "addr", "==", "\"\"", "{", "return", "nil", "\n", "}", "\n", "if", "len", "(", "h", ".", "hmap", ".", "byAddr", ")", "!=", "0", "{", "if", "hosts", ",", "ok", ":=", "h", ".", "hmap", ".", "byAddr", "[", "addr", "]", ";", "ok", "{", "hostsCp", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "hosts", ")", ")", "\n", "copy", "(", "hostsCp", ",", "hosts", ")", "\n", "return", "hostsCp", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LookupStaticAddr looks up the hosts for the given address from the hosts file.
[ "LookupStaticAddr", "looks", "up", "the", "hosts", "for", "the", "given", "address", "from", "the", "hosts", "file", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/hosts/hostsfile.go#L213-L228
train
inverse-inc/packetfence
go/coredns/plugin/cache/cache.go
key
func key(m *dns.Msg, t response.Type, do bool) int { // We don't store truncated responses. if m.Truncated { return -1 } // Nor errors or Meta or Update if t == response.OtherError || t == response.Meta || t == response.Update { return -1 } return int(hash(m.Question[0].Name, m.Question[0].Qtype, do)) }
go
func key(m *dns.Msg, t response.Type, do bool) int { // We don't store truncated responses. if m.Truncated { return -1 } // Nor errors or Meta or Update if t == response.OtherError || t == response.Meta || t == response.Update { return -1 } return int(hash(m.Question[0].Name, m.Question[0].Qtype, do)) }
[ "func", "key", "(", "m", "*", "dns", ".", "Msg", ",", "t", "response", ".", "Type", ",", "do", "bool", ")", "int", "{", "if", "m", ".", "Truncated", "{", "return", "-", "1", "\n", "}", "\n", "if", "t", "==", "response", ".", "OtherError", "||", "t", "==", "response", ".", "Meta", "||", "t", "==", "response", ".", "Update", "{", "return", "-", "1", "\n", "}", "\n", "return", "int", "(", "hash", "(", "m", ".", "Question", "[", "0", "]", ".", "Name", ",", "m", ".", "Question", "[", "0", "]", ".", "Qtype", ",", "do", ")", ")", "\n", "}" ]
// Return key under which we store the item, -1 will be returned if we don't store the // message. // Currently we do not cache Truncated, errors zone transfers or dynamic update messages.
[ "Return", "key", "under", "which", "we", "store", "the", "item", "-", "1", "will", "be", "returned", "if", "we", "don", "t", "store", "the", "message", ".", "Currently", "we", "do", "not", "cache", "Truncated", "errors", "zone", "transfers", "or", "dynamic", "update", "messages", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/cache/cache.go#L40-L51
train
inverse-inc/packetfence
go/caddy/caddy/startupshutdown/startupshutdown.go
registerCallback
func registerCallback(c *caddy.Controller, registerFunc func(func() error)) error { var funcs []func() error for c.Next() { args := c.RemainingArgs() if len(args) == 0 { return c.ArgErr() } nonblock := false if len(args) > 1 && args[len(args)-1] == "&" { // Run command in background; non-blocking nonblock = true args = args[:len(args)-1] } command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " ")) if err != nil { return c.Err(err.Error()) } fn := func() error { cmd := exec.Command(command, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if nonblock { log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " ")) return cmd.Start() } log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " ")) return cmd.Run() } funcs = append(funcs, fn) } return c.OncePerServerBlock(func() error { for _, fn := range funcs { registerFunc(fn) } return nil }) }
go
func registerCallback(c *caddy.Controller, registerFunc func(func() error)) error { var funcs []func() error for c.Next() { args := c.RemainingArgs() if len(args) == 0 { return c.ArgErr() } nonblock := false if len(args) > 1 && args[len(args)-1] == "&" { // Run command in background; non-blocking nonblock = true args = args[:len(args)-1] } command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " ")) if err != nil { return c.Err(err.Error()) } fn := func() error { cmd := exec.Command(command, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if nonblock { log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " ")) return cmd.Start() } log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " ")) return cmd.Run() } funcs = append(funcs, fn) } return c.OncePerServerBlock(func() error { for _, fn := range funcs { registerFunc(fn) } return nil }) }
[ "func", "registerCallback", "(", "c", "*", "caddy", ".", "Controller", ",", "registerFunc", "func", "(", "func", "(", ")", "error", ")", ")", "error", "{", "var", "funcs", "[", "]", "func", "(", ")", "error", "\n", "for", "c", ".", "Next", "(", ")", "{", "args", ":=", "c", ".", "RemainingArgs", "(", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "return", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "nonblock", ":=", "false", "\n", "if", "len", "(", "args", ")", ">", "1", "&&", "args", "[", "len", "(", "args", ")", "-", "1", "]", "==", "\"&\"", "{", "nonblock", "=", "true", "\n", "args", "=", "args", "[", ":", "len", "(", "args", ")", "-", "1", "]", "\n", "}", "\n", "command", ",", "args", ",", "err", ":=", "caddy", ".", "SplitCommandAndArgs", "(", "strings", ".", "Join", "(", "args", ",", "\" \"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "c", ".", "Err", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "fn", ":=", "func", "(", ")", "error", "{", "cmd", ":=", "exec", ".", "Command", "(", "command", ",", "args", "...", ")", "\n", "cmd", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "if", "nonblock", "{", "log", ".", "Printf", "(", "\"[INFO] Nonblocking Command:\\\"%s %s\\\"\"", ",", "\\\"", ",", "\\\"", ")", "\n", "command", "\n", "}", "\n", "strings", ".", "Join", "(", "args", ",", "\" \"", ")", "\n", "return", "cmd", ".", "Start", "(", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"[INFO] Blocking Command:\\\"%s %s\\\"\"", ",", "\\\"", ",", "\\\"", ")", "\n", "}", "\n", "command", "\n", "}" ]
// registerCallback registers a callback function to execute by // using c to parse the directive. It registers the callback // to be executed using registerFunc.
[ "registerCallback", "registers", "a", "callback", "function", "to", "execute", "by", "using", "c", "to", "parse", "the", "directive", ".", "It", "registers", "the", "callback", "to", "be", "executed", "using", "registerFunc", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/startupshutdown/startupshutdown.go#L30-L73
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/msg.go
AddrMsg
func (b *Builder) AddrMsg(a net.Addr, m *dns.Msg) (err error) { err = b.RemoteAddr(a) if err != nil { return } return b.Msg(m) }
go
func (b *Builder) AddrMsg(a net.Addr, m *dns.Msg) (err error) { err = b.RemoteAddr(a) if err != nil { return } return b.Msg(m) }
[ "func", "(", "b", "*", "Builder", ")", "AddrMsg", "(", "a", "net", ".", "Addr", ",", "m", "*", "dns", ".", "Msg", ")", "(", "err", "error", ")", "{", "err", "=", "b", ".", "RemoteAddr", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "b", ".", "Msg", "(", "m", ")", "\n", "}" ]
// AddrMsg parses the info of net.Addr and dns.Msg.
[ "AddrMsg", "parses", "the", "info", "of", "net", ".", "Addr", "and", "dns", ".", "Msg", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L20-L26
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/msg.go
Msg
func (b *Builder) Msg(m *dns.Msg) (err error) { if b.Full { err = b.Pack(m) } return }
go
func (b *Builder) Msg(m *dns.Msg) (err error) { if b.Full { err = b.Pack(m) } return }
[ "func", "(", "b", "*", "Builder", ")", "Msg", "(", "m", "*", "dns", ".", "Msg", ")", "(", "err", "error", ")", "{", "if", "b", ".", "Full", "{", "err", "=", "b", ".", "Pack", "(", "m", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Msg parses the info of dns.Msg.
[ "Msg", "parses", "the", "info", "of", "dns", ".", "Msg", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L29-L34
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/msg.go
HostPort
func (d *Data) HostPort(addr string) error { ip, port, err := net.SplitHostPort(addr) if err != nil { return err } p, err := strconv.ParseUint(port, 10, 32) if err != nil { return err } d.Port = uint32(p) if ip := net.ParseIP(ip); ip != nil { d.Address = []byte(ip) if ip := ip.To4(); ip != nil { d.SocketFam = tap.SocketFamily_INET } else { d.SocketFam = tap.SocketFamily_INET6 } return nil } return errors.New("not an ip address") }
go
func (d *Data) HostPort(addr string) error { ip, port, err := net.SplitHostPort(addr) if err != nil { return err } p, err := strconv.ParseUint(port, 10, 32) if err != nil { return err } d.Port = uint32(p) if ip := net.ParseIP(ip); ip != nil { d.Address = []byte(ip) if ip := ip.To4(); ip != nil { d.SocketFam = tap.SocketFamily_INET } else { d.SocketFam = tap.SocketFamily_INET6 } return nil } return errors.New("not an ip address") }
[ "func", "(", "d", "*", "Data", ")", "HostPort", "(", "addr", "string", ")", "error", "{", "ip", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "port", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "Port", "=", "uint32", "(", "p", ")", "\n", "if", "ip", ":=", "net", ".", "ParseIP", "(", "ip", ")", ";", "ip", "!=", "nil", "{", "d", ".", "Address", "=", "[", "]", "byte", "(", "ip", ")", "\n", "if", "ip", ":=", "ip", ".", "To4", "(", ")", ";", "ip", "!=", "nil", "{", "d", ".", "SocketFam", "=", "tap", ".", "SocketFamily_INET", "\n", "}", "else", "{", "d", ".", "SocketFam", "=", "tap", ".", "SocketFamily_INET6", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"not an ip address\"", ")", "\n", "}" ]
// HostPort decodes into Data any string returned by dnsutil.ParseHostPortOrFile.
[ "HostPort", "decodes", "into", "Data", "any", "string", "returned", "by", "dnsutil", ".", "ParseHostPortOrFile", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L48-L69
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/msg.go
RemoteAddr
func (d *Data) RemoteAddr(remote net.Addr) error { switch addr := remote.(type) { case *net.TCPAddr: d.Address = addr.IP d.Port = uint32(addr.Port) d.SocketProto = tap.SocketProtocol_TCP case *net.UDPAddr: d.Address = addr.IP d.Port = uint32(addr.Port) d.SocketProto = tap.SocketProtocol_UDP default: return errors.New("unknown remote address type") } if a := net.IP(d.Address); a.To4() != nil { d.SocketFam = tap.SocketFamily_INET } else { d.SocketFam = tap.SocketFamily_INET6 } return nil }
go
func (d *Data) RemoteAddr(remote net.Addr) error { switch addr := remote.(type) { case *net.TCPAddr: d.Address = addr.IP d.Port = uint32(addr.Port) d.SocketProto = tap.SocketProtocol_TCP case *net.UDPAddr: d.Address = addr.IP d.Port = uint32(addr.Port) d.SocketProto = tap.SocketProtocol_UDP default: return errors.New("unknown remote address type") } if a := net.IP(d.Address); a.To4() != nil { d.SocketFam = tap.SocketFamily_INET } else { d.SocketFam = tap.SocketFamily_INET6 } return nil }
[ "func", "(", "d", "*", "Data", ")", "RemoteAddr", "(", "remote", "net", ".", "Addr", ")", "error", "{", "switch", "addr", ":=", "remote", ".", "(", "type", ")", "{", "case", "*", "net", ".", "TCPAddr", ":", "d", ".", "Address", "=", "addr", ".", "IP", "\n", "d", ".", "Port", "=", "uint32", "(", "addr", ".", "Port", ")", "\n", "d", ".", "SocketProto", "=", "tap", ".", "SocketProtocol_TCP", "\n", "case", "*", "net", ".", "UDPAddr", ":", "d", ".", "Address", "=", "addr", ".", "IP", "\n", "d", ".", "Port", "=", "uint32", "(", "addr", ".", "Port", ")", "\n", "d", ".", "SocketProto", "=", "tap", ".", "SocketProtocol_UDP", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"unknown remote address type\"", ")", "\n", "}", "\n", "if", "a", ":=", "net", ".", "IP", "(", "d", ".", "Address", ")", ";", "a", ".", "To4", "(", ")", "!=", "nil", "{", "d", ".", "SocketFam", "=", "tap", ".", "SocketFamily_INET", "\n", "}", "else", "{", "d", ".", "SocketFam", "=", "tap", ".", "SocketFamily_INET6", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoteAddr parses the information about the remote address into Data.
[ "RemoteAddr", "parses", "the", "information", "about", "the", "remote", "address", "into", "Data", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L72-L93
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/msg.go
Pack
func (d *Data) Pack(m *dns.Msg) error { packed, err := m.Pack() if err != nil { return err } d.Packed = packed return nil }
go
func (d *Data) Pack(m *dns.Msg) error { packed, err := m.Pack() if err != nil { return err } d.Packed = packed return nil }
[ "func", "(", "d", "*", "Data", ")", "Pack", "(", "m", "*", "dns", ".", "Msg", ")", "error", "{", "packed", ",", "err", ":=", "m", ".", "Pack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "Packed", "=", "packed", "\n", "return", "nil", "\n", "}" ]
// Pack encodes the DNS message into Data.
[ "Pack", "encodes", "the", "DNS", "message", "into", "Data", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/msg.go#L96-L103
train
inverse-inc/packetfence
go/coredns/plugin/proxy/google.go
newUpstream
func newUpstream(hosts []string, old *staticUpstream) Upstream { upstream := &staticUpstream{ from: old.from, HealthCheck: healthcheck.HealthCheck{ FailTimeout: 5 * time.Second, MaxFails: 3, }, ex: old.ex, IgnoredSubDomains: old.IgnoredSubDomains, } upstream.Hosts = make([]*healthcheck.UpstreamHost, len(hosts)) for i, host := range hosts { uh := &healthcheck.UpstreamHost{ Name: host, Conns: 0, Fails: 0, FailTimeout: upstream.FailTimeout, CheckDown: checkDownFunc(upstream), } upstream.Hosts[i] = uh } return upstream }
go
func newUpstream(hosts []string, old *staticUpstream) Upstream { upstream := &staticUpstream{ from: old.from, HealthCheck: healthcheck.HealthCheck{ FailTimeout: 5 * time.Second, MaxFails: 3, }, ex: old.ex, IgnoredSubDomains: old.IgnoredSubDomains, } upstream.Hosts = make([]*healthcheck.UpstreamHost, len(hosts)) for i, host := range hosts { uh := &healthcheck.UpstreamHost{ Name: host, Conns: 0, Fails: 0, FailTimeout: upstream.FailTimeout, CheckDown: checkDownFunc(upstream), } upstream.Hosts[i] = uh } return upstream }
[ "func", "newUpstream", "(", "hosts", "[", "]", "string", ",", "old", "*", "staticUpstream", ")", "Upstream", "{", "upstream", ":=", "&", "staticUpstream", "{", "from", ":", "old", ".", "from", ",", "HealthCheck", ":", "healthcheck", ".", "HealthCheck", "{", "FailTimeout", ":", "5", "*", "time", ".", "Second", ",", "MaxFails", ":", "3", ",", "}", ",", "ex", ":", "old", ".", "ex", ",", "IgnoredSubDomains", ":", "old", ".", "IgnoredSubDomains", ",", "}", "\n", "upstream", ".", "Hosts", "=", "make", "(", "[", "]", "*", "healthcheck", ".", "UpstreamHost", ",", "len", "(", "hosts", ")", ")", "\n", "for", "i", ",", "host", ":=", "range", "hosts", "{", "uh", ":=", "&", "healthcheck", ".", "UpstreamHost", "{", "Name", ":", "host", ",", "Conns", ":", "0", ",", "Fails", ":", "0", ",", "FailTimeout", ":", "upstream", ".", "FailTimeout", ",", "CheckDown", ":", "checkDownFunc", "(", "upstream", ")", ",", "}", "\n", "upstream", ".", "Hosts", "[", "i", "]", "=", "uh", "\n", "}", "\n", "return", "upstream", "\n", "}" ]
// newUpstream returns an upstream initialized with hosts.
[ "newUpstream", "returns", "an", "upstream", "initialized", "with", "hosts", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/google.go#L191-L214
train
inverse-inc/packetfence
go/caddy/caddy/caddyfile/parse.go
replaceEnvReferences
func replaceEnvReferences(s, refStart, refEnd string) string { index := strings.Index(s, refStart) for index != -1 { endIndex := strings.Index(s, refEnd) if endIndex != -1 { ref := s[index : endIndex+len(refEnd)] s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1) } else { return s } index = strings.Index(s, refStart) } return s }
go
func replaceEnvReferences(s, refStart, refEnd string) string { index := strings.Index(s, refStart) for index != -1 { endIndex := strings.Index(s, refEnd) if endIndex != -1 { ref := s[index : endIndex+len(refEnd)] s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1) } else { return s } index = strings.Index(s, refStart) } return s }
[ "func", "replaceEnvReferences", "(", "s", ",", "refStart", ",", "refEnd", "string", ")", "string", "{", "index", ":=", "strings", ".", "Index", "(", "s", ",", "refStart", ")", "\n", "for", "index", "!=", "-", "1", "{", "endIndex", ":=", "strings", ".", "Index", "(", "s", ",", "refEnd", ")", "\n", "if", "endIndex", "!=", "-", "1", "{", "ref", ":=", "s", "[", "index", ":", "endIndex", "+", "len", "(", "refEnd", ")", "]", "\n", "s", "=", "strings", ".", "Replace", "(", "s", ",", "ref", ",", "os", ".", "Getenv", "(", "ref", "[", "len", "(", "refStart", ")", ":", "len", "(", "ref", ")", "-", "len", "(", "refEnd", ")", "]", ")", ",", "-", "1", ")", "\n", "}", "else", "{", "return", "s", "\n", "}", "\n", "index", "=", "strings", ".", "Index", "(", "s", ",", "refStart", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// replaceEnvReferences performs the actual replacement of env variables // in s, given the placeholder start and placeholder end strings.
[ "replaceEnvReferences", "performs", "the", "actual", "replacement", "of", "env", "variables", "in", "s", "given", "the", "placeholder", "start", "and", "placeholder", "end", "strings", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyfile/parse.go#L396-L409
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/https.go
redirPlaintextHost
func redirPlaintextHost(cfg *SiteConfig) *SiteConfig { redirPort := cfg.Addr.Port if redirPort == "443" { // default port is redundant redirPort = "" } redirMiddleware := func(next Handler) Handler { return HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { toURL := "https://" + r.Host if redirPort != "" { toURL += ":" + redirPort } toURL += r.URL.RequestURI() w.Header().Set("Connection", "close") http.Redirect(w, r, toURL, http.StatusMovedPermanently) return 0, nil }) } host := cfg.Addr.Host port := "80" addr := net.JoinHostPort(host, port) return &SiteConfig{ Addr: Address{Original: addr, Host: host, Port: port}, ListenHost: cfg.ListenHost, middleware: []Middleware{redirMiddleware}, TLS: &caddytls.Config{AltHTTPPort: cfg.TLS.AltHTTPPort}, } }
go
func redirPlaintextHost(cfg *SiteConfig) *SiteConfig { redirPort := cfg.Addr.Port if redirPort == "443" { // default port is redundant redirPort = "" } redirMiddleware := func(next Handler) Handler { return HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { toURL := "https://" + r.Host if redirPort != "" { toURL += ":" + redirPort } toURL += r.URL.RequestURI() w.Header().Set("Connection", "close") http.Redirect(w, r, toURL, http.StatusMovedPermanently) return 0, nil }) } host := cfg.Addr.Host port := "80" addr := net.JoinHostPort(host, port) return &SiteConfig{ Addr: Address{Original: addr, Host: host, Port: port}, ListenHost: cfg.ListenHost, middleware: []Middleware{redirMiddleware}, TLS: &caddytls.Config{AltHTTPPort: cfg.TLS.AltHTTPPort}, } }
[ "func", "redirPlaintextHost", "(", "cfg", "*", "SiteConfig", ")", "*", "SiteConfig", "{", "redirPort", ":=", "cfg", ".", "Addr", ".", "Port", "\n", "if", "redirPort", "==", "\"443\"", "{", "redirPort", "=", "\"\"", "\n", "}", "\n", "redirMiddleware", ":=", "func", "(", "next", "Handler", ")", "Handler", "{", "return", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "int", ",", "error", ")", "{", "toURL", ":=", "\"https://\"", "+", "r", ".", "Host", "\n", "if", "redirPort", "!=", "\"\"", "{", "toURL", "+=", "\":\"", "+", "redirPort", "\n", "}", "\n", "toURL", "+=", "r", ".", "URL", ".", "RequestURI", "(", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Connection\"", ",", "\"close\"", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "toURL", ",", "http", ".", "StatusMovedPermanently", ")", "\n", "return", "0", ",", "nil", "\n", "}", ")", "\n", "}", "\n", "host", ":=", "cfg", ".", "Addr", ".", "Host", "\n", "port", ":=", "\"80\"", "\n", "addr", ":=", "net", ".", "JoinHostPort", "(", "host", ",", "port", ")", "\n", "return", "&", "SiteConfig", "{", "Addr", ":", "Address", "{", "Original", ":", "addr", ",", "Host", ":", "host", ",", "Port", ":", "port", "}", ",", "ListenHost", ":", "cfg", ".", "ListenHost", ",", "middleware", ":", "[", "]", "Middleware", "{", "redirMiddleware", "}", ",", "TLS", ":", "&", "caddytls", ".", "Config", "{", "AltHTTPPort", ":", "cfg", ".", "TLS", ".", "AltHTTPPort", "}", ",", "}", "\n", "}" ]
// redirPlaintextHost returns a new plaintext HTTP configuration for // a virtualHost that simply redirects to cfg, which is assumed to // be the HTTPS configuration. The returned configuration is set // to listen on port 80. The TLS field of cfg must not be nil.
[ "redirPlaintextHost", "returns", "a", "new", "plaintext", "HTTP", "configuration", "for", "a", "virtualHost", "that", "simply", "redirects", "to", "cfg", "which", "is", "assumed", "to", "be", "the", "HTTPS", "configuration", ".", "The", "returned", "configuration", "is", "set", "to", "listen", "on", "port", "80", ".", "The", "TLS", "field", "of", "cfg", "must", "not", "be", "nil", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/https.go#L139-L166
train
inverse-inc/packetfence
go/coredns/plugin/metrics/vars/report.go
Report
func Report(req request.Request, zone, rcode string, size int, start time.Time) { // Proto and Family. net := req.Proto() fam := "1" if req.Family() == 2 { fam = "2" } typ := req.QType() RequestCount.WithLabelValues(zone, net, fam).Inc() RequestDuration.WithLabelValues(zone).Observe(float64(time.Since(start) / time.Millisecond)) if req.Do() { RequestDo.WithLabelValues(zone).Inc() } if _, known := monitorType[typ]; known { RequestType.WithLabelValues(zone, dns.Type(typ).String()).Inc() } else { RequestType.WithLabelValues(zone, other).Inc() } ResponseSize.WithLabelValues(zone, net).Observe(float64(size)) RequestSize.WithLabelValues(zone, net).Observe(float64(req.Len())) ResponseRcode.WithLabelValues(zone, rcode).Inc() }
go
func Report(req request.Request, zone, rcode string, size int, start time.Time) { // Proto and Family. net := req.Proto() fam := "1" if req.Family() == 2 { fam = "2" } typ := req.QType() RequestCount.WithLabelValues(zone, net, fam).Inc() RequestDuration.WithLabelValues(zone).Observe(float64(time.Since(start) / time.Millisecond)) if req.Do() { RequestDo.WithLabelValues(zone).Inc() } if _, known := monitorType[typ]; known { RequestType.WithLabelValues(zone, dns.Type(typ).String()).Inc() } else { RequestType.WithLabelValues(zone, other).Inc() } ResponseSize.WithLabelValues(zone, net).Observe(float64(size)) RequestSize.WithLabelValues(zone, net).Observe(float64(req.Len())) ResponseRcode.WithLabelValues(zone, rcode).Inc() }
[ "func", "Report", "(", "req", "request", ".", "Request", ",", "zone", ",", "rcode", "string", ",", "size", "int", ",", "start", "time", ".", "Time", ")", "{", "net", ":=", "req", ".", "Proto", "(", ")", "\n", "fam", ":=", "\"1\"", "\n", "if", "req", ".", "Family", "(", ")", "==", "2", "{", "fam", "=", "\"2\"", "\n", "}", "\n", "typ", ":=", "req", ".", "QType", "(", ")", "\n", "RequestCount", ".", "WithLabelValues", "(", "zone", ",", "net", ",", "fam", ")", ".", "Inc", "(", ")", "\n", "RequestDuration", ".", "WithLabelValues", "(", "zone", ")", ".", "Observe", "(", "float64", "(", "time", ".", "Since", "(", "start", ")", "/", "time", ".", "Millisecond", ")", ")", "\n", "if", "req", ".", "Do", "(", ")", "{", "RequestDo", ".", "WithLabelValues", "(", "zone", ")", ".", "Inc", "(", ")", "\n", "}", "\n", "if", "_", ",", "known", ":=", "monitorType", "[", "typ", "]", ";", "known", "{", "RequestType", ".", "WithLabelValues", "(", "zone", ",", "dns", ".", "Type", "(", "typ", ")", ".", "String", "(", ")", ")", ".", "Inc", "(", ")", "\n", "}", "else", "{", "RequestType", ".", "WithLabelValues", "(", "zone", ",", "other", ")", ".", "Inc", "(", ")", "\n", "}", "\n", "ResponseSize", ".", "WithLabelValues", "(", "zone", ",", "net", ")", ".", "Observe", "(", "float64", "(", "size", ")", ")", "\n", "RequestSize", ".", "WithLabelValues", "(", "zone", ",", "net", ")", ".", "Observe", "(", "float64", "(", "req", ".", "Len", "(", ")", ")", ")", "\n", "ResponseRcode", ".", "WithLabelValues", "(", "zone", ",", "rcode", ")", ".", "Inc", "(", ")", "\n", "}" ]
// Report reports the metrics data associcated with request.
[ "Report", "reports", "the", "metrics", "data", "associcated", "with", "request", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/metrics/vars/report.go#L12-L39
train
inverse-inc/packetfence
go/caddy/api-aaa/api-aaa.go
setup
func setup(c *caddy.Controller) error { ctx := log.LoggerNewContext(context.Background()) apiAAA, err := buildApiAAAHandler(ctx) if err != nil { return err } httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { apiAAA.Next = next return apiAAA }) return nil }
go
func setup(c *caddy.Controller) error { ctx := log.LoggerNewContext(context.Background()) apiAAA, err := buildApiAAAHandler(ctx) if err != nil { return err } httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { apiAAA.Next = next return apiAAA }) return nil }
[ "func", "setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "ctx", ":=", "log", ".", "LoggerNewContext", "(", "context", ".", "Background", "(", ")", ")", "\n", "apiAAA", ",", "err", ":=", "buildApiAAAHandler", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "apiAAA", ".", "Next", "=", "next", "\n", "return", "apiAAA", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Setup the api-aaa middleware // Also loads the pfconfig resources and registers them in the pool
[ "Setup", "the", "api", "-", "aaa", "middleware", "Also", "loads", "the", "pfconfig", "resources", "and", "registers", "them", "in", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L50-L65
train
inverse-inc/packetfence
go/caddy/api-aaa/api-aaa.go
buildApiAAAHandler
func buildApiAAAHandler(ctx context.Context) (ApiAAAHandler, error) { apiAAA := ApiAAAHandler{} pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.PfConf.Webservices) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.UnifiedApiSystemUser) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.AdminRoles) tokenBackend := aaa.NewMemTokenBackend(15*time.Minute, 12*time.Hour) apiAAA.authentication = aaa.NewTokenAuthenticationMiddleware(tokenBackend) // Backend for the system Unified API user if pfconfigdriver.Config.UnifiedApiSystemUser.User != "" { apiAAA.systemBackend = aaa.NewMemAuthenticationBackend( map[string]string{}, map[string]bool{"ALL": true}, ) apiAAA.systemBackend.SetUser(pfconfigdriver.Config.UnifiedApiSystemUser.User, pfconfigdriver.Config.UnifiedApiSystemUser.Pass) apiAAA.authentication.AddAuthenticationBackend(apiAAA.systemBackend) } // Backend for the pf.conf webservices user apiAAA.webservicesBackend = aaa.NewMemAuthenticationBackend( map[string]string{}, map[string]bool{"ALL": true}, ) apiAAA.authentication.AddAuthenticationBackend(apiAAA.webservicesBackend) if pfconfigdriver.Config.PfConf.Webservices.User != "" { apiAAA.webservicesBackend.SetUser(pfconfigdriver.Config.PfConf.Webservices.User, pfconfigdriver.Config.PfConf.Webservices.Pass) } url, err := url.Parse("http://127.0.0.1:8080/api/v1/authentication/admin_authentication") sharedutils.CheckError(err) apiAAA.authentication.AddAuthenticationBackend(aaa.NewPfAuthenticationBackend(ctx, url, false)) apiAAA.authorization = aaa.NewTokenAuthorizationMiddleware(tokenBackend) router := httprouter.New() router.POST("/api/v1/login", apiAAA.handleLogin) router.GET("/api/v1/token_info", apiAAA.handleTokenInfo) apiAAA.router = router return apiAAA, nil }
go
func buildApiAAAHandler(ctx context.Context) (ApiAAAHandler, error) { apiAAA := ApiAAAHandler{} pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.PfConf.Webservices) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.UnifiedApiSystemUser) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.AdminRoles) tokenBackend := aaa.NewMemTokenBackend(15*time.Minute, 12*time.Hour) apiAAA.authentication = aaa.NewTokenAuthenticationMiddleware(tokenBackend) // Backend for the system Unified API user if pfconfigdriver.Config.UnifiedApiSystemUser.User != "" { apiAAA.systemBackend = aaa.NewMemAuthenticationBackend( map[string]string{}, map[string]bool{"ALL": true}, ) apiAAA.systemBackend.SetUser(pfconfigdriver.Config.UnifiedApiSystemUser.User, pfconfigdriver.Config.UnifiedApiSystemUser.Pass) apiAAA.authentication.AddAuthenticationBackend(apiAAA.systemBackend) } // Backend for the pf.conf webservices user apiAAA.webservicesBackend = aaa.NewMemAuthenticationBackend( map[string]string{}, map[string]bool{"ALL": true}, ) apiAAA.authentication.AddAuthenticationBackend(apiAAA.webservicesBackend) if pfconfigdriver.Config.PfConf.Webservices.User != "" { apiAAA.webservicesBackend.SetUser(pfconfigdriver.Config.PfConf.Webservices.User, pfconfigdriver.Config.PfConf.Webservices.Pass) } url, err := url.Parse("http://127.0.0.1:8080/api/v1/authentication/admin_authentication") sharedutils.CheckError(err) apiAAA.authentication.AddAuthenticationBackend(aaa.NewPfAuthenticationBackend(ctx, url, false)) apiAAA.authorization = aaa.NewTokenAuthorizationMiddleware(tokenBackend) router := httprouter.New() router.POST("/api/v1/login", apiAAA.handleLogin) router.GET("/api/v1/token_info", apiAAA.handleTokenInfo) apiAAA.router = router return apiAAA, nil }
[ "func", "buildApiAAAHandler", "(", "ctx", "context", ".", "Context", ")", "(", "ApiAAAHandler", ",", "error", ")", "{", "apiAAA", ":=", "ApiAAAHandler", "{", "}", "\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&", "pfconfigdriver", ".", "Config", ".", "PfConf", ".", "Webservices", ")", "\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&", "pfconfigdriver", ".", "Config", ".", "UnifiedApiSystemUser", ")", "\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&", "pfconfigdriver", ".", "Config", ".", "AdminRoles", ")", "\n", "tokenBackend", ":=", "aaa", ".", "NewMemTokenBackend", "(", "15", "*", "time", ".", "Minute", ",", "12", "*", "time", ".", "Hour", ")", "\n", "apiAAA", ".", "authentication", "=", "aaa", ".", "NewTokenAuthenticationMiddleware", "(", "tokenBackend", ")", "\n", "if", "pfconfigdriver", ".", "Config", ".", "UnifiedApiSystemUser", ".", "User", "!=", "\"\"", "{", "apiAAA", ".", "systemBackend", "=", "aaa", ".", "NewMemAuthenticationBackend", "(", "map", "[", "string", "]", "string", "{", "}", ",", "map", "[", "string", "]", "bool", "{", "\"ALL\"", ":", "true", "}", ",", ")", "\n", "apiAAA", ".", "systemBackend", ".", "SetUser", "(", "pfconfigdriver", ".", "Config", ".", "UnifiedApiSystemUser", ".", "User", ",", "pfconfigdriver", ".", "Config", ".", "UnifiedApiSystemUser", ".", "Pass", ")", "\n", "apiAAA", ".", "authentication", ".", "AddAuthenticationBackend", "(", "apiAAA", ".", "systemBackend", ")", "\n", "}", "\n", "apiAAA", ".", "webservicesBackend", "=", "aaa", ".", "NewMemAuthenticationBackend", "(", "map", "[", "string", "]", "string", "{", "}", ",", "map", "[", "string", "]", "bool", "{", "\"ALL\"", ":", "true", "}", ",", ")", "\n", "apiAAA", ".", "authentication", ".", "AddAuthenticationBackend", "(", "apiAAA", ".", "webservicesBackend", ")", "\n", "if", "pfconfigdriver", ".", "Config", ".", "PfConf", ".", "Webservices", ".", "User", "!=", "\"\"", "{", "apiAAA", ".", "webservicesBackend", ".", "SetUser", "(", "pfconfigdriver", ".", "Config", ".", "PfConf", ".", "Webservices", ".", "User", ",", "pfconfigdriver", ".", "Config", ".", "PfConf", ".", "Webservices", ".", "Pass", ")", "\n", "}", "\n", "url", ",", "err", ":=", "url", ".", "Parse", "(", "\"http://127.0.0.1:8080/api/v1/authentication/admin_authentication\"", ")", "\n", "sharedutils", ".", "CheckError", "(", "err", ")", "\n", "apiAAA", ".", "authentication", ".", "AddAuthenticationBackend", "(", "aaa", ".", "NewPfAuthenticationBackend", "(", "ctx", ",", "url", ",", "false", ")", ")", "\n", "apiAAA", ".", "authorization", "=", "aaa", ".", "NewTokenAuthorizationMiddleware", "(", "tokenBackend", ")", "\n", "router", ":=", "httprouter", ".", "New", "(", ")", "\n", "router", ".", "POST", "(", "\"/api/v1/login\"", ",", "apiAAA", ".", "handleLogin", ")", "\n", "router", ".", "GET", "(", "\"/api/v1/token_info\"", ",", "apiAAA", ".", "handleTokenInfo", ")", "\n", "apiAAA", ".", "router", "=", "router", "\n", "return", "apiAAA", ",", "nil", "\n", "}" ]
// Build the ApiAAAHandler which will initialize the cache and instantiate the router along with its routes
[ "Build", "the", "ApiAAAHandler", "which", "will", "initialize", "the", "cache", "and", "instantiate", "the", "router", "along", "with", "its", "routes" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L68-L113
train
inverse-inc/packetfence
go/caddy/api-aaa/api-aaa.go
handleLogin
func (h ApiAAAHandler) handleLogin(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("api-aaa.login") var loginParams struct { Username string Password string } err := json.NewDecoder(r.Body).Decode(&loginParams) if err != nil { msg := fmt.Sprintf("Error while decoding payload: %s", err) log.LoggerWContext(ctx).Error(msg) http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } auth, token, err := h.authentication.Login(ctx, loginParams.Username, loginParams.Password) if auth { w.WriteHeader(http.StatusOK) res, _ := json.Marshal(map[string]string{ "token": token, }) fmt.Fprintf(w, string(res)) } else { w.WriteHeader(http.StatusUnauthorized) res, _ := json.Marshal(map[string]string{ "message": err.Error(), }) fmt.Fprintf(w, string(res)) } }
go
func (h ApiAAAHandler) handleLogin(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("api-aaa.login") var loginParams struct { Username string Password string } err := json.NewDecoder(r.Body).Decode(&loginParams) if err != nil { msg := fmt.Sprintf("Error while decoding payload: %s", err) log.LoggerWContext(ctx).Error(msg) http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } auth, token, err := h.authentication.Login(ctx, loginParams.Username, loginParams.Password) if auth { w.WriteHeader(http.StatusOK) res, _ := json.Marshal(map[string]string{ "token": token, }) fmt.Fprintf(w, string(res)) } else { w.WriteHeader(http.StatusUnauthorized) res, _ := json.Marshal(map[string]string{ "message": err.Error(), }) fmt.Fprintf(w, string(res)) } }
[ "func", "(", "h", "ApiAAAHandler", ")", "handleLogin", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "p", "httprouter", ".", "Params", ")", "{", "ctx", ":=", "r", ".", "Context", "(", ")", "\n", "defer", "statsd", ".", "NewStatsDTiming", "(", "ctx", ")", ".", "Send", "(", "\"api-aaa.login\"", ")", "\n", "var", "loginParams", "struct", "{", "Username", "string", "\n", "Password", "string", "\n", "}", "\n", "err", ":=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", ".", "Decode", "(", "&", "loginParams", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"Error while decoding payload: %s\"", ",", "err", ")", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "msg", ")", "\n", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprint", "(", "err", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "auth", ",", "token", ",", "err", ":=", "h", ".", "authentication", ".", "Login", "(", "ctx", ",", "loginParams", ".", "Username", ",", "loginParams", ".", "Password", ")", "\n", "if", "auth", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "res", ",", "_", ":=", "json", ".", "Marshal", "(", "map", "[", "string", "]", "string", "{", "\"token\"", ":", "token", ",", "}", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "string", "(", "res", ")", ")", "\n", "}", "else", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusUnauthorized", ")", "\n", "res", ",", "_", ":=", "json", ".", "Marshal", "(", "map", "[", "string", "]", "string", "{", "\"message\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "string", "(", "res", ")", ")", "\n", "}", "\n", "}" ]
// Handle an API login
[ "Handle", "an", "API", "login" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L116-L149
train
inverse-inc/packetfence
go/caddy/api-aaa/api-aaa.go
handleTokenInfo
func (h ApiAAAHandler) handleTokenInfo(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("api-aaa.token_info") info, expiration := h.authorization.GetTokenInfoFromBearerRequest(ctx, r) if info != nil { // We'll want to render the roles as an array, not as a map prettyInfo := PrettyTokenInfo{ AdminActions: make([]string, len(info.AdminActions())), AdminRoles: make([]string, len(info.AdminRoles)), TenantId: info.TenantId, Username: info.Username, ExpiresAt: expiration, } i := 0 for r, _ := range info.AdminActions() { prettyInfo.AdminActions[i] = r i++ } i = 0 for r, _ := range info.AdminRoles { prettyInfo.AdminRoles[i] = r i++ } w.WriteHeader(http.StatusOK) res, _ := json.Marshal(map[string]interface{}{ "item": prettyInfo, }) fmt.Fprintf(w, string(res)) } else { w.WriteHeader(http.StatusNotFound) res, _ := json.Marshal(map[string]string{ "message": "Couldn't find any information for the current token. Either it is invalid or it has expired.", }) fmt.Fprintf(w, string(res)) } }
go
func (h ApiAAAHandler) handleTokenInfo(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("api-aaa.token_info") info, expiration := h.authorization.GetTokenInfoFromBearerRequest(ctx, r) if info != nil { // We'll want to render the roles as an array, not as a map prettyInfo := PrettyTokenInfo{ AdminActions: make([]string, len(info.AdminActions())), AdminRoles: make([]string, len(info.AdminRoles)), TenantId: info.TenantId, Username: info.Username, ExpiresAt: expiration, } i := 0 for r, _ := range info.AdminActions() { prettyInfo.AdminActions[i] = r i++ } i = 0 for r, _ := range info.AdminRoles { prettyInfo.AdminRoles[i] = r i++ } w.WriteHeader(http.StatusOK) res, _ := json.Marshal(map[string]interface{}{ "item": prettyInfo, }) fmt.Fprintf(w, string(res)) } else { w.WriteHeader(http.StatusNotFound) res, _ := json.Marshal(map[string]string{ "message": "Couldn't find any information for the current token. Either it is invalid or it has expired.", }) fmt.Fprintf(w, string(res)) } }
[ "func", "(", "h", "ApiAAAHandler", ")", "handleTokenInfo", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "p", "httprouter", ".", "Params", ")", "{", "ctx", ":=", "r", ".", "Context", "(", ")", "\n", "defer", "statsd", ".", "NewStatsDTiming", "(", "ctx", ")", ".", "Send", "(", "\"api-aaa.token_info\"", ")", "\n", "info", ",", "expiration", ":=", "h", ".", "authorization", ".", "GetTokenInfoFromBearerRequest", "(", "ctx", ",", "r", ")", "\n", "if", "info", "!=", "nil", "{", "prettyInfo", ":=", "PrettyTokenInfo", "{", "AdminActions", ":", "make", "(", "[", "]", "string", ",", "len", "(", "info", ".", "AdminActions", "(", ")", ")", ")", ",", "AdminRoles", ":", "make", "(", "[", "]", "string", ",", "len", "(", "info", ".", "AdminRoles", ")", ")", ",", "TenantId", ":", "info", ".", "TenantId", ",", "Username", ":", "info", ".", "Username", ",", "ExpiresAt", ":", "expiration", ",", "}", "\n", "i", ":=", "0", "\n", "for", "r", ",", "_", ":=", "range", "info", ".", "AdminActions", "(", ")", "{", "prettyInfo", ".", "AdminActions", "[", "i", "]", "=", "r", "\n", "i", "++", "\n", "}", "\n", "i", "=", "0", "\n", "for", "r", ",", "_", ":=", "range", "info", ".", "AdminRoles", "{", "prettyInfo", ".", "AdminRoles", "[", "i", "]", "=", "r", "\n", "i", "++", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "res", ",", "_", ":=", "json", ".", "Marshal", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"item\"", ":", "prettyInfo", ",", "}", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "string", "(", "res", ")", ")", "\n", "}", "else", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "res", ",", "_", ":=", "json", ".", "Marshal", "(", "map", "[", "string", "]", "string", "{", "\"message\"", ":", "\"Couldn't find any information for the current token. Either it is invalid or it has expired.\"", ",", "}", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "string", "(", "res", ")", ")", "\n", "}", "\n", "}" ]
// Handle getting the token info
[ "Handle", "getting", "the", "token", "info" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/api-aaa/api-aaa.go#L152-L192
train
inverse-inc/packetfence
go/coredns/core/dnsserver/server-grpc.go
NewServergRPC
func NewServergRPC(addr string, group []*Config) (*ServergRPC, error) { s, err := NewServer(addr, group) if err != nil { return nil, err } gs := &ServergRPC{Server: s} return gs, nil }
go
func NewServergRPC(addr string, group []*Config) (*ServergRPC, error) { s, err := NewServer(addr, group) if err != nil { return nil, err } gs := &ServergRPC{Server: s} return gs, nil }
[ "func", "NewServergRPC", "(", "addr", "string", ",", "group", "[", "]", "*", "Config", ")", "(", "*", "ServergRPC", ",", "error", ")", "{", "s", ",", "err", ":=", "NewServer", "(", "addr", ",", "group", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "gs", ":=", "&", "ServergRPC", "{", "Server", ":", "s", "}", "\n", "return", "gs", ",", "nil", "\n", "}" ]
// NewServergRPC returns a new CoreDNS GRPC server and compiles all plugin in to it.
[ "NewServergRPC", "returns", "a", "new", "CoreDNS", "GRPC", "server", "and", "compiles", "all", "plugin", "in", "to", "it", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/server-grpc.go#L28-L36
train
inverse-inc/packetfence
go/coredns/core/dnsserver/server-grpc.go
Query
func (s *ServergRPC) Query(ctx context.Context, in *pb.DnsPacket) (*pb.DnsPacket, error) { msg := new(dns.Msg) err := msg.Unpack(in.Msg) if err != nil { return nil, err } p, ok := peer.FromContext(ctx) if !ok { return nil, errors.New("no peer in gRPC context") } a, ok := p.Addr.(*net.TCPAddr) if !ok { return nil, fmt.Errorf("no TCP peer in gRPC context: %v", p.Addr) } r := &net.IPAddr{IP: a.IP} w := &gRPCresponse{localAddr: s.listenAddr, remoteAddr: r, Msg: msg} s.ServeDNS(ctx, w, msg) packed, err := w.Msg.Pack() if err != nil { return nil, err } return &pb.DnsPacket{Msg: packed}, nil }
go
func (s *ServergRPC) Query(ctx context.Context, in *pb.DnsPacket) (*pb.DnsPacket, error) { msg := new(dns.Msg) err := msg.Unpack(in.Msg) if err != nil { return nil, err } p, ok := peer.FromContext(ctx) if !ok { return nil, errors.New("no peer in gRPC context") } a, ok := p.Addr.(*net.TCPAddr) if !ok { return nil, fmt.Errorf("no TCP peer in gRPC context: %v", p.Addr) } r := &net.IPAddr{IP: a.IP} w := &gRPCresponse{localAddr: s.listenAddr, remoteAddr: r, Msg: msg} s.ServeDNS(ctx, w, msg) packed, err := w.Msg.Pack() if err != nil { return nil, err } return &pb.DnsPacket{Msg: packed}, nil }
[ "func", "(", "s", "*", "ServergRPC", ")", "Query", "(", "ctx", "context", ".", "Context", ",", "in", "*", "pb", ".", "DnsPacket", ")", "(", "*", "pb", ".", "DnsPacket", ",", "error", ")", "{", "msg", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "err", ":=", "msg", ".", "Unpack", "(", "in", ".", "Msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ",", "ok", ":=", "peer", ".", "FromContext", "(", "ctx", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"no peer in gRPC context\"", ")", "\n", "}", "\n", "a", ",", "ok", ":=", "p", ".", "Addr", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"no TCP peer in gRPC context: %v\"", ",", "p", ".", "Addr", ")", "\n", "}", "\n", "r", ":=", "&", "net", ".", "IPAddr", "{", "IP", ":", "a", ".", "IP", "}", "\n", "w", ":=", "&", "gRPCresponse", "{", "localAddr", ":", "s", ".", "listenAddr", ",", "remoteAddr", ":", "r", ",", "Msg", ":", "msg", "}", "\n", "s", ".", "ServeDNS", "(", "ctx", ",", "w", ",", "msg", ")", "\n", "packed", ",", "err", ":=", "w", ".", "Msg", ".", "Pack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "pb", ".", "DnsPacket", "{", "Msg", ":", "packed", "}", ",", "nil", "\n", "}" ]
// Query is the main entry-point into the gRPC server. From here we call ServeDNS like // any normal server. We use a custom responseWriter to pick up the bytes we need to write // back to the client as a protobuf.
[ "Query", "is", "the", "main", "entry", "-", "point", "into", "the", "gRPC", "server", ".", "From", "here", "we", "call", "ServeDNS", "like", "any", "normal", "server", ".", "We", "use", "a", "custom", "responseWriter", "to", "pick", "up", "the", "bytes", "we", "need", "to", "write", "back", "to", "the", "client", "as", "a", "protobuf", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/server-grpc.go#L119-L147
train
inverse-inc/packetfence
go/coredns/core/dnsserver/server.go
DefaultErrorFunc
func DefaultErrorFunc(w dns.ResponseWriter, r *dns.Msg, rc int) { state := request.Request{W: w, Req: r} answer := new(dns.Msg) answer.SetRcode(r, rc) state.SizeAndDo(answer) vars.Report(state, vars.Dropped, rcode.ToString(rc), answer.Len(), time.Now()) w.WriteMsg(answer) }
go
func DefaultErrorFunc(w dns.ResponseWriter, r *dns.Msg, rc int) { state := request.Request{W: w, Req: r} answer := new(dns.Msg) answer.SetRcode(r, rc) state.SizeAndDo(answer) vars.Report(state, vars.Dropped, rcode.ToString(rc), answer.Len(), time.Now()) w.WriteMsg(answer) }
[ "func", "DefaultErrorFunc", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ",", "rc", "int", ")", "{", "state", ":=", "request", ".", "Request", "{", "W", ":", "w", ",", "Req", ":", "r", "}", "\n", "answer", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "answer", ".", "SetRcode", "(", "r", ",", "rc", ")", "\n", "state", ".", "SizeAndDo", "(", "answer", ")", "\n", "vars", ".", "Report", "(", "state", ",", "vars", ".", "Dropped", ",", "rcode", ".", "ToString", "(", "rc", ")", ",", "answer", ".", "Len", "(", ")", ",", "time", ".", "Now", "(", ")", ")", "\n", "w", ".", "WriteMsg", "(", "answer", ")", "\n", "}" ]
// DefaultErrorFunc responds to an DNS request with an error.
[ "DefaultErrorFunc", "responds", "to", "an", "DNS", "request", "with", "an", "error", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/server.go#L304-L315
train
inverse-inc/packetfence
go/coredns/plugin/file/reload.go
Reload
func (z *Zone) Reload() error { if z.NoReload { return nil } tick := time.NewTicker(TickTime) go func() { for { select { case <-tick.C: reader, err := os.Open(z.file) if err != nil { log.Printf("[ERROR] Failed to open zone %q in %q: %v", z.origin, z.file, err) continue } serial := z.SOASerialIfDefined() zone, err := Parse(reader, z.origin, z.file, serial) if err != nil { if _, ok := err.(*serialErr); !ok { log.Printf("[ERROR] Parsing zone %q: %v", z.origin, err) } continue } // copy elements we need z.reloadMu.Lock() z.Apex = zone.Apex z.Tree = zone.Tree z.reloadMu.Unlock() log.Printf("[INFO] Successfully reloaded zone %q in %q with serial %d", z.origin, z.file, z.Apex.SOA.Serial) z.Notify() case <-z.ReloadShutdown: tick.Stop() return } } }() return nil }
go
func (z *Zone) Reload() error { if z.NoReload { return nil } tick := time.NewTicker(TickTime) go func() { for { select { case <-tick.C: reader, err := os.Open(z.file) if err != nil { log.Printf("[ERROR] Failed to open zone %q in %q: %v", z.origin, z.file, err) continue } serial := z.SOASerialIfDefined() zone, err := Parse(reader, z.origin, z.file, serial) if err != nil { if _, ok := err.(*serialErr); !ok { log.Printf("[ERROR] Parsing zone %q: %v", z.origin, err) } continue } // copy elements we need z.reloadMu.Lock() z.Apex = zone.Apex z.Tree = zone.Tree z.reloadMu.Unlock() log.Printf("[INFO] Successfully reloaded zone %q in %q with serial %d", z.origin, z.file, z.Apex.SOA.Serial) z.Notify() case <-z.ReloadShutdown: tick.Stop() return } } }() return nil }
[ "func", "(", "z", "*", "Zone", ")", "Reload", "(", ")", "error", "{", "if", "z", ".", "NoReload", "{", "return", "nil", "\n", "}", "\n", "tick", ":=", "time", ".", "NewTicker", "(", "TickTime", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "tick", ".", "C", ":", "reader", ",", "err", ":=", "os", ".", "Open", "(", "z", ".", "file", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"[ERROR] Failed to open zone %q in %q: %v\"", ",", "z", ".", "origin", ",", "z", ".", "file", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "serial", ":=", "z", ".", "SOASerialIfDefined", "(", ")", "\n", "zone", ",", "err", ":=", "Parse", "(", "reader", ",", "z", ".", "origin", ",", "z", ".", "file", ",", "serial", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "serialErr", ")", ";", "!", "ok", "{", "log", ".", "Printf", "(", "\"[ERROR] Parsing zone %q: %v\"", ",", "z", ".", "origin", ",", "err", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "z", ".", "reloadMu", ".", "Lock", "(", ")", "\n", "z", ".", "Apex", "=", "zone", ".", "Apex", "\n", "z", ".", "Tree", "=", "zone", ".", "Tree", "\n", "z", ".", "reloadMu", ".", "Unlock", "(", ")", "\n", "log", ".", "Printf", "(", "\"[INFO] Successfully reloaded zone %q in %q with serial %d\"", ",", "z", ".", "origin", ",", "z", ".", "file", ",", "z", ".", "Apex", ".", "SOA", ".", "Serial", ")", "\n", "z", ".", "Notify", "(", ")", "\n", "case", "<-", "z", ".", "ReloadShutdown", ":", "tick", ".", "Stop", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Reload reloads a zone when it is changed on disk. If z.NoRoload is true, no reloading will be done.
[ "Reload", "reloads", "a", "zone", "when", "it", "is", "changed", "on", "disk", ".", "If", "z", ".", "NoRoload", "is", "true", "no", "reloading", "will", "be", "done", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/file/reload.go#L13-L57
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/proxy/upstream.go
NewStaticUpstreams
func NewStaticUpstreams(c caddyfile.Dispenser) ([]Upstream, error) { var upstreams []Upstream for c.Next() { upstream := &staticUpstream{ from: "", upstreamHeaders: make(http.Header), downstreamHeaders: make(http.Header), Hosts: nil, Policy: &Random{}, MaxFails: 1, TryInterval: 250 * time.Millisecond, MaxConns: 0, KeepAlive: http.DefaultMaxIdleConnsPerHost, Timeout: 30 * time.Second, } if !c.Args(&upstream.from) { return upstreams, c.ArgErr() } var to []string for _, t := range c.RemainingArgs() { parsed, err := parseUpstream(t) if err != nil { return upstreams, err } to = append(to, parsed...) } for c.NextBlock() { switch c.Val() { case "upstream": if !c.NextArg() { return upstreams, c.ArgErr() } parsed, err := parseUpstream(c.Val()) if err != nil { return upstreams, err } to = append(to, parsed...) default: if err := parseBlock(&c, upstream); err != nil { return upstreams, err } } } if len(to) == 0 { return upstreams, c.ArgErr() } upstream.Hosts = make([]*UpstreamHost, len(to)) for i, host := range to { uh, err := upstream.NewHost(host) if err != nil { return upstreams, err } upstream.Hosts[i] = uh } if upstream.HealthCheck.Path != "" { upstream.HealthCheck.Client = http.Client{ Timeout: upstream.HealthCheck.Timeout, } go upstream.HealthCheckWorker(nil) } upstreams = append(upstreams, upstream) } return upstreams, nil }
go
func NewStaticUpstreams(c caddyfile.Dispenser) ([]Upstream, error) { var upstreams []Upstream for c.Next() { upstream := &staticUpstream{ from: "", upstreamHeaders: make(http.Header), downstreamHeaders: make(http.Header), Hosts: nil, Policy: &Random{}, MaxFails: 1, TryInterval: 250 * time.Millisecond, MaxConns: 0, KeepAlive: http.DefaultMaxIdleConnsPerHost, Timeout: 30 * time.Second, } if !c.Args(&upstream.from) { return upstreams, c.ArgErr() } var to []string for _, t := range c.RemainingArgs() { parsed, err := parseUpstream(t) if err != nil { return upstreams, err } to = append(to, parsed...) } for c.NextBlock() { switch c.Val() { case "upstream": if !c.NextArg() { return upstreams, c.ArgErr() } parsed, err := parseUpstream(c.Val()) if err != nil { return upstreams, err } to = append(to, parsed...) default: if err := parseBlock(&c, upstream); err != nil { return upstreams, err } } } if len(to) == 0 { return upstreams, c.ArgErr() } upstream.Hosts = make([]*UpstreamHost, len(to)) for i, host := range to { uh, err := upstream.NewHost(host) if err != nil { return upstreams, err } upstream.Hosts[i] = uh } if upstream.HealthCheck.Path != "" { upstream.HealthCheck.Client = http.Client{ Timeout: upstream.HealthCheck.Timeout, } go upstream.HealthCheckWorker(nil) } upstreams = append(upstreams, upstream) } return upstreams, nil }
[ "func", "NewStaticUpstreams", "(", "c", "caddyfile", ".", "Dispenser", ")", "(", "[", "]", "Upstream", ",", "error", ")", "{", "var", "upstreams", "[", "]", "Upstream", "\n", "for", "c", ".", "Next", "(", ")", "{", "upstream", ":=", "&", "staticUpstream", "{", "from", ":", "\"\"", ",", "upstreamHeaders", ":", "make", "(", "http", ".", "Header", ")", ",", "downstreamHeaders", ":", "make", "(", "http", ".", "Header", ")", ",", "Hosts", ":", "nil", ",", "Policy", ":", "&", "Random", "{", "}", ",", "MaxFails", ":", "1", ",", "TryInterval", ":", "250", "*", "time", ".", "Millisecond", ",", "MaxConns", ":", "0", ",", "KeepAlive", ":", "http", ".", "DefaultMaxIdleConnsPerHost", ",", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "}", "\n", "if", "!", "c", ".", "Args", "(", "&", "upstream", ".", "from", ")", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "var", "to", "[", "]", "string", "\n", "for", "_", ",", "t", ":=", "range", "c", ".", "RemainingArgs", "(", ")", "{", "parsed", ",", "err", ":=", "parseUpstream", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "to", "=", "append", "(", "to", ",", "parsed", "...", ")", "\n", "}", "\n", "for", "c", ".", "NextBlock", "(", ")", "{", "switch", "c", ".", "Val", "(", ")", "{", "case", "\"upstream\"", ":", "if", "!", "c", ".", "NextArg", "(", ")", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "parsed", ",", "err", ":=", "parseUpstream", "(", "c", ".", "Val", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "to", "=", "append", "(", "to", ",", "parsed", "...", ")", "\n", "default", ":", "if", "err", ":=", "parseBlock", "(", "&", "c", ",", "upstream", ")", ";", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "to", ")", "==", "0", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "upstream", ".", "Hosts", "=", "make", "(", "[", "]", "*", "UpstreamHost", ",", "len", "(", "to", ")", ")", "\n", "for", "i", ",", "host", ":=", "range", "to", "{", "uh", ",", "err", ":=", "upstream", ".", "NewHost", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "upstream", ".", "Hosts", "[", "i", "]", "=", "uh", "\n", "}", "\n", "if", "upstream", ".", "HealthCheck", ".", "Path", "!=", "\"\"", "{", "upstream", ".", "HealthCheck", ".", "Client", "=", "http", ".", "Client", "{", "Timeout", ":", "upstream", ".", "HealthCheck", ".", "Timeout", ",", "}", "\n", "go", "upstream", ".", "HealthCheckWorker", "(", "nil", ")", "\n", "}", "\n", "upstreams", "=", "append", "(", "upstreams", ",", "upstream", ")", "\n", "}", "\n", "return", "upstreams", ",", "nil", "\n", "}" ]
// NewStaticUpstreams parses the configuration input and sets up // static upstreams for the proxy middleware.
[ "NewStaticUpstreams", "parses", "the", "configuration", "input", "and", "sets", "up", "static", "upstreams", "for", "the", "proxy", "middleware", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/proxy/upstream.go#L48-L117
train
inverse-inc/packetfence
go/coredns/plugin/pfdns/pfdns.go
WebservicesInit
func (pf *pfdns) WebservicesInit() error { var ctx = context.Background() var webservices pfconfigdriver.PfConfWebservices webservices.PfconfigNS = "config::Pf" webservices.PfconfigMethod = "hash_element" webservices.PfconfigHashNS = "webservices" pfconfigdriver.FetchDecodeSocket(ctx, &webservices) pf.Webservices = webservices return nil }
go
func (pf *pfdns) WebservicesInit() error { var ctx = context.Background() var webservices pfconfigdriver.PfConfWebservices webservices.PfconfigNS = "config::Pf" webservices.PfconfigMethod = "hash_element" webservices.PfconfigHashNS = "webservices" pfconfigdriver.FetchDecodeSocket(ctx, &webservices) pf.Webservices = webservices return nil }
[ "func", "(", "pf", "*", "pfdns", ")", "WebservicesInit", "(", ")", "error", "{", "var", "ctx", "=", "context", ".", "Background", "(", ")", "\n", "var", "webservices", "pfconfigdriver", ".", "PfConfWebservices", "\n", "webservices", ".", "PfconfigNS", "=", "\"config::Pf\"", "\n", "webservices", ".", "PfconfigMethod", "=", "\"hash_element\"", "\n", "webservices", ".", "PfconfigHashNS", "=", "\"webservices\"", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "webservices", ")", "\n", "pf", ".", "Webservices", "=", "webservices", "\n", "return", "nil", "\n", "}" ]
// WebservicesInit read pfconfig webservices configuration
[ "WebservicesInit", "read", "pfconfig", "webservices", "configuration" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pfdns/pfdns.go#L509-L520
train
inverse-inc/packetfence
go/coredns/plugin/pfdns/pfdns.go
addDetectionMechanismsToList
func (pf *pfdns) addDetectionMechanismsToList(ctx context.Context, r string) error { rgx, err := regexp.Compile(r) if err == nil { pf.mutex.Lock() pf.detectionMechanisms = append(pf.detectionMechanisms, rgx) pf.mutex.Unlock() } else { log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to compile the regexp %s", err)) } return err }
go
func (pf *pfdns) addDetectionMechanismsToList(ctx context.Context, r string) error { rgx, err := regexp.Compile(r) if err == nil { pf.mutex.Lock() pf.detectionMechanisms = append(pf.detectionMechanisms, rgx) pf.mutex.Unlock() } else { log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to compile the regexp %s", err)) } return err }
[ "func", "(", "pf", "*", "pfdns", ")", "addDetectionMechanismsToList", "(", "ctx", "context", ".", "Context", ",", "r", "string", ")", "error", "{", "rgx", ",", "err", ":=", "regexp", ".", "Compile", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "pf", ".", "mutex", ".", "Lock", "(", ")", "\n", "pf", ".", "detectionMechanisms", "=", "append", "(", "pf", ".", "detectionMechanisms", ",", "rgx", ")", "\n", "pf", ".", "mutex", ".", "Unlock", "(", ")", "\n", "}", "else", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Not able to compile the regexp %s\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// addDetectionMechanismsToList add all detection mechanisms in a list
[ "addDetectionMechanismsToList", "add", "all", "detection", "mechanisms", "in", "a", "list" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pfdns/pfdns.go#L736-L746
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/user.go
newUser
func newUser(email string) (User, error) { user := User{Email: email} privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return user, errors.New("error generating private key: " + err.Error()) } user.key = privateKey return user, nil }
go
func newUser(email string) (User, error) { user := User{Email: email} privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return user, errors.New("error generating private key: " + err.Error()) } user.key = privateKey return user, nil }
[ "func", "newUser", "(", "email", "string", ")", "(", "User", ",", "error", ")", "{", "user", ":=", "User", "{", "Email", ":", "email", "}", "\n", "privateKey", ",", "err", ":=", "ecdsa", ".", "GenerateKey", "(", "elliptic", ".", "P384", "(", ")", ",", "rand", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "user", ",", "errors", ".", "New", "(", "\"error generating private key: \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "user", ".", "key", "=", "privateKey", "\n", "return", "user", ",", "nil", "\n", "}" ]
// newUser creates a new User for the given email address // with a new private key. This function does NOT save the // user to disk or register it via ACME. If you want to use // a user account that might already exist, call getUser // instead. It does NOT prompt the user.
[ "newUser", "creates", "a", "new", "User", "for", "the", "given", "email", "address", "with", "a", "new", "private", "key", ".", "This", "function", "does", "NOT", "save", "the", "user", "to", "disk", "or", "register", "it", "via", "ACME", ".", "If", "you", "want", "to", "use", "a", "user", "account", "that", "might", "already", "exist", "call", "getUser", "instead", ".", "It", "does", "NOT", "prompt", "the", "user", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L46-L54
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/user.go
getUser
func getUser(storage Storage, email string) (User, error) { var user User // open user reg userData, err := storage.LoadUser(email) if err != nil { if _, ok := err.(ErrNotExist); ok { // create a new user return newUser(email) } return user, err } // load user information err = json.Unmarshal(userData.Reg, &user) if err != nil { return user, err } // load their private key user.key, err = loadPrivateKey(userData.Key) return user, err }
go
func getUser(storage Storage, email string) (User, error) { var user User // open user reg userData, err := storage.LoadUser(email) if err != nil { if _, ok := err.(ErrNotExist); ok { // create a new user return newUser(email) } return user, err } // load user information err = json.Unmarshal(userData.Reg, &user) if err != nil { return user, err } // load their private key user.key, err = loadPrivateKey(userData.Key) return user, err }
[ "func", "getUser", "(", "storage", "Storage", ",", "email", "string", ")", "(", "User", ",", "error", ")", "{", "var", "user", "User", "\n", "userData", ",", "err", ":=", "storage", ".", "LoadUser", "(", "email", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "ErrNotExist", ")", ";", "ok", "{", "return", "newUser", "(", "email", ")", "\n", "}", "\n", "return", "user", ",", "err", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "userData", ".", "Reg", ",", "&", "user", ")", "\n", "if", "err", "!=", "nil", "{", "return", "user", ",", "err", "\n", "}", "\n", "user", ".", "key", ",", "err", "=", "loadPrivateKey", "(", "userData", ".", "Key", ")", "\n", "return", "user", ",", "err", "\n", "}" ]
// getUser loads the user with the given email from disk // using the provided storage. If the user does not exist, // it will create a new one, but it does NOT save new // users to the disk or register them via ACME. It does // NOT prompt the user.
[ "getUser", "loads", "the", "user", "with", "the", "given", "email", "from", "disk", "using", "the", "provided", "storage", ".", "If", "the", "user", "does", "not", "exist", "it", "will", "create", "a", "new", "one", "but", "it", "does", "NOT", "save", "new", "users", "to", "the", "disk", "or", "register", "them", "via", "ACME", ".", "It", "does", "NOT", "prompt", "the", "user", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L100-L122
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/user.go
saveUser
func saveUser(storage Storage, user User) error { // Save the private key and registration userData := new(UserData) var err error userData.Key, err = savePrivateKey(user.key) if err == nil { userData.Reg, err = json.MarshalIndent(&user, "", "\t") } if err == nil { err = storage.StoreUser(user.Email, userData) } return err }
go
func saveUser(storage Storage, user User) error { // Save the private key and registration userData := new(UserData) var err error userData.Key, err = savePrivateKey(user.key) if err == nil { userData.Reg, err = json.MarshalIndent(&user, "", "\t") } if err == nil { err = storage.StoreUser(user.Email, userData) } return err }
[ "func", "saveUser", "(", "storage", "Storage", ",", "user", "User", ")", "error", "{", "userData", ":=", "new", "(", "UserData", ")", "\n", "var", "err", "error", "\n", "userData", ".", "Key", ",", "err", "=", "savePrivateKey", "(", "user", ".", "key", ")", "\n", "if", "err", "==", "nil", "{", "userData", ".", "Reg", ",", "err", "=", "json", ".", "MarshalIndent", "(", "&", "user", ",", "\"\"", ",", "\"\\t\"", ")", "\n", "}", "\n", "\\t", "\n", "if", "err", "==", "nil", "{", "err", "=", "storage", ".", "StoreUser", "(", "user", ".", "Email", ",", "userData", ")", "\n", "}", "\n", "}" ]
// saveUser persists a user's key and account registration // to the file system. It does NOT register the user via ACME // or prompt the user. You must also pass in the storage // wherein the user should be saved. It should be the storage // for the CA with which user has an account.
[ "saveUser", "persists", "a", "user", "s", "key", "and", "account", "registration", "to", "the", "file", "system", ".", "It", "does", "NOT", "register", "the", "user", "via", "ACME", "or", "prompt", "the", "user", ".", "You", "must", "also", "pass", "in", "the", "storage", "wherein", "the", "user", "should", "be", "saved", ".", "It", "should", "be", "the", "storage", "for", "the", "CA", "with", "which", "user", "has", "an", "account", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L129-L141
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/user.go
promptUserAgreement
func promptUserAgreement(agreementURL string, changed bool) bool { if changed { fmt.Printf("The Let's Encrypt Subscriber Agreement has changed:\n %s\n", agreementURL) fmt.Print("Do you agree to the new terms? (y/n): ") } else { fmt.Printf("To continue, you must agree to the Let's Encrypt Subscriber Agreement:\n %s\n", agreementURL) fmt.Print("Do you agree to the terms? (y/n): ") } reader := bufio.NewReader(stdin) answer, err := reader.ReadString('\n') if err != nil { return false } answer = strings.ToLower(strings.TrimSpace(answer)) return answer == "y" || answer == "yes" }
go
func promptUserAgreement(agreementURL string, changed bool) bool { if changed { fmt.Printf("The Let's Encrypt Subscriber Agreement has changed:\n %s\n", agreementURL) fmt.Print("Do you agree to the new terms? (y/n): ") } else { fmt.Printf("To continue, you must agree to the Let's Encrypt Subscriber Agreement:\n %s\n", agreementURL) fmt.Print("Do you agree to the terms? (y/n): ") } reader := bufio.NewReader(stdin) answer, err := reader.ReadString('\n') if err != nil { return false } answer = strings.ToLower(strings.TrimSpace(answer)) return answer == "y" || answer == "yes" }
[ "func", "promptUserAgreement", "(", "agreementURL", "string", ",", "changed", "bool", ")", "bool", "{", "if", "changed", "{", "fmt", ".", "Printf", "(", "\"The Let's Encrypt Subscriber Agreement has changed:\\n %s\\n\"", ",", "\\n", ")", "\n", "\\n", "\n", "}", "else", "agreementURL", "\n", "fmt", ".", "Print", "(", "\"Do you agree to the new terms? (y/n): \"", ")", "\n", "{", "fmt", ".", "Printf", "(", "\"To continue, you must agree to the Let's Encrypt Subscriber Agreement:\\n %s\\n\"", ",", "\\n", ")", "\n", "\\n", "\n", "}", "\n", "agreementURL", "\n", "fmt", ".", "Print", "(", "\"Do you agree to the terms? (y/n): \"", ")", "\n", "reader", ":=", "bufio", ".", "NewReader", "(", "stdin", ")", "\n", "}" ]
// promptUserAgreement prompts the user to agree to the agreement // at agreementURL via stdin. If the agreement has changed, then pass // true as the second argument. If this is the user's first time // agreeing, pass false. It returns whether the user agreed or not.
[ "promptUserAgreement", "prompts", "the", "user", "to", "agree", "to", "the", "agreement", "at", "agreementURL", "via", "stdin", ".", "If", "the", "agreement", "has", "changed", "then", "pass", "true", "as", "the", "second", "argument", ".", "If", "this", "is", "the", "user", "s", "first", "time", "agreeing", "pass", "false", ".", "It", "returns", "whether", "the", "user", "agreed", "or", "not", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/user.go#L147-L164
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/out/socket.go
NewSocket
func NewSocket(path string) (s *Socket, err error) { s = &Socket{path: path} if err = openSocket(s); err != nil { err = fmt.Errorf("open socket: %s", err) s.err = err return } return }
go
func NewSocket(path string) (s *Socket, err error) { s = &Socket{path: path} if err = openSocket(s); err != nil { err = fmt.Errorf("open socket: %s", err) s.err = err return } return }
[ "func", "NewSocket", "(", "path", "string", ")", "(", "s", "*", "Socket", ",", "err", "error", ")", "{", "s", "=", "&", "Socket", "{", "path", ":", "path", "}", "\n", "if", "err", "=", "openSocket", "(", "s", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"open socket: %s\"", ",", "err", ")", "\n", "s", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "return", "\n", "}" ]
// NewSocket will always return a new Socket. // err if nothing is listening to it, it will attempt to reconnect on the next Write.
[ "NewSocket", "will", "always", "return", "a", "new", "Socket", ".", "err", "if", "nothing", "is", "listening", "to", "it", "it", "will", "attempt", "to", "reconnect", "on", "the", "next", "Write", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/out/socket.go#L40-L48
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/out/socket.go
Close
func (s *Socket) Close() error { if s.err != nil { // nothing to close return nil } defer s.conn.Close() if err := s.enc.Flush(); err != nil { return fmt.Errorf("flush: %s", err) } return s.enc.Close() }
go
func (s *Socket) Close() error { if s.err != nil { // nothing to close return nil } defer s.conn.Close() if err := s.enc.Flush(); err != nil { return fmt.Errorf("flush: %s", err) } return s.enc.Close() }
[ "func", "(", "s", "*", "Socket", ")", "Close", "(", ")", "error", "{", "if", "s", ".", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "defer", "s", ".", "conn", ".", "Close", "(", ")", "\n", "if", "err", ":=", "s", ".", "enc", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"flush: %s\"", ",", "err", ")", "\n", "}", "\n", "return", "s", ".", "enc", ".", "Close", "(", ")", "\n", "}" ]
// Close the socket and flush the remaining frames.
[ "Close", "the", "socket", "and", "flush", "the", "remaining", "frames", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/out/socket.go#L70-L82
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/fastcgi/fcgiclient.go
DialTimeout
func DialTimeout(network string, address string, timeout time.Duration) (fcgi *FCGIClient, err error) { conn, err := net.DialTimeout(network, address, timeout) if err != nil { return } fcgi = &FCGIClient{conn: conn, keepAlive: false, reqID: 1} return fcgi, nil }
go
func DialTimeout(network string, address string, timeout time.Duration) (fcgi *FCGIClient, err error) { conn, err := net.DialTimeout(network, address, timeout) if err != nil { return } fcgi = &FCGIClient{conn: conn, keepAlive: false, reqID: 1} return fcgi, nil }
[ "func", "DialTimeout", "(", "network", "string", ",", "address", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "fcgi", "*", "FCGIClient", ",", "err", "error", ")", "{", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "network", ",", "address", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "fcgi", "=", "&", "FCGIClient", "{", "conn", ":", "conn", ",", "keepAlive", ":", "false", ",", "reqID", ":", "1", "}", "\n", "return", "fcgi", ",", "nil", "\n", "}" ]
// DialTimeout connects to the fcgi responder at the specified network address, using default net.Dialer. // See func net.Dial for a description of the network and address parameters.
[ "DialTimeout", "connects", "to", "the", "fcgi", "responder", "at", "the", "specified", "network", "address", "using", "default", "net", ".", "Dialer", ".", "See", "func", "net", ".", "Dial", "for", "a", "description", "of", "the", "network", "and", "address", "parameters", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/fastcgi/fcgiclient.go#L188-L197
train
inverse-inc/packetfence
go/requesthistory/request_history.go
UuidIndex
func (rh *RequestHistory) UuidIndex(uuid string) int { rh.lock.RLock() defer rh.lock.RUnlock() return rh.uuidIndexNoLock(uuid) }
go
func (rh *RequestHistory) UuidIndex(uuid string) int { rh.lock.RLock() defer rh.lock.RUnlock() return rh.uuidIndexNoLock(uuid) }
[ "func", "(", "rh", "*", "RequestHistory", ")", "UuidIndex", "(", "uuid", "string", ")", "int", "{", "rh", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "rh", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "rh", ".", "uuidIndexNoLock", "(", "uuid", ")", "\n", "}" ]
// Returns the index at which to find the request for the UUID // Returns -1 if the UUID is unknown
[ "Returns", "the", "index", "at", "which", "to", "find", "the", "request", "for", "the", "UUID", "Returns", "-", "1", "if", "the", "UUID", "is", "unknown" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/requesthistory/request_history.go#L74-L79
train
inverse-inc/packetfence
go/dhcp/utils.go
connectDB
func connectDB(configDatabase pfconfigdriver.PfConfDatabase) { db, err := db.DbFromConfig(ctx) sharedutils.CheckError(err) MySQLdatabase = db }
go
func connectDB(configDatabase pfconfigdriver.PfConfDatabase) { db, err := db.DbFromConfig(ctx) sharedutils.CheckError(err) MySQLdatabase = db }
[ "func", "connectDB", "(", "configDatabase", "pfconfigdriver", ".", "PfConfDatabase", ")", "{", "db", ",", "err", ":=", "db", ".", "DbFromConfig", "(", "ctx", ")", "\n", "sharedutils", ".", "CheckError", "(", "err", ")", "\n", "MySQLdatabase", "=", "db", "\n", "}" ]
// connectDB connect to the database
[ "connectDB", "connect", "to", "the", "database" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L30-L34
train
inverse-inc/packetfence
go/dhcp/utils.go
initiaLease
func initiaLease(dhcpHandler *DHCPHandler, ConfNet pfconfigdriver.RessourseNetworkConf) { // Need to calculate the end ip because of the ip per role feature now := time.Now() endip := binary.BigEndian.Uint32(dhcpHandler.start.To4()) + uint32(dhcpHandler.leaseRange) - uint32(1) a := make([]byte, 4) binary.BigEndian.PutUint32(a, endip) ipend := net.IPv4(a[0], a[1], a[2], a[3]) rows, err := MySQLdatabase.Query("select ip,mac,end_time,start_time from ip4log i where inet_aton(ip) between inet_aton(?) and inet_aton(?) and (end_time = 0 OR end_time > NOW()) and end_time in (select MAX(end_time) from ip4log where mac = i.mac) ORDER BY mac,end_time desc", dhcpHandler.start.String(), ipend.String()) if err != nil { log.LoggerWContext(ctx).Error(err.Error()) return } defer rows.Close() var ( ipstr string mac string end_time time.Time start_time time.Time reservedIP []net.IP found bool ) found = false excludeIP := ExcludeIP(dhcpHandler, ConfNet.IpReserved) dhcpHandler.ipAssigned, reservedIP = AssignIP(dhcpHandler, ConfNet.IpAssigned) dhcpHandler.ipReserved = ConfNet.IpReserved for rows.Next() { err := rows.Scan(&ipstr, &mac, &end_time, &start_time) if err != nil { log.LoggerWContext(ctx).Error(err.Error()) return } for _, ans := range append(excludeIP, reservedIP...) { if net.ParseIP(ipstr).Equal(ans) { found = true break } } if found == false { // Calculate the leasetime from the date in the database var leaseDuration time.Duration if end_time.IsZero() { leaseDuration = dhcpHandler.leaseDuration } else { leaseDuration = end_time.Sub(now) } ip := net.ParseIP(ipstr) // Calculate the position for the roaring bitmap position := uint32(binary.BigEndian.Uint32(ip.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4())) // Remove the position in the roaming bitmap dhcpHandler.available.ReserveIPIndex(uint64(position), mac) // Add the mac in the cache dhcpHandler.hwcache.Set(mac, int(position), leaseDuration) GlobalIpCache.Set(ipstr, mac, leaseDuration) GlobalMacCache.Set(mac, ipstr, leaseDuration) } } }
go
func initiaLease(dhcpHandler *DHCPHandler, ConfNet pfconfigdriver.RessourseNetworkConf) { // Need to calculate the end ip because of the ip per role feature now := time.Now() endip := binary.BigEndian.Uint32(dhcpHandler.start.To4()) + uint32(dhcpHandler.leaseRange) - uint32(1) a := make([]byte, 4) binary.BigEndian.PutUint32(a, endip) ipend := net.IPv4(a[0], a[1], a[2], a[3]) rows, err := MySQLdatabase.Query("select ip,mac,end_time,start_time from ip4log i where inet_aton(ip) between inet_aton(?) and inet_aton(?) and (end_time = 0 OR end_time > NOW()) and end_time in (select MAX(end_time) from ip4log where mac = i.mac) ORDER BY mac,end_time desc", dhcpHandler.start.String(), ipend.String()) if err != nil { log.LoggerWContext(ctx).Error(err.Error()) return } defer rows.Close() var ( ipstr string mac string end_time time.Time start_time time.Time reservedIP []net.IP found bool ) found = false excludeIP := ExcludeIP(dhcpHandler, ConfNet.IpReserved) dhcpHandler.ipAssigned, reservedIP = AssignIP(dhcpHandler, ConfNet.IpAssigned) dhcpHandler.ipReserved = ConfNet.IpReserved for rows.Next() { err := rows.Scan(&ipstr, &mac, &end_time, &start_time) if err != nil { log.LoggerWContext(ctx).Error(err.Error()) return } for _, ans := range append(excludeIP, reservedIP...) { if net.ParseIP(ipstr).Equal(ans) { found = true break } } if found == false { // Calculate the leasetime from the date in the database var leaseDuration time.Duration if end_time.IsZero() { leaseDuration = dhcpHandler.leaseDuration } else { leaseDuration = end_time.Sub(now) } ip := net.ParseIP(ipstr) // Calculate the position for the roaring bitmap position := uint32(binary.BigEndian.Uint32(ip.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4())) // Remove the position in the roaming bitmap dhcpHandler.available.ReserveIPIndex(uint64(position), mac) // Add the mac in the cache dhcpHandler.hwcache.Set(mac, int(position), leaseDuration) GlobalIpCache.Set(ipstr, mac, leaseDuration) GlobalMacCache.Set(mac, ipstr, leaseDuration) } } }
[ "func", "initiaLease", "(", "dhcpHandler", "*", "DHCPHandler", ",", "ConfNet", "pfconfigdriver", ".", "RessourseNetworkConf", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "endip", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "dhcpHandler", ".", "start", ".", "To4", "(", ")", ")", "+", "uint32", "(", "dhcpHandler", ".", "leaseRange", ")", "-", "uint32", "(", "1", ")", "\n", "a", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "a", ",", "endip", ")", "\n", "ipend", ":=", "net", ".", "IPv4", "(", "a", "[", "0", "]", ",", "a", "[", "1", "]", ",", "a", "[", "2", "]", ",", "a", "[", "3", "]", ")", "\n", "rows", ",", "err", ":=", "MySQLdatabase", ".", "Query", "(", "\"select ip,mac,end_time,start_time from ip4log i where inet_aton(ip) between inet_aton(?) and inet_aton(?) and (end_time = 0 OR end_time > NOW()) and end_time in (select MAX(end_time) from ip4log where mac = i.mac) ORDER BY mac,end_time desc\"", ",", "dhcpHandler", ".", "start", ".", "String", "(", ")", ",", "ipend", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "var", "(", "ipstr", "string", "\n", "mac", "string", "\n", "end_time", "time", ".", "Time", "\n", "start_time", "time", ".", "Time", "\n", "reservedIP", "[", "]", "net", ".", "IP", "\n", "found", "bool", "\n", ")", "\n", "found", "=", "false", "\n", "excludeIP", ":=", "ExcludeIP", "(", "dhcpHandler", ",", "ConfNet", ".", "IpReserved", ")", "\n", "dhcpHandler", ".", "ipAssigned", ",", "reservedIP", "=", "AssignIP", "(", "dhcpHandler", ",", "ConfNet", ".", "IpAssigned", ")", "\n", "dhcpHandler", ".", "ipReserved", "=", "ConfNet", ".", "IpReserved", "\n", "for", "rows", ".", "Next", "(", ")", "{", "err", ":=", "rows", ".", "Scan", "(", "&", "ipstr", ",", "&", "mac", ",", "&", "end_time", ",", "&", "start_time", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "append", "(", "excludeIP", ",", "reservedIP", "...", ")", "{", "if", "net", ".", "ParseIP", "(", "ipstr", ")", ".", "Equal", "(", "ans", ")", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "found", "==", "false", "{", "var", "leaseDuration", "time", ".", "Duration", "\n", "if", "end_time", ".", "IsZero", "(", ")", "{", "leaseDuration", "=", "dhcpHandler", ".", "leaseDuration", "\n", "}", "else", "{", "leaseDuration", "=", "end_time", ".", "Sub", "(", "now", ")", "\n", "}", "\n", "ip", ":=", "net", ".", "ParseIP", "(", "ipstr", ")", "\n", "position", ":=", "uint32", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "ip", ".", "To4", "(", ")", ")", ")", "-", "uint32", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "dhcpHandler", ".", "start", ".", "To4", "(", ")", ")", ")", "\n", "dhcpHandler", ".", "available", ".", "ReserveIPIndex", "(", "uint64", "(", "position", ")", ",", "mac", ")", "\n", "dhcpHandler", ".", "hwcache", ".", "Set", "(", "mac", ",", "int", "(", "position", ")", ",", "leaseDuration", ")", "\n", "GlobalIpCache", ".", "Set", "(", "ipstr", ",", "mac", ",", "leaseDuration", ")", "\n", "GlobalMacCache", ".", "Set", "(", "mac", ",", "ipstr", ",", "leaseDuration", ")", "\n", "}", "\n", "}", "\n", "}" ]
// initiaLease fetch the database to remove already assigned ip addresses
[ "initiaLease", "fetch", "the", "database", "to", "remove", "already", "assigned", "ip", "addresses" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L37-L96
train
inverse-inc/packetfence
go/dhcp/utils.go
ExcludeIP
func ExcludeIP(dhcpHandler *DHCPHandler, ipRange string) []net.IP { excludeIPs, _ := IPsFromRange(ipRange) for _, excludeIP := range excludeIPs { if excludeIP != nil { // Calculate the position for the dhcp pool position := uint32(binary.BigEndian.Uint32(excludeIP.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4())) dhcpHandler.available.ReserveIPIndex(uint64(position), FakeMac) } } return excludeIPs }
go
func ExcludeIP(dhcpHandler *DHCPHandler, ipRange string) []net.IP { excludeIPs, _ := IPsFromRange(ipRange) for _, excludeIP := range excludeIPs { if excludeIP != nil { // Calculate the position for the dhcp pool position := uint32(binary.BigEndian.Uint32(excludeIP.To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4())) dhcpHandler.available.ReserveIPIndex(uint64(position), FakeMac) } } return excludeIPs }
[ "func", "ExcludeIP", "(", "dhcpHandler", "*", "DHCPHandler", ",", "ipRange", "string", ")", "[", "]", "net", ".", "IP", "{", "excludeIPs", ",", "_", ":=", "IPsFromRange", "(", "ipRange", ")", "\n", "for", "_", ",", "excludeIP", ":=", "range", "excludeIPs", "{", "if", "excludeIP", "!=", "nil", "{", "position", ":=", "uint32", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "excludeIP", ".", "To4", "(", ")", ")", ")", "-", "uint32", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "dhcpHandler", ".", "start", ".", "To4", "(", ")", ")", ")", "\n", "dhcpHandler", ".", "available", ".", "ReserveIPIndex", "(", "uint64", "(", "position", ")", ",", "FakeMac", ")", "\n", "}", "\n", "}", "\n", "return", "excludeIPs", "\n", "}" ]
// ExcludeIP remove IP from the pool
[ "ExcludeIP", "remove", "IP", "from", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L293-L305
train
inverse-inc/packetfence
go/dhcp/utils.go
AssignIP
func AssignIP(dhcpHandler *DHCPHandler, ipRange string) (map[string]uint32, []net.IP) { couple := make(map[string]uint32) var iplist []net.IP if ipRange != "" { rgx, _ := regexp.Compile("((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}):((?:[0-9]{1,3}.){3}(?:[0-9]{1,3}))") ipRangeArray := strings.Split(ipRange, ",") if len(ipRangeArray) >= 1 { for _, rangeip := range ipRangeArray { result := rgx.FindStringSubmatch(rangeip) position := uint32(binary.BigEndian.Uint32(net.ParseIP(result[2]).To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4())) // Remove the position in the roaming bitmap dhcpHandler.available.ReserveIPIndex(uint64(position), result[1]) couple[result[1]] = position iplist = append(iplist, net.ParseIP(result[2])) } } } return couple, iplist }
go
func AssignIP(dhcpHandler *DHCPHandler, ipRange string) (map[string]uint32, []net.IP) { couple := make(map[string]uint32) var iplist []net.IP if ipRange != "" { rgx, _ := regexp.Compile("((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}):((?:[0-9]{1,3}.){3}(?:[0-9]{1,3}))") ipRangeArray := strings.Split(ipRange, ",") if len(ipRangeArray) >= 1 { for _, rangeip := range ipRangeArray { result := rgx.FindStringSubmatch(rangeip) position := uint32(binary.BigEndian.Uint32(net.ParseIP(result[2]).To4())) - uint32(binary.BigEndian.Uint32(dhcpHandler.start.To4())) // Remove the position in the roaming bitmap dhcpHandler.available.ReserveIPIndex(uint64(position), result[1]) couple[result[1]] = position iplist = append(iplist, net.ParseIP(result[2])) } } } return couple, iplist }
[ "func", "AssignIP", "(", "dhcpHandler", "*", "DHCPHandler", ",", "ipRange", "string", ")", "(", "map", "[", "string", "]", "uint32", ",", "[", "]", "net", ".", "IP", ")", "{", "couple", ":=", "make", "(", "map", "[", "string", "]", "uint32", ")", "\n", "var", "iplist", "[", "]", "net", ".", "IP", "\n", "if", "ipRange", "!=", "\"\"", "{", "rgx", ",", "_", ":=", "regexp", ".", "Compile", "(", "\"((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}):((?:[0-9]{1,3}.){3}(?:[0-9]{1,3}))\"", ")", "\n", "ipRangeArray", ":=", "strings", ".", "Split", "(", "ipRange", ",", "\",\"", ")", "\n", "if", "len", "(", "ipRangeArray", ")", ">=", "1", "{", "for", "_", ",", "rangeip", ":=", "range", "ipRangeArray", "{", "result", ":=", "rgx", ".", "FindStringSubmatch", "(", "rangeip", ")", "\n", "position", ":=", "uint32", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "net", ".", "ParseIP", "(", "result", "[", "2", "]", ")", ".", "To4", "(", ")", ")", ")", "-", "uint32", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "dhcpHandler", ".", "start", ".", "To4", "(", ")", ")", ")", "\n", "dhcpHandler", ".", "available", ".", "ReserveIPIndex", "(", "uint64", "(", "position", ")", ",", "result", "[", "1", "]", ")", "\n", "couple", "[", "result", "[", "1", "]", "]", "=", "position", "\n", "iplist", "=", "append", "(", "iplist", ",", "net", ".", "ParseIP", "(", "result", "[", "2", "]", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "couple", ",", "iplist", "\n", "}" ]
// Assign static IP address to a mac address and remove it from the pool
[ "Assign", "static", "IP", "address", "to", "a", "mac", "address", "and", "remove", "it", "from", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L308-L326
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/handshake.go
GetCertificate
func (cg configGroup) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { cert, err := cg.getCertDuringHandshake(strings.ToLower(clientHello.ServerName), true, true) return &cert.Certificate, err }
go
func (cg configGroup) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { cert, err := cg.getCertDuringHandshake(strings.ToLower(clientHello.ServerName), true, true) return &cert.Certificate, err }
[ "func", "(", "cg", "configGroup", ")", "GetCertificate", "(", "clientHello", "*", "tls", ".", "ClientHelloInfo", ")", "(", "*", "tls", ".", "Certificate", ",", "error", ")", "{", "cert", ",", "err", ":=", "cg", ".", "getCertDuringHandshake", "(", "strings", ".", "ToLower", "(", "clientHello", ".", "ServerName", ")", ",", "true", ",", "true", ")", "\n", "return", "&", "cert", ".", "Certificate", ",", "err", "\n", "}" ]
// GetCertificate gets a certificate to satisfy clientHello. In getting // the certificate, it abides the rules and settings defined in the // Config that matches clientHello.ServerName. It first checks the in- // memory cache, then, if the config enables "OnDemand", it accesses // disk, then accesses the network if it must obtain a new certificate // via ACME. // // This method is safe for use as a tls.Config.GetCertificate callback.
[ "GetCertificate", "gets", "a", "certificate", "to", "satisfy", "clientHello", ".", "In", "getting", "the", "certificate", "it", "abides", "the", "rules", "and", "settings", "defined", "in", "the", "Config", "that", "matches", "clientHello", ".", "ServerName", ".", "It", "first", "checks", "the", "in", "-", "memory", "cache", "then", "if", "the", "config", "enables", "OnDemand", "it", "accesses", "disk", "then", "accesses", "the", "network", "if", "it", "must", "obtain", "a", "new", "certificate", "via", "ACME", ".", "This", "method", "is", "safe", "for", "use", "as", "a", "tls", ".", "Config", ".", "GetCertificate", "callback", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L61-L64
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/handshake.go
checkLimitsForObtainingNewCerts
func (cg configGroup) checkLimitsForObtainingNewCerts(name string, cfg *Config) error { // User can set hard limit for number of certs for the process to issue if cfg.OnDemandState.MaxObtain > 0 && atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= cfg.OnDemandState.MaxObtain { return fmt.Errorf("%s: maximum certificates issued (%d)", name, cfg.OnDemandState.MaxObtain) } // Make sure name hasn't failed a challenge recently failedIssuanceMu.RLock() when, ok := failedIssuance[name] failedIssuanceMu.RUnlock() if ok { return fmt.Errorf("%s: throttled; refusing to issue cert since last attempt on %s failed", name, when.String()) } // Make sure, if we've issued a few certificates already, that we haven't // issued any recently lastIssueTimeMu.Lock() since := time.Since(lastIssueTime) lastIssueTimeMu.Unlock() if atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= 10 && since < 10*time.Minute { return fmt.Errorf("%s: throttled; last certificate was obtained %v ago", name, since) } // 👍Good to go return nil }
go
func (cg configGroup) checkLimitsForObtainingNewCerts(name string, cfg *Config) error { // User can set hard limit for number of certs for the process to issue if cfg.OnDemandState.MaxObtain > 0 && atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= cfg.OnDemandState.MaxObtain { return fmt.Errorf("%s: maximum certificates issued (%d)", name, cfg.OnDemandState.MaxObtain) } // Make sure name hasn't failed a challenge recently failedIssuanceMu.RLock() when, ok := failedIssuance[name] failedIssuanceMu.RUnlock() if ok { return fmt.Errorf("%s: throttled; refusing to issue cert since last attempt on %s failed", name, when.String()) } // Make sure, if we've issued a few certificates already, that we haven't // issued any recently lastIssueTimeMu.Lock() since := time.Since(lastIssueTime) lastIssueTimeMu.Unlock() if atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= 10 && since < 10*time.Minute { return fmt.Errorf("%s: throttled; last certificate was obtained %v ago", name, since) } // 👍Good to go return nil }
[ "func", "(", "cg", "configGroup", ")", "checkLimitsForObtainingNewCerts", "(", "name", "string", ",", "cfg", "*", "Config", ")", "error", "{", "if", "cfg", ".", "OnDemandState", ".", "MaxObtain", ">", "0", "&&", "atomic", ".", "LoadInt32", "(", "&", "cfg", ".", "OnDemandState", ".", "ObtainedCount", ")", ">=", "cfg", ".", "OnDemandState", ".", "MaxObtain", "{", "return", "fmt", ".", "Errorf", "(", "\"%s: maximum certificates issued (%d)\"", ",", "name", ",", "cfg", ".", "OnDemandState", ".", "MaxObtain", ")", "\n", "}", "\n", "failedIssuanceMu", ".", "RLock", "(", ")", "\n", "when", ",", "ok", ":=", "failedIssuance", "[", "name", "]", "\n", "failedIssuanceMu", ".", "RUnlock", "(", ")", "\n", "if", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"%s: throttled; refusing to issue cert since last attempt on %s failed\"", ",", "name", ",", "when", ".", "String", "(", ")", ")", "\n", "}", "\n", "lastIssueTimeMu", ".", "Lock", "(", ")", "\n", "since", ":=", "time", ".", "Since", "(", "lastIssueTime", ")", "\n", "lastIssueTimeMu", ".", "Unlock", "(", ")", "\n", "if", "atomic", ".", "LoadInt32", "(", "&", "cfg", ".", "OnDemandState", ".", "ObtainedCount", ")", ">=", "10", "&&", "since", "<", "10", "*", "time", ".", "Minute", "{", "return", "fmt", ".", "Errorf", "(", "\"%s: throttled; last certificate was obtained %v ago\"", ",", "name", ",", "since", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkLimitsForObtainingNewCerts checks to see if name can be issued right // now according to mitigating factors we keep track of and preferences the // user has set. If a non-nil error is returned, do not issue a new certificate // for name.
[ "checkLimitsForObtainingNewCerts", "checks", "to", "see", "if", "name", "can", "be", "issued", "right", "now", "according", "to", "mitigating", "factors", "we", "keep", "track", "of", "and", "preferences", "the", "user", "has", "set", ".", "If", "a", "non", "-", "nil", "error", "is", "returned", "do", "not", "issue", "a", "new", "certificate", "for", "name", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L130-L156
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/handshake.go
obtainOnDemandCertificate
func (cg configGroup) obtainOnDemandCertificate(name string, cfg *Config) (Certificate, error) { // We must protect this process from happening concurrently, so synchronize. obtainCertWaitChansMu.Lock() wait, ok := obtainCertWaitChans[name] if ok { // lucky us -- another goroutine is already obtaining the certificate. // wait for it to finish obtaining the cert and then we'll use it. obtainCertWaitChansMu.Unlock() <-wait return cg.getCertDuringHandshake(name, true, false) } // looks like it's up to us to do all the work and obtain the cert. // make a chan others can wait on if needed wait = make(chan struct{}) obtainCertWaitChans[name] = wait obtainCertWaitChansMu.Unlock() // do the obtain log.Printf("[INFO] Obtaining new certificate for %s", name) err := cfg.ObtainCert(name, false) // immediately unblock anyone waiting for it; doing this in // a defer would risk deadlock because of the recursive call // to getCertDuringHandshake below when we return! obtainCertWaitChansMu.Lock() close(wait) delete(obtainCertWaitChans, name) obtainCertWaitChansMu.Unlock() if err != nil { // Failed to solve challenge, so don't allow another on-demand // issue for this name to be attempted for a little while. failedIssuanceMu.Lock() failedIssuance[name] = time.Now() go func(name string) { time.Sleep(5 * time.Minute) failedIssuanceMu.Lock() delete(failedIssuance, name) failedIssuanceMu.Unlock() }(name) failedIssuanceMu.Unlock() return Certificate{}, err } // Success - update counters and stuff atomic.AddInt32(&cfg.OnDemandState.ObtainedCount, 1) lastIssueTimeMu.Lock() lastIssueTime = time.Now() lastIssueTimeMu.Unlock() // certificate is already on disk; now just start over to load it and serve it return cg.getCertDuringHandshake(name, true, false) }
go
func (cg configGroup) obtainOnDemandCertificate(name string, cfg *Config) (Certificate, error) { // We must protect this process from happening concurrently, so synchronize. obtainCertWaitChansMu.Lock() wait, ok := obtainCertWaitChans[name] if ok { // lucky us -- another goroutine is already obtaining the certificate. // wait for it to finish obtaining the cert and then we'll use it. obtainCertWaitChansMu.Unlock() <-wait return cg.getCertDuringHandshake(name, true, false) } // looks like it's up to us to do all the work and obtain the cert. // make a chan others can wait on if needed wait = make(chan struct{}) obtainCertWaitChans[name] = wait obtainCertWaitChansMu.Unlock() // do the obtain log.Printf("[INFO] Obtaining new certificate for %s", name) err := cfg.ObtainCert(name, false) // immediately unblock anyone waiting for it; doing this in // a defer would risk deadlock because of the recursive call // to getCertDuringHandshake below when we return! obtainCertWaitChansMu.Lock() close(wait) delete(obtainCertWaitChans, name) obtainCertWaitChansMu.Unlock() if err != nil { // Failed to solve challenge, so don't allow another on-demand // issue for this name to be attempted for a little while. failedIssuanceMu.Lock() failedIssuance[name] = time.Now() go func(name string) { time.Sleep(5 * time.Minute) failedIssuanceMu.Lock() delete(failedIssuance, name) failedIssuanceMu.Unlock() }(name) failedIssuanceMu.Unlock() return Certificate{}, err } // Success - update counters and stuff atomic.AddInt32(&cfg.OnDemandState.ObtainedCount, 1) lastIssueTimeMu.Lock() lastIssueTime = time.Now() lastIssueTimeMu.Unlock() // certificate is already on disk; now just start over to load it and serve it return cg.getCertDuringHandshake(name, true, false) }
[ "func", "(", "cg", "configGroup", ")", "obtainOnDemandCertificate", "(", "name", "string", ",", "cfg", "*", "Config", ")", "(", "Certificate", ",", "error", ")", "{", "obtainCertWaitChansMu", ".", "Lock", "(", ")", "\n", "wait", ",", "ok", ":=", "obtainCertWaitChans", "[", "name", "]", "\n", "if", "ok", "{", "obtainCertWaitChansMu", ".", "Unlock", "(", ")", "\n", "<-", "wait", "\n", "return", "cg", ".", "getCertDuringHandshake", "(", "name", ",", "true", ",", "false", ")", "\n", "}", "\n", "wait", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "obtainCertWaitChans", "[", "name", "]", "=", "wait", "\n", "obtainCertWaitChansMu", ".", "Unlock", "(", ")", "\n", "log", ".", "Printf", "(", "\"[INFO] Obtaining new certificate for %s\"", ",", "name", ")", "\n", "err", ":=", "cfg", ".", "ObtainCert", "(", "name", ",", "false", ")", "\n", "obtainCertWaitChansMu", ".", "Lock", "(", ")", "\n", "close", "(", "wait", ")", "\n", "delete", "(", "obtainCertWaitChans", ",", "name", ")", "\n", "obtainCertWaitChansMu", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "failedIssuanceMu", ".", "Lock", "(", ")", "\n", "failedIssuance", "[", "name", "]", "=", "time", ".", "Now", "(", ")", "\n", "go", "func", "(", "name", "string", ")", "{", "time", ".", "Sleep", "(", "5", "*", "time", ".", "Minute", ")", "\n", "failedIssuanceMu", ".", "Lock", "(", ")", "\n", "delete", "(", "failedIssuance", ",", "name", ")", "\n", "failedIssuanceMu", ".", "Unlock", "(", ")", "\n", "}", "(", "name", ")", "\n", "failedIssuanceMu", ".", "Unlock", "(", ")", "\n", "return", "Certificate", "{", "}", ",", "err", "\n", "}", "\n", "atomic", ".", "AddInt32", "(", "&", "cfg", ".", "OnDemandState", ".", "ObtainedCount", ",", "1", ")", "\n", "lastIssueTimeMu", ".", "Lock", "(", ")", "\n", "lastIssueTime", "=", "time", ".", "Now", "(", ")", "\n", "lastIssueTimeMu", ".", "Unlock", "(", ")", "\n", "return", "cg", ".", "getCertDuringHandshake", "(", "name", ",", "true", ",", "false", ")", "\n", "}" ]
// obtainOnDemandCertificate obtains a certificate for name for the given // name. If another goroutine has already started obtaining a cert for // name, it will wait and use what the other goroutine obtained. // // This function is safe for use by multiple concurrent goroutines.
[ "obtainOnDemandCertificate", "obtains", "a", "certificate", "for", "name", "for", "the", "given", "name", ".", "If", "another", "goroutine", "has", "already", "started", "obtaining", "a", "cert", "for", "name", "it", "will", "wait", "and", "use", "what", "the", "other", "goroutine", "obtained", ".", "This", "function", "is", "safe", "for", "use", "by", "multiple", "concurrent", "goroutines", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L163-L216
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/handshake.go
handshakeMaintenance
func (cg configGroup) handshakeMaintenance(name string, cert Certificate) (Certificate, error) { // Check cert expiration timeLeft := cert.NotAfter.Sub(time.Now().UTC()) if timeLeft < RenewDurationBefore { log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft) return cg.renewDynamicCertificate(name, cert.Config) } // Check OCSP staple validity if cert.OCSP != nil { refreshTime := cert.OCSP.ThisUpdate.Add(cert.OCSP.NextUpdate.Sub(cert.OCSP.ThisUpdate) / 2) if time.Now().After(refreshTime) { err := stapleOCSP(&cert, nil) if err != nil { // An error with OCSP stapling is not the end of the world, and in fact, is // quite common considering not all certs have issuer URLs that support it. log.Printf("[ERROR] Getting OCSP for %s: %v", name, err) } certCacheMu.Lock() certCache[name] = cert certCacheMu.Unlock() } } return cert, nil }
go
func (cg configGroup) handshakeMaintenance(name string, cert Certificate) (Certificate, error) { // Check cert expiration timeLeft := cert.NotAfter.Sub(time.Now().UTC()) if timeLeft < RenewDurationBefore { log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft) return cg.renewDynamicCertificate(name, cert.Config) } // Check OCSP staple validity if cert.OCSP != nil { refreshTime := cert.OCSP.ThisUpdate.Add(cert.OCSP.NextUpdate.Sub(cert.OCSP.ThisUpdate) / 2) if time.Now().After(refreshTime) { err := stapleOCSP(&cert, nil) if err != nil { // An error with OCSP stapling is not the end of the world, and in fact, is // quite common considering not all certs have issuer URLs that support it. log.Printf("[ERROR] Getting OCSP for %s: %v", name, err) } certCacheMu.Lock() certCache[name] = cert certCacheMu.Unlock() } } return cert, nil }
[ "func", "(", "cg", "configGroup", ")", "handshakeMaintenance", "(", "name", "string", ",", "cert", "Certificate", ")", "(", "Certificate", ",", "error", ")", "{", "timeLeft", ":=", "cert", ".", "NotAfter", ".", "Sub", "(", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ")", "\n", "if", "timeLeft", "<", "RenewDurationBefore", "{", "log", ".", "Printf", "(", "\"[INFO] Certificate for %v expires in %v; attempting renewal\"", ",", "cert", ".", "Names", ",", "timeLeft", ")", "\n", "return", "cg", ".", "renewDynamicCertificate", "(", "name", ",", "cert", ".", "Config", ")", "\n", "}", "\n", "if", "cert", ".", "OCSP", "!=", "nil", "{", "refreshTime", ":=", "cert", ".", "OCSP", ".", "ThisUpdate", ".", "Add", "(", "cert", ".", "OCSP", ".", "NextUpdate", ".", "Sub", "(", "cert", ".", "OCSP", ".", "ThisUpdate", ")", "/", "2", ")", "\n", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "refreshTime", ")", "{", "err", ":=", "stapleOCSP", "(", "&", "cert", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"[ERROR] Getting OCSP for %s: %v\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "certCacheMu", ".", "Lock", "(", ")", "\n", "certCache", "[", "name", "]", "=", "cert", "\n", "certCacheMu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "return", "cert", ",", "nil", "\n", "}" ]
// handshakeMaintenance performs a check on cert for expiration and OCSP // validity. // // This function is safe for use by multiple concurrent goroutines.
[ "handshakeMaintenance", "performs", "a", "check", "on", "cert", "for", "expiration", "and", "OCSP", "validity", ".", "This", "function", "is", "safe", "for", "use", "by", "multiple", "concurrent", "goroutines", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L222-L247
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/handshake.go
renewDynamicCertificate
func (cg configGroup) renewDynamicCertificate(name string, cfg *Config) (Certificate, error) { obtainCertWaitChansMu.Lock() wait, ok := obtainCertWaitChans[name] if ok { // lucky us -- another goroutine is already renewing the certificate. // wait for it to finish, then we'll use the new one. obtainCertWaitChansMu.Unlock() <-wait return cg.getCertDuringHandshake(name, true, false) } // looks like it's up to us to do all the work and renew the cert wait = make(chan struct{}) obtainCertWaitChans[name] = wait obtainCertWaitChansMu.Unlock() // do the renew log.Printf("[INFO] Renewing certificate for %s", name) err := cfg.RenewCert(name, false) // immediately unblock anyone waiting for it; doing this in // a defer would risk deadlock because of the recursive call // to getCertDuringHandshake below when we return! obtainCertWaitChansMu.Lock() close(wait) delete(obtainCertWaitChans, name) obtainCertWaitChansMu.Unlock() if err != nil { return Certificate{}, err } return cg.getCertDuringHandshake(name, true, false) }
go
func (cg configGroup) renewDynamicCertificate(name string, cfg *Config) (Certificate, error) { obtainCertWaitChansMu.Lock() wait, ok := obtainCertWaitChans[name] if ok { // lucky us -- another goroutine is already renewing the certificate. // wait for it to finish, then we'll use the new one. obtainCertWaitChansMu.Unlock() <-wait return cg.getCertDuringHandshake(name, true, false) } // looks like it's up to us to do all the work and renew the cert wait = make(chan struct{}) obtainCertWaitChans[name] = wait obtainCertWaitChansMu.Unlock() // do the renew log.Printf("[INFO] Renewing certificate for %s", name) err := cfg.RenewCert(name, false) // immediately unblock anyone waiting for it; doing this in // a defer would risk deadlock because of the recursive call // to getCertDuringHandshake below when we return! obtainCertWaitChansMu.Lock() close(wait) delete(obtainCertWaitChans, name) obtainCertWaitChansMu.Unlock() if err != nil { return Certificate{}, err } return cg.getCertDuringHandshake(name, true, false) }
[ "func", "(", "cg", "configGroup", ")", "renewDynamicCertificate", "(", "name", "string", ",", "cfg", "*", "Config", ")", "(", "Certificate", ",", "error", ")", "{", "obtainCertWaitChansMu", ".", "Lock", "(", ")", "\n", "wait", ",", "ok", ":=", "obtainCertWaitChans", "[", "name", "]", "\n", "if", "ok", "{", "obtainCertWaitChansMu", ".", "Unlock", "(", ")", "\n", "<-", "wait", "\n", "return", "cg", ".", "getCertDuringHandshake", "(", "name", ",", "true", ",", "false", ")", "\n", "}", "\n", "wait", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "obtainCertWaitChans", "[", "name", "]", "=", "wait", "\n", "obtainCertWaitChansMu", ".", "Unlock", "(", ")", "\n", "log", ".", "Printf", "(", "\"[INFO] Renewing certificate for %s\"", ",", "name", ")", "\n", "err", ":=", "cfg", ".", "RenewCert", "(", "name", ",", "false", ")", "\n", "obtainCertWaitChansMu", ".", "Lock", "(", ")", "\n", "close", "(", "wait", ")", "\n", "delete", "(", "obtainCertWaitChans", ",", "name", ")", "\n", "obtainCertWaitChansMu", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Certificate", "{", "}", ",", "err", "\n", "}", "\n", "return", "cg", ".", "getCertDuringHandshake", "(", "name", ",", "true", ",", "false", ")", "\n", "}" ]
// renewDynamicCertificate renews the certificate for name using cfg. It returns the // certificate to use and an error, if any. currentCert may be returned even if an // error occurs, since we perform renewals before they expire and it may still be // usable. name should already be lower-cased before calling this function. // // This function is safe for use by multiple concurrent goroutines.
[ "renewDynamicCertificate", "renews", "the", "certificate", "for", "name", "using", "cfg", ".", "It", "returns", "the", "certificate", "to", "use", "and", "an", "error", "if", "any", ".", "currentCert", "may", "be", "returned", "even", "if", "an", "error", "occurs", "since", "we", "perform", "renewals", "before", "they", "expire", "and", "it", "may", "still", "be", "usable", ".", "name", "should", "already", "be", "lower", "-", "cased", "before", "calling", "this", "function", ".", "This", "function", "is", "safe", "for", "use", "by", "multiple", "concurrent", "goroutines", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/handshake.go#L255-L288
train
inverse-inc/packetfence
go/dhcp/rawClient.go
NewRawClient
func NewRawClient(ifi *net.Interface) (*RawClient, error) { // Open raw socket to send Wake-on-LAN magic packets var cfg raw.Config p, err := raw.ListenPacket(ifi, 0x0806, &cfg) if err != nil { return nil, err } return &RawClient{ ifi: ifi, p: p, }, nil }
go
func NewRawClient(ifi *net.Interface) (*RawClient, error) { // Open raw socket to send Wake-on-LAN magic packets var cfg raw.Config p, err := raw.ListenPacket(ifi, 0x0806, &cfg) if err != nil { return nil, err } return &RawClient{ ifi: ifi, p: p, }, nil }
[ "func", "NewRawClient", "(", "ifi", "*", "net", ".", "Interface", ")", "(", "*", "RawClient", ",", "error", ")", "{", "var", "cfg", "raw", ".", "Config", "\n", "p", ",", "err", ":=", "raw", ".", "ListenPacket", "(", "ifi", ",", "0x0806", ",", "&", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "RawClient", "{", "ifi", ":", "ifi", ",", "p", ":", "p", ",", "}", ",", "nil", "\n", "}" ]
// NewRawClient creates a new RawClient using the specified network interface. // // Note that raw sockets typically require elevated user privileges, such as // the 'root' user on Linux, or the 'SET_CAP_RAW' capability. // // For this reason, it is typically recommended to use the regular Client type // instead, which operates over UDP.
[ "NewRawClient", "creates", "a", "new", "RawClient", "using", "the", "specified", "network", "interface", ".", "Note", "that", "raw", "sockets", "typically", "require", "elevated", "user", "privileges", "such", "as", "the", "root", "user", "on", "Linux", "or", "the", "SET_CAP_RAW", "capability", ".", "For", "this", "reason", "it", "is", "typically", "recommended", "to", "use", "the", "regular", "Client", "type", "instead", "which", "operates", "over", "UDP", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/rawClient.go#L62-L75
train
inverse-inc/packetfence
go/dhcp/rawClient.go
sendDHCP
func (c *RawClient) sendDHCP(target net.HardwareAddr, dhcp []byte, dstIP net.IP, srcIP net.IP) error { proto := 17 udpsrc := uint(67) udpdst := uint(68) udp := udphdr{ src: uint16(udpsrc), dst: uint16(udpdst), } udplen := 8 + len(dhcp) ip := iphdr{ vhl: 0x45, tos: 0, id: 0x0000, // the kernel overwrites id if it is zero off: 0, ttl: 128, proto: uint8(proto), } copy(ip.src[:], srcIP.To4()) copy(ip.dst[:], dstIP.To4()) udp.ulen = uint16(udplen) udp.checksum(&ip, dhcp) totalLen := 20 + udplen ip.iplen = uint16(totalLen) ip.checksum() buf := bytes.NewBuffer([]byte{}) err := binary.Write(buf, binary.BigEndian, &udp) if err != nil { log.Fatal(err) } udpHeader := buf.Bytes() dataWithHeader := append(udpHeader, dhcp...) buff := bytes.NewBuffer([]byte{}) err = binary.Write(buff, binary.BigEndian, &ip) if err != nil { log.Fatal(err) } ipHeader := buff.Bytes() packet := append(ipHeader, dataWithHeader...) // Create Ethernet frame f := &ethernet.Frame{ Destination: target, Source: c.ifi.HardwareAddr, EtherType: ethernet.EtherTypeIPv4, Payload: packet, } fb, err := f.MarshalBinary() if err != nil { return err } // Send packet to target _, err = c.p.WriteTo(fb, &raw.Addr{ HardwareAddr: target, }) return err }
go
func (c *RawClient) sendDHCP(target net.HardwareAddr, dhcp []byte, dstIP net.IP, srcIP net.IP) error { proto := 17 udpsrc := uint(67) udpdst := uint(68) udp := udphdr{ src: uint16(udpsrc), dst: uint16(udpdst), } udplen := 8 + len(dhcp) ip := iphdr{ vhl: 0x45, tos: 0, id: 0x0000, // the kernel overwrites id if it is zero off: 0, ttl: 128, proto: uint8(proto), } copy(ip.src[:], srcIP.To4()) copy(ip.dst[:], dstIP.To4()) udp.ulen = uint16(udplen) udp.checksum(&ip, dhcp) totalLen := 20 + udplen ip.iplen = uint16(totalLen) ip.checksum() buf := bytes.NewBuffer([]byte{}) err := binary.Write(buf, binary.BigEndian, &udp) if err != nil { log.Fatal(err) } udpHeader := buf.Bytes() dataWithHeader := append(udpHeader, dhcp...) buff := bytes.NewBuffer([]byte{}) err = binary.Write(buff, binary.BigEndian, &ip) if err != nil { log.Fatal(err) } ipHeader := buff.Bytes() packet := append(ipHeader, dataWithHeader...) // Create Ethernet frame f := &ethernet.Frame{ Destination: target, Source: c.ifi.HardwareAddr, EtherType: ethernet.EtherTypeIPv4, Payload: packet, } fb, err := f.MarshalBinary() if err != nil { return err } // Send packet to target _, err = c.p.WriteTo(fb, &raw.Addr{ HardwareAddr: target, }) return err }
[ "func", "(", "c", "*", "RawClient", ")", "sendDHCP", "(", "target", "net", ".", "HardwareAddr", ",", "dhcp", "[", "]", "byte", ",", "dstIP", "net", ".", "IP", ",", "srcIP", "net", ".", "IP", ")", "error", "{", "proto", ":=", "17", "\n", "udpsrc", ":=", "uint", "(", "67", ")", "\n", "udpdst", ":=", "uint", "(", "68", ")", "\n", "udp", ":=", "udphdr", "{", "src", ":", "uint16", "(", "udpsrc", ")", ",", "dst", ":", "uint16", "(", "udpdst", ")", ",", "}", "\n", "udplen", ":=", "8", "+", "len", "(", "dhcp", ")", "\n", "ip", ":=", "iphdr", "{", "vhl", ":", "0x45", ",", "tos", ":", "0", ",", "id", ":", "0x0000", ",", "off", ":", "0", ",", "ttl", ":", "128", ",", "proto", ":", "uint8", "(", "proto", ")", ",", "}", "\n", "copy", "(", "ip", ".", "src", "[", ":", "]", ",", "srcIP", ".", "To4", "(", ")", ")", "\n", "copy", "(", "ip", ".", "dst", "[", ":", "]", ",", "dstIP", ".", "To4", "(", ")", ")", "\n", "udp", ".", "ulen", "=", "uint16", "(", "udplen", ")", "\n", "udp", ".", "checksum", "(", "&", "ip", ",", "dhcp", ")", "\n", "totalLen", ":=", "20", "+", "udplen", "\n", "ip", ".", "iplen", "=", "uint16", "(", "totalLen", ")", "\n", "ip", ".", "checksum", "(", ")", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "{", "}", ")", "\n", "err", ":=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "BigEndian", ",", "&", "udp", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "udpHeader", ":=", "buf", ".", "Bytes", "(", ")", "\n", "dataWithHeader", ":=", "append", "(", "udpHeader", ",", "dhcp", "...", ")", "\n", "buff", ":=", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "{", "}", ")", "\n", "err", "=", "binary", ".", "Write", "(", "buff", ",", "binary", ".", "BigEndian", ",", "&", "ip", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "ipHeader", ":=", "buff", ".", "Bytes", "(", ")", "\n", "packet", ":=", "append", "(", "ipHeader", ",", "dataWithHeader", "...", ")", "\n", "f", ":=", "&", "ethernet", ".", "Frame", "{", "Destination", ":", "target", ",", "Source", ":", "c", ".", "ifi", ".", "HardwareAddr", ",", "EtherType", ":", "ethernet", ".", "EtherTypeIPv4", ",", "Payload", ":", "packet", ",", "}", "\n", "fb", ",", "err", ":=", "f", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "p", ".", "WriteTo", "(", "fb", ",", "&", "raw", ".", "Addr", "{", "HardwareAddr", ":", "target", ",", "}", ")", "\n", "return", "err", "\n", "}" ]
// sendDHCP create a udp packet and stores it in an // Ethernet frame, and sends the frame over a raw socket to attempt to wake // a machine.
[ "sendDHCP", "create", "a", "udp", "packet", "and", "stores", "it", "in", "an", "Ethernet", "frame", "and", "sends", "the", "frame", "over", "a", "raw", "socket", "to", "attempt", "to", "wake", "a", "machine", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/rawClient.go#L85-L153
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
setupEdns0Opt
func setupEdns0Opt(r *dns.Msg) *dns.OPT { o := r.IsEdns0() if o == nil { r.SetEdns0(4096, true) o = r.IsEdns0() } return o }
go
func setupEdns0Opt(r *dns.Msg) *dns.OPT { o := r.IsEdns0() if o == nil { r.SetEdns0(4096, true) o = r.IsEdns0() } return o }
[ "func", "setupEdns0Opt", "(", "r", "*", "dns", ".", "Msg", ")", "*", "dns", ".", "OPT", "{", "o", ":=", "r", ".", "IsEdns0", "(", ")", "\n", "if", "o", "==", "nil", "{", "r", ".", "SetEdns0", "(", "4096", ",", "true", ")", "\n", "o", "=", "r", ".", "IsEdns0", "(", ")", "\n", "}", "\n", "return", "o", "\n", "}" ]
// setupEdns0Opt will retrieve the EDNS0 OPT or create it if it does not exist
[ "setupEdns0Opt", "will", "retrieve", "the", "EDNS0", "OPT", "or", "create", "it", "if", "it", "does", "not", "exist" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L39-L46
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
Rewrite
func (rule *edns0LocalRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { result := RewriteIgnored o := setupEdns0Opt(r) found := false for _, s := range o.Option { switch e := s.(type) { case *dns.EDNS0_LOCAL: if rule.code == e.Code { if rule.action == Replace || rule.action == Set { e.Data = rule.data result = RewriteDone } found = true break } } } // add option if not found if !found && (rule.action == Append || rule.action == Set) { o.SetDo() var opt dns.EDNS0_LOCAL opt.Code = rule.code opt.Data = rule.data o.Option = append(o.Option, &opt) result = RewriteDone } return result }
go
func (rule *edns0LocalRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { result := RewriteIgnored o := setupEdns0Opt(r) found := false for _, s := range o.Option { switch e := s.(type) { case *dns.EDNS0_LOCAL: if rule.code == e.Code { if rule.action == Replace || rule.action == Set { e.Data = rule.data result = RewriteDone } found = true break } } } // add option if not found if !found && (rule.action == Append || rule.action == Set) { o.SetDo() var opt dns.EDNS0_LOCAL opt.Code = rule.code opt.Data = rule.data o.Option = append(o.Option, &opt) result = RewriteDone } return result }
[ "func", "(", "rule", "*", "edns0LocalRule", ")", "Rewrite", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", "Result", "{", "result", ":=", "RewriteIgnored", "\n", "o", ":=", "setupEdns0Opt", "(", "r", ")", "\n", "found", ":=", "false", "\n", "for", "_", ",", "s", ":=", "range", "o", ".", "Option", "{", "switch", "e", ":=", "s", ".", "(", "type", ")", "{", "case", "*", "dns", ".", "EDNS0_LOCAL", ":", "if", "rule", ".", "code", "==", "e", ".", "Code", "{", "if", "rule", ".", "action", "==", "Replace", "||", "rule", ".", "action", "==", "Set", "{", "e", ".", "Data", "=", "rule", ".", "data", "\n", "result", "=", "RewriteDone", "\n", "}", "\n", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "!", "found", "&&", "(", "rule", ".", "action", "==", "Append", "||", "rule", ".", "action", "==", "Set", ")", "{", "o", ".", "SetDo", "(", ")", "\n", "var", "opt", "dns", ".", "EDNS0_LOCAL", "\n", "opt", ".", "Code", "=", "rule", ".", "code", "\n", "opt", ".", "Data", "=", "rule", ".", "data", "\n", "o", ".", "Option", "=", "append", "(", "o", ".", "Option", ",", "&", "opt", ")", "\n", "result", "=", "RewriteDone", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Rewrite will alter the request EDNS0 local options
[ "Rewrite", "will", "alter", "the", "request", "EDNS0", "local", "options" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L82-L111
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
newEdns0Rule
func newEdns0Rule(mode string, args ...string) (Rule, error) { if len(args) < 2 { return nil, fmt.Errorf("too few arguments for an EDNS0 rule") } ruleType := strings.ToLower(args[0]) action := strings.ToLower(args[1]) switch action { case Append: case Replace: case Set: default: return nil, fmt.Errorf("invalid action: %q", action) } switch ruleType { case "local": if len(args) != 4 { return nil, fmt.Errorf("EDNS0 local rules require exactly three args") } //Check for variable option if strings.HasPrefix(args[3], "{") && strings.HasSuffix(args[3], "}") { return newEdns0VariableRule(mode, action, args[2], args[3]) } return newEdns0LocalRule(mode, action, args[2], args[3]) case "nsid": if len(args) != 2 { return nil, fmt.Errorf("EDNS0 NSID rules do not accept args") } return &edns0NsidRule{mode: mode, action: action}, nil case "subnet": if len(args) != 4 { return nil, fmt.Errorf("EDNS0 subnet rules require exactly three args") } return newEdns0SubnetRule(mode, action, args[2], args[3]) default: return nil, fmt.Errorf("invalid rule type %q", ruleType) } }
go
func newEdns0Rule(mode string, args ...string) (Rule, error) { if len(args) < 2 { return nil, fmt.Errorf("too few arguments for an EDNS0 rule") } ruleType := strings.ToLower(args[0]) action := strings.ToLower(args[1]) switch action { case Append: case Replace: case Set: default: return nil, fmt.Errorf("invalid action: %q", action) } switch ruleType { case "local": if len(args) != 4 { return nil, fmt.Errorf("EDNS0 local rules require exactly three args") } //Check for variable option if strings.HasPrefix(args[3], "{") && strings.HasSuffix(args[3], "}") { return newEdns0VariableRule(mode, action, args[2], args[3]) } return newEdns0LocalRule(mode, action, args[2], args[3]) case "nsid": if len(args) != 2 { return nil, fmt.Errorf("EDNS0 NSID rules do not accept args") } return &edns0NsidRule{mode: mode, action: action}, nil case "subnet": if len(args) != 4 { return nil, fmt.Errorf("EDNS0 subnet rules require exactly three args") } return newEdns0SubnetRule(mode, action, args[2], args[3]) default: return nil, fmt.Errorf("invalid rule type %q", ruleType) } }
[ "func", "newEdns0Rule", "(", "mode", "string", ",", "args", "...", "string", ")", "(", "Rule", ",", "error", ")", "{", "if", "len", "(", "args", ")", "<", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"too few arguments for an EDNS0 rule\"", ")", "\n", "}", "\n", "ruleType", ":=", "strings", ".", "ToLower", "(", "args", "[", "0", "]", ")", "\n", "action", ":=", "strings", ".", "ToLower", "(", "args", "[", "1", "]", ")", "\n", "switch", "action", "{", "case", "Append", ":", "case", "Replace", ":", "case", "Set", ":", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid action: %q\"", ",", "action", ")", "\n", "}", "\n", "switch", "ruleType", "{", "case", "\"local\"", ":", "if", "len", "(", "args", ")", "!=", "4", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"EDNS0 local rules require exactly three args\"", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "args", "[", "3", "]", ",", "\"{\"", ")", "&&", "strings", ".", "HasSuffix", "(", "args", "[", "3", "]", ",", "\"}\"", ")", "{", "return", "newEdns0VariableRule", "(", "mode", ",", "action", ",", "args", "[", "2", "]", ",", "args", "[", "3", "]", ")", "\n", "}", "\n", "return", "newEdns0LocalRule", "(", "mode", ",", "action", ",", "args", "[", "2", "]", ",", "args", "[", "3", "]", ")", "\n", "case", "\"nsid\"", ":", "if", "len", "(", "args", ")", "!=", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"EDNS0 NSID rules do not accept args\"", ")", "\n", "}", "\n", "return", "&", "edns0NsidRule", "{", "mode", ":", "mode", ",", "action", ":", "action", "}", ",", "nil", "\n", "case", "\"subnet\"", ":", "if", "len", "(", "args", ")", "!=", "4", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"EDNS0 subnet rules require exactly three args\"", ")", "\n", "}", "\n", "return", "newEdns0SubnetRule", "(", "mode", ",", "action", ",", "args", "[", "2", "]", ",", "args", "[", "3", "]", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid rule type %q\"", ",", "ruleType", ")", "\n", "}", "\n", "}" ]
// newEdns0Rule creates an EDNS0 rule of the appropriate type based on the args
[ "newEdns0Rule", "creates", "an", "EDNS0", "rule", "of", "the", "appropriate", "type", "based", "on", "the", "args" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L119-L157
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
newEdns0VariableRule
func newEdns0VariableRule(mode, action, code, variable string) (*edns0VariableRule, error) { c, err := strconv.ParseUint(code, 0, 16) if err != nil { return nil, err } //Validate if !isValidVariable(variable) { return nil, fmt.Errorf("unsupported variable name %q", variable) } return &edns0VariableRule{mode: mode, action: action, code: uint16(c), variable: variable}, nil }
go
func newEdns0VariableRule(mode, action, code, variable string) (*edns0VariableRule, error) { c, err := strconv.ParseUint(code, 0, 16) if err != nil { return nil, err } //Validate if !isValidVariable(variable) { return nil, fmt.Errorf("unsupported variable name %q", variable) } return &edns0VariableRule{mode: mode, action: action, code: uint16(c), variable: variable}, nil }
[ "func", "newEdns0VariableRule", "(", "mode", ",", "action", ",", "code", ",", "variable", "string", ")", "(", "*", "edns0VariableRule", ",", "error", ")", "{", "c", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "code", ",", "0", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "isValidVariable", "(", "variable", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unsupported variable name %q\"", ",", "variable", ")", "\n", "}", "\n", "return", "&", "edns0VariableRule", "{", "mode", ":", "mode", ",", "action", ":", "action", ",", "code", ":", "uint16", "(", "c", ")", ",", "variable", ":", "variable", "}", ",", "nil", "\n", "}" ]
// newEdns0VariableRule creates an EDNS0 rule that handles variable substitution
[ "newEdns0VariableRule", "creates", "an", "EDNS0", "rule", "that", "handles", "variable", "substitution" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L176-L186
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
ruleData
func (rule *edns0VariableRule) ruleData(w dns.ResponseWriter, r *dns.Msg) ([]byte, error) { req := request.Request{W: w, Req: r} switch rule.variable { case queryName: //Query name is written as ascii string return []byte(req.QName()), nil case queryType: return rule.uint16ToWire(req.QType()), nil case clientIP: return rule.ipToWire(req.Family(), req.IP()) case clientPort: return rule.portToWire(req.Port()) case protocol: // Proto is written as ascii string return []byte(req.Proto()), nil case serverIP: ip, _, err := net.SplitHostPort(w.LocalAddr().String()) if err != nil { ip = w.RemoteAddr().String() } return rule.ipToWire(rule.family(w.RemoteAddr()), ip) case serverPort: _, port, err := net.SplitHostPort(w.LocalAddr().String()) if err != nil { port = "0" } return rule.portToWire(port) } return nil, fmt.Errorf("Unable to extract data for variable %s", rule.variable) }
go
func (rule *edns0VariableRule) ruleData(w dns.ResponseWriter, r *dns.Msg) ([]byte, error) { req := request.Request{W: w, Req: r} switch rule.variable { case queryName: //Query name is written as ascii string return []byte(req.QName()), nil case queryType: return rule.uint16ToWire(req.QType()), nil case clientIP: return rule.ipToWire(req.Family(), req.IP()) case clientPort: return rule.portToWire(req.Port()) case protocol: // Proto is written as ascii string return []byte(req.Proto()), nil case serverIP: ip, _, err := net.SplitHostPort(w.LocalAddr().String()) if err != nil { ip = w.RemoteAddr().String() } return rule.ipToWire(rule.family(w.RemoteAddr()), ip) case serverPort: _, port, err := net.SplitHostPort(w.LocalAddr().String()) if err != nil { port = "0" } return rule.portToWire(port) } return nil, fmt.Errorf("Unable to extract data for variable %s", rule.variable) }
[ "func", "(", "rule", "*", "edns0VariableRule", ")", "ruleData", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "req", ":=", "request", ".", "Request", "{", "W", ":", "w", ",", "Req", ":", "r", "}", "\n", "switch", "rule", ".", "variable", "{", "case", "queryName", ":", "return", "[", "]", "byte", "(", "req", ".", "QName", "(", ")", ")", ",", "nil", "\n", "case", "queryType", ":", "return", "rule", ".", "uint16ToWire", "(", "req", ".", "QType", "(", ")", ")", ",", "nil", "\n", "case", "clientIP", ":", "return", "rule", ".", "ipToWire", "(", "req", ".", "Family", "(", ")", ",", "req", ".", "IP", "(", ")", ")", "\n", "case", "clientPort", ":", "return", "rule", ".", "portToWire", "(", "req", ".", "Port", "(", ")", ")", "\n", "case", "protocol", ":", "return", "[", "]", "byte", "(", "req", ".", "Proto", "(", ")", ")", ",", "nil", "\n", "case", "serverIP", ":", "ip", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "w", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "ip", "=", "w", ".", "RemoteAddr", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "return", "rule", ".", "ipToWire", "(", "rule", ".", "family", "(", "w", ".", "RemoteAddr", "(", ")", ")", ",", "ip", ")", "\n", "case", "serverPort", ":", "_", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "w", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "port", "=", "\"0\"", "\n", "}", "\n", "return", "rule", ".", "portToWire", "(", "port", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to extract data for variable %s\"", ",", "rule", ".", "variable", ")", "\n", "}" ]
// ruleData returns the data specified by the variable
[ "ruleData", "returns", "the", "data", "specified", "by", "the", "variable" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L233-L270
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
fillEcsData
func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg, ecs *dns.EDNS0_SUBNET) error { req := request.Request{W: w, Req: r} family := req.Family() if (family != 1) && (family != 2) { return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family") } ecs.Family = uint16(family) ecs.SourceScope = 0 ipAddr := req.IP() switch family { case 1: ipv4Mask := net.CIDRMask(int(rule.v4BitMaskLen), 32) ipv4Addr := net.ParseIP(ipAddr) ecs.SourceNetmask = rule.v4BitMaskLen ecs.Address = ipv4Addr.Mask(ipv4Mask).To4() case 2: ipv6Mask := net.CIDRMask(int(rule.v6BitMaskLen), 128) ipv6Addr := net.ParseIP(ipAddr) ecs.SourceNetmask = rule.v6BitMaskLen ecs.Address = ipv6Addr.Mask(ipv6Mask).To16() } return nil }
go
func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg, ecs *dns.EDNS0_SUBNET) error { req := request.Request{W: w, Req: r} family := req.Family() if (family != 1) && (family != 2) { return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family") } ecs.Family = uint16(family) ecs.SourceScope = 0 ipAddr := req.IP() switch family { case 1: ipv4Mask := net.CIDRMask(int(rule.v4BitMaskLen), 32) ipv4Addr := net.ParseIP(ipAddr) ecs.SourceNetmask = rule.v4BitMaskLen ecs.Address = ipv4Addr.Mask(ipv4Mask).To4() case 2: ipv6Mask := net.CIDRMask(int(rule.v6BitMaskLen), 128) ipv6Addr := net.ParseIP(ipAddr) ecs.SourceNetmask = rule.v6BitMaskLen ecs.Address = ipv6Addr.Mask(ipv6Mask).To16() } return nil }
[ "func", "(", "rule", "*", "edns0SubnetRule", ")", "fillEcsData", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ",", "ecs", "*", "dns", ".", "EDNS0_SUBNET", ")", "error", "{", "req", ":=", "request", ".", "Request", "{", "W", ":", "w", ",", "Req", ":", "r", "}", "\n", "family", ":=", "req", ".", "Family", "(", ")", "\n", "if", "(", "family", "!=", "1", ")", "&&", "(", "family", "!=", "2", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to fill data for EDNS0 subnet due to invalid IP family\"", ")", "\n", "}", "\n", "ecs", ".", "Family", "=", "uint16", "(", "family", ")", "\n", "ecs", ".", "SourceScope", "=", "0", "\n", "ipAddr", ":=", "req", ".", "IP", "(", ")", "\n", "switch", "family", "{", "case", "1", ":", "ipv4Mask", ":=", "net", ".", "CIDRMask", "(", "int", "(", "rule", ".", "v4BitMaskLen", ")", ",", "32", ")", "\n", "ipv4Addr", ":=", "net", ".", "ParseIP", "(", "ipAddr", ")", "\n", "ecs", ".", "SourceNetmask", "=", "rule", ".", "v4BitMaskLen", "\n", "ecs", ".", "Address", "=", "ipv4Addr", ".", "Mask", "(", "ipv4Mask", ")", ".", "To4", "(", ")", "\n", "case", "2", ":", "ipv6Mask", ":=", "net", ".", "CIDRMask", "(", "int", "(", "rule", ".", "v6BitMaskLen", ")", ",", "128", ")", "\n", "ipv6Addr", ":=", "net", ".", "ParseIP", "(", "ipAddr", ")", "\n", "ecs", ".", "SourceNetmask", "=", "rule", ".", "v6BitMaskLen", "\n", "ecs", ".", "Address", "=", "ipv6Addr", ".", "Mask", "(", "ipv6Mask", ")", ".", "To16", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// fillEcsData sets the subnet data into the ecs option
[ "fillEcsData", "sets", "the", "subnet", "data", "into", "the", "ecs", "option" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L362-L388
train
inverse-inc/packetfence
go/coredns/plugin/rewrite/edns0.go
Rewrite
func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { result := RewriteIgnored o := setupEdns0Opt(r) found := false for _, s := range o.Option { switch e := s.(type) { case *dns.EDNS0_SUBNET: if rule.action == Replace || rule.action == Set { if rule.fillEcsData(w, r, e) == nil { result = RewriteDone } } found = true break } } // add option if not found if !found && (rule.action == Append || rule.action == Set) { o.SetDo() opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET} if rule.fillEcsData(w, r, &opt) == nil { o.Option = append(o.Option, &opt) result = RewriteDone } } return result }
go
func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result { result := RewriteIgnored o := setupEdns0Opt(r) found := false for _, s := range o.Option { switch e := s.(type) { case *dns.EDNS0_SUBNET: if rule.action == Replace || rule.action == Set { if rule.fillEcsData(w, r, e) == nil { result = RewriteDone } } found = true break } } // add option if not found if !found && (rule.action == Append || rule.action == Set) { o.SetDo() opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET} if rule.fillEcsData(w, r, &opt) == nil { o.Option = append(o.Option, &opt) result = RewriteDone } } return result }
[ "func", "(", "rule", "*", "edns0SubnetRule", ")", "Rewrite", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", "Result", "{", "result", ":=", "RewriteIgnored", "\n", "o", ":=", "setupEdns0Opt", "(", "r", ")", "\n", "found", ":=", "false", "\n", "for", "_", ",", "s", ":=", "range", "o", ".", "Option", "{", "switch", "e", ":=", "s", ".", "(", "type", ")", "{", "case", "*", "dns", ".", "EDNS0_SUBNET", ":", "if", "rule", ".", "action", "==", "Replace", "||", "rule", ".", "action", "==", "Set", "{", "if", "rule", ".", "fillEcsData", "(", "w", ",", "r", ",", "e", ")", "==", "nil", "{", "result", "=", "RewriteDone", "\n", "}", "\n", "}", "\n", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "&&", "(", "rule", ".", "action", "==", "Append", "||", "rule", ".", "action", "==", "Set", ")", "{", "o", ".", "SetDo", "(", ")", "\n", "opt", ":=", "dns", ".", "EDNS0_SUBNET", "{", "Code", ":", "dns", ".", "EDNS0SUBNET", "}", "\n", "if", "rule", ".", "fillEcsData", "(", "w", ",", "r", ",", "&", "opt", ")", "==", "nil", "{", "o", ".", "Option", "=", "append", "(", "o", ".", "Option", ",", "&", "opt", ")", "\n", "result", "=", "RewriteDone", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Rewrite will alter the request EDNS0 subnet option
[ "Rewrite", "will", "alter", "the", "request", "EDNS0", "subnet", "option" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/rewrite/edns0.go#L391-L419
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
setup
func setup(c *caddy.Controller) error { ctx := log.LoggerNewContext(context.Background()) pfsso, err := buildPfssoHandler(ctx) if err != nil { return err } // Declare all pfconfig resources that will be necessary pfconfigdriver.PfconfigPool.AddRefreshable(ctx, &firewallsso.Firewalls) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Interfaces.ManagementNetwork) httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { pfsso.Next = next return pfsso }) return nil }
go
func setup(c *caddy.Controller) error { ctx := log.LoggerNewContext(context.Background()) pfsso, err := buildPfssoHandler(ctx) if err != nil { return err } // Declare all pfconfig resources that will be necessary pfconfigdriver.PfconfigPool.AddRefreshable(ctx, &firewallsso.Firewalls) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Interfaces.ManagementNetwork) httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { pfsso.Next = next return pfsso }) return nil }
[ "func", "setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "ctx", ":=", "log", ".", "LoggerNewContext", "(", "context", ".", "Background", "(", ")", ")", "\n", "pfsso", ",", "err", ":=", "buildPfssoHandler", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddRefreshable", "(", "ctx", ",", "&", "firewallsso", ".", "Firewalls", ")", "\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&", "pfconfigdriver", ".", "Config", ".", "Interfaces", ".", "ManagementNetwork", ")", "\n", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "pfsso", ".", "Next", "=", "next", "\n", "return", "pfsso", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Setup the pfsso middleware // Also loads the pfconfig resources and registers them in the pool
[ "Setup", "the", "pfsso", "middleware", "Also", "loads", "the", "pfconfig", "resources", "and", "registers", "them", "in", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L41-L60
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
buildPfssoHandler
func buildPfssoHandler(ctx context.Context) (PfssoHandler, error) { pfsso := PfssoHandler{} pfsso.updateCache = cache.New(1*time.Hour, 30*time.Second) router := httprouter.New() router.POST("/api/v1/firewall_sso/update", pfsso.handleUpdate) router.POST("/api/v1/firewall_sso/start", pfsso.handleStart) router.POST("/api/v1/firewall_sso/stop", pfsso.handleStop) pfsso.router = router return pfsso, nil }
go
func buildPfssoHandler(ctx context.Context) (PfssoHandler, error) { pfsso := PfssoHandler{} pfsso.updateCache = cache.New(1*time.Hour, 30*time.Second) router := httprouter.New() router.POST("/api/v1/firewall_sso/update", pfsso.handleUpdate) router.POST("/api/v1/firewall_sso/start", pfsso.handleStart) router.POST("/api/v1/firewall_sso/stop", pfsso.handleStop) pfsso.router = router return pfsso, nil }
[ "func", "buildPfssoHandler", "(", "ctx", "context", ".", "Context", ")", "(", "PfssoHandler", ",", "error", ")", "{", "pfsso", ":=", "PfssoHandler", "{", "}", "\n", "pfsso", ".", "updateCache", "=", "cache", ".", "New", "(", "1", "*", "time", ".", "Hour", ",", "30", "*", "time", ".", "Second", ")", "\n", "router", ":=", "httprouter", ".", "New", "(", ")", "\n", "router", ".", "POST", "(", "\"/api/v1/firewall_sso/update\"", ",", "pfsso", ".", "handleUpdate", ")", "\n", "router", ".", "POST", "(", "\"/api/v1/firewall_sso/start\"", ",", "pfsso", ".", "handleStart", ")", "\n", "router", ".", "POST", "(", "\"/api/v1/firewall_sso/stop\"", ",", "pfsso", ".", "handleStop", ")", "\n", "pfsso", ".", "router", "=", "router", "\n", "return", "pfsso", ",", "nil", "\n", "}" ]
// Build the PfssoHandler which will initialize the cache and instantiate the router along with its routes
[ "Build", "the", "PfssoHandler", "which", "will", "initialize", "the", "cache", "and", "instantiate", "the", "router", "along", "with", "its", "routes" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L63-L77
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
validateInfo
func (h PfssoHandler) validateInfo(ctx context.Context, info map[string]string) error { required := []string{"ip", "mac", "username", "role"} for _, k := range required { if _, ok := info[k]; !ok { return errors.New(fmt.Sprintf("Missing %s in request", k)) } } return nil }
go
func (h PfssoHandler) validateInfo(ctx context.Context, info map[string]string) error { required := []string{"ip", "mac", "username", "role"} for _, k := range required { if _, ok := info[k]; !ok { return errors.New(fmt.Sprintf("Missing %s in request", k)) } } return nil }
[ "func", "(", "h", "PfssoHandler", ")", "validateInfo", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "error", "{", "required", ":=", "[", "]", "string", "{", "\"ip\"", ",", "\"mac\"", ",", "\"username\"", ",", "\"role\"", "}", "\n", "for", "_", ",", "k", ":=", "range", "required", "{", "if", "_", ",", "ok", ":=", "info", "[", "k", "]", ";", "!", "ok", "{", "return", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"Missing %s in request\"", ",", "k", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate that all the required fields are there in the request
[ "Validate", "that", "all", "the", "required", "fields", "are", "there", "in", "the", "request" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L110-L118
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
spawnSso
func (h PfssoHandler) spawnSso(ctx context.Context, firewall firewallsso.FirewallSSOInt, info map[string]string, f func(info map[string]string) (bool, error)) { // Perform a copy of the information hash before spawning the goroutine infoCopy := map[string]string{} for k, v := range info { infoCopy[k] = v } go func() { defer panichandler.Standard(ctx) sent, err := f(infoCopy) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error while sending SSO to %s: %s"+firewall.GetFirewallSSO(ctx).PfconfigHashNS, err)) } if sent { log.LoggerWContext(ctx).Debug("Sent SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS) } else { log.LoggerWContext(ctx).Debug("Didn't send SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS) } }() }
go
func (h PfssoHandler) spawnSso(ctx context.Context, firewall firewallsso.FirewallSSOInt, info map[string]string, f func(info map[string]string) (bool, error)) { // Perform a copy of the information hash before spawning the goroutine infoCopy := map[string]string{} for k, v := range info { infoCopy[k] = v } go func() { defer panichandler.Standard(ctx) sent, err := f(infoCopy) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error while sending SSO to %s: %s"+firewall.GetFirewallSSO(ctx).PfconfigHashNS, err)) } if sent { log.LoggerWContext(ctx).Debug("Sent SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS) } else { log.LoggerWContext(ctx).Debug("Didn't send SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS) } }() }
[ "func", "(", "h", "PfssoHandler", ")", "spawnSso", "(", "ctx", "context", ".", "Context", ",", "firewall", "firewallsso", ".", "FirewallSSOInt", ",", "info", "map", "[", "string", "]", "string", ",", "f", "func", "(", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", ")", "{", "infoCopy", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "info", "{", "infoCopy", "[", "k", "]", "=", "v", "\n", "}", "\n", "go", "func", "(", ")", "{", "defer", "panichandler", ".", "Standard", "(", "ctx", ")", "\n", "sent", ",", "err", ":=", "f", "(", "infoCopy", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Error while sending SSO to %s: %s\"", "+", "firewall", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "PfconfigHashNS", ",", "err", ")", ")", "\n", "}", "\n", "if", "sent", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"Sent SSO to \"", "+", "firewall", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "PfconfigHashNS", ")", "\n", "}", "else", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"Didn't send SSO to \"", "+", "firewall", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "PfconfigHashNS", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Spawn an async SSO request for a specific firewall
[ "Spawn", "an", "async", "SSO", "request", "for", "a", "specific", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L121-L141
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
addInfoToContext
func (h PfssoHandler) addInfoToContext(ctx context.Context, info map[string]string) context.Context { return log.AddToLogContext(ctx, "username", info["username"], "ip", info["ip"], "mac", info["mac"], "role", info["role"]) }
go
func (h PfssoHandler) addInfoToContext(ctx context.Context, info map[string]string) context.Context { return log.AddToLogContext(ctx, "username", info["username"], "ip", info["ip"], "mac", info["mac"], "role", info["role"]) }
[ "func", "(", "h", "PfssoHandler", ")", "addInfoToContext", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "context", ".", "Context", "{", "return", "log", ".", "AddToLogContext", "(", "ctx", ",", "\"username\"", ",", "info", "[", "\"username\"", "]", ",", "\"ip\"", ",", "info", "[", "\"ip\"", "]", ",", "\"mac\"", ",", "info", "[", "\"mac\"", "]", ",", "\"role\"", ",", "info", "[", "\"role\"", "]", ")", "\n", "}" ]
// Add the info in the request to the log context
[ "Add", "the", "info", "in", "the", "request", "to", "the", "log", "context" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L144-L146
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
handleUpdate
func (h PfssoHandler) handleUpdate(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleUpdate") info, timeout, err := h.parseSsoRequest(ctx, r.Body) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } ctx = h.addInfoToContext(ctx, info) var shouldStart bool for _, firewall := range firewallsso.Firewalls.Structs { cacheKey := firewall.GetFirewallSSO(ctx).PfconfigHashNS + "|ip|" + info["ip"] + "|username|" + info["username"] + "|role|" + info["role"] // Check whether or not this firewall has cache updates // Then check if an entry in the cache exists // If it does exist, we don't send a Start // Otherwise, we add an entry in the cache // Note that this has a race condition between the cache.Get and the cache.Set but it is acceptable since worst case will be that 2 SSO will be sent if both requests came in at that same nanosecond if firewall.ShouldCacheUpdates(ctx) { if _, found := h.updateCache.Get(cacheKey); !found { var cacheTimeout int if firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx) != 0 { cacheTimeout = firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx) } else if timeout != 0 { cacheTimeout = timeout / 2 } else { log.LoggerWContext(ctx).Error("Impossible to cache updates. There is no cache timeout in the firewall and no timeout defined in the request.") } if cacheTimeout != 0 { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Caching SSO for %d seconds", cacheTimeout)) h.updateCache.Set(cacheKey, 1, time.Duration(cacheTimeout)*time.Second) } shouldStart = true } } else { shouldStart = true } if shouldStart { //Creating a shallow copy here so the anonymous function has the right reference firewall := firewall h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) { return firewallsso.ExecuteStart(ctx, firewall, info, timeout) }) } else { log.LoggerWContext(ctx).Debug("Determined that SSO start was not necessary for this update") } } w.WriteHeader(http.StatusAccepted) }
go
func (h PfssoHandler) handleUpdate(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleUpdate") info, timeout, err := h.parseSsoRequest(ctx, r.Body) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } ctx = h.addInfoToContext(ctx, info) var shouldStart bool for _, firewall := range firewallsso.Firewalls.Structs { cacheKey := firewall.GetFirewallSSO(ctx).PfconfigHashNS + "|ip|" + info["ip"] + "|username|" + info["username"] + "|role|" + info["role"] // Check whether or not this firewall has cache updates // Then check if an entry in the cache exists // If it does exist, we don't send a Start // Otherwise, we add an entry in the cache // Note that this has a race condition between the cache.Get and the cache.Set but it is acceptable since worst case will be that 2 SSO will be sent if both requests came in at that same nanosecond if firewall.ShouldCacheUpdates(ctx) { if _, found := h.updateCache.Get(cacheKey); !found { var cacheTimeout int if firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx) != 0 { cacheTimeout = firewall.GetFirewallSSO(ctx).GetCacheTimeout(ctx) } else if timeout != 0 { cacheTimeout = timeout / 2 } else { log.LoggerWContext(ctx).Error("Impossible to cache updates. There is no cache timeout in the firewall and no timeout defined in the request.") } if cacheTimeout != 0 { log.LoggerWContext(ctx).Debug(fmt.Sprintf("Caching SSO for %d seconds", cacheTimeout)) h.updateCache.Set(cacheKey, 1, time.Duration(cacheTimeout)*time.Second) } shouldStart = true } } else { shouldStart = true } if shouldStart { //Creating a shallow copy here so the anonymous function has the right reference firewall := firewall h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) { return firewallsso.ExecuteStart(ctx, firewall, info, timeout) }) } else { log.LoggerWContext(ctx).Debug("Determined that SSO start was not necessary for this update") } } w.WriteHeader(http.StatusAccepted) }
[ "func", "(", "h", "PfssoHandler", ")", "handleUpdate", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "p", "httprouter", ".", "Params", ")", "{", "ctx", ":=", "r", ".", "Context", "(", ")", "\n", "defer", "statsd", ".", "NewStatsDTiming", "(", "ctx", ")", ".", "Send", "(", "\"PfssoHandler.handleUpdate\"", ")", "\n", "info", ",", "timeout", ",", "err", ":=", "h", ".", "parseSsoRequest", "(", "ctx", ",", "r", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprint", "(", "err", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "ctx", "=", "h", ".", "addInfoToContext", "(", "ctx", ",", "info", ")", "\n", "var", "shouldStart", "bool", "\n", "for", "_", ",", "firewall", ":=", "range", "firewallsso", ".", "Firewalls", ".", "Structs", "{", "cacheKey", ":=", "firewall", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "PfconfigHashNS", "+", "\"|ip|\"", "+", "info", "[", "\"ip\"", "]", "+", "\"|username|\"", "+", "info", "[", "\"username\"", "]", "+", "\"|role|\"", "+", "info", "[", "\"role\"", "]", "\n", "if", "firewall", ".", "ShouldCacheUpdates", "(", "ctx", ")", "{", "if", "_", ",", "found", ":=", "h", ".", "updateCache", ".", "Get", "(", "cacheKey", ")", ";", "!", "found", "{", "var", "cacheTimeout", "int", "\n", "if", "firewall", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "GetCacheTimeout", "(", "ctx", ")", "!=", "0", "{", "cacheTimeout", "=", "firewall", ".", "GetFirewallSSO", "(", "ctx", ")", ".", "GetCacheTimeout", "(", "ctx", ")", "\n", "}", "else", "if", "timeout", "!=", "0", "{", "cacheTimeout", "=", "timeout", "/", "2", "\n", "}", "else", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "\"Impossible to cache updates. There is no cache timeout in the firewall and no timeout defined in the request.\"", ")", "\n", "}", "\n", "if", "cacheTimeout", "!=", "0", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "fmt", ".", "Sprintf", "(", "\"Caching SSO for %d seconds\"", ",", "cacheTimeout", ")", ")", "\n", "h", ".", "updateCache", ".", "Set", "(", "cacheKey", ",", "1", ",", "time", ".", "Duration", "(", "cacheTimeout", ")", "*", "time", ".", "Second", ")", "\n", "}", "\n", "shouldStart", "=", "true", "\n", "}", "\n", "}", "else", "{", "shouldStart", "=", "true", "\n", "}", "\n", "if", "shouldStart", "{", "firewall", ":=", "firewall", "\n", "h", ".", "spawnSso", "(", "ctx", ",", "firewall", ",", "info", ",", "func", "(", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "return", "firewallsso", ".", "ExecuteStart", "(", "ctx", ",", "firewall", ",", "info", ",", "timeout", ")", "\n", "}", ")", "\n", "}", "else", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"Determined that SSO start was not necessary for this update\"", ")", "\n", "}", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusAccepted", ")", "\n", "}" ]
// Handle an update action for pfsso // If the firewall has cached updates enabled, it will handle it here // The cache is in-memory so that means that a restart of the process will clear the cached updates cache
[ "Handle", "an", "update", "action", "for", "pfsso", "If", "the", "firewall", "has", "cached", "updates", "enabled", "it", "will", "handle", "it", "here", "The", "cache", "is", "in", "-", "memory", "so", "that", "means", "that", "a", "restart", "of", "the", "process", "will", "clear", "the", "cached", "updates", "cache" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L151-L207
train
inverse-inc/packetfence
go/caddy/pfsso/pfsso.go
handleStop
func (h PfssoHandler) handleStop(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleStop") info, _, err := h.parseSsoRequest(ctx, r.Body) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } ctx = h.addInfoToContext(ctx, info) for _, firewall := range firewallsso.Firewalls.Structs { //Creating a shallow copy here so the anonymous function has the right reference firewall := firewall h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) { return firewallsso.ExecuteStop(ctx, firewall, info) }) } w.WriteHeader(http.StatusAccepted) }
go
func (h PfssoHandler) handleStop(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleStop") info, _, err := h.parseSsoRequest(ctx, r.Body) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } ctx = h.addInfoToContext(ctx, info) for _, firewall := range firewallsso.Firewalls.Structs { //Creating a shallow copy here so the anonymous function has the right reference firewall := firewall h.spawnSso(ctx, firewall, info, func(info map[string]string) (bool, error) { return firewallsso.ExecuteStop(ctx, firewall, info) }) } w.WriteHeader(http.StatusAccepted) }
[ "func", "(", "h", "PfssoHandler", ")", "handleStop", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "p", "httprouter", ".", "Params", ")", "{", "ctx", ":=", "r", ".", "Context", "(", ")", "\n", "defer", "statsd", ".", "NewStatsDTiming", "(", "ctx", ")", ".", "Send", "(", "\"PfssoHandler.handleStop\"", ")", "\n", "info", ",", "_", ",", "err", ":=", "h", ".", "parseSsoRequest", "(", "ctx", ",", "r", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprint", "(", "err", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "ctx", "=", "h", ".", "addInfoToContext", "(", "ctx", ",", "info", ")", "\n", "for", "_", ",", "firewall", ":=", "range", "firewallsso", ".", "Firewalls", ".", "Structs", "{", "firewall", ":=", "firewall", "\n", "h", ".", "spawnSso", "(", "ctx", ",", "firewall", ",", "info", ",", "func", "(", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "return", "firewallsso", ".", "ExecuteStop", "(", "ctx", ",", "firewall", ",", "info", ")", "\n", "}", ")", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusAccepted", ")", "\n", "}" ]
// Handle an SSO stop
[ "Handle", "an", "SSO", "stop" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfsso/pfsso.go#L234-L255
train
inverse-inc/packetfence
go/coredns/plugin/hosts/hosts.go
a
func a(zone string, ips []net.IP) []dns.RR { answers := []dns.RR{} for _, ip := range ips { r := new(dns.A) r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 3600} r.A = ip answers = append(answers, r) } return answers }
go
func a(zone string, ips []net.IP) []dns.RR { answers := []dns.RR{} for _, ip := range ips { r := new(dns.A) r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 3600} r.A = ip answers = append(answers, r) } return answers }
[ "func", "a", "(", "zone", "string", ",", "ips", "[", "]", "net", ".", "IP", ")", "[", "]", "dns", ".", "RR", "{", "answers", ":=", "[", "]", "dns", ".", "RR", "{", "}", "\n", "for", "_", ",", "ip", ":=", "range", "ips", "{", "r", ":=", "new", "(", "dns", ".", "A", ")", "\n", "r", ".", "Hdr", "=", "dns", ".", "RR_Header", "{", "Name", ":", "zone", ",", "Rrtype", ":", "dns", ".", "TypeA", ",", "Class", ":", "dns", ".", "ClassINET", ",", "Ttl", ":", "3600", "}", "\n", "r", ".", "A", "=", "ip", "\n", "answers", "=", "append", "(", "answers", ",", "r", ")", "\n", "}", "\n", "return", "answers", "\n", "}" ]
// a takes a slice of net.IPs and returns a slice of A RRs.
[ "a", "takes", "a", "slice", "of", "net", ".", "IPs", "and", "returns", "a", "slice", "of", "A", "RRs", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/hosts/hosts.go#L100-L110
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
NewFileStorage
func NewFileStorage(caURL *url.URL) (Storage, error) { return &FileStorage{ Path: filepath.Join(storageBasePath, caURL.Host), nameLocks: make(map[string]*sync.WaitGroup), }, nil }
go
func NewFileStorage(caURL *url.URL) (Storage, error) { return &FileStorage{ Path: filepath.Join(storageBasePath, caURL.Host), nameLocks: make(map[string]*sync.WaitGroup), }, nil }
[ "func", "NewFileStorage", "(", "caURL", "*", "url", ".", "URL", ")", "(", "Storage", ",", "error", ")", "{", "return", "&", "FileStorage", "{", "Path", ":", "filepath", ".", "Join", "(", "storageBasePath", ",", "caURL", ".", "Host", ")", ",", "nameLocks", ":", "make", "(", "map", "[", "string", "]", "*", "sync", ".", "WaitGroup", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewFileStorage is a StorageConstructor function that creates a new // Storage instance backed by the local disk. The resulting Storage // instance is guaranteed to be non-nil if there is no error.
[ "NewFileStorage", "is", "a", "StorageConstructor", "function", "that", "creates", "a", "new", "Storage", "instance", "backed", "by", "the", "local", "disk", ".", "The", "resulting", "Storage", "instance", "is", "guaranteed", "to", "be", "non", "-", "nil", "if", "there", "is", "no", "error", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L26-L31
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
site
func (s *FileStorage) site(domain string) string { domain = strings.ToLower(domain) return filepath.Join(s.sites(), domain) }
go
func (s *FileStorage) site(domain string) string { domain = strings.ToLower(domain) return filepath.Join(s.sites(), domain) }
[ "func", "(", "s", "*", "FileStorage", ")", "site", "(", "domain", "string", ")", "string", "{", "domain", "=", "strings", ".", "ToLower", "(", "domain", ")", "\n", "return", "filepath", ".", "Join", "(", "s", ".", "sites", "(", ")", ",", "domain", ")", "\n", "}" ]
// site returns the path to the folder containing assets for domain.
[ "site", "returns", "the", "path", "to", "the", "folder", "containing", "assets", "for", "domain", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L48-L51
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
user
func (s *FileStorage) user(email string) string { if email == "" { email = emptyEmail } email = strings.ToLower(email) return filepath.Join(s.users(), email) }
go
func (s *FileStorage) user(email string) string { if email == "" { email = emptyEmail } email = strings.ToLower(email) return filepath.Join(s.users(), email) }
[ "func", "(", "s", "*", "FileStorage", ")", "user", "(", "email", "string", ")", "string", "{", "if", "email", "==", "\"\"", "{", "email", "=", "emptyEmail", "\n", "}", "\n", "email", "=", "strings", ".", "ToLower", "(", "email", ")", "\n", "return", "filepath", ".", "Join", "(", "s", ".", "users", "(", ")", ",", "email", ")", "\n", "}" ]
// user gets the account folder for the user with email
[ "user", "gets", "the", "account", "folder", "for", "the", "user", "with", "email" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L77-L83
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
emailUsername
func emailUsername(email string) string { at := strings.Index(email, "@") if at == -1 { return email } else if at == 0 { return email[1:] } return email[:at] }
go
func emailUsername(email string) string { at := strings.Index(email, "@") if at == -1 { return email } else if at == 0 { return email[1:] } return email[:at] }
[ "func", "emailUsername", "(", "email", "string", ")", "string", "{", "at", ":=", "strings", ".", "Index", "(", "email", ",", "\"@\"", ")", "\n", "if", "at", "==", "-", "1", "{", "return", "email", "\n", "}", "else", "if", "at", "==", "0", "{", "return", "email", "[", "1", ":", "]", "\n", "}", "\n", "return", "email", "[", ":", "at", "]", "\n", "}" ]
// emailUsername returns the username portion of an email address (part before // '@') or the original input if it can't find the "@" symbol.
[ "emailUsername", "returns", "the", "username", "portion", "of", "an", "email", "address", "(", "part", "before" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L87-L95
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
userRegFile
func (s *FileStorage) userRegFile(email string) string { if email == "" { email = emptyEmail } email = strings.ToLower(email) fileName := emailUsername(email) if fileName == "" { fileName = "registration" } return filepath.Join(s.user(email), fileName+".json") }
go
func (s *FileStorage) userRegFile(email string) string { if email == "" { email = emptyEmail } email = strings.ToLower(email) fileName := emailUsername(email) if fileName == "" { fileName = "registration" } return filepath.Join(s.user(email), fileName+".json") }
[ "func", "(", "s", "*", "FileStorage", ")", "userRegFile", "(", "email", "string", ")", "string", "{", "if", "email", "==", "\"\"", "{", "email", "=", "emptyEmail", "\n", "}", "\n", "email", "=", "strings", ".", "ToLower", "(", "email", ")", "\n", "fileName", ":=", "emailUsername", "(", "email", ")", "\n", "if", "fileName", "==", "\"\"", "{", "fileName", "=", "\"registration\"", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "s", ".", "user", "(", "email", ")", ",", "fileName", "+", "\".json\"", ")", "\n", "}" ]
// userRegFile gets the path to the registration file for the user with the // given email address.
[ "userRegFile", "gets", "the", "path", "to", "the", "registration", "file", "for", "the", "user", "with", "the", "given", "email", "address", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L99-L109
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
readFile
func (s *FileStorage) readFile(file string) ([]byte, error) { b, err := ioutil.ReadFile(file) if os.IsNotExist(err) { return nil, ErrNotExist(err) } return b, err }
go
func (s *FileStorage) readFile(file string) ([]byte, error) { b, err := ioutil.ReadFile(file) if os.IsNotExist(err) { return nil, ErrNotExist(err) } return b, err }
[ "func", "(", "s", "*", "FileStorage", ")", "readFile", "(", "file", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "ErrNotExist", "(", "err", ")", "\n", "}", "\n", "return", "b", ",", "err", "\n", "}" ]
// readFile abstracts a simple ioutil.ReadFile, making sure to return an // ErrNotExist instance when the file is not found.
[ "readFile", "abstracts", "a", "simple", "ioutil", ".", "ReadFile", "making", "sure", "to", "return", "an", "ErrNotExist", "instance", "when", "the", "file", "is", "not", "found", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L127-L133
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
SiteExists
func (s *FileStorage) SiteExists(domain string) (bool, error) { _, err := os.Stat(s.siteCertFile(domain)) if os.IsNotExist(err) { return false, nil } else if err != nil { return false, err } _, err = os.Stat(s.siteKeyFile(domain)) if err != nil { return false, err } return true, nil }
go
func (s *FileStorage) SiteExists(domain string) (bool, error) { _, err := os.Stat(s.siteCertFile(domain)) if os.IsNotExist(err) { return false, nil } else if err != nil { return false, err } _, err = os.Stat(s.siteKeyFile(domain)) if err != nil { return false, err } return true, nil }
[ "func", "(", "s", "*", "FileStorage", ")", "SiteExists", "(", "domain", "string", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "s", ".", "siteCertFile", "(", "domain", ")", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "s", ".", "siteKeyFile", "(", "domain", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// SiteExists implements Storage.SiteExists by checking for the presence of // cert and key files.
[ "SiteExists", "implements", "Storage", ".", "SiteExists", "by", "checking", "for", "the", "presence", "of", "cert", "and", "key", "files", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L137-L150
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
LoadSite
func (s *FileStorage) LoadSite(domain string) (*SiteData, error) { var err error siteData := new(SiteData) siteData.Cert, err = s.readFile(s.siteCertFile(domain)) if err != nil { return nil, err } siteData.Key, err = s.readFile(s.siteKeyFile(domain)) if err != nil { return nil, err } siteData.Meta, err = s.readFile(s.siteMetaFile(domain)) if err != nil { return nil, err } return siteData, nil }
go
func (s *FileStorage) LoadSite(domain string) (*SiteData, error) { var err error siteData := new(SiteData) siteData.Cert, err = s.readFile(s.siteCertFile(domain)) if err != nil { return nil, err } siteData.Key, err = s.readFile(s.siteKeyFile(domain)) if err != nil { return nil, err } siteData.Meta, err = s.readFile(s.siteMetaFile(domain)) if err != nil { return nil, err } return siteData, nil }
[ "func", "(", "s", "*", "FileStorage", ")", "LoadSite", "(", "domain", "string", ")", "(", "*", "SiteData", ",", "error", ")", "{", "var", "err", "error", "\n", "siteData", ":=", "new", "(", "SiteData", ")", "\n", "siteData", ".", "Cert", ",", "err", "=", "s", ".", "readFile", "(", "s", ".", "siteCertFile", "(", "domain", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "siteData", ".", "Key", ",", "err", "=", "s", ".", "readFile", "(", "s", ".", "siteKeyFile", "(", "domain", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "siteData", ".", "Meta", ",", "err", "=", "s", ".", "readFile", "(", "s", ".", "siteMetaFile", "(", "domain", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "siteData", ",", "nil", "\n", "}" ]
// LoadSite implements Storage.LoadSite by loading it from disk. If it is not // present, an instance of ErrNotExist is returned.
[ "LoadSite", "implements", "Storage", ".", "LoadSite", "by", "loading", "it", "from", "disk", ".", "If", "it", "is", "not", "present", "an", "instance", "of", "ErrNotExist", "is", "returned", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L154-L170
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
StoreSite
func (s *FileStorage) StoreSite(domain string, data *SiteData) error { err := os.MkdirAll(s.site(domain), 0700) if err != nil { return fmt.Errorf("making site directory: %v", err) } err = ioutil.WriteFile(s.siteCertFile(domain), data.Cert, 0600) if err != nil { return fmt.Errorf("writing certificate file: %v", err) } err = ioutil.WriteFile(s.siteKeyFile(domain), data.Key, 0600) if err != nil { return fmt.Errorf("writing key file: %v", err) } err = ioutil.WriteFile(s.siteMetaFile(domain), data.Meta, 0600) if err != nil { return fmt.Errorf("writing cert meta file: %v", err) } return nil }
go
func (s *FileStorage) StoreSite(domain string, data *SiteData) error { err := os.MkdirAll(s.site(domain), 0700) if err != nil { return fmt.Errorf("making site directory: %v", err) } err = ioutil.WriteFile(s.siteCertFile(domain), data.Cert, 0600) if err != nil { return fmt.Errorf("writing certificate file: %v", err) } err = ioutil.WriteFile(s.siteKeyFile(domain), data.Key, 0600) if err != nil { return fmt.Errorf("writing key file: %v", err) } err = ioutil.WriteFile(s.siteMetaFile(domain), data.Meta, 0600) if err != nil { return fmt.Errorf("writing cert meta file: %v", err) } return nil }
[ "func", "(", "s", "*", "FileStorage", ")", "StoreSite", "(", "domain", "string", ",", "data", "*", "SiteData", ")", "error", "{", "err", ":=", "os", ".", "MkdirAll", "(", "s", ".", "site", "(", "domain", ")", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"making site directory: %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "s", ".", "siteCertFile", "(", "domain", ")", ",", "data", ".", "Cert", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"writing certificate file: %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "s", ".", "siteKeyFile", "(", "domain", ")", ",", "data", ".", "Key", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"writing key file: %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "s", ".", "siteMetaFile", "(", "domain", ")", ",", "data", ".", "Meta", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"writing cert meta file: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StoreSite implements Storage.StoreSite by writing it to disk. The base // directories needed for the file are automatically created as needed.
[ "StoreSite", "implements", "Storage", ".", "StoreSite", "by", "writing", "it", "to", "disk", ".", "The", "base", "directories", "needed", "for", "the", "file", "are", "automatically", "created", "as", "needed", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L174-L192
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
DeleteSite
func (s *FileStorage) DeleteSite(domain string) error { err := os.Remove(s.siteCertFile(domain)) if err != nil { if os.IsNotExist(err) { return ErrNotExist(err) } return err } return nil }
go
func (s *FileStorage) DeleteSite(domain string) error { err := os.Remove(s.siteCertFile(domain)) if err != nil { if os.IsNotExist(err) { return ErrNotExist(err) } return err } return nil }
[ "func", "(", "s", "*", "FileStorage", ")", "DeleteSite", "(", "domain", "string", ")", "error", "{", "err", ":=", "os", ".", "Remove", "(", "s", ".", "siteCertFile", "(", "domain", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "ErrNotExist", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteSite implements Storage.DeleteSite by deleting just the cert from // disk. If it is not present, an instance of ErrNotExist is returned.
[ "DeleteSite", "implements", "Storage", ".", "DeleteSite", "by", "deleting", "just", "the", "cert", "from", "disk", ".", "If", "it", "is", "not", "present", "an", "instance", "of", "ErrNotExist", "is", "returned", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L196-L205
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
LoadUser
func (s *FileStorage) LoadUser(email string) (*UserData, error) { var err error userData := new(UserData) userData.Reg, err = s.readFile(s.userRegFile(email)) if err != nil { return nil, err } userData.Key, err = s.readFile(s.userKeyFile(email)) if err != nil { return nil, err } return userData, nil }
go
func (s *FileStorage) LoadUser(email string) (*UserData, error) { var err error userData := new(UserData) userData.Reg, err = s.readFile(s.userRegFile(email)) if err != nil { return nil, err } userData.Key, err = s.readFile(s.userKeyFile(email)) if err != nil { return nil, err } return userData, nil }
[ "func", "(", "s", "*", "FileStorage", ")", "LoadUser", "(", "email", "string", ")", "(", "*", "UserData", ",", "error", ")", "{", "var", "err", "error", "\n", "userData", ":=", "new", "(", "UserData", ")", "\n", "userData", ".", "Reg", ",", "err", "=", "s", ".", "readFile", "(", "s", ".", "userRegFile", "(", "email", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "userData", ".", "Key", ",", "err", "=", "s", ".", "readFile", "(", "s", ".", "userKeyFile", "(", "email", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "userData", ",", "nil", "\n", "}" ]
// LoadUser implements Storage.LoadUser by loading it from disk. If it is not // present, an instance of ErrNotExist is returned.
[ "LoadUser", "implements", "Storage", ".", "LoadUser", "by", "loading", "it", "from", "disk", ".", "If", "it", "is", "not", "present", "an", "instance", "of", "ErrNotExist", "is", "returned", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L209-L221
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
StoreUser
func (s *FileStorage) StoreUser(email string, data *UserData) error { err := os.MkdirAll(s.user(email), 0700) if err != nil { return fmt.Errorf("making user directory: %v", err) } err = ioutil.WriteFile(s.userRegFile(email), data.Reg, 0600) if err != nil { return fmt.Errorf("writing user registration file: %v", err) } err = ioutil.WriteFile(s.userKeyFile(email), data.Key, 0600) if err != nil { return fmt.Errorf("writing user key file: %v", err) } return nil }
go
func (s *FileStorage) StoreUser(email string, data *UserData) error { err := os.MkdirAll(s.user(email), 0700) if err != nil { return fmt.Errorf("making user directory: %v", err) } err = ioutil.WriteFile(s.userRegFile(email), data.Reg, 0600) if err != nil { return fmt.Errorf("writing user registration file: %v", err) } err = ioutil.WriteFile(s.userKeyFile(email), data.Key, 0600) if err != nil { return fmt.Errorf("writing user key file: %v", err) } return nil }
[ "func", "(", "s", "*", "FileStorage", ")", "StoreUser", "(", "email", "string", ",", "data", "*", "UserData", ")", "error", "{", "err", ":=", "os", ".", "MkdirAll", "(", "s", ".", "user", "(", "email", ")", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"making user directory: %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "s", ".", "userRegFile", "(", "email", ")", ",", "data", ".", "Reg", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"writing user registration file: %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "s", ".", "userKeyFile", "(", "email", ")", ",", "data", ".", "Key", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"writing user key file: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StoreUser implements Storage.StoreUser by writing it to disk. The base // directories needed for the file are automatically created as needed.
[ "StoreUser", "implements", "Storage", ".", "StoreUser", "by", "writing", "it", "to", "disk", ".", "The", "base", "directories", "needed", "for", "the", "file", "are", "automatically", "created", "as", "needed", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L225-L239
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
TryLock
func (s *FileStorage) TryLock(name string) (Waiter, error) { s.nameLocksMu.Lock() defer s.nameLocksMu.Unlock() wg, ok := s.nameLocks[name] if ok { // lock already obtained, let caller wait on it return wg, nil } // caller gets lock wg = new(sync.WaitGroup) wg.Add(1) s.nameLocks[name] = wg return nil, nil }
go
func (s *FileStorage) TryLock(name string) (Waiter, error) { s.nameLocksMu.Lock() defer s.nameLocksMu.Unlock() wg, ok := s.nameLocks[name] if ok { // lock already obtained, let caller wait on it return wg, nil } // caller gets lock wg = new(sync.WaitGroup) wg.Add(1) s.nameLocks[name] = wg return nil, nil }
[ "func", "(", "s", "*", "FileStorage", ")", "TryLock", "(", "name", "string", ")", "(", "Waiter", ",", "error", ")", "{", "s", ".", "nameLocksMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "nameLocksMu", ".", "Unlock", "(", ")", "\n", "wg", ",", "ok", ":=", "s", ".", "nameLocks", "[", "name", "]", "\n", "if", "ok", "{", "return", "wg", ",", "nil", "\n", "}", "\n", "wg", "=", "new", "(", "sync", ".", "WaitGroup", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "s", ".", "nameLocks", "[", "name", "]", "=", "wg", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// TryLock attempts to get a lock for name, otherwise it returns // a Waiter value to wait until the other process is finished.
[ "TryLock", "attempts", "to", "get", "a", "lock", "for", "name", "otherwise", "it", "returns", "a", "Waiter", "value", "to", "wait", "until", "the", "other", "process", "is", "finished", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L243-L256
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
Unlock
func (s *FileStorage) Unlock(name string) error { s.nameLocksMu.Lock() defer s.nameLocksMu.Unlock() wg, ok := s.nameLocks[name] if !ok { return fmt.Errorf("FileStorage: no lock to release for %s", name) } wg.Done() delete(s.nameLocks, name) return nil }
go
func (s *FileStorage) Unlock(name string) error { s.nameLocksMu.Lock() defer s.nameLocksMu.Unlock() wg, ok := s.nameLocks[name] if !ok { return fmt.Errorf("FileStorage: no lock to release for %s", name) } wg.Done() delete(s.nameLocks, name) return nil }
[ "func", "(", "s", "*", "FileStorage", ")", "Unlock", "(", "name", "string", ")", "error", "{", "s", ".", "nameLocksMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "nameLocksMu", ".", "Unlock", "(", ")", "\n", "wg", ",", "ok", ":=", "s", ".", "nameLocks", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"FileStorage: no lock to release for %s\"", ",", "name", ")", "\n", "}", "\n", "wg", ".", "Done", "(", ")", "\n", "delete", "(", "s", ".", "nameLocks", ",", "name", ")", "\n", "return", "nil", "\n", "}" ]
// Unlock unlocks name.
[ "Unlock", "unlocks", "name", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L259-L269
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/filestorage.go
MostRecentUserEmail
func (s *FileStorage) MostRecentUserEmail() string { userDirs, err := ioutil.ReadDir(s.users()) if err != nil { return "" } var mostRecent os.FileInfo for _, dir := range userDirs { if !dir.IsDir() { continue } if mostRecent == nil || dir.ModTime().After(mostRecent.ModTime()) { mostRecent = dir } } if mostRecent != nil { return mostRecent.Name() } return "" }
go
func (s *FileStorage) MostRecentUserEmail() string { userDirs, err := ioutil.ReadDir(s.users()) if err != nil { return "" } var mostRecent os.FileInfo for _, dir := range userDirs { if !dir.IsDir() { continue } if mostRecent == nil || dir.ModTime().After(mostRecent.ModTime()) { mostRecent = dir } } if mostRecent != nil { return mostRecent.Name() } return "" }
[ "func", "(", "s", "*", "FileStorage", ")", "MostRecentUserEmail", "(", ")", "string", "{", "userDirs", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "s", ".", "users", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", "\n", "}", "\n", "var", "mostRecent", "os", ".", "FileInfo", "\n", "for", "_", ",", "dir", ":=", "range", "userDirs", "{", "if", "!", "dir", ".", "IsDir", "(", ")", "{", "continue", "\n", "}", "\n", "if", "mostRecent", "==", "nil", "||", "dir", ".", "ModTime", "(", ")", ".", "After", "(", "mostRecent", ".", "ModTime", "(", ")", ")", "{", "mostRecent", "=", "dir", "\n", "}", "\n", "}", "\n", "if", "mostRecent", "!=", "nil", "{", "return", "mostRecent", ".", "Name", "(", ")", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// MostRecentUserEmail implements Storage.MostRecentUserEmail by finding the // most recently written sub directory in the users' directory. It is named // after the email address. This corresponds to the most recent call to // StoreUser.
[ "MostRecentUserEmail", "implements", "Storage", ".", "MostRecentUserEmail", "by", "finding", "the", "most", "recently", "written", "sub", "directory", "in", "the", "users", "directory", ".", "It", "is", "named", "after", "the", "email", "address", ".", "This", "corresponds", "to", "the", "most", "recent", "call", "to", "StoreUser", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/filestorage.go#L275-L293
train
inverse-inc/packetfence
go/caddy/pfipset/pfipset.go
setup
func setup(c *caddy.Controller) error { ctx := log.LoggerNewContext(context.Background()) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Cluster.HostsIp) pfipset, err := buildPfipsetHandler(ctx) if err != nil { return err } httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { pfipset.Next = next return pfipset }) return nil }
go
func setup(c *caddy.Controller) error { ctx := log.LoggerNewContext(context.Background()) pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Cluster.HostsIp) pfipset, err := buildPfipsetHandler(ctx) if err != nil { return err } httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { pfipset.Next = next return pfipset }) return nil }
[ "func", "setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "ctx", ":=", "log", ".", "LoggerNewContext", "(", "context", ".", "Background", "(", ")", ")", "\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&", "pfconfigdriver", ".", "Config", ".", "Cluster", ".", "HostsIp", ")", "\n", "pfipset", ",", "err", ":=", "buildPfipsetHandler", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "pfipset", ".", "Next", "=", "next", "\n", "return", "pfipset", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Setup the pfipset middleware // Also loads the pfconfig resources and registers them in the pool
[ "Setup", "the", "pfipset", "middleware", "Also", "loads", "the", "pfconfig", "resources", "and", "registers", "them", "in", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfipset/pfipset.go#L44-L61
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/extensions/ext.go
resourceExists
func resourceExists(root, path string) bool { _, err := os.Stat(root + path) // technically we should use os.IsNotExist(err) // but we don't handle any other kinds of errors anyway return err == nil }
go
func resourceExists(root, path string) bool { _, err := os.Stat(root + path) // technically we should use os.IsNotExist(err) // but we don't handle any other kinds of errors anyway return err == nil }
[ "func", "resourceExists", "(", "root", ",", "path", "string", ")", "bool", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "root", "+", "path", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// resourceExists returns true if the file specified at // root + path exists; false otherwise.
[ "resourceExists", "returns", "true", "if", "the", "file", "specified", "at", "root", "+", "path", "exists", ";", "false", "otherwise", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/extensions/ext.go#L47-L52
train