repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
koding/kite
kontrol/kontrol.go
registerSelf
func (k *Kontrol) registerSelf() { value := &kontrolprotocol.RegisterValue{ URL: k.Kite.Config.KontrolURL, } // change if the user wants something different if k.RegisterURL != "" { value.URL = k.RegisterURL } keyPair, err := k.KeyPair() if err != nil { if err != errNoSelfKeyPair { k.log.Error("%s", err) } // If Kontrol does not hold any key pairs that was used // to generate its kitekey or no kitekey is defined, // use a dummy entry in order to register the kontrol. keyPair = &KeyPair{ Public: "kontrol-self", Private: "kontrol-self", } if id, err := uuid.NewV4(); err == nil { keyPair.ID = id.String() if err := k.keyPair.AddKey(keyPair); err != nil { k.log.Error("%s", err) } } else { k.log.Error("%s", err) } } if pair, err := k.keyPair.GetKeyFromPublic(keyPair.Public); err == nil { keyPair = pair } value.KeyID = keyPair.ID // Register first by adding the value to the storage. We don't return any // error because we need to know why kontrol doesn't register itself if err := k.storage.Add(k.Kite.Kite(), value); err != nil { k.log.Error("%s", err) } for { select { case <-k.closed: return default: if err := k.storage.Update(k.Kite.Kite(), value); err != nil { k.log.Error("%s", err) time.Sleep(time.Second) continue } time.Sleep(HeartbeatDelay + HeartbeatInterval) } } }
go
func (k *Kontrol) registerSelf() { value := &kontrolprotocol.RegisterValue{ URL: k.Kite.Config.KontrolURL, } // change if the user wants something different if k.RegisterURL != "" { value.URL = k.RegisterURL } keyPair, err := k.KeyPair() if err != nil { if err != errNoSelfKeyPair { k.log.Error("%s", err) } // If Kontrol does not hold any key pairs that was used // to generate its kitekey or no kitekey is defined, // use a dummy entry in order to register the kontrol. keyPair = &KeyPair{ Public: "kontrol-self", Private: "kontrol-self", } if id, err := uuid.NewV4(); err == nil { keyPair.ID = id.String() if err := k.keyPair.AddKey(keyPair); err != nil { k.log.Error("%s", err) } } else { k.log.Error("%s", err) } } if pair, err := k.keyPair.GetKeyFromPublic(keyPair.Public); err == nil { keyPair = pair } value.KeyID = keyPair.ID // Register first by adding the value to the storage. We don't return any // error because we need to know why kontrol doesn't register itself if err := k.storage.Add(k.Kite.Kite(), value); err != nil { k.log.Error("%s", err) } for { select { case <-k.closed: return default: if err := k.storage.Update(k.Kite.Kite(), value); err != nil { k.log.Error("%s", err) time.Sleep(time.Second) continue } time.Sleep(HeartbeatDelay + HeartbeatInterval) } } }
[ "func", "(", "k", "*", "Kontrol", ")", "registerSelf", "(", ")", "{", "value", ":=", "&", "kontrolprotocol", ".", "RegisterValue", "{", "URL", ":", "k", ".", "Kite", ".", "Config", ".", "KontrolURL", ",", "}", "\n\n", "// change if the user wants something different", "if", "k", ".", "RegisterURL", "!=", "\"", "\"", "{", "value", ".", "URL", "=", "k", ".", "RegisterURL", "\n", "}", "\n\n", "keyPair", ",", "err", ":=", "k", ".", "KeyPair", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "errNoSelfKeyPair", "{", "k", ".", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// If Kontrol does not hold any key pairs that was used", "// to generate its kitekey or no kitekey is defined,", "// use a dummy entry in order to register the kontrol.", "keyPair", "=", "&", "KeyPair", "{", "Public", ":", "\"", "\"", ",", "Private", ":", "\"", "\"", ",", "}", "\n\n", "if", "id", ",", "err", ":=", "uuid", ".", "NewV4", "(", ")", ";", "err", "==", "nil", "{", "keyPair", ".", "ID", "=", "id", ".", "String", "(", ")", "\n\n", "if", "err", ":=", "k", ".", "keyPair", ".", "AddKey", "(", "keyPair", ")", ";", "err", "!=", "nil", "{", "k", ".", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "k", ".", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "pair", ",", "err", ":=", "k", ".", "keyPair", ".", "GetKeyFromPublic", "(", "keyPair", ".", "Public", ")", ";", "err", "==", "nil", "{", "keyPair", "=", "pair", "\n", "}", "\n\n", "value", ".", "KeyID", "=", "keyPair", ".", "ID", "\n\n", "// Register first by adding the value to the storage. We don't return any", "// error because we need to know why kontrol doesn't register itself", "if", "err", ":=", "k", ".", "storage", ".", "Add", "(", "k", ".", "Kite", ".", "Kite", "(", ")", ",", "value", ")", ";", "err", "!=", "nil", "{", "k", ".", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "<-", "k", ".", "closed", ":", "return", "\n", "default", ":", "if", "err", ":=", "k", ".", "storage", ".", "Update", "(", "k", ".", "Kite", ".", "Kite", "(", ")", ",", "value", ")", ";", "err", "!=", "nil", "{", "k", ".", "log", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "continue", "\n", "}", "\n\n", "time", ".", "Sleep", "(", "HeartbeatDelay", "+", "HeartbeatInterval", ")", "\n", "}", "\n", "}", "\n", "}" ]
// registerSelf adds Kontrol itself to the storage as a kite.
[ "registerSelf", "adds", "Kontrol", "itself", "to", "the", "storage", "as", "a", "kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kontrol.go#L390-L451
train
koding/kite
kontrol/kontrol.go
KeyPair
func (k *Kontrol) KeyPair() (pair *KeyPair, err error) { if k.selfKeyPair != nil { return k.selfKeyPair, nil } kiteKey := k.Kite.KiteKey() if kiteKey == "" || len(k.lastPublic) == 0 { return nil, errNoSelfKeyPair } keyIndex := -1 me := new(multiError) for i := range k.lastPublic { ri := len(k.lastPublic) - i - 1 keyFn := func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, errors.New("invalid signing method") } return jwt.ParseRSAPublicKeyFromPEM([]byte(k.lastPublic[ri])) } if _, err := jwt.ParseWithClaims(kiteKey, &kitekey.KiteClaims{}, keyFn); err != nil { me.err = append(me.err, err) continue } keyIndex = ri break } if keyIndex == -1 { return nil, fmt.Errorf("no matching self key pair found: %s", me) } k.selfKeyPair = &KeyPair{ ID: k.lastIDs[keyIndex], Public: k.lastPublic[keyIndex], Private: k.lastPrivate[keyIndex], } return k.selfKeyPair, nil }
go
func (k *Kontrol) KeyPair() (pair *KeyPair, err error) { if k.selfKeyPair != nil { return k.selfKeyPair, nil } kiteKey := k.Kite.KiteKey() if kiteKey == "" || len(k.lastPublic) == 0 { return nil, errNoSelfKeyPair } keyIndex := -1 me := new(multiError) for i := range k.lastPublic { ri := len(k.lastPublic) - i - 1 keyFn := func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, errors.New("invalid signing method") } return jwt.ParseRSAPublicKeyFromPEM([]byte(k.lastPublic[ri])) } if _, err := jwt.ParseWithClaims(kiteKey, &kitekey.KiteClaims{}, keyFn); err != nil { me.err = append(me.err, err) continue } keyIndex = ri break } if keyIndex == -1 { return nil, fmt.Errorf("no matching self key pair found: %s", me) } k.selfKeyPair = &KeyPair{ ID: k.lastIDs[keyIndex], Public: k.lastPublic[keyIndex], Private: k.lastPrivate[keyIndex], } return k.selfKeyPair, nil }
[ "func", "(", "k", "*", "Kontrol", ")", "KeyPair", "(", ")", "(", "pair", "*", "KeyPair", ",", "err", "error", ")", "{", "if", "k", ".", "selfKeyPair", "!=", "nil", "{", "return", "k", ".", "selfKeyPair", ",", "nil", "\n", "}", "\n\n", "kiteKey", ":=", "k", ".", "Kite", ".", "KiteKey", "(", ")", "\n\n", "if", "kiteKey", "==", "\"", "\"", "||", "len", "(", "k", ".", "lastPublic", ")", "==", "0", "{", "return", "nil", ",", "errNoSelfKeyPair", "\n", "}", "\n\n", "keyIndex", ":=", "-", "1", "\n\n", "me", ":=", "new", "(", "multiError", ")", "\n\n", "for", "i", ":=", "range", "k", ".", "lastPublic", "{", "ri", ":=", "len", "(", "k", ".", "lastPublic", ")", "-", "i", "-", "1", "\n\n", "keyFn", ":=", "func", "(", "token", "*", "jwt", ".", "Token", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "_", ",", "ok", ":=", "token", ".", "Method", ".", "(", "*", "jwt", ".", "SigningMethodRSA", ")", ";", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "jwt", ".", "ParseRSAPublicKeyFromPEM", "(", "[", "]", "byte", "(", "k", ".", "lastPublic", "[", "ri", "]", ")", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "jwt", ".", "ParseWithClaims", "(", "kiteKey", ",", "&", "kitekey", ".", "KiteClaims", "{", "}", ",", "keyFn", ")", ";", "err", "!=", "nil", "{", "me", ".", "err", "=", "append", "(", "me", ".", "err", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "keyIndex", "=", "ri", "\n", "break", "\n", "}", "\n\n", "if", "keyIndex", "==", "-", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "me", ")", "\n", "}", "\n\n", "k", ".", "selfKeyPair", "=", "&", "KeyPair", "{", "ID", ":", "k", ".", "lastIDs", "[", "keyIndex", "]", ",", "Public", ":", "k", ".", "lastPublic", "[", "keyIndex", "]", ",", "Private", ":", "k", ".", "lastPrivate", "[", "keyIndex", "]", ",", "}", "\n\n", "return", "k", ".", "selfKeyPair", ",", "nil", "\n", "}" ]
// KeyPair looks up a key pair that was used to sign Kontrol's kite key. // // The value is cached on first call of the function.
[ "KeyPair", "looks", "up", "a", "key", "pair", "that", "was", "used", "to", "sign", "Kontrol", "s", "kite", "key", ".", "The", "value", "is", "cached", "on", "first", "call", "of", "the", "function", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kontrol.go#L456-L502
train
koding/kite
kontrol/kontrol.go
cacheToken
func (k *Kontrol) cacheToken(key, signed string) { if ct, ok := k.tokenCache[key]; ok { ct.timer.Stop() } k.tokenCache[key] = cachedToken{ signed: signed, timer: time.AfterFunc(k.tokenTTL()-k.tokenLeeway(), func() { k.tokenCacheMu.Lock() delete(k.tokenCache, key) k.tokenCacheMu.Unlock() }), } }
go
func (k *Kontrol) cacheToken(key, signed string) { if ct, ok := k.tokenCache[key]; ok { ct.timer.Stop() } k.tokenCache[key] = cachedToken{ signed: signed, timer: time.AfterFunc(k.tokenTTL()-k.tokenLeeway(), func() { k.tokenCacheMu.Lock() delete(k.tokenCache, key) k.tokenCacheMu.Unlock() }), } }
[ "func", "(", "k", "*", "Kontrol", ")", "cacheToken", "(", "key", ",", "signed", "string", ")", "{", "if", "ct", ",", "ok", ":=", "k", ".", "tokenCache", "[", "key", "]", ";", "ok", "{", "ct", ".", "timer", ".", "Stop", "(", ")", "\n", "}", "\n\n", "k", ".", "tokenCache", "[", "key", "]", "=", "cachedToken", "{", "signed", ":", "signed", ",", "timer", ":", "time", ".", "AfterFunc", "(", "k", ".", "tokenTTL", "(", ")", "-", "k", ".", "tokenLeeway", "(", ")", ",", "func", "(", ")", "{", "k", ".", "tokenCacheMu", ".", "Lock", "(", ")", "\n", "delete", "(", "k", ".", "tokenCache", ",", "key", ")", "\n", "k", ".", "tokenCacheMu", ".", "Unlock", "(", ")", "\n", "}", ")", ",", "}", "\n", "}" ]
// cacheToken cached the signed token under the given key. // // It also ensures the token is invalidated after its expiration time. // // If the token was already exists in the cache, it will be // overwritten with a new value.
[ "cacheToken", "cached", "the", "signed", "token", "under", "the", "given", "key", ".", "It", "also", "ensures", "the", "token", "is", "invalidated", "after", "its", "expiration", "time", ".", "If", "the", "token", "was", "already", "exists", "in", "the", "cache", "it", "will", "be", "overwritten", "with", "a", "new", "value", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kontrol.go#L543-L556
train
koding/kite
dnode/partial.go
UnmarshalJSON
func (p *Partial) UnmarshalJSON(data []byte) error { if p == nil { return errors.New("json.Partial: UnmarshalJSON on nil pointer") } p.Raw = make([]byte, len(data)) copy(p.Raw, data) return nil }
go
func (p *Partial) UnmarshalJSON(data []byte) error { if p == nil { return errors.New("json.Partial: UnmarshalJSON on nil pointer") } p.Raw = make([]byte, len(data)) copy(p.Raw, data) return nil }
[ "func", "(", "p", "*", "Partial", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "p", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ".", "Raw", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "data", ")", ")", "\n", "copy", "(", "p", ".", "Raw", ",", "data", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON puts the data into Partial.Raw.
[ "UnmarshalJSON", "puts", "the", "data", "into", "Partial", ".", "Raw", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L22-L30
train
koding/kite
dnode/partial.go
SliceOfLength
func (p *Partial) SliceOfLength(length int) (a []*Partial, err error) { err = p.Unmarshal(&a) if err != nil { return } if len(a) != length { err = errors.New("Invalid array length") } return }
go
func (p *Partial) SliceOfLength(length int) (a []*Partial, err error) { err = p.Unmarshal(&a) if err != nil { return } if len(a) != length { err = errors.New("Invalid array length") } return }
[ "func", "(", "p", "*", "Partial", ")", "SliceOfLength", "(", "length", "int", ")", "(", "a", "[", "]", "*", "Partial", ",", "err", "error", ")", "{", "err", "=", "p", ".", "Unmarshal", "(", "&", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "len", "(", "a", ")", "!=", "length", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// SliceOfLength is a helper method to unmarshal a JSON Array with specified length.
[ "SliceOfLength", "is", "a", "helper", "method", "to", "unmarshal", "a", "JSON", "Array", "with", "specified", "length", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L70-L81
train
koding/kite
dnode/partial.go
Map
func (p *Partial) Map() (m map[string]*Partial, err error) { err = p.Unmarshal(&m) return }
go
func (p *Partial) Map() (m map[string]*Partial, err error) { err = p.Unmarshal(&m) return }
[ "func", "(", "p", "*", "Partial", ")", "Map", "(", ")", "(", "m", "map", "[", "string", "]", "*", "Partial", ",", "err", "error", ")", "{", "err", "=", "p", ".", "Unmarshal", "(", "&", "m", ")", "\n", "return", "\n", "}" ]
// Map is a helper method to unmarshal to a JSON Object.
[ "Map", "is", "a", "helper", "method", "to", "unmarshal", "to", "a", "JSON", "Object", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L84-L87
train
koding/kite
dnode/partial.go
String
func (p *Partial) String() (s string, err error) { err = p.Unmarshal(&s) return }
go
func (p *Partial) String() (s string, err error) { err = p.Unmarshal(&s) return }
[ "func", "(", "p", "*", "Partial", ")", "String", "(", ")", "(", "s", "string", ",", "err", "error", ")", "{", "err", "=", "p", ".", "Unmarshal", "(", "&", "s", ")", "\n", "return", "\n", "}" ]
// String is a helper to unmarshal a JSON String.
[ "String", "is", "a", "helper", "to", "unmarshal", "a", "JSON", "String", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L90-L93
train
koding/kite
dnode/partial.go
Float64
func (p *Partial) Float64() (f float64, err error) { err = p.Unmarshal(&f) return }
go
func (p *Partial) Float64() (f float64, err error) { err = p.Unmarshal(&f) return }
[ "func", "(", "p", "*", "Partial", ")", "Float64", "(", ")", "(", "f", "float64", ",", "err", "error", ")", "{", "err", "=", "p", ".", "Unmarshal", "(", "&", "f", ")", "\n", "return", "\n", "}" ]
// Float64 is a helper to unmarshal a JSON Number.
[ "Float64", "is", "a", "helper", "to", "unmarshal", "a", "JSON", "Number", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L96-L99
train
koding/kite
dnode/partial.go
Bool
func (p *Partial) Bool() (b bool, err error) { err = p.Unmarshal(&b) return }
go
func (p *Partial) Bool() (b bool, err error) { err = p.Unmarshal(&b) return }
[ "func", "(", "p", "*", "Partial", ")", "Bool", "(", ")", "(", "b", "bool", ",", "err", "error", ")", "{", "err", "=", "p", ".", "Unmarshal", "(", "&", "b", ")", "\n", "return", "\n", "}" ]
// Bool is a helper to unmarshal a JSON Boolean.
[ "Bool", "is", "a", "helper", "to", "unmarshal", "a", "JSON", "Boolean", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L102-L105
train
koding/kite
dnode/partial.go
Function
func (p *Partial) Function() (f Function, err error) { err = p.Unmarshal(&f) return }
go
func (p *Partial) Function() (f Function, err error) { err = p.Unmarshal(&f) return }
[ "func", "(", "p", "*", "Partial", ")", "Function", "(", ")", "(", "f", "Function", ",", "err", "error", ")", "{", "err", "=", "p", ".", "Unmarshal", "(", "&", "f", ")", "\n", "return", "\n", "}" ]
// Function is a helper to unmarshal a callback function.
[ "Function", "is", "a", "helper", "to", "unmarshal", "a", "callback", "function", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L108-L111
train
koding/kite
kontrol/etcd.go
validateKiteKey
func validateKiteKey(k *protocol.Kite) error { fields := k.Query().Fields() // Validate fields. for k, v := range fields { if v == "" { return fmt.Errorf("Empty Kite field: %s", k) } if strings.ContainsRune(v, '/') { return fmt.Errorf("Field \"%s\" must not contain '/'", k) } } return nil }
go
func validateKiteKey(k *protocol.Kite) error { fields := k.Query().Fields() // Validate fields. for k, v := range fields { if v == "" { return fmt.Errorf("Empty Kite field: %s", k) } if strings.ContainsRune(v, '/') { return fmt.Errorf("Field \"%s\" must not contain '/'", k) } } return nil }
[ "func", "validateKiteKey", "(", "k", "*", "protocol", ".", "Kite", ")", "error", "{", "fields", ":=", "k", ".", "Query", "(", ")", ".", "Fields", "(", ")", "\n\n", "// Validate fields.", "for", "k", ",", "v", ":=", "range", "fields", "{", "if", "v", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "if", "strings", ".", "ContainsRune", "(", "v", ",", "'/'", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "k", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateKiteKey returns a string representing the kite uniquely // that is suitable to use as a key for etcd.
[ "validateKiteKey", "returns", "a", "string", "representing", "the", "kite", "uniquely", "that", "is", "suitable", "to", "use", "as", "a", "key", "for", "etcd", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/etcd.go#L300-L314
train
koding/kite
kontrol/etcd.go
onlyIDQuery
func onlyIDQuery(q *protocol.KontrolQuery) bool { fields := q.Fields() // check if any other key exist, if yes return a false for _, k := range keyOrder { v := fields[k] if k != "id" && v != "" { return false } } // now all other keys are empty, check finally for our ID if fields["id"] != "" { return true } // ID is empty too! return false }
go
func onlyIDQuery(q *protocol.KontrolQuery) bool { fields := q.Fields() // check if any other key exist, if yes return a false for _, k := range keyOrder { v := fields[k] if k != "id" && v != "" { return false } } // now all other keys are empty, check finally for our ID if fields["id"] != "" { return true } // ID is empty too! return false }
[ "func", "onlyIDQuery", "(", "q", "*", "protocol", ".", "KontrolQuery", ")", "bool", "{", "fields", ":=", "q", ".", "Fields", "(", ")", "\n\n", "// check if any other key exist, if yes return a false", "for", "_", ",", "k", ":=", "range", "keyOrder", "{", "v", ":=", "fields", "[", "k", "]", "\n", "if", "k", "!=", "\"", "\"", "&&", "v", "!=", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// now all other keys are empty, check finally for our ID", "if", "fields", "[", "\"", "\"", "]", "!=", "\"", "\"", "{", "return", "true", "\n", "}", "\n\n", "// ID is empty too!", "return", "false", "\n", "}" ]
// onlyIDQuery returns true if the query contains only a non-empty ID and all // others keys are empty
[ "onlyIDQuery", "returns", "true", "if", "the", "query", "contains", "only", "a", "non", "-", "empty", "ID", "and", "all", "others", "keys", "are", "empty" ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/etcd.go#L318-L336
train
koding/kite
kontrol/etcd.go
GetQueryKey
func GetQueryKey(q *protocol.KontrolQuery) (string, error) { fields := q.Fields() if q.Username == "" { return "", errors.New("Empty username field") } // Validate query and build key. path := "/" empty := false // encountered with empty field? empytField := "" // for error log // http://golang.org/doc/go1.3#map, order is important and we can't rely on // maps because the keys are not ordered :) for _, key := range keyOrder { v := fields[key] if v == "" { empty = true empytField = key continue } if empty && v != "" { return "", fmt.Errorf("Invalid query. Query option is not set: %s", empytField) } path = path + v + "/" } path = strings.TrimSuffix(path, "/") return path, nil }
go
func GetQueryKey(q *protocol.KontrolQuery) (string, error) { fields := q.Fields() if q.Username == "" { return "", errors.New("Empty username field") } // Validate query and build key. path := "/" empty := false // encountered with empty field? empytField := "" // for error log // http://golang.org/doc/go1.3#map, order is important and we can't rely on // maps because the keys are not ordered :) for _, key := range keyOrder { v := fields[key] if v == "" { empty = true empytField = key continue } if empty && v != "" { return "", fmt.Errorf("Invalid query. Query option is not set: %s", empytField) } path = path + v + "/" } path = strings.TrimSuffix(path, "/") return path, nil }
[ "func", "GetQueryKey", "(", "q", "*", "protocol", ".", "KontrolQuery", ")", "(", "string", ",", "error", ")", "{", "fields", ":=", "q", ".", "Fields", "(", ")", "\n\n", "if", "q", ".", "Username", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate query and build key.", "path", ":=", "\"", "\"", "\n\n", "empty", ":=", "false", "// encountered with empty field?", "\n", "empytField", ":=", "\"", "\"", "// for error log", "\n\n", "// http://golang.org/doc/go1.3#map, order is important and we can't rely on", "// maps because the keys are not ordered :)", "for", "_", ",", "key", ":=", "range", "keyOrder", "{", "v", ":=", "fields", "[", "key", "]", "\n", "if", "v", "==", "\"", "\"", "{", "empty", "=", "true", "\n", "empytField", "=", "key", "\n", "continue", "\n", "}", "\n\n", "if", "empty", "&&", "v", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "empytField", ")", "\n", "}", "\n\n", "path", "=", "path", "+", "v", "+", "\"", "\"", "\n", "}", "\n\n", "path", "=", "strings", ".", "TrimSuffix", "(", "path", ",", "\"", "\"", ")", "\n\n", "return", "path", ",", "nil", "\n", "}" ]
// getQueryKey returns the etcd key for the query.
[ "getQueryKey", "returns", "the", "etcd", "key", "for", "the", "query", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/etcd.go#L339-L372
train
koding/kite
kite.go
New
func New(name, version string) *Kite { return NewWithConfig(name, version, config.New()) }
go
func New(name, version string) *Kite { return NewWithConfig(name, version, config.New()) }
[ "func", "New", "(", "name", ",", "version", "string", ")", "*", "Kite", "{", "return", "NewWithConfig", "(", "name", ",", "version", ",", "config", ".", "New", "(", ")", ")", "\n", "}" ]
// New creates, initializes and then returns a new Kite instance. // // Version must be in 3-digit semantic form. // // Name is important that it's also used to be searched by others.
[ "New", "creates", "initializes", "and", "then", "returns", "a", "new", "Kite", "instance", ".", "Version", "must", "be", "in", "3", "-", "digit", "semantic", "form", ".", "Name", "is", "important", "that", "it", "s", "also", "used", "to", "be", "searched", "by", "others", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L163-L165
train
koding/kite
kite.go
NewWithConfig
func NewWithConfig(name, version string, cfg *config.Config) *Kite { if name == "" { panic("kite: name cannot be empty") } if digits := strings.Split(version, "."); len(digits) != 3 { panic("kite: version must be 3-digits semantic version") } kiteID := uuid.Must(uuid.NewV4()) l, setlevel := newLogger(name) kClient := &kontrolClient{ readyConnected: make(chan struct{}), readyRegistered: make(chan struct{}), registerChan: make(chan *url.URL, 1), } k := &Kite{ Config: cfg, Log: l, SetLogLevel: setlevel, Authenticators: make(map[string]func(*Request) error), handlers: make(map[string]*Method), kontrol: kClient, name: name, version: version, Id: kiteID.String(), readyC: make(chan bool), closeC: make(chan bool), heartbeatC: make(chan *heartbeatReq, 1), muxer: mux.NewRouter(), } if cfg != nil && cfg.UseWebRTC { k.WebRTCHandler = NewWebRCTHandler() } // All sockjs communication is done through this endpoint.. k.muxer.PathPrefix("/kite").Handler(sockjs.NewHandler("/kite", *cfg.SockJS, k.sockjsHandler)) // Add useful debug logs k.OnConnect(func(c *Client) { k.Log.Debug("New session: %s", c.session.ID()) }) k.OnFirstRequest(func(c *Client) { k.Log.Debug("Session %q is identified as %q", c.session.ID(), c.Kite) }) k.OnDisconnect(func(c *Client) { k.Log.Debug("Kite has disconnected: %q", c.Kite) }) k.OnRegister(k.updateAuth) // Every kite should be able to authenticate the user from token. // Tokens are granted by Kontrol Kite. k.Authenticators["token"] = k.AuthenticateFromToken // A kite accepts requests with the same username. k.Authenticators["kiteKey"] = k.AuthenticateFromKiteKey // Register default methods and handlers. k.addDefaultHandlers() go k.processHeartbeats() return k }
go
func NewWithConfig(name, version string, cfg *config.Config) *Kite { if name == "" { panic("kite: name cannot be empty") } if digits := strings.Split(version, "."); len(digits) != 3 { panic("kite: version must be 3-digits semantic version") } kiteID := uuid.Must(uuid.NewV4()) l, setlevel := newLogger(name) kClient := &kontrolClient{ readyConnected: make(chan struct{}), readyRegistered: make(chan struct{}), registerChan: make(chan *url.URL, 1), } k := &Kite{ Config: cfg, Log: l, SetLogLevel: setlevel, Authenticators: make(map[string]func(*Request) error), handlers: make(map[string]*Method), kontrol: kClient, name: name, version: version, Id: kiteID.String(), readyC: make(chan bool), closeC: make(chan bool), heartbeatC: make(chan *heartbeatReq, 1), muxer: mux.NewRouter(), } if cfg != nil && cfg.UseWebRTC { k.WebRTCHandler = NewWebRCTHandler() } // All sockjs communication is done through this endpoint.. k.muxer.PathPrefix("/kite").Handler(sockjs.NewHandler("/kite", *cfg.SockJS, k.sockjsHandler)) // Add useful debug logs k.OnConnect(func(c *Client) { k.Log.Debug("New session: %s", c.session.ID()) }) k.OnFirstRequest(func(c *Client) { k.Log.Debug("Session %q is identified as %q", c.session.ID(), c.Kite) }) k.OnDisconnect(func(c *Client) { k.Log.Debug("Kite has disconnected: %q", c.Kite) }) k.OnRegister(k.updateAuth) // Every kite should be able to authenticate the user from token. // Tokens are granted by Kontrol Kite. k.Authenticators["token"] = k.AuthenticateFromToken // A kite accepts requests with the same username. k.Authenticators["kiteKey"] = k.AuthenticateFromKiteKey // Register default methods and handlers. k.addDefaultHandlers() go k.processHeartbeats() return k }
[ "func", "NewWithConfig", "(", "name", ",", "version", "string", ",", "cfg", "*", "config", ".", "Config", ")", "*", "Kite", "{", "if", "name", "==", "\"", "\"", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "digits", ":=", "strings", ".", "Split", "(", "version", ",", "\"", "\"", ")", ";", "len", "(", "digits", ")", "!=", "3", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "kiteID", ":=", "uuid", ".", "Must", "(", "uuid", ".", "NewV4", "(", ")", ")", "\n\n", "l", ",", "setlevel", ":=", "newLogger", "(", "name", ")", "\n\n", "kClient", ":=", "&", "kontrolClient", "{", "readyConnected", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "readyRegistered", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "registerChan", ":", "make", "(", "chan", "*", "url", ".", "URL", ",", "1", ")", ",", "}", "\n\n", "k", ":=", "&", "Kite", "{", "Config", ":", "cfg", ",", "Log", ":", "l", ",", "SetLogLevel", ":", "setlevel", ",", "Authenticators", ":", "make", "(", "map", "[", "string", "]", "func", "(", "*", "Request", ")", "error", ")", ",", "handlers", ":", "make", "(", "map", "[", "string", "]", "*", "Method", ")", ",", "kontrol", ":", "kClient", ",", "name", ":", "name", ",", "version", ":", "version", ",", "Id", ":", "kiteID", ".", "String", "(", ")", ",", "readyC", ":", "make", "(", "chan", "bool", ")", ",", "closeC", ":", "make", "(", "chan", "bool", ")", ",", "heartbeatC", ":", "make", "(", "chan", "*", "heartbeatReq", ",", "1", ")", ",", "muxer", ":", "mux", ".", "NewRouter", "(", ")", ",", "}", "\n\n", "if", "cfg", "!=", "nil", "&&", "cfg", ".", "UseWebRTC", "{", "k", ".", "WebRTCHandler", "=", "NewWebRCTHandler", "(", ")", "\n", "}", "\n\n", "// All sockjs communication is done through this endpoint..", "k", ".", "muxer", ".", "PathPrefix", "(", "\"", "\"", ")", ".", "Handler", "(", "sockjs", ".", "NewHandler", "(", "\"", "\"", ",", "*", "cfg", ".", "SockJS", ",", "k", ".", "sockjsHandler", ")", ")", "\n\n", "// Add useful debug logs", "k", ".", "OnConnect", "(", "func", "(", "c", "*", "Client", ")", "{", "k", ".", "Log", ".", "Debug", "(", "\"", "\"", ",", "c", ".", "session", ".", "ID", "(", ")", ")", "}", ")", "\n", "k", ".", "OnFirstRequest", "(", "func", "(", "c", "*", "Client", ")", "{", "k", ".", "Log", ".", "Debug", "(", "\"", "\"", ",", "c", ".", "session", ".", "ID", "(", ")", ",", "c", ".", "Kite", ")", "}", ")", "\n", "k", ".", "OnDisconnect", "(", "func", "(", "c", "*", "Client", ")", "{", "k", ".", "Log", ".", "Debug", "(", "\"", "\"", ",", "c", ".", "Kite", ")", "}", ")", "\n", "k", ".", "OnRegister", "(", "k", ".", "updateAuth", ")", "\n\n", "// Every kite should be able to authenticate the user from token.", "// Tokens are granted by Kontrol Kite.", "k", ".", "Authenticators", "[", "\"", "\"", "]", "=", "k", ".", "AuthenticateFromToken", "\n\n", "// A kite accepts requests with the same username.", "k", ".", "Authenticators", "[", "\"", "\"", "]", "=", "k", ".", "AuthenticateFromKiteKey", "\n\n", "// Register default methods and handlers.", "k", ".", "addDefaultHandlers", "(", ")", "\n\n", "go", "k", ".", "processHeartbeats", "(", ")", "\n\n", "return", "k", "\n", "}" ]
// NewWithConfig builds a new kite value for the given configuration.
[ "NewWithConfig", "builds", "a", "new", "kite", "value", "for", "the", "given", "configuration", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L168-L229
train
koding/kite
kite.go
Kite
func (k *Kite) Kite() *protocol.Kite { return &protocol.Kite{ Username: k.Config.Username, Environment: k.Config.Environment, Name: k.name, Version: k.version, Region: k.Config.Region, Hostname: hostname, ID: k.Id, } }
go
func (k *Kite) Kite() *protocol.Kite { return &protocol.Kite{ Username: k.Config.Username, Environment: k.Config.Environment, Name: k.name, Version: k.version, Region: k.Config.Region, Hostname: hostname, ID: k.Id, } }
[ "func", "(", "k", "*", "Kite", ")", "Kite", "(", ")", "*", "protocol", ".", "Kite", "{", "return", "&", "protocol", ".", "Kite", "{", "Username", ":", "k", ".", "Config", ".", "Username", ",", "Environment", ":", "k", ".", "Config", ".", "Environment", ",", "Name", ":", "k", ".", "name", ",", "Version", ":", "k", ".", "version", ",", "Region", ":", "k", ".", "Config", ".", "Region", ",", "Hostname", ":", "hostname", ",", "ID", ":", "k", ".", "Id", ",", "}", "\n", "}" ]
// Kite returns the definition of the kite.
[ "Kite", "returns", "the", "definition", "of", "the", "kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L232-L242
train
koding/kite
kite.go
KiteKey
func (k *Kite) KiteKey() string { k.configMu.RLock() defer k.configMu.RUnlock() return k.Config.KiteKey }
go
func (k *Kite) KiteKey() string { k.configMu.RLock() defer k.configMu.RUnlock() return k.Config.KiteKey }
[ "func", "(", "k", "*", "Kite", ")", "KiteKey", "(", ")", "string", "{", "k", ".", "configMu", ".", "RLock", "(", ")", "\n", "defer", "k", ".", "configMu", ".", "RUnlock", "(", ")", "\n\n", "return", "k", ".", "Config", ".", "KiteKey", "\n", "}" ]
// KiteKey gives a kite key used to authenticate to kontrol and other kites.
[ "KiteKey", "gives", "a", "kite", "key", "used", "to", "authenticate", "to", "kontrol", "and", "other", "kites", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L245-L250
train
koding/kite
kite.go
KontrolKey
func (k *Kite) KontrolKey() *rsa.PublicKey { k.configMu.RLock() defer k.configMu.RUnlock() return k.kontrolKey }
go
func (k *Kite) KontrolKey() *rsa.PublicKey { k.configMu.RLock() defer k.configMu.RUnlock() return k.kontrolKey }
[ "func", "(", "k", "*", "Kite", ")", "KontrolKey", "(", ")", "*", "rsa", ".", "PublicKey", "{", "k", ".", "configMu", ".", "RLock", "(", ")", "\n", "defer", "k", ".", "configMu", ".", "RUnlock", "(", ")", "\n\n", "return", "k", ".", "kontrolKey", "\n", "}" ]
// KontrolKey gives a Kontrol's public key. // // The value is taken form kite key's kontrolKey claim.
[ "KontrolKey", "gives", "a", "Kontrol", "s", "public", "key", ".", "The", "value", "is", "taken", "form", "kite", "key", "s", "kontrolKey", "claim", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L255-L260
train
koding/kite
kite.go
HandleHTTP
func (k *Kite) HandleHTTP(pattern string, handler http.Handler) { k.muxer.Handle(pattern, handler) }
go
func (k *Kite) HandleHTTP(pattern string, handler http.Handler) { k.muxer.Handle(pattern, handler) }
[ "func", "(", "k", "*", "Kite", ")", "HandleHTTP", "(", "pattern", "string", ",", "handler", "http", ".", "Handler", ")", "{", "k", ".", "muxer", ".", "Handle", "(", "pattern", ",", "handler", ")", "\n", "}" ]
// HandleHTTP registers the HTTP handler for the given pattern into the // underlying HTTP muxer.
[ "HandleHTTP", "registers", "the", "HTTP", "handler", "for", "the", "given", "pattern", "into", "the", "underlying", "HTTP", "muxer", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L264-L266
train
koding/kite
kite.go
HandleHTTPFunc
func (k *Kite) HandleHTTPFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { k.muxer.HandleFunc(pattern, handler) }
go
func (k *Kite) HandleHTTPFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { k.muxer.HandleFunc(pattern, handler) }
[ "func", "(", "k", "*", "Kite", ")", "HandleHTTPFunc", "(", "pattern", "string", ",", "handler", "func", "(", "http", ".", "ResponseWriter", ",", "*", "http", ".", "Request", ")", ")", "{", "k", ".", "muxer", ".", "HandleFunc", "(", "pattern", ",", "handler", ")", "\n", "}" ]
// HandleHTTPFunc registers the HTTP handler for the given pattern into the // underlying HTTP muxer.
[ "HandleHTTPFunc", "registers", "the", "HTTP", "handler", "for", "the", "given", "pattern", "into", "the", "underlying", "HTTP", "muxer", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L270-L272
train
koding/kite
kite.go
ServeHTTP
func (k *Kite) ServeHTTP(w http.ResponseWriter, req *http.Request) { k.muxer.ServeHTTP(w, req) }
go
func (k *Kite) ServeHTTP(w http.ResponseWriter, req *http.Request) { k.muxer.ServeHTTP(w, req) }
[ "func", "(", "k", "*", "Kite", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "k", ".", "muxer", ".", "ServeHTTP", "(", "w", ",", "req", ")", "\n", "}" ]
// ServeHTTP helps Kite to satisfy the http.Handler interface. So kite can be // used as a standard http server.
[ "ServeHTTP", "helps", "Kite", "to", "satisfy", "the", "http", ".", "Handler", "interface", ".", "So", "kite", "can", "be", "used", "as", "a", "standard", "http", "server", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L276-L278
train
koding/kite
kite.go
OnConnect
func (k *Kite) OnConnect(handler func(*Client)) { k.handlersMu.Lock() k.onConnectHandlers = append(k.onConnectHandlers, handler) k.handlersMu.Unlock() }
go
func (k *Kite) OnConnect(handler func(*Client)) { k.handlersMu.Lock() k.onConnectHandlers = append(k.onConnectHandlers, handler) k.handlersMu.Unlock() }
[ "func", "(", "k", "*", "Kite", ")", "OnConnect", "(", "handler", "func", "(", "*", "Client", ")", ")", "{", "k", ".", "handlersMu", ".", "Lock", "(", ")", "\n", "k", ".", "onConnectHandlers", "=", "append", "(", "k", ".", "onConnectHandlers", ",", "handler", ")", "\n", "k", ".", "handlersMu", ".", "Unlock", "(", ")", "\n", "}" ]
// OnConnect registers a callbacks which is called when a Kite connects // to the k Kite.
[ "OnConnect", "registers", "a", "callbacks", "which", "is", "called", "when", "a", "Kite", "connects", "to", "the", "k", "Kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L304-L308
train
koding/kite
kite.go
OnFirstRequest
func (k *Kite) OnFirstRequest(handler func(*Client)) { k.handlersMu.Lock() k.onFirstRequestHandlers = append(k.onFirstRequestHandlers, handler) k.handlersMu.Unlock() }
go
func (k *Kite) OnFirstRequest(handler func(*Client)) { k.handlersMu.Lock() k.onFirstRequestHandlers = append(k.onFirstRequestHandlers, handler) k.handlersMu.Unlock() }
[ "func", "(", "k", "*", "Kite", ")", "OnFirstRequest", "(", "handler", "func", "(", "*", "Client", ")", ")", "{", "k", ".", "handlersMu", ".", "Lock", "(", ")", "\n", "k", ".", "onFirstRequestHandlers", "=", "append", "(", "k", ".", "onFirstRequestHandlers", ",", "handler", ")", "\n", "k", ".", "handlersMu", ".", "Unlock", "(", ")", "\n", "}" ]
// OnFirstRequest registers a function to run when we receive first request // from other Kite.
[ "OnFirstRequest", "registers", "a", "function", "to", "run", "when", "we", "receive", "first", "request", "from", "other", "Kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L312-L316
train
koding/kite
kite.go
OnDisconnect
func (k *Kite) OnDisconnect(handler func(*Client)) { k.handlersMu.Lock() k.onDisconnectHandlers = append(k.onDisconnectHandlers, handler) k.handlersMu.Unlock() }
go
func (k *Kite) OnDisconnect(handler func(*Client)) { k.handlersMu.Lock() k.onDisconnectHandlers = append(k.onDisconnectHandlers, handler) k.handlersMu.Unlock() }
[ "func", "(", "k", "*", "Kite", ")", "OnDisconnect", "(", "handler", "func", "(", "*", "Client", ")", ")", "{", "k", ".", "handlersMu", ".", "Lock", "(", ")", "\n", "k", ".", "onDisconnectHandlers", "=", "append", "(", "k", ".", "onDisconnectHandlers", ",", "handler", ")", "\n", "k", ".", "handlersMu", ".", "Unlock", "(", ")", "\n", "}" ]
// OnDisconnect registers a function to run when a connected Kite is disconnected.
[ "OnDisconnect", "registers", "a", "function", "to", "run", "when", "a", "connected", "Kite", "is", "disconnected", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L319-L323
train
koding/kite
kite.go
OnRegister
func (k *Kite) OnRegister(handler func(*protocol.RegisterResult)) { k.handlersMu.Lock() k.onRegisterHandlers = append(k.onRegisterHandlers, handler) k.handlersMu.Unlock() }
go
func (k *Kite) OnRegister(handler func(*protocol.RegisterResult)) { k.handlersMu.Lock() k.onRegisterHandlers = append(k.onRegisterHandlers, handler) k.handlersMu.Unlock() }
[ "func", "(", "k", "*", "Kite", ")", "OnRegister", "(", "handler", "func", "(", "*", "protocol", ".", "RegisterResult", ")", ")", "{", "k", ".", "handlersMu", ".", "Lock", "(", ")", "\n", "k", ".", "onRegisterHandlers", "=", "append", "(", "k", ".", "onRegisterHandlers", ",", "handler", ")", "\n", "k", ".", "handlersMu", ".", "Unlock", "(", ")", "\n", "}" ]
// OnRegister registers a callback which is called when a Kite registers // to a Kontrol.
[ "OnRegister", "registers", "a", "callback", "which", "is", "called", "when", "a", "Kite", "registers", "to", "a", "Kontrol", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L327-L331
train
koding/kite
kite.go
RSAKey
func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) { k.verifyOnce.Do(k.verifyInit) kontrolKey := k.KontrolKey() if kontrolKey == nil { panic("kontrol key is not set in config") } if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, errors.New("invalid signing method") } claims, ok := token.Claims.(*kitekey.KiteClaims) if !ok { return nil, errors.New("token does not have valid claims") } if claims.Issuer != k.Config.KontrolUser { return nil, fmt.Errorf("issuer is not trusted: %s", claims.Issuer) } return kontrolKey, nil }
go
func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) { k.verifyOnce.Do(k.verifyInit) kontrolKey := k.KontrolKey() if kontrolKey == nil { panic("kontrol key is not set in config") } if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, errors.New("invalid signing method") } claims, ok := token.Claims.(*kitekey.KiteClaims) if !ok { return nil, errors.New("token does not have valid claims") } if claims.Issuer != k.Config.KontrolUser { return nil, fmt.Errorf("issuer is not trusted: %s", claims.Issuer) } return kontrolKey, nil }
[ "func", "(", "k", "*", "Kite", ")", "RSAKey", "(", "token", "*", "jwt", ".", "Token", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "k", ".", "verifyOnce", ".", "Do", "(", "k", ".", "verifyInit", ")", "\n\n", "kontrolKey", ":=", "k", ".", "KontrolKey", "(", ")", "\n\n", "if", "kontrolKey", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "token", ".", "Method", ".", "(", "*", "jwt", ".", "SigningMethodRSA", ")", ";", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "claims", ",", "ok", ":=", "token", ".", "Claims", ".", "(", "*", "kitekey", ".", "KiteClaims", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "claims", ".", "Issuer", "!=", "k", ".", "Config", ".", "KontrolUser", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "claims", ".", "Issuer", ")", "\n", "}", "\n\n", "return", "kontrolKey", ",", "nil", "\n", "}" ]
// RSAKey returns the corresponding public key for the issuer of the token. // It is called by jwt-go package when validating the signature in the token.
[ "RSAKey", "returns", "the", "corresponding", "public", "key", "for", "the", "issuer", "of", "the", "token", ".", "It", "is", "called", "by", "jwt", "-", "go", "package", "when", "validating", "the", "signature", "in", "the", "token", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L422-L445
train
koding/kite
kite.go
Error
func (err *ErrClose) Error() string { if len(err.Errs) == 1 { return err.Errs[0].Error() } var buf bytes.Buffer fmt.Fprintf(&buf, "The following kites failed to close:\n\n") for i, e := range err.Errs { if e == nil { continue } fmt.Fprintf(&buf, "\t[%d] %s\n", i, e) } return buf.String() }
go
func (err *ErrClose) Error() string { if len(err.Errs) == 1 { return err.Errs[0].Error() } var buf bytes.Buffer fmt.Fprintf(&buf, "The following kites failed to close:\n\n") for i, e := range err.Errs { if e == nil { continue } fmt.Fprintf(&buf, "\t[%d] %s\n", i, e) } return buf.String() }
[ "func", "(", "err", "*", "ErrClose", ")", "Error", "(", ")", "string", "{", "if", "len", "(", "err", ".", "Errs", ")", "==", "1", "{", "return", "err", ".", "Errs", "[", "0", "]", ".", "Error", "(", ")", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\\n", "\\n", "\"", ")", "\n\n", "for", "i", ",", "e", ":=", "range", "err", ".", "Errs", "{", "if", "e", "==", "nil", "{", "continue", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\\t", "\\n", "\"", ",", "i", ",", "e", ")", "\n", "}", "\n\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Error implements the built-in error interface.
[ "Error", "implements", "the", "built", "-", "in", "error", "interface", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L456-L474
train
koding/kite
kontrol/postgres.go
RunCleaner
func (p *Postgres) RunCleaner(interval, expire time.Duration) { cleanFunc := func() { affectedRows, err := p.CleanExpiredRows(expire) if err != nil { p.Log.Warning("postgres: cleaning old rows failed: %s", err) } else if affectedRows != 0 { p.Log.Debug("postgres: cleaned up %d rows", affectedRows) } } for range time.Tick(interval) { cleanFunc() } }
go
func (p *Postgres) RunCleaner(interval, expire time.Duration) { cleanFunc := func() { affectedRows, err := p.CleanExpiredRows(expire) if err != nil { p.Log.Warning("postgres: cleaning old rows failed: %s", err) } else if affectedRows != 0 { p.Log.Debug("postgres: cleaned up %d rows", affectedRows) } } for range time.Tick(interval) { cleanFunc() } }
[ "func", "(", "p", "*", "Postgres", ")", "RunCleaner", "(", "interval", ",", "expire", "time", ".", "Duration", ")", "{", "cleanFunc", ":=", "func", "(", ")", "{", "affectedRows", ",", "err", ":=", "p", ".", "CleanExpiredRows", "(", "expire", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "Log", ".", "Warning", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "if", "affectedRows", "!=", "0", "{", "p", ".", "Log", ".", "Debug", "(", "\"", "\"", ",", "affectedRows", ")", "\n", "}", "\n", "}", "\n\n", "for", "range", "time", ".", "Tick", "(", "interval", ")", "{", "cleanFunc", "(", ")", "\n", "}", "\n", "}" ]
// RunCleaner deletes every "interval" duration rows which are older than // "expire" duration based on the "updated_at" field. For more info check // CleanExpireRows which is used to delete old rows.
[ "RunCleaner", "deletes", "every", "interval", "duration", "rows", "which", "are", "older", "than", "expire", "duration", "based", "on", "the", "updated_at", "field", ".", "For", "more", "info", "check", "CleanExpireRows", "which", "is", "used", "to", "delete", "old", "rows", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L93-L106
train
koding/kite
kontrol/postgres.go
CleanExpiredRows
func (p *Postgres) CleanExpiredRows(expire time.Duration) (int64, error) { // See: http://stackoverflow.com/questions/14465727/how-to-insert-things-like-now-interval-2-minutes-into-php-pdo-query // basically by passing an integer to INTERVAL is not possible, we need to // cast it. However there is a more simpler way, we can multiply INTERVAL // with an integer so we just declare a one second INTERVAL and multiply it // with the amount we want. cleanOldRows := `DELETE FROM kite.kite WHERE updated_at < (now() at time zone 'utc') - ((INTERVAL '1 second') * $1)` rows, err := p.DB.Exec(cleanOldRows, int64(expire/time.Second)) if err != nil { return 0, err } return rows.RowsAffected() }
go
func (p *Postgres) CleanExpiredRows(expire time.Duration) (int64, error) { // See: http://stackoverflow.com/questions/14465727/how-to-insert-things-like-now-interval-2-minutes-into-php-pdo-query // basically by passing an integer to INTERVAL is not possible, we need to // cast it. However there is a more simpler way, we can multiply INTERVAL // with an integer so we just declare a one second INTERVAL and multiply it // with the amount we want. cleanOldRows := `DELETE FROM kite.kite WHERE updated_at < (now() at time zone 'utc') - ((INTERVAL '1 second') * $1)` rows, err := p.DB.Exec(cleanOldRows, int64(expire/time.Second)) if err != nil { return 0, err } return rows.RowsAffected() }
[ "func", "(", "p", "*", "Postgres", ")", "CleanExpiredRows", "(", "expire", "time", ".", "Duration", ")", "(", "int64", ",", "error", ")", "{", "// See: http://stackoverflow.com/questions/14465727/how-to-insert-things-like-now-interval-2-minutes-into-php-pdo-query", "// basically by passing an integer to INTERVAL is not possible, we need to", "// cast it. However there is a more simpler way, we can multiply INTERVAL", "// with an integer so we just declare a one second INTERVAL and multiply it", "// with the amount we want.", "cleanOldRows", ":=", "`DELETE FROM kite.kite WHERE updated_at < (now() at time zone 'utc') - ((INTERVAL '1 second') * $1)`", "\n\n", "rows", ",", "err", ":=", "p", ".", "DB", ".", "Exec", "(", "cleanOldRows", ",", "int64", "(", "expire", "/", "time", ".", "Second", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "rows", ".", "RowsAffected", "(", ")", "\n", "}" ]
// CleanExpiredRows deletes rows that are at least "expire" duration old. So if // say an expire duration of 10 second is given, it will delete all rows that // were updated 10 seconds ago
[ "CleanExpiredRows", "deletes", "rows", "that", "are", "at", "least", "expire", "duration", "old", ".", "So", "if", "say", "an", "expire", "duration", "of", "10", "second", "is", "given", "it", "will", "delete", "all", "rows", "that", "were", "updated", "10", "seconds", "ago" ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L111-L125
train
koding/kite
kontrol/postgres.go
selectQuery
func selectQuery(query *protocol.KontrolQuery) (string, []interface{}, error) { psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) kites := psql.Select("*").From("kite.kite") fields := query.Fields() andQuery := sq.And{} // we stop for the first empty value for _, key := range keyOrder { v := fields[key] if v == "" { continue } // we are using "kitename" as the columname if key == "name" { key = "kitename" } andQuery = append(andQuery, sq.Eq{key: v}) } if len(andQuery) == 0 { return "", nil, ErrQueryFieldsEmpty } return kites.Where(andQuery).ToSql() }
go
func selectQuery(query *protocol.KontrolQuery) (string, []interface{}, error) { psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) kites := psql.Select("*").From("kite.kite") fields := query.Fields() andQuery := sq.And{} // we stop for the first empty value for _, key := range keyOrder { v := fields[key] if v == "" { continue } // we are using "kitename" as the columname if key == "name" { key = "kitename" } andQuery = append(andQuery, sq.Eq{key: v}) } if len(andQuery) == 0 { return "", nil, ErrQueryFieldsEmpty } return kites.Where(andQuery).ToSql() }
[ "func", "selectQuery", "(", "query", "*", "protocol", ".", "KontrolQuery", ")", "(", "string", ",", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "psql", ":=", "sq", ".", "StatementBuilder", ".", "PlaceholderFormat", "(", "sq", ".", "Dollar", ")", "\n\n", "kites", ":=", "psql", ".", "Select", "(", "\"", "\"", ")", ".", "From", "(", "\"", "\"", ")", "\n", "fields", ":=", "query", ".", "Fields", "(", ")", "\n", "andQuery", ":=", "sq", ".", "And", "{", "}", "\n\n", "// we stop for the first empty value", "for", "_", ",", "key", ":=", "range", "keyOrder", "{", "v", ":=", "fields", "[", "key", "]", "\n", "if", "v", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "// we are using \"kitename\" as the columname", "if", "key", "==", "\"", "\"", "{", "key", "=", "\"", "\"", "\n", "}", "\n\n", "andQuery", "=", "append", "(", "andQuery", ",", "sq", ".", "Eq", "{", "key", ":", "v", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "andQuery", ")", "==", "0", "{", "return", "\"", "\"", ",", "nil", ",", "ErrQueryFieldsEmpty", "\n", "}", "\n\n", "return", "kites", ".", "Where", "(", "andQuery", ")", ".", "ToSql", "(", ")", "\n", "}" ]
// selectQuery returns a SQL query for the given query
[ "selectQuery", "returns", "a", "SQL", "query", "for", "the", "given", "query" ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L334-L361
train
koding/kite
kontrol/postgres.go
insertKiteQuery
func insertKiteQuery(kiteProt *protocol.Kite, url, keyId string) (string, []interface{}, error) { psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) kiteValues := kiteProt.Values() values := make([]interface{}, len(kiteValues)) for i, kiteVal := range kiteValues { values[i] = kiteVal } values = append(values, url) values = append(values, keyId) return psql.Insert("kite.kite").Columns( "username", "environment", "kitename", "version", "region", "hostname", "id", "url", "key_id", ).Values(values...).ToSql() }
go
func insertKiteQuery(kiteProt *protocol.Kite, url, keyId string) (string, []interface{}, error) { psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) kiteValues := kiteProt.Values() values := make([]interface{}, len(kiteValues)) for i, kiteVal := range kiteValues { values[i] = kiteVal } values = append(values, url) values = append(values, keyId) return psql.Insert("kite.kite").Columns( "username", "environment", "kitename", "version", "region", "hostname", "id", "url", "key_id", ).Values(values...).ToSql() }
[ "func", "insertKiteQuery", "(", "kiteProt", "*", "protocol", ".", "Kite", ",", "url", ",", "keyId", "string", ")", "(", "string", ",", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "psql", ":=", "sq", ".", "StatementBuilder", ".", "PlaceholderFormat", "(", "sq", ".", "Dollar", ")", "\n\n", "kiteValues", ":=", "kiteProt", ".", "Values", "(", ")", "\n", "values", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "kiteValues", ")", ")", "\n\n", "for", "i", ",", "kiteVal", ":=", "range", "kiteValues", "{", "values", "[", "i", "]", "=", "kiteVal", "\n", "}", "\n\n", "values", "=", "append", "(", "values", ",", "url", ")", "\n", "values", "=", "append", "(", "values", ",", "keyId", ")", "\n\n", "return", "psql", ".", "Insert", "(", "\"", "\"", ")", ".", "Columns", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", ")", ".", "Values", "(", "values", "...", ")", ".", "ToSql", "(", ")", "\n", "}" ]
// inseryKiteQuery inserts the given kite, url and key to the kite.kite table
[ "inseryKiteQuery", "inserts", "the", "given", "kite", "url", "and", "key", "to", "the", "kite", ".", "kite", "table" ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L364-L388
train
koding/kite
logger_unix.go
SetupSignalHandler
func (k *Kite) SetupSignalHandler() { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGUSR2) go func() { for s := range c { k.Log.Info("Got signal: %s", s) if debugMode { // toogle back to old settings. k.Log.Info("Disabling debug mode") if k.SetLogLevel == nil { k.Log.Error("SetLogLevel is not defined") continue } k.SetLogLevel(getLogLevel()) debugMode = false } else { k.Log.Info("Enabling debug mode") if k.SetLogLevel == nil { k.Log.Error("SetLogLevel is not defined") continue } k.SetLogLevel(DEBUG) debugMode = true } } }() }
go
func (k *Kite) SetupSignalHandler() { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGUSR2) go func() { for s := range c { k.Log.Info("Got signal: %s", s) if debugMode { // toogle back to old settings. k.Log.Info("Disabling debug mode") if k.SetLogLevel == nil { k.Log.Error("SetLogLevel is not defined") continue } k.SetLogLevel(getLogLevel()) debugMode = false } else { k.Log.Info("Enabling debug mode") if k.SetLogLevel == nil { k.Log.Error("SetLogLevel is not defined") continue } k.SetLogLevel(DEBUG) debugMode = true } } }() }
[ "func", "(", "k", "*", "Kite", ")", "SetupSignalHandler", "(", ")", "{", "c", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n\n", "signal", ".", "Notify", "(", "c", ",", "syscall", ".", "SIGUSR2", ")", "\n", "go", "func", "(", ")", "{", "for", "s", ":=", "range", "c", "{", "k", ".", "Log", ".", "Info", "(", "\"", "\"", ",", "s", ")", "\n\n", "if", "debugMode", "{", "// toogle back to old settings.", "k", ".", "Log", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "k", ".", "SetLogLevel", "==", "nil", "{", "k", ".", "Log", ".", "Error", "(", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "k", ".", "SetLogLevel", "(", "getLogLevel", "(", ")", ")", "\n", "debugMode", "=", "false", "\n", "}", "else", "{", "k", ".", "Log", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "k", ".", "SetLogLevel", "==", "nil", "{", "k", ".", "Log", ".", "Error", "(", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "k", ".", "SetLogLevel", "(", "DEBUG", ")", "\n", "debugMode", "=", "true", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// SetupSignalHandler listens to signals and toggles the log level to DEBUG // mode when it received a SIGUSR2 signal. Another SIGUSR2 toggles the log // level back to the old level.
[ "SetupSignalHandler", "listens", "to", "signals", "and", "toggles", "the", "log", "level", "to", "DEBUG", "mode", "when", "it", "received", "a", "SIGUSR2", "signal", ".", "Another", "SIGUSR2", "toggles", "the", "log", "level", "back", "to", "the", "old", "level", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/logger_unix.go#L14-L44
train
koding/kite
sockjsclient/xhr.go
DialXHR
func DialXHR(uri string, cfg *config.Config) (*XHRSession, error) { // following /server_id/session_id should always be the same for every session serverID := threeDigits() sessionID := utils.RandomString(20) sessionURL := uri + "/" + serverID + "/" + sessionID // start the initial session handshake sessionResp, err := cfg.XHR.Post(sessionURL+"/xhr", "text/plain", nil) if err != nil { return nil, err } defer sessionResp.Body.Close() if sessionResp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Starting new session failed. Want: %d Got: %d", http.StatusOK, sessionResp.StatusCode) } frame, err := newFrameReader(sessionResp.Body, cfg.Timeout).ReadByte() if err != nil { return nil, err } if frame != 'o' { return nil, fmt.Errorf("can't start session, invalid frame: %s", string(frame)) } return &XHRSession{ client: cfg.XHR, timeout: cfg.Timeout, sessionID: sessionID, sessionURL: sessionURL, state: sockjs.SessionActive, abort: make(chan struct{}, 1), }, nil }
go
func DialXHR(uri string, cfg *config.Config) (*XHRSession, error) { // following /server_id/session_id should always be the same for every session serverID := threeDigits() sessionID := utils.RandomString(20) sessionURL := uri + "/" + serverID + "/" + sessionID // start the initial session handshake sessionResp, err := cfg.XHR.Post(sessionURL+"/xhr", "text/plain", nil) if err != nil { return nil, err } defer sessionResp.Body.Close() if sessionResp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Starting new session failed. Want: %d Got: %d", http.StatusOK, sessionResp.StatusCode) } frame, err := newFrameReader(sessionResp.Body, cfg.Timeout).ReadByte() if err != nil { return nil, err } if frame != 'o' { return nil, fmt.Errorf("can't start session, invalid frame: %s", string(frame)) } return &XHRSession{ client: cfg.XHR, timeout: cfg.Timeout, sessionID: sessionID, sessionURL: sessionURL, state: sockjs.SessionActive, abort: make(chan struct{}, 1), }, nil }
[ "func", "DialXHR", "(", "uri", "string", ",", "cfg", "*", "config", ".", "Config", ")", "(", "*", "XHRSession", ",", "error", ")", "{", "// following /server_id/session_id should always be the same for every session", "serverID", ":=", "threeDigits", "(", ")", "\n", "sessionID", ":=", "utils", ".", "RandomString", "(", "20", ")", "\n", "sessionURL", ":=", "uri", "+", "\"", "\"", "+", "serverID", "+", "\"", "\"", "+", "sessionID", "\n\n", "// start the initial session handshake", "sessionResp", ",", "err", ":=", "cfg", ".", "XHR", ".", "Post", "(", "sessionURL", "+", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "sessionResp", ".", "Body", ".", "Close", "(", ")", "\n\n", "if", "sessionResp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "http", ".", "StatusOK", ",", "sessionResp", ".", "StatusCode", ")", "\n", "}", "\n\n", "frame", ",", "err", ":=", "newFrameReader", "(", "sessionResp", ".", "Body", ",", "cfg", ".", "Timeout", ")", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "frame", "!=", "'o'", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "frame", ")", ")", "\n", "}", "\n\n", "return", "&", "XHRSession", "{", "client", ":", "cfg", ".", "XHR", ",", "timeout", ":", "cfg", ".", "Timeout", ",", "sessionID", ":", "sessionID", ",", "sessionURL", ":", "sessionURL", ",", "state", ":", "sockjs", ".", "SessionActive", ",", "abort", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "}", ",", "nil", "\n", "}" ]
// DialXHR establishes a SockJS session over a XHR connection. // // Requires cfg.XHR to be a valid client.
[ "DialXHR", "establishes", "a", "SockJS", "session", "over", "a", "XHR", "connection", ".", "Requires", "cfg", ".", "XHR", "to", "be", "a", "valid", "client", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/xhr.go#L49-L84
train
koding/kite
handlers.go
ServeKite
func (w *webRTCHandler) ServeKite(r *Request) (interface{}, error) { var args protocol.WebRTCSignalMessage if err := r.Args.One().Unmarshal(&args); err != nil { return nil, fmt.Errorf("invalid query: %s", err) } args.Src = r.Client.ID w.registerSrc(r.Client) dst, err := w.getDst(args.Dst) if err != nil { return nil, err } return nil, dst.SendWebRTCRequest(&args) }
go
func (w *webRTCHandler) ServeKite(r *Request) (interface{}, error) { var args protocol.WebRTCSignalMessage if err := r.Args.One().Unmarshal(&args); err != nil { return nil, fmt.Errorf("invalid query: %s", err) } args.Src = r.Client.ID w.registerSrc(r.Client) dst, err := w.getDst(args.Dst) if err != nil { return nil, err } return nil, dst.SendWebRTCRequest(&args) }
[ "func", "(", "w", "*", "webRTCHandler", ")", "ServeKite", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "args", "protocol", ".", "WebRTCSignalMessage", "\n\n", "if", "err", ":=", "r", ".", "Args", ".", "One", "(", ")", ".", "Unmarshal", "(", "&", "args", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "args", ".", "Src", "=", "r", ".", "Client", ".", "ID", "\n\n", "w", ".", "registerSrc", "(", "r", ".", "Client", ")", "\n\n", "dst", ",", "err", ":=", "w", ".", "getDst", "(", "args", ".", "Dst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "nil", ",", "dst", ".", "SendWebRTCRequest", "(", "&", "args", ")", "\n", "}" ]
// ServeKite implements Hander interface.
[ "ServeKite", "implements", "Hander", "interface", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L64-L81
train
koding/kite
handlers.go
handleLog
func (k *Kite) handleLog(r *Request) (interface{}, error) { msg, err := r.Args.One().String() if err != nil { return nil, err } k.Log.Info("%s: %s", r.Client.Name, msg) return nil, nil }
go
func (k *Kite) handleLog(r *Request) (interface{}, error) { msg, err := r.Args.One().String() if err != nil { return nil, err } k.Log.Info("%s: %s", r.Client.Name, msg) return nil, nil }
[ "func", "(", "k", "*", "Kite", ")", "handleLog", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "msg", ",", "err", ":=", "r", ".", "Args", ".", "One", "(", ")", ".", "String", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "k", ".", "Log", ".", "Info", "(", "\"", "\"", ",", "r", ".", "Client", ".", "Name", ",", "msg", ")", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleLog prints a log message to stderr.
[ "handleLog", "prints", "a", "log", "message", "to", "stderr", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L107-L116
train
koding/kite
handlers.go
handlePrint
func handlePrint(r *Request) (interface{}, error) { return fmt.Print(r.Args.One().MustString()) }
go
func handlePrint(r *Request) (interface{}, error) { return fmt.Print(r.Args.One().MustString()) }
[ "func", "handlePrint", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "fmt", ".", "Print", "(", "r", ".", "Args", ".", "One", "(", ")", ".", "MustString", "(", ")", ")", "\n", "}" ]
// handlePrint prints a message to stdout.
[ "handlePrint", "prints", "a", "message", "to", "stdout", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L124-L126
train
koding/kite
handlers.go
handlePrompt
func handlePrompt(r *Request) (interface{}, error) { fmt.Print(r.Args.One().MustString()) var s string _, err := fmt.Scanln(&s) return s, err }
go
func handlePrompt(r *Request) (interface{}, error) { fmt.Print(r.Args.One().MustString()) var s string _, err := fmt.Scanln(&s) return s, err }
[ "func", "handlePrompt", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "fmt", ".", "Print", "(", "r", ".", "Args", ".", "One", "(", ")", ".", "MustString", "(", ")", ")", "\n", "var", "s", "string", "\n", "_", ",", "err", ":=", "fmt", ".", "Scanln", "(", "&", "s", ")", "\n", "return", "s", ",", "err", "\n", "}" ]
// handlePrompt asks user a single line input.
[ "handlePrompt", "asks", "user", "a", "single", "line", "input", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L129-L134
train
koding/kite
handlers.go
handleGetPass
func handleGetPass(r *Request) (interface{}, error) { fmt.Print(r.Args.One().MustString()) data, err := terminal.ReadPassword(int(os.Stdin.Fd())) // stdin fmt.Println() if err != nil { return nil, err } return string(data), nil }
go
func handleGetPass(r *Request) (interface{}, error) { fmt.Print(r.Args.One().MustString()) data, err := terminal.ReadPassword(int(os.Stdin.Fd())) // stdin fmt.Println() if err != nil { return nil, err } return string(data), nil }
[ "func", "handleGetPass", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "fmt", ".", "Print", "(", "r", ".", "Args", ".", "One", "(", ")", ".", "MustString", "(", ")", ")", "\n", "data", ",", "err", ":=", "terminal", ".", "ReadPassword", "(", "int", "(", "os", ".", "Stdin", ".", "Fd", "(", ")", ")", ")", "// stdin", "\n", "fmt", ".", "Println", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "string", "(", "data", ")", ",", "nil", "\n", "}" ]
// handleGetPass reads a line of input from a terminal without local echo.
[ "handleGetPass", "reads", "a", "line", "of", "input", "from", "a", "terminal", "without", "local", "echo", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L137-L145
train
koding/kite
handlers.go
handleNotifyDarwin
func handleNotifyDarwin(r *Request) (interface{}, error) { args := r.Args.MustSliceOfLength(3) cmd := exec.Command("osascript", "-e", fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\"", args[1].MustString(), args[2].MustString(), args[0].MustString())) return nil, cmd.Start() }
go
func handleNotifyDarwin(r *Request) (interface{}, error) { args := r.Args.MustSliceOfLength(3) cmd := exec.Command("osascript", "-e", fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\"", args[1].MustString(), args[2].MustString(), args[0].MustString())) return nil, cmd.Start() }
[ "func", "handleNotifyDarwin", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "args", ":=", "r", ".", "Args", ".", "MustSliceOfLength", "(", "3", ")", "\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "args", "[", "1", "]", ".", "MustString", "(", ")", ",", "args", "[", "2", "]", ".", "MustString", "(", ")", ",", "args", "[", "0", "]", ".", "MustString", "(", ")", ")", ")", "\n", "return", "nil", ",", "cmd", ".", "Start", "(", ")", "\n", "}" ]
// handleNotifyDarwin displays a desktop notification on OS X.
[ "handleNotifyDarwin", "displays", "a", "desktop", "notification", "on", "OS", "X", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L148-L153
train
koding/kite
handlers.go
handleTunnel
func handleTunnel(r *Request) (interface{}, error) { var args struct { URL string } r.Args.One().MustUnmarshal(&args) parsed, err := url.Parse(args.URL) if err != nil { return nil, err } requestHeader := http.Header{} requestHeader.Add("Origin", "http://"+parsed.Host) remoteConn, _, err := websocket.DefaultDialer.Dial(parsed.String(), requestHeader) if err != nil { return nil, err } session := sockjsclient.NewWebsocketSession(remoteConn) go r.LocalKite.sockjsHandler(session) return nil, nil }
go
func handleTunnel(r *Request) (interface{}, error) { var args struct { URL string } r.Args.One().MustUnmarshal(&args) parsed, err := url.Parse(args.URL) if err != nil { return nil, err } requestHeader := http.Header{} requestHeader.Add("Origin", "http://"+parsed.Host) remoteConn, _, err := websocket.DefaultDialer.Dial(parsed.String(), requestHeader) if err != nil { return nil, err } session := sockjsclient.NewWebsocketSession(remoteConn) go r.LocalKite.sockjsHandler(session) return nil, nil }
[ "func", "handleTunnel", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "args", "struct", "{", "URL", "string", "\n", "}", "\n", "r", ".", "Args", ".", "One", "(", ")", ".", "MustUnmarshal", "(", "&", "args", ")", "\n\n", "parsed", ",", "err", ":=", "url", ".", "Parse", "(", "args", ".", "URL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "requestHeader", ":=", "http", ".", "Header", "{", "}", "\n", "requestHeader", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", "+", "parsed", ".", "Host", ")", "\n\n", "remoteConn", ",", "_", ",", "err", ":=", "websocket", ".", "DefaultDialer", ".", "Dial", "(", "parsed", ".", "String", "(", ")", ",", "requestHeader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "session", ":=", "sockjsclient", ".", "NewWebsocketSession", "(", "remoteConn", ")", "\n\n", "go", "r", ".", "LocalKite", ".", "sockjsHandler", "(", "session", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleTunnel opens two websockets, one to proxy kite and one to itself, // then it copies the message between them.
[ "handleTunnel", "opens", "two", "websockets", "one", "to", "proxy", "kite", "and", "one", "to", "itself", "then", "it", "copies", "the", "message", "between", "them", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L157-L180
train
koding/kite
tokenrenewer.go
parse
func (t *TokenRenewer) parse(tokenString string) error { claims := &kitekey.KiteClaims{} _, err := jwt.ParseWithClaims(tokenString, claims, t.localKite.RSAKey) if err != nil { valErr, ok := err.(*jwt.ValidationError) if !ok { return err } // do noy return for ValidationErrorSignatureValid. This is because we // might asked for a kite who's public Key is different what we have. // We still should be able to send them requests. if (valErr.Errors & jwt.ValidationErrorSignatureInvalid) == 0 { return fmt.Errorf("Cannot parse token: %s", err) } } t.validUntil = time.Unix(claims.ExpiresAt, 0).UTC() return nil }
go
func (t *TokenRenewer) parse(tokenString string) error { claims := &kitekey.KiteClaims{} _, err := jwt.ParseWithClaims(tokenString, claims, t.localKite.RSAKey) if err != nil { valErr, ok := err.(*jwt.ValidationError) if !ok { return err } // do noy return for ValidationErrorSignatureValid. This is because we // might asked for a kite who's public Key is different what we have. // We still should be able to send them requests. if (valErr.Errors & jwt.ValidationErrorSignatureInvalid) == 0 { return fmt.Errorf("Cannot parse token: %s", err) } } t.validUntil = time.Unix(claims.ExpiresAt, 0).UTC() return nil }
[ "func", "(", "t", "*", "TokenRenewer", ")", "parse", "(", "tokenString", "string", ")", "error", "{", "claims", ":=", "&", "kitekey", ".", "KiteClaims", "{", "}", "\n\n", "_", ",", "err", ":=", "jwt", ".", "ParseWithClaims", "(", "tokenString", ",", "claims", ",", "t", ".", "localKite", ".", "RSAKey", ")", "\n", "if", "err", "!=", "nil", "{", "valErr", ",", "ok", ":=", "err", ".", "(", "*", "jwt", ".", "ValidationError", ")", "\n", "if", "!", "ok", "{", "return", "err", "\n", "}", "\n\n", "// do noy return for ValidationErrorSignatureValid. This is because we", "// might asked for a kite who's public Key is different what we have.", "// We still should be able to send them requests.", "if", "(", "valErr", ".", "Errors", "&", "jwt", ".", "ValidationErrorSignatureInvalid", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "t", ".", "validUntil", "=", "time", ".", "Unix", "(", "claims", ".", "ExpiresAt", ",", "0", ")", ".", "UTC", "(", ")", "\n", "return", "nil", "\n", "}" ]
// parse the token string and set
[ "parse", "the", "token", "string", "and", "set" ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/tokenrenewer.go#L41-L61
train
koding/kite
tokenrenewer.go
renewDuration
func (t *TokenRenewer) renewDuration() time.Duration { return t.validUntil.Add(-renewBefore).Sub(time.Now().UTC()) }
go
func (t *TokenRenewer) renewDuration() time.Duration { return t.validUntil.Add(-renewBefore).Sub(time.Now().UTC()) }
[ "func", "(", "t", "*", "TokenRenewer", ")", "renewDuration", "(", ")", "time", ".", "Duration", "{", "return", "t", ".", "validUntil", ".", "Add", "(", "-", "renewBefore", ")", ".", "Sub", "(", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ")", "\n", "}" ]
// The duration from now to the time token needs to be renewed. // Needs to be calculated after renewing the token.
[ "The", "duration", "from", "now", "to", "the", "time", "token", "needs", "to", "be", "renewed", ".", "Needs", "to", "be", "calculated", "after", "renewing", "the", "token", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/tokenrenewer.go#L111-L113
train
koding/kite
tokenrenewer.go
renewToken
func (t *TokenRenewer) renewToken() error { renew := &protocol.Kite{ ID: t.client.Kite.ID, } token, err := t.localKite.GetToken(renew) if err != nil { return err } if err = t.parse(token); err != nil { return err } t.client.authMu.Lock() t.client.Auth.Key = token t.client.authMu.Unlock() t.client.callOnTokenRenewHandlers(token) return nil }
go
func (t *TokenRenewer) renewToken() error { renew := &protocol.Kite{ ID: t.client.Kite.ID, } token, err := t.localKite.GetToken(renew) if err != nil { return err } if err = t.parse(token); err != nil { return err } t.client.authMu.Lock() t.client.Auth.Key = token t.client.authMu.Unlock() t.client.callOnTokenRenewHandlers(token) return nil }
[ "func", "(", "t", "*", "TokenRenewer", ")", "renewToken", "(", ")", "error", "{", "renew", ":=", "&", "protocol", ".", "Kite", "{", "ID", ":", "t", ".", "client", ".", "Kite", ".", "ID", ",", "}", "\n\n", "token", ",", "err", ":=", "t", ".", "localKite", ".", "GetToken", "(", "renew", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "t", ".", "parse", "(", "token", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "t", ".", "client", ".", "authMu", ".", "Lock", "(", ")", "\n", "t", ".", "client", ".", "Auth", ".", "Key", "=", "token", "\n", "t", ".", "client", ".", "authMu", ".", "Unlock", "(", ")", "\n\n", "t", ".", "client", ".", "callOnTokenRenewHandlers", "(", "token", ")", "\n\n", "return", "nil", "\n", "}" ]
// renewToken gets a new token from a kontrolClient, parses it and sets it as the token.
[ "renewToken", "gets", "a", "new", "token", "from", "a", "kontrolClient", "parses", "it", "and", "sets", "it", "as", "the", "token", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/tokenrenewer.go#L144-L165
train
koding/kite
config/config.go
NewFromKiteKey
func NewFromKiteKey(file string) (*Config, error) { key, err := kitekey.ParseFile(file) if err != nil { return nil, err } var c Config if err := c.ReadToken(key); err != nil { return nil, err } return &c, nil }
go
func NewFromKiteKey(file string) (*Config, error) { key, err := kitekey.ParseFile(file) if err != nil { return nil, err } var c Config if err := c.ReadToken(key); err != nil { return nil, err } return &c, nil }
[ "func", "NewFromKiteKey", "(", "file", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "key", ",", "err", ":=", "kitekey", ".", "ParseFile", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "c", "Config", "\n", "if", "err", ":=", "c", ".", "ReadToken", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "c", ",", "nil", "\n", "}" ]
// NewFromKiteKey parses the given kite key file and gives a new Config value.
[ "NewFromKiteKey", "parses", "the", "given", "kite", "key", "file", "and", "gives", "a", "new", "Config", "value", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L154-L166
train
koding/kite
config/config.go
ReadKiteKey
func (c *Config) ReadKiteKey() error { key, err := kitekey.Parse() if err != nil { return err } return c.ReadToken(key) }
go
func (c *Config) ReadKiteKey() error { key, err := kitekey.Parse() if err != nil { return err } return c.ReadToken(key) }
[ "func", "(", "c", "*", "Config", ")", "ReadKiteKey", "(", ")", "error", "{", "key", ",", "err", ":=", "kitekey", ".", "Parse", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "c", ".", "ReadToken", "(", "key", ")", "\n", "}" ]
// ReadKiteKey parsed the user's kite key and returns a new Config.
[ "ReadKiteKey", "parsed", "the", "user", "s", "kite", "key", "and", "returns", "a", "new", "Config", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L244-L251
train
koding/kite
config/config.go
ReadToken
func (c *Config) ReadToken(key *jwt.Token) error { c.KiteKey = key.Raw claims, ok := key.Claims.(*kitekey.KiteClaims) if !ok { return errors.New("no claims found") } c.Username = claims.Subject c.KontrolUser = claims.Issuer c.Id = claims.Id // jti is used for jwt's but let's also use it for kite ID c.KontrolURL = claims.KontrolURL c.KontrolKey = claims.KontrolKey return nil }
go
func (c *Config) ReadToken(key *jwt.Token) error { c.KiteKey = key.Raw claims, ok := key.Claims.(*kitekey.KiteClaims) if !ok { return errors.New("no claims found") } c.Username = claims.Subject c.KontrolUser = claims.Issuer c.Id = claims.Id // jti is used for jwt's but let's also use it for kite ID c.KontrolURL = claims.KontrolURL c.KontrolKey = claims.KontrolKey return nil }
[ "func", "(", "c", "*", "Config", ")", "ReadToken", "(", "key", "*", "jwt", ".", "Token", ")", "error", "{", "c", ".", "KiteKey", "=", "key", ".", "Raw", "\n\n", "claims", ",", "ok", ":=", "key", ".", "Claims", ".", "(", "*", "kitekey", ".", "KiteClaims", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "c", ".", "Username", "=", "claims", ".", "Subject", "\n", "c", ".", "KontrolUser", "=", "claims", ".", "Issuer", "\n", "c", ".", "Id", "=", "claims", ".", "Id", "// jti is used for jwt's but let's also use it for kite ID", "\n", "c", ".", "KontrolURL", "=", "claims", ".", "KontrolURL", "\n", "c", ".", "KontrolKey", "=", "claims", ".", "KontrolKey", "\n\n", "return", "nil", "\n", "}" ]
// ReadToken reads Kite Claims from JWT token and uses them to initialize Config.
[ "ReadToken", "reads", "Kite", "Claims", "from", "JWT", "token", "and", "uses", "them", "to", "initialize", "Config", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L254-L269
train
koding/kite
config/config.go
Copy
func (c *Config) Copy() *Config { copy := *c if c.XHR != nil { xhr := *copy.XHR copy.XHR = &xhr } if c.Client != nil { client := *copy.Client copy.Client = &client } if c.Websocket != nil { ws := *copy.Websocket copy.Websocket = &ws } return &copy }
go
func (c *Config) Copy() *Config { copy := *c if c.XHR != nil { xhr := *copy.XHR copy.XHR = &xhr } if c.Client != nil { client := *copy.Client copy.Client = &client } if c.Websocket != nil { ws := *copy.Websocket copy.Websocket = &ws } return &copy }
[ "func", "(", "c", "*", "Config", ")", "Copy", "(", ")", "*", "Config", "{", "copy", ":=", "*", "c", "\n\n", "if", "c", ".", "XHR", "!=", "nil", "{", "xhr", ":=", "*", "copy", ".", "XHR", "\n", "copy", ".", "XHR", "=", "&", "xhr", "\n", "}", "\n\n", "if", "c", ".", "Client", "!=", "nil", "{", "client", ":=", "*", "copy", ".", "Client", "\n", "copy", ".", "Client", "=", "&", "client", "\n", "}", "\n\n", "if", "c", ".", "Websocket", "!=", "nil", "{", "ws", ":=", "*", "copy", ".", "Websocket", "\n", "copy", ".", "Websocket", "=", "&", "ws", "\n", "}", "\n\n", "return", "&", "copy", "\n", "}" ]
// Copy returns a new copy of the config object.
[ "Copy", "returns", "a", "new", "copy", "of", "the", "config", "object", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L272-L291
train
koding/kite
request.go
runMethod
func (c *Client) runMethod(method *Method, args *dnode.Partial) { var ( callFunc func(interface{}, *Error) request *Request ) // Recover dnode argument errors and send them back. The caller can use // functions like MustString(), MustSlice()... without the fear of panic. defer func() { if r := recover(); r != nil { debug.PrintStack() kiteErr := createError(request, r) c.LocalKite.Log.Error(kiteErr.Error()) // let's log it too :) callFunc(nil, kiteErr) } }() // The request that will be constructed from incoming dnode message. request, callFunc = c.newRequest(method.name, args) if method.authenticate { if err := request.authenticate(); err != nil { callFunc(nil, createError(request, err)) return } } else { // if not validated accept any username it sends, also useful for test // cases. request.Username = request.Client.Kite.Username } method.mu.Lock() if !method.initialized { method.preHandlers = append(method.preHandlers, c.LocalKite.preHandlers...) method.postHandlers = append(method.postHandlers, c.LocalKite.postHandlers...) method.finalFuncs = append(method.finalFuncs, c.LocalKite.finalFuncs...) method.initialized = true } method.mu.Unlock() // check if any throttling is enabled and then check token's available. // Tokens are filled per frequency of the initial bucket, so every request // is going to take one token from the bucket. If many requests come in (in // span time larger than the bucket's frequency), there will be no token's // available more so it will return a zero. if method.bucket != nil && method.bucket.TakeAvailable(1) == 0 { callFunc(nil, &Error{ Type: "requestLimitError", Message: "The maximum request rate is exceeded.", RequestID: request.ID, }) return } // Call the handler functions. result, err := method.ServeKite(request) callFunc(result, createError(request, err)) }
go
func (c *Client) runMethod(method *Method, args *dnode.Partial) { var ( callFunc func(interface{}, *Error) request *Request ) // Recover dnode argument errors and send them back. The caller can use // functions like MustString(), MustSlice()... without the fear of panic. defer func() { if r := recover(); r != nil { debug.PrintStack() kiteErr := createError(request, r) c.LocalKite.Log.Error(kiteErr.Error()) // let's log it too :) callFunc(nil, kiteErr) } }() // The request that will be constructed from incoming dnode message. request, callFunc = c.newRequest(method.name, args) if method.authenticate { if err := request.authenticate(); err != nil { callFunc(nil, createError(request, err)) return } } else { // if not validated accept any username it sends, also useful for test // cases. request.Username = request.Client.Kite.Username } method.mu.Lock() if !method.initialized { method.preHandlers = append(method.preHandlers, c.LocalKite.preHandlers...) method.postHandlers = append(method.postHandlers, c.LocalKite.postHandlers...) method.finalFuncs = append(method.finalFuncs, c.LocalKite.finalFuncs...) method.initialized = true } method.mu.Unlock() // check if any throttling is enabled and then check token's available. // Tokens are filled per frequency of the initial bucket, so every request // is going to take one token from the bucket. If many requests come in (in // span time larger than the bucket's frequency), there will be no token's // available more so it will return a zero. if method.bucket != nil && method.bucket.TakeAvailable(1) == 0 { callFunc(nil, &Error{ Type: "requestLimitError", Message: "The maximum request rate is exceeded.", RequestID: request.ID, }) return } // Call the handler functions. result, err := method.ServeKite(request) callFunc(result, createError(request, err)) }
[ "func", "(", "c", "*", "Client", ")", "runMethod", "(", "method", "*", "Method", ",", "args", "*", "dnode", ".", "Partial", ")", "{", "var", "(", "callFunc", "func", "(", "interface", "{", "}", ",", "*", "Error", ")", "\n", "request", "*", "Request", "\n", ")", "\n\n", "// Recover dnode argument errors and send them back. The caller can use", "// functions like MustString(), MustSlice()... without the fear of panic.", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "debug", ".", "PrintStack", "(", ")", "\n", "kiteErr", ":=", "createError", "(", "request", ",", "r", ")", "\n", "c", ".", "LocalKite", ".", "Log", ".", "Error", "(", "kiteErr", ".", "Error", "(", ")", ")", "// let's log it too :)", "\n", "callFunc", "(", "nil", ",", "kiteErr", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// The request that will be constructed from incoming dnode message.", "request", ",", "callFunc", "=", "c", ".", "newRequest", "(", "method", ".", "name", ",", "args", ")", "\n", "if", "method", ".", "authenticate", "{", "if", "err", ":=", "request", ".", "authenticate", "(", ")", ";", "err", "!=", "nil", "{", "callFunc", "(", "nil", ",", "createError", "(", "request", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "// if not validated accept any username it sends, also useful for test", "// cases.", "request", ".", "Username", "=", "request", ".", "Client", ".", "Kite", ".", "Username", "\n", "}", "\n\n", "method", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "!", "method", ".", "initialized", "{", "method", ".", "preHandlers", "=", "append", "(", "method", ".", "preHandlers", ",", "c", ".", "LocalKite", ".", "preHandlers", "...", ")", "\n", "method", ".", "postHandlers", "=", "append", "(", "method", ".", "postHandlers", ",", "c", ".", "LocalKite", ".", "postHandlers", "...", ")", "\n", "method", ".", "finalFuncs", "=", "append", "(", "method", ".", "finalFuncs", ",", "c", ".", "LocalKite", ".", "finalFuncs", "...", ")", "\n", "method", ".", "initialized", "=", "true", "\n", "}", "\n", "method", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// check if any throttling is enabled and then check token's available.", "// Tokens are filled per frequency of the initial bucket, so every request", "// is going to take one token from the bucket. If many requests come in (in", "// span time larger than the bucket's frequency), there will be no token's", "// available more so it will return a zero.", "if", "method", ".", "bucket", "!=", "nil", "&&", "method", ".", "bucket", ".", "TakeAvailable", "(", "1", ")", "==", "0", "{", "callFunc", "(", "nil", ",", "&", "Error", "{", "Type", ":", "\"", "\"", ",", "Message", ":", "\"", "\"", ",", "RequestID", ":", "request", ".", "ID", ",", "}", ")", "\n", "return", "\n", "}", "\n\n", "// Call the handler functions.", "result", ",", "err", ":=", "method", ".", "ServeKite", "(", "request", ")", "\n\n", "callFunc", "(", "result", ",", "createError", "(", "request", ",", "err", ")", ")", "\n", "}" ]
// runMethod is called when a method is received from remote Kite.
[ "runMethod", "is", "called", "when", "a", "method", "is", "received", "from", "remote", "Kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L62-L119
train
koding/kite
request.go
runCallback
func (c *Client) runCallback(callback func(*dnode.Partial), args *dnode.Partial) { // Do not panic no matter what. defer func() { if err := recover(); err != nil { c.LocalKite.Log.Warning("Error in calling the callback function : %v", err) } }() // Call the callback function. callback(args) }
go
func (c *Client) runCallback(callback func(*dnode.Partial), args *dnode.Partial) { // Do not panic no matter what. defer func() { if err := recover(); err != nil { c.LocalKite.Log.Warning("Error in calling the callback function : %v", err) } }() // Call the callback function. callback(args) }
[ "func", "(", "c", "*", "Client", ")", "runCallback", "(", "callback", "func", "(", "*", "dnode", ".", "Partial", ")", ",", "args", "*", "dnode", ".", "Partial", ")", "{", "// Do not panic no matter what.", "defer", "func", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", "c", ".", "LocalKite", ".", "Log", ".", "Warning", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Call the callback function.", "callback", "(", "args", ")", "\n", "}" ]
// runCallback is called when a callback method call is received from remote Kite.
[ "runCallback", "is", "called", "when", "a", "callback", "method", "call", "is", "received", "from", "remote", "Kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L122-L132
train
koding/kite
request.go
authenticate
func (r *Request) authenticate() *Error { // Trust the Kite if we have initiated the connection. Following casts // means, session is opened by the client. if _, ok := r.Client.session.(*sockjsclient.WebsocketSession); ok { return nil } if _, ok := r.Client.session.(*sockjsclient.XHRSession); ok { return nil } if r.Auth == nil { return &Error{ Type: "authenticationError", Message: "No authentication information is provided", } } // Select authenticator function. f := r.LocalKite.Authenticators[r.Auth.Type] if f == nil { return &Error{ Type: "authenticationError", Message: fmt.Sprintf("Unknown authentication type: %s", r.Auth.Type), } } // Call authenticator function. It sets the Request.Username field. err := f(r) if err != nil { return &Error{ Type: "authenticationError", Message: fmt.Sprintf("%s: %s", r.Auth.Type, err), } } // Replace username of the remote Kite with the username that client send // us. This prevents a Kite to impersonate someone else's Kite. r.Client.SetUsername(r.Username) return nil }
go
func (r *Request) authenticate() *Error { // Trust the Kite if we have initiated the connection. Following casts // means, session is opened by the client. if _, ok := r.Client.session.(*sockjsclient.WebsocketSession); ok { return nil } if _, ok := r.Client.session.(*sockjsclient.XHRSession); ok { return nil } if r.Auth == nil { return &Error{ Type: "authenticationError", Message: "No authentication information is provided", } } // Select authenticator function. f := r.LocalKite.Authenticators[r.Auth.Type] if f == nil { return &Error{ Type: "authenticationError", Message: fmt.Sprintf("Unknown authentication type: %s", r.Auth.Type), } } // Call authenticator function. It sets the Request.Username field. err := f(r) if err != nil { return &Error{ Type: "authenticationError", Message: fmt.Sprintf("%s: %s", r.Auth.Type, err), } } // Replace username of the remote Kite with the username that client send // us. This prevents a Kite to impersonate someone else's Kite. r.Client.SetUsername(r.Username) return nil }
[ "func", "(", "r", "*", "Request", ")", "authenticate", "(", ")", "*", "Error", "{", "// Trust the Kite if we have initiated the connection. Following casts", "// means, session is opened by the client.", "if", "_", ",", "ok", ":=", "r", ".", "Client", ".", "session", ".", "(", "*", "sockjsclient", ".", "WebsocketSession", ")", ";", "ok", "{", "return", "nil", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "r", ".", "Client", ".", "session", ".", "(", "*", "sockjsclient", ".", "XHRSession", ")", ";", "ok", "{", "return", "nil", "\n", "}", "\n\n", "if", "r", ".", "Auth", "==", "nil", "{", "return", "&", "Error", "{", "Type", ":", "\"", "\"", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "// Select authenticator function.", "f", ":=", "r", ".", "LocalKite", ".", "Authenticators", "[", "r", ".", "Auth", ".", "Type", "]", "\n", "if", "f", "==", "nil", "{", "return", "&", "Error", "{", "Type", ":", "\"", "\"", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "Auth", ".", "Type", ")", ",", "}", "\n", "}", "\n\n", "// Call authenticator function. It sets the Request.Username field.", "err", ":=", "f", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "Error", "{", "Type", ":", "\"", "\"", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "Auth", ".", "Type", ",", "err", ")", ",", "}", "\n", "}", "\n\n", "// Replace username of the remote Kite with the username that client send", "// us. This prevents a Kite to impersonate someone else's Kite.", "r", ".", "Client", ".", "SetUsername", "(", "r", ".", "Username", ")", "\n", "return", "nil", "\n", "}" ]
// authenticate tries to authenticate the user by selecting appropriate // authenticator function.
[ "authenticate", "tries", "to", "authenticate", "the", "user", "by", "selecting", "appropriate", "authenticator", "function", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L182-L222
train
koding/kite
request.go
AuthenticateFromToken
func (k *Kite) AuthenticateFromToken(r *Request) error { k.verifyOnce.Do(k.verifyInit) token, err := jwt.ParseWithClaims(r.Auth.Key, &kitekey.KiteClaims{}, r.LocalKite.RSAKey) if e, ok := err.(*jwt.ValidationError); ok { // Translate public key mismatch errors to token-is-expired one. // This is to signal remote client the key pairs have been // updated on kontrol and it should invalidate all tokens. if (e.Errors & jwt.ValidationErrorSignatureInvalid) != 0 { return errors.New("token is expired") } } if err != nil { return err } if !token.Valid { return errors.New("Invalid signature in token") } claims, ok := token.Claims.(*kitekey.KiteClaims) if !ok { return errors.New("token does not have valid claims") } if claims.Audience == "" { return errors.New("token has no audience") } if claims.Subject == "" { return errors.New("token has no username") } // check if we have an audience and it matches our own signature if err := k.verifyAudienceFunc(k.Kite(), claims.Audience); err != nil { return err } // We don't check for exp and nbf claims here because jwt-go package // already checks them. // replace the requester username so we reflect the validated r.Username = claims.Subject return nil }
go
func (k *Kite) AuthenticateFromToken(r *Request) error { k.verifyOnce.Do(k.verifyInit) token, err := jwt.ParseWithClaims(r.Auth.Key, &kitekey.KiteClaims{}, r.LocalKite.RSAKey) if e, ok := err.(*jwt.ValidationError); ok { // Translate public key mismatch errors to token-is-expired one. // This is to signal remote client the key pairs have been // updated on kontrol and it should invalidate all tokens. if (e.Errors & jwt.ValidationErrorSignatureInvalid) != 0 { return errors.New("token is expired") } } if err != nil { return err } if !token.Valid { return errors.New("Invalid signature in token") } claims, ok := token.Claims.(*kitekey.KiteClaims) if !ok { return errors.New("token does not have valid claims") } if claims.Audience == "" { return errors.New("token has no audience") } if claims.Subject == "" { return errors.New("token has no username") } // check if we have an audience and it matches our own signature if err := k.verifyAudienceFunc(k.Kite(), claims.Audience); err != nil { return err } // We don't check for exp and nbf claims here because jwt-go package // already checks them. // replace the requester username so we reflect the validated r.Username = claims.Subject return nil }
[ "func", "(", "k", "*", "Kite", ")", "AuthenticateFromToken", "(", "r", "*", "Request", ")", "error", "{", "k", ".", "verifyOnce", ".", "Do", "(", "k", ".", "verifyInit", ")", "\n\n", "token", ",", "err", ":=", "jwt", ".", "ParseWithClaims", "(", "r", ".", "Auth", ".", "Key", ",", "&", "kitekey", ".", "KiteClaims", "{", "}", ",", "r", ".", "LocalKite", ".", "RSAKey", ")", "\n\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "*", "jwt", ".", "ValidationError", ")", ";", "ok", "{", "// Translate public key mismatch errors to token-is-expired one.", "// This is to signal remote client the key pairs have been", "// updated on kontrol and it should invalidate all tokens.", "if", "(", "e", ".", "Errors", "&", "jwt", ".", "ValidationErrorSignatureInvalid", ")", "!=", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "token", ".", "Valid", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "claims", ",", "ok", ":=", "token", ".", "Claims", ".", "(", "*", "kitekey", ".", "KiteClaims", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "claims", ".", "Audience", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "claims", ".", "Subject", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// check if we have an audience and it matches our own signature", "if", "err", ":=", "k", ".", "verifyAudienceFunc", "(", "k", ".", "Kite", "(", ")", ",", "claims", ".", "Audience", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// We don't check for exp and nbf claims here because jwt-go package", "// already checks them.", "// replace the requester username so we reflect the validated", "r", ".", "Username", "=", "claims", ".", "Subject", "\n\n", "return", "nil", "\n", "}" ]
// AuthenticateFromToken is the default Authenticator for Kite.
[ "AuthenticateFromToken", "is", "the", "default", "Authenticator", "for", "Kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L225-L272
train
koding/kite
request.go
AuthenticateFromKiteKey
func (k *Kite) AuthenticateFromKiteKey(r *Request) error { claims := &kitekey.KiteClaims{} token, err := jwt.ParseWithClaims(r.Auth.Key, claims, k.verify) if err != nil { return err } if !token.Valid { return errors.New("Invalid signature in kite key") } if claims.Subject == "" { return errors.New("token has no username") } r.Username = claims.Subject return nil }
go
func (k *Kite) AuthenticateFromKiteKey(r *Request) error { claims := &kitekey.KiteClaims{} token, err := jwt.ParseWithClaims(r.Auth.Key, claims, k.verify) if err != nil { return err } if !token.Valid { return errors.New("Invalid signature in kite key") } if claims.Subject == "" { return errors.New("token has no username") } r.Username = claims.Subject return nil }
[ "func", "(", "k", "*", "Kite", ")", "AuthenticateFromKiteKey", "(", "r", "*", "Request", ")", "error", "{", "claims", ":=", "&", "kitekey", ".", "KiteClaims", "{", "}", "\n\n", "token", ",", "err", ":=", "jwt", ".", "ParseWithClaims", "(", "r", ".", "Auth", ".", "Key", ",", "claims", ",", "k", ".", "verify", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "token", ".", "Valid", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "claims", ".", "Subject", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "r", ".", "Username", "=", "claims", ".", "Subject", "\n\n", "return", "nil", "\n", "}" ]
// AuthenticateFromKiteKey authenticates user from kite key.
[ "AuthenticateFromKiteKey", "authenticates", "user", "from", "kite", "key", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L275-L294
train
koding/kite
registerurl.go
publicIP
func publicIP() (net.IP, error) { resp, err := http.Get(publicEcho) if err != nil { return nil, err } defer resp.Body.Close() // The ip address is 16 chars long, we read more // to account for excessive whitespace. p, err := ioutil.ReadAll(io.LimitReader(resp.Body, 24)) if err != nil { return nil, err } n := net.ParseIP(string(bytes.TrimSpace(p))) if n == nil { return nil, fmt.Errorf("cannot parse ip %s", p) } return n, nil }
go
func publicIP() (net.IP, error) { resp, err := http.Get(publicEcho) if err != nil { return nil, err } defer resp.Body.Close() // The ip address is 16 chars long, we read more // to account for excessive whitespace. p, err := ioutil.ReadAll(io.LimitReader(resp.Body, 24)) if err != nil { return nil, err } n := net.ParseIP(string(bytes.TrimSpace(p))) if n == nil { return nil, fmt.Errorf("cannot parse ip %s", p) } return n, nil }
[ "func", "publicIP", "(", ")", "(", "net", ".", "IP", ",", "error", ")", "{", "resp", ",", "err", ":=", "http", ".", "Get", "(", "publicEcho", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "// The ip address is 16 chars long, we read more", "// to account for excessive whitespace.", "p", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "io", ".", "LimitReader", "(", "resp", ".", "Body", ",", "24", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "n", ":=", "net", ".", "ParseIP", "(", "string", "(", "bytes", ".", "TrimSpace", "(", "p", ")", ")", ")", "\n", "if", "n", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ")", "\n", "}", "\n\n", "return", "n", ",", "nil", "\n", "}" ]
// publicIP returns an IP that is supposed to be Public.
[ "publicIP", "returns", "an", "IP", "that", "is", "supposed", "to", "be", "Public", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/registerurl.go#L80-L100
train
koding/kite
kitectl/command/install.go
extractTar
func extractTar(r io.Reader, dir string) error { first := true // true if we are on the first entry of tarball tr := tar.NewReader(r) for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return err } // Check if the same kite version is installed before if first { first = false kiteName := strings.TrimSuffix(hdr.Name, ".kite/") installed, err := isInstalled(kiteName) if err != nil { return err } if installed { return fmt.Errorf("Already installed: %s", kiteName) } } path := filepath.Join(dir, hdr.Name) if hdr.FileInfo().IsDir() { os.MkdirAll(path, 0700) } else { mode := 0600 if isBinaryFile(hdr.Name) { mode = 0700 } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(mode)) if err != nil { return err } if _, err := io.Copy(f, tr); err != nil { return err } } } return nil }
go
func extractTar(r io.Reader, dir string) error { first := true // true if we are on the first entry of tarball tr := tar.NewReader(r) for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return err } // Check if the same kite version is installed before if first { first = false kiteName := strings.TrimSuffix(hdr.Name, ".kite/") installed, err := isInstalled(kiteName) if err != nil { return err } if installed { return fmt.Errorf("Already installed: %s", kiteName) } } path := filepath.Join(dir, hdr.Name) if hdr.FileInfo().IsDir() { os.MkdirAll(path, 0700) } else { mode := 0600 if isBinaryFile(hdr.Name) { mode = 0700 } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(mode)) if err != nil { return err } if _, err := io.Copy(f, tr); err != nil { return err } } } return nil }
[ "func", "extractTar", "(", "r", "io", ".", "Reader", ",", "dir", "string", ")", "error", "{", "first", ":=", "true", "// true if we are on the first entry of tarball", "\n", "tr", ":=", "tar", ".", "NewReader", "(", "r", ")", "\n", "for", "{", "hdr", ",", "err", ":=", "tr", ".", "Next", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "// end of tar archive", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check if the same kite version is installed before", "if", "first", "{", "first", "=", "false", "\n", "kiteName", ":=", "strings", ".", "TrimSuffix", "(", "hdr", ".", "Name", ",", "\"", "\"", ")", "\n\n", "installed", ",", "err", ":=", "isInstalled", "(", "kiteName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "installed", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "kiteName", ")", "\n", "}", "\n", "}", "\n\n", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "hdr", ".", "Name", ")", "\n\n", "if", "hdr", ".", "FileInfo", "(", ")", ".", "IsDir", "(", ")", "{", "os", ".", "MkdirAll", "(", "path", ",", "0700", ")", "\n", "}", "else", "{", "mode", ":=", "0600", "\n", "if", "isBinaryFile", "(", "hdr", ".", "Name", ")", "{", "mode", "=", "0700", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "os", ".", "FileMode", "(", "mode", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "f", ",", "tr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// extractTar reads from the io.Reader and writes the files into the directory.
[ "extractTar", "reads", "from", "the", "io", ".", "Reader", "and", "writes", "the", "files", "into", "the", "directory", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kitectl/command/install.go#L189-L238
train
koding/kite
kitectl/command/install.go
validatePackage
func validatePackage(tempKitePath, repoName string) (bundlePath string, err error) { dirs, err := ioutil.ReadDir(tempKitePath) if err != nil { return "", err } if len(dirs) != 1 { return "", errors.New("Invalid package: Package must contain only one directory.") } bundlePath = filepath.Join(tempKitePath, dirs[0].Name()) parts := strings.Split(repoName, "/") if len(parts) == 0 { return "", errors.New("invalid repo URL") } kiteName := strings.TrimSuffix(parts[len(parts)-1], ".kite") _, err = os.Stat(filepath.Join(bundlePath, "bin", kiteName)) return bundlePath, err }
go
func validatePackage(tempKitePath, repoName string) (bundlePath string, err error) { dirs, err := ioutil.ReadDir(tempKitePath) if err != nil { return "", err } if len(dirs) != 1 { return "", errors.New("Invalid package: Package must contain only one directory.") } bundlePath = filepath.Join(tempKitePath, dirs[0].Name()) parts := strings.Split(repoName, "/") if len(parts) == 0 { return "", errors.New("invalid repo URL") } kiteName := strings.TrimSuffix(parts[len(parts)-1], ".kite") _, err = os.Stat(filepath.Join(bundlePath, "bin", kiteName)) return bundlePath, err }
[ "func", "validatePackage", "(", "tempKitePath", ",", "repoName", "string", ")", "(", "bundlePath", "string", ",", "err", "error", ")", "{", "dirs", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "tempKitePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "dirs", ")", "!=", "1", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "bundlePath", "=", "filepath", ".", "Join", "(", "tempKitePath", ",", "dirs", "[", "0", "]", ".", "Name", "(", ")", ")", "\n\n", "parts", ":=", "strings", ".", "Split", "(", "repoName", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "==", "0", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "kiteName", ":=", "strings", ".", "TrimSuffix", "(", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", ",", "\"", "\"", ")", "\n\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "bundlePath", ",", "\"", "\"", ",", "kiteName", ")", ")", "\n", "return", "bundlePath", ",", "err", "\n", "}" ]
// validatePackage does some checks on kite bundle and returns the bundle path.
[ "validatePackage", "does", "some", "checks", "on", "kite", "bundle", "and", "returns", "the", "bundle", "path", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kitectl/command/install.go#L241-L262
train
koding/kite
dnode/scrubber.go
RemoveCallback
func (s *Scrubber) RemoveCallback(id uint64) { s.Lock() delete(s.callbacks, id) s.Unlock() }
go
func (s *Scrubber) RemoveCallback(id uint64) { s.Lock() delete(s.callbacks, id) s.Unlock() }
[ "func", "(", "s", "*", "Scrubber", ")", "RemoveCallback", "(", "id", "uint64", ")", "{", "s", ".", "Lock", "(", ")", "\n", "delete", "(", "s", ".", "callbacks", ",", "id", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// RemoveCallback removes the callback with id from callbacks. // Can be used to remove unused callbacks to free memory.
[ "RemoveCallback", "removes", "the", "callback", "with", "id", "from", "callbacks", ".", "Can", "be", "used", "to", "remove", "unused", "callbacks", "to", "free", "memory", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/scrubber.go#L24-L28
train
koding/kite
method.go
addHandle
func (k *Kite) addHandle(method string, handler Handler) *Method { authenticate := true if k.Config.DisableAuthentication { authenticate = false } m := &Method{ name: method, handler: handler, authenticate: authenticate, handling: k.MethodHandling, } k.handlers[method] = m return m }
go
func (k *Kite) addHandle(method string, handler Handler) *Method { authenticate := true if k.Config.DisableAuthentication { authenticate = false } m := &Method{ name: method, handler: handler, authenticate: authenticate, handling: k.MethodHandling, } k.handlers[method] = m return m }
[ "func", "(", "k", "*", "Kite", ")", "addHandle", "(", "method", "string", ",", "handler", "Handler", ")", "*", "Method", "{", "authenticate", ":=", "true", "\n", "if", "k", ".", "Config", ".", "DisableAuthentication", "{", "authenticate", "=", "false", "\n", "}", "\n\n", "m", ":=", "&", "Method", "{", "name", ":", "method", ",", "handler", ":", "handler", ",", "authenticate", ":", "authenticate", ",", "handling", ":", "k", ".", "MethodHandling", ",", "}", "\n\n", "k", ".", "handlers", "[", "method", "]", "=", "m", "\n", "return", "m", "\n", "}" ]
// addHandle is an internal method to add a handler
[ "addHandle", "is", "an", "internal", "method", "to", "add", "a", "handler" ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L78-L93
train
koding/kite
method.go
PreHandle
func (m *Method) PreHandle(handler Handler) *Method { m.preHandlers = append(m.preHandlers, handler) return m }
go
func (m *Method) PreHandle(handler Handler) *Method { m.preHandlers = append(m.preHandlers, handler) return m }
[ "func", "(", "m", "*", "Method", ")", "PreHandle", "(", "handler", "Handler", ")", "*", "Method", "{", "m", ".", "preHandlers", "=", "append", "(", "m", ".", "preHandlers", ",", "handler", ")", "\n", "return", "m", "\n", "}" ]
// PreHandler adds a new kite handler which is executed before the method.
[ "PreHandler", "adds", "a", "new", "kite", "handler", "which", "is", "executed", "before", "the", "method", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L126-L129
train
koding/kite
method.go
PostHandle
func (m *Method) PostHandle(handler Handler) *Method { m.postHandlers = append(m.postHandlers, handler) return m }
go
func (m *Method) PostHandle(handler Handler) *Method { m.postHandlers = append(m.postHandlers, handler) return m }
[ "func", "(", "m", "*", "Method", ")", "PostHandle", "(", "handler", "Handler", ")", "*", "Method", "{", "m", ".", "postHandlers", "=", "append", "(", "m", ".", "postHandlers", ",", "handler", ")", "\n", "return", "m", "\n", "}" ]
// PostHandle adds a new kite handler which is executed after the method.
[ "PostHandle", "adds", "a", "new", "kite", "handler", "which", "is", "executed", "after", "the", "method", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L138-L141
train
koding/kite
method.go
FinalFunc
func (m *Method) FinalFunc(f FinalFunc) *Method { m.finalFuncs = append(m.finalFuncs, f) return m }
go
func (m *Method) FinalFunc(f FinalFunc) *Method { m.finalFuncs = append(m.finalFuncs, f) return m }
[ "func", "(", "m", "*", "Method", ")", "FinalFunc", "(", "f", "FinalFunc", ")", "*", "Method", "{", "m", ".", "finalFuncs", "=", "append", "(", "m", ".", "finalFuncs", ",", "f", ")", "\n", "return", "m", "\n", "}" ]
// FinalFunc registers a function that is always called as a last one // after pre-, handler and post- functions for the given method. // // It receives a result and an error from last handler that // got executed prior to calling final func.
[ "FinalFunc", "registers", "a", "function", "that", "is", "always", "called", "as", "a", "last", "one", "after", "pre", "-", "handler", "and", "post", "-", "functions", "for", "the", "given", "method", ".", "It", "receives", "a", "result", "and", "an", "error", "from", "last", "handler", "that", "got", "executed", "prior", "to", "calling", "final", "func", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L154-L157
train
koding/kite
method.go
Handle
func (k *Kite) Handle(method string, handler Handler) *Method { return k.addHandle(method, handler) }
go
func (k *Kite) Handle(method string, handler Handler) *Method { return k.addHandle(method, handler) }
[ "func", "(", "k", "*", "Kite", ")", "Handle", "(", "method", "string", ",", "handler", "Handler", ")", "*", "Method", "{", "return", "k", ".", "addHandle", "(", "method", ",", "handler", ")", "\n", "}" ]
// Handle registers the handler for the given method. The handler is called // when a method call is received from a Kite.
[ "Handle", "registers", "the", "handler", "for", "the", "given", "method", ".", "The", "handler", "is", "called", "when", "a", "method", "call", "is", "received", "from", "a", "Kite", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L161-L163
train
koding/kite
method.go
PreHandle
func (k *Kite) PreHandle(handler Handler) { k.preHandlers = append(k.preHandlers, handler) }
go
func (k *Kite) PreHandle(handler Handler) { k.preHandlers = append(k.preHandlers, handler) }
[ "func", "(", "k", "*", "Kite", ")", "PreHandle", "(", "handler", "Handler", ")", "{", "k", ".", "preHandlers", "=", "append", "(", "k", ".", "preHandlers", ",", "handler", ")", "\n", "}" ]
// PreHandle registers an handler which is executed before a kite.Handler // method is executed. Calling PreHandle multiple times registers multiple // handlers. A non-error return triggers the execution of the next handler. The // execution order is FIFO.
[ "PreHandle", "registers", "an", "handler", "which", "is", "executed", "before", "a", "kite", ".", "Handler", "method", "is", "executed", ".", "Calling", "PreHandle", "multiple", "times", "registers", "multiple", "handlers", ".", "A", "non", "-", "error", "return", "triggers", "the", "execution", "of", "the", "next", "handler", ".", "The", "execution", "order", "is", "FIFO", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L176-L178
train
koding/kite
method.go
PostHandle
func (k *Kite) PostHandle(handler Handler) { k.postHandlers = append(k.postHandlers, handler) }
go
func (k *Kite) PostHandle(handler Handler) { k.postHandlers = append(k.postHandlers, handler) }
[ "func", "(", "k", "*", "Kite", ")", "PostHandle", "(", "handler", "Handler", ")", "{", "k", ".", "postHandlers", "=", "append", "(", "k", ".", "postHandlers", ",", "handler", ")", "\n", "}" ]
// PostHandle registers an handler which is executed after a kite.Handler // method is executed. Calling PostHandler multiple times registers multiple // handlers. A non-error return triggers the execution of the next handler. The // execution order is FIFO.
[ "PostHandle", "registers", "an", "handler", "which", "is", "executed", "after", "a", "kite", ".", "Handler", "method", "is", "executed", ".", "Calling", "PostHandler", "multiple", "times", "registers", "multiple", "handlers", ".", "A", "non", "-", "error", "return", "triggers", "the", "execution", "of", "the", "next", "handler", ".", "The", "execution", "order", "is", "FIFO", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L189-L191
train
koding/kite
method.go
FinalFunc
func (k *Kite) FinalFunc(f FinalFunc) { k.finalFuncs = append(k.finalFuncs, f) }
go
func (k *Kite) FinalFunc(f FinalFunc) { k.finalFuncs = append(k.finalFuncs, f) }
[ "func", "(", "k", "*", "Kite", ")", "FinalFunc", "(", "f", "FinalFunc", ")", "{", "k", ".", "finalFuncs", "=", "append", "(", "k", ".", "finalFuncs", ",", "f", ")", "\n", "}" ]
// FinalFunc registers a function that is always called as a last one // after pre-, handler and post- functions. // // It receives a result and an error from last handler that // got executed prior to calling final func.
[ "FinalFunc", "registers", "a", "function", "that", "is", "always", "called", "as", "a", "last", "one", "after", "pre", "-", "handler", "and", "post", "-", "functions", ".", "It", "receives", "a", "result", "and", "an", "error", "from", "last", "handler", "that", "got", "executed", "prior", "to", "calling", "final", "func", "." ]
baa1a54919e3035417f7571dd46005e91afe8abe
https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L203-L205
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/httpserver/path.go
Matches
func (p Path) Matches(other string) bool { if CaseSensitivePath { return strings.HasPrefix(string(p), other) } return strings.HasPrefix(strings.ToLower(string(p)), strings.ToLower(other)) }
go
func (p Path) Matches(other string) bool { if CaseSensitivePath { return strings.HasPrefix(string(p), other) } return strings.HasPrefix(strings.ToLower(string(p)), strings.ToLower(other)) }
[ "func", "(", "p", "Path", ")", "Matches", "(", "other", "string", ")", "bool", "{", "if", "CaseSensitivePath", "{", "return", "strings", ".", "HasPrefix", "(", "string", "(", "p", ")", ",", "other", ")", "\n", "}", "\n", "return", "strings", ".", "HasPrefix", "(", "strings", ".", "ToLower", "(", "string", "(", "p", ")", ")", ",", "strings", ".", "ToLower", "(", "other", ")", ")", "\n", "}" ]
// Matches checks to see if other matches p. // // Path matching will probably not always be a direct // comparison; this method assures that paths can be // easily and consistently matched.
[ "Matches", "checks", "to", "see", "if", "other", "matches", "p", ".", "Path", "matching", "will", "probably", "not", "always", "be", "a", "direct", "comparison", ";", "this", "method", "assures", "that", "paths", "can", "be", "easily", "and", "consistently", "matched", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/path.go#L16-L21
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/gzip/gzip.go
Write
func (w *gzipResponseWriter) Write(b []byte) (int, error) { if w.Header().Get("Content-Type") == "" { w.Header().Set("Content-Type", http.DetectContentType(b)) } if !w.statusCodeWritten { w.WriteHeader(http.StatusOK) } n, err := w.Writer.Write(b) return n, err }
go
func (w *gzipResponseWriter) Write(b []byte) (int, error) { if w.Header().Get("Content-Type") == "" { w.Header().Set("Content-Type", http.DetectContentType(b)) } if !w.statusCodeWritten { w.WriteHeader(http.StatusOK) } n, err := w.Writer.Write(b) return n, err }
[ "func", "(", "w", "*", "gzipResponseWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "w", ".", "Header", "(", ")", ".", "Get", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "http", ".", "DetectContentType", "(", "b", ")", ")", "\n", "}", "\n", "if", "!", "w", ".", "statusCodeWritten", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}", "\n", "n", ",", "err", ":=", "w", ".", "Writer", ".", "Write", "(", "b", ")", "\n", "return", "n", ",", "err", "\n", "}" ]
// Write wraps the underlying Write method to do compression.
[ "Write", "wraps", "the", "underlying", "Write", "method", "to", "do", "compression", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/gzip/gzip.go#L126-L135
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/staticfiles/fileserver.go
IsHidden
func (fs FileServer) IsHidden(d os.FileInfo) bool { // If the file is supposed to be hidden, return a 404 for _, hiddenPath := range fs.Hide { // Check if the served file is exactly the hidden file. if hFile, err := fs.Root.Open(hiddenPath); err == nil { fs, _ := hFile.Stat() hFile.Close() if os.SameFile(d, fs) { return true } } } return false }
go
func (fs FileServer) IsHidden(d os.FileInfo) bool { // If the file is supposed to be hidden, return a 404 for _, hiddenPath := range fs.Hide { // Check if the served file is exactly the hidden file. if hFile, err := fs.Root.Open(hiddenPath); err == nil { fs, _ := hFile.Stat() hFile.Close() if os.SameFile(d, fs) { return true } } } return false }
[ "func", "(", "fs", "FileServer", ")", "IsHidden", "(", "d", "os", ".", "FileInfo", ")", "bool", "{", "// If the file is supposed to be hidden, return a 404", "for", "_", ",", "hiddenPath", ":=", "range", "fs", ".", "Hide", "{", "// Check if the served file is exactly the hidden file.", "if", "hFile", ",", "err", ":=", "fs", ".", "Root", ".", "Open", "(", "hiddenPath", ")", ";", "err", "==", "nil", "{", "fs", ",", "_", ":=", "hFile", ".", "Stat", "(", ")", "\n", "hFile", ".", "Close", "(", ")", "\n", "if", "os", ".", "SameFile", "(", "d", ",", "fs", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsHidden checks if file with FileInfo d is on hide list.
[ "IsHidden", "checks", "if", "file", "with", "FileInfo", "d", "is", "on", "hide", "list", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/staticfiles/fileserver.go#L184-L197
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/staticfiles/fileserver.go
Redirect
func Redirect(w http.ResponseWriter, r *http.Request, newPath string, statusCode int) { if q := r.URL.RawQuery; q != "" { newPath += "?" + q } http.Redirect(w, r, newPath, statusCode) }
go
func Redirect(w http.ResponseWriter, r *http.Request, newPath string, statusCode int) { if q := r.URL.RawQuery; q != "" { newPath += "?" + q } http.Redirect(w, r, newPath, statusCode) }
[ "func", "Redirect", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "newPath", "string", ",", "statusCode", "int", ")", "{", "if", "q", ":=", "r", ".", "URL", ".", "RawQuery", ";", "q", "!=", "\"", "\"", "{", "newPath", "+=", "\"", "\"", "+", "q", "\n", "}", "\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "newPath", ",", "statusCode", ")", "\n", "}" ]
// Redirect sends an HTTP redirect to the client but will preserve // the query string for the new path. Based on http.localRedirect // from the Go standard library.
[ "Redirect", "sends", "an", "HTTP", "redirect", "to", "the", "client", "but", "will", "preserve", "the", "query", "string", "for", "the", "new", "path", ".", "Based", "on", "http", ".", "localRedirect", "from", "the", "Go", "standard", "library", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/staticfiles/fileserver.go#L202-L207
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/handler.go
TapperFromContext
func TapperFromContext(ctx context.Context) (t Tapper) { t, _ = ctx.(Tapper) return }
go
func TapperFromContext(ctx context.Context) (t Tapper) { t, _ = ctx.(Tapper) return }
[ "func", "TapperFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "t", "Tapper", ")", "{", "t", ",", "_", "=", "ctx", ".", "(", "Tapper", ")", "\n", "return", "\n", "}" ]
// TapperFromContext will return a Tapper if the dnstap plugin is enabled.
[ "TapperFromContext", "will", "return", "a", "Tapper", "if", "the", "dnstap", "plugin", "is", "enabled", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/handler.go#L48-L51
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/handler.go
TapBuilder
func (h Dnstap) TapBuilder() msg.Builder { return msg.Builder{Full: h.Pack} }
go
func (h Dnstap) TapBuilder() msg.Builder { return msg.Builder{Full: h.Pack} }
[ "func", "(", "h", "Dnstap", ")", "TapBuilder", "(", ")", "msg", ".", "Builder", "{", "return", "msg", ".", "Builder", "{", "Full", ":", "h", ".", "Pack", "}", "\n", "}" ]
// TapBuilder implements Tapper.
[ "TapBuilder", "implements", "Tapper", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/handler.go#L69-L71
train
inverse-inc/packetfence
go/dhcp/pool/pool.go
GetIssues
func (dp *DHCPPool) GetIssues(macs []string) ([]string, map[uint64]string) { dp.lock.Lock() defer dp.lock.Unlock() var found bool found = false var inPoolNotInCache []string var duplicateInPool map[uint64]string duplicateInPool = make(map[uint64]string) var count int var saveindex uint64 for i := uint64(0); i < dp.capacity; i++ { if dp.free[i] { continue } for _, mac := range macs { if dp.mac[i] == mac { found = true } } if !found { inPoolNotInCache = append(inPoolNotInCache, dp.mac[i]+", "+strconv.Itoa(int(i))) } } for _, mac := range macs { count = 0 saveindex = 0 for i := uint64(0); i < dp.capacity; i++ { if dp.free[i] { continue } if dp.mac[i] == mac { if count == 0 { saveindex = i } if count == 1 { duplicateInPool[saveindex] = mac duplicateInPool[i] = mac } else if count > 1 { duplicateInPool[i] = mac } count++ } } } return inPoolNotInCache, duplicateInPool }
go
func (dp *DHCPPool) GetIssues(macs []string) ([]string, map[uint64]string) { dp.lock.Lock() defer dp.lock.Unlock() var found bool found = false var inPoolNotInCache []string var duplicateInPool map[uint64]string duplicateInPool = make(map[uint64]string) var count int var saveindex uint64 for i := uint64(0); i < dp.capacity; i++ { if dp.free[i] { continue } for _, mac := range macs { if dp.mac[i] == mac { found = true } } if !found { inPoolNotInCache = append(inPoolNotInCache, dp.mac[i]+", "+strconv.Itoa(int(i))) } } for _, mac := range macs { count = 0 saveindex = 0 for i := uint64(0); i < dp.capacity; i++ { if dp.free[i] { continue } if dp.mac[i] == mac { if count == 0 { saveindex = i } if count == 1 { duplicateInPool[saveindex] = mac duplicateInPool[i] = mac } else if count > 1 { duplicateInPool[i] = mac } count++ } } } return inPoolNotInCache, duplicateInPool }
[ "func", "(", "dp", "*", "DHCPPool", ")", "GetIssues", "(", "macs", "[", "]", "string", ")", "(", "[", "]", "string", ",", "map", "[", "uint64", "]", "string", ")", "{", "dp", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "dp", ".", "lock", ".", "Unlock", "(", ")", "\n", "var", "found", "bool", "\n", "found", "=", "false", "\n", "var", "inPoolNotInCache", "[", "]", "string", "\n", "var", "duplicateInPool", "map", "[", "uint64", "]", "string", "\n", "duplicateInPool", "=", "make", "(", "map", "[", "uint64", "]", "string", ")", "\n\n", "var", "count", "int", "\n", "var", "saveindex", "uint64", "\n", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<", "dp", ".", "capacity", ";", "i", "++", "{", "if", "dp", ".", "free", "[", "i", "]", "{", "continue", "\n", "}", "\n", "for", "_", ",", "mac", ":=", "range", "macs", "{", "if", "dp", ".", "mac", "[", "i", "]", "==", "mac", "{", "found", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "inPoolNotInCache", "=", "append", "(", "inPoolNotInCache", ",", "dp", ".", "mac", "[", "i", "]", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "int", "(", "i", ")", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "mac", ":=", "range", "macs", "{", "count", "=", "0", "\n", "saveindex", "=", "0", "\n\n", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<", "dp", ".", "capacity", ";", "i", "++", "{", "if", "dp", ".", "free", "[", "i", "]", "{", "continue", "\n", "}", "\n", "if", "dp", ".", "mac", "[", "i", "]", "==", "mac", "{", "if", "count", "==", "0", "{", "saveindex", "=", "i", "\n", "}", "\n", "if", "count", "==", "1", "{", "duplicateInPool", "[", "saveindex", "]", "=", "mac", "\n", "duplicateInPool", "[", "i", "]", "=", "mac", "\n", "}", "else", "if", "count", ">", "1", "{", "duplicateInPool", "[", "i", "]", "=", "mac", "\n", "}", "\n", "count", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "inPoolNotInCache", ",", "duplicateInPool", "\n", "}" ]
// Compare what we have in the cache with what we have in the pool
[ "Compare", "what", "we", "have", "in", "the", "cache", "with", "what", "we", "have", "in", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L34-L81
train
inverse-inc/packetfence
go/dhcp/pool/pool.go
ReserveIPIndex
func (dp *DHCPPool) ReserveIPIndex(index uint64, mac string) (error, string) { dp.lock.Lock() defer dp.lock.Unlock() if index >= dp.capacity { return errors.New("Trying to reserve an IP that is outside the capacity of this pool"), FreeMac } if _, free := dp.free[index]; free { delete(dp.free, index) dp.mac[index] = mac return nil, mac } else { return errors.New("IP is already reserved"), FreeMac } }
go
func (dp *DHCPPool) ReserveIPIndex(index uint64, mac string) (error, string) { dp.lock.Lock() defer dp.lock.Unlock() if index >= dp.capacity { return errors.New("Trying to reserve an IP that is outside the capacity of this pool"), FreeMac } if _, free := dp.free[index]; free { delete(dp.free, index) dp.mac[index] = mac return nil, mac } else { return errors.New("IP is already reserved"), FreeMac } }
[ "func", "(", "dp", "*", "DHCPPool", ")", "ReserveIPIndex", "(", "index", "uint64", ",", "mac", "string", ")", "(", "error", ",", "string", ")", "{", "dp", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "dp", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "index", ">=", "dp", ".", "capacity", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", ",", "FreeMac", "\n", "}", "\n\n", "if", "_", ",", "free", ":=", "dp", ".", "free", "[", "index", "]", ";", "free", "{", "delete", "(", "dp", ".", "free", ",", "index", ")", "\n", "dp", ".", "mac", "[", "index", "]", "=", "mac", "\n", "return", "nil", ",", "mac", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", ",", "FreeMac", "\n", "}", "\n", "}" ]
// Reserves an IP in the pool, returns an error if the IP has already been reserved
[ "Reserves", "an", "IP", "in", "the", "pool", "returns", "an", "error", "if", "the", "IP", "has", "already", "been", "reserved" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L84-L99
train
inverse-inc/packetfence
go/dhcp/pool/pool.go
FreeIPIndex
func (dp *DHCPPool) FreeIPIndex(index uint64) error { dp.lock.Lock() defer dp.lock.Unlock() if !dp.IndexInPool(index) { return errors.New("Trying to free an IP that is outside the capacity of this pool") } if _, free := dp.free[index]; free { return errors.New("IP is already free") } else { dp.free[index] = true delete(dp.mac, index) return nil } }
go
func (dp *DHCPPool) FreeIPIndex(index uint64) error { dp.lock.Lock() defer dp.lock.Unlock() if !dp.IndexInPool(index) { return errors.New("Trying to free an IP that is outside the capacity of this pool") } if _, free := dp.free[index]; free { return errors.New("IP is already free") } else { dp.free[index] = true delete(dp.mac, index) return nil } }
[ "func", "(", "dp", "*", "DHCPPool", ")", "FreeIPIndex", "(", "index", "uint64", ")", "error", "{", "dp", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "dp", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "!", "dp", ".", "IndexInPool", "(", "index", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "free", ":=", "dp", ".", "free", "[", "index", "]", ";", "free", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "{", "dp", ".", "free", "[", "index", "]", "=", "true", "\n", "delete", "(", "dp", ".", "mac", ",", "index", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Frees an IP in the pool, returns an error if the IP is already free
[ "Frees", "an", "IP", "in", "the", "pool", "returns", "an", "error", "if", "the", "IP", "is", "already", "free" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L102-L117
train
inverse-inc/packetfence
go/dhcp/pool/pool.go
GetFreeIPIndex
func (dp *DHCPPool) GetFreeIPIndex(mac string) (uint64, string, error) { dp.lock.Lock() defer dp.lock.Unlock() if len(dp.free) == 0 { return 0, FreeMac, errors.New("DHCP pool is full") } index := rand.Intn(len(dp.free)) var available uint64 for available = range dp.free { if index == 0 { break } index-- } delete(dp.free, available) dp.mac[available] = mac return available, mac, nil }
go
func (dp *DHCPPool) GetFreeIPIndex(mac string) (uint64, string, error) { dp.lock.Lock() defer dp.lock.Unlock() if len(dp.free) == 0 { return 0, FreeMac, errors.New("DHCP pool is full") } index := rand.Intn(len(dp.free)) var available uint64 for available = range dp.free { if index == 0 { break } index-- } delete(dp.free, available) dp.mac[available] = mac return available, mac, nil }
[ "func", "(", "dp", "*", "DHCPPool", ")", "GetFreeIPIndex", "(", "mac", "string", ")", "(", "uint64", ",", "string", ",", "error", ")", "{", "dp", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "dp", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "dp", ".", "free", ")", "==", "0", "{", "return", "0", ",", "FreeMac", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "index", ":=", "rand", ".", "Intn", "(", "len", "(", "dp", ".", "free", ")", ")", "\n\n", "var", "available", "uint64", "\n", "for", "available", "=", "range", "dp", ".", "free", "{", "if", "index", "==", "0", "{", "break", "\n", "}", "\n", "index", "--", "\n", "}", "\n\n", "delete", "(", "dp", ".", "free", ",", "available", ")", "\n", "dp", ".", "mac", "[", "available", "]", "=", "mac", "\n\n", "return", "available", ",", "mac", ",", "nil", "\n", "}" ]
// Returns a random free IP address, an error if the pool is full
[ "Returns", "a", "random", "free", "IP", "address", "an", "error", "if", "the", "pool", "is", "full" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L152-L173
train
inverse-inc/packetfence
go/dhcp/pool/pool.go
FreeIPsRemaining
func (dp *DHCPPool) FreeIPsRemaining() uint64 { dp.lock.Lock() defer dp.lock.Unlock() return uint64(len(dp.free)) }
go
func (dp *DHCPPool) FreeIPsRemaining() uint64 { dp.lock.Lock() defer dp.lock.Unlock() return uint64(len(dp.free)) }
[ "func", "(", "dp", "*", "DHCPPool", ")", "FreeIPsRemaining", "(", ")", "uint64", "{", "dp", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "dp", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "uint64", "(", "len", "(", "dp", ".", "free", ")", ")", "\n", "}" ]
// Returns the amount of free IPs in the pool
[ "Returns", "the", "amount", "of", "free", "IPs", "in", "the", "pool" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L181-L185
train
inverse-inc/packetfence
go/firewallsso/watchguard.go
Stop
func (fw *WatchGuard) Stop(ctx context.Context, info map[string]string) (bool, error) { p := fw.stopRadiusPacket(ctx, info) client := fw.getRadiusClient(ctx) var err error client.Dialer.LocalAddr, err = net.ResolveUDPAddr("udp", fw.getSourceIp(ctx).String()+":0") sharedutils.CheckError(err) // Use the background context since we don't want the lib to use our context ctx2, cancel := fw.RadiusContextWithTimeout() defer cancel() _, err = client.Exchange(ctx2, p, fw.PfconfigHashNS+":"+fw.Port) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Couldn't SSO to the WatchGuard, got the following error: %s", err)) return false, err } else { return true, nil } }
go
func (fw *WatchGuard) Stop(ctx context.Context, info map[string]string) (bool, error) { p := fw.stopRadiusPacket(ctx, info) client := fw.getRadiusClient(ctx) var err error client.Dialer.LocalAddr, err = net.ResolveUDPAddr("udp", fw.getSourceIp(ctx).String()+":0") sharedutils.CheckError(err) // Use the background context since we don't want the lib to use our context ctx2, cancel := fw.RadiusContextWithTimeout() defer cancel() _, err = client.Exchange(ctx2, p, fw.PfconfigHashNS+":"+fw.Port) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Couldn't SSO to the WatchGuard, got the following error: %s", err)) return false, err } else { return true, nil } }
[ "func", "(", "fw", "*", "WatchGuard", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "p", ":=", "fw", ".", "stopRadiusPacket", "(", "ctx", ",", "info", ")", "\n", "client", ":=", "fw", ".", "getRadiusClient", "(", "ctx", ")", "\n\n", "var", "err", "error", "\n", "client", ".", "Dialer", ".", "LocalAddr", ",", "err", "=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "fw", ".", "getSourceIp", "(", "ctx", ")", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n", "sharedutils", ".", "CheckError", "(", "err", ")", "\n\n", "// Use the background context since we don't want the lib to use our context", "ctx2", ",", "cancel", ":=", "fw", ".", "RadiusContextWithTimeout", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "err", "=", "client", ".", "Exchange", "(", "ctx2", ",", "p", ",", "fw", ".", "PfconfigHashNS", "+", "\"", "\"", "+", "fw", ".", "Port", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", ",", "err", "\n", "}", "else", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}" ]
// Send an SSO stop to the WatchGuard firewall // Returns an error unless there is a valid reply from the firewall
[ "Send", "an", "SSO", "stop", "to", "the", "WatchGuard", "firewall", "Returns", "an", "error", "unless", "there", "is", "a", "valid", "reply", "from", "the", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/watchguard.go#L58-L76
train
inverse-inc/packetfence
go/firewallsso/watchguard.go
stopRadiusPacket
func (fw *WatchGuard) stopRadiusPacket(ctx context.Context, info map[string]string) *radius.Packet { r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password)) rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"]) rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Stop) rfc2865.UserName_AddString(r, info["username"]) rfc2865.FilterID_AddString(r, info["role"]) rfc2865.CalledStationID_AddString(r, "00:11:22:33:44:55") rfc2865.FramedIPAddress_Add(r, net.ParseIP(info["ip"])) rfc2865.CallingStationID_AddString(r, info["mac"]) return r }
go
func (fw *WatchGuard) stopRadiusPacket(ctx context.Context, info map[string]string) *radius.Packet { r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password)) rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"]) rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Stop) rfc2865.UserName_AddString(r, info["username"]) rfc2865.FilterID_AddString(r, info["role"]) rfc2865.CalledStationID_AddString(r, "00:11:22:33:44:55") rfc2865.FramedIPAddress_Add(r, net.ParseIP(info["ip"])) rfc2865.CallingStationID_AddString(r, info["mac"]) return r }
[ "func", "(", "fw", "*", "WatchGuard", ")", "stopRadiusPacket", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "*", "radius", ".", "Packet", "{", "r", ":=", "radius", ".", "New", "(", "radius", ".", "CodeAccountingRequest", ",", "[", "]", "byte", "(", "fw", ".", "Password", ")", ")", "\n", "rfc2866", ".", "AcctSessionID_AddString", "(", "r", ",", "\"", "\"", "+", "info", "[", "\"", "\"", "]", ")", "\n", "rfc2866", ".", "AcctStatusType_Add", "(", "r", ",", "rfc2866", ".", "AcctStatusType_Value_Stop", ")", "\n", "rfc2865", ".", "UserName_AddString", "(", "r", ",", "info", "[", "\"", "\"", "]", ")", "\n", "rfc2865", ".", "FilterID_AddString", "(", "r", ",", "info", "[", "\"", "\"", "]", ")", "\n", "rfc2865", ".", "CalledStationID_AddString", "(", "r", ",", "\"", "\"", ")", "\n", "rfc2865", ".", "FramedIPAddress_Add", "(", "r", ",", "net", ".", "ParseIP", "(", "info", "[", "\"", "\"", "]", ")", ")", "\n", "rfc2865", ".", "CallingStationID_AddString", "(", "r", ",", "info", "[", "\"", "\"", "]", ")", "\n\n", "return", "r", "\n", "}" ]
// Build the RADIUS packet for an SSO stop
[ "Build", "the", "RADIUS", "packet", "for", "an", "SSO", "stop" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/watchguard.go#L79-L90
train
inverse-inc/packetfence
go/caddy/requestlimit/requestlimit.go
setup
func setup(c *caddy.Controller) error { var max int for c.Next() { val := c.Val() switch val { case "requestlimit": if !c.NextArg() { fmt.Println("Missing limit argument for requestlimit") return c.ArgErr() } else { val := c.Val() if val != "" { max64, err := strconv.ParseInt(c.Val(), 10, 32) if err != nil { msg := fmt.Sprintf("Cannot parse request limit value %s", val) return errors.New(msg) } else { max = int(max64) fmt.Printf("Setting up requestlimit with a limit of %d\n", max) break } } } default: return c.ArgErr() } } httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { return RequestLimitHandler{Next: next, sem: make(chan int, max)} }) return nil }
go
func setup(c *caddy.Controller) error { var max int for c.Next() { val := c.Val() switch val { case "requestlimit": if !c.NextArg() { fmt.Println("Missing limit argument for requestlimit") return c.ArgErr() } else { val := c.Val() if val != "" { max64, err := strconv.ParseInt(c.Val(), 10, 32) if err != nil { msg := fmt.Sprintf("Cannot parse request limit value %s", val) return errors.New(msg) } else { max = int(max64) fmt.Printf("Setting up requestlimit with a limit of %d\n", max) break } } } default: return c.ArgErr() } } httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { return RequestLimitHandler{Next: next, sem: make(chan int, max)} }) return nil }
[ "func", "setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "var", "max", "int", "\n\n", "for", "c", ".", "Next", "(", ")", "{", "val", ":=", "c", ".", "Val", "(", ")", "\n", "switch", "val", "{", "case", "\"", "\"", ":", "if", "!", "c", ".", "NextArg", "(", ")", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "c", ".", "ArgErr", "(", ")", "\n", "}", "else", "{", "val", ":=", "c", ".", "Val", "(", ")", "\n", "if", "val", "!=", "\"", "\"", "{", "max64", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "c", ".", "Val", "(", ")", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "val", ")", "\n", "return", "errors", ".", "New", "(", "msg", ")", "\n", "}", "else", "{", "max", "=", "int", "(", "max64", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "max", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "default", ":", "return", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "}", "\n\n", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "return", "RequestLimitHandler", "{", "Next", ":", "next", ",", "sem", ":", "make", "(", "chan", "int", ",", "max", ")", "}", "\n", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// Setup the rate limiter with the configuration in the Caddyfile
[ "Setup", "the", "rate", "limiter", "with", "the", "configuration", "in", "the", "Caddyfile" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/requestlimit/requestlimit.go#L21-L55
train
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", ")", "{", "// Limit the concurrent requests that can run through the sem channel", "h", ".", "sem", "<-", "1", "\n", "defer", "func", "(", ")", "{", "<-", "h", ".", "sem", "\n", "}", "(", ")", "\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\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\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", "(", "\"", "\"", ")", "\n", "}", "\n", "clientConn", ",", "bufReader", ",", "err", ":=", "hijacker", ".", "Hijack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "http", ".", "StatusInternalServerError", ",", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "defer", "clientConn", ".", "Close", "(", ")", "\n", "// 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", ")", "\n", "if", "err", "!=", "nil", "{", "return", "http", ".", "StatusBadGateway", ",", "err", "\n", "}", "\n", "targetConn", ".", "Write", "(", "rbuf", ")", "\n", "}", "\n", "}", "\n", "// 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", ":", "\"", "\"", ",", "ProtoMajor", ":", "1", ",", "ProtoMinor", ":", "1", ",", "Header", ":", "make", "(", "http", ".", "Header", ")", ",", "}", "\n", "res", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "err", "=", "res", ".", "Write", "(", "clientConn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "http", ".", "StatusInternalServerError", ",", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\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", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "pa", ")", "!=", "2", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "strings", ".", "ToLower", "(", "pa", "[", "0", "]", ")", "!=", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "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", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\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", "(", "\"", "\"", ")", "// remove Server: Caddy, append via instead", "\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "response", ".", "ProtoMajor", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "response", ".", "ProtoMinor", ")", "+", "\"", "\"", ")", "\n\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", ")", "{", "// 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", "(", "\"", "\"", ")", "\n", "}", "\n", "strUrl", ":=", "inReq", ".", "RequestURI", "\n", "if", "strUrl", "[", "0", "]", "==", "'/'", "{", "strUrl", "=", "inReq", ".", "Host", "+", "strUrl", "\n", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "strUrl", ",", "\"", "\"", ")", "{", "strUrl", "=", "\"", "\"", "+", "strUrl", "\n", "}", "\n", "outReq", ",", "err", ":=", "http", ".", "NewRequest", "(", "inReq", ".", "Method", ",", "strUrl", ",", "inReq", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "outReq", ",", "errors", ".", "New", "(", "\"", "\"", "+", "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\n", "if", "!", "fp", ".", "hideIP", "{", "outReq", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\\\"", "\"", "+", "inReq", ".", "RemoteAddr", "+", "\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "// https://tools.ietf.org/html/rfc7230#section-5.7.1", "outReq", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "inReq", ".", "ProtoMajor", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "inReq", ".", "ProtoMinor", ")", "+", "\"", "\"", ")", "\n", "return", "outReq", ",", "nil", "\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", "// includes shallow copies of maps, but okay", "\n", "// 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", "\n", "}", "\n\n", "// Restore URL Path if it has been modified", "if", "outreq", ".", "URL", ".", "RawPath", "!=", "\"", "\"", "{", "outreq", ".", "URL", ".", "Opaque", "=", "outreq", ".", "URL", ".", "RawPath", "\n", "}", "\n\n", "// We are modifying the same underlying map from req (shallow", "// copied above) so we only copy it if necessary.", "copiedHeaders", ":=", "false", "\n\n", "// Remove hop-by-hop headers listed in the \"Connection\" header.", "// See RFC 2616, section 14.10.", "if", "c", ":=", "outreq", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "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\n", "// 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", ")", "\n", "copyHeader", "(", "outreq", ".", "Header", ",", "r", ".", "Header", ")", "\n", "copiedHeaders", "=", "true", "\n", "}", "\n", "outreq", ".", "Header", ".", "Del", "(", "h", ")", "\n", "}", "\n", "}", "\n\n", "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", "[", "\"", "\"", "]", ";", "ok", "{", "clientIP", "=", "strings", ".", "Join", "(", "prior", ",", "\"", "\"", ")", "+", "\"", "\"", "+", "clientIP", "\n", "}", "\n", "outreq", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "clientIP", ")", "\n", "}", "\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\n", "for", "name", ":=", "range", "stypePlugins", "{", "if", "stypePlugins", "[", "name", "]", ".", "StartupHook", "==", "nil", "{", "continue", "\n", "}", "\n\n", "err", ":=", "stypePlugins", "[", "name", "]", ".", "StartupHook", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\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\n", "if", "len", "(", "l", ".", "Path", ")", "==", "0", "{", "return", "result", "\n", "}", "\n\n", "// skip trailing slash", "lpath", ":=", "l", ".", "Path", "\n", "if", "lpath", "[", "len", "(", "lpath", ")", "-", "1", "]", "==", "'/'", "{", "lpath", "=", "lpath", "[", ":", "len", "(", "lpath", ")", "-", "1", "]", "\n", "}", "\n\n", "parts", ":=", "strings", ".", "Split", "(", "lpath", ",", "\"", "\"", ")", "\n", "for", "i", ",", "part", ":=", "range", "parts", "{", "if", "i", "==", "0", "&&", "part", "==", "\"", "\"", "{", "// Leading slash (root)", "result", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "continue", "\n", "}", "\n", "result", "[", "strings", ".", "Join", "(", "parts", "[", ":", "i", "+", "1", "]", ",", "\"", "\"", ")", "]", "=", "part", "\n", "}", "\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", "(", ")", "{", "// Check '.Order' to know how to sort", "if", "l", ".", "Order", "==", "\"", "\"", "{", "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", ":", "// If not one of the above, do nothing", "return", "\n", "}", "\n", "}", "else", "{", "// If we had more Orderings we could add them here", "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", ":", "// If not one of the above, do nothing", "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", ")", "{", "// See if there's a browse configuration to match the path", "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\n", "// Browse works on existing directories; delegate everything else", "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\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\n", "// Do not reply to anything else because it might be nonsensical", "switch", "r", ".", "Method", "{", "case", "http", ".", "MethodGet", ",", "http", ".", "MethodHead", ":", "// proceed, noop", "case", "\"", "\"", ",", "http", ".", "MethodOptions", ":", "return", "http", ".", "StatusNotImplemented", ",", "nil", "\n", "default", ":", "return", "b", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n\n", "// 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", ")", "\n", "return", "0", ",", "nil", "\n", "}", "\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", "(", "\"", "\"", ",", "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\n", "// Split input into components (prepend with // to assert host by default)", "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\n", "// separate host and port", "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\n", "// see if we can set port based off scheme", "if", "port", "==", "\"", "\"", "{", "if", "u", ".", "Scheme", "==", "\"", "\"", "{", "port", "=", "\"", "\"", "\n", "}", "else", "if", "u", ".", "Scheme", "==", "\"", "\"", "{", "port", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "// repeated or conflicting scheme is confusing, so error", "if", "u", ".", "Scheme", "!=", "\"", "\"", "&&", "(", "port", "==", "\"", "\"", "||", "port", "==", "\"", "\"", ")", "{", "return", "Address", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "input", ")", "\n", "}", "\n\n", "// error if scheme and port combination violate convention", "if", "(", "u", ".", "Scheme", "==", "\"", "\"", "&&", "port", "==", "\"", "\"", ")", "||", "(", "u", ".", "Scheme", "==", "\"", "\"", "&&", "port", "==", "\"", "\"", ")", "{", "return", "Address", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "input", ")", "\n", "}", "\n\n", "// standardize http and https ports to their respective port numbers", "if", "port", "==", "\"", "\"", "{", "u", ".", "Scheme", "=", "\"", "\"", "\n", "port", "=", "\"", "\"", "\n", "}", "else", "if", "port", "==", "\"", "\"", "{", "u", ".", "Scheme", "=", "\"", "\"", "\n", "port", "=", "\"", "\"", "\n", "}", "\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", "{", "// Will close local/remote syslog connections too :)", "if", "closer", ",", "ok", ":=", "l", ".", "writer", ".", "(", "io", ".", "WriteCloser", ")", ";", "ok", "{", "l", ".", "fileMu", ".", "Lock", "(", ")", "\n", "err", ":=", "closer", ".", "Close", "(", ")", "\n", "l", ".", "fileMu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\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\n", "// Default to DNS if there isn't a transport protocol prefix.", "trans", ":=", "TransportDNS", "\n\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\n", "host", ",", "port", ",", "ipnet", ",", "err", ":=", "plugin", ".", "SplitHostPort", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "zoneAddr", "{", "}", ",", "err", "\n", "}", "\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\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\n", "matches", ":=", "re", ".", "FindStringSubmatchIndex", "(", "base", ")", "\n", "if", "matches", "==", "nil", "{", "return", "false", ",", "\"", "\"", "\n", "}", "\n\n", "by", ":=", "re", ".", "ExpandString", "(", "nil", ",", "template", ",", "base", ",", "matches", ")", "\n", "if", "by", "==", "nil", "{", "return", "false", ",", "\"", "\"", "\n", "}", "\n\n", "origin", "=", "dns", ".", "Fqdn", "(", "string", "(", "by", ")", ")", "\n\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