id
int32 0
167k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
14,100 | itsyouonline/identityserver | db/user/User.go | GetAvatarByLabel | func (u *User) GetAvatarByLabel(label string) (avatar Avatar, err error) {
for _, avatar = range u.Avatars {
if avatar.Label == label {
return
}
}
err = errors.New("Could not find Avatar with Label " + label)
return
} | go | func (u *User) GetAvatarByLabel(label string) (avatar Avatar, err error) {
for _, avatar = range u.Avatars {
if avatar.Label == label {
return
}
}
err = errors.New("Could not find Avatar with Label " + label)
return
} | [
"func",
"(",
"u",
"*",
"User",
")",
"GetAvatarByLabel",
"(",
"label",
"string",
")",
"(",
"avatar",
"Avatar",
",",
"err",
"error",
")",
"{",
"for",
"_",
",",
"avatar",
"=",
"range",
"u",
".",
"Avatars",
"{",
"if",
"avatar",
".",
"Label",
"==",
"label",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"label",
")",
"\n",
"return",
"\n",
"}"
] | // GetAvatarByLabel gets the avatar associated with this label | [
"GetAvatarByLabel",
"gets",
"the",
"avatar",
"associated",
"with",
"this",
"label"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/user/User.go#L109-L117 |
14,101 | itsyouonline/identityserver | db/company/Company.go | IsValid | func (c *Company) IsValid() (valid bool) {
valid = true
globalIDLength := len(c.Globalid)
valid = valid && (globalIDLength >= 3) && (globalIDLength <= 150) && c.Globalid == strings.ToLower(c.Globalid)
return
} | go | func (c *Company) IsValid() (valid bool) {
valid = true
globalIDLength := len(c.Globalid)
valid = valid && (globalIDLength >= 3) && (globalIDLength <= 150) && c.Globalid == strings.ToLower(c.Globalid)
return
} | [
"func",
"(",
"c",
"*",
"Company",
")",
"IsValid",
"(",
")",
"(",
"valid",
"bool",
")",
"{",
"valid",
"=",
"true",
"\n",
"globalIDLength",
":=",
"len",
"(",
"c",
".",
"Globalid",
")",
"\n",
"valid",
"=",
"valid",
"&&",
"(",
"globalIDLength",
">=",
"3",
")",
"&&",
"(",
"globalIDLength",
"<=",
"150",
")",
"&&",
"c",
".",
"Globalid",
"==",
"strings",
".",
"ToLower",
"(",
"c",
".",
"Globalid",
")",
"\n",
"return",
"\n",
"}"
] | // IsValid performs basic validation on the content of a company's fields | [
"IsValid",
"performs",
"basic",
"validation",
"on",
"the",
"content",
"of",
"a",
"company",
"s",
"fields"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/company/Company.go#L21-L26 |
14,102 | itsyouonline/identityserver | oauthservice/service.go | GetWebuser | func (service *Service) GetWebuser(r *http.Request, w http.ResponseWriter) (username string, err error) {
username, err = service.sessionService.GetLoggedInUser(r, w)
return
} | go | func (service *Service) GetWebuser(r *http.Request, w http.ResponseWriter) (username string, err error) {
username, err = service.sessionService.GetLoggedInUser(r, w)
return
} | [
"func",
"(",
"service",
"*",
"Service",
")",
"GetWebuser",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"(",
"username",
"string",
",",
"err",
"error",
")",
"{",
"username",
",",
"err",
"=",
"service",
".",
"sessionService",
".",
"GetLoggedInUser",
"(",
"r",
",",
"w",
")",
"\n",
"return",
"\n",
"}"
] | //GetWebuser returns the authenticated user if any or an empty string if not | [
"GetWebuser",
"returns",
"the",
"authenticated",
"user",
"if",
"any",
"or",
"an",
"empty",
"string",
"if",
"not"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/oauthservice/service.go#L53-L56 |
14,103 | itsyouonline/identityserver | oauthservice/service.go | AddRoutes | func (service *Service) AddRoutes(router *mux.Router) {
service.router = router
router.HandleFunc("/v1/oauth/authorize", service.AuthorizeHandler).Methods("GET")
router.HandleFunc("/v1/oauth/authorize",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "GET")
}).Methods("OPTIONS")
router.HandleFunc("/v1/oauth/access_token", service.AccessTokenHandler).Methods("POST")
router.HandleFunc("/v1/oauth/access_token",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "POST")
// Allow cors
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "POST")
// Allow all requested headers, we do not use them anyway
w.Header().Add("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
}).Methods("OPTIONS")
router.HandleFunc("/v1/oauth/jwt", service.JWTHandler).Methods("POST", "GET")
router.HandleFunc("/v1/oauth/jwt",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "GET,POST")
}).Methods("OPTIONS")
router.HandleFunc("/v1/oauth/jwt/refresh", service.RefreshJWTHandler).Methods("POST", "GET")
router.HandleFunc("/v1/oauth/jwt/refresh",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "GET,POST")
}).Methods("OPTIONS")
InitModels()
} | go | func (service *Service) AddRoutes(router *mux.Router) {
service.router = router
router.HandleFunc("/v1/oauth/authorize", service.AuthorizeHandler).Methods("GET")
router.HandleFunc("/v1/oauth/authorize",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "GET")
}).Methods("OPTIONS")
router.HandleFunc("/v1/oauth/access_token", service.AccessTokenHandler).Methods("POST")
router.HandleFunc("/v1/oauth/access_token",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "POST")
// Allow cors
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "POST")
// Allow all requested headers, we do not use them anyway
w.Header().Add("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
}).Methods("OPTIONS")
router.HandleFunc("/v1/oauth/jwt", service.JWTHandler).Methods("POST", "GET")
router.HandleFunc("/v1/oauth/jwt",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "GET,POST")
}).Methods("OPTIONS")
router.HandleFunc("/v1/oauth/jwt/refresh", service.RefreshJWTHandler).Methods("POST", "GET")
router.HandleFunc("/v1/oauth/jwt/refresh",
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Allow", "GET,POST")
}).Methods("OPTIONS")
InitModels()
} | [
"func",
"(",
"service",
"*",
"Service",
")",
"AddRoutes",
"(",
"router",
"*",
"mux",
".",
"Router",
")",
"{",
"service",
".",
"router",
"=",
"router",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"service",
".",
"AuthorizeHandler",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"service",
".",
"AccessTokenHandler",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"// Allow cors",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"// Allow all requested headers, we do not use them anyway",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"service",
".",
"JWTHandler",
")",
".",
"Methods",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"service",
".",
"RefreshJWTHandler",
")",
".",
"Methods",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n\n",
"InitModels",
"(",
")",
"\n",
"}"
] | //AddRoutes adds the routes and handlerfunctions to the router | [
"AddRoutes",
"adds",
"the",
"routes",
"and",
"handlerfunctions",
"to",
"the",
"router"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/oauthservice/service.go#L72-L103 |
14,104 | itsyouonline/identityserver | globalconfig/globalconfig.go | Insert | func (m *Manager) Insert(c *GlobalConfig) error {
err := m.collection.Insert(c)
return err
} | go | func (m *Manager) Insert(c *GlobalConfig) error {
err := m.collection.Insert(c)
return err
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"Insert",
"(",
"c",
"*",
"GlobalConfig",
")",
"error",
"{",
"err",
":=",
"m",
".",
"collection",
".",
"Insert",
"(",
"c",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Insert a config key | [
"Insert",
"a",
"config",
"key"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/globalconfig/globalconfig.go#L66-L70 |
14,105 | itsyouonline/identityserver | globalconfig/globalconfig.go | Delete | func (m *Manager) Delete(key string) error {
config, err := m.GetByKey(key)
if err != nil {
return err
}
return m.collection.Remove(config)
} | go | func (m *Manager) Delete(key string) error {
config, err := m.GetByKey(key)
if err != nil {
return err
}
return m.collection.Remove(config)
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"Delete",
"(",
"key",
"string",
")",
"error",
"{",
"config",
",",
"err",
":=",
"m",
".",
"GetByKey",
"(",
"key",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"m",
".",
"collection",
".",
"Remove",
"(",
"config",
")",
"\n",
"}"
] | // Delete a config key | [
"Delete",
"a",
"config",
"key"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/globalconfig/globalconfig.go#L73-L81 |
14,106 | itsyouonline/identityserver | db/organization/Organization.go | IsValid | func (org *Organization) IsValid() bool {
regex, _ := regexp.Compile(`^[a-z\d\-_\s]{3,150}$`)
return validator.Validate(org) == nil && regex.MatchString(org.Globalid)
} | go | func (org *Organization) IsValid() bool {
regex, _ := regexp.Compile(`^[a-z\d\-_\s]{3,150}$`)
return validator.Validate(org) == nil && regex.MatchString(org.Globalid)
} | [
"func",
"(",
"org",
"*",
"Organization",
")",
"IsValid",
"(",
")",
"bool",
"{",
"regex",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"`^[a-z\\d\\-_\\s]{3,150}$`",
")",
"\n",
"return",
"validator",
".",
"Validate",
"(",
"org",
")",
"==",
"nil",
"&&",
"regex",
".",
"MatchString",
"(",
"org",
".",
"Globalid",
")",
"\n",
"}"
] | // IsValid performs basic validation on the content of an organizations fields | [
"IsValid",
"performs",
"basic",
"validation",
"on",
"the",
"content",
"of",
"an",
"organizations",
"fields"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/organization/Organization.go#L28-L31 |
14,107 | itsyouonline/identityserver | db/organization/Organization.go | ConvertToView | func (org *Organization) ConvertToView(usrMgr *user.Manager, valMgr *validation.Manager) (*OrganizationView, error) {
view := &OrganizationView{}
view.DNS = org.DNS
view.Globalid = org.Globalid
view.PublicKeys = org.PublicKeys
view.SecondsValidity = org.SecondsValidity
view.OrgOwners = org.OrgOwners
view.OrgMembers = org.OrgMembers
view.RequiredScopes = org.RequiredScopes
view.IncludeSubOrgsOf = org.IncludeSubOrgsOf
var err error
view.Members, err = ConvertUsernamesToIdentifiers(org.Members, valMgr)
if err != nil {
return view, err
}
view.Owners, err = ConvertUsernamesToIdentifiers(org.Owners, valMgr)
return view, err
} | go | func (org *Organization) ConvertToView(usrMgr *user.Manager, valMgr *validation.Manager) (*OrganizationView, error) {
view := &OrganizationView{}
view.DNS = org.DNS
view.Globalid = org.Globalid
view.PublicKeys = org.PublicKeys
view.SecondsValidity = org.SecondsValidity
view.OrgOwners = org.OrgOwners
view.OrgMembers = org.OrgMembers
view.RequiredScopes = org.RequiredScopes
view.IncludeSubOrgsOf = org.IncludeSubOrgsOf
var err error
view.Members, err = ConvertUsernamesToIdentifiers(org.Members, valMgr)
if err != nil {
return view, err
}
view.Owners, err = ConvertUsernamesToIdentifiers(org.Owners, valMgr)
return view, err
} | [
"func",
"(",
"org",
"*",
"Organization",
")",
"ConvertToView",
"(",
"usrMgr",
"*",
"user",
".",
"Manager",
",",
"valMgr",
"*",
"validation",
".",
"Manager",
")",
"(",
"*",
"OrganizationView",
",",
"error",
")",
"{",
"view",
":=",
"&",
"OrganizationView",
"{",
"}",
"\n",
"view",
".",
"DNS",
"=",
"org",
".",
"DNS",
"\n",
"view",
".",
"Globalid",
"=",
"org",
".",
"Globalid",
"\n",
"view",
".",
"PublicKeys",
"=",
"org",
".",
"PublicKeys",
"\n",
"view",
".",
"SecondsValidity",
"=",
"org",
".",
"SecondsValidity",
"\n",
"view",
".",
"OrgOwners",
"=",
"org",
".",
"OrgOwners",
"\n",
"view",
".",
"OrgMembers",
"=",
"org",
".",
"OrgMembers",
"\n",
"view",
".",
"RequiredScopes",
"=",
"org",
".",
"RequiredScopes",
"\n",
"view",
".",
"IncludeSubOrgsOf",
"=",
"org",
".",
"IncludeSubOrgsOf",
"\n\n",
"var",
"err",
"error",
"\n",
"view",
".",
"Members",
",",
"err",
"=",
"ConvertUsernamesToIdentifiers",
"(",
"org",
".",
"Members",
",",
"valMgr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"view",
",",
"err",
"\n",
"}",
"\n",
"view",
".",
"Owners",
",",
"err",
"=",
"ConvertUsernamesToIdentifiers",
"(",
"org",
".",
"Owners",
",",
"valMgr",
")",
"\n\n",
"return",
"view",
",",
"err",
"\n",
"}"
] | // ConvertToView converts an organization from the DB to a view served by the API | [
"ConvertToView",
"converts",
"an",
"organization",
"from",
"the",
"DB",
"to",
"a",
"view",
"served",
"by",
"the",
"API"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/organization/Organization.go#L40-L59 |
14,108 | itsyouonline/identityserver | db/organization/Organization.go | ConvertUsernamesToIdentifiers | func ConvertUsernamesToIdentifiers(usernames []string, valMgr *validation.Manager) ([]string, error) {
identifiers := []string{}
checkedUsers := map[string]bool{}
for _, u := range usernames {
checkedUsers[u] = false
}
emails, err := valMgr.GetValidatedEmailAddressesByUsernames(usernames)
if err != nil {
return identifiers, err
}
for _, validatedEmail := range emails {
if !checkedUsers[validatedEmail.Username] {
identifiers = append(identifiers, validatedEmail.EmailAddress)
checkedUsers[validatedEmail.Username] = true
}
}
checkPhoneUsernames := []string{}
for username, checked := range checkedUsers {
if !checked {
checkPhoneUsernames = append(checkPhoneUsernames, username)
}
}
validatedPhoneNumbers, err := valMgr.GetValidatedPhoneNumbersByUsernames(checkPhoneUsernames)
if err != nil {
return identifiers, err
}
for _, validatedPhone := range validatedPhoneNumbers {
if !checkedUsers[validatedPhone.Username] {
identifiers = append(identifiers, validatedPhone.Phonenumber)
checkedUsers[validatedPhone.Username] = true
}
}
return identifiers, nil
} | go | func ConvertUsernamesToIdentifiers(usernames []string, valMgr *validation.Manager) ([]string, error) {
identifiers := []string{}
checkedUsers := map[string]bool{}
for _, u := range usernames {
checkedUsers[u] = false
}
emails, err := valMgr.GetValidatedEmailAddressesByUsernames(usernames)
if err != nil {
return identifiers, err
}
for _, validatedEmail := range emails {
if !checkedUsers[validatedEmail.Username] {
identifiers = append(identifiers, validatedEmail.EmailAddress)
checkedUsers[validatedEmail.Username] = true
}
}
checkPhoneUsernames := []string{}
for username, checked := range checkedUsers {
if !checked {
checkPhoneUsernames = append(checkPhoneUsernames, username)
}
}
validatedPhoneNumbers, err := valMgr.GetValidatedPhoneNumbersByUsernames(checkPhoneUsernames)
if err != nil {
return identifiers, err
}
for _, validatedPhone := range validatedPhoneNumbers {
if !checkedUsers[validatedPhone.Username] {
identifiers = append(identifiers, validatedPhone.Phonenumber)
checkedUsers[validatedPhone.Username] = true
}
}
return identifiers, nil
} | [
"func",
"ConvertUsernamesToIdentifiers",
"(",
"usernames",
"[",
"]",
"string",
",",
"valMgr",
"*",
"validation",
".",
"Manager",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"identifiers",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"checkedUsers",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"for",
"_",
",",
"u",
":=",
"range",
"usernames",
"{",
"checkedUsers",
"[",
"u",
"]",
"=",
"false",
"\n",
"}",
"\n",
"emails",
",",
"err",
":=",
"valMgr",
".",
"GetValidatedEmailAddressesByUsernames",
"(",
"usernames",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"identifiers",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"validatedEmail",
":=",
"range",
"emails",
"{",
"if",
"!",
"checkedUsers",
"[",
"validatedEmail",
".",
"Username",
"]",
"{",
"identifiers",
"=",
"append",
"(",
"identifiers",
",",
"validatedEmail",
".",
"EmailAddress",
")",
"\n",
"checkedUsers",
"[",
"validatedEmail",
".",
"Username",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"checkPhoneUsernames",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"username",
",",
"checked",
":=",
"range",
"checkedUsers",
"{",
"if",
"!",
"checked",
"{",
"checkPhoneUsernames",
"=",
"append",
"(",
"checkPhoneUsernames",
",",
"username",
")",
"\n",
"}",
"\n",
"}",
"\n",
"validatedPhoneNumbers",
",",
"err",
":=",
"valMgr",
".",
"GetValidatedPhoneNumbersByUsernames",
"(",
"checkPhoneUsernames",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"identifiers",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"validatedPhone",
":=",
"range",
"validatedPhoneNumbers",
"{",
"if",
"!",
"checkedUsers",
"[",
"validatedPhone",
".",
"Username",
"]",
"{",
"identifiers",
"=",
"append",
"(",
"identifiers",
",",
"validatedPhone",
".",
"Phonenumber",
")",
"\n",
"checkedUsers",
"[",
"validatedPhone",
".",
"Username",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"identifiers",
",",
"nil",
"\n",
"}"
] | // ConvertUsernamesToIdentifiers converts a list of usernames to a list of user identifiers | [
"ConvertUsernamesToIdentifiers",
"converts",
"a",
"list",
"of",
"usernames",
"to",
"a",
"list",
"of",
"user",
"identifiers"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/organization/Organization.go#L62-L95 |
14,109 | itsyouonline/identityserver | db/organization/Organization.go | ConvertUsernameToIdentifier | func ConvertUsernameToIdentifier(username string, usrMgr *user.Manager, valMgr *validation.Manager) (string, error) {
userIdentifier := username
usr, err := usrMgr.GetByName(username)
if err != nil {
return userIdentifier, err
}
// check for a validated email address
for _, email := range usr.EmailAddresses {
validated, err := valMgr.IsEmailAddressValidated(username, email.EmailAddress)
if err != nil {
return userIdentifier, err
}
if validated {
return email.EmailAddress, err
}
}
// try the phone numbers
for _, phone := range usr.Phonenumbers {
validated, err := valMgr.IsPhonenumberValidated(username, phone.Phonenumber)
if err != nil {
return userIdentifier, err
}
if validated {
return phone.Phonenumber, err
}
}
// No verified email or phone number. Fallback to username
return userIdentifier, err
} | go | func ConvertUsernameToIdentifier(username string, usrMgr *user.Manager, valMgr *validation.Manager) (string, error) {
userIdentifier := username
usr, err := usrMgr.GetByName(username)
if err != nil {
return userIdentifier, err
}
// check for a validated email address
for _, email := range usr.EmailAddresses {
validated, err := valMgr.IsEmailAddressValidated(username, email.EmailAddress)
if err != nil {
return userIdentifier, err
}
if validated {
return email.EmailAddress, err
}
}
// try the phone numbers
for _, phone := range usr.Phonenumbers {
validated, err := valMgr.IsPhonenumberValidated(username, phone.Phonenumber)
if err != nil {
return userIdentifier, err
}
if validated {
return phone.Phonenumber, err
}
}
// No verified email or phone number. Fallback to username
return userIdentifier, err
} | [
"func",
"ConvertUsernameToIdentifier",
"(",
"username",
"string",
",",
"usrMgr",
"*",
"user",
".",
"Manager",
",",
"valMgr",
"*",
"validation",
".",
"Manager",
")",
"(",
"string",
",",
"error",
")",
"{",
"userIdentifier",
":=",
"username",
"\n",
"usr",
",",
"err",
":=",
"usrMgr",
".",
"GetByName",
"(",
"username",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"userIdentifier",
",",
"err",
"\n",
"}",
"\n",
"// check for a validated email address",
"for",
"_",
",",
"email",
":=",
"range",
"usr",
".",
"EmailAddresses",
"{",
"validated",
",",
"err",
":=",
"valMgr",
".",
"IsEmailAddressValidated",
"(",
"username",
",",
"email",
".",
"EmailAddress",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"userIdentifier",
",",
"err",
"\n",
"}",
"\n",
"if",
"validated",
"{",
"return",
"email",
".",
"EmailAddress",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// try the phone numbers",
"for",
"_",
",",
"phone",
":=",
"range",
"usr",
".",
"Phonenumbers",
"{",
"validated",
",",
"err",
":=",
"valMgr",
".",
"IsPhonenumberValidated",
"(",
"username",
",",
"phone",
".",
"Phonenumber",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"userIdentifier",
",",
"err",
"\n",
"}",
"\n",
"if",
"validated",
"{",
"return",
"phone",
".",
"Phonenumber",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// No verified email or phone number. Fallback to username",
"return",
"userIdentifier",
",",
"err",
"\n",
"}"
] | // ConvertUsernameToIdentifier converts a username into an identifier. It tries validated email addresses first. If
// there are none, attempt to use validated phone numbers. If the user also doesn't have any of those, keep the username | [
"ConvertUsernameToIdentifier",
"converts",
"a",
"username",
"into",
"an",
"identifier",
".",
"It",
"tries",
"validated",
"email",
"addresses",
"first",
".",
"If",
"there",
"are",
"none",
"attempt",
"to",
"use",
"validated",
"phone",
"numbers",
".",
"If",
"the",
"user",
"also",
"doesn",
"t",
"have",
"any",
"of",
"those",
"keep",
"the",
"username"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/organization/Organization.go#L119-L147 |
14,110 | itsyouonline/identityserver | db/organization/Organization.go | ConvertIdentifierToUsername | func ConvertIdentifierToUsername(identifier string, valMgr *validation.Manager) (string, error) {
email, err := valMgr.GetByEmailAddress(identifier)
if err == nil {
return email.Username, err
} else if valMgr.IsErrNotFound(err) {
phone, err := valMgr.GetByPhoneNumber(identifier)
if err == nil || db.IsNotFound(err) {
return phone.Username, nil
}
return identifier, err
}
return identifier, err
} | go | func ConvertIdentifierToUsername(identifier string, valMgr *validation.Manager) (string, error) {
email, err := valMgr.GetByEmailAddress(identifier)
if err == nil {
return email.Username, err
} else if valMgr.IsErrNotFound(err) {
phone, err := valMgr.GetByPhoneNumber(identifier)
if err == nil || db.IsNotFound(err) {
return phone.Username, nil
}
return identifier, err
}
return identifier, err
} | [
"func",
"ConvertIdentifierToUsername",
"(",
"identifier",
"string",
",",
"valMgr",
"*",
"validation",
".",
"Manager",
")",
"(",
"string",
",",
"error",
")",
"{",
"email",
",",
"err",
":=",
"valMgr",
".",
"GetByEmailAddress",
"(",
"identifier",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"email",
".",
"Username",
",",
"err",
"\n",
"}",
"else",
"if",
"valMgr",
".",
"IsErrNotFound",
"(",
"err",
")",
"{",
"phone",
",",
"err",
":=",
"valMgr",
".",
"GetByPhoneNumber",
"(",
"identifier",
")",
"\n",
"if",
"err",
"==",
"nil",
"||",
"db",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"phone",
".",
"Username",
",",
"nil",
"\n",
"}",
"\n",
"return",
"identifier",
",",
"err",
"\n\n",
"}",
"\n",
"return",
"identifier",
",",
"err",
"\n",
"}"
] | // ConvertIdentifierToUsername converts an identifier to a username. | [
"ConvertIdentifierToUsername",
"converts",
"an",
"identifier",
"to",
"a",
"username",
"."
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/organization/Organization.go#L150-L163 |
14,111 | itsyouonline/identityserver | db/smshistory/model.go | New | func New(phonenumber string) *SmsHistory {
return &SmsHistory{
Phonenumber: phonenumber,
CreatedAt: time.Now(),
}
} | go | func New(phonenumber string) *SmsHistory {
return &SmsHistory{
Phonenumber: phonenumber,
CreatedAt: time.Now(),
}
} | [
"func",
"New",
"(",
"phonenumber",
"string",
")",
"*",
"SmsHistory",
"{",
"return",
"&",
"SmsHistory",
"{",
"Phonenumber",
":",
"phonenumber",
",",
"CreatedAt",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
"\n",
"}"
] | // New creates a new SmsHistory | [
"New",
"creates",
"a",
"new",
"SmsHistory"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/smshistory/model.go#L12-L17 |
14,112 | itsyouonline/identityserver | credentials/oauth2/scopes.go | SplitScopeString | func SplitScopeString(scopestring string) (scopeList []string) {
scopeList = []string{}
for _, value := range strings.Split(scopestring, ",") {
scope := strings.TrimSpace(value)
if scope != "" {
scopeList = append(scopeList, scope)
}
}
return
} | go | func SplitScopeString(scopestring string) (scopeList []string) {
scopeList = []string{}
for _, value := range strings.Split(scopestring, ",") {
scope := strings.TrimSpace(value)
if scope != "" {
scopeList = append(scopeList, scope)
}
}
return
} | [
"func",
"SplitScopeString",
"(",
"scopestring",
"string",
")",
"(",
"scopeList",
"[",
"]",
"string",
")",
"{",
"scopeList",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"value",
":=",
"range",
"strings",
".",
"Split",
"(",
"scopestring",
",",
"\"",
"\"",
")",
"{",
"scope",
":=",
"strings",
".",
"TrimSpace",
"(",
"value",
")",
"\n",
"if",
"scope",
"!=",
"\"",
"\"",
"{",
"scopeList",
"=",
"append",
"(",
"scopeList",
",",
"scope",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | //SplitScopeString takes a comma seperated string representation of scopes and returns it as a slice | [
"SplitScopeString",
"takes",
"a",
"comma",
"seperated",
"string",
"representation",
"of",
"scopes",
"and",
"returns",
"it",
"as",
"a",
"slice"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/credentials/oauth2/scopes.go#L6-L15 |
14,113 | itsyouonline/identityserver | credentials/oauth2/scopes.go | CheckScopes | func CheckScopes(possibleScopes []string, authorizedScopes []string) bool {
if len(possibleScopes) == 0 {
return true
}
for _, allowed := range possibleScopes {
for _, scope := range authorizedScopes {
if scope == allowed {
return true
}
}
}
return false
} | go | func CheckScopes(possibleScopes []string, authorizedScopes []string) bool {
if len(possibleScopes) == 0 {
return true
}
for _, allowed := range possibleScopes {
for _, scope := range authorizedScopes {
if scope == allowed {
return true
}
}
}
return false
} | [
"func",
"CheckScopes",
"(",
"possibleScopes",
"[",
"]",
"string",
",",
"authorizedScopes",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"possibleScopes",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"allowed",
":=",
"range",
"possibleScopes",
"{",
"for",
"_",
",",
"scope",
":=",
"range",
"authorizedScopes",
"{",
"if",
"scope",
"==",
"allowed",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // CheckScopes checks whether one of the possibleScopes is in the authorized scopes list | [
"CheckScopes",
"checks",
"whether",
"one",
"of",
"the",
"possibleScopes",
"is",
"in",
"the",
"authorized",
"scopes",
"list"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/credentials/oauth2/scopes.go#L18-L31 |
14,114 | itsyouonline/identityserver | siteservice/middleware/ratelimit.go | RateLimit | func RateLimit(period time.Duration, limit int) RateLimiter {
store := memory.NewStore()
rate := limiter.Rate{
Period: period,
Limit: int64(limit),
}
lmt := limiter.New(store, rate)
middleware := stdlib.NewMiddleware(lmt, stdlib.WithForwardHeader(true))
middleware.OnLimitReached = func(w http.ResponseWriter, r *http.Request) {
// Get the clients ip address.
ipString := r.RemoteAddr
// Account for proxies.
if forwardString := r.Header.Get("X-Forwarded-For"); forwardString != "" {
ipString = forwardString
}
// Cloudflare creates a special ipv6 address if the client uses ipv6,
// so check for the appropriate header
// We will rate limit on this special ipv4 address, but this is not a problem
// as Cloudflare maps these special addresses to the underlying ipv6 address
// in a one on one relationship
if ipv6 := r.Header.Get("Cf-Connecting-Ipv6"); ipv6 != "" {
ipString = ipv6
}
log.Info("Rate limiting request from: ", ipString)
// Write some info back to the client
w.WriteHeader(http.StatusTooManyRequests)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("You have reached the maximum request limit."))
return
}
return RateLimiter{middleware}
} | go | func RateLimit(period time.Duration, limit int) RateLimiter {
store := memory.NewStore()
rate := limiter.Rate{
Period: period,
Limit: int64(limit),
}
lmt := limiter.New(store, rate)
middleware := stdlib.NewMiddleware(lmt, stdlib.WithForwardHeader(true))
middleware.OnLimitReached = func(w http.ResponseWriter, r *http.Request) {
// Get the clients ip address.
ipString := r.RemoteAddr
// Account for proxies.
if forwardString := r.Header.Get("X-Forwarded-For"); forwardString != "" {
ipString = forwardString
}
// Cloudflare creates a special ipv6 address if the client uses ipv6,
// so check for the appropriate header
// We will rate limit on this special ipv4 address, but this is not a problem
// as Cloudflare maps these special addresses to the underlying ipv6 address
// in a one on one relationship
if ipv6 := r.Header.Get("Cf-Connecting-Ipv6"); ipv6 != "" {
ipString = ipv6
}
log.Info("Rate limiting request from: ", ipString)
// Write some info back to the client
w.WriteHeader(http.StatusTooManyRequests)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("You have reached the maximum request limit."))
return
}
return RateLimiter{middleware}
} | [
"func",
"RateLimit",
"(",
"period",
"time",
".",
"Duration",
",",
"limit",
"int",
")",
"RateLimiter",
"{",
"store",
":=",
"memory",
".",
"NewStore",
"(",
")",
"\n",
"rate",
":=",
"limiter",
".",
"Rate",
"{",
"Period",
":",
"period",
",",
"Limit",
":",
"int64",
"(",
"limit",
")",
",",
"}",
"\n\n",
"lmt",
":=",
"limiter",
".",
"New",
"(",
"store",
",",
"rate",
")",
"\n",
"middleware",
":=",
"stdlib",
".",
"NewMiddleware",
"(",
"lmt",
",",
"stdlib",
".",
"WithForwardHeader",
"(",
"true",
")",
")",
"\n",
"middleware",
".",
"OnLimitReached",
"=",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"// Get the clients ip address.",
"ipString",
":=",
"r",
".",
"RemoteAddr",
"\n",
"// Account for proxies.",
"if",
"forwardString",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"forwardString",
"!=",
"\"",
"\"",
"{",
"ipString",
"=",
"forwardString",
"\n",
"}",
"\n",
"// Cloudflare creates a special ipv6 address if the client uses ipv6,",
"// so check for the appropriate header",
"// We will rate limit on this special ipv4 address, but this is not a problem",
"// as Cloudflare maps these special addresses to the underlying ipv6 address",
"// in a one on one relationship",
"if",
"ipv6",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"ipv6",
"!=",
"\"",
"\"",
"{",
"ipString",
"=",
"ipv6",
"\n",
"}",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"ipString",
")",
"\n\n",
"// Write some info back to the client",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusTooManyRequests",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"return",
"RateLimiter",
"{",
"middleware",
"}",
"\n\n",
"}"
] | // RateLimit creates a new rate limiting middleware with in memory store
// the amount of maximum requests can be set as wel as the duration in which this limit
// applies | [
"RateLimit",
"creates",
"a",
"new",
"rate",
"limiting",
"middleware",
"with",
"in",
"memory",
"store",
"the",
"amount",
"of",
"maximum",
"requests",
"can",
"be",
"set",
"as",
"wel",
"as",
"the",
"duration",
"in",
"which",
"this",
"limit",
"applies"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/siteservice/middleware/ratelimit.go#L28-L62 |
14,115 | itsyouonline/identityserver | db/smshistory/db.go | AddSMSHistory | func (m *Manager) AddSMSHistory(sh *SmsHistory) error {
return m.collection.Insert(sh)
} | go | func (m *Manager) AddSMSHistory(sh *SmsHistory) error {
return m.collection.Insert(sh)
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"AddSMSHistory",
"(",
"sh",
"*",
"SmsHistory",
")",
"error",
"{",
"return",
"m",
".",
"collection",
".",
"Insert",
"(",
"sh",
")",
"\n",
"}"
] | // AddSMSHistory adds SmsHistory to the database | [
"AddSMSHistory",
"adds",
"SmsHistory",
"to",
"the",
"database"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/smshistory/db.go#L44-L46 |
14,116 | itsyouonline/identityserver | db/smshistory/db.go | CountSMSHistorySince | func (m *Manager) CountSMSHistorySince(phonenumber string, since time.Time) (int, error) {
return m.collection.Find(bson.M{"createdat": bson.M{"$gte": since}}).Count()
} | go | func (m *Manager) CountSMSHistorySince(phonenumber string, since time.Time) (int, error) {
return m.collection.Find(bson.M{"createdat": bson.M{"$gte": since}}).Count()
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"CountSMSHistorySince",
"(",
"phonenumber",
"string",
",",
"since",
"time",
".",
"Time",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"m",
".",
"collection",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"since",
"}",
"}",
")",
".",
"Count",
"(",
")",
"\n",
"}"
] | // CountSMSHistorySince counts the amount of sms sent to a phone number since a specific time | [
"CountSMSHistorySince",
"counts",
"the",
"amount",
"of",
"sms",
"sent",
"to",
"a",
"phone",
"number",
"since",
"a",
"specific",
"time"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/db/smshistory/db.go#L49-L51 |
14,117 | itsyouonline/identityserver | identityservice/organization/APIKey.go | FromOAuthClient | func FromOAuthClient(client *oauthservice.Oauth2Client) APIKey {
apiKey := APIKey{
CallbackURL: client.CallbackURL,
ClientCredentialsGrantType: client.ClientCredentialsGrantType,
Label: client.Label,
Secret: client.Secret,
}
return apiKey
} | go | func FromOAuthClient(client *oauthservice.Oauth2Client) APIKey {
apiKey := APIKey{
CallbackURL: client.CallbackURL,
ClientCredentialsGrantType: client.ClientCredentialsGrantType,
Label: client.Label,
Secret: client.Secret,
}
return apiKey
} | [
"func",
"FromOAuthClient",
"(",
"client",
"*",
"oauthservice",
".",
"Oauth2Client",
")",
"APIKey",
"{",
"apiKey",
":=",
"APIKey",
"{",
"CallbackURL",
":",
"client",
".",
"CallbackURL",
",",
"ClientCredentialsGrantType",
":",
"client",
".",
"ClientCredentialsGrantType",
",",
"Label",
":",
"client",
".",
"Label",
",",
"Secret",
":",
"client",
".",
"Secret",
",",
"}",
"\n",
"return",
"apiKey",
"\n",
"}"
] | //FromOAuthClient creates an APIKey instance from an oauthservice.Oauth2Client | [
"FromOAuthClient",
"creates",
"an",
"APIKey",
"instance",
"from",
"an",
"oauthservice",
".",
"Oauth2Client"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/identityservice/organization/APIKey.go#L18-L26 |
14,118 | itsyouonline/identityserver | identityservice/invitations/JoinOrganizationInvitation.go | ConvertToView | func (inv *JoinOrganizationInvitation) ConvertToView(usrMgr *user.Manager, valMgr *validation.Manager) (*JoinOrganizationInvitationView, error) {
vw := &JoinOrganizationInvitationView{}
vw.Organization = inv.Organization
vw.Role = inv.Role
vw.Status = inv.Status
vw.Created = inv.Created
vw.Method = inv.Method
vw.EmailAddress = inv.EmailAddress
vw.PhoneNumber = inv.PhoneNumber
vw.IsOrganization = inv.IsOrganization
var err error
vw.User, err = organization.ConvertUsernameToIdentifier(inv.User, usrMgr, valMgr)
// user can be empty if invited through email or phone number
if db.IsNotFound(err) {
err = nil
}
return vw, err
} | go | func (inv *JoinOrganizationInvitation) ConvertToView(usrMgr *user.Manager, valMgr *validation.Manager) (*JoinOrganizationInvitationView, error) {
vw := &JoinOrganizationInvitationView{}
vw.Organization = inv.Organization
vw.Role = inv.Role
vw.Status = inv.Status
vw.Created = inv.Created
vw.Method = inv.Method
vw.EmailAddress = inv.EmailAddress
vw.PhoneNumber = inv.PhoneNumber
vw.IsOrganization = inv.IsOrganization
var err error
vw.User, err = organization.ConvertUsernameToIdentifier(inv.User, usrMgr, valMgr)
// user can be empty if invited through email or phone number
if db.IsNotFound(err) {
err = nil
}
return vw, err
} | [
"func",
"(",
"inv",
"*",
"JoinOrganizationInvitation",
")",
"ConvertToView",
"(",
"usrMgr",
"*",
"user",
".",
"Manager",
",",
"valMgr",
"*",
"validation",
".",
"Manager",
")",
"(",
"*",
"JoinOrganizationInvitationView",
",",
"error",
")",
"{",
"vw",
":=",
"&",
"JoinOrganizationInvitationView",
"{",
"}",
"\n",
"vw",
".",
"Organization",
"=",
"inv",
".",
"Organization",
"\n",
"vw",
".",
"Role",
"=",
"inv",
".",
"Role",
"\n",
"vw",
".",
"Status",
"=",
"inv",
".",
"Status",
"\n",
"vw",
".",
"Created",
"=",
"inv",
".",
"Created",
"\n",
"vw",
".",
"Method",
"=",
"inv",
".",
"Method",
"\n",
"vw",
".",
"EmailAddress",
"=",
"inv",
".",
"EmailAddress",
"\n",
"vw",
".",
"PhoneNumber",
"=",
"inv",
".",
"PhoneNumber",
"\n",
"vw",
".",
"IsOrganization",
"=",
"inv",
".",
"IsOrganization",
"\n\n",
"var",
"err",
"error",
"\n",
"vw",
".",
"User",
",",
"err",
"=",
"organization",
".",
"ConvertUsernameToIdentifier",
"(",
"inv",
".",
"User",
",",
"usrMgr",
",",
"valMgr",
")",
"\n",
"// user can be empty if invited through email or phone number",
"if",
"db",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"vw",
",",
"err",
"\n",
"}"
] | // ConvertToView converts a JoinOrganizationInvitation to a JoinOrganizationInvitationView | [
"ConvertToView",
"converts",
"a",
"JoinOrganizationInvitation",
"to",
"a",
"JoinOrganizationInvitationView"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/identityservice/invitations/JoinOrganizationInvitation.go#L89-L107 |
14,119 | itsyouonline/identityserver | credentials/oauth2/jwt.go | GetValidJWT | func GetValidJWT(r *http.Request, publicKey *ecdsa.PublicKey) (token *jwt.Token, err error) {
authorizationHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authorizationHeader, "bearer ") && !strings.HasPrefix(authorizationHeader, "Bearer ") {
return
}
jwtstring := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(authorizationHeader, "Bearer"), "bearer"))
token, err = jwt.Parse(jwtstring, func(token *jwt.Token) (interface{}, error) {
m, ok := token.Method.(*jwt.SigningMethodECDSA)
if !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
if token.Header["alg"] != m.Alg() {
return nil, fmt.Errorf("Unexpected signing algorithm: %v", token.Header["alg"])
}
return publicKey, nil
})
if err == nil && !token.Valid {
err = errors.New("Invalid jwt supplied:" + jwtstring)
}
return
} | go | func GetValidJWT(r *http.Request, publicKey *ecdsa.PublicKey) (token *jwt.Token, err error) {
authorizationHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authorizationHeader, "bearer ") && !strings.HasPrefix(authorizationHeader, "Bearer ") {
return
}
jwtstring := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(authorizationHeader, "Bearer"), "bearer"))
token, err = jwt.Parse(jwtstring, func(token *jwt.Token) (interface{}, error) {
m, ok := token.Method.(*jwt.SigningMethodECDSA)
if !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
if token.Header["alg"] != m.Alg() {
return nil, fmt.Errorf("Unexpected signing algorithm: %v", token.Header["alg"])
}
return publicKey, nil
})
if err == nil && !token.Valid {
err = errors.New("Invalid jwt supplied:" + jwtstring)
}
return
} | [
"func",
"GetValidJWT",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"publicKey",
"*",
"ecdsa",
".",
"PublicKey",
")",
"(",
"token",
"*",
"jwt",
".",
"Token",
",",
"err",
"error",
")",
"{",
"authorizationHeader",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"authorizationHeader",
",",
"\"",
"\"",
")",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"authorizationHeader",
",",
"\"",
"\"",
")",
"{",
"return",
"\n",
"}",
"\n",
"jwtstring",
":=",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"TrimPrefix",
"(",
"strings",
".",
"TrimPrefix",
"(",
"authorizationHeader",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"token",
",",
"err",
"=",
"jwt",
".",
"Parse",
"(",
"jwtstring",
",",
"func",
"(",
"token",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"m",
",",
"ok",
":=",
"token",
".",
"Method",
".",
"(",
"*",
"jwt",
".",
"SigningMethodECDSA",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
".",
"Header",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}",
"\n",
"if",
"token",
".",
"Header",
"[",
"\"",
"\"",
"]",
"!=",
"m",
".",
"Alg",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
".",
"Header",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}",
"\n",
"return",
"publicKey",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"!",
"token",
".",
"Valid",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"jwtstring",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | //GetValidJWT returns a validated ES384 signed jwt from the authorization header that needs to start with "bearer "
// If no jwt is found in the authorization header, nil is returned
// Validation against the supplied publickey is performed | [
"GetValidJWT",
"returns",
"a",
"validated",
"ES384",
"signed",
"jwt",
"from",
"the",
"authorization",
"header",
"that",
"needs",
"to",
"start",
"with",
"bearer",
"If",
"no",
"jwt",
"is",
"found",
"in",
"the",
"authorization",
"header",
"nil",
"is",
"returned",
"Validation",
"against",
"the",
"supplied",
"publickey",
"is",
"performed"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/credentials/oauth2/jwt.go#L16-L36 |
14,120 | itsyouonline/identityserver | credentials/oauth2/jwt.go | GetScopestringFromJWT | func GetScopestringFromJWT(token *jwt.Token) (scopestring string) {
if token == nil {
return
}
scopes := GetScopesFromJWT(token)
scopestring = strings.Join(scopes, ",")
return
} | go | func GetScopestringFromJWT(token *jwt.Token) (scopestring string) {
if token == nil {
return
}
scopes := GetScopesFromJWT(token)
scopestring = strings.Join(scopes, ",")
return
} | [
"func",
"GetScopestringFromJWT",
"(",
"token",
"*",
"jwt",
".",
"Token",
")",
"(",
"scopestring",
"string",
")",
"{",
"if",
"token",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"scopes",
":=",
"GetScopesFromJWT",
"(",
"token",
")",
"\n",
"scopestring",
"=",
"strings",
".",
"Join",
"(",
"scopes",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}"
] | // GetScopestringFromJWT turns the scopes from a jwt in to a commaseperated scopestring | [
"GetScopestringFromJWT",
"turns",
"the",
"scopes",
"from",
"a",
"jwt",
"in",
"to",
"a",
"commaseperated",
"scopestring"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/credentials/oauth2/jwt.go#L53-L60 |
14,121 | itsyouonline/identityserver | credentials/oauth2/jwt.go | IgnoreExpired | func IgnoreExpired(err error) error {
vErr, ok := err.(*jwt.ValidationError)
if ok && vErr.Errors == jwt.ValidationErrorExpired {
return nil
}
return err
} | go | func IgnoreExpired(err error) error {
vErr, ok := err.(*jwt.ValidationError)
if ok && vErr.Errors == jwt.ValidationErrorExpired {
return nil
}
return err
} | [
"func",
"IgnoreExpired",
"(",
"err",
"error",
")",
"error",
"{",
"vErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"jwt",
".",
"ValidationError",
")",
"\n",
"if",
"ok",
"&&",
"vErr",
".",
"Errors",
"==",
"jwt",
".",
"ValidationErrorExpired",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // IgnoreExpired checks if the input error is only an expired error. Nil is returned in
// this case, else the original error | [
"IgnoreExpired",
"checks",
"if",
"the",
"input",
"error",
"is",
"only",
"an",
"expired",
"error",
".",
"Nil",
"is",
"returned",
"in",
"this",
"case",
"else",
"the",
"original",
"error"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/credentials/oauth2/jwt.go#L64-L70 |
14,122 | itsyouonline/identityserver | communication/sms.go | Send | func (s *SMSServiceProxySeparateRussia) Send(phonenumber string, message string) (err error) {
if IsRussianMobileNumber(phonenumber) {
return s.RussianSMSService.Send(phonenumber, message)
}
return s.DefaultSMSService.Send(phonenumber, message)
} | go | func (s *SMSServiceProxySeparateRussia) Send(phonenumber string, message string) (err error) {
if IsRussianMobileNumber(phonenumber) {
return s.RussianSMSService.Send(phonenumber, message)
}
return s.DefaultSMSService.Send(phonenumber, message)
} | [
"func",
"(",
"s",
"*",
"SMSServiceProxySeparateRussia",
")",
"Send",
"(",
"phonenumber",
"string",
",",
"message",
"string",
")",
"(",
"err",
"error",
")",
"{",
"if",
"IsRussianMobileNumber",
"(",
"phonenumber",
")",
"{",
"return",
"s",
".",
"RussianSMSService",
".",
"Send",
"(",
"phonenumber",
",",
"message",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"DefaultSMSService",
".",
"Send",
"(",
"phonenumber",
",",
"message",
")",
"\n",
"}"
] | // Send proxies the send call to the right provider based on the phonenumber | [
"Send",
"proxies",
"the",
"send",
"call",
"to",
"the",
"right",
"provider",
"based",
"on",
"the",
"phonenumber"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/communication/sms.go#L110-L115 |
14,123 | itsyouonline/identityserver | communication/ratelimitedsms.go | NewRateLimitedSMSService | func NewRateLimitedSMSService(window int, maxSMS int, actualService SMSService) SMSService {
return &RateLimitedSMSService{
actualService: actualService,
window: time.Duration(int(time.Second) * window),
maxSMS: maxSMS,
}
} | go | func NewRateLimitedSMSService(window int, maxSMS int, actualService SMSService) SMSService {
return &RateLimitedSMSService{
actualService: actualService,
window: time.Duration(int(time.Second) * window),
maxSMS: maxSMS,
}
} | [
"func",
"NewRateLimitedSMSService",
"(",
"window",
"int",
",",
"maxSMS",
"int",
",",
"actualService",
"SMSService",
")",
"SMSService",
"{",
"return",
"&",
"RateLimitedSMSService",
"{",
"actualService",
":",
"actualService",
",",
"window",
":",
"time",
".",
"Duration",
"(",
"int",
"(",
"time",
".",
"Second",
")",
"*",
"window",
")",
",",
"maxSMS",
":",
"maxSMS",
",",
"}",
"\n",
"}"
] | // NewRateLimitedSMSService rates limit an existing sms service to the defined rate | [
"NewRateLimitedSMSService",
"rates",
"limit",
"an",
"existing",
"sms",
"service",
"to",
"the",
"defined",
"rate"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/communication/ratelimitedsms.go#L25-L31 |
14,124 | itsyouonline/identityserver | communication/ratelimitedsms.go | Send | func (s *RateLimitedSMSService) Send(phonenumber string, message string) (err error) {
conn := db.NewSession()
if conn == nil {
return errors.New("Failed to get DB connection")
}
mgr := smshistory.NewManager(conn)
sendCount, err := mgr.CountSMSHistorySince(phonenumber, time.Now().Add(-s.window))
if err != nil && !db.IsNotFound(err) {
log.Error("Failed to count sms history: ", err)
return err
}
// if we've send more or equal than max sms count msges already return an error
if sendCount >= s.maxSMS {
log.Info("Rate limiting sms sending to ", phonenumber, ", already sent ", sendCount, " SMS in the last ", s.window)
return ErrMaxSMS
}
// Add log entry
record := smshistory.New(phonenumber)
if err = mgr.AddSMSHistory(record); err != nil {
return err
}
// Send the actual sms
return s.actualService.Send(phonenumber, message)
} | go | func (s *RateLimitedSMSService) Send(phonenumber string, message string) (err error) {
conn := db.NewSession()
if conn == nil {
return errors.New("Failed to get DB connection")
}
mgr := smshistory.NewManager(conn)
sendCount, err := mgr.CountSMSHistorySince(phonenumber, time.Now().Add(-s.window))
if err != nil && !db.IsNotFound(err) {
log.Error("Failed to count sms history: ", err)
return err
}
// if we've send more or equal than max sms count msges already return an error
if sendCount >= s.maxSMS {
log.Info("Rate limiting sms sending to ", phonenumber, ", already sent ", sendCount, " SMS in the last ", s.window)
return ErrMaxSMS
}
// Add log entry
record := smshistory.New(phonenumber)
if err = mgr.AddSMSHistory(record); err != nil {
return err
}
// Send the actual sms
return s.actualService.Send(phonenumber, message)
} | [
"func",
"(",
"s",
"*",
"RateLimitedSMSService",
")",
"Send",
"(",
"phonenumber",
"string",
",",
"message",
"string",
")",
"(",
"err",
"error",
")",
"{",
"conn",
":=",
"db",
".",
"NewSession",
"(",
")",
"\n",
"if",
"conn",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"mgr",
":=",
"smshistory",
".",
"NewManager",
"(",
"conn",
")",
"\n\n",
"sendCount",
",",
"err",
":=",
"mgr",
".",
"CountSMSHistorySince",
"(",
"phonenumber",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"s",
".",
"window",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"db",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// if we've send more or equal than max sms count msges already return an error",
"if",
"sendCount",
">=",
"s",
".",
"maxSMS",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"phonenumber",
",",
"\"",
"\"",
",",
"sendCount",
",",
"\"",
"\"",
",",
"s",
".",
"window",
")",
"\n",
"return",
"ErrMaxSMS",
"\n",
"}",
"\n\n",
"// Add log entry",
"record",
":=",
"smshistory",
".",
"New",
"(",
"phonenumber",
")",
"\n",
"if",
"err",
"=",
"mgr",
".",
"AddSMSHistory",
"(",
"record",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Send the actual sms",
"return",
"s",
".",
"actualService",
".",
"Send",
"(",
"phonenumber",
",",
"message",
")",
"\n",
"}"
] | // Send checksif the message can be send according to the rate limiting rules, and then
// deligates the acutal sender to the wrapped service. This uses a sliding window approach | [
"Send",
"checksif",
"the",
"message",
"can",
"be",
"send",
"according",
"to",
"the",
"rate",
"limiting",
"rules",
"and",
"then",
"deligates",
"the",
"acutal",
"sender",
"to",
"the",
"wrapped",
"service",
".",
"This",
"uses",
"a",
"sliding",
"window",
"approach"
] | 333d78810c675fe259e970c190f35a5dc5586569 | https://github.com/itsyouonline/identityserver/blob/333d78810c675fe259e970c190f35a5dc5586569/communication/ratelimitedsms.go#L35-L63 |
14,125 | sourcegraph/ctxvfs | namespace.go | Fprint | func (ns NameSpace) Fprint(w io.Writer) {
fmt.Fprint(w, "name space {\n")
var all []string
for mtpt := range ns {
all = append(all, mtpt)
}
sort.Strings(all)
for _, mtpt := range all {
fmt.Fprintf(w, "\t%s:\n", mtpt)
for _, m := range ns[mtpt] {
fmt.Fprintf(w, "\t\t%s %s\n", m.fs, m.new)
}
}
fmt.Fprint(w, "}\n")
} | go | func (ns NameSpace) Fprint(w io.Writer) {
fmt.Fprint(w, "name space {\n")
var all []string
for mtpt := range ns {
all = append(all, mtpt)
}
sort.Strings(all)
for _, mtpt := range all {
fmt.Fprintf(w, "\t%s:\n", mtpt)
for _, m := range ns[mtpt] {
fmt.Fprintf(w, "\t\t%s %s\n", m.fs, m.new)
}
}
fmt.Fprint(w, "}\n")
} | [
"func",
"(",
"ns",
"NameSpace",
")",
"Fprint",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"var",
"all",
"[",
"]",
"string",
"\n",
"for",
"mtpt",
":=",
"range",
"ns",
"{",
"all",
"=",
"append",
"(",
"all",
",",
"mtpt",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"all",
")",
"\n",
"for",
"_",
",",
"mtpt",
":=",
"range",
"all",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\n",
"\"",
",",
"mtpt",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"ns",
"[",
"mtpt",
"]",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\t",
"\\n",
"\"",
",",
"m",
".",
"fs",
",",
"m",
".",
"new",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] | // Fprint writes a text representation of the name space to w. | [
"Fprint",
"writes",
"a",
"text",
"representation",
"of",
"the",
"name",
"space",
"to",
"w",
"."
] | 2b65f1b1ea81f660ad7bc9931991f39617eb783e | https://github.com/sourcegraph/ctxvfs/blob/2b65f1b1ea81f660ad7bc9931991f39617eb783e/namespace.go#L58-L72 |
14,126 | sourcegraph/ctxvfs | namespace.go | resolve | func (ns NameSpace) resolve(path string) []mountedFS {
path = ns.clean(path)
for {
if m := ns[path]; m != nil {
if debugNS {
fmt.Printf("resolve %s: %v\n", path, m)
}
return m
}
if path == "/" {
break
}
path = pathpkg.Dir(path)
}
return nil
} | go | func (ns NameSpace) resolve(path string) []mountedFS {
path = ns.clean(path)
for {
if m := ns[path]; m != nil {
if debugNS {
fmt.Printf("resolve %s: %v\n", path, m)
}
return m
}
if path == "/" {
break
}
path = pathpkg.Dir(path)
}
return nil
} | [
"func",
"(",
"ns",
"NameSpace",
")",
"resolve",
"(",
"path",
"string",
")",
"[",
"]",
"mountedFS",
"{",
"path",
"=",
"ns",
".",
"clean",
"(",
"path",
")",
"\n",
"for",
"{",
"if",
"m",
":=",
"ns",
"[",
"path",
"]",
";",
"m",
"!=",
"nil",
"{",
"if",
"debugNS",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"path",
",",
"m",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}",
"\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"break",
"\n",
"}",
"\n",
"path",
"=",
"pathpkg",
".",
"Dir",
"(",
"path",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // resolve resolves a path to the list of mountedFS to use for path. | [
"resolve",
"resolves",
"a",
"path",
"to",
"the",
"list",
"of",
"mountedFS",
"to",
"use",
"for",
"path",
"."
] | 2b65f1b1ea81f660ad7bc9931991f39617eb783e | https://github.com/sourcegraph/ctxvfs/blob/2b65f1b1ea81f660ad7bc9931991f39617eb783e/namespace.go#L124-L139 |
14,127 | sourcegraph/ctxvfs | namespace.go | stat | func (ns NameSpace) stat(ctx context.Context, path string, f func(FileSystem, context.Context, string) (os.FileInfo, error)) (os.FileInfo, error) {
var err error
for _, m := range ns.resolve(path) {
fi, err1 := f(m.fs, ctx, m.translate(path))
if err1 == nil {
return fi, nil
}
if err == nil {
err = err1
}
}
// Check if path is an ancestor dir of a mount point.
if err == nil || os.IsNotExist(err) && len(ns) > 0 {
for old := range ns {
if hasPathPrefix(old, path) && old != path {
return dirInfo(pathpkg.Base(path)), nil
}
}
}
if err == nil {
err = &os.PathError{Op: "stat", Path: path, Err: os.ErrNotExist}
}
return nil, err
} | go | func (ns NameSpace) stat(ctx context.Context, path string, f func(FileSystem, context.Context, string) (os.FileInfo, error)) (os.FileInfo, error) {
var err error
for _, m := range ns.resolve(path) {
fi, err1 := f(m.fs, ctx, m.translate(path))
if err1 == nil {
return fi, nil
}
if err == nil {
err = err1
}
}
// Check if path is an ancestor dir of a mount point.
if err == nil || os.IsNotExist(err) && len(ns) > 0 {
for old := range ns {
if hasPathPrefix(old, path) && old != path {
return dirInfo(pathpkg.Base(path)), nil
}
}
}
if err == nil {
err = &os.PathError{Op: "stat", Path: path, Err: os.ErrNotExist}
}
return nil, err
} | [
"func",
"(",
"ns",
"NameSpace",
")",
"stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"f",
"func",
"(",
"FileSystem",
",",
"context",
".",
"Context",
",",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"ns",
".",
"resolve",
"(",
"path",
")",
"{",
"fi",
",",
"err1",
":=",
"f",
"(",
"m",
".",
"fs",
",",
"ctx",
",",
"m",
".",
"translate",
"(",
"path",
")",
")",
"\n",
"if",
"err1",
"==",
"nil",
"{",
"return",
"fi",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"err1",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Check if path is an ancestor dir of a mount point.",
"if",
"err",
"==",
"nil",
"||",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"&&",
"len",
"(",
"ns",
")",
">",
"0",
"{",
"for",
"old",
":=",
"range",
"ns",
"{",
"if",
"hasPathPrefix",
"(",
"old",
",",
"path",
")",
"&&",
"old",
"!=",
"path",
"{",
"return",
"dirInfo",
"(",
"pathpkg",
".",
"Base",
"(",
"path",
")",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"&",
"os",
".",
"PathError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Path",
":",
"path",
",",
"Err",
":",
"os",
".",
"ErrNotExist",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}"
] | // stat implements the FileSystem Stat and Lstat methods. | [
"stat",
"implements",
"the",
"FileSystem",
"Stat",
"and",
"Lstat",
"methods",
"."
] | 2b65f1b1ea81f660ad7bc9931991f39617eb783e | https://github.com/sourcegraph/ctxvfs/blob/2b65f1b1ea81f660ad7bc9931991f39617eb783e/namespace.go#L165-L190 |
14,128 | sourcegraph/ctxvfs | walk.go | Walk | func Walk(ctx context.Context, root string, fs FileSystem) *Walker {
info, err := fs.Lstat(ctx, root)
return &Walker{
fs: fs,
ctx: ctx,
stack: []item{{root, info, err}},
}
} | go | func Walk(ctx context.Context, root string, fs FileSystem) *Walker {
info, err := fs.Lstat(ctx, root)
return &Walker{
fs: fs,
ctx: ctx,
stack: []item{{root, info, err}},
}
} | [
"func",
"Walk",
"(",
"ctx",
"context",
".",
"Context",
",",
"root",
"string",
",",
"fs",
"FileSystem",
")",
"*",
"Walker",
"{",
"info",
",",
"err",
":=",
"fs",
".",
"Lstat",
"(",
"ctx",
",",
"root",
")",
"\n",
"return",
"&",
"Walker",
"{",
"fs",
":",
"fs",
",",
"ctx",
":",
"ctx",
",",
"stack",
":",
"[",
"]",
"item",
"{",
"{",
"root",
",",
"info",
",",
"err",
"}",
"}",
",",
"}",
"\n",
"}"
] | // Walk returns a new Walker rooted at root on the FileSystem fs. | [
"Walk",
"returns",
"a",
"new",
"Walker",
"rooted",
"at",
"root",
"on",
"the",
"FileSystem",
"fs",
"."
] | 2b65f1b1ea81f660ad7bc9931991f39617eb783e | https://github.com/sourcegraph/ctxvfs/blob/2b65f1b1ea81f660ad7bc9931991f39617eb783e/walk.go#L60-L67 |
14,129 | sourcegraph/ctxvfs | sync.go | Sync | func Sync(mu *sync.Mutex, fs FileSystem) FileSystem {
return &syncFS{mu, fs}
} | go | func Sync(mu *sync.Mutex, fs FileSystem) FileSystem {
return &syncFS{mu, fs}
} | [
"func",
"Sync",
"(",
"mu",
"*",
"sync",
".",
"Mutex",
",",
"fs",
"FileSystem",
")",
"FileSystem",
"{",
"return",
"&",
"syncFS",
"{",
"mu",
",",
"fs",
"}",
"\n",
"}"
] | // Sync creates a new file system wrapper around fs that locks a mutex
// during its operations.
//
// The contents of files must be immutable, since it has no way of
// synchronizing access to the ReadSeekCloser from Open after Open
// returns. | [
"Sync",
"creates",
"a",
"new",
"file",
"system",
"wrapper",
"around",
"fs",
"that",
"locks",
"a",
"mutex",
"during",
"its",
"operations",
".",
"The",
"contents",
"of",
"files",
"must",
"be",
"immutable",
"since",
"it",
"has",
"no",
"way",
"of",
"synchronizing",
"access",
"to",
"the",
"ReadSeekCloser",
"from",
"Open",
"after",
"Open",
"returns",
"."
] | 2b65f1b1ea81f660ad7bc9931991f39617eb783e | https://github.com/sourcegraph/ctxvfs/blob/2b65f1b1ea81f660ad7bc9931991f39617eb783e/sync.go#L16-L18 |
14,130 | infobloxopen/infoblox-go-client | object_manager.go | validateMatchClient | func validateMatchClient(value string) bool {
match_client := [5]string{"MAC_ADDRESS", "CLIENT_ID", "RESERVED", "CIRCUIT_ID", "REMOTE_ID"}
for _, val := range match_client {
if val == value {
return true
}
}
return false
} | go | func validateMatchClient(value string) bool {
match_client := [5]string{"MAC_ADDRESS", "CLIENT_ID", "RESERVED", "CIRCUIT_ID", "REMOTE_ID"}
for _, val := range match_client {
if val == value {
return true
}
}
return false
} | [
"func",
"validateMatchClient",
"(",
"value",
"string",
")",
"bool",
"{",
"match_client",
":=",
"[",
"5",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n\n",
"for",
"_",
",",
"val",
":=",
"range",
"match_client",
"{",
"if",
"val",
"==",
"value",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // validation for match_client | [
"validation",
"for",
"match_client"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L350-L359 |
14,131 | infobloxopen/infoblox-go-client | object_manager.go | CreateMultiObject | func (objMgr *ObjectManager) CreateMultiObject(req *MultiRequest) ([]map[string]interface{}, error) {
conn := objMgr.connector.(*Connector)
queryParams := QueryParams{forceProxy: false}
res, err := conn.makeRequest(CREATE, req, "", queryParams)
if err != nil {
return nil, err
}
var result []map[string]interface{}
err = json.Unmarshal(res, &result)
if err != nil {
return nil, err
}
return result, nil
} | go | func (objMgr *ObjectManager) CreateMultiObject(req *MultiRequest) ([]map[string]interface{}, error) {
conn := objMgr.connector.(*Connector)
queryParams := QueryParams{forceProxy: false}
res, err := conn.makeRequest(CREATE, req, "", queryParams)
if err != nil {
return nil, err
}
var result []map[string]interface{}
err = json.Unmarshal(res, &result)
if err != nil {
return nil, err
}
return result, nil
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"CreateMultiObject",
"(",
"req",
"*",
"MultiRequest",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"conn",
":=",
"objMgr",
".",
"connector",
".",
"(",
"*",
"Connector",
")",
"\n",
"queryParams",
":=",
"QueryParams",
"{",
"forceProxy",
":",
"false",
"}",
"\n",
"res",
",",
"err",
":=",
"conn",
".",
"makeRequest",
"(",
"CREATE",
",",
"req",
",",
"\"",
"\"",
",",
"queryParams",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"result",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"result",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // CreateMultiObject unmarshals the result into slice of maps | [
"CreateMultiObject",
"unmarshals",
"the",
"result",
"into",
"slice",
"of",
"maps"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L610-L628 |
14,132 | infobloxopen/infoblox-go-client | object_manager.go | GetUpgradeStatus | func (objMgr *ObjectManager) GetUpgradeStatus(statusType string) ([]UpgradeStatus, error) {
var res []UpgradeStatus
if statusType == "" {
// TODO option may vary according to the WAPI version, need to
// throw relevant error.
msg := fmt.Sprintf("Status type can not be nil")
return res, errors.New(msg)
}
upgradestatus := NewUpgradeStatus(UpgradeStatus{Type: statusType})
err := objMgr.connector.GetObject(upgradestatus, "", &res)
return res, err
} | go | func (objMgr *ObjectManager) GetUpgradeStatus(statusType string) ([]UpgradeStatus, error) {
var res []UpgradeStatus
if statusType == "" {
// TODO option may vary according to the WAPI version, need to
// throw relevant error.
msg := fmt.Sprintf("Status type can not be nil")
return res, errors.New(msg)
}
upgradestatus := NewUpgradeStatus(UpgradeStatus{Type: statusType})
err := objMgr.connector.GetObject(upgradestatus, "", &res)
return res, err
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"GetUpgradeStatus",
"(",
"statusType",
"string",
")",
"(",
"[",
"]",
"UpgradeStatus",
",",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"UpgradeStatus",
"\n\n",
"if",
"statusType",
"==",
"\"",
"\"",
"{",
"// TODO option may vary according to the WAPI version, need to",
"// throw relevant error.",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"res",
",",
"errors",
".",
"New",
"(",
"msg",
")",
"\n",
"}",
"\n",
"upgradestatus",
":=",
"NewUpgradeStatus",
"(",
"UpgradeStatus",
"{",
"Type",
":",
"statusType",
"}",
")",
"\n",
"err",
":=",
"objMgr",
".",
"connector",
".",
"GetObject",
"(",
"upgradestatus",
",",
"\"",
"\"",
",",
"&",
"res",
")",
"\n\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // GetUpgradeStatus returns the grid upgrade information | [
"GetUpgradeStatus",
"returns",
"the",
"grid",
"upgrade",
"information"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L631-L644 |
14,133 | infobloxopen/infoblox-go-client | object_manager.go | GetAllMembers | func (objMgr *ObjectManager) GetAllMembers() ([]Member, error) {
var res []Member
memberObj := NewMember(Member{})
err := objMgr.connector.GetObject(memberObj, "", &res)
return res, err
} | go | func (objMgr *ObjectManager) GetAllMembers() ([]Member, error) {
var res []Member
memberObj := NewMember(Member{})
err := objMgr.connector.GetObject(memberObj, "", &res)
return res, err
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"GetAllMembers",
"(",
")",
"(",
"[",
"]",
"Member",
",",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"Member",
"\n\n",
"memberObj",
":=",
"NewMember",
"(",
"Member",
"{",
"}",
")",
"\n",
"err",
":=",
"objMgr",
".",
"connector",
".",
"GetObject",
"(",
"memberObj",
",",
"\"",
"\"",
",",
"&",
"res",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // GetAllMembers returns all members information | [
"GetAllMembers",
"returns",
"all",
"members",
"information"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L647-L653 |
14,134 | infobloxopen/infoblox-go-client | object_manager.go | GetCapacityReport | func (objMgr *ObjectManager) GetCapacityReport(name string) ([]CapacityReport, error) {
var res []CapacityReport
capacityObj := CapacityReport{Name: name}
capacityReport := NewCapcityReport(capacityObj)
err := objMgr.connector.GetObject(capacityReport, "", &res)
return res, err
} | go | func (objMgr *ObjectManager) GetCapacityReport(name string) ([]CapacityReport, error) {
var res []CapacityReport
capacityObj := CapacityReport{Name: name}
capacityReport := NewCapcityReport(capacityObj)
err := objMgr.connector.GetObject(capacityReport, "", &res)
return res, err
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"GetCapacityReport",
"(",
"name",
"string",
")",
"(",
"[",
"]",
"CapacityReport",
",",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"CapacityReport",
"\n\n",
"capacityObj",
":=",
"CapacityReport",
"{",
"Name",
":",
"name",
"}",
"\n",
"capacityReport",
":=",
"NewCapcityReport",
"(",
"capacityObj",
")",
"\n",
"err",
":=",
"objMgr",
".",
"connector",
".",
"GetObject",
"(",
"capacityReport",
",",
"\"",
"\"",
",",
"&",
"res",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // GetCapacityReport returns all capacity for members | [
"GetCapacityReport",
"returns",
"all",
"capacity",
"for",
"members"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L656-L663 |
14,135 | infobloxopen/infoblox-go-client | object_manager.go | GetLicense | func (objMgr *ObjectManager) GetLicense() ([]License, error) {
var res []License
licenseObj := NewLicense(License{})
err := objMgr.connector.GetObject(licenseObj, "", &res)
return res, err
} | go | func (objMgr *ObjectManager) GetLicense() ([]License, error) {
var res []License
licenseObj := NewLicense(License{})
err := objMgr.connector.GetObject(licenseObj, "", &res)
return res, err
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"GetLicense",
"(",
")",
"(",
"[",
"]",
"License",
",",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"License",
"\n\n",
"licenseObj",
":=",
"NewLicense",
"(",
"License",
"{",
"}",
")",
"\n",
"err",
":=",
"objMgr",
".",
"connector",
".",
"GetObject",
"(",
"licenseObj",
",",
"\"",
"\"",
",",
"&",
"res",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // GetLicense returns the license details for member | [
"GetLicense",
"returns",
"the",
"license",
"details",
"for",
"member"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L666-L672 |
14,136 | infobloxopen/infoblox-go-client | object_manager.go | GetGridLicense | func (objMgr *ObjectManager) GetGridLicense() ([]License, error) {
var res []License
licenseObj := NewGridLicense(License{})
err := objMgr.connector.GetObject(licenseObj, "", &res)
return res, err
} | go | func (objMgr *ObjectManager) GetGridLicense() ([]License, error) {
var res []License
licenseObj := NewGridLicense(License{})
err := objMgr.connector.GetObject(licenseObj, "", &res)
return res, err
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"GetGridLicense",
"(",
")",
"(",
"[",
"]",
"License",
",",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"License",
"\n\n",
"licenseObj",
":=",
"NewGridLicense",
"(",
"License",
"{",
"}",
")",
"\n",
"err",
":=",
"objMgr",
".",
"connector",
".",
"GetObject",
"(",
"licenseObj",
",",
"\"",
"\"",
",",
"&",
"res",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // GetLicense returns the license details for grid | [
"GetLicense",
"returns",
"the",
"license",
"details",
"for",
"grid"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L675-L681 |
14,137 | infobloxopen/infoblox-go-client | object_manager.go | GetGridInfo | func (objMgr *ObjectManager) GetGridInfo() ([]Grid, error) {
var res []Grid
gridObj := NewGrid(Grid{})
err := objMgr.connector.GetObject(gridObj, "", &res)
return res, err
} | go | func (objMgr *ObjectManager) GetGridInfo() ([]Grid, error) {
var res []Grid
gridObj := NewGrid(Grid{})
err := objMgr.connector.GetObject(gridObj, "", &res)
return res, err
} | [
"func",
"(",
"objMgr",
"*",
"ObjectManager",
")",
"GetGridInfo",
"(",
")",
"(",
"[",
"]",
"Grid",
",",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"Grid",
"\n\n",
"gridObj",
":=",
"NewGrid",
"(",
"Grid",
"{",
"}",
")",
"\n",
"err",
":=",
"objMgr",
".",
"connector",
".",
"GetObject",
"(",
"gridObj",
",",
"\"",
"\"",
",",
"&",
"res",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // GetGridInfo returns the details for grid | [
"GetGridInfo",
"returns",
"the",
"details",
"for",
"grid"
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/object_manager.go#L684-L690 |
14,138 | infobloxopen/infoblox-go-client | connector.go | Logout | func (c *Connector) Logout() (err error) {
queryParams := QueryParams{forceProxy: false}
_, err = c.makeRequest(CREATE, nil, "logout", queryParams)
if err != nil {
log.Printf("Logout request error: '%s'\n", err)
}
return
} | go | func (c *Connector) Logout() (err error) {
queryParams := QueryParams{forceProxy: false}
_, err = c.makeRequest(CREATE, nil, "logout", queryParams)
if err != nil {
log.Printf("Logout request error: '%s'\n", err)
}
return
} | [
"func",
"(",
"c",
"*",
"Connector",
")",
"Logout",
"(",
")",
"(",
"err",
"error",
")",
"{",
"queryParams",
":=",
"QueryParams",
"{",
"forceProxy",
":",
"false",
"}",
"\n",
"_",
",",
"err",
"=",
"c",
".",
"makeRequest",
"(",
"CREATE",
",",
"nil",
",",
"\"",
"\"",
",",
"queryParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Logout sends a request to invalidate the ibapauth cookie and should
// be used in a defer statement after the Connector has been successfully
// initialized. | [
"Logout",
"sends",
"a",
"request",
"to",
"invalidate",
"the",
"ibapauth",
"cookie",
"and",
"should",
"be",
"used",
"in",
"a",
"defer",
"statement",
"after",
"the",
"Connector",
"has",
"been",
"successfully",
"initialized",
"."
] | 7247dee3156a9d790d26ee2e0ea609bd24e844a0 | https://github.com/infobloxopen/infoblox-go-client/blob/7247dee3156a9d790d26ee2e0ea609bd24e844a0/connector.go#L349-L357 |
14,139 | d2g/dhcp4client | client.go | SendDiscoverPacket | func (c *Client) SendDiscoverPacket() (dhcp4.Packet, error) {
discoveryPacket := c.DiscoverPacket()
discoveryPacket.PadToMinSize()
return discoveryPacket, c.SendPacket(discoveryPacket)
} | go | func (c *Client) SendDiscoverPacket() (dhcp4.Packet, error) {
discoveryPacket := c.DiscoverPacket()
discoveryPacket.PadToMinSize()
return discoveryPacket, c.SendPacket(discoveryPacket)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendDiscoverPacket",
"(",
")",
"(",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"discoveryPacket",
":=",
"c",
".",
"DiscoverPacket",
"(",
")",
"\n",
"discoveryPacket",
".",
"PadToMinSize",
"(",
")",
"\n\n",
"return",
"discoveryPacket",
",",
"c",
".",
"SendPacket",
"(",
"discoveryPacket",
")",
"\n",
"}"
] | //Send the Discovery Packet to the Broadcast Channel | [
"Send",
"the",
"Discovery",
"Packet",
"to",
"the",
"Broadcast",
"Channel"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L140-L145 |
14,140 | d2g/dhcp4client | client.go | GetOffer | func (c *Client) GetOffer(discoverPacket *dhcp4.Packet) (dhcp4.Packet, error) {
start := time.Now()
for {
timeout := c.timeout - time.Since(start)
if timeout < 0 {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
c.connection.SetReadTimeout(timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EAGAIN {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
return dhcp4.Packet{}, err
}
offerPacket := dhcp4.Packet(readBuffer)
offerPacketOptions := offerPacket.ParseOptions()
// Ignore Servers in my Ignore list
for _, ignoreServer := range c.ignoreServers {
if source.Equal(ignoreServer) {
continue
}
if offerPacket.SIAddr().Equal(ignoreServer) {
continue
}
}
if len(offerPacketOptions[dhcp4.OptionDHCPMessageType]) < 1 || dhcp4.MessageType(offerPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.Offer || !bytes.Equal(discoverPacket.XId(), offerPacket.XId()) {
continue
}
return offerPacket, nil
}
} | go | func (c *Client) GetOffer(discoverPacket *dhcp4.Packet) (dhcp4.Packet, error) {
start := time.Now()
for {
timeout := c.timeout - time.Since(start)
if timeout < 0 {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
c.connection.SetReadTimeout(timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EAGAIN {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
return dhcp4.Packet{}, err
}
offerPacket := dhcp4.Packet(readBuffer)
offerPacketOptions := offerPacket.ParseOptions()
// Ignore Servers in my Ignore list
for _, ignoreServer := range c.ignoreServers {
if source.Equal(ignoreServer) {
continue
}
if offerPacket.SIAddr().Equal(ignoreServer) {
continue
}
}
if len(offerPacketOptions[dhcp4.OptionDHCPMessageType]) < 1 || dhcp4.MessageType(offerPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.Offer || !bytes.Equal(discoverPacket.XId(), offerPacket.XId()) {
continue
}
return offerPacket, nil
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetOffer",
"(",
"discoverPacket",
"*",
"dhcp4",
".",
"Packet",
")",
"(",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"for",
"{",
"timeout",
":=",
"c",
".",
"timeout",
"-",
"time",
".",
"Since",
"(",
"start",
")",
"\n",
"if",
"timeout",
"<",
"0",
"{",
"return",
"dhcp4",
".",
"Packet",
"{",
"}",
",",
"&",
"TimeoutError",
"{",
"Timeout",
":",
"c",
".",
"timeout",
"}",
"\n",
"}",
"\n\n",
"c",
".",
"connection",
".",
"SetReadTimeout",
"(",
"timeout",
")",
"\n",
"readBuffer",
",",
"source",
",",
"err",
":=",
"c",
".",
"connection",
".",
"ReadFrom",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errno",
",",
"ok",
":=",
"err",
".",
"(",
"syscall",
".",
"Errno",
")",
";",
"ok",
"&&",
"errno",
"==",
"syscall",
".",
"EAGAIN",
"{",
"return",
"dhcp4",
".",
"Packet",
"{",
"}",
",",
"&",
"TimeoutError",
"{",
"Timeout",
":",
"c",
".",
"timeout",
"}",
"\n",
"}",
"\n",
"return",
"dhcp4",
".",
"Packet",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"offerPacket",
":=",
"dhcp4",
".",
"Packet",
"(",
"readBuffer",
")",
"\n",
"offerPacketOptions",
":=",
"offerPacket",
".",
"ParseOptions",
"(",
")",
"\n\n",
"// Ignore Servers in my Ignore list",
"for",
"_",
",",
"ignoreServer",
":=",
"range",
"c",
".",
"ignoreServers",
"{",
"if",
"source",
".",
"Equal",
"(",
"ignoreServer",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"offerPacket",
".",
"SIAddr",
"(",
")",
".",
"Equal",
"(",
"ignoreServer",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"offerPacketOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
")",
"<",
"1",
"||",
"dhcp4",
".",
"MessageType",
"(",
"offerPacketOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
"[",
"0",
"]",
")",
"!=",
"dhcp4",
".",
"Offer",
"||",
"!",
"bytes",
".",
"Equal",
"(",
"discoverPacket",
".",
"XId",
"(",
")",
",",
"offerPacket",
".",
"XId",
"(",
")",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"return",
"offerPacket",
",",
"nil",
"\n",
"}",
"\n\n",
"}"
] | //Retreive Offer...
//Wait for the offer for a specific Discovery Packet. | [
"Retreive",
"Offer",
"...",
"Wait",
"for",
"the",
"offer",
"for",
"a",
"specific",
"Discovery",
"Packet",
"."
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L158-L197 |
14,141 | d2g/dhcp4client | client.go | SendRequest | func (c *Client) SendRequest(offerPacket *dhcp4.Packet) (dhcp4.Packet, error) {
requestPacket := c.RequestPacket(offerPacket)
requestPacket.PadToMinSize()
return requestPacket, c.SendPacket(requestPacket)
} | go | func (c *Client) SendRequest(offerPacket *dhcp4.Packet) (dhcp4.Packet, error) {
requestPacket := c.RequestPacket(offerPacket)
requestPacket.PadToMinSize()
return requestPacket, c.SendPacket(requestPacket)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendRequest",
"(",
"offerPacket",
"*",
"dhcp4",
".",
"Packet",
")",
"(",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"requestPacket",
":=",
"c",
".",
"RequestPacket",
"(",
"offerPacket",
")",
"\n",
"requestPacket",
".",
"PadToMinSize",
"(",
")",
"\n\n",
"return",
"requestPacket",
",",
"c",
".",
"SendPacket",
"(",
"requestPacket",
")",
"\n",
"}"
] | //Send Request Based On the offer Received. | [
"Send",
"Request",
"Based",
"On",
"the",
"offer",
"Received",
"."
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L200-L205 |
14,142 | d2g/dhcp4client | client.go | GetAcknowledgement | func (c *Client) GetAcknowledgement(requestPacket *dhcp4.Packet) (dhcp4.Packet, error) {
start := time.Now()
for {
timeout := c.timeout - time.Since(start)
if timeout < 0 {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
c.connection.SetReadTimeout(timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EAGAIN {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
return dhcp4.Packet{}, err
}
acknowledgementPacket := dhcp4.Packet(readBuffer)
acknowledgementPacketOptions := acknowledgementPacket.ParseOptions()
// Ignore Servers in my Ignore list
for _, ignoreServer := range c.ignoreServers {
if source.Equal(ignoreServer) {
continue
}
if acknowledgementPacket.SIAddr().Equal(ignoreServer) {
continue
}
}
if !bytes.Equal(requestPacket.XId(), acknowledgementPacket.XId()) || len(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType]) < 1 || (dhcp4.MessageType(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK && dhcp4.MessageType(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.NAK) {
continue
}
return acknowledgementPacket, nil
}
} | go | func (c *Client) GetAcknowledgement(requestPacket *dhcp4.Packet) (dhcp4.Packet, error) {
start := time.Now()
for {
timeout := c.timeout - time.Since(start)
if timeout < 0 {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
c.connection.SetReadTimeout(timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EAGAIN {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
return dhcp4.Packet{}, err
}
acknowledgementPacket := dhcp4.Packet(readBuffer)
acknowledgementPacketOptions := acknowledgementPacket.ParseOptions()
// Ignore Servers in my Ignore list
for _, ignoreServer := range c.ignoreServers {
if source.Equal(ignoreServer) {
continue
}
if acknowledgementPacket.SIAddr().Equal(ignoreServer) {
continue
}
}
if !bytes.Equal(requestPacket.XId(), acknowledgementPacket.XId()) || len(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType]) < 1 || (dhcp4.MessageType(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK && dhcp4.MessageType(acknowledgementPacketOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.NAK) {
continue
}
return acknowledgementPacket, nil
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetAcknowledgement",
"(",
"requestPacket",
"*",
"dhcp4",
".",
"Packet",
")",
"(",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"for",
"{",
"timeout",
":=",
"c",
".",
"timeout",
"-",
"time",
".",
"Since",
"(",
"start",
")",
"\n",
"if",
"timeout",
"<",
"0",
"{",
"return",
"dhcp4",
".",
"Packet",
"{",
"}",
",",
"&",
"TimeoutError",
"{",
"Timeout",
":",
"c",
".",
"timeout",
"}",
"\n",
"}",
"\n\n",
"c",
".",
"connection",
".",
"SetReadTimeout",
"(",
"timeout",
")",
"\n",
"readBuffer",
",",
"source",
",",
"err",
":=",
"c",
".",
"connection",
".",
"ReadFrom",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errno",
",",
"ok",
":=",
"err",
".",
"(",
"syscall",
".",
"Errno",
")",
";",
"ok",
"&&",
"errno",
"==",
"syscall",
".",
"EAGAIN",
"{",
"return",
"dhcp4",
".",
"Packet",
"{",
"}",
",",
"&",
"TimeoutError",
"{",
"Timeout",
":",
"c",
".",
"timeout",
"}",
"\n",
"}",
"\n",
"return",
"dhcp4",
".",
"Packet",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"acknowledgementPacket",
":=",
"dhcp4",
".",
"Packet",
"(",
"readBuffer",
")",
"\n",
"acknowledgementPacketOptions",
":=",
"acknowledgementPacket",
".",
"ParseOptions",
"(",
")",
"\n\n",
"// Ignore Servers in my Ignore list",
"for",
"_",
",",
"ignoreServer",
":=",
"range",
"c",
".",
"ignoreServers",
"{",
"if",
"source",
".",
"Equal",
"(",
"ignoreServer",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"acknowledgementPacket",
".",
"SIAddr",
"(",
")",
".",
"Equal",
"(",
"ignoreServer",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"requestPacket",
".",
"XId",
"(",
")",
",",
"acknowledgementPacket",
".",
"XId",
"(",
")",
")",
"||",
"len",
"(",
"acknowledgementPacketOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
")",
"<",
"1",
"||",
"(",
"dhcp4",
".",
"MessageType",
"(",
"acknowledgementPacketOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
"[",
"0",
"]",
")",
"!=",
"dhcp4",
".",
"ACK",
"&&",
"dhcp4",
".",
"MessageType",
"(",
"acknowledgementPacketOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
"[",
"0",
"]",
")",
"!=",
"dhcp4",
".",
"NAK",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"return",
"acknowledgementPacket",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | //Retreive Acknowledgement
//Wait for the offer for a specific Request Packet. | [
"Retreive",
"Acknowledgement",
"Wait",
"for",
"the",
"offer",
"for",
"a",
"specific",
"Request",
"Packet",
"."
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L209-L247 |
14,143 | d2g/dhcp4client | client.go | SendDecline | func (c *Client) SendDecline(acknowledgementPacket *dhcp4.Packet) (dhcp4.Packet, error) {
declinePacket := c.DeclinePacket(acknowledgementPacket)
declinePacket.PadToMinSize()
return declinePacket, c.SendPacket(declinePacket)
} | go | func (c *Client) SendDecline(acknowledgementPacket *dhcp4.Packet) (dhcp4.Packet, error) {
declinePacket := c.DeclinePacket(acknowledgementPacket)
declinePacket.PadToMinSize()
return declinePacket, c.SendPacket(declinePacket)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendDecline",
"(",
"acknowledgementPacket",
"*",
"dhcp4",
".",
"Packet",
")",
"(",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"declinePacket",
":=",
"c",
".",
"DeclinePacket",
"(",
"acknowledgementPacket",
")",
"\n",
"declinePacket",
".",
"PadToMinSize",
"(",
")",
"\n\n",
"return",
"declinePacket",
",",
"c",
".",
"SendPacket",
"(",
"declinePacket",
")",
"\n",
"}"
] | //Send Decline to the received acknowledgement. | [
"Send",
"Decline",
"to",
"the",
"received",
"acknowledgement",
"."
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L250-L255 |
14,144 | d2g/dhcp4client | client.go | SendPacket | func (c *Client) SendPacket(packet dhcp4.Packet) error {
return c.connection.Write(packet)
} | go | func (c *Client) SendPacket(packet dhcp4.Packet) error {
return c.connection.Write(packet)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendPacket",
"(",
"packet",
"dhcp4",
".",
"Packet",
")",
"error",
"{",
"return",
"c",
".",
"connection",
".",
"Write",
"(",
"packet",
")",
"\n",
"}"
] | //Send a DHCP Packet. | [
"Send",
"a",
"DHCP",
"Packet",
"."
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L258-L260 |
14,145 | d2g/dhcp4client | client.go | DiscoverPacket | func (c *Client) DiscoverPacket() dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(c.hardwareAddr)
packet.SetXId(messageid)
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Discover)})
//packet.PadToMinSize()
return packet
} | go | func (c *Client) DiscoverPacket() dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(c.hardwareAddr)
packet.SetXId(messageid)
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Discover)})
//packet.PadToMinSize()
return packet
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DiscoverPacket",
"(",
")",
"dhcp4",
".",
"Packet",
"{",
"messageid",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"c",
".",
"generateXID",
"(",
"messageid",
")",
"\n\n",
"packet",
":=",
"dhcp4",
".",
"NewPacket",
"(",
"dhcp4",
".",
"BootRequest",
")",
"\n",
"packet",
".",
"SetCHAddr",
"(",
"c",
".",
"hardwareAddr",
")",
"\n",
"packet",
".",
"SetXId",
"(",
"messageid",
")",
"\n",
"packet",
".",
"SetBroadcast",
"(",
"c",
".",
"broadcast",
")",
"\n\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionDHCPMessageType",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"dhcp4",
".",
"Discover",
")",
"}",
")",
"\n",
"//packet.PadToMinSize()",
"return",
"packet",
"\n",
"}"
] | //Create Discover Packet | [
"Create",
"Discover",
"Packet"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L263-L275 |
14,146 | d2g/dhcp4client | client.go | RequestPacket | func (c *Client) RequestPacket(offerPacket *dhcp4.Packet) dhcp4.Packet {
offerOptions := offerPacket.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(c.hardwareAddr)
packet.SetXId(offerPacket.XId())
packet.SetCIAddr(offerPacket.CIAddr())
packet.SetSIAddr(offerPacket.SIAddr())
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (offerPacket.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, offerOptions[dhcp4.OptionServerIdentifier])
return packet
} | go | func (c *Client) RequestPacket(offerPacket *dhcp4.Packet) dhcp4.Packet {
offerOptions := offerPacket.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(c.hardwareAddr)
packet.SetXId(offerPacket.XId())
packet.SetCIAddr(offerPacket.CIAddr())
packet.SetSIAddr(offerPacket.SIAddr())
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (offerPacket.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, offerOptions[dhcp4.OptionServerIdentifier])
return packet
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"RequestPacket",
"(",
"offerPacket",
"*",
"dhcp4",
".",
"Packet",
")",
"dhcp4",
".",
"Packet",
"{",
"offerOptions",
":=",
"offerPacket",
".",
"ParseOptions",
"(",
")",
"\n\n",
"packet",
":=",
"dhcp4",
".",
"NewPacket",
"(",
"dhcp4",
".",
"BootRequest",
")",
"\n",
"packet",
".",
"SetCHAddr",
"(",
"c",
".",
"hardwareAddr",
")",
"\n\n",
"packet",
".",
"SetXId",
"(",
"offerPacket",
".",
"XId",
"(",
")",
")",
"\n",
"packet",
".",
"SetCIAddr",
"(",
"offerPacket",
".",
"CIAddr",
"(",
")",
")",
"\n",
"packet",
".",
"SetSIAddr",
"(",
"offerPacket",
".",
"SIAddr",
"(",
")",
")",
"\n\n",
"packet",
".",
"SetBroadcast",
"(",
"c",
".",
"broadcast",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionDHCPMessageType",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"dhcp4",
".",
"Request",
")",
"}",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionRequestedIPAddress",
",",
"(",
"offerPacket",
".",
"YIAddr",
"(",
")",
")",
".",
"To4",
"(",
")",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionServerIdentifier",
",",
"offerOptions",
"[",
"dhcp4",
".",
"OptionServerIdentifier",
"]",
")",
"\n\n",
"return",
"packet",
"\n",
"}"
] | //Create Request Packet | [
"Create",
"Request",
"Packet"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L278-L294 |
14,147 | d2g/dhcp4client | client.go | RenewalRequestPacket | func (c *Client) RenewalRequestPacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.SetCIAddr(acknowledgement.YIAddr())
packet.SetSIAddr(acknowledgement.SIAddr())
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
} | go | func (c *Client) RenewalRequestPacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.SetCIAddr(acknowledgement.YIAddr())
packet.SetSIAddr(acknowledgement.SIAddr())
packet.SetBroadcast(c.broadcast)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"RenewalRequestPacket",
"(",
"acknowledgement",
"*",
"dhcp4",
".",
"Packet",
")",
"dhcp4",
".",
"Packet",
"{",
"messageid",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"c",
".",
"generateXID",
"(",
"messageid",
")",
"\n\n",
"acknowledgementOptions",
":=",
"acknowledgement",
".",
"ParseOptions",
"(",
")",
"\n\n",
"packet",
":=",
"dhcp4",
".",
"NewPacket",
"(",
"dhcp4",
".",
"BootRequest",
")",
"\n",
"packet",
".",
"SetCHAddr",
"(",
"acknowledgement",
".",
"CHAddr",
"(",
")",
")",
"\n\n",
"packet",
".",
"SetXId",
"(",
"messageid",
")",
"\n",
"packet",
".",
"SetCIAddr",
"(",
"acknowledgement",
".",
"YIAddr",
"(",
")",
")",
"\n",
"packet",
".",
"SetSIAddr",
"(",
"acknowledgement",
".",
"SIAddr",
"(",
")",
")",
"\n\n",
"packet",
".",
"SetBroadcast",
"(",
"c",
".",
"broadcast",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionDHCPMessageType",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"dhcp4",
".",
"Request",
")",
"}",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionRequestedIPAddress",
",",
"(",
"acknowledgement",
".",
"YIAddr",
"(",
")",
")",
".",
"To4",
"(",
")",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionServerIdentifier",
",",
"acknowledgementOptions",
"[",
"dhcp4",
".",
"OptionServerIdentifier",
"]",
")",
"\n\n",
"return",
"packet",
"\n",
"}"
] | //Create Request Packet For a Renew | [
"Create",
"Request",
"Packet",
"For",
"a",
"Renew"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L297-L316 |
14,148 | d2g/dhcp4client | client.go | ReleasePacket | func (c *Client) ReleasePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.SetCIAddr(acknowledgement.YIAddr())
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Release)})
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
} | go | func (c *Client) ReleasePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.SetCIAddr(acknowledgement.YIAddr())
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Release)})
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ReleasePacket",
"(",
"acknowledgement",
"*",
"dhcp4",
".",
"Packet",
")",
"dhcp4",
".",
"Packet",
"{",
"messageid",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"c",
".",
"generateXID",
"(",
"messageid",
")",
"\n\n",
"acknowledgementOptions",
":=",
"acknowledgement",
".",
"ParseOptions",
"(",
")",
"\n\n",
"packet",
":=",
"dhcp4",
".",
"NewPacket",
"(",
"dhcp4",
".",
"BootRequest",
")",
"\n",
"packet",
".",
"SetCHAddr",
"(",
"acknowledgement",
".",
"CHAddr",
"(",
")",
")",
"\n\n",
"packet",
".",
"SetXId",
"(",
"messageid",
")",
"\n",
"packet",
".",
"SetCIAddr",
"(",
"acknowledgement",
".",
"YIAddr",
"(",
")",
")",
"\n\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionDHCPMessageType",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"dhcp4",
".",
"Release",
")",
"}",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionServerIdentifier",
",",
"acknowledgementOptions",
"[",
"dhcp4",
".",
"OptionServerIdentifier",
"]",
")",
"\n\n",
"return",
"packet",
"\n",
"}"
] | //Create Release Packet For a Release | [
"Create",
"Release",
"Packet",
"For",
"a",
"Release"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L319-L335 |
14,149 | d2g/dhcp4client | client.go | DeclinePacket | func (c *Client) DeclinePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Decline)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
} | go | func (c *Client) DeclinePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
messageid := make([]byte, 4)
c.generateXID(messageid)
acknowledgementOptions := acknowledgement.ParseOptions()
packet := dhcp4.NewPacket(dhcp4.BootRequest)
packet.SetCHAddr(acknowledgement.CHAddr())
packet.SetXId(messageid)
packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Decline)})
packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])
return packet
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DeclinePacket",
"(",
"acknowledgement",
"*",
"dhcp4",
".",
"Packet",
")",
"dhcp4",
".",
"Packet",
"{",
"messageid",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"c",
".",
"generateXID",
"(",
"messageid",
")",
"\n\n",
"acknowledgementOptions",
":=",
"acknowledgement",
".",
"ParseOptions",
"(",
")",
"\n\n",
"packet",
":=",
"dhcp4",
".",
"NewPacket",
"(",
"dhcp4",
".",
"BootRequest",
")",
"\n",
"packet",
".",
"SetCHAddr",
"(",
"acknowledgement",
".",
"CHAddr",
"(",
")",
")",
"\n",
"packet",
".",
"SetXId",
"(",
"messageid",
")",
"\n\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionDHCPMessageType",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"dhcp4",
".",
"Decline",
")",
"}",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionRequestedIPAddress",
",",
"(",
"acknowledgement",
".",
"YIAddr",
"(",
")",
")",
".",
"To4",
"(",
")",
")",
"\n",
"packet",
".",
"AddOption",
"(",
"dhcp4",
".",
"OptionServerIdentifier",
",",
"acknowledgementOptions",
"[",
"dhcp4",
".",
"OptionServerIdentifier",
"]",
")",
"\n\n",
"return",
"packet",
"\n",
"}"
] | //Create Decline Packet | [
"Create",
"Decline",
"Packet"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L338-L353 |
14,150 | d2g/dhcp4client | client.go | Request | func (c *Client) Request() (bool, dhcp4.Packet, error) {
discoveryPacket, err := c.SendDiscoverPacket()
if err != nil {
return false, discoveryPacket, err
}
offerPacket, err := c.GetOffer(&discoveryPacket)
if err != nil {
return false, offerPacket, err
}
requestPacket, err := c.SendRequest(&offerPacket)
if err != nil {
return false, requestPacket, err
}
acknowledgement, err := c.GetAcknowledgement(&requestPacket)
if err != nil {
return false, acknowledgement, err
}
acknowledgementOptions := acknowledgement.ParseOptions()
if dhcp4.MessageType(acknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
return false, acknowledgement, nil
}
return true, acknowledgement, nil
} | go | func (c *Client) Request() (bool, dhcp4.Packet, error) {
discoveryPacket, err := c.SendDiscoverPacket()
if err != nil {
return false, discoveryPacket, err
}
offerPacket, err := c.GetOffer(&discoveryPacket)
if err != nil {
return false, offerPacket, err
}
requestPacket, err := c.SendRequest(&offerPacket)
if err != nil {
return false, requestPacket, err
}
acknowledgement, err := c.GetAcknowledgement(&requestPacket)
if err != nil {
return false, acknowledgement, err
}
acknowledgementOptions := acknowledgement.ParseOptions()
if dhcp4.MessageType(acknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
return false, acknowledgement, nil
}
return true, acknowledgement, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Request",
"(",
")",
"(",
"bool",
",",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"discoveryPacket",
",",
"err",
":=",
"c",
".",
"SendDiscoverPacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"discoveryPacket",
",",
"err",
"\n",
"}",
"\n\n",
"offerPacket",
",",
"err",
":=",
"c",
".",
"GetOffer",
"(",
"&",
"discoveryPacket",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"offerPacket",
",",
"err",
"\n",
"}",
"\n\n",
"requestPacket",
",",
"err",
":=",
"c",
".",
"SendRequest",
"(",
"&",
"offerPacket",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"requestPacket",
",",
"err",
"\n",
"}",
"\n\n",
"acknowledgement",
",",
"err",
":=",
"c",
".",
"GetAcknowledgement",
"(",
"&",
"requestPacket",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"acknowledgement",
",",
"err",
"\n",
"}",
"\n\n",
"acknowledgementOptions",
":=",
"acknowledgement",
".",
"ParseOptions",
"(",
")",
"\n",
"if",
"dhcp4",
".",
"MessageType",
"(",
"acknowledgementOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
"[",
"0",
"]",
")",
"!=",
"dhcp4",
".",
"ACK",
"{",
"return",
"false",
",",
"acknowledgement",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"acknowledgement",
",",
"nil",
"\n",
"}"
] | //Lets do a Full DHCP Request. | [
"Lets",
"do",
"a",
"Full",
"DHCP",
"Request",
"."
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L356-L383 |
14,151 | d2g/dhcp4client | client.go | Renew | func (c *Client) Renew(acknowledgement dhcp4.Packet) (bool, dhcp4.Packet, error) {
renewRequest := c.RenewalRequestPacket(&acknowledgement)
renewRequest.PadToMinSize()
err := c.SendPacket(renewRequest)
if err != nil {
return false, renewRequest, err
}
newAcknowledgement, err := c.GetAcknowledgement(&renewRequest)
if err != nil {
return false, newAcknowledgement, err
}
newAcknowledgementOptions := newAcknowledgement.ParseOptions()
if dhcp4.MessageType(newAcknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
return false, newAcknowledgement, nil
}
return true, newAcknowledgement, nil
} | go | func (c *Client) Renew(acknowledgement dhcp4.Packet) (bool, dhcp4.Packet, error) {
renewRequest := c.RenewalRequestPacket(&acknowledgement)
renewRequest.PadToMinSize()
err := c.SendPacket(renewRequest)
if err != nil {
return false, renewRequest, err
}
newAcknowledgement, err := c.GetAcknowledgement(&renewRequest)
if err != nil {
return false, newAcknowledgement, err
}
newAcknowledgementOptions := newAcknowledgement.ParseOptions()
if dhcp4.MessageType(newAcknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
return false, newAcknowledgement, nil
}
return true, newAcknowledgement, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Renew",
"(",
"acknowledgement",
"dhcp4",
".",
"Packet",
")",
"(",
"bool",
",",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"renewRequest",
":=",
"c",
".",
"RenewalRequestPacket",
"(",
"&",
"acknowledgement",
")",
"\n",
"renewRequest",
".",
"PadToMinSize",
"(",
")",
"\n\n",
"err",
":=",
"c",
".",
"SendPacket",
"(",
"renewRequest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"renewRequest",
",",
"err",
"\n",
"}",
"\n\n",
"newAcknowledgement",
",",
"err",
":=",
"c",
".",
"GetAcknowledgement",
"(",
"&",
"renewRequest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"newAcknowledgement",
",",
"err",
"\n",
"}",
"\n\n",
"newAcknowledgementOptions",
":=",
"newAcknowledgement",
".",
"ParseOptions",
"(",
")",
"\n",
"if",
"dhcp4",
".",
"MessageType",
"(",
"newAcknowledgementOptions",
"[",
"dhcp4",
".",
"OptionDHCPMessageType",
"]",
"[",
"0",
"]",
")",
"!=",
"dhcp4",
".",
"ACK",
"{",
"return",
"false",
",",
"newAcknowledgement",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"newAcknowledgement",
",",
"nil",
"\n",
"}"
] | //Renew a lease backed on the Acknowledgement Packet.
//Returns Sucessfull, The AcknoledgementPacket, Any Errors | [
"Renew",
"a",
"lease",
"backed",
"on",
"the",
"Acknowledgement",
"Packet",
".",
"Returns",
"Sucessfull",
"The",
"AcknoledgementPacket",
"Any",
"Errors"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L387-L407 |
14,152 | d2g/dhcp4client | client.go | Release | func (c *Client) Release(acknowledgement dhcp4.Packet) error {
release := c.ReleasePacket(&acknowledgement)
release.PadToMinSize()
return c.SendPacket(release)
} | go | func (c *Client) Release(acknowledgement dhcp4.Packet) error {
release := c.ReleasePacket(&acknowledgement)
release.PadToMinSize()
return c.SendPacket(release)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Release",
"(",
"acknowledgement",
"dhcp4",
".",
"Packet",
")",
"error",
"{",
"release",
":=",
"c",
".",
"ReleasePacket",
"(",
"&",
"acknowledgement",
")",
"\n",
"release",
".",
"PadToMinSize",
"(",
")",
"\n\n",
"return",
"c",
".",
"SendPacket",
"(",
"release",
")",
"\n",
"}"
] | //Release a lease backed on the Acknowledgement Packet.
//Returns Any Errors | [
"Release",
"a",
"lease",
"backed",
"on",
"the",
"Acknowledgement",
"Packet",
".",
"Returns",
"Any",
"Errors"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/client.go#L411-L416 |
14,153 | d2g/dhcp4client | pktsock_linux.go | chksum | func chksum(p []byte, csum []byte) {
cklen := len(p)
s := uint32(0)
for i := 0; i < (cklen - 1); i += 2 {
s += uint32(p[i+1])<<8 | uint32(p[i])
}
if cklen&1 == 1 {
s += uint32(p[cklen-1])
}
s = (s >> 16) + (s & 0xffff)
s = s + (s >> 16)
s = ^s
csum[0] = uint8(s & 0xff)
csum[1] = uint8(s >> 8)
} | go | func chksum(p []byte, csum []byte) {
cklen := len(p)
s := uint32(0)
for i := 0; i < (cklen - 1); i += 2 {
s += uint32(p[i+1])<<8 | uint32(p[i])
}
if cklen&1 == 1 {
s += uint32(p[cklen-1])
}
s = (s >> 16) + (s & 0xffff)
s = s + (s >> 16)
s = ^s
csum[0] = uint8(s & 0xff)
csum[1] = uint8(s >> 8)
} | [
"func",
"chksum",
"(",
"p",
"[",
"]",
"byte",
",",
"csum",
"[",
"]",
"byte",
")",
"{",
"cklen",
":=",
"len",
"(",
"p",
")",
"\n",
"s",
":=",
"uint32",
"(",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"(",
"cklen",
"-",
"1",
")",
";",
"i",
"+=",
"2",
"{",
"s",
"+=",
"uint32",
"(",
"p",
"[",
"i",
"+",
"1",
"]",
")",
"<<",
"8",
"|",
"uint32",
"(",
"p",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"if",
"cklen",
"&",
"1",
"==",
"1",
"{",
"s",
"+=",
"uint32",
"(",
"p",
"[",
"cklen",
"-",
"1",
"]",
")",
"\n",
"}",
"\n",
"s",
"=",
"(",
"s",
">>",
"16",
")",
"+",
"(",
"s",
"&",
"0xffff",
")",
"\n",
"s",
"=",
"s",
"+",
"(",
"s",
">>",
"16",
")",
"\n",
"s",
"=",
"^",
"s",
"\n\n",
"csum",
"[",
"0",
"]",
"=",
"uint8",
"(",
"s",
"&",
"0xff",
")",
"\n",
"csum",
"[",
"1",
"]",
"=",
"uint8",
"(",
"s",
">>",
"8",
")",
"\n",
"}"
] | // compute's 1's complement checksum | [
"compute",
"s",
"1",
"s",
"complement",
"checksum"
] | ef524ad9cb076fe235ecc3c55913ef8445fa35fa | https://github.com/d2g/dhcp4client/blob/ef524ad9cb076fe235ecc3c55913ef8445fa35fa/pktsock_linux.go#L98-L113 |
14,154 | googlearchive/go-gcm | cmd/gcm-logger/gcm-logger.go | onMessage | func onMessage(cm gcm.CcsMessage) error {
toylog.Infoln("Message, from:", cm.From, "with:", cm.Data)
// Echo the message with a tag.
cm.Data["echoed"] = true
m := gcm.HttpMessage{To: cm.From, Data: cm.Data}
r, err := gcm.SendHttp(*serverKey, m)
if err != nil {
toylog.Errorln("Error sending message.", err)
return err
}
toylog.Infof("Sent message. %+v -> %+v", m, r)
return nil
} | go | func onMessage(cm gcm.CcsMessage) error {
toylog.Infoln("Message, from:", cm.From, "with:", cm.Data)
// Echo the message with a tag.
cm.Data["echoed"] = true
m := gcm.HttpMessage{To: cm.From, Data: cm.Data}
r, err := gcm.SendHttp(*serverKey, m)
if err != nil {
toylog.Errorln("Error sending message.", err)
return err
}
toylog.Infof("Sent message. %+v -> %+v", m, r)
return nil
} | [
"func",
"onMessage",
"(",
"cm",
"gcm",
".",
"CcsMessage",
")",
"error",
"{",
"toylog",
".",
"Infoln",
"(",
"\"",
"\"",
",",
"cm",
".",
"From",
",",
"\"",
"\"",
",",
"cm",
".",
"Data",
")",
"\n",
"// Echo the message with a tag.",
"cm",
".",
"Data",
"[",
"\"",
"\"",
"]",
"=",
"true",
"\n",
"m",
":=",
"gcm",
".",
"HttpMessage",
"{",
"To",
":",
"cm",
".",
"From",
",",
"Data",
":",
"cm",
".",
"Data",
"}",
"\n",
"r",
",",
"err",
":=",
"gcm",
".",
"SendHttp",
"(",
"*",
"serverKey",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"toylog",
".",
"Errorln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"toylog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"m",
",",
"r",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // onMessage receives messages, logs them, and echoes a response. | [
"onMessage",
"receives",
"messages",
"logs",
"them",
"and",
"echoes",
"a",
"response",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/cmd/gcm-logger/gcm-logger.go#L16-L28 |
14,155 | googlearchive/go-gcm | gcm.go | send | func (c *httpGcmClient) send(apiKey string, m HttpMessage) (*HttpResponse, error) {
bs, err := json.Marshal(m)
if err != nil {
return nil, fmt.Errorf("error marshalling message>%v", err)
}
debug("sending", string(bs))
req, err := http.NewRequest("POST", c.GcmURL, bytes.NewReader(bs))
if err != nil {
return nil, fmt.Errorf("error creating request>%v", err)
}
req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json")
req.Header.Add(http.CanonicalHeaderKey("Authorization"), authHeader(apiKey))
httpResp, err := c.HttpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error sending request to HTTP connection server>%v", err)
}
gcmResp := &HttpResponse{}
body, err := ioutil.ReadAll(httpResp.Body)
defer httpResp.Body.Close()
if err != nil {
return gcmResp, fmt.Errorf("error reading http response body>%v", err)
}
debug("received body", string(body))
err = json.Unmarshal(body, &gcmResp)
if err != nil {
return gcmResp, fmt.Errorf("error unmarshaling json from body: %v", err)
}
// TODO(silvano): this is assuming that the header contains seconds instead of a date, need to check
c.retryAfter = httpResp.Header.Get(http.CanonicalHeaderKey("Retry-After"))
return gcmResp, nil
} | go | func (c *httpGcmClient) send(apiKey string, m HttpMessage) (*HttpResponse, error) {
bs, err := json.Marshal(m)
if err != nil {
return nil, fmt.Errorf("error marshalling message>%v", err)
}
debug("sending", string(bs))
req, err := http.NewRequest("POST", c.GcmURL, bytes.NewReader(bs))
if err != nil {
return nil, fmt.Errorf("error creating request>%v", err)
}
req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json")
req.Header.Add(http.CanonicalHeaderKey("Authorization"), authHeader(apiKey))
httpResp, err := c.HttpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error sending request to HTTP connection server>%v", err)
}
gcmResp := &HttpResponse{}
body, err := ioutil.ReadAll(httpResp.Body)
defer httpResp.Body.Close()
if err != nil {
return gcmResp, fmt.Errorf("error reading http response body>%v", err)
}
debug("received body", string(body))
err = json.Unmarshal(body, &gcmResp)
if err != nil {
return gcmResp, fmt.Errorf("error unmarshaling json from body: %v", err)
}
// TODO(silvano): this is assuming that the header contains seconds instead of a date, need to check
c.retryAfter = httpResp.Header.Get(http.CanonicalHeaderKey("Retry-After"))
return gcmResp, nil
} | [
"func",
"(",
"c",
"*",
"httpGcmClient",
")",
"send",
"(",
"apiKey",
"string",
",",
"m",
"HttpMessage",
")",
"(",
"*",
"HttpResponse",
",",
"error",
")",
"{",
"bs",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"debug",
"(",
"\"",
"\"",
",",
"string",
"(",
"bs",
")",
")",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"c",
".",
"GcmURL",
",",
"bytes",
".",
"NewReader",
"(",
"bs",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"http",
".",
"CanonicalHeaderKey",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"http",
".",
"CanonicalHeaderKey",
"(",
"\"",
"\"",
")",
",",
"authHeader",
"(",
"apiKey",
")",
")",
"\n",
"httpResp",
",",
"err",
":=",
"c",
".",
"HttpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"gcmResp",
":=",
"&",
"HttpResponse",
"{",
"}",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"httpResp",
".",
"Body",
")",
"\n",
"defer",
"httpResp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gcmResp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"debug",
"(",
"\"",
"\"",
",",
"string",
"(",
"body",
")",
")",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"gcmResp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gcmResp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// TODO(silvano): this is assuming that the header contains seconds instead of a date, need to check",
"c",
".",
"retryAfter",
"=",
"httpResp",
".",
"Header",
".",
"Get",
"(",
"http",
".",
"CanonicalHeaderKey",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"gcmResp",
",",
"nil",
"\n",
"}"
] | // httpGcmClient implementation to send a message through GCM Http server. | [
"httpGcmClient",
"implementation",
"to",
"send",
"a",
"message",
"through",
"GCM",
"Http",
"server",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L180-L210 |
14,156 | googlearchive/go-gcm | gcm.go | retryMessage | func (c *xmppGcmClient) retryMessage(cm CcsMessage, h MessageHandler) {
c.messages.RLock()
defer c.messages.RUnlock()
if me, ok := c.messages.m[cm.MessageId]; ok {
if me.backoff.sendAnother() {
go func(m *messageLogEntry) {
m.backoff.wait()
c.send(*m.body)
}(me)
} else {
debug("Exponential backoff failed over limit for message: ", me)
go h(cm)
}
}
} | go | func (c *xmppGcmClient) retryMessage(cm CcsMessage, h MessageHandler) {
c.messages.RLock()
defer c.messages.RUnlock()
if me, ok := c.messages.m[cm.MessageId]; ok {
if me.backoff.sendAnother() {
go func(m *messageLogEntry) {
m.backoff.wait()
c.send(*m.body)
}(me)
} else {
debug("Exponential backoff failed over limit for message: ", me)
go h(cm)
}
}
} | [
"func",
"(",
"c",
"*",
"xmppGcmClient",
")",
"retryMessage",
"(",
"cm",
"CcsMessage",
",",
"h",
"MessageHandler",
")",
"{",
"c",
".",
"messages",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"messages",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"me",
",",
"ok",
":=",
"c",
".",
"messages",
".",
"m",
"[",
"cm",
".",
"MessageId",
"]",
";",
"ok",
"{",
"if",
"me",
".",
"backoff",
".",
"sendAnother",
"(",
")",
"{",
"go",
"func",
"(",
"m",
"*",
"messageLogEntry",
")",
"{",
"m",
".",
"backoff",
".",
"wait",
"(",
")",
"\n",
"c",
".",
"send",
"(",
"*",
"m",
".",
"body",
")",
"\n",
"}",
"(",
"me",
")",
"\n",
"}",
"else",
"{",
"debug",
"(",
"\"",
"\"",
",",
"me",
")",
"\n",
"go",
"h",
"(",
"cm",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Retry sending a message with exponential backoff; if over limit, bubble up the failed message. | [
"Retry",
"sending",
"a",
"message",
"with",
"exponential",
"backoff",
";",
"if",
"over",
"limit",
"bubble",
"up",
"the",
"failed",
"message",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L405-L419 |
14,157 | googlearchive/go-gcm | gcm.go | newExponentialBackoff | func newExponentialBackoff() *exponentialBackoff {
b := &backoff.Backoff{
Min: DefaultMinBackoff,
Max: DefaultMaxBackoff,
Jitter: true,
}
return &exponentialBackoff{b: *b, currentDelay: b.Duration()}
} | go | func newExponentialBackoff() *exponentialBackoff {
b := &backoff.Backoff{
Min: DefaultMinBackoff,
Max: DefaultMaxBackoff,
Jitter: true,
}
return &exponentialBackoff{b: *b, currentDelay: b.Duration()}
} | [
"func",
"newExponentialBackoff",
"(",
")",
"*",
"exponentialBackoff",
"{",
"b",
":=",
"&",
"backoff",
".",
"Backoff",
"{",
"Min",
":",
"DefaultMinBackoff",
",",
"Max",
":",
"DefaultMaxBackoff",
",",
"Jitter",
":",
"true",
",",
"}",
"\n",
"return",
"&",
"exponentialBackoff",
"{",
"b",
":",
"*",
"b",
",",
"currentDelay",
":",
"b",
".",
"Duration",
"(",
")",
"}",
"\n",
"}"
] | // Factory method for exponential backoff, uses default values for Min and Max and
// adds Jitter. | [
"Factory",
"method",
"for",
"exponential",
"backoff",
"uses",
"default",
"values",
"for",
"Min",
"and",
"Max",
"and",
"adds",
"Jitter",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L436-L443 |
14,158 | googlearchive/go-gcm | gcm.go | setMin | func (eb *exponentialBackoff) setMin(min time.Duration) {
eb.b.Min = min
if (eb.currentDelay) < min {
eb.currentDelay = min
}
} | go | func (eb *exponentialBackoff) setMin(min time.Duration) {
eb.b.Min = min
if (eb.currentDelay) < min {
eb.currentDelay = min
}
} | [
"func",
"(",
"eb",
"*",
"exponentialBackoff",
")",
"setMin",
"(",
"min",
"time",
".",
"Duration",
")",
"{",
"eb",
".",
"b",
".",
"Min",
"=",
"min",
"\n",
"if",
"(",
"eb",
".",
"currentDelay",
")",
"<",
"min",
"{",
"eb",
".",
"currentDelay",
"=",
"min",
"\n",
"}",
"\n",
"}"
] | // Set the minumim delay for backoff | [
"Set",
"the",
"minumim",
"delay",
"for",
"backoff"
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L451-L456 |
14,159 | googlearchive/go-gcm | gcm.go | wait | func (eb exponentialBackoff) wait() {
time.Sleep(eb.currentDelay)
eb.currentDelay = eb.b.Duration()
} | go | func (eb exponentialBackoff) wait() {
time.Sleep(eb.currentDelay)
eb.currentDelay = eb.b.Duration()
} | [
"func",
"(",
"eb",
"exponentialBackoff",
")",
"wait",
"(",
")",
"{",
"time",
".",
"Sleep",
"(",
"eb",
".",
"currentDelay",
")",
"\n",
"eb",
".",
"currentDelay",
"=",
"eb",
".",
"b",
".",
"Duration",
"(",
")",
"\n",
"}"
] | // Wait for the current value of backoff | [
"Wait",
"for",
"the",
"current",
"value",
"of",
"backoff"
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L459-L462 |
14,160 | googlearchive/go-gcm | gcm.go | SendHttp | func SendHttp(apiKey string, m HttpMessage) (*HttpResponse, error) {
c := &httpGcmClient{httpAddress, &http.Client{}, "0"}
b := newExponentialBackoff()
return sendHttp(apiKey, m, c, b)
} | go | func SendHttp(apiKey string, m HttpMessage) (*HttpResponse, error) {
c := &httpGcmClient{httpAddress, &http.Client{}, "0"}
b := newExponentialBackoff()
return sendHttp(apiKey, m, c, b)
} | [
"func",
"SendHttp",
"(",
"apiKey",
"string",
",",
"m",
"HttpMessage",
")",
"(",
"*",
"HttpResponse",
",",
"error",
")",
"{",
"c",
":=",
"&",
"httpGcmClient",
"{",
"httpAddress",
",",
"&",
"http",
".",
"Client",
"{",
"}",
",",
"\"",
"\"",
"}",
"\n",
"b",
":=",
"newExponentialBackoff",
"(",
")",
"\n",
"return",
"sendHttp",
"(",
"apiKey",
",",
"m",
",",
"c",
",",
"b",
")",
"\n",
"}"
] | // Send a message using the HTTP GCM connection server. | [
"Send",
"a",
"message",
"using",
"the",
"HTTP",
"GCM",
"connection",
"server",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L465-L469 |
14,161 | googlearchive/go-gcm | gcm.go | sendHttp | func sendHttp(apiKey string, m HttpMessage, c httpClient, b backoffProvider) (*HttpResponse, error) {
// TODO(silvano): check this with responses for topic/notification group
gcmResp := &HttpResponse{}
var multicastId int
targets, err := messageTargetAsStringsArray(m)
if err != nil {
return gcmResp, fmt.Errorf("error extracting target from message: %v", err)
}
// make a copy of the targets to keep track of results during retries
localTo := make([]string, len(targets))
copy(localTo, targets)
resultsState := &multicastResultsState{}
for b.sendAnother() {
gcmResp, err = c.send(apiKey, m)
if err != nil {
return gcmResp, fmt.Errorf("error sending request to GCM HTTP server: %v", err)
}
if len(gcmResp.Results) > 0 {
doRetry, toRetry, err := checkResults(gcmResp.Results, localTo, *resultsState)
multicastId = gcmResp.MulticastId
if err != nil {
return gcmResp, fmt.Errorf("error checking GCM results: %v", err)
}
if doRetry {
retryAfter, err := time.ParseDuration(c.getRetryAfter())
if err != nil {
b.setMin(retryAfter)
}
localTo = make([]string, len(toRetry))
copy(localTo, toRetry)
if m.RegistrationIds != nil {
m.RegistrationIds = toRetry
}
b.wait()
continue
} else {
break
}
} else {
break
}
}
// if it was multicast, reconstruct response in case there have been retries
if len(targets) > 1 {
gcmResp = buildRespForMulticast(targets, *resultsState, multicastId)
}
return gcmResp, nil
} | go | func sendHttp(apiKey string, m HttpMessage, c httpClient, b backoffProvider) (*HttpResponse, error) {
// TODO(silvano): check this with responses for topic/notification group
gcmResp := &HttpResponse{}
var multicastId int
targets, err := messageTargetAsStringsArray(m)
if err != nil {
return gcmResp, fmt.Errorf("error extracting target from message: %v", err)
}
// make a copy of the targets to keep track of results during retries
localTo := make([]string, len(targets))
copy(localTo, targets)
resultsState := &multicastResultsState{}
for b.sendAnother() {
gcmResp, err = c.send(apiKey, m)
if err != nil {
return gcmResp, fmt.Errorf("error sending request to GCM HTTP server: %v", err)
}
if len(gcmResp.Results) > 0 {
doRetry, toRetry, err := checkResults(gcmResp.Results, localTo, *resultsState)
multicastId = gcmResp.MulticastId
if err != nil {
return gcmResp, fmt.Errorf("error checking GCM results: %v", err)
}
if doRetry {
retryAfter, err := time.ParseDuration(c.getRetryAfter())
if err != nil {
b.setMin(retryAfter)
}
localTo = make([]string, len(toRetry))
copy(localTo, toRetry)
if m.RegistrationIds != nil {
m.RegistrationIds = toRetry
}
b.wait()
continue
} else {
break
}
} else {
break
}
}
// if it was multicast, reconstruct response in case there have been retries
if len(targets) > 1 {
gcmResp = buildRespForMulticast(targets, *resultsState, multicastId)
}
return gcmResp, nil
} | [
"func",
"sendHttp",
"(",
"apiKey",
"string",
",",
"m",
"HttpMessage",
",",
"c",
"httpClient",
",",
"b",
"backoffProvider",
")",
"(",
"*",
"HttpResponse",
",",
"error",
")",
"{",
"// TODO(silvano): check this with responses for topic/notification group",
"gcmResp",
":=",
"&",
"HttpResponse",
"{",
"}",
"\n",
"var",
"multicastId",
"int",
"\n",
"targets",
",",
"err",
":=",
"messageTargetAsStringsArray",
"(",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gcmResp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// make a copy of the targets to keep track of results during retries",
"localTo",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"targets",
")",
")",
"\n",
"copy",
"(",
"localTo",
",",
"targets",
")",
"\n",
"resultsState",
":=",
"&",
"multicastResultsState",
"{",
"}",
"\n",
"for",
"b",
".",
"sendAnother",
"(",
")",
"{",
"gcmResp",
",",
"err",
"=",
"c",
".",
"send",
"(",
"apiKey",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gcmResp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"gcmResp",
".",
"Results",
")",
">",
"0",
"{",
"doRetry",
",",
"toRetry",
",",
"err",
":=",
"checkResults",
"(",
"gcmResp",
".",
"Results",
",",
"localTo",
",",
"*",
"resultsState",
")",
"\n",
"multicastId",
"=",
"gcmResp",
".",
"MulticastId",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gcmResp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"doRetry",
"{",
"retryAfter",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"c",
".",
"getRetryAfter",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"setMin",
"(",
"retryAfter",
")",
"\n",
"}",
"\n",
"localTo",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"toRetry",
")",
")",
"\n",
"copy",
"(",
"localTo",
",",
"toRetry",
")",
"\n",
"if",
"m",
".",
"RegistrationIds",
"!=",
"nil",
"{",
"m",
".",
"RegistrationIds",
"=",
"toRetry",
"\n",
"}",
"\n",
"b",
".",
"wait",
"(",
")",
"\n",
"continue",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"// if it was multicast, reconstruct response in case there have been retries",
"if",
"len",
"(",
"targets",
")",
">",
"1",
"{",
"gcmResp",
"=",
"buildRespForMulticast",
"(",
"targets",
",",
"*",
"resultsState",
",",
"multicastId",
")",
"\n",
"}",
"\n",
"return",
"gcmResp",
",",
"nil",
"\n",
"}"
] | // sendHttp sends an http message using exponential backoff, handling multicast replies. | [
"sendHttp",
"sends",
"an",
"http",
"message",
"using",
"exponential",
"backoff",
"handling",
"multicast",
"replies",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L472-L519 |
14,162 | googlearchive/go-gcm | gcm.go | buildRespForMulticast | func buildRespForMulticast(to []string, mrs multicastResultsState, mid int) *HttpResponse {
resp := &HttpResponse{}
resp.MulticastId = mid
resp.Results = make([]Result, len(to))
for i, regId := range to {
result, ok := mrs[regId]
if !ok {
continue
}
resp.Results[i] = *result
if result.MessageId != "" {
resp.Success++
} else if result.Error != "" {
resp.Failure++
}
if result.RegistrationId != "" {
resp.CanonicalIds++
}
}
return resp
} | go | func buildRespForMulticast(to []string, mrs multicastResultsState, mid int) *HttpResponse {
resp := &HttpResponse{}
resp.MulticastId = mid
resp.Results = make([]Result, len(to))
for i, regId := range to {
result, ok := mrs[regId]
if !ok {
continue
}
resp.Results[i] = *result
if result.MessageId != "" {
resp.Success++
} else if result.Error != "" {
resp.Failure++
}
if result.RegistrationId != "" {
resp.CanonicalIds++
}
}
return resp
} | [
"func",
"buildRespForMulticast",
"(",
"to",
"[",
"]",
"string",
",",
"mrs",
"multicastResultsState",
",",
"mid",
"int",
")",
"*",
"HttpResponse",
"{",
"resp",
":=",
"&",
"HttpResponse",
"{",
"}",
"\n",
"resp",
".",
"MulticastId",
"=",
"mid",
"\n",
"resp",
".",
"Results",
"=",
"make",
"(",
"[",
"]",
"Result",
",",
"len",
"(",
"to",
")",
")",
"\n",
"for",
"i",
",",
"regId",
":=",
"range",
"to",
"{",
"result",
",",
"ok",
":=",
"mrs",
"[",
"regId",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"resp",
".",
"Results",
"[",
"i",
"]",
"=",
"*",
"result",
"\n",
"if",
"result",
".",
"MessageId",
"!=",
"\"",
"\"",
"{",
"resp",
".",
"Success",
"++",
"\n",
"}",
"else",
"if",
"result",
".",
"Error",
"!=",
"\"",
"\"",
"{",
"resp",
".",
"Failure",
"++",
"\n",
"}",
"\n",
"if",
"result",
".",
"RegistrationId",
"!=",
"\"",
"\"",
"{",
"resp",
".",
"CanonicalIds",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"resp",
"\n",
"}"
] | // Builds the final response for a multicast message, in case there have been retries for
// subsets of the original recipients. | [
"Builds",
"the",
"final",
"response",
"for",
"a",
"multicast",
"message",
"in",
"case",
"there",
"have",
"been",
"retries",
"for",
"subsets",
"of",
"the",
"original",
"recipients",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L523-L543 |
14,163 | googlearchive/go-gcm | gcm.go | messageTargetAsStringsArray | func messageTargetAsStringsArray(m HttpMessage) ([]string, error) {
if m.RegistrationIds != nil {
return m.RegistrationIds, nil
} else if m.To != "" {
target := []string{m.To}
return target, nil
}
target := []string{}
return target, fmt.Errorf("can't find any valid target field in message.")
} | go | func messageTargetAsStringsArray(m HttpMessage) ([]string, error) {
if m.RegistrationIds != nil {
return m.RegistrationIds, nil
} else if m.To != "" {
target := []string{m.To}
return target, nil
}
target := []string{}
return target, fmt.Errorf("can't find any valid target field in message.")
} | [
"func",
"messageTargetAsStringsArray",
"(",
"m",
"HttpMessage",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"m",
".",
"RegistrationIds",
"!=",
"nil",
"{",
"return",
"m",
".",
"RegistrationIds",
",",
"nil",
"\n",
"}",
"else",
"if",
"m",
".",
"To",
"!=",
"\"",
"\"",
"{",
"target",
":=",
"[",
"]",
"string",
"{",
"m",
".",
"To",
"}",
"\n",
"return",
"target",
",",
"nil",
"\n",
"}",
"\n",
"target",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"return",
"target",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Transform the recipient in an array of strings if needed. | [
"Transform",
"the",
"recipient",
"in",
"an",
"array",
"of",
"strings",
"if",
"needed",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L546-L555 |
14,164 | googlearchive/go-gcm | gcm.go | checkResults | func checkResults(gcmResults []Result, recipients []string, resultsState multicastResultsState) (doRetry bool, toRetry []string, err error) {
doRetry = false
toRetry = []string{}
for i := 0; i < len(gcmResults); i++ {
result := gcmResults[i]
regId := recipients[i]
resultsState[regId] = &result
if result.Error != "" {
if retryableErrors[result.Error] {
toRetry = append(toRetry, regId)
if doRetry == false {
doRetry = true
}
}
}
}
return doRetry, toRetry, nil
} | go | func checkResults(gcmResults []Result, recipients []string, resultsState multicastResultsState) (doRetry bool, toRetry []string, err error) {
doRetry = false
toRetry = []string{}
for i := 0; i < len(gcmResults); i++ {
result := gcmResults[i]
regId := recipients[i]
resultsState[regId] = &result
if result.Error != "" {
if retryableErrors[result.Error] {
toRetry = append(toRetry, regId)
if doRetry == false {
doRetry = true
}
}
}
}
return doRetry, toRetry, nil
} | [
"func",
"checkResults",
"(",
"gcmResults",
"[",
"]",
"Result",
",",
"recipients",
"[",
"]",
"string",
",",
"resultsState",
"multicastResultsState",
")",
"(",
"doRetry",
"bool",
",",
"toRetry",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"doRetry",
"=",
"false",
"\n",
"toRetry",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"gcmResults",
")",
";",
"i",
"++",
"{",
"result",
":=",
"gcmResults",
"[",
"i",
"]",
"\n",
"regId",
":=",
"recipients",
"[",
"i",
"]",
"\n",
"resultsState",
"[",
"regId",
"]",
"=",
"&",
"result",
"\n",
"if",
"result",
".",
"Error",
"!=",
"\"",
"\"",
"{",
"if",
"retryableErrors",
"[",
"result",
".",
"Error",
"]",
"{",
"toRetry",
"=",
"append",
"(",
"toRetry",
",",
"regId",
")",
"\n",
"if",
"doRetry",
"==",
"false",
"{",
"doRetry",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"doRetry",
",",
"toRetry",
",",
"nil",
"\n",
"}"
] | // For a multicast send, determines which errors can be retried. | [
"For",
"a",
"multicast",
"send",
"determines",
"which",
"errors",
"can",
"be",
"retried",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L558-L575 |
14,165 | googlearchive/go-gcm | gcm.go | SendXmpp | func SendXmpp(senderId, apiKey string, m XmppMessage) (string, int, error) {
c, err := newXmppGcmClient(senderId, apiKey)
if err != nil {
return "", 0, fmt.Errorf("error creating xmpp client>%v", err)
}
return c.send(m)
} | go | func SendXmpp(senderId, apiKey string, m XmppMessage) (string, int, error) {
c, err := newXmppGcmClient(senderId, apiKey)
if err != nil {
return "", 0, fmt.Errorf("error creating xmpp client>%v", err)
}
return c.send(m)
} | [
"func",
"SendXmpp",
"(",
"senderId",
",",
"apiKey",
"string",
",",
"m",
"XmppMessage",
")",
"(",
"string",
",",
"int",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"newXmppGcmClient",
"(",
"senderId",
",",
"apiKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"send",
"(",
"m",
")",
"\n",
"}"
] | // SendXmpp sends a message using the XMPP GCM connection server. | [
"SendXmpp",
"sends",
"a",
"message",
"using",
"the",
"XMPP",
"GCM",
"connection",
"server",
"."
] | f387343038b10aec84c22f3809773a30630c12e8 | https://github.com/googlearchive/go-gcm/blob/f387343038b10aec84c22f3809773a30630c12e8/gcm.go#L578-L584 |
14,166 | dnsimple/dnsimple-go | dnsimple/oauth.go | ExchangeAuthorizationForToken | func (s *OauthService) ExchangeAuthorizationForToken(authorization *ExchangeAuthorizationRequest) (*AccessToken, error) {
path := versioned("/oauth/access_token")
req, err := s.client.NewRequest("POST", path, authorization)
if err != nil {
return nil, err
}
resp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
errorResponse := &ExchangeAuthorizationError{}
errorResponse.HttpResponse = resp
json.NewDecoder(resp.Body).Decode(errorResponse)
return nil, errorResponse
}
accessToken := &AccessToken{}
err = json.NewDecoder(resp.Body).Decode(accessToken)
return accessToken, err
} | go | func (s *OauthService) ExchangeAuthorizationForToken(authorization *ExchangeAuthorizationRequest) (*AccessToken, error) {
path := versioned("/oauth/access_token")
req, err := s.client.NewRequest("POST", path, authorization)
if err != nil {
return nil, err
}
resp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
errorResponse := &ExchangeAuthorizationError{}
errorResponse.HttpResponse = resp
json.NewDecoder(resp.Body).Decode(errorResponse)
return nil, errorResponse
}
accessToken := &AccessToken{}
err = json.NewDecoder(resp.Body).Decode(accessToken)
return accessToken, err
} | [
"func",
"(",
"s",
"*",
"OauthService",
")",
"ExchangeAuthorizationForToken",
"(",
"authorization",
"*",
"ExchangeAuthorizationRequest",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"path",
":=",
"versioned",
"(",
"\"",
"\"",
")",
"\n\n",
"req",
",",
"err",
":=",
"s",
".",
"client",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"path",
",",
"authorization",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"s",
".",
"client",
".",
"httpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"errorResponse",
":=",
"&",
"ExchangeAuthorizationError",
"{",
"}",
"\n",
"errorResponse",
".",
"HttpResponse",
"=",
"resp",
"\n",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"errorResponse",
")",
"\n",
"return",
"nil",
",",
"errorResponse",
"\n",
"}",
"\n\n",
"accessToken",
":=",
"&",
"AccessToken",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"accessToken",
")",
"\n\n",
"return",
"accessToken",
",",
"err",
"\n",
"}"
] | // ExchangeAuthorizationForToken exchanges the short-lived authorization code for an access token
// you can use to authenticate your API calls. | [
"ExchangeAuthorizationForToken",
"exchanges",
"the",
"short",
"-",
"lived",
"authorization",
"code",
"for",
"an",
"access",
"token",
"you",
"can",
"use",
"to",
"authenticate",
"your",
"API",
"calls",
"."
] | 7f63b6276b126cfe51ee03cb5fa41c87267ed2c7 | https://github.com/dnsimple/dnsimple-go/blob/7f63b6276b126cfe51ee03cb5fa41c87267ed2c7/dnsimple/oauth.go#L67-L92 |
14,167 | dnsimple/dnsimple-go | dnsimple/oauth.go | AuthorizeURL | func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string {
uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1))
uri.Path = "/oauth/authorize"
query := uri.Query()
query.Add("client_id", clientID)
query.Add("response_type", "code")
uri.RawQuery = query.Encode()
path, _ := addURLQueryOptions(uri.String(), options)
return path
} | go | func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string {
uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1))
uri.Path = "/oauth/authorize"
query := uri.Query()
query.Add("client_id", clientID)
query.Add("response_type", "code")
uri.RawQuery = query.Encode()
path, _ := addURLQueryOptions(uri.String(), options)
return path
} | [
"func",
"(",
"s",
"*",
"OauthService",
")",
"AuthorizeURL",
"(",
"clientID",
"string",
",",
"options",
"*",
"AuthorizationOptions",
")",
"string",
"{",
"uri",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"strings",
".",
"Replace",
"(",
"s",
".",
"client",
".",
"BaseURL",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"1",
")",
")",
"\n",
"uri",
".",
"Path",
"=",
"\"",
"\"",
"\n",
"query",
":=",
"uri",
".",
"Query",
"(",
")",
"\n",
"query",
".",
"Add",
"(",
"\"",
"\"",
",",
"clientID",
")",
"\n",
"query",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"uri",
".",
"RawQuery",
"=",
"query",
".",
"Encode",
"(",
")",
"\n\n",
"path",
",",
"_",
":=",
"addURLQueryOptions",
"(",
"uri",
".",
"String",
"(",
")",
",",
"options",
")",
"\n",
"return",
"path",
"\n",
"}"
] | // AuthorizeURL generates the URL to authorize an user for an application via the OAuth2 flow. | [
"AuthorizeURL",
"generates",
"the",
"URL",
"to",
"authorize",
"an",
"user",
"for",
"an",
"application",
"via",
"the",
"OAuth2",
"flow",
"."
] | 7f63b6276b126cfe51ee03cb5fa41c87267ed2c7 | https://github.com/dnsimple/dnsimple-go/blob/7f63b6276b126cfe51ee03cb5fa41c87267ed2c7/dnsimple/oauth.go#L103-L113 |
14,168 | dnsimple/dnsimple-go | dnsimple/webhook/webhook.go | Parse | func Parse(payload []byte) (Event, error) {
action, err := ParseName(payload)
if err != nil {
return nil, err
}
return switchEvent(action, payload)
} | go | func Parse(payload []byte) (Event, error) {
action, err := ParseName(payload)
if err != nil {
return nil, err
}
return switchEvent(action, payload)
} | [
"func",
"Parse",
"(",
"payload",
"[",
"]",
"byte",
")",
"(",
"Event",
",",
"error",
")",
"{",
"action",
",",
"err",
":=",
"ParseName",
"(",
"payload",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"switchEvent",
"(",
"action",
",",
"payload",
")",
"\n",
"}"
] | // Parse takes a payload and attempts to deserialize the payload into an event type
// that matches the event action in the payload. If no direct match is found, then a DefaultEvent is returned.
//
// Parse returns type is an Event interface. Therefore, you must perform typecasting
// to access any event-specific field. | [
"Parse",
"takes",
"a",
"payload",
"and",
"attempts",
"to",
"deserialize",
"the",
"payload",
"into",
"an",
"event",
"type",
"that",
"matches",
"the",
"event",
"action",
"in",
"the",
"payload",
".",
"If",
"no",
"direct",
"match",
"is",
"found",
"then",
"a",
"DefaultEvent",
"is",
"returned",
".",
"Parse",
"returns",
"type",
"is",
"an",
"Event",
"interface",
".",
"Therefore",
"you",
"must",
"perform",
"typecasting",
"to",
"access",
"any",
"event",
"-",
"specific",
"field",
"."
] | 7f63b6276b126cfe51ee03cb5fa41c87267ed2c7 | https://github.com/dnsimple/dnsimple-go/blob/7f63b6276b126cfe51ee03cb5fa41c87267ed2c7/dnsimple/webhook/webhook.go#L81-L88 |
14,169 | dnsimple/dnsimple-go | dnsimple/dnsimple.go | Do | func (c *Client) Do(req *http.Request, obj interface{}) (*http.Response, error) {
if c.Debug {
log.Printf("Executing request (%v): %#v", req.URL, req)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if c.Debug {
log.Printf("Response received: %#v", resp)
}
err = CheckResponse(resp)
if err != nil {
return resp, err
}
// If obj implements the io.Writer,
// the response body is decoded into v.
if obj != nil {
if w, ok := obj.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(obj)
}
}
return resp, err
} | go | func (c *Client) Do(req *http.Request, obj interface{}) (*http.Response, error) {
if c.Debug {
log.Printf("Executing request (%v): %#v", req.URL, req)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if c.Debug {
log.Printf("Response received: %#v", resp)
}
err = CheckResponse(resp)
if err != nil {
return resp, err
}
// If obj implements the io.Writer,
// the response body is decoded into v.
if obj != nil {
if w, ok := obj.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(obj)
}
}
return resp, err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Do",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"obj",
"interface",
"{",
"}",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"c",
".",
"Debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"req",
".",
"URL",
",",
"req",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"c",
".",
"httpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"c",
".",
"Debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"resp",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"CheckResponse",
"(",
"resp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resp",
",",
"err",
"\n",
"}",
"\n\n",
"// If obj implements the io.Writer,",
"// the response body is decoded into v.",
"if",
"obj",
"!=",
"nil",
"{",
"if",
"w",
",",
"ok",
":=",
"obj",
".",
"(",
"io",
".",
"Writer",
")",
";",
"ok",
"{",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"w",
",",
"resp",
".",
"Body",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"obj",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"resp",
",",
"err",
"\n",
"}"
] | // Do sends an API request and returns the API response.
//
// The API response is JSON decoded and stored in the value pointed by obj,
// or returned as an error if an API error has occurred.
// If obj implements the io.Writer interface, the raw response body will be written to obj,
// without attempting to decode it. | [
"Do",
"sends",
"an",
"API",
"request",
"and",
"returns",
"the",
"API",
"response",
".",
"The",
"API",
"response",
"is",
"JSON",
"decoded",
"and",
"stored",
"in",
"the",
"value",
"pointed",
"by",
"obj",
"or",
"returned",
"as",
"an",
"error",
"if",
"an",
"API",
"error",
"has",
"occurred",
".",
"If",
"obj",
"implements",
"the",
"io",
".",
"Writer",
"interface",
"the",
"raw",
"response",
"body",
"will",
"be",
"written",
"to",
"obj",
"without",
"attempting",
"to",
"decode",
"it",
"."
] | 7f63b6276b126cfe51ee03cb5fa41c87267ed2c7 | https://github.com/dnsimple/dnsimple-go/blob/7f63b6276b126cfe51ee03cb5fa41c87267ed2c7/dnsimple/dnsimple.go#L207-L238 |
14,170 | dnsimple/dnsimple-go | dnsimple/dnsimple.go | RateLimit | func (r *Response) RateLimit() int {
value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Limit"))
return value
} | go | func (r *Response) RateLimit() int {
value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Limit"))
return value
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"RateLimit",
"(",
")",
"int",
"{",
"value",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"r",
".",
"HttpResponse",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"value",
"\n",
"}"
] | // RateLimit returns the maximum amount of requests this account can send in an hour. | [
"RateLimit",
"returns",
"the",
"maximum",
"amount",
"of",
"requests",
"this",
"account",
"can",
"send",
"in",
"an",
"hour",
"."
] | 7f63b6276b126cfe51ee03cb5fa41c87267ed2c7 | https://github.com/dnsimple/dnsimple-go/blob/7f63b6276b126cfe51ee03cb5fa41c87267ed2c7/dnsimple/dnsimple.go#L250-L253 |
14,171 | dnsimple/dnsimple-go | dnsimple/dnsimple.go | RateLimitReset | func (r *Response) RateLimitReset() time.Time {
value, _ := strconv.ParseInt(r.HttpResponse.Header.Get("X-RateLimit-Reset"), 10, 64)
return time.Unix(value, 0)
} | go | func (r *Response) RateLimitReset() time.Time {
value, _ := strconv.ParseInt(r.HttpResponse.Header.Get("X-RateLimit-Reset"), 10, 64)
return time.Unix(value, 0)
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"RateLimitReset",
"(",
")",
"time",
".",
"Time",
"{",
"value",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"r",
".",
"HttpResponse",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"10",
",",
"64",
")",
"\n",
"return",
"time",
".",
"Unix",
"(",
"value",
",",
"0",
")",
"\n",
"}"
] | // RateLimitReset returns when the throttling window will be reset for this account. | [
"RateLimitReset",
"returns",
"when",
"the",
"throttling",
"window",
"will",
"be",
"reset",
"for",
"this",
"account",
"."
] | 7f63b6276b126cfe51ee03cb5fa41c87267ed2c7 | https://github.com/dnsimple/dnsimple-go/blob/7f63b6276b126cfe51ee03cb5fa41c87267ed2c7/dnsimple/dnsimple.go#L262-L265 |
14,172 | capnm/sysinfo | sysinfo.go | String | func (si SI) String() string {
// XXX: Is the copy of SI done atomic? Not sure.
// Without an outer lock this may print a junk.
return fmt.Sprintf("uptime\t\t%v\nload\t\t%2.2f %2.2f %2.2f\nprocs\t\t%d\n"+
"ram total\t%d kB\nram free\t%d kB\nram buffer\t%d kB\n"+
"swap total\t%d kB\nswap free\t%d kB",
//"high ram total\t%d kB\nhigh ram free\t%d kB\n"
si.Uptime, si.Loads[0], si.Loads[1], si.Loads[2], si.Procs,
si.TotalRam, si.FreeRam, si.BufferRam,
si.TotalSwap, si.FreeSwap,
// archaic si.TotalHighRam, si.FreeHighRam
)
} | go | func (si SI) String() string {
// XXX: Is the copy of SI done atomic? Not sure.
// Without an outer lock this may print a junk.
return fmt.Sprintf("uptime\t\t%v\nload\t\t%2.2f %2.2f %2.2f\nprocs\t\t%d\n"+
"ram total\t%d kB\nram free\t%d kB\nram buffer\t%d kB\n"+
"swap total\t%d kB\nswap free\t%d kB",
//"high ram total\t%d kB\nhigh ram free\t%d kB\n"
si.Uptime, si.Loads[0], si.Loads[1], si.Loads[2], si.Procs,
si.TotalRam, si.FreeRam, si.BufferRam,
si.TotalSwap, si.FreeSwap,
// archaic si.TotalHighRam, si.FreeHighRam
)
} | [
"func",
"(",
"si",
"SI",
")",
"String",
"(",
")",
"string",
"{",
"// XXX: Is the copy of SI done atomic? Not sure.",
"// Without an outer lock this may print a junk.",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\t",
"\\t",
"\\n",
"\\t",
"\\t",
"\\n",
"\\t",
"\\t",
"\\n",
"\"",
"+",
"\"",
"\\t",
"\\n",
"\\t",
"\\n",
"\\t",
"\\n",
"\"",
"+",
"\"",
"\\t",
"\\n",
"\\t",
"\"",
",",
"//\"high ram total\\t%d kB\\nhigh ram free\\t%d kB\\n\"",
"si",
".",
"Uptime",
",",
"si",
".",
"Loads",
"[",
"0",
"]",
",",
"si",
".",
"Loads",
"[",
"1",
"]",
",",
"si",
".",
"Loads",
"[",
"2",
"]",
",",
"si",
".",
"Procs",
",",
"si",
".",
"TotalRam",
",",
"si",
".",
"FreeRam",
",",
"si",
".",
"BufferRam",
",",
"si",
".",
"TotalSwap",
",",
"si",
".",
"FreeSwap",
",",
"// archaic si.TotalHighRam, si.FreeHighRam",
")",
"\n",
"}"
] | // Make the "fmt" Stringer interface happy. | [
"Make",
"the",
"fmt",
"Stringer",
"interface",
"happy",
"."
] | 5909a53897f32d198d9c81e3417f6d25ecfd2229 | https://github.com/capnm/sysinfo/blob/5909a53897f32d198d9c81e3417f6d25ecfd2229/sysinfo.go#L94-L106 |
14,173 | fuyufjh/splunk-hec-go | client.go | WaitForAcknowledgementWithContext | func (hec *Client) WaitForAcknowledgementWithContext(ctx context.Context) error {
// Make our own copy of the list of acknowledgement IDs and remove them
// from the client while we check them.
hec.ackMux.Lock()
ackIDs := hec.ackIDs
hec.ackIDs = nil
hec.ackMux.Unlock()
if len(ackIDs) == 0 {
return nil
}
endpoint := "/services/collector/ack?channel=" + hec.channel
for {
ackRequestData, _ := json.Marshal(acknowledgementRequest{Acks: ackIDs})
response, err := hec.makeRequest(ctx, endpoint, ackRequestData)
if err != nil {
// Put the remaining unacknowledged IDs back
hec.ackMux.Lock()
hec.ackIDs = append(hec.ackIDs, ackIDs...)
hec.ackMux.Unlock()
return err
}
for ackIDString, status := range response.Acks {
if status {
ackID, err := strconv.Atoi(ackIDString)
if err != nil {
return fmt.Errorf("could not convert ack ID to int: %v", err)
}
ackIDs = remove(ackIDs, ackID)
}
}
if len(ackIDs) == 0 {
break
}
// If the server did not indicate that all acknowledgements have been
// made, check again after a short delay.
select {
case <-time.After(retryWaitTime):
continue
case <-ctx.Done():
// Put the remaining unacknowledged IDs back
hec.ackMux.Lock()
hec.ackIDs = append(hec.ackIDs, ackIDs...)
hec.ackMux.Unlock()
return ctx.Err()
}
}
return nil
} | go | func (hec *Client) WaitForAcknowledgementWithContext(ctx context.Context) error {
// Make our own copy of the list of acknowledgement IDs and remove them
// from the client while we check them.
hec.ackMux.Lock()
ackIDs := hec.ackIDs
hec.ackIDs = nil
hec.ackMux.Unlock()
if len(ackIDs) == 0 {
return nil
}
endpoint := "/services/collector/ack?channel=" + hec.channel
for {
ackRequestData, _ := json.Marshal(acknowledgementRequest{Acks: ackIDs})
response, err := hec.makeRequest(ctx, endpoint, ackRequestData)
if err != nil {
// Put the remaining unacknowledged IDs back
hec.ackMux.Lock()
hec.ackIDs = append(hec.ackIDs, ackIDs...)
hec.ackMux.Unlock()
return err
}
for ackIDString, status := range response.Acks {
if status {
ackID, err := strconv.Atoi(ackIDString)
if err != nil {
return fmt.Errorf("could not convert ack ID to int: %v", err)
}
ackIDs = remove(ackIDs, ackID)
}
}
if len(ackIDs) == 0 {
break
}
// If the server did not indicate that all acknowledgements have been
// made, check again after a short delay.
select {
case <-time.After(retryWaitTime):
continue
case <-ctx.Done():
// Put the remaining unacknowledged IDs back
hec.ackMux.Lock()
hec.ackIDs = append(hec.ackIDs, ackIDs...)
hec.ackMux.Unlock()
return ctx.Err()
}
}
return nil
} | [
"func",
"(",
"hec",
"*",
"Client",
")",
"WaitForAcknowledgementWithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"// Make our own copy of the list of acknowledgement IDs and remove them",
"// from the client while we check them.",
"hec",
".",
"ackMux",
".",
"Lock",
"(",
")",
"\n",
"ackIDs",
":=",
"hec",
".",
"ackIDs",
"\n",
"hec",
".",
"ackIDs",
"=",
"nil",
"\n",
"hec",
".",
"ackMux",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"ackIDs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"endpoint",
":=",
"\"",
"\"",
"+",
"hec",
".",
"channel",
"\n\n",
"for",
"{",
"ackRequestData",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"acknowledgementRequest",
"{",
"Acks",
":",
"ackIDs",
"}",
")",
"\n\n",
"response",
",",
"err",
":=",
"hec",
".",
"makeRequest",
"(",
"ctx",
",",
"endpoint",
",",
"ackRequestData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Put the remaining unacknowledged IDs back",
"hec",
".",
"ackMux",
".",
"Lock",
"(",
")",
"\n",
"hec",
".",
"ackIDs",
"=",
"append",
"(",
"hec",
".",
"ackIDs",
",",
"ackIDs",
"...",
")",
"\n",
"hec",
".",
"ackMux",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"ackIDString",
",",
"status",
":=",
"range",
"response",
".",
"Acks",
"{",
"if",
"status",
"{",
"ackID",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"ackIDString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"ackIDs",
"=",
"remove",
"(",
"ackIDs",
",",
"ackID",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"ackIDs",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n\n",
"// If the server did not indicate that all acknowledgements have been",
"// made, check again after a short delay.",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"retryWaitTime",
")",
":",
"continue",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"// Put the remaining unacknowledged IDs back",
"hec",
".",
"ackMux",
".",
"Lock",
"(",
")",
"\n",
"hec",
".",
"ackIDs",
"=",
"append",
"(",
"hec",
".",
"ackIDs",
",",
"ackIDs",
"...",
")",
"\n",
"hec",
".",
"ackMux",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // WaitForAcknowledgementWithContext blocks until the Splunk indexer has
// acknowledged that all previously submitted data has been successfully
// indexed or if the provided context is cancelled. This requires the HEC token
// configuration in Splunk to have indexer acknowledgement enabled. | [
"WaitForAcknowledgementWithContext",
"blocks",
"until",
"the",
"Splunk",
"indexer",
"has",
"acknowledged",
"that",
"all",
"previously",
"submitted",
"data",
"has",
"been",
"successfully",
"indexed",
"or",
"if",
"the",
"provided",
"context",
"is",
"cancelled",
".",
"This",
"requires",
"the",
"HEC",
"token",
"configuration",
"in",
"Splunk",
"to",
"have",
"indexer",
"acknowledgement",
"enabled",
"."
] | 10df423a9f3633e5395eaf8132da3a257251b189 | https://github.com/fuyufjh/splunk-hec-go/blob/10df423a9f3633e5395eaf8132da3a257251b189/client.go#L187-L243 |
14,174 | fuyufjh/splunk-hec-go | client.go | WaitForAcknowledgement | func (hec *Client) WaitForAcknowledgement() error {
ctx, cancel := context.WithTimeout(context.Background(), defaultAcknowledgementTimeout)
defer cancel()
return hec.WaitForAcknowledgementWithContext(ctx)
} | go | func (hec *Client) WaitForAcknowledgement() error {
ctx, cancel := context.WithTimeout(context.Background(), defaultAcknowledgementTimeout)
defer cancel()
return hec.WaitForAcknowledgementWithContext(ctx)
} | [
"func",
"(",
"hec",
"*",
"Client",
")",
"WaitForAcknowledgement",
"(",
")",
"error",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"defaultAcknowledgementTimeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"return",
"hec",
".",
"WaitForAcknowledgementWithContext",
"(",
"ctx",
")",
"\n",
"}"
] | // WaitForAcknowledgement blocks until the Splunk indexer has acknowledged
// that all previously submitted data has been successfully indexed or if the
// default acknowledgement timeout is reached. This requires the HEC token
// configuration in Splunk to have indexer acknowledgement enabled. | [
"WaitForAcknowledgement",
"blocks",
"until",
"the",
"Splunk",
"indexer",
"has",
"acknowledged",
"that",
"all",
"previously",
"submitted",
"data",
"has",
"been",
"successfully",
"indexed",
"or",
"if",
"the",
"default",
"acknowledgement",
"timeout",
"is",
"reached",
".",
"This",
"requires",
"the",
"HEC",
"token",
"configuration",
"in",
"Splunk",
"to",
"have",
"indexer",
"acknowledgement",
"enabled",
"."
] | 10df423a9f3633e5395eaf8132da3a257251b189 | https://github.com/fuyufjh/splunk-hec-go/blob/10df423a9f3633e5395eaf8132da3a257251b189/client.go#L249-L253 |
14,175 | u-root/dhcp4 | packet.go | NewPacket | func NewPacket(op OpCode) *Packet {
return &Packet{
Op: op,
HType: 1, /* ethernet */
Options: make(Options),
}
} | go | func NewPacket(op OpCode) *Packet {
return &Packet{
Op: op,
HType: 1, /* ethernet */
Options: make(Options),
}
} | [
"func",
"NewPacket",
"(",
"op",
"OpCode",
")",
"*",
"Packet",
"{",
"return",
"&",
"Packet",
"{",
"Op",
":",
"op",
",",
"HType",
":",
"1",
",",
"/* ethernet */",
"Options",
":",
"make",
"(",
"Options",
")",
",",
"}",
"\n",
"}"
] | // NewPacket returns a new DHCP packet with the given op code. | [
"NewPacket",
"returns",
"a",
"new",
"DHCP",
"packet",
"with",
"the",
"given",
"op",
"code",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/packet.go#L87-L93 |
14,176 | u-root/dhcp4 | packet.go | MarshalBinary | func (p *Packet) MarshalBinary() ([]byte, error) {
b := uio.NewBigEndianBuffer(make([]byte, 0, minPacketLen))
b.Write8(uint8(p.Op))
b.Write8(p.HType)
// HLen
b.Write8(uint8(len(p.CHAddr)))
b.Write8(p.Hops)
b.WriteBytes(p.TransactionID[:])
b.Write16(p.Secs)
var flags uint16
if p.Broadcast {
flags |= flagBroadcast
}
b.Write16(flags)
writeIP(b, p.CIAddr)
writeIP(b, p.YIAddr)
writeIP(b, p.SIAddr)
writeIP(b, p.GIAddr)
copy(b.WriteN(chaddrLen), p.CHAddr)
var sname [64]byte
copy(sname[:], []byte(p.ServerName))
sname[len(p.ServerName)] = 0
b.WriteBytes(sname[:])
var file [128]byte
copy(file[:], []byte(p.BootFile))
file[len(p.BootFile)] = 0
b.WriteBytes(file[:])
// The magic cookie.
b.WriteBytes(magicCookie[:])
p.Options.Marshal(b)
// TODO pad to 272 bytes for really old crap.
return b.Data(), nil
} | go | func (p *Packet) MarshalBinary() ([]byte, error) {
b := uio.NewBigEndianBuffer(make([]byte, 0, minPacketLen))
b.Write8(uint8(p.Op))
b.Write8(p.HType)
// HLen
b.Write8(uint8(len(p.CHAddr)))
b.Write8(p.Hops)
b.WriteBytes(p.TransactionID[:])
b.Write16(p.Secs)
var flags uint16
if p.Broadcast {
flags |= flagBroadcast
}
b.Write16(flags)
writeIP(b, p.CIAddr)
writeIP(b, p.YIAddr)
writeIP(b, p.SIAddr)
writeIP(b, p.GIAddr)
copy(b.WriteN(chaddrLen), p.CHAddr)
var sname [64]byte
copy(sname[:], []byte(p.ServerName))
sname[len(p.ServerName)] = 0
b.WriteBytes(sname[:])
var file [128]byte
copy(file[:], []byte(p.BootFile))
file[len(p.BootFile)] = 0
b.WriteBytes(file[:])
// The magic cookie.
b.WriteBytes(magicCookie[:])
p.Options.Marshal(b)
// TODO pad to 272 bytes for really old crap.
return b.Data(), nil
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"minPacketLen",
")",
")",
"\n",
"b",
".",
"Write8",
"(",
"uint8",
"(",
"p",
".",
"Op",
")",
")",
"\n",
"b",
".",
"Write8",
"(",
"p",
".",
"HType",
")",
"\n\n",
"// HLen",
"b",
".",
"Write8",
"(",
"uint8",
"(",
"len",
"(",
"p",
".",
"CHAddr",
")",
")",
")",
"\n",
"b",
".",
"Write8",
"(",
"p",
".",
"Hops",
")",
"\n",
"b",
".",
"WriteBytes",
"(",
"p",
".",
"TransactionID",
"[",
":",
"]",
")",
"\n",
"b",
".",
"Write16",
"(",
"p",
".",
"Secs",
")",
"\n\n",
"var",
"flags",
"uint16",
"\n",
"if",
"p",
".",
"Broadcast",
"{",
"flags",
"|=",
"flagBroadcast",
"\n",
"}",
"\n",
"b",
".",
"Write16",
"(",
"flags",
")",
"\n\n",
"writeIP",
"(",
"b",
",",
"p",
".",
"CIAddr",
")",
"\n",
"writeIP",
"(",
"b",
",",
"p",
".",
"YIAddr",
")",
"\n",
"writeIP",
"(",
"b",
",",
"p",
".",
"SIAddr",
")",
"\n",
"writeIP",
"(",
"b",
",",
"p",
".",
"GIAddr",
")",
"\n",
"copy",
"(",
"b",
".",
"WriteN",
"(",
"chaddrLen",
")",
",",
"p",
".",
"CHAddr",
")",
"\n\n",
"var",
"sname",
"[",
"64",
"]",
"byte",
"\n",
"copy",
"(",
"sname",
"[",
":",
"]",
",",
"[",
"]",
"byte",
"(",
"p",
".",
"ServerName",
")",
")",
"\n",
"sname",
"[",
"len",
"(",
"p",
".",
"ServerName",
")",
"]",
"=",
"0",
"\n",
"b",
".",
"WriteBytes",
"(",
"sname",
"[",
":",
"]",
")",
"\n\n",
"var",
"file",
"[",
"128",
"]",
"byte",
"\n",
"copy",
"(",
"file",
"[",
":",
"]",
",",
"[",
"]",
"byte",
"(",
"p",
".",
"BootFile",
")",
")",
"\n",
"file",
"[",
"len",
"(",
"p",
".",
"BootFile",
")",
"]",
"=",
"0",
"\n",
"b",
".",
"WriteBytes",
"(",
"file",
"[",
":",
"]",
")",
"\n\n",
"// The magic cookie.",
"b",
".",
"WriteBytes",
"(",
"magicCookie",
"[",
":",
"]",
")",
"\n\n",
"p",
".",
"Options",
".",
"Marshal",
"(",
"b",
")",
"\n",
"// TODO pad to 272 bytes for really old crap.",
"return",
"b",
".",
"Data",
"(",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary writes the packet to binary. | [
"MarshalBinary",
"writes",
"the",
"packet",
"to",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/packet.go#L105-L144 |
14,177 | u-root/dhcp4 | packet.go | ParsePacket | func ParsePacket(q []byte) (*Packet, error) {
var pkt Packet
if err := (&pkt).UnmarshalBinary(q); err != nil {
return nil, err
}
return &pkt, nil
} | go | func ParsePacket(q []byte) (*Packet, error) {
var pkt Packet
if err := (&pkt).UnmarshalBinary(q); err != nil {
return nil, err
}
return &pkt, nil
} | [
"func",
"ParsePacket",
"(",
"q",
"[",
"]",
"byte",
")",
"(",
"*",
"Packet",
",",
"error",
")",
"{",
"var",
"pkt",
"Packet",
"\n",
"if",
"err",
":=",
"(",
"&",
"pkt",
")",
".",
"UnmarshalBinary",
"(",
"q",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"pkt",
",",
"nil",
"\n",
"}"
] | // ParsePacket parses a DHCP4 packet from q. | [
"ParsePacket",
"parses",
"a",
"DHCP4",
"packet",
"from",
"q",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/packet.go#L147-L153 |
14,178 | u-root/dhcp4 | packet.go | UnmarshalBinary | func (p *Packet) UnmarshalBinary(q []byte) error {
b := uio.NewBigEndianBuffer(q)
p.Op = OpCode(b.Read8())
p.HType = b.Read8()
hlen := b.Read8()
p.Hops = b.Read8()
b.ReadBytes(p.TransactionID[:])
p.Secs = b.Read16()
flags := b.Read16()
if flags&flagBroadcast != 0 {
p.Broadcast = true
}
p.CIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.CIAddr)
p.YIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.YIAddr)
p.SIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.SIAddr)
p.GIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.GIAddr)
if hlen > chaddrLen {
hlen = chaddrLen
}
// Always read 16 bytes, but only use hlen of them.
p.CHAddr = make(net.HardwareAddr, chaddrLen)
b.ReadBytes(p.CHAddr)
p.CHAddr = p.CHAddr[:hlen]
var sname [64]byte
b.ReadBytes(sname[:])
length := strings.Index(string(sname[:]), "\x00")
if length == -1 {
length = 64
}
p.ServerName = string(sname[:length])
var file [128]byte
b.ReadBytes(file[:])
length = strings.Index(string(file[:]), "\x00")
if length == -1 {
length = 128
}
p.BootFile = string(file[:length])
var cookie [4]byte
b.ReadBytes(cookie[:])
if cookie != magicCookie {
return fmt.Errorf("malformed DHCP packet: got magic cookie %v, want %v", cookie[:], magicCookie[:])
}
if err := p.Options.Unmarshal(b); err != nil {
return err
}
return b.FinError()
} | go | func (p *Packet) UnmarshalBinary(q []byte) error {
b := uio.NewBigEndianBuffer(q)
p.Op = OpCode(b.Read8())
p.HType = b.Read8()
hlen := b.Read8()
p.Hops = b.Read8()
b.ReadBytes(p.TransactionID[:])
p.Secs = b.Read16()
flags := b.Read16()
if flags&flagBroadcast != 0 {
p.Broadcast = true
}
p.CIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.CIAddr)
p.YIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.YIAddr)
p.SIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.SIAddr)
p.GIAddr = make(net.IP, net.IPv4len)
b.ReadBytes(p.GIAddr)
if hlen > chaddrLen {
hlen = chaddrLen
}
// Always read 16 bytes, but only use hlen of them.
p.CHAddr = make(net.HardwareAddr, chaddrLen)
b.ReadBytes(p.CHAddr)
p.CHAddr = p.CHAddr[:hlen]
var sname [64]byte
b.ReadBytes(sname[:])
length := strings.Index(string(sname[:]), "\x00")
if length == -1 {
length = 64
}
p.ServerName = string(sname[:length])
var file [128]byte
b.ReadBytes(file[:])
length = strings.Index(string(file[:]), "\x00")
if length == -1 {
length = 128
}
p.BootFile = string(file[:length])
var cookie [4]byte
b.ReadBytes(cookie[:])
if cookie != magicCookie {
return fmt.Errorf("malformed DHCP packet: got magic cookie %v, want %v", cookie[:], magicCookie[:])
}
if err := p.Options.Unmarshal(b); err != nil {
return err
}
return b.FinError()
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"UnmarshalBinary",
"(",
"q",
"[",
"]",
"byte",
")",
"error",
"{",
"b",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"q",
")",
"\n\n",
"p",
".",
"Op",
"=",
"OpCode",
"(",
"b",
".",
"Read8",
"(",
")",
")",
"\n",
"p",
".",
"HType",
"=",
"b",
".",
"Read8",
"(",
")",
"\n",
"hlen",
":=",
"b",
".",
"Read8",
"(",
")",
"\n",
"p",
".",
"Hops",
"=",
"b",
".",
"Read8",
"(",
")",
"\n",
"b",
".",
"ReadBytes",
"(",
"p",
".",
"TransactionID",
"[",
":",
"]",
")",
"\n",
"p",
".",
"Secs",
"=",
"b",
".",
"Read16",
"(",
")",
"\n\n",
"flags",
":=",
"b",
".",
"Read16",
"(",
")",
"\n",
"if",
"flags",
"&",
"flagBroadcast",
"!=",
"0",
"{",
"p",
".",
"Broadcast",
"=",
"true",
"\n",
"}",
"\n\n",
"p",
".",
"CIAddr",
"=",
"make",
"(",
"net",
".",
"IP",
",",
"net",
".",
"IPv4len",
")",
"\n",
"b",
".",
"ReadBytes",
"(",
"p",
".",
"CIAddr",
")",
"\n",
"p",
".",
"YIAddr",
"=",
"make",
"(",
"net",
".",
"IP",
",",
"net",
".",
"IPv4len",
")",
"\n",
"b",
".",
"ReadBytes",
"(",
"p",
".",
"YIAddr",
")",
"\n",
"p",
".",
"SIAddr",
"=",
"make",
"(",
"net",
".",
"IP",
",",
"net",
".",
"IPv4len",
")",
"\n",
"b",
".",
"ReadBytes",
"(",
"p",
".",
"SIAddr",
")",
"\n",
"p",
".",
"GIAddr",
"=",
"make",
"(",
"net",
".",
"IP",
",",
"net",
".",
"IPv4len",
")",
"\n",
"b",
".",
"ReadBytes",
"(",
"p",
".",
"GIAddr",
")",
"\n\n",
"if",
"hlen",
">",
"chaddrLen",
"{",
"hlen",
"=",
"chaddrLen",
"\n",
"}",
"\n",
"// Always read 16 bytes, but only use hlen of them.",
"p",
".",
"CHAddr",
"=",
"make",
"(",
"net",
".",
"HardwareAddr",
",",
"chaddrLen",
")",
"\n",
"b",
".",
"ReadBytes",
"(",
"p",
".",
"CHAddr",
")",
"\n",
"p",
".",
"CHAddr",
"=",
"p",
".",
"CHAddr",
"[",
":",
"hlen",
"]",
"\n\n",
"var",
"sname",
"[",
"64",
"]",
"byte",
"\n",
"b",
".",
"ReadBytes",
"(",
"sname",
"[",
":",
"]",
")",
"\n",
"length",
":=",
"strings",
".",
"Index",
"(",
"string",
"(",
"sname",
"[",
":",
"]",
")",
",",
"\"",
"\\x00",
"\"",
")",
"\n",
"if",
"length",
"==",
"-",
"1",
"{",
"length",
"=",
"64",
"\n",
"}",
"\n",
"p",
".",
"ServerName",
"=",
"string",
"(",
"sname",
"[",
":",
"length",
"]",
")",
"\n\n",
"var",
"file",
"[",
"128",
"]",
"byte",
"\n",
"b",
".",
"ReadBytes",
"(",
"file",
"[",
":",
"]",
")",
"\n",
"length",
"=",
"strings",
".",
"Index",
"(",
"string",
"(",
"file",
"[",
":",
"]",
")",
",",
"\"",
"\\x00",
"\"",
")",
"\n",
"if",
"length",
"==",
"-",
"1",
"{",
"length",
"=",
"128",
"\n",
"}",
"\n",
"p",
".",
"BootFile",
"=",
"string",
"(",
"file",
"[",
":",
"length",
"]",
")",
"\n\n",
"var",
"cookie",
"[",
"4",
"]",
"byte",
"\n",
"b",
".",
"ReadBytes",
"(",
"cookie",
"[",
":",
"]",
")",
"\n",
"if",
"cookie",
"!=",
"magicCookie",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cookie",
"[",
":",
"]",
",",
"magicCookie",
"[",
":",
"]",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"p",
".",
"Options",
".",
"Unmarshal",
"(",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"b",
".",
"FinError",
"(",
")",
"\n",
"}"
] | // UnmarshalBinary reads the packet from binary. | [
"UnmarshalBinary",
"reads",
"the",
"packet",
"from",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/packet.go#L156-L214 |
14,179 | u-root/dhcp4 | options.go | Unmarshal | func (o *Options) Unmarshal(buf *uio.Lexer) error {
*o = make(Options)
var end bool
for buf.Has(1) {
// 1 byte: option code
// 1 byte: option length n
// n bytes: data
code := OptionCode(buf.Read8())
if code == Pad {
continue
} else if code == End {
end = true
break
}
if !buf.Has(1) {
return io.ErrUnexpectedEOF
}
length := int(buf.Read8())
if length == 0 {
continue
}
if !buf.Has(length) {
return io.ErrUnexpectedEOF
}
// N bytes: option data
data := buf.Consume(length)
if data == nil {
return io.ErrUnexpectedEOF
}
data = data[:length:length]
// RFC 3396: Just concatenate the data if the option code was
// specified multiple times.
o.AddRaw(code, data)
}
if !end {
return io.ErrUnexpectedEOF
}
// Any bytes left must be padding.
for buf.Has(1) {
if OptionCode(buf.Read8()) != Pad {
return ErrInvalidOptions
}
}
return nil
} | go | func (o *Options) Unmarshal(buf *uio.Lexer) error {
*o = make(Options)
var end bool
for buf.Has(1) {
// 1 byte: option code
// 1 byte: option length n
// n bytes: data
code := OptionCode(buf.Read8())
if code == Pad {
continue
} else if code == End {
end = true
break
}
if !buf.Has(1) {
return io.ErrUnexpectedEOF
}
length := int(buf.Read8())
if length == 0 {
continue
}
if !buf.Has(length) {
return io.ErrUnexpectedEOF
}
// N bytes: option data
data := buf.Consume(length)
if data == nil {
return io.ErrUnexpectedEOF
}
data = data[:length:length]
// RFC 3396: Just concatenate the data if the option code was
// specified multiple times.
o.AddRaw(code, data)
}
if !end {
return io.ErrUnexpectedEOF
}
// Any bytes left must be padding.
for buf.Has(1) {
if OptionCode(buf.Read8()) != Pad {
return ErrInvalidOptions
}
}
return nil
} | [
"func",
"(",
"o",
"*",
"Options",
")",
"Unmarshal",
"(",
"buf",
"*",
"uio",
".",
"Lexer",
")",
"error",
"{",
"*",
"o",
"=",
"make",
"(",
"Options",
")",
"\n\n",
"var",
"end",
"bool",
"\n",
"for",
"buf",
".",
"Has",
"(",
"1",
")",
"{",
"// 1 byte: option code",
"// 1 byte: option length n",
"// n bytes: data",
"code",
":=",
"OptionCode",
"(",
"buf",
".",
"Read8",
"(",
")",
")",
"\n\n",
"if",
"code",
"==",
"Pad",
"{",
"continue",
"\n",
"}",
"else",
"if",
"code",
"==",
"End",
"{",
"end",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"!",
"buf",
".",
"Has",
"(",
"1",
")",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n\n",
"length",
":=",
"int",
"(",
"buf",
".",
"Read8",
"(",
")",
")",
"\n",
"if",
"length",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"!",
"buf",
".",
"Has",
"(",
"length",
")",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n\n",
"// N bytes: option data",
"data",
":=",
"buf",
".",
"Consume",
"(",
"length",
")",
"\n",
"if",
"data",
"==",
"nil",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n",
"data",
"=",
"data",
"[",
":",
"length",
":",
"length",
"]",
"\n\n",
"// RFC 3396: Just concatenate the data if the option code was",
"// specified multiple times.",
"o",
".",
"AddRaw",
"(",
"code",
",",
"data",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"end",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n\n",
"// Any bytes left must be padding.",
"for",
"buf",
".",
"Has",
"(",
"1",
")",
"{",
"if",
"OptionCode",
"(",
"buf",
".",
"Read8",
"(",
")",
")",
"!=",
"Pad",
"{",
"return",
"ErrInvalidOptions",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Unmarshal fills opts with option codes and corresponding values from an
// input byte slice.
//
// It is used with various different types to enable parsing of both top-level
// options. If options data is malformed, it returns ErrInvalidOptions or
// io.ErrUnexpectedEOF. | [
"Unmarshal",
"fills",
"opts",
"with",
"option",
"codes",
"and",
"corresponding",
"values",
"from",
"an",
"input",
"byte",
"slice",
".",
"It",
"is",
"used",
"with",
"various",
"different",
"types",
"to",
"enable",
"parsing",
"of",
"both",
"top",
"-",
"level",
"options",
".",
"If",
"options",
"data",
"is",
"malformed",
"it",
"returns",
"ErrInvalidOptions",
"or",
"io",
".",
"ErrUnexpectedEOF",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/options.go#L70-L122 |
14,180 | u-root/dhcp4 | options.go | Marshal | func (o Options) Marshal(b *uio.Lexer) {
for _, c := range o.sortedKeys() {
code := OptionCode(c)
data := o[code]
// RFC 3396: If more than 256 bytes of data are given, the
// option is simply listed multiple times.
for len(data) > 0 {
// 1 byte: option code
b.Write8(uint8(code))
// Some DHCPv4 options have fixed length and do not put
// length on the wire.
if code == End || code == Pad {
continue
}
n := len(data)
if n > math.MaxUint8 {
n = math.MaxUint8
}
// 1 byte: option length
b.Write8(uint8(n))
// N bytes: option data
b.WriteBytes(data[:n])
data = data[n:]
}
}
// If "End" option is not in map, marshal it manually.
if _, ok := o[End]; !ok {
b.Write8(uint8(End))
}
} | go | func (o Options) Marshal(b *uio.Lexer) {
for _, c := range o.sortedKeys() {
code := OptionCode(c)
data := o[code]
// RFC 3396: If more than 256 bytes of data are given, the
// option is simply listed multiple times.
for len(data) > 0 {
// 1 byte: option code
b.Write8(uint8(code))
// Some DHCPv4 options have fixed length and do not put
// length on the wire.
if code == End || code == Pad {
continue
}
n := len(data)
if n > math.MaxUint8 {
n = math.MaxUint8
}
// 1 byte: option length
b.Write8(uint8(n))
// N bytes: option data
b.WriteBytes(data[:n])
data = data[n:]
}
}
// If "End" option is not in map, marshal it manually.
if _, ok := o[End]; !ok {
b.Write8(uint8(End))
}
} | [
"func",
"(",
"o",
"Options",
")",
"Marshal",
"(",
"b",
"*",
"uio",
".",
"Lexer",
")",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"o",
".",
"sortedKeys",
"(",
")",
"{",
"code",
":=",
"OptionCode",
"(",
"c",
")",
"\n",
"data",
":=",
"o",
"[",
"code",
"]",
"\n\n",
"// RFC 3396: If more than 256 bytes of data are given, the",
"// option is simply listed multiple times.",
"for",
"len",
"(",
"data",
")",
">",
"0",
"{",
"// 1 byte: option code",
"b",
".",
"Write8",
"(",
"uint8",
"(",
"code",
")",
")",
"\n\n",
"// Some DHCPv4 options have fixed length and do not put",
"// length on the wire.",
"if",
"code",
"==",
"End",
"||",
"code",
"==",
"Pad",
"{",
"continue",
"\n",
"}",
"\n\n",
"n",
":=",
"len",
"(",
"data",
")",
"\n",
"if",
"n",
">",
"math",
".",
"MaxUint8",
"{",
"n",
"=",
"math",
".",
"MaxUint8",
"\n",
"}",
"\n\n",
"// 1 byte: option length",
"b",
".",
"Write8",
"(",
"uint8",
"(",
"n",
")",
")",
"\n\n",
"// N bytes: option data",
"b",
".",
"WriteBytes",
"(",
"data",
"[",
":",
"n",
"]",
")",
"\n",
"data",
"=",
"data",
"[",
"n",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If \"End\" option is not in map, marshal it manually.",
"if",
"_",
",",
"ok",
":=",
"o",
"[",
"End",
"]",
";",
"!",
"ok",
"{",
"b",
".",
"Write8",
"(",
"uint8",
"(",
"End",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Marshal writes options into the provided Buffer sorted by option codes. | [
"Marshal",
"writes",
"options",
"into",
"the",
"provided",
"Buffer",
"sorted",
"by",
"option",
"codes",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/options.go#L125-L160 |
14,181 | u-root/dhcp4 | options.go | sortedKeys | func (o Options) sortedKeys() []int {
// Send all values for a given key
var codes []int
for k := range o {
codes = append(codes, int(k))
}
sort.Sort(sort.IntSlice(codes))
return codes
} | go | func (o Options) sortedKeys() []int {
// Send all values for a given key
var codes []int
for k := range o {
codes = append(codes, int(k))
}
sort.Sort(sort.IntSlice(codes))
return codes
} | [
"func",
"(",
"o",
"Options",
")",
"sortedKeys",
"(",
")",
"[",
"]",
"int",
"{",
"// Send all values for a given key",
"var",
"codes",
"[",
"]",
"int",
"\n",
"for",
"k",
":=",
"range",
"o",
"{",
"codes",
"=",
"append",
"(",
"codes",
",",
"int",
"(",
"k",
")",
")",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"sort",
".",
"IntSlice",
"(",
"codes",
")",
")",
"\n",
"return",
"codes",
"\n",
"}"
] | // sortedKeys returns an ordered slice of option keys from the Options map, for
// use in serializing options to binary. | [
"sortedKeys",
"returns",
"an",
"ordered",
"slice",
"of",
"option",
"keys",
"from",
"the",
"Options",
"map",
"for",
"use",
"in",
"serializing",
"options",
"to",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/options.go#L164-L173 |
14,182 | u-root/dhcp4 | dhcp4client/client.go | New | func New(iface netlink.Link, opts ...ClientOpt) (*Client, error) {
c := &Client{
iface: iface,
timeout: 10 * time.Second,
retry: 3,
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
if c.conn == nil {
var err error
c.conn, err = NewPacketUDPConn(iface.Attrs().Name, ClientPort)
if err != nil {
return nil, err
}
}
return c, nil
} | go | func New(iface netlink.Link, opts ...ClientOpt) (*Client, error) {
c := &Client{
iface: iface,
timeout: 10 * time.Second,
retry: 3,
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
if c.conn == nil {
var err error
c.conn, err = NewPacketUDPConn(iface.Attrs().Name, ClientPort)
if err != nil {
return nil, err
}
}
return c, nil
} | [
"func",
"New",
"(",
"iface",
"netlink",
".",
"Link",
",",
"opts",
"...",
"ClientOpt",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"c",
":=",
"&",
"Client",
"{",
"iface",
":",
"iface",
",",
"timeout",
":",
"10",
"*",
"time",
".",
"Second",
",",
"retry",
":",
"3",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"if",
"err",
":=",
"opt",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"conn",
"==",
"nil",
"{",
"var",
"err",
"error",
"\n",
"c",
".",
"conn",
",",
"err",
"=",
"NewPacketUDPConn",
"(",
"iface",
".",
"Attrs",
"(",
")",
".",
"Name",
",",
"ClientPort",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // New creates a new DHCP client that sends and receives packets on the given
// interface. | [
"New",
"creates",
"a",
"new",
"DHCP",
"client",
"that",
"sends",
"and",
"receives",
"packets",
"on",
"the",
"given",
"interface",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L53-L74 |
14,183 | u-root/dhcp4 | dhcp4client/client.go | WithConn | func WithConn(conn net.PacketConn) ClientOpt {
return func(c *Client) error {
c.conn = conn
return nil
}
} | go | func WithConn(conn net.PacketConn) ClientOpt {
return func(c *Client) error {
c.conn = conn
return nil
}
} | [
"func",
"WithConn",
"(",
"conn",
"net",
".",
"PacketConn",
")",
"ClientOpt",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"error",
"{",
"c",
".",
"conn",
"=",
"conn",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // WithConn configures the packet connection to use. | [
"WithConn",
"configures",
"the",
"packet",
"connection",
"to",
"use",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L104-L109 |
14,184 | u-root/dhcp4 | dhcp4client/client.go | DiscoverOffer | func (c *Client) DiscoverOffer() (*dhcp4.Packet, error) {
ctx, cancel := context.WithCancel(context.Background())
wg, out, errCh := c.SimpleSendAndRead(ctx, DefaultServers, c.DiscoverPacket())
defer func() {
// Explicitly cancel first, then wait.
cancel()
wg.Wait()
}()
for packet := range out {
msgType := dhcp4opts.GetDHCPMessageType(packet.Packet.Options)
if msgType == dhcp4opts.DHCPOffer {
// Deferred cancel will cancel the goroutine.
return packet.Packet, nil
}
}
if err, ok := <-errCh; ok && err != nil {
return nil, err
}
return nil, fmt.Errorf("didn't get a packet")
} | go | func (c *Client) DiscoverOffer() (*dhcp4.Packet, error) {
ctx, cancel := context.WithCancel(context.Background())
wg, out, errCh := c.SimpleSendAndRead(ctx, DefaultServers, c.DiscoverPacket())
defer func() {
// Explicitly cancel first, then wait.
cancel()
wg.Wait()
}()
for packet := range out {
msgType := dhcp4opts.GetDHCPMessageType(packet.Packet.Options)
if msgType == dhcp4opts.DHCPOffer {
// Deferred cancel will cancel the goroutine.
return packet.Packet, nil
}
}
if err, ok := <-errCh; ok && err != nil {
return nil, err
}
return nil, fmt.Errorf("didn't get a packet")
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DiscoverOffer",
"(",
")",
"(",
"*",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"wg",
",",
"out",
",",
"errCh",
":=",
"c",
".",
"SimpleSendAndRead",
"(",
"ctx",
",",
"DefaultServers",
",",
"c",
".",
"DiscoverPacket",
"(",
")",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"// Explicitly cancel first, then wait.",
"cancel",
"(",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"packet",
":=",
"range",
"out",
"{",
"msgType",
":=",
"dhcp4opts",
".",
"GetDHCPMessageType",
"(",
"packet",
".",
"Packet",
".",
"Options",
")",
"\n",
"if",
"msgType",
"==",
"dhcp4opts",
".",
"DHCPOffer",
"{",
"// Deferred cancel will cancel the goroutine.",
"return",
"packet",
".",
"Packet",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
",",
"ok",
":=",
"<-",
"errCh",
";",
"ok",
"&&",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // DiscoverOffer sends a DHCPDiscover message and returns the first valid offer
// received. | [
"DiscoverOffer",
"sends",
"a",
"DHCPDiscover",
"message",
"and",
"returns",
"the",
"first",
"valid",
"offer",
"received",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L113-L134 |
14,185 | u-root/dhcp4 | dhcp4client/client.go | Request | func (c *Client) Request() (*dhcp4.Packet, error) {
offer, err := c.DiscoverOffer()
if err != nil {
return nil, err
}
return c.SendAndReadOne(c.RequestPacket(offer))
} | go | func (c *Client) Request() (*dhcp4.Packet, error) {
offer, err := c.DiscoverOffer()
if err != nil {
return nil, err
}
return c.SendAndReadOne(c.RequestPacket(offer))
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Request",
"(",
")",
"(",
"*",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"offer",
",",
"err",
":=",
"c",
".",
"DiscoverOffer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"SendAndReadOne",
"(",
"c",
".",
"RequestPacket",
"(",
"offer",
")",
")",
"\n",
"}"
] | // Request completes the 4-way Discover-Offer-Request-Ack handshake. | [
"Request",
"completes",
"the",
"4",
"-",
"way",
"Discover",
"-",
"Offer",
"-",
"Request",
"-",
"Ack",
"handshake",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L137-L144 |
14,186 | u-root/dhcp4 | dhcp4client/client.go | Renew | func (c *Client) Renew(ack *dhcp4.Packet) (*dhcp4.Packet, error) {
return c.SendAndReadOne(c.RequestPacket(ack))
} | go | func (c *Client) Renew(ack *dhcp4.Packet) (*dhcp4.Packet, error) {
return c.SendAndReadOne(c.RequestPacket(ack))
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Renew",
"(",
"ack",
"*",
"dhcp4",
".",
"Packet",
")",
"(",
"*",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"return",
"c",
".",
"SendAndReadOne",
"(",
"c",
".",
"RequestPacket",
"(",
"ack",
")",
")",
"\n",
"}"
] | // Renew sends a renewal request packet and waits for the corresponding response. | [
"Renew",
"sends",
"a",
"renewal",
"request",
"packet",
"and",
"waits",
"for",
"the",
"corresponding",
"response",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L147-L149 |
14,187 | u-root/dhcp4 | dhcp4client/client.go | Close | func (c *Client) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
} | go | func (c *Client) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"c",
".",
"conn",
"!=",
"nil",
"{",
"return",
"c",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes the client connection. | [
"Close",
"closes",
"the",
"client",
"connection",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L152-L157 |
14,188 | u-root/dhcp4 | dhcp4client/client.go | SendAndReadOne | func (c *Client) SendAndReadOne(packet *dhcp4.Packet) (*dhcp4.Packet, error) {
ctx, cancel := context.WithCancel(context.Background())
wg, out, errCh := c.SimpleSendAndRead(ctx, DefaultServers, packet)
defer func() {
// Explicitly cancel first, then wait.
cancel()
wg.Wait()
}()
if response, ok := <-out; ok {
// We're just gonna take the first packet.
return response.Packet, nil
}
if err, ok := <-errCh; ok && err != nil {
return nil, err
}
return nil, fmt.Errorf("no packet received")
} | go | func (c *Client) SendAndReadOne(packet *dhcp4.Packet) (*dhcp4.Packet, error) {
ctx, cancel := context.WithCancel(context.Background())
wg, out, errCh := c.SimpleSendAndRead(ctx, DefaultServers, packet)
defer func() {
// Explicitly cancel first, then wait.
cancel()
wg.Wait()
}()
if response, ok := <-out; ok {
// We're just gonna take the first packet.
return response.Packet, nil
}
if err, ok := <-errCh; ok && err != nil {
return nil, err
}
return nil, fmt.Errorf("no packet received")
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendAndReadOne",
"(",
"packet",
"*",
"dhcp4",
".",
"Packet",
")",
"(",
"*",
"dhcp4",
".",
"Packet",
",",
"error",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"wg",
",",
"out",
",",
"errCh",
":=",
"c",
".",
"SimpleSendAndRead",
"(",
"ctx",
",",
"DefaultServers",
",",
"packet",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"// Explicitly cancel first, then wait.",
"cancel",
"(",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"response",
",",
"ok",
":=",
"<-",
"out",
";",
"ok",
"{",
"// We're just gonna take the first packet.",
"return",
"response",
".",
"Packet",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
",",
"ok",
":=",
"<-",
"errCh",
";",
"ok",
"&&",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // SendAndReadOne sends one packet and returns the first response returned by
// any server. | [
"SendAndReadOne",
"sends",
"one",
"packet",
"and",
"returns",
"the",
"first",
"response",
"returned",
"by",
"any",
"server",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4client/client.go#L161-L178 |
14,189 | u-root/dhcp4 | dhcp4opts/types.go | UnmarshalBinary | func (d *DHCPMessageType) UnmarshalBinary(p []byte) error {
buf := uio.NewBigEndianBuffer(p)
*d = DHCPMessageType(buf.Read8())
return buf.FinError()
} | go | func (d *DHCPMessageType) UnmarshalBinary(p []byte) error {
buf := uio.NewBigEndianBuffer(p)
*d = DHCPMessageType(buf.Read8())
return buf.FinError()
} | [
"func",
"(",
"d",
"*",
"DHCPMessageType",
")",
"UnmarshalBinary",
"(",
"p",
"[",
"]",
"byte",
")",
"error",
"{",
"buf",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"p",
")",
"\n",
"*",
"d",
"=",
"DHCPMessageType",
"(",
"buf",
".",
"Read8",
"(",
")",
")",
"\n",
"return",
"buf",
".",
"FinError",
"(",
")",
"\n",
"}"
] | // UnmarshalBinary unmarshals the DHCP message type option from binary. | [
"UnmarshalBinary",
"unmarshals",
"the",
"DHCP",
"message",
"type",
"option",
"from",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L38-L42 |
14,190 | u-root/dhcp4 | dhcp4opts/types.go | MarshalBinary | func (s SubnetMask) MarshalBinary() ([]byte, error) {
return []byte(s[:net.IPv4len]), nil
} | go | func (s SubnetMask) MarshalBinary() ([]byte, error) {
return []byte(s[:net.IPv4len]), nil
} | [
"func",
"(",
"s",
"SubnetMask",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"s",
"[",
":",
"net",
".",
"IPv4len",
"]",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary writes the subnet mask option to binary. | [
"MarshalBinary",
"writes",
"the",
"subnet",
"mask",
"option",
"to",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L50-L52 |
14,191 | u-root/dhcp4 | dhcp4opts/types.go | UnmarshalBinary | func (s *SubnetMask) UnmarshalBinary(p []byte) error {
buf := uio.NewBigEndianBuffer(p)
*s = buf.CopyN(net.IPv4len)
return buf.FinError()
} | go | func (s *SubnetMask) UnmarshalBinary(p []byte) error {
buf := uio.NewBigEndianBuffer(p)
*s = buf.CopyN(net.IPv4len)
return buf.FinError()
} | [
"func",
"(",
"s",
"*",
"SubnetMask",
")",
"UnmarshalBinary",
"(",
"p",
"[",
"]",
"byte",
")",
"error",
"{",
"buf",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"p",
")",
"\n",
"*",
"s",
"=",
"buf",
".",
"CopyN",
"(",
"net",
".",
"IPv4len",
")",
"\n",
"return",
"buf",
".",
"FinError",
"(",
")",
"\n",
"}"
] | // UnmarshalBinary reads the subnet mask option from binary. | [
"UnmarshalBinary",
"reads",
"the",
"subnet",
"mask",
"option",
"from",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L55-L59 |
14,192 | u-root/dhcp4 | dhcp4opts/types.go | MarshalBinary | func (i IP) MarshalBinary() ([]byte, error) {
return []byte(i[:net.IPv4len]), nil
} | go | func (i IP) MarshalBinary() ([]byte, error) {
return []byte(i[:net.IPv4len]), nil
} | [
"func",
"(",
"i",
"IP",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"i",
"[",
":",
"net",
".",
"IPv4len",
"]",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary writes the IP address to binary. | [
"MarshalBinary",
"writes",
"the",
"IP",
"address",
"to",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L67-L69 |
14,193 | u-root/dhcp4 | dhcp4opts/types.go | UnmarshalBinary | func (i *IP) UnmarshalBinary(p []byte) error {
if len(p) < net.IPv4len {
return io.ErrUnexpectedEOF
}
*i = make([]byte, net.IPv4len)
copy(*i, p[:net.IPv4len])
return nil
} | go | func (i *IP) UnmarshalBinary(p []byte) error {
if len(p) < net.IPv4len {
return io.ErrUnexpectedEOF
}
*i = make([]byte, net.IPv4len)
copy(*i, p[:net.IPv4len])
return nil
} | [
"func",
"(",
"i",
"*",
"IP",
")",
"UnmarshalBinary",
"(",
"p",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"len",
"(",
"p",
")",
"<",
"net",
".",
"IPv4len",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n\n",
"*",
"i",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"net",
".",
"IPv4len",
")",
"\n",
"copy",
"(",
"*",
"i",
",",
"p",
"[",
":",
"net",
".",
"IPv4len",
"]",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalBinary reads the IP address from binary. | [
"UnmarshalBinary",
"reads",
"the",
"IP",
"address",
"from",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L72-L80 |
14,194 | u-root/dhcp4 | dhcp4opts/types.go | GetIP | func GetIP(code dhcp4.OptionCode, o dhcp4.Options) IP {
v := o.Get(code)
if v == nil {
return nil
}
var ip IP
if err := (&ip).UnmarshalBinary(v); err != nil {
return nil
}
return ip
} | go | func GetIP(code dhcp4.OptionCode, o dhcp4.Options) IP {
v := o.Get(code)
if v == nil {
return nil
}
var ip IP
if err := (&ip).UnmarshalBinary(v); err != nil {
return nil
}
return ip
} | [
"func",
"GetIP",
"(",
"code",
"dhcp4",
".",
"OptionCode",
",",
"o",
"dhcp4",
".",
"Options",
")",
"IP",
"{",
"v",
":=",
"o",
".",
"Get",
"(",
"code",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"ip",
"IP",
"\n",
"if",
"err",
":=",
"(",
"&",
"ip",
")",
".",
"UnmarshalBinary",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"ip",
"\n",
"}"
] | // GetIP returns the IP encoded in `code` option of `o`, if there is one. | [
"GetIP",
"returns",
"the",
"IP",
"encoded",
"in",
"code",
"option",
"of",
"o",
"if",
"there",
"is",
"one",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L83-L93 |
14,195 | u-root/dhcp4 | dhcp4opts/types.go | MarshalBinary | func (i IPs) MarshalBinary() ([]byte, error) {
b := uio.NewBigEndianBuffer(make([]byte, 0, net.IPv4len*len(i)))
for _, ip := range i {
b.WriteBytes(ip.To4())
}
return b.Data(), nil
} | go | func (i IPs) MarshalBinary() ([]byte, error) {
b := uio.NewBigEndianBuffer(make([]byte, 0, net.IPv4len*len(i)))
for _, ip := range i {
b.WriteBytes(ip.To4())
}
return b.Data(), nil
} | [
"func",
"(",
"i",
"IPs",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"net",
".",
"IPv4len",
"*",
"len",
"(",
"i",
")",
")",
")",
"\n",
"for",
"_",
",",
"ip",
":=",
"range",
"i",
"{",
"b",
".",
"WriteBytes",
"(",
"ip",
".",
"To4",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"b",
".",
"Data",
"(",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary writes the list of IPs to binary. | [
"MarshalBinary",
"writes",
"the",
"list",
"of",
"IPs",
"to",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L101-L107 |
14,196 | u-root/dhcp4 | dhcp4opts/types.go | UnmarshalBinary | func (i *IPs) UnmarshalBinary(p []byte) error {
b := uio.NewBigEndianBuffer(p)
*i = make([]net.IP, 0, b.Len()/net.IPv4len)
for b.Has(net.IPv4len) {
*i = append(*i, net.IP(b.CopyN(net.IPv4len)))
}
return b.FinError()
} | go | func (i *IPs) UnmarshalBinary(p []byte) error {
b := uio.NewBigEndianBuffer(p)
*i = make([]net.IP, 0, b.Len()/net.IPv4len)
for b.Has(net.IPv4len) {
*i = append(*i, net.IP(b.CopyN(net.IPv4len)))
}
return b.FinError()
} | [
"func",
"(",
"i",
"*",
"IPs",
")",
"UnmarshalBinary",
"(",
"p",
"[",
"]",
"byte",
")",
"error",
"{",
"b",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"p",
")",
"\n\n",
"*",
"i",
"=",
"make",
"(",
"[",
"]",
"net",
".",
"IP",
",",
"0",
",",
"b",
".",
"Len",
"(",
")",
"/",
"net",
".",
"IPv4len",
")",
"\n",
"for",
"b",
".",
"Has",
"(",
"net",
".",
"IPv4len",
")",
"{",
"*",
"i",
"=",
"append",
"(",
"*",
"i",
",",
"net",
".",
"IP",
"(",
"b",
".",
"CopyN",
"(",
"net",
".",
"IPv4len",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"b",
".",
"FinError",
"(",
")",
"\n",
"}"
] | // UnmarshalBinary reads a list of IPs from binary. | [
"UnmarshalBinary",
"reads",
"a",
"list",
"of",
"IPs",
"from",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L110-L118 |
14,197 | u-root/dhcp4 | dhcp4opts/types.go | GetIPs | func GetIPs(code dhcp4.OptionCode, o dhcp4.Options) IPs {
v := o.Get(code)
if v == nil {
return nil
}
var i IPs
if err := i.UnmarshalBinary(v); err != nil {
return nil
}
return i
} | go | func GetIPs(code dhcp4.OptionCode, o dhcp4.Options) IPs {
v := o.Get(code)
if v == nil {
return nil
}
var i IPs
if err := i.UnmarshalBinary(v); err != nil {
return nil
}
return i
} | [
"func",
"GetIPs",
"(",
"code",
"dhcp4",
".",
"OptionCode",
",",
"o",
"dhcp4",
".",
"Options",
")",
"IPs",
"{",
"v",
":=",
"o",
".",
"Get",
"(",
"code",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"i",
"IPs",
"\n",
"if",
"err",
":=",
"i",
".",
"UnmarshalBinary",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"i",
"\n",
"}"
] | // GetIPs returns the list of IPs encoded in `code` option of `o`. | [
"GetIPs",
"returns",
"the",
"list",
"of",
"IPs",
"encoded",
"in",
"code",
"option",
"of",
"o",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L121-L132 |
14,198 | u-root/dhcp4 | dhcp4opts/types.go | GetString | func GetString(code dhcp4.OptionCode, o dhcp4.Options) string {
v := o.Get(code)
if v == nil {
return ""
}
return string(v)
} | go | func GetString(code dhcp4.OptionCode, o dhcp4.Options) string {
v := o.Get(code)
if v == nil {
return ""
}
return string(v)
} | [
"func",
"GetString",
"(",
"code",
"dhcp4",
".",
"OptionCode",
",",
"o",
"dhcp4",
".",
"Options",
")",
"string",
"{",
"v",
":=",
"o",
".",
"Get",
"(",
"code",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"string",
"(",
"v",
")",
"\n",
"}"
] | // GetString returns the string encoded in the `code` option of `o`. | [
"GetString",
"returns",
"the",
"string",
"encoded",
"in",
"the",
"code",
"option",
"of",
"o",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L145-L151 |
14,199 | u-root/dhcp4 | dhcp4opts/types.go | MarshalBinary | func (o OptionCodes) MarshalBinary() ([]byte, error) {
b := uio.NewBigEndianBuffer(nil)
for _, code := range o {
b.Write8(uint8(code))
}
return b.Data(), nil
} | go | func (o OptionCodes) MarshalBinary() ([]byte, error) {
b := uio.NewBigEndianBuffer(nil)
for _, code := range o {
b.Write8(uint8(code))
}
return b.Data(), nil
} | [
"func",
"(",
"o",
"OptionCodes",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
":=",
"uio",
".",
"NewBigEndianBuffer",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"code",
":=",
"range",
"o",
"{",
"b",
".",
"Write8",
"(",
"uint8",
"(",
"code",
")",
")",
"\n",
"}",
"\n",
"return",
"b",
".",
"Data",
"(",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary writes the option code list to binary. | [
"MarshalBinary",
"writes",
"the",
"option",
"code",
"list",
"to",
"binary",
"."
] | 03363dc71ec82763595440b4b2c3e5f69f47a4e0 | https://github.com/u-root/dhcp4/blob/03363dc71ec82763595440b4b2c3e5f69f47a4e0/dhcp4opts/types.go#L159-L165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.