repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
securego/gosec
rules/archive.go
NewArchive
func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { calls := gosec.NewCallList() calls.Add("path/filepath", "Join") return &archive{ calls: calls, argType: "*archive/zip.File", MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "File traversal when extracting zip archive", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { calls := gosec.NewCallList() calls.Add("path/filepath", "Join") return &archive{ calls: calls, argType: "*archive/zip.File", MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "File traversal when extracting zip archive", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewArchive", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "calls", ":=", "gosec", ".", "NewCallList", "(", ")", "\n", "calls", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "&", "archive", "{", "calls", ":", "calls", ",", "argType", ":", "\"", "\"", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "High", ",", "What", ":", "\"", "\"", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewArchive creates a new rule which detects the file traversal when extracting zip archives
[ "NewArchive", "creates", "a", "new", "rule", "which", "detects", "the", "file", "traversal", "when", "extracting", "zip", "archives" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/archive.go#L47-L60
train
securego/gosec
call_list.go
AddAll
func (c CallList) AddAll(selector string, idents ...string) { for _, ident := range idents { c.Add(selector, ident) } }
go
func (c CallList) AddAll(selector string, idents ...string) { for _, ident := range idents { c.Add(selector, ident) } }
[ "func", "(", "c", "CallList", ")", "AddAll", "(", "selector", "string", ",", "idents", "...", "string", ")", "{", "for", "_", ",", "ident", ":=", "range", "idents", "{", "c", ".", "Add", "(", "selector", ",", "ident", ")", "\n", "}", "\n", "}" ]
// AddAll will add several calls to the call list at once
[ "AddAll", "will", "add", "several", "calls", "to", "the", "call", "list", "at", "once" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/call_list.go#L35-L39
train
securego/gosec
call_list.go
Add
func (c CallList) Add(selector, ident string) { if _, ok := c[selector]; !ok { c[selector] = make(set) } c[selector][ident] = true }
go
func (c CallList) Add(selector, ident string) { if _, ok := c[selector]; !ok { c[selector] = make(set) } c[selector][ident] = true }
[ "func", "(", "c", "CallList", ")", "Add", "(", "selector", ",", "ident", "string", ")", "{", "if", "_", ",", "ok", ":=", "c", "[", "selector", "]", ";", "!", "ok", "{", "c", "[", "selector", "]", "=", "make", "(", "set", ")", "\n", "}", "\n", "c", "[", "selector", "]", "[", "ident", "]", "=", "true", "\n", "}" ]
// Add a selector and call to the call list
[ "Add", "a", "selector", "and", "call", "to", "the", "call", "list" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/call_list.go#L42-L47
train
securego/gosec
helpers.go
MatchCompLit
func MatchCompLit(n ast.Node, ctx *Context, required string) *ast.CompositeLit { if complit, ok := n.(*ast.CompositeLit); ok { typeOf := ctx.Info.TypeOf(complit) if typeOf.String() == required { return complit } } return nil }
go
func MatchCompLit(n ast.Node, ctx *Context, required string) *ast.CompositeLit { if complit, ok := n.(*ast.CompositeLit); ok { typeOf := ctx.Info.TypeOf(complit) if typeOf.String() == required { return complit } } return nil }
[ "func", "MatchCompLit", "(", "n", "ast", ".", "Node", ",", "ctx", "*", "Context", ",", "required", "string", ")", "*", "ast", ".", "CompositeLit", "{", "if", "complit", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "CompositeLit", ")", ";", "ok", "{", "typeOf", ":=", "ctx", ".", "Info", ".", "TypeOf", "(", "complit", ")", "\n", "if", "typeOf", ".", "String", "(", ")", "==", "required", "{", "return", "complit", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MatchCompLit will match an ast.CompositeLit based on the supplied type
[ "MatchCompLit", "will", "match", "an", "ast", ".", "CompositeLit", "based", "on", "the", "supplied", "type" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L86-L94
train
securego/gosec
helpers.go
GetInt
func GetInt(n ast.Node) (int64, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.INT { return strconv.ParseInt(node.Value, 0, 64) } return 0, fmt.Errorf("Unexpected AST node type: %T", n) }
go
func GetInt(n ast.Node) (int64, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.INT { return strconv.ParseInt(node.Value, 0, 64) } return 0, fmt.Errorf("Unexpected AST node type: %T", n) }
[ "func", "GetInt", "(", "n", "ast", ".", "Node", ")", "(", "int64", ",", "error", ")", "{", "if", "node", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "&&", "node", ".", "Kind", "==", "token", ".", "INT", "{", "return", "strconv", ".", "ParseInt", "(", "node", ".", "Value", ",", "0", ",", "64", ")", "\n", "}", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}" ]
// GetInt will read and return an integer value from an ast.BasicLit
[ "GetInt", "will", "read", "and", "return", "an", "integer", "value", "from", "an", "ast", ".", "BasicLit" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L97-L102
train
securego/gosec
helpers.go
GetFloat
func GetFloat(n ast.Node) (float64, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.FLOAT { return strconv.ParseFloat(node.Value, 64) } return 0.0, fmt.Errorf("Unexpected AST node type: %T", n) }
go
func GetFloat(n ast.Node) (float64, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.FLOAT { return strconv.ParseFloat(node.Value, 64) } return 0.0, fmt.Errorf("Unexpected AST node type: %T", n) }
[ "func", "GetFloat", "(", "n", "ast", ".", "Node", ")", "(", "float64", ",", "error", ")", "{", "if", "node", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "&&", "node", ".", "Kind", "==", "token", ".", "FLOAT", "{", "return", "strconv", ".", "ParseFloat", "(", "node", ".", "Value", ",", "64", ")", "\n", "}", "\n", "return", "0.0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}" ]
// GetFloat will read and return a float value from an ast.BasicLit
[ "GetFloat", "will", "read", "and", "return", "a", "float", "value", "from", "an", "ast", ".", "BasicLit" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L105-L110
train
securego/gosec
helpers.go
GetChar
func GetChar(n ast.Node) (byte, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.CHAR { return node.Value[0], nil } return 0, fmt.Errorf("Unexpected AST node type: %T", n) }
go
func GetChar(n ast.Node) (byte, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.CHAR { return node.Value[0], nil } return 0, fmt.Errorf("Unexpected AST node type: %T", n) }
[ "func", "GetChar", "(", "n", "ast", ".", "Node", ")", "(", "byte", ",", "error", ")", "{", "if", "node", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "&&", "node", ".", "Kind", "==", "token", ".", "CHAR", "{", "return", "node", ".", "Value", "[", "0", "]", ",", "nil", "\n", "}", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}" ]
// GetChar will read and return a char value from an ast.BasicLit
[ "GetChar", "will", "read", "and", "return", "a", "char", "value", "from", "an", "ast", ".", "BasicLit" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L113-L118
train
securego/gosec
helpers.go
GetString
func GetString(n ast.Node) (string, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.STRING { return strconv.Unquote(node.Value) } return "", fmt.Errorf("Unexpected AST node type: %T", n) }
go
func GetString(n ast.Node) (string, error) { if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.STRING { return strconv.Unquote(node.Value) } return "", fmt.Errorf("Unexpected AST node type: %T", n) }
[ "func", "GetString", "(", "n", "ast", ".", "Node", ")", "(", "string", ",", "error", ")", "{", "if", "node", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "&&", "node", ".", "Kind", "==", "token", ".", "STRING", "{", "return", "strconv", ".", "Unquote", "(", "node", ".", "Value", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}" ]
// GetString will read and return a string value from an ast.BasicLit
[ "GetString", "will", "read", "and", "return", "a", "string", "value", "from", "an", "ast", ".", "BasicLit" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L121-L126
train
securego/gosec
helpers.go
GetCallObject
func GetCallObject(n ast.Node, ctx *Context) (*ast.CallExpr, types.Object) { switch node := n.(type) { case *ast.CallExpr: switch fn := node.Fun.(type) { case *ast.Ident: return node, ctx.Info.Uses[fn] case *ast.SelectorExpr: return node, ctx.Info.Uses[fn.Sel] } } return nil, nil }
go
func GetCallObject(n ast.Node, ctx *Context) (*ast.CallExpr, types.Object) { switch node := n.(type) { case *ast.CallExpr: switch fn := node.Fun.(type) { case *ast.Ident: return node, ctx.Info.Uses[fn] case *ast.SelectorExpr: return node, ctx.Info.Uses[fn.Sel] } } return nil, nil }
[ "func", "GetCallObject", "(", "n", "ast", ".", "Node", ",", "ctx", "*", "Context", ")", "(", "*", "ast", ".", "CallExpr", ",", "types", ".", "Object", ")", "{", "switch", "node", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "CallExpr", ":", "switch", "fn", ":=", "node", ".", "Fun", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "Ident", ":", "return", "node", ",", "ctx", ".", "Info", ".", "Uses", "[", "fn", "]", "\n", "case", "*", "ast", ".", "SelectorExpr", ":", "return", "node", ",", "ctx", ".", "Info", ".", "Uses", "[", "fn", ".", "Sel", "]", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// GetCallObject returns the object and call expression and associated // object for a given AST node. nil, nil will be returned if the // object cannot be resolved.
[ "GetCallObject", "returns", "the", "object", "and", "call", "expression", "and", "associated", "object", "for", "a", "given", "AST", "node", ".", "nil", "nil", "will", "be", "returned", "if", "the", "object", "cannot", "be", "resolved", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L131-L142
train
securego/gosec
helpers.go
GetCallInfo
func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) { switch node := n.(type) { case *ast.CallExpr: switch fn := node.Fun.(type) { case *ast.SelectorExpr: switch expr := fn.X.(type) { case *ast.Ident: if expr.Obj != nil && expr.Obj.Kind == ast.Var { t := ctx.Info.TypeOf(expr) if t != nil { return t.String(), fn.Sel.Name, nil } return "undefined", fn.Sel.Name, fmt.Errorf("missing type info") } return expr.Name, fn.Sel.Name, nil } case *ast.Ident: return ctx.Pkg.Name(), fn.Name, nil } } return "", "", fmt.Errorf("unable to determine call info") }
go
func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) { switch node := n.(type) { case *ast.CallExpr: switch fn := node.Fun.(type) { case *ast.SelectorExpr: switch expr := fn.X.(type) { case *ast.Ident: if expr.Obj != nil && expr.Obj.Kind == ast.Var { t := ctx.Info.TypeOf(expr) if t != nil { return t.String(), fn.Sel.Name, nil } return "undefined", fn.Sel.Name, fmt.Errorf("missing type info") } return expr.Name, fn.Sel.Name, nil } case *ast.Ident: return ctx.Pkg.Name(), fn.Name, nil } } return "", "", fmt.Errorf("unable to determine call info") }
[ "func", "GetCallInfo", "(", "n", "ast", ".", "Node", ",", "ctx", "*", "Context", ")", "(", "string", ",", "string", ",", "error", ")", "{", "switch", "node", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "CallExpr", ":", "switch", "fn", ":=", "node", ".", "Fun", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "SelectorExpr", ":", "switch", "expr", ":=", "fn", ".", "X", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "Ident", ":", "if", "expr", ".", "Obj", "!=", "nil", "&&", "expr", ".", "Obj", ".", "Kind", "==", "ast", ".", "Var", "{", "t", ":=", "ctx", ".", "Info", ".", "TypeOf", "(", "expr", ")", "\n", "if", "t", "!=", "nil", "{", "return", "t", ".", "String", "(", ")", ",", "fn", ".", "Sel", ".", "Name", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "fn", ".", "Sel", ".", "Name", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "expr", ".", "Name", ",", "fn", ".", "Sel", ".", "Name", ",", "nil", "\n", "}", "\n", "case", "*", "ast", ".", "Ident", ":", "return", "ctx", ".", "Pkg", ".", "Name", "(", ")", ",", "fn", ".", "Name", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// GetCallInfo returns the package or type and name associated with a // call expression.
[ "GetCallInfo", "returns", "the", "package", "or", "type", "and", "name", "associated", "with", "a", "call", "expression", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L146-L167
train
securego/gosec
helpers.go
GetCallStringArgsValues
func GetCallStringArgsValues(n ast.Node, ctx *Context) []string { values := []string{} switch node := n.(type) { case *ast.CallExpr: for _, arg := range node.Args { switch param := arg.(type) { case *ast.BasicLit: value, err := GetString(param) if err == nil { values = append(values, value) } case *ast.Ident: values = append(values, GetIdentStringValues(param)...) } } } return values }
go
func GetCallStringArgsValues(n ast.Node, ctx *Context) []string { values := []string{} switch node := n.(type) { case *ast.CallExpr: for _, arg := range node.Args { switch param := arg.(type) { case *ast.BasicLit: value, err := GetString(param) if err == nil { values = append(values, value) } case *ast.Ident: values = append(values, GetIdentStringValues(param)...) } } } return values }
[ "func", "GetCallStringArgsValues", "(", "n", "ast", ".", "Node", ",", "ctx", "*", "Context", ")", "[", "]", "string", "{", "values", ":=", "[", "]", "string", "{", "}", "\n", "switch", "node", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "CallExpr", ":", "for", "_", ",", "arg", ":=", "range", "node", ".", "Args", "{", "switch", "param", ":=", "arg", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "BasicLit", ":", "value", ",", "err", ":=", "GetString", "(", "param", ")", "\n", "if", "err", "==", "nil", "{", "values", "=", "append", "(", "values", ",", "value", ")", "\n", "}", "\n", "case", "*", "ast", ".", "Ident", ":", "values", "=", "append", "(", "values", ",", "GetIdentStringValues", "(", "param", ")", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "values", "\n", "}" ]
// GetCallStringArgsValues returns the values of strings arguments if they can be resolved
[ "GetCallStringArgsValues", "returns", "the", "values", "of", "strings", "arguments", "if", "they", "can", "be", "resolved" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L170-L187
train
securego/gosec
helpers.go
GetIdentStringValues
func GetIdentStringValues(ident *ast.Ident) []string { values := []string{} obj := ident.Obj if obj != nil { switch decl := obj.Decl.(type) { case *ast.ValueSpec: for _, v := range decl.Values { value, err := GetString(v) if err == nil { values = append(values, value) } } case *ast.AssignStmt: for _, v := range decl.Rhs { value, err := GetString(v) if err == nil { values = append(values, value) } } } } return values }
go
func GetIdentStringValues(ident *ast.Ident) []string { values := []string{} obj := ident.Obj if obj != nil { switch decl := obj.Decl.(type) { case *ast.ValueSpec: for _, v := range decl.Values { value, err := GetString(v) if err == nil { values = append(values, value) } } case *ast.AssignStmt: for _, v := range decl.Rhs { value, err := GetString(v) if err == nil { values = append(values, value) } } } } return values }
[ "func", "GetIdentStringValues", "(", "ident", "*", "ast", ".", "Ident", ")", "[", "]", "string", "{", "values", ":=", "[", "]", "string", "{", "}", "\n", "obj", ":=", "ident", ".", "Obj", "\n", "if", "obj", "!=", "nil", "{", "switch", "decl", ":=", "obj", ".", "Decl", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "ValueSpec", ":", "for", "_", ",", "v", ":=", "range", "decl", ".", "Values", "{", "value", ",", "err", ":=", "GetString", "(", "v", ")", "\n", "if", "err", "==", "nil", "{", "values", "=", "append", "(", "values", ",", "value", ")", "\n", "}", "\n", "}", "\n", "case", "*", "ast", ".", "AssignStmt", ":", "for", "_", ",", "v", ":=", "range", "decl", ".", "Rhs", "{", "value", ",", "err", ":=", "GetString", "(", "v", ")", "\n", "if", "err", "==", "nil", "{", "values", "=", "append", "(", "values", ",", "value", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}", "\n", "return", "values", "\n", "}" ]
// GetIdentStringValues return the string values of an Ident if they can be resolved
[ "GetIdentStringValues", "return", "the", "string", "values", "of", "an", "Ident", "if", "they", "can", "be", "resolved" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L190-L213
train
securego/gosec
helpers.go
GetImportedName
func GetImportedName(path string, ctx *Context) (string, bool) { importName, imported := ctx.Imports.Imported[path] if !imported { return "", false } if _, initonly := ctx.Imports.InitOnly[path]; initonly { return "", false } if alias, ok := ctx.Imports.Aliased[path]; ok { importName = alias } return importName, true }
go
func GetImportedName(path string, ctx *Context) (string, bool) { importName, imported := ctx.Imports.Imported[path] if !imported { return "", false } if _, initonly := ctx.Imports.InitOnly[path]; initonly { return "", false } if alias, ok := ctx.Imports.Aliased[path]; ok { importName = alias } return importName, true }
[ "func", "GetImportedName", "(", "path", "string", ",", "ctx", "*", "Context", ")", "(", "string", ",", "bool", ")", "{", "importName", ",", "imported", ":=", "ctx", ".", "Imports", ".", "Imported", "[", "path", "]", "\n", "if", "!", "imported", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n\n", "if", "_", ",", "initonly", ":=", "ctx", ".", "Imports", ".", "InitOnly", "[", "path", "]", ";", "initonly", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n\n", "if", "alias", ",", "ok", ":=", "ctx", ".", "Imports", ".", "Aliased", "[", "path", "]", ";", "ok", "{", "importName", "=", "alias", "\n", "}", "\n", "return", "importName", ",", "true", "\n", "}" ]
// GetImportedName returns the name used for the package within the // code. It will resolve aliases and ignores initialization only imports.
[ "GetImportedName", "returns", "the", "name", "used", "for", "the", "package", "within", "the", "code", ".", "It", "will", "resolve", "aliases", "and", "ignores", "initialization", "only", "imports", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L217-L231
train
securego/gosec
helpers.go
GetImportPath
func GetImportPath(name string, ctx *Context) (string, bool) { for path := range ctx.Imports.Imported { if imported, ok := GetImportedName(path, ctx); ok && imported == name { return path, true } } return "", false }
go
func GetImportPath(name string, ctx *Context) (string, bool) { for path := range ctx.Imports.Imported { if imported, ok := GetImportedName(path, ctx); ok && imported == name { return path, true } } return "", false }
[ "func", "GetImportPath", "(", "name", "string", ",", "ctx", "*", "Context", ")", "(", "string", ",", "bool", ")", "{", "for", "path", ":=", "range", "ctx", ".", "Imports", ".", "Imported", "{", "if", "imported", ",", "ok", ":=", "GetImportedName", "(", "path", ",", "ctx", ")", ";", "ok", "&&", "imported", "==", "name", "{", "return", "path", ",", "true", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "false", "\n", "}" ]
// GetImportPath resolves the full import path of an identifier based on // the imports in the current context.
[ "GetImportPath", "resolves", "the", "full", "import", "path", "of", "an", "identifier", "based", "on", "the", "imports", "in", "the", "current", "context", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L235-L242
train
securego/gosec
helpers.go
GetLocation
func GetLocation(n ast.Node, ctx *Context) (string, int) { fobj := ctx.FileSet.File(n.Pos()) return fobj.Name(), fobj.Line(n.Pos()) }
go
func GetLocation(n ast.Node, ctx *Context) (string, int) { fobj := ctx.FileSet.File(n.Pos()) return fobj.Name(), fobj.Line(n.Pos()) }
[ "func", "GetLocation", "(", "n", "ast", ".", "Node", ",", "ctx", "*", "Context", ")", "(", "string", ",", "int", ")", "{", "fobj", ":=", "ctx", ".", "FileSet", ".", "File", "(", "n", ".", "Pos", "(", ")", ")", "\n", "return", "fobj", ".", "Name", "(", ")", ",", "fobj", ".", "Line", "(", "n", ".", "Pos", "(", ")", ")", "\n", "}" ]
// GetLocation returns the filename and line number of an ast.Node
[ "GetLocation", "returns", "the", "filename", "and", "line", "number", "of", "an", "ast", ".", "Node" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L245-L248
train
securego/gosec
helpers.go
Gopath
func Gopath() []string { defaultGoPath := runtime.GOROOT() if u, err := user.Current(); err == nil { defaultGoPath = filepath.Join(u.HomeDir, "go") } path := Getenv("GOPATH", defaultGoPath) paths := strings.Split(path, string(os.PathListSeparator)) for idx, path := range paths { if abs, err := filepath.Abs(path); err == nil { paths[idx] = abs } } return paths }
go
func Gopath() []string { defaultGoPath := runtime.GOROOT() if u, err := user.Current(); err == nil { defaultGoPath = filepath.Join(u.HomeDir, "go") } path := Getenv("GOPATH", defaultGoPath) paths := strings.Split(path, string(os.PathListSeparator)) for idx, path := range paths { if abs, err := filepath.Abs(path); err == nil { paths[idx] = abs } } return paths }
[ "func", "Gopath", "(", ")", "[", "]", "string", "{", "defaultGoPath", ":=", "runtime", ".", "GOROOT", "(", ")", "\n", "if", "u", ",", "err", ":=", "user", ".", "Current", "(", ")", ";", "err", "==", "nil", "{", "defaultGoPath", "=", "filepath", ".", "Join", "(", "u", ".", "HomeDir", ",", "\"", "\"", ")", "\n", "}", "\n", "path", ":=", "Getenv", "(", "\"", "\"", ",", "defaultGoPath", ")", "\n", "paths", ":=", "strings", ".", "Split", "(", "path", ",", "string", "(", "os", ".", "PathListSeparator", ")", ")", "\n", "for", "idx", ",", "path", ":=", "range", "paths", "{", "if", "abs", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", ";", "err", "==", "nil", "{", "paths", "[", "idx", "]", "=", "abs", "\n", "}", "\n", "}", "\n", "return", "paths", "\n", "}" ]
// Gopath returns all GOPATHs
[ "Gopath", "returns", "all", "GOPATHs" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L251-L264
train
securego/gosec
helpers.go
Getenv
func Getenv(key, userDefault string) string { if val := os.Getenv(key); val != "" { return val } return userDefault }
go
func Getenv(key, userDefault string) string { if val := os.Getenv(key); val != "" { return val } return userDefault }
[ "func", "Getenv", "(", "key", ",", "userDefault", "string", ")", "string", "{", "if", "val", ":=", "os", ".", "Getenv", "(", "key", ")", ";", "val", "!=", "\"", "\"", "{", "return", "val", "\n", "}", "\n", "return", "userDefault", "\n", "}" ]
// Getenv returns the values of the environment variable, otherwise //returns the default if variable is not set
[ "Getenv", "returns", "the", "values", "of", "the", "environment", "variable", "otherwise", "returns", "the", "default", "if", "variable", "is", "not", "set" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L268-L273
train
securego/gosec
helpers.go
GetPkgRelativePath
func GetPkgRelativePath(path string) (string, error) { abspath, err := filepath.Abs(path) if err != nil { abspath = path } if strings.HasSuffix(abspath, ".go") { abspath = filepath.Dir(abspath) } for _, base := range Gopath() { projectRoot := filepath.FromSlash(fmt.Sprintf("%s/src/", base)) if strings.HasPrefix(abspath, projectRoot) { return strings.TrimPrefix(abspath, projectRoot), nil } } return "", errors.New("no project relative path found") }
go
func GetPkgRelativePath(path string) (string, error) { abspath, err := filepath.Abs(path) if err != nil { abspath = path } if strings.HasSuffix(abspath, ".go") { abspath = filepath.Dir(abspath) } for _, base := range Gopath() { projectRoot := filepath.FromSlash(fmt.Sprintf("%s/src/", base)) if strings.HasPrefix(abspath, projectRoot) { return strings.TrimPrefix(abspath, projectRoot), nil } } return "", errors.New("no project relative path found") }
[ "func", "GetPkgRelativePath", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "abspath", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "abspath", "=", "path", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "abspath", ",", "\"", "\"", ")", "{", "abspath", "=", "filepath", ".", "Dir", "(", "abspath", ")", "\n", "}", "\n", "for", "_", ",", "base", ":=", "range", "Gopath", "(", ")", "{", "projectRoot", ":=", "filepath", ".", "FromSlash", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "base", ")", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "abspath", ",", "projectRoot", ")", "{", "return", "strings", ".", "TrimPrefix", "(", "abspath", ",", "projectRoot", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// GetPkgRelativePath returns the Go relative relative path derived // form the given path
[ "GetPkgRelativePath", "returns", "the", "Go", "relative", "relative", "path", "derived", "form", "the", "given", "path" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L277-L292
train
securego/gosec
helpers.go
GetPkgAbsPath
func GetPkgAbsPath(pkgPath string) (string, error) { absPath, err := filepath.Abs(pkgPath) if err != nil { return "", err } if _, err := os.Stat(absPath); os.IsNotExist(err) { return "", errors.New("no project absolute path found") } return absPath, nil }
go
func GetPkgAbsPath(pkgPath string) (string, error) { absPath, err := filepath.Abs(pkgPath) if err != nil { return "", err } if _, err := os.Stat(absPath); os.IsNotExist(err) { return "", errors.New("no project absolute path found") } return absPath, nil }
[ "func", "GetPkgAbsPath", "(", "pkgPath", "string", ")", "(", "string", ",", "error", ")", "{", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "pkgPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "absPath", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "absPath", ",", "nil", "\n", "}" ]
// GetPkgAbsPath returns the Go package absolute path derived from // the given path
[ "GetPkgAbsPath", "returns", "the", "Go", "package", "absolute", "path", "derived", "from", "the", "given", "path" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L296-L305
train
securego/gosec
helpers.go
ConcatString
func ConcatString(n *ast.BinaryExpr) (string, bool) { var s string // sub expressions are found in X object, Y object is always last BasicLit if rightOperand, ok := n.Y.(*ast.BasicLit); ok { if str, err := GetString(rightOperand); err == nil { s = str + s } } else { return "", false } if leftOperand, ok := n.X.(*ast.BinaryExpr); ok { if recursion, ok := ConcatString(leftOperand); ok { s = recursion + s } } else if leftOperand, ok := n.X.(*ast.BasicLit); ok { if str, err := GetString(leftOperand); err == nil { s = str + s } } else { return "", false } return s, true }
go
func ConcatString(n *ast.BinaryExpr) (string, bool) { var s string // sub expressions are found in X object, Y object is always last BasicLit if rightOperand, ok := n.Y.(*ast.BasicLit); ok { if str, err := GetString(rightOperand); err == nil { s = str + s } } else { return "", false } if leftOperand, ok := n.X.(*ast.BinaryExpr); ok { if recursion, ok := ConcatString(leftOperand); ok { s = recursion + s } } else if leftOperand, ok := n.X.(*ast.BasicLit); ok { if str, err := GetString(leftOperand); err == nil { s = str + s } } else { return "", false } return s, true }
[ "func", "ConcatString", "(", "n", "*", "ast", ".", "BinaryExpr", ")", "(", "string", ",", "bool", ")", "{", "var", "s", "string", "\n", "// sub expressions are found in X object, Y object is always last BasicLit", "if", "rightOperand", ",", "ok", ":=", "n", ".", "Y", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "{", "if", "str", ",", "err", ":=", "GetString", "(", "rightOperand", ")", ";", "err", "==", "nil", "{", "s", "=", "str", "+", "s", "\n", "}", "\n", "}", "else", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "if", "leftOperand", ",", "ok", ":=", "n", ".", "X", ".", "(", "*", "ast", ".", "BinaryExpr", ")", ";", "ok", "{", "if", "recursion", ",", "ok", ":=", "ConcatString", "(", "leftOperand", ")", ";", "ok", "{", "s", "=", "recursion", "+", "s", "\n", "}", "\n", "}", "else", "if", "leftOperand", ",", "ok", ":=", "n", ".", "X", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "{", "if", "str", ",", "err", ":=", "GetString", "(", "leftOperand", ")", ";", "err", "==", "nil", "{", "s", "=", "str", "+", "s", "\n", "}", "\n", "}", "else", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "return", "s", ",", "true", "\n", "}" ]
// ConcatString recursively concatenates strings from a binary expression
[ "ConcatString", "recursively", "concatenates", "strings", "from", "a", "binary", "expression" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L308-L330
train
securego/gosec
helpers.go
FindVarIdentities
func FindVarIdentities(n *ast.BinaryExpr, c *Context) ([]*ast.Ident, bool) { identities := []*ast.Ident{} // sub expressions are found in X object, Y object is always the last term if rightOperand, ok := n.Y.(*ast.Ident); ok { obj := c.Info.ObjectOf(rightOperand) if _, ok := obj.(*types.Var); ok && !TryResolve(rightOperand, c) { identities = append(identities, rightOperand) } } if leftOperand, ok := n.X.(*ast.BinaryExpr); ok { if leftIdentities, ok := FindVarIdentities(leftOperand, c); ok { identities = append(identities, leftIdentities...) } } else { if leftOperand, ok := n.X.(*ast.Ident); ok { obj := c.Info.ObjectOf(leftOperand) if _, ok := obj.(*types.Var); ok && !TryResolve(leftOperand, c) { identities = append(identities, leftOperand) } } } if len(identities) > 0 { return identities, true } // if nil or error, return false return nil, false }
go
func FindVarIdentities(n *ast.BinaryExpr, c *Context) ([]*ast.Ident, bool) { identities := []*ast.Ident{} // sub expressions are found in X object, Y object is always the last term if rightOperand, ok := n.Y.(*ast.Ident); ok { obj := c.Info.ObjectOf(rightOperand) if _, ok := obj.(*types.Var); ok && !TryResolve(rightOperand, c) { identities = append(identities, rightOperand) } } if leftOperand, ok := n.X.(*ast.BinaryExpr); ok { if leftIdentities, ok := FindVarIdentities(leftOperand, c); ok { identities = append(identities, leftIdentities...) } } else { if leftOperand, ok := n.X.(*ast.Ident); ok { obj := c.Info.ObjectOf(leftOperand) if _, ok := obj.(*types.Var); ok && !TryResolve(leftOperand, c) { identities = append(identities, leftOperand) } } } if len(identities) > 0 { return identities, true } // if nil or error, return false return nil, false }
[ "func", "FindVarIdentities", "(", "n", "*", "ast", ".", "BinaryExpr", ",", "c", "*", "Context", ")", "(", "[", "]", "*", "ast", ".", "Ident", ",", "bool", ")", "{", "identities", ":=", "[", "]", "*", "ast", ".", "Ident", "{", "}", "\n", "// sub expressions are found in X object, Y object is always the last term", "if", "rightOperand", ",", "ok", ":=", "n", ".", "Y", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "obj", ":=", "c", ".", "Info", ".", "ObjectOf", "(", "rightOperand", ")", "\n", "if", "_", ",", "ok", ":=", "obj", ".", "(", "*", "types", ".", "Var", ")", ";", "ok", "&&", "!", "TryResolve", "(", "rightOperand", ",", "c", ")", "{", "identities", "=", "append", "(", "identities", ",", "rightOperand", ")", "\n", "}", "\n", "}", "\n", "if", "leftOperand", ",", "ok", ":=", "n", ".", "X", ".", "(", "*", "ast", ".", "BinaryExpr", ")", ";", "ok", "{", "if", "leftIdentities", ",", "ok", ":=", "FindVarIdentities", "(", "leftOperand", ",", "c", ")", ";", "ok", "{", "identities", "=", "append", "(", "identities", ",", "leftIdentities", "...", ")", "\n", "}", "\n", "}", "else", "{", "if", "leftOperand", ",", "ok", ":=", "n", ".", "X", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "obj", ":=", "c", ".", "Info", ".", "ObjectOf", "(", "leftOperand", ")", "\n", "if", "_", ",", "ok", ":=", "obj", ".", "(", "*", "types", ".", "Var", ")", ";", "ok", "&&", "!", "TryResolve", "(", "leftOperand", ",", "c", ")", "{", "identities", "=", "append", "(", "identities", ",", "leftOperand", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "identities", ")", ">", "0", "{", "return", "identities", ",", "true", "\n", "}", "\n", "// if nil or error, return false", "return", "nil", ",", "false", "\n", "}" ]
// FindVarIdentities returns array of all variable identities in a given binary expression
[ "FindVarIdentities", "returns", "array", "of", "all", "variable", "identities", "in", "a", "given", "binary", "expression" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L333-L360
train
securego/gosec
helpers.go
PackagePaths
func PackagePaths(root string, exclude *regexp.Regexp) ([]string, error) { if strings.HasSuffix(root, "...") { root = root[0 : len(root)-3] } else { return []string{root}, nil } paths := map[string]bool{} err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error { if filepath.Ext(path) == ".go" { path = filepath.Dir(path) if exclude != nil && exclude.MatchString(path) { return nil } paths[path] = true } return nil }) if err != nil { return []string{}, err } result := []string{} for path := range paths { result = append(result, path) } return result, nil }
go
func PackagePaths(root string, exclude *regexp.Regexp) ([]string, error) { if strings.HasSuffix(root, "...") { root = root[0 : len(root)-3] } else { return []string{root}, nil } paths := map[string]bool{} err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error { if filepath.Ext(path) == ".go" { path = filepath.Dir(path) if exclude != nil && exclude.MatchString(path) { return nil } paths[path] = true } return nil }) if err != nil { return []string{}, err } result := []string{} for path := range paths { result = append(result, path) } return result, nil }
[ "func", "PackagePaths", "(", "root", "string", ",", "exclude", "*", "regexp", ".", "Regexp", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "strings", ".", "HasSuffix", "(", "root", ",", "\"", "\"", ")", "{", "root", "=", "root", "[", "0", ":", "len", "(", "root", ")", "-", "3", "]", "\n", "}", "else", "{", "return", "[", "]", "string", "{", "root", "}", ",", "nil", "\n", "}", "\n", "paths", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "err", ":=", "filepath", ".", "Walk", "(", "root", ",", "func", "(", "path", "string", ",", "f", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "filepath", ".", "Ext", "(", "path", ")", "==", "\"", "\"", "{", "path", "=", "filepath", ".", "Dir", "(", "path", ")", "\n", "if", "exclude", "!=", "nil", "&&", "exclude", ".", "MatchString", "(", "path", ")", "{", "return", "nil", "\n", "}", "\n", "paths", "[", "path", "]", "=", "true", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "string", "{", "}", ",", "err", "\n", "}", "\n\n", "result", ":=", "[", "]", "string", "{", "}", "\n", "for", "path", ":=", "range", "paths", "{", "result", "=", "append", "(", "result", ",", "path", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// PackagePaths returns a slice with all packages path at given root directory
[ "PackagePaths", "returns", "a", "slice", "with", "all", "packages", "path", "at", "given", "root", "directory" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L363-L389
train
securego/gosec
rules/tls_config.go
NewModernTLSCheck
func NewModernTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &insecureConfigTLS{ MetaData: gosec.MetaData{ID: id}, requiredType: "crypto/tls.Config", MinVersion: 0x0303, MaxVersion: 0x0303, goodCiphers: []string{ "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", }, }, []ast.Node{(*ast.CompositeLit)(nil)} }
go
func NewModernTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &insecureConfigTLS{ MetaData: gosec.MetaData{ID: id}, requiredType: "crypto/tls.Config", MinVersion: 0x0303, MaxVersion: 0x0303, goodCiphers: []string{ "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", }, }, []ast.Node{(*ast.CompositeLit)(nil)} }
[ "func", "NewModernTLSCheck", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "return", "&", "insecureConfigTLS", "{", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", "}", ",", "requiredType", ":", "\"", "\"", ",", "MinVersion", ":", "0x0303", ",", "MaxVersion", ":", "0x0303", ",", "goodCiphers", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CompositeLit", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewModernTLSCheck creates a check for Modern TLS ciphers // DO NOT EDIT - generated by tlsconfig tool
[ "NewModernTLSCheck", "creates", "a", "check", "for", "Modern", "TLS", "ciphers", "DO", "NOT", "EDIT", "-", "generated", "by", "tlsconfig", "tool" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/tls_config.go#L11-L30
train
securego/gosec
rule.go
Register
func (r RuleSet) Register(rule Rule, nodes ...ast.Node) { for _, n := range nodes { t := reflect.TypeOf(n) if rules, ok := r[t]; ok { r[t] = append(rules, rule) } else { r[t] = []Rule{rule} } } }
go
func (r RuleSet) Register(rule Rule, nodes ...ast.Node) { for _, n := range nodes { t := reflect.TypeOf(n) if rules, ok := r[t]; ok { r[t] = append(rules, rule) } else { r[t] = []Rule{rule} } } }
[ "func", "(", "r", "RuleSet", ")", "Register", "(", "rule", "Rule", ",", "nodes", "...", "ast", ".", "Node", ")", "{", "for", "_", ",", "n", ":=", "range", "nodes", "{", "t", ":=", "reflect", ".", "TypeOf", "(", "n", ")", "\n", "if", "rules", ",", "ok", ":=", "r", "[", "t", "]", ";", "ok", "{", "r", "[", "t", "]", "=", "append", "(", "rules", ",", "rule", ")", "\n", "}", "else", "{", "r", "[", "t", "]", "=", "[", "]", "Rule", "{", "rule", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Register adds a trigger for the supplied rule for the the // specified ast nodes.
[ "Register", "adds", "a", "trigger", "for", "the", "supplied", "rule", "for", "the", "the", "specified", "ast", "nodes", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rule.go#L41-L50
train
securego/gosec
rule.go
RegisteredFor
func (r RuleSet) RegisteredFor(n ast.Node) []Rule { if rules, found := r[reflect.TypeOf(n)]; found { return rules } return []Rule{} }
go
func (r RuleSet) RegisteredFor(n ast.Node) []Rule { if rules, found := r[reflect.TypeOf(n)]; found { return rules } return []Rule{} }
[ "func", "(", "r", "RuleSet", ")", "RegisteredFor", "(", "n", "ast", ".", "Node", ")", "[", "]", "Rule", "{", "if", "rules", ",", "found", ":=", "r", "[", "reflect", ".", "TypeOf", "(", "n", ")", "]", ";", "found", "{", "return", "rules", "\n", "}", "\n", "return", "[", "]", "Rule", "{", "}", "\n", "}" ]
// RegisteredFor will return all rules that are registered for a // specified ast node.
[ "RegisteredFor", "will", "return", "all", "rules", "that", "are", "registered", "for", "a", "specified", "ast", "node", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rule.go#L54-L59
train
securego/gosec
rules/sql.go
MatchPatterns
func (s *sqlStatement) MatchPatterns(str string) bool { for _, pattern := range s.patterns { if !pattern.MatchString(str) { return false } } return true }
go
func (s *sqlStatement) MatchPatterns(str string) bool { for _, pattern := range s.patterns { if !pattern.MatchString(str) { return false } } return true }
[ "func", "(", "s", "*", "sqlStatement", ")", "MatchPatterns", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "pattern", ":=", "range", "s", ".", "patterns", "{", "if", "!", "pattern", ".", "MatchString", "(", "str", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// See if the string matches the patterns for the statement.
[ "See", "if", "the", "string", "matches", "the", "patterns", "for", "the", "statement", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L36-L43
train
securego/gosec
rules/sql.go
checkObject
func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool { if n.Obj != nil { return n.Obj.Kind != ast.Var && n.Obj.Kind != ast.Fun } // Try to resolve unresolved identifiers using other files in same package for _, file := range c.PkgFiles { if node, ok := file.Scope.Objects[n.String()]; ok { return node.Kind != ast.Var && node.Kind != ast.Fun } } return false }
go
func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool { if n.Obj != nil { return n.Obj.Kind != ast.Var && n.Obj.Kind != ast.Fun } // Try to resolve unresolved identifiers using other files in same package for _, file := range c.PkgFiles { if node, ok := file.Scope.Objects[n.String()]; ok { return node.Kind != ast.Var && node.Kind != ast.Fun } } return false }
[ "func", "(", "s", "*", "sqlStrConcat", ")", "checkObject", "(", "n", "*", "ast", ".", "Ident", ",", "c", "*", "gosec", ".", "Context", ")", "bool", "{", "if", "n", ".", "Obj", "!=", "nil", "{", "return", "n", ".", "Obj", ".", "Kind", "!=", "ast", ".", "Var", "&&", "n", ".", "Obj", ".", "Kind", "!=", "ast", ".", "Fun", "\n", "}", "\n\n", "// Try to resolve unresolved identifiers using other files in same package", "for", "_", ",", "file", ":=", "range", "c", ".", "PkgFiles", "{", "if", "node", ",", "ok", ":=", "file", ".", "Scope", ".", "Objects", "[", "n", ".", "String", "(", ")", "]", ";", "ok", "{", "return", "node", ".", "Kind", "!=", "ast", ".", "Var", "&&", "node", ".", "Kind", "!=", "ast", ".", "Fun", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// see if we can figure out what it is
[ "see", "if", "we", "can", "figure", "out", "what", "it", "is" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L54-L66
train
securego/gosec
rules/sql.go
NewSQLStrConcat
func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &sqlStrConcat{ sqlStatement: sqlStatement{ patterns: []*regexp.Regexp{ regexp.MustCompile(`(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) `), }, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "SQL string concatenation", }, }, }, []ast.Node{(*ast.BinaryExpr)(nil)} }
go
func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &sqlStrConcat{ sqlStatement: sqlStatement{ patterns: []*regexp.Regexp{ regexp.MustCompile(`(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) `), }, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "SQL string concatenation", }, }, }, []ast.Node{(*ast.BinaryExpr)(nil)} }
[ "func", "NewSQLStrConcat", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "return", "&", "sqlStrConcat", "{", "sqlStatement", ":", "sqlStatement", "{", "patterns", ":", "[", "]", "*", "regexp", ".", "Regexp", "{", "regexp", ".", "MustCompile", "(", "`(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) `", ")", ",", "}", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "High", ",", "What", ":", "\"", "\"", ",", "}", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "BinaryExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewSQLStrConcat looks for cases where we are building SQL strings via concatenation
[ "NewSQLStrConcat", "looks", "for", "cases", "where", "we", "are", "building", "SQL", "strings", "via", "concatenation" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L90-L104
train
securego/gosec
rules/sql.go
NewSQLStrFormat
func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { rule := &sqlStrFormat{ calls: gosec.NewCallList(), noIssue: gosec.NewCallList(), noIssueQuoted: gosec.NewCallList(), sqlStatement: sqlStatement{ patterns: []*regexp.Regexp{ regexp.MustCompile("(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) "), regexp.MustCompile("%[^bdoxXfFp]"), }, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "SQL string formatting", }, }, } rule.calls.AddAll("fmt", "Sprint", "Sprintf", "Sprintln", "Fprintf") rule.noIssue.AddAll("os", "Stdout", "Stderr") rule.noIssueQuoted.Add("github.com/lib/pq", "QuoteIdentifier") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { rule := &sqlStrFormat{ calls: gosec.NewCallList(), noIssue: gosec.NewCallList(), noIssueQuoted: gosec.NewCallList(), sqlStatement: sqlStatement{ patterns: []*regexp.Regexp{ regexp.MustCompile("(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) "), regexp.MustCompile("%[^bdoxXfFp]"), }, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "SQL string formatting", }, }, } rule.calls.AddAll("fmt", "Sprint", "Sprintf", "Sprintln", "Fprintf") rule.noIssue.AddAll("os", "Stdout", "Stderr") rule.noIssueQuoted.Add("github.com/lib/pq", "QuoteIdentifier") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewSQLStrFormat", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "rule", ":=", "&", "sqlStrFormat", "{", "calls", ":", "gosec", ".", "NewCallList", "(", ")", ",", "noIssue", ":", "gosec", ".", "NewCallList", "(", ")", ",", "noIssueQuoted", ":", "gosec", ".", "NewCallList", "(", ")", ",", "sqlStatement", ":", "sqlStatement", "{", "patterns", ":", "[", "]", "*", "regexp", ".", "Regexp", "{", "regexp", ".", "MustCompile", "(", "\"", "\"", ")", ",", "regexp", ".", "MustCompile", "(", "\"", "\"", ")", ",", "}", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "High", ",", "What", ":", "\"", "\"", ",", "}", ",", "}", ",", "}", "\n", "rule", ".", "calls", ".", "AddAll", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "rule", ".", "noIssue", ".", "AddAll", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "rule", ".", "noIssueQuoted", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "rule", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewSQLStrFormat looks for cases where we're building SQL query strings using format strings
[ "NewSQLStrFormat", "looks", "for", "cases", "where", "we", "re", "building", "SQL", "query", "strings", "using", "format", "strings" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L177-L199
train
securego/gosec
config.go
ReadFrom
func (c Config) ReadFrom(r io.Reader) (int64, error) { data, err := ioutil.ReadAll(r) if err != nil { return int64(len(data)), err } if err = json.Unmarshal(data, &c); err != nil { return int64(len(data)), err } return int64(len(data)), nil }
go
func (c Config) ReadFrom(r io.Reader) (int64, error) { data, err := ioutil.ReadAll(r) if err != nil { return int64(len(data)), err } if err = json.Unmarshal(data, &c); err != nil { return int64(len(data)), err } return int64(len(data)), nil }
[ "func", "(", "c", "Config", ")", "ReadFrom", "(", "r", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "int64", "(", "len", "(", "data", ")", ")", ",", "err", "\n", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "c", ")", ";", "err", "!=", "nil", "{", "return", "int64", "(", "len", "(", "data", ")", ")", ",", "err", "\n", "}", "\n", "return", "int64", "(", "len", "(", "data", ")", ")", ",", "nil", "\n", "}" ]
// ReadFrom implements the io.ReaderFrom interface. This // should be used with io.Reader to load configuration from //file or from string etc.
[ "ReadFrom", "implements", "the", "io", ".", "ReaderFrom", "interface", ".", "This", "should", "be", "used", "with", "io", ".", "Reader", "to", "load", "configuration", "from", "file", "or", "from", "string", "etc", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L42-L51
train
securego/gosec
config.go
WriteTo
func (c Config) WriteTo(w io.Writer) (int64, error) { data, err := json.Marshal(c) if err != nil { return int64(len(data)), err } return io.Copy(w, bytes.NewReader(data)) }
go
func (c Config) WriteTo(w io.Writer) (int64, error) { data, err := json.Marshal(c) if err != nil { return int64(len(data)), err } return io.Copy(w, bytes.NewReader(data)) }
[ "func", "(", "c", "Config", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "int64", "(", "len", "(", "data", ")", ")", ",", "err", "\n", "}", "\n", "return", "io", ".", "Copy", "(", "w", ",", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n", "}" ]
// WriteTo implements the io.WriteTo interface. This should // be used to save or print out the configuration information.
[ "WriteTo", "implements", "the", "io", ".", "WriteTo", "interface", ".", "This", "should", "be", "used", "to", "save", "or", "print", "out", "the", "configuration", "information", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L55-L61
train
securego/gosec
config.go
Get
func (c Config) Get(section string) (interface{}, error) { settings, found := c[section] if !found { return nil, fmt.Errorf("Section %s not in configuration", section) } return settings, nil }
go
func (c Config) Get(section string) (interface{}, error) { settings, found := c[section] if !found { return nil, fmt.Errorf("Section %s not in configuration", section) } return settings, nil }
[ "func", "(", "c", "Config", ")", "Get", "(", "section", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "settings", ",", "found", ":=", "c", "[", "section", "]", "\n", "if", "!", "found", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "section", ")", "\n", "}", "\n", "return", "settings", ",", "nil", "\n", "}" ]
// Get returns the configuration section for the supplied key
[ "Get", "returns", "the", "configuration", "section", "for", "the", "supplied", "key" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L64-L70
train
securego/gosec
config.go
GetGlobal
func (c Config) GetGlobal(option GlobalOption) (string, error) { if globals, ok := c[Globals]; ok { if settings, ok := globals.(map[GlobalOption]string); ok { if value, ok := settings[option]; ok { return value, nil } return "", fmt.Errorf("global setting for %s not found", option) } } return "", fmt.Errorf("no global config options found") }
go
func (c Config) GetGlobal(option GlobalOption) (string, error) { if globals, ok := c[Globals]; ok { if settings, ok := globals.(map[GlobalOption]string); ok { if value, ok := settings[option]; ok { return value, nil } return "", fmt.Errorf("global setting for %s not found", option) } } return "", fmt.Errorf("no global config options found") }
[ "func", "(", "c", "Config", ")", "GetGlobal", "(", "option", "GlobalOption", ")", "(", "string", ",", "error", ")", "{", "if", "globals", ",", "ok", ":=", "c", "[", "Globals", "]", ";", "ok", "{", "if", "settings", ",", "ok", ":=", "globals", ".", "(", "map", "[", "GlobalOption", "]", "string", ")", ";", "ok", "{", "if", "value", ",", "ok", ":=", "settings", "[", "option", "]", ";", "ok", "{", "return", "value", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "option", ")", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n\n", "}" ]
// GetGlobal returns value associated with global configuration option
[ "GetGlobal", "returns", "value", "associated", "with", "global", "configuration", "option" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L78-L89
train
securego/gosec
config.go
SetGlobal
func (c Config) SetGlobal(option GlobalOption, value string) { if globals, ok := c[Globals]; ok { if settings, ok := globals.(map[GlobalOption]string); ok { settings[option] = value } } }
go
func (c Config) SetGlobal(option GlobalOption, value string) { if globals, ok := c[Globals]; ok { if settings, ok := globals.(map[GlobalOption]string); ok { settings[option] = value } } }
[ "func", "(", "c", "Config", ")", "SetGlobal", "(", "option", "GlobalOption", ",", "value", "string", ")", "{", "if", "globals", ",", "ok", ":=", "c", "[", "Globals", "]", ";", "ok", "{", "if", "settings", ",", "ok", ":=", "globals", ".", "(", "map", "[", "GlobalOption", "]", "string", ")", ";", "ok", "{", "settings", "[", "option", "]", "=", "value", "\n", "}", "\n", "}", "\n", "}" ]
// SetGlobal associates a value with a global configuration option
[ "SetGlobal", "associates", "a", "value", "with", "a", "global", "configuration", "option" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L92-L98
train
securego/gosec
config.go
IsGlobalEnabled
func (c Config) IsGlobalEnabled(option GlobalOption) (bool, error) { value, err := c.GetGlobal(option) if err != nil { return false, err } return (value == "true" || value == "enabled"), nil }
go
func (c Config) IsGlobalEnabled(option GlobalOption) (bool, error) { value, err := c.GetGlobal(option) if err != nil { return false, err } return (value == "true" || value == "enabled"), nil }
[ "func", "(", "c", "Config", ")", "IsGlobalEnabled", "(", "option", "GlobalOption", ")", "(", "bool", ",", "error", ")", "{", "value", ",", "err", ":=", "c", ".", "GetGlobal", "(", "option", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "(", "value", "==", "\"", "\"", "||", "value", "==", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// IsGlobalEnabled checks if a global option is enabled
[ "IsGlobalEnabled", "checks", "if", "a", "global", "option", "is", "enabled" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L101-L107
train
securego/gosec
rules/rand.go
NewWeakRandCheck
func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &weakRand{ funcNames: []string{"Read", "Int"}, packagePath: "math/rand", MetaData: gosec.MetaData{ ID: id, Severity: gosec.High, Confidence: gosec.Medium, What: "Use of weak random number generator (math/rand instead of crypto/rand)", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &weakRand{ funcNames: []string{"Read", "Int"}, packagePath: "math/rand", MetaData: gosec.MetaData{ ID: id, Severity: gosec.High, Confidence: gosec.Medium, What: "Use of weak random number generator (math/rand instead of crypto/rand)", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewWeakRandCheck", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "return", "&", "weakRand", "{", "funcNames", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "packagePath", ":", "\"", "\"", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "Severity", ":", "gosec", ".", "High", ",", "Confidence", ":", "gosec", ".", "Medium", ",", "What", ":", "\"", "\"", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure
[ "NewWeakRandCheck", "detects", "the", "use", "of", "random", "number", "generator", "that", "isn", "t", "cryptographically", "secure" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rand.go#L44-L55
train
securego/gosec
rules/ssh.go
NewSSHHostKey
func NewSSHHostKey(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &sshHostKey{ pkg: "golang.org/x/crypto/ssh", calls: []string{"InsecureIgnoreHostKey"}, MetaData: gosec.MetaData{ ID: id, What: "Use of ssh InsecureIgnoreHostKey should be audited", Severity: gosec.Medium, Confidence: gosec.High, }, }, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewSSHHostKey(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &sshHostKey{ pkg: "golang.org/x/crypto/ssh", calls: []string{"InsecureIgnoreHostKey"}, MetaData: gosec.MetaData{ ID: id, What: "Use of ssh InsecureIgnoreHostKey should be audited", Severity: gosec.Medium, Confidence: gosec.High, }, }, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewSSHHostKey", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "return", "&", "sshHostKey", "{", "pkg", ":", "\"", "\"", ",", "calls", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "What", ":", "\"", "\"", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "High", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewSSHHostKey rule detects the use of insecure ssh HostKeyCallback.
[ "NewSSHHostKey", "rule", "detects", "the", "use", "of", "insecure", "ssh", "HostKeyCallback", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssh.go#L27-L38
train
securego/gosec
rules/errors.go
NewNoErrorCheck
func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { // TODO(gm) Come up with sensible defaults here. Or flip it to use a // black list instead. whitelist := gosec.NewCallList() whitelist.AddAll("bytes.Buffer", "Write", "WriteByte", "WriteRune", "WriteString") whitelist.AddAll("fmt", "Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln") whitelist.AddAll("strings.Builder", "Write", "WriteByte", "WriteRune", "WriteString") whitelist.Add("io.PipeWriter", "CloseWithError") if configured, ok := conf["G104"]; ok { if whitelisted, ok := configured.(map[string][]string); ok { for key, val := range whitelisted { whitelist.AddAll(key, val...) } } } return &noErrorCheck{ MetaData: gosec.MetaData{ ID: id, Severity: gosec.Low, Confidence: gosec.High, What: "Errors unhandled.", }, whitelist: whitelist, }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)} }
go
func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { // TODO(gm) Come up with sensible defaults here. Or flip it to use a // black list instead. whitelist := gosec.NewCallList() whitelist.AddAll("bytes.Buffer", "Write", "WriteByte", "WriteRune", "WriteString") whitelist.AddAll("fmt", "Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln") whitelist.AddAll("strings.Builder", "Write", "WriteByte", "WriteRune", "WriteString") whitelist.Add("io.PipeWriter", "CloseWithError") if configured, ok := conf["G104"]; ok { if whitelisted, ok := configured.(map[string][]string); ok { for key, val := range whitelisted { whitelist.AddAll(key, val...) } } } return &noErrorCheck{ MetaData: gosec.MetaData{ ID: id, Severity: gosec.Low, Confidence: gosec.High, What: "Errors unhandled.", }, whitelist: whitelist, }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)} }
[ "func", "NewNoErrorCheck", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "// TODO(gm) Come up with sensible defaults here. Or flip it to use a", "// black list instead.", "whitelist", ":=", "gosec", ".", "NewCallList", "(", ")", "\n", "whitelist", ".", "AddAll", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "whitelist", ".", "AddAll", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "whitelist", ".", "AddAll", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "whitelist", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "configured", ",", "ok", ":=", "conf", "[", "\"", "\"", "]", ";", "ok", "{", "if", "whitelisted", ",", "ok", ":=", "configured", ".", "(", "map", "[", "string", "]", "[", "]", "string", ")", ";", "ok", "{", "for", "key", ",", "val", ":=", "range", "whitelisted", "{", "whitelist", ".", "AddAll", "(", "key", ",", "val", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "&", "noErrorCheck", "{", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "Severity", ":", "gosec", ".", "Low", ",", "Confidence", ":", "gosec", ".", "High", ",", "What", ":", "\"", "\"", ",", "}", ",", "whitelist", ":", "whitelist", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "AssignStmt", ")", "(", "nil", ")", ",", "(", "*", "ast", ".", "ExprStmt", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewNoErrorCheck detects if the returned error is unchecked
[ "NewNoErrorCheck", "detects", "if", "the", "returned", "error", "is", "unchecked" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/errors.go#L81-L106
train
securego/gosec
rules/big.go
NewUsingBigExp
func NewUsingBigExp(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &usingBigExp{ pkg: "*math/big.Int", calls: []string{"Exp"}, MetaData: gosec.MetaData{ ID: id, What: "Use of math/big.Int.Exp function should be audited for modulus == 0", Severity: gosec.Low, Confidence: gosec.High, }, }, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewUsingBigExp(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &usingBigExp{ pkg: "*math/big.Int", calls: []string{"Exp"}, MetaData: gosec.MetaData{ ID: id, What: "Use of math/big.Int.Exp function should be audited for modulus == 0", Severity: gosec.Low, Confidence: gosec.High, }, }, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewUsingBigExp", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "return", "&", "usingBigExp", "{", "pkg", ":", "\"", "\"", ",", "calls", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "What", ":", "\"", "\"", ",", "Severity", ":", "gosec", ".", "Low", ",", "Confidence", ":", "gosec", ".", "High", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewUsingBigExp detects issues with modulus == 0 for Bignum
[ "NewUsingBigExp", "detects", "issues", "with", "modulus", "==", "0", "for", "Bignum" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/big.go#L41-L52
train
securego/gosec
rules/rulelist.go
Builders
func (rl RuleList) Builders() map[string]gosec.RuleBuilder { builders := make(map[string]gosec.RuleBuilder) for _, def := range rl { builders[def.ID] = def.Create } return builders }
go
func (rl RuleList) Builders() map[string]gosec.RuleBuilder { builders := make(map[string]gosec.RuleBuilder) for _, def := range rl { builders[def.ID] = def.Create } return builders }
[ "func", "(", "rl", "RuleList", ")", "Builders", "(", ")", "map", "[", "string", "]", "gosec", ".", "RuleBuilder", "{", "builders", ":=", "make", "(", "map", "[", "string", "]", "gosec", ".", "RuleBuilder", ")", "\n", "for", "_", ",", "def", ":=", "range", "rl", "{", "builders", "[", "def", ".", "ID", "]", "=", "def", ".", "Create", "\n", "}", "\n", "return", "builders", "\n", "}" ]
// Builders returns all the create methods for a given rule list
[ "Builders", "returns", "all", "the", "create", "methods", "for", "a", "given", "rule", "list" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rulelist.go#L31-L37
train
securego/gosec
rules/rulelist.go
Generate
func Generate(filters ...RuleFilter) RuleList { rules := []RuleDefinition{ // misc {"G101", "Look for hardcoded credentials", NewHardcodedCredentials}, {"G102", "Bind to all interfaces", NewBindsToAllNetworkInterfaces}, {"G103", "Audit the use of unsafe block", NewUsingUnsafe}, {"G104", "Audit errors not checked", NewNoErrorCheck}, {"G105", "Audit the use of big.Exp function", NewUsingBigExp}, {"G106", "Audit the use of ssh.InsecureIgnoreHostKey function", NewSSHHostKey}, {"G107", "Url provided to HTTP request as taint input", NewSSRFCheck}, // injection {"G201", "SQL query construction using format string", NewSQLStrFormat}, {"G202", "SQL query construction using string concatenation", NewSQLStrConcat}, {"G203", "Use of unescaped data in HTML templates", NewTemplateCheck}, {"G204", "Audit use of command execution", NewSubproc}, // filesystem {"G301", "Poor file permissions used when creating a directory", NewMkdirPerms}, {"G302", "Poor file permissions used when creation file or using chmod", NewFilePerms}, {"G303", "Creating tempfile using a predictable path", NewBadTempFile}, {"G304", "File path provided as taint input", NewReadFile}, {"G305", "File path traversal when extracting zip archive", NewArchive}, // crypto {"G401", "Detect the usage of DES, RC4, MD5 or SHA1", NewUsesWeakCryptography}, {"G402", "Look for bad TLS connection settings", NewIntermediateTLSCheck}, {"G403", "Ensure minimum RSA key length of 2048 bits", NewWeakKeyStrength}, {"G404", "Insecure random number source (rand)", NewWeakRandCheck}, // blacklist {"G501", "Import blacklist: crypto/md5", NewBlacklistedImportMD5}, {"G502", "Import blacklist: crypto/des", NewBlacklistedImportDES}, {"G503", "Import blacklist: crypto/rc4", NewBlacklistedImportRC4}, {"G504", "Import blacklist: net/http/cgi", NewBlacklistedImportCGI}, {"G505", "Import blacklist: crypto/sha1", NewBlacklistedImportSHA1}, } ruleMap := make(map[string]RuleDefinition) RULES: for _, rule := range rules { for _, filter := range filters { if filter(rule.ID) { continue RULES } } ruleMap[rule.ID] = rule } return ruleMap }
go
func Generate(filters ...RuleFilter) RuleList { rules := []RuleDefinition{ // misc {"G101", "Look for hardcoded credentials", NewHardcodedCredentials}, {"G102", "Bind to all interfaces", NewBindsToAllNetworkInterfaces}, {"G103", "Audit the use of unsafe block", NewUsingUnsafe}, {"G104", "Audit errors not checked", NewNoErrorCheck}, {"G105", "Audit the use of big.Exp function", NewUsingBigExp}, {"G106", "Audit the use of ssh.InsecureIgnoreHostKey function", NewSSHHostKey}, {"G107", "Url provided to HTTP request as taint input", NewSSRFCheck}, // injection {"G201", "SQL query construction using format string", NewSQLStrFormat}, {"G202", "SQL query construction using string concatenation", NewSQLStrConcat}, {"G203", "Use of unescaped data in HTML templates", NewTemplateCheck}, {"G204", "Audit use of command execution", NewSubproc}, // filesystem {"G301", "Poor file permissions used when creating a directory", NewMkdirPerms}, {"G302", "Poor file permissions used when creation file or using chmod", NewFilePerms}, {"G303", "Creating tempfile using a predictable path", NewBadTempFile}, {"G304", "File path provided as taint input", NewReadFile}, {"G305", "File path traversal when extracting zip archive", NewArchive}, // crypto {"G401", "Detect the usage of DES, RC4, MD5 or SHA1", NewUsesWeakCryptography}, {"G402", "Look for bad TLS connection settings", NewIntermediateTLSCheck}, {"G403", "Ensure minimum RSA key length of 2048 bits", NewWeakKeyStrength}, {"G404", "Insecure random number source (rand)", NewWeakRandCheck}, // blacklist {"G501", "Import blacklist: crypto/md5", NewBlacklistedImportMD5}, {"G502", "Import blacklist: crypto/des", NewBlacklistedImportDES}, {"G503", "Import blacklist: crypto/rc4", NewBlacklistedImportRC4}, {"G504", "Import blacklist: net/http/cgi", NewBlacklistedImportCGI}, {"G505", "Import blacklist: crypto/sha1", NewBlacklistedImportSHA1}, } ruleMap := make(map[string]RuleDefinition) RULES: for _, rule := range rules { for _, filter := range filters { if filter(rule.ID) { continue RULES } } ruleMap[rule.ID] = rule } return ruleMap }
[ "func", "Generate", "(", "filters", "...", "RuleFilter", ")", "RuleList", "{", "rules", ":=", "[", "]", "RuleDefinition", "{", "// misc", "{", "\"", "\"", ",", "\"", "\"", ",", "NewHardcodedCredentials", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBindsToAllNetworkInterfaces", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewUsingUnsafe", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewNoErrorCheck", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewUsingBigExp", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewSSHHostKey", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewSSRFCheck", "}", ",", "// injection", "{", "\"", "\"", ",", "\"", "\"", ",", "NewSQLStrFormat", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewSQLStrConcat", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewTemplateCheck", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewSubproc", "}", ",", "// filesystem", "{", "\"", "\"", ",", "\"", "\"", ",", "NewMkdirPerms", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewFilePerms", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBadTempFile", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewReadFile", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewArchive", "}", ",", "// crypto", "{", "\"", "\"", ",", "\"", "\"", ",", "NewUsesWeakCryptography", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewIntermediateTLSCheck", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewWeakKeyStrength", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewWeakRandCheck", "}", ",", "// blacklist", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBlacklistedImportMD5", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBlacklistedImportDES", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBlacklistedImportRC4", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBlacklistedImportCGI", "}", ",", "{", "\"", "\"", ",", "\"", "\"", ",", "NewBlacklistedImportSHA1", "}", ",", "}", "\n\n", "ruleMap", ":=", "make", "(", "map", "[", "string", "]", "RuleDefinition", ")", "\n\n", "RULES", ":", "for", "_", ",", "rule", ":=", "range", "rules", "{", "for", "_", ",", "filter", ":=", "range", "filters", "{", "if", "filter", "(", "rule", ".", "ID", ")", "{", "continue", "RULES", "\n", "}", "\n", "}", "\n", "ruleMap", "[", "rule", ".", "ID", "]", "=", "rule", "\n", "}", "\n", "return", "ruleMap", "\n", "}" ]
// Generate the list of rules to use
[ "Generate", "the", "list", "of", "rules", "to", "use" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rulelist.go#L59-L109
train
securego/gosec
errors.go
NewError
func NewError(line, column int, err string) *Error { return &Error{ Line: line, Column: column, Err: err, } }
go
func NewError(line, column int, err string) *Error { return &Error{ Line: line, Column: column, Err: err, } }
[ "func", "NewError", "(", "line", ",", "column", "int", ",", "err", "string", ")", "*", "Error", "{", "return", "&", "Error", "{", "Line", ":", "line", ",", "Column", ":", "column", ",", "Err", ":", "err", ",", "}", "\n", "}" ]
// NewError creates Error object
[ "NewError", "creates", "Error", "object" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/errors.go#L15-L21
train
securego/gosec
errors.go
sortErrors
func sortErrors(allErrors map[string][]Error) { for _, errors := range allErrors { sort.Slice(errors, func(i, j int) bool { if errors[i].Line == errors[j].Line { return errors[i].Column <= errors[j].Column } return errors[i].Line < errors[j].Line }) } }
go
func sortErrors(allErrors map[string][]Error) { for _, errors := range allErrors { sort.Slice(errors, func(i, j int) bool { if errors[i].Line == errors[j].Line { return errors[i].Column <= errors[j].Column } return errors[i].Line < errors[j].Line }) } }
[ "func", "sortErrors", "(", "allErrors", "map", "[", "string", "]", "[", "]", "Error", ")", "{", "for", "_", ",", "errors", ":=", "range", "allErrors", "{", "sort", ".", "Slice", "(", "errors", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "if", "errors", "[", "i", "]", ".", "Line", "==", "errors", "[", "j", "]", ".", "Line", "{", "return", "errors", "[", "i", "]", ".", "Column", "<=", "errors", "[", "j", "]", ".", "Column", "\n", "}", "\n", "return", "errors", "[", "i", "]", ".", "Line", "<", "errors", "[", "j", "]", ".", "Line", "\n", "}", ")", "\n", "}", "\n", "}" ]
// sortErros sorts the golang erros by line
[ "sortErros", "sorts", "the", "golang", "erros", "by", "line" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/errors.go#L24-L33
train
securego/gosec
rules/tempfiles.go
NewBadTempFile
func NewBadTempFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { calls := gosec.NewCallList() calls.Add("io/ioutil", "WriteFile") calls.Add("os", "Create") return &badTempFile{ calls: calls, args: regexp.MustCompile(`^/tmp/.*$|^/var/tmp/.*$`), MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "File creation in shared tmp directory without using ioutil.Tempfile", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewBadTempFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { calls := gosec.NewCallList() calls.Add("io/ioutil", "WriteFile") calls.Add("os", "Create") return &badTempFile{ calls: calls, args: regexp.MustCompile(`^/tmp/.*$|^/var/tmp/.*$`), MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "File creation in shared tmp directory without using ioutil.Tempfile", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewBadTempFile", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "calls", ":=", "gosec", ".", "NewCallList", "(", ")", "\n", "calls", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "calls", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "&", "badTempFile", "{", "calls", ":", "calls", ",", "args", ":", "regexp", ".", "MustCompile", "(", "`^/tmp/.*$|^/var/tmp/.*$`", ")", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "High", ",", "What", ":", "\"", "\"", ",", "}", ",", "}", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewBadTempFile detects direct writes to predictable path in temporary directory
[ "NewBadTempFile", "detects", "direct", "writes", "to", "predictable", "path", "in", "temporary", "directory" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/tempfiles.go#L44-L58
train
securego/gosec
import_tracker.go
NewImportTracker
func NewImportTracker() *ImportTracker { return &ImportTracker{ make(map[string]string), make(map[string]string), make(map[string]bool), } }
go
func NewImportTracker() *ImportTracker { return &ImportTracker{ make(map[string]string), make(map[string]string), make(map[string]bool), } }
[ "func", "NewImportTracker", "(", ")", "*", "ImportTracker", "{", "return", "&", "ImportTracker", "{", "make", "(", "map", "[", "string", "]", "string", ")", ",", "make", "(", "map", "[", "string", "]", "string", ")", ",", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "}", "\n", "}" ]
// NewImportTracker creates an empty Import tracker instance
[ "NewImportTracker", "creates", "an", "empty", "Import", "tracker", "instance" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L31-L37
train
securego/gosec
import_tracker.go
TrackFile
func (t *ImportTracker) TrackFile(file *ast.File) { for _, imp := range file.Imports { path := strings.Trim(imp.Path.Value, `"`) parts := strings.Split(path, "/") if len(parts) > 0 { name := parts[len(parts)-1] t.Imported[path] = name } } }
go
func (t *ImportTracker) TrackFile(file *ast.File) { for _, imp := range file.Imports { path := strings.Trim(imp.Path.Value, `"`) parts := strings.Split(path, "/") if len(parts) > 0 { name := parts[len(parts)-1] t.Imported[path] = name } } }
[ "func", "(", "t", "*", "ImportTracker", ")", "TrackFile", "(", "file", "*", "ast", ".", "File", ")", "{", "for", "_", ",", "imp", ":=", "range", "file", ".", "Imports", "{", "path", ":=", "strings", ".", "Trim", "(", "imp", ".", "Path", ".", "Value", ",", "`\"`", ")", "\n", "parts", ":=", "strings", ".", "Split", "(", "path", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", ">", "0", "{", "name", ":=", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", "\n", "t", ".", "Imported", "[", "path", "]", "=", "name", "\n", "}", "\n", "}", "\n", "}" ]
// TrackFile track all the imports used by the supplied file
[ "TrackFile", "track", "all", "the", "imports", "used", "by", "the", "supplied", "file" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L40-L49
train
securego/gosec
import_tracker.go
TrackPackages
func (t *ImportTracker) TrackPackages(pkgs ...*types.Package) { for _, pkg := range pkgs { t.Imported[pkg.Path()] = pkg.Name() } }
go
func (t *ImportTracker) TrackPackages(pkgs ...*types.Package) { for _, pkg := range pkgs { t.Imported[pkg.Path()] = pkg.Name() } }
[ "func", "(", "t", "*", "ImportTracker", ")", "TrackPackages", "(", "pkgs", "...", "*", "types", ".", "Package", ")", "{", "for", "_", ",", "pkg", ":=", "range", "pkgs", "{", "t", ".", "Imported", "[", "pkg", ".", "Path", "(", ")", "]", "=", "pkg", ".", "Name", "(", ")", "\n", "}", "\n", "}" ]
// TrackPackages tracks all the imports used by the supplied packages
[ "TrackPackages", "tracks", "all", "the", "imports", "used", "by", "the", "supplied", "packages" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L52-L56
train
securego/gosec
import_tracker.go
TrackImport
func (t *ImportTracker) TrackImport(n ast.Node) { if imported, ok := n.(*ast.ImportSpec); ok { path := strings.Trim(imported.Path.Value, `"`) if imported.Name != nil { if imported.Name.Name == "_" { // Initialization only import t.InitOnly[path] = true } else { // Aliased import t.Aliased[path] = imported.Name.Name } } if path == "unsafe" { t.Imported[path] = path } } }
go
func (t *ImportTracker) TrackImport(n ast.Node) { if imported, ok := n.(*ast.ImportSpec); ok { path := strings.Trim(imported.Path.Value, `"`) if imported.Name != nil { if imported.Name.Name == "_" { // Initialization only import t.InitOnly[path] = true } else { // Aliased import t.Aliased[path] = imported.Name.Name } } if path == "unsafe" { t.Imported[path] = path } } }
[ "func", "(", "t", "*", "ImportTracker", ")", "TrackImport", "(", "n", "ast", ".", "Node", ")", "{", "if", "imported", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "ImportSpec", ")", ";", "ok", "{", "path", ":=", "strings", ".", "Trim", "(", "imported", ".", "Path", ".", "Value", ",", "`\"`", ")", "\n", "if", "imported", ".", "Name", "!=", "nil", "{", "if", "imported", ".", "Name", ".", "Name", "==", "\"", "\"", "{", "// Initialization only import", "t", ".", "InitOnly", "[", "path", "]", "=", "true", "\n", "}", "else", "{", "// Aliased import", "t", ".", "Aliased", "[", "path", "]", "=", "imported", ".", "Name", ".", "Name", "\n", "}", "\n", "}", "\n", "if", "path", "==", "\"", "\"", "{", "t", ".", "Imported", "[", "path", "]", "=", "path", "\n", "}", "\n", "}", "\n", "}" ]
// TrackImport tracks imports and handles the 'unsafe' import
[ "TrackImport", "tracks", "imports", "and", "handles", "the", "unsafe", "import" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L59-L75
train
securego/gosec
rules/readfile.go
isJoinFunc
func (r *readfile) isJoinFunc(n ast.Node, c *gosec.Context) bool { if call := r.pathJoin.ContainsCallExpr(n, c, false); call != nil { for _, arg := range call.Args { // edge case: check if one of the args is a BinaryExpr if binExp, ok := arg.(*ast.BinaryExpr); ok { // iterate and resolve all found identities from the BinaryExpr if _, ok := gosec.FindVarIdentities(binExp, c); ok { return true } } // try and resolve identity if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return true } } } } return false }
go
func (r *readfile) isJoinFunc(n ast.Node, c *gosec.Context) bool { if call := r.pathJoin.ContainsCallExpr(n, c, false); call != nil { for _, arg := range call.Args { // edge case: check if one of the args is a BinaryExpr if binExp, ok := arg.(*ast.BinaryExpr); ok { // iterate and resolve all found identities from the BinaryExpr if _, ok := gosec.FindVarIdentities(binExp, c); ok { return true } } // try and resolve identity if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return true } } } } return false }
[ "func", "(", "r", "*", "readfile", ")", "isJoinFunc", "(", "n", "ast", ".", "Node", ",", "c", "*", "gosec", ".", "Context", ")", "bool", "{", "if", "call", ":=", "r", ".", "pathJoin", ".", "ContainsCallExpr", "(", "n", ",", "c", ",", "false", ")", ";", "call", "!=", "nil", "{", "for", "_", ",", "arg", ":=", "range", "call", ".", "Args", "{", "// edge case: check if one of the args is a BinaryExpr", "if", "binExp", ",", "ok", ":=", "arg", ".", "(", "*", "ast", ".", "BinaryExpr", ")", ";", "ok", "{", "// iterate and resolve all found identities from the BinaryExpr", "if", "_", ",", "ok", ":=", "gosec", ".", "FindVarIdentities", "(", "binExp", ",", "c", ")", ";", "ok", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "// try and resolve identity", "if", "ident", ",", "ok", ":=", "arg", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "obj", ":=", "c", ".", "Info", ".", "ObjectOf", "(", "ident", ")", "\n", "if", "_", ",", "ok", ":=", "obj", ".", "(", "*", "types", ".", "Var", ")", ";", "ok", "&&", "!", "gosec", ".", "TryResolve", "(", "ident", ",", "c", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isJoinFunc checks if there is a filepath.Join or other join function
[ "isJoinFunc", "checks", "if", "there", "is", "a", "filepath", ".", "Join", "or", "other", "join", "function" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/readfile.go#L36-L57
train
securego/gosec
rules/readfile.go
Match
func (r *readfile) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { if node := r.ContainsCallExpr(n, c, false); node != nil { for _, arg := range node.Args { // handles path joining functions in Arg // eg. os.Open(filepath.Join("/tmp/", file)) if callExpr, ok := arg.(*ast.CallExpr); ok { if r.isJoinFunc(callExpr, c) { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } // handles binary string concatenation eg. ioutil.Readfile("/tmp/" + file + "/blob") if binExp, ok := arg.(*ast.BinaryExpr); ok { // resolve all found identities from the BinaryExpr if _, ok := gosec.FindVarIdentities(binExp, c); ok { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } } } return nil, nil }
go
func (r *readfile) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { if node := r.ContainsCallExpr(n, c, false); node != nil { for _, arg := range node.Args { // handles path joining functions in Arg // eg. os.Open(filepath.Join("/tmp/", file)) if callExpr, ok := arg.(*ast.CallExpr); ok { if r.isJoinFunc(callExpr, c) { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } // handles binary string concatenation eg. ioutil.Readfile("/tmp/" + file + "/blob") if binExp, ok := arg.(*ast.BinaryExpr); ok { // resolve all found identities from the BinaryExpr if _, ok := gosec.FindVarIdentities(binExp, c); ok { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } } } return nil, nil }
[ "func", "(", "r", "*", "readfile", ")", "Match", "(", "n", "ast", ".", "Node", ",", "c", "*", "gosec", ".", "Context", ")", "(", "*", "gosec", ".", "Issue", ",", "error", ")", "{", "if", "node", ":=", "r", ".", "ContainsCallExpr", "(", "n", ",", "c", ",", "false", ")", ";", "node", "!=", "nil", "{", "for", "_", ",", "arg", ":=", "range", "node", ".", "Args", "{", "// handles path joining functions in Arg", "// eg. os.Open(filepath.Join(\"/tmp/\", file))", "if", "callExpr", ",", "ok", ":=", "arg", ".", "(", "*", "ast", ".", "CallExpr", ")", ";", "ok", "{", "if", "r", ".", "isJoinFunc", "(", "callExpr", ",", "c", ")", "{", "return", "gosec", ".", "NewIssue", "(", "c", ",", "n", ",", "r", ".", "ID", "(", ")", ",", "r", ".", "What", ",", "r", ".", "Severity", ",", "r", ".", "Confidence", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "// handles binary string concatenation eg. ioutil.Readfile(\"/tmp/\" + file + \"/blob\")", "if", "binExp", ",", "ok", ":=", "arg", ".", "(", "*", "ast", ".", "BinaryExpr", ")", ";", "ok", "{", "// resolve all found identities from the BinaryExpr", "if", "_", ",", "ok", ":=", "gosec", ".", "FindVarIdentities", "(", "binExp", ",", "c", ")", ";", "ok", "{", "return", "gosec", ".", "NewIssue", "(", "c", ",", "n", ",", "r", ".", "ID", "(", ")", ",", "r", ".", "What", ",", "r", ".", "Severity", ",", "r", ".", "Confidence", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "if", "ident", ",", "ok", ":=", "arg", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "obj", ":=", "c", ".", "Info", ".", "ObjectOf", "(", "ident", ")", "\n", "if", "_", ",", "ok", ":=", "obj", ".", "(", "*", "types", ".", "Var", ")", ";", "ok", "&&", "!", "gosec", ".", "TryResolve", "(", "ident", ",", "c", ")", "{", "return", "gosec", ".", "NewIssue", "(", "c", ",", "n", ",", "r", ".", "ID", "(", ")", ",", "r", ".", "What", ",", "r", ".", "Severity", ",", "r", ".", "Confidence", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// Match inspects AST nodes to determine if the match the methods `os.Open` or `ioutil.ReadFile`
[ "Match", "inspects", "AST", "nodes", "to", "determine", "if", "the", "match", "the", "methods", "os", ".", "Open", "or", "ioutil", ".", "ReadFile" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/readfile.go#L60-L87
train
securego/gosec
rules/readfile.go
NewReadFile
func NewReadFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { rule := &readfile{ pathJoin: gosec.NewCallList(), CallList: gosec.NewCallList(), MetaData: gosec.MetaData{ ID: id, What: "Potential file inclusion via variable", Severity: gosec.Medium, Confidence: gosec.High, }, } rule.pathJoin.Add("path/filepath", "Join") rule.pathJoin.Add("path", "Join") rule.Add("io/ioutil", "ReadFile") rule.Add("os", "Open") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewReadFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { rule := &readfile{ pathJoin: gosec.NewCallList(), CallList: gosec.NewCallList(), MetaData: gosec.MetaData{ ID: id, What: "Potential file inclusion via variable", Severity: gosec.Medium, Confidence: gosec.High, }, } rule.pathJoin.Add("path/filepath", "Join") rule.pathJoin.Add("path", "Join") rule.Add("io/ioutil", "ReadFile") rule.Add("os", "Open") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewReadFile", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "rule", ":=", "&", "readfile", "{", "pathJoin", ":", "gosec", ".", "NewCallList", "(", ")", ",", "CallList", ":", "gosec", ".", "NewCallList", "(", ")", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "What", ":", "\"", "\"", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "High", ",", "}", ",", "}", "\n", "rule", ".", "pathJoin", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rule", ".", "pathJoin", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rule", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rule", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "rule", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewReadFile detects cases where we read files
[ "NewReadFile", "detects", "cases", "where", "we", "read", "files" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/readfile.go#L90-L106
train
securego/gosec
rules/ssrf.go
ResolveVar
func (r *ssrf) ResolveVar(n *ast.CallExpr, c *gosec.Context) bool { if len(n.Args) > 0 { arg := n.Args[0] if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return true } } } return false }
go
func (r *ssrf) ResolveVar(n *ast.CallExpr, c *gosec.Context) bool { if len(n.Args) > 0 { arg := n.Args[0] if ident, ok := arg.(*ast.Ident); ok { obj := c.Info.ObjectOf(ident) if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) { return true } } } return false }
[ "func", "(", "r", "*", "ssrf", ")", "ResolveVar", "(", "n", "*", "ast", ".", "CallExpr", ",", "c", "*", "gosec", ".", "Context", ")", "bool", "{", "if", "len", "(", "n", ".", "Args", ")", ">", "0", "{", "arg", ":=", "n", ".", "Args", "[", "0", "]", "\n", "if", "ident", ",", "ok", ":=", "arg", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "obj", ":=", "c", ".", "Info", ".", "ObjectOf", "(", "ident", ")", "\n", "if", "_", ",", "ok", ":=", "obj", ".", "(", "*", "types", ".", "Var", ")", ";", "ok", "&&", "!", "gosec", ".", "TryResolve", "(", "ident", ",", "c", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ResolveVar tries to resolve the first argument of a call expression // The first argument is the url
[ "ResolveVar", "tries", "to", "resolve", "the", "first", "argument", "of", "a", "call", "expression", "The", "first", "argument", "is", "the", "url" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssrf.go#L22-L33
train
securego/gosec
rules/ssrf.go
NewSSRFCheck
func NewSSRFCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { rule := &ssrf{ CallList: gosec.NewCallList(), MetaData: gosec.MetaData{ ID: id, What: "Potential HTTP request made with variable url", Severity: gosec.Medium, Confidence: gosec.Medium, }, } rule.AddAll("net/http", "Do", "Get", "Head", "Post", "PostForm", "RoundTrip") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
go
func NewSSRFCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { rule := &ssrf{ CallList: gosec.NewCallList(), MetaData: gosec.MetaData{ ID: id, What: "Potential HTTP request made with variable url", Severity: gosec.Medium, Confidence: gosec.Medium, }, } rule.AddAll("net/http", "Do", "Get", "Head", "Post", "PostForm", "RoundTrip") return rule, []ast.Node{(*ast.CallExpr)(nil)} }
[ "func", "NewSSRFCheck", "(", "id", "string", ",", "conf", "gosec", ".", "Config", ")", "(", "gosec", ".", "Rule", ",", "[", "]", "ast", ".", "Node", ")", "{", "rule", ":=", "&", "ssrf", "{", "CallList", ":", "gosec", ".", "NewCallList", "(", ")", ",", "MetaData", ":", "gosec", ".", "MetaData", "{", "ID", ":", "id", ",", "What", ":", "\"", "\"", ",", "Severity", ":", "gosec", ".", "Medium", ",", "Confidence", ":", "gosec", ".", "Medium", ",", "}", ",", "}", "\n", "rule", ".", "AddAll", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "rule", ",", "[", "]", "ast", ".", "Node", "{", "(", "*", "ast", ".", "CallExpr", ")", "(", "nil", ")", "}", "\n", "}" ]
// NewSSRFCheck detects cases where HTTP requests are sent
[ "NewSSRFCheck", "detects", "cases", "where", "HTTP", "requests", "are", "sent" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssrf.go#L47-L59
train
securego/gosec
resolve.go
TryResolve
func TryResolve(n ast.Node, c *Context) bool { switch node := n.(type) { case *ast.BasicLit: return true case *ast.CompositeLit: return resolveCompLit(node, c) case *ast.Ident: return resolveIdent(node, c) case *ast.AssignStmt: return resolveAssign(node, c) case *ast.CallExpr: return resolveCallExpr(node, c) case *ast.BinaryExpr: return resolveBinExpr(node, c) } return false }
go
func TryResolve(n ast.Node, c *Context) bool { switch node := n.(type) { case *ast.BasicLit: return true case *ast.CompositeLit: return resolveCompLit(node, c) case *ast.Ident: return resolveIdent(node, c) case *ast.AssignStmt: return resolveAssign(node, c) case *ast.CallExpr: return resolveCallExpr(node, c) case *ast.BinaryExpr: return resolveBinExpr(node, c) } return false }
[ "func", "TryResolve", "(", "n", "ast", ".", "Node", ",", "c", "*", "Context", ")", "bool", "{", "switch", "node", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "BasicLit", ":", "return", "true", "\n\n", "case", "*", "ast", ".", "CompositeLit", ":", "return", "resolveCompLit", "(", "node", ",", "c", ")", "\n\n", "case", "*", "ast", ".", "Ident", ":", "return", "resolveIdent", "(", "node", ",", "c", ")", "\n\n", "case", "*", "ast", ".", "AssignStmt", ":", "return", "resolveAssign", "(", "node", ",", "c", ")", "\n\n", "case", "*", "ast", ".", "CallExpr", ":", "return", "resolveCallExpr", "(", "node", ",", "c", ")", "\n\n", "case", "*", "ast", ".", "BinaryExpr", ":", "return", "resolveBinExpr", "(", "node", ",", "c", ")", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// TryResolve will attempt, given a subtree starting at some ATS node, to resolve // all values contained within to a known constant. It is used to check for any // unknown values in compound expressions.
[ "TryResolve", "will", "attempt", "given", "a", "subtree", "starting", "at", "some", "ATS", "node", "to", "resolve", "all", "values", "contained", "within", "to", "a", "known", "constant", ".", "It", "is", "used", "to", "check", "for", "any", "unknown", "values", "in", "compound", "expressions", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/resolve.go#L60-L82
train
securego/gosec
issue.go
NewIssue
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue { var code string fobj := ctx.FileSet.File(node.Pos()) name := fobj.Name() start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) line := strconv.Itoa(start) if start != end { line = fmt.Sprintf("%d-%d", start, end) } // #nosec if file, err := os.Open(fobj.Name()); err == nil { defer file.Close() s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64 e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64 code, err = codeSnippet(file, s, e, node) if err != nil { code = err.Error() } } return &Issue{ File: name, Line: line, RuleID: ruleID, What: desc, Confidence: confidence, Severity: severity, Code: code, } }
go
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue { var code string fobj := ctx.FileSet.File(node.Pos()) name := fobj.Name() start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) line := strconv.Itoa(start) if start != end { line = fmt.Sprintf("%d-%d", start, end) } // #nosec if file, err := os.Open(fobj.Name()); err == nil { defer file.Close() s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64 e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64 code, err = codeSnippet(file, s, e, node) if err != nil { code = err.Error() } } return &Issue{ File: name, Line: line, RuleID: ruleID, What: desc, Confidence: confidence, Severity: severity, Code: code, } }
[ "func", "NewIssue", "(", "ctx", "*", "Context", ",", "node", "ast", ".", "Node", ",", "ruleID", ",", "desc", "string", ",", "severity", "Score", ",", "confidence", "Score", ")", "*", "Issue", "{", "var", "code", "string", "\n", "fobj", ":=", "ctx", ".", "FileSet", ".", "File", "(", "node", ".", "Pos", "(", ")", ")", "\n", "name", ":=", "fobj", ".", "Name", "(", ")", "\n\n", "start", ",", "end", ":=", "fobj", ".", "Line", "(", "node", ".", "Pos", "(", ")", ")", ",", "fobj", ".", "Line", "(", "node", ".", "End", "(", ")", ")", "\n", "line", ":=", "strconv", ".", "Itoa", "(", "start", ")", "\n", "if", "start", "!=", "end", "{", "line", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "start", ",", "end", ")", "\n", "}", "\n\n", "// #nosec", "if", "file", ",", "err", ":=", "os", ".", "Open", "(", "fobj", ".", "Name", "(", ")", ")", ";", "err", "==", "nil", "{", "defer", "file", ".", "Close", "(", ")", "\n", "s", ":=", "(", "int64", ")", "(", "fobj", ".", "Position", "(", "node", ".", "Pos", "(", ")", ")", ".", "Offset", ")", "// Go bug, should be int64", "\n", "e", ":=", "(", "int64", ")", "(", "fobj", ".", "Position", "(", "node", ".", "End", "(", ")", ")", ".", "Offset", ")", "// Go bug, should be int64", "\n", "code", ",", "err", "=", "codeSnippet", "(", "file", ",", "s", ",", "e", ",", "node", ")", "\n", "if", "err", "!=", "nil", "{", "code", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "Issue", "{", "File", ":", "name", ",", "Line", ":", "line", ",", "RuleID", ":", "ruleID", ",", "What", ":", "desc", ",", "Confidence", ":", "confidence", ",", "Severity", ":", "severity", ",", "Code", ":", "code", ",", "}", "\n", "}" ]
// NewIssue creates a new Issue
[ "NewIssue", "creates", "a", "new", "Issue" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/issue.go#L94-L125
train
securego/gosec
analyzer.go
NewAnalyzer
func NewAnalyzer(conf Config, tests bool, logger *log.Logger) *Analyzer { ignoreNoSec := false if enabled, err := conf.IsGlobalEnabled(Nosec); err == nil { ignoreNoSec = enabled } if logger == nil { logger = log.New(os.Stderr, "[gosec]", log.LstdFlags) } return &Analyzer{ ignoreNosec: ignoreNoSec, ruleset: make(RuleSet), context: &Context{}, config: conf, logger: logger, issues: make([]*Issue, 0, 16), stats: &Metrics{}, errors: make(map[string][]Error), tests: tests, } }
go
func NewAnalyzer(conf Config, tests bool, logger *log.Logger) *Analyzer { ignoreNoSec := false if enabled, err := conf.IsGlobalEnabled(Nosec); err == nil { ignoreNoSec = enabled } if logger == nil { logger = log.New(os.Stderr, "[gosec]", log.LstdFlags) } return &Analyzer{ ignoreNosec: ignoreNoSec, ruleset: make(RuleSet), context: &Context{}, config: conf, logger: logger, issues: make([]*Issue, 0, 16), stats: &Metrics{}, errors: make(map[string][]Error), tests: tests, } }
[ "func", "NewAnalyzer", "(", "conf", "Config", ",", "tests", "bool", ",", "logger", "*", "log", ".", "Logger", ")", "*", "Analyzer", "{", "ignoreNoSec", ":=", "false", "\n", "if", "enabled", ",", "err", ":=", "conf", ".", "IsGlobalEnabled", "(", "Nosec", ")", ";", "err", "==", "nil", "{", "ignoreNoSec", "=", "enabled", "\n", "}", "\n", "if", "logger", "==", "nil", "{", "logger", "=", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", "\n", "}", "\n", "return", "&", "Analyzer", "{", "ignoreNosec", ":", "ignoreNoSec", ",", "ruleset", ":", "make", "(", "RuleSet", ")", ",", "context", ":", "&", "Context", "{", "}", ",", "config", ":", "conf", ",", "logger", ":", "logger", ",", "issues", ":", "make", "(", "[", "]", "*", "Issue", ",", "0", ",", "16", ")", ",", "stats", ":", "&", "Metrics", "{", "}", ",", "errors", ":", "make", "(", "map", "[", "string", "]", "[", "]", "Error", ")", ",", "tests", ":", "tests", ",", "}", "\n", "}" ]
// NewAnalyzer builds a new analyzer.
[ "NewAnalyzer", "builds", "a", "new", "analyzer", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L74-L93
train
securego/gosec
analyzer.go
LoadRules
func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder) { for id, def := range ruleDefinitions { r, nodes := def(id, gosec.config) gosec.ruleset.Register(r, nodes...) } }
go
func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder) { for id, def := range ruleDefinitions { r, nodes := def(id, gosec.config) gosec.ruleset.Register(r, nodes...) } }
[ "func", "(", "gosec", "*", "Analyzer", ")", "LoadRules", "(", "ruleDefinitions", "map", "[", "string", "]", "RuleBuilder", ")", "{", "for", "id", ",", "def", ":=", "range", "ruleDefinitions", "{", "r", ",", "nodes", ":=", "def", "(", "id", ",", "gosec", ".", "config", ")", "\n", "gosec", ".", "ruleset", ".", "Register", "(", "r", ",", "nodes", "...", ")", "\n", "}", "\n", "}" ]
// LoadRules instantiates all the rules to be used when analyzing source // packages
[ "LoadRules", "instantiates", "all", "the", "rules", "to", "be", "used", "when", "analyzing", "source", "packages" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L97-L102
train
securego/gosec
analyzer.go
Process
func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error { config := gosec.pkgConfig(buildTags) for _, pkgPath := range packagePaths { pkgs, err := gosec.load(pkgPath, config) if err != nil { gosec.AppendError(pkgPath, err) } for _, pkg := range pkgs { if pkg.Name != "" { err := gosec.ParseErrors(pkg) if err != nil { return fmt.Errorf("parsing errors in pkg %q: %v", pkg.Name, err) } gosec.check(pkg) } } } sortErrors(gosec.errors) return nil }
go
func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error { config := gosec.pkgConfig(buildTags) for _, pkgPath := range packagePaths { pkgs, err := gosec.load(pkgPath, config) if err != nil { gosec.AppendError(pkgPath, err) } for _, pkg := range pkgs { if pkg.Name != "" { err := gosec.ParseErrors(pkg) if err != nil { return fmt.Errorf("parsing errors in pkg %q: %v", pkg.Name, err) } gosec.check(pkg) } } } sortErrors(gosec.errors) return nil }
[ "func", "(", "gosec", "*", "Analyzer", ")", "Process", "(", "buildTags", "[", "]", "string", ",", "packagePaths", "...", "string", ")", "error", "{", "config", ":=", "gosec", ".", "pkgConfig", "(", "buildTags", ")", "\n", "for", "_", ",", "pkgPath", ":=", "range", "packagePaths", "{", "pkgs", ",", "err", ":=", "gosec", ".", "load", "(", "pkgPath", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "gosec", ".", "AppendError", "(", "pkgPath", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "pkg", ":=", "range", "pkgs", "{", "if", "pkg", ".", "Name", "!=", "\"", "\"", "{", "err", ":=", "gosec", ".", "ParseErrors", "(", "pkg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pkg", ".", "Name", ",", "err", ")", "\n", "}", "\n", "gosec", ".", "check", "(", "pkg", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "sortErrors", "(", "gosec", ".", "errors", ")", "\n", "return", "nil", "\n", "}" ]
// Process kicks off the analysis process for a given package
[ "Process", "kicks", "off", "the", "analysis", "process", "for", "a", "given", "package" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L105-L124
train
securego/gosec
analyzer.go
ParseErrors
func (gosec *Analyzer) ParseErrors(pkg *packages.Package) error { if len(pkg.Errors) == 0 { return nil } for _, pkgErr := range pkg.Errors { parts := strings.Split(pkgErr.Pos, ":") file := parts[0] var err error var line int if len(parts) > 1 { if line, err = strconv.Atoi(parts[1]); err != nil { return fmt.Errorf("parsing line: %v", err) } } var column int if len(parts) > 2 { if column, err = strconv.Atoi(parts[2]); err != nil { return fmt.Errorf("parsing column: %v", err) } } msg := strings.TrimSpace(pkgErr.Msg) newErr := NewError(line, column, msg) if errSlice, ok := gosec.errors[file]; ok { gosec.errors[file] = append(errSlice, *newErr) } else { errSlice = []Error{} gosec.errors[file] = append(errSlice, *newErr) } } return nil }
go
func (gosec *Analyzer) ParseErrors(pkg *packages.Package) error { if len(pkg.Errors) == 0 { return nil } for _, pkgErr := range pkg.Errors { parts := strings.Split(pkgErr.Pos, ":") file := parts[0] var err error var line int if len(parts) > 1 { if line, err = strconv.Atoi(parts[1]); err != nil { return fmt.Errorf("parsing line: %v", err) } } var column int if len(parts) > 2 { if column, err = strconv.Atoi(parts[2]); err != nil { return fmt.Errorf("parsing column: %v", err) } } msg := strings.TrimSpace(pkgErr.Msg) newErr := NewError(line, column, msg) if errSlice, ok := gosec.errors[file]; ok { gosec.errors[file] = append(errSlice, *newErr) } else { errSlice = []Error{} gosec.errors[file] = append(errSlice, *newErr) } } return nil }
[ "func", "(", "gosec", "*", "Analyzer", ")", "ParseErrors", "(", "pkg", "*", "packages", ".", "Package", ")", "error", "{", "if", "len", "(", "pkg", ".", "Errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "pkgErr", ":=", "range", "pkg", ".", "Errors", "{", "parts", ":=", "strings", ".", "Split", "(", "pkgErr", ".", "Pos", ",", "\"", "\"", ")", "\n", "file", ":=", "parts", "[", "0", "]", "\n", "var", "err", "error", "\n", "var", "line", "int", "\n", "if", "len", "(", "parts", ")", ">", "1", "{", "if", "line", ",", "err", "=", "strconv", ".", "Atoi", "(", "parts", "[", "1", "]", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "var", "column", "int", "\n", "if", "len", "(", "parts", ")", ">", "2", "{", "if", "column", ",", "err", "=", "strconv", ".", "Atoi", "(", "parts", "[", "2", "]", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "msg", ":=", "strings", ".", "TrimSpace", "(", "pkgErr", ".", "Msg", ")", "\n", "newErr", ":=", "NewError", "(", "line", ",", "column", ",", "msg", ")", "\n", "if", "errSlice", ",", "ok", ":=", "gosec", ".", "errors", "[", "file", "]", ";", "ok", "{", "gosec", ".", "errors", "[", "file", "]", "=", "append", "(", "errSlice", ",", "*", "newErr", ")", "\n", "}", "else", "{", "errSlice", "=", "[", "]", "Error", "{", "}", "\n", "gosec", ".", "errors", "[", "file", "]", "=", "append", "(", "errSlice", ",", "*", "newErr", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseErrors parses the errors from given package
[ "ParseErrors", "parses", "the", "errors", "from", "given", "package" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L193-L223
train
securego/gosec
analyzer.go
AppendError
func (gosec *Analyzer) AppendError(file string, err error) { // Do not report the error for empty packages (e.g. files excluded from build with a tag) r := regexp.MustCompile(`no buildable Go source files in`) if r.MatchString(err.Error()) { return } errors := []Error{} if ferrs, ok := gosec.errors[file]; ok { errors = ferrs } ferr := NewError(0, 0, err.Error()) errors = append(errors, *ferr) gosec.errors[file] = errors }
go
func (gosec *Analyzer) AppendError(file string, err error) { // Do not report the error for empty packages (e.g. files excluded from build with a tag) r := regexp.MustCompile(`no buildable Go source files in`) if r.MatchString(err.Error()) { return } errors := []Error{} if ferrs, ok := gosec.errors[file]; ok { errors = ferrs } ferr := NewError(0, 0, err.Error()) errors = append(errors, *ferr) gosec.errors[file] = errors }
[ "func", "(", "gosec", "*", "Analyzer", ")", "AppendError", "(", "file", "string", ",", "err", "error", ")", "{", "// Do not report the error for empty packages (e.g. files excluded from build with a tag)", "r", ":=", "regexp", ".", "MustCompile", "(", "`no buildable Go source files in`", ")", "\n", "if", "r", ".", "MatchString", "(", "err", ".", "Error", "(", ")", ")", "{", "return", "\n", "}", "\n", "errors", ":=", "[", "]", "Error", "{", "}", "\n", "if", "ferrs", ",", "ok", ":=", "gosec", ".", "errors", "[", "file", "]", ";", "ok", "{", "errors", "=", "ferrs", "\n", "}", "\n", "ferr", ":=", "NewError", "(", "0", ",", "0", ",", "err", ".", "Error", "(", ")", ")", "\n", "errors", "=", "append", "(", "errors", ",", "*", "ferr", ")", "\n", "gosec", ".", "errors", "[", "file", "]", "=", "errors", "\n", "}" ]
// AppendError appends an error to the file errors
[ "AppendError", "appends", "an", "error", "to", "the", "file", "errors" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L226-L239
train
securego/gosec
analyzer.go
Visit
func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor { // If we've reached the end of this branch, pop off the ignores stack. if n == nil { if len(gosec.context.Ignores) > 0 { gosec.context.Ignores = gosec.context.Ignores[1:] } return gosec } // Get any new rule exclusions. ignoredRules, ignoreAll := gosec.ignore(n) if ignoreAll { return nil } // Now create the union of exclusions. ignores := map[string]bool{} if len(gosec.context.Ignores) > 0 { for k, v := range gosec.context.Ignores[0] { ignores[k] = v } } for _, v := range ignoredRules { ignores[v] = true } // Push the new set onto the stack. gosec.context.Ignores = append([]map[string]bool{ignores}, gosec.context.Ignores...) // Track aliased and initialization imports gosec.context.Imports.TrackImport(n) for _, rule := range gosec.ruleset.RegisteredFor(n) { if _, ok := ignores[rule.ID()]; ok { continue } issue, err := rule.Match(n, gosec.context) if err != nil { file, line := GetLocation(n, gosec.context) file = path.Base(file) gosec.logger.Printf("Rule error: %v => %s (%s:%d)\n", reflect.TypeOf(rule), err, file, line) } if issue != nil { gosec.issues = append(gosec.issues, issue) gosec.stats.NumFound++ } } return gosec }
go
func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor { // If we've reached the end of this branch, pop off the ignores stack. if n == nil { if len(gosec.context.Ignores) > 0 { gosec.context.Ignores = gosec.context.Ignores[1:] } return gosec } // Get any new rule exclusions. ignoredRules, ignoreAll := gosec.ignore(n) if ignoreAll { return nil } // Now create the union of exclusions. ignores := map[string]bool{} if len(gosec.context.Ignores) > 0 { for k, v := range gosec.context.Ignores[0] { ignores[k] = v } } for _, v := range ignoredRules { ignores[v] = true } // Push the new set onto the stack. gosec.context.Ignores = append([]map[string]bool{ignores}, gosec.context.Ignores...) // Track aliased and initialization imports gosec.context.Imports.TrackImport(n) for _, rule := range gosec.ruleset.RegisteredFor(n) { if _, ok := ignores[rule.ID()]; ok { continue } issue, err := rule.Match(n, gosec.context) if err != nil { file, line := GetLocation(n, gosec.context) file = path.Base(file) gosec.logger.Printf("Rule error: %v => %s (%s:%d)\n", reflect.TypeOf(rule), err, file, line) } if issue != nil { gosec.issues = append(gosec.issues, issue) gosec.stats.NumFound++ } } return gosec }
[ "func", "(", "gosec", "*", "Analyzer", ")", "Visit", "(", "n", "ast", ".", "Node", ")", "ast", ".", "Visitor", "{", "// If we've reached the end of this branch, pop off the ignores stack.", "if", "n", "==", "nil", "{", "if", "len", "(", "gosec", ".", "context", ".", "Ignores", ")", ">", "0", "{", "gosec", ".", "context", ".", "Ignores", "=", "gosec", ".", "context", ".", "Ignores", "[", "1", ":", "]", "\n", "}", "\n", "return", "gosec", "\n", "}", "\n\n", "// Get any new rule exclusions.", "ignoredRules", ",", "ignoreAll", ":=", "gosec", ".", "ignore", "(", "n", ")", "\n", "if", "ignoreAll", "{", "return", "nil", "\n", "}", "\n\n", "// Now create the union of exclusions.", "ignores", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "if", "len", "(", "gosec", ".", "context", ".", "Ignores", ")", ">", "0", "{", "for", "k", ",", "v", ":=", "range", "gosec", ".", "context", ".", "Ignores", "[", "0", "]", "{", "ignores", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "ignoredRules", "{", "ignores", "[", "v", "]", "=", "true", "\n", "}", "\n\n", "// Push the new set onto the stack.", "gosec", ".", "context", ".", "Ignores", "=", "append", "(", "[", "]", "map", "[", "string", "]", "bool", "{", "ignores", "}", ",", "gosec", ".", "context", ".", "Ignores", "...", ")", "\n\n", "// Track aliased and initialization imports", "gosec", ".", "context", ".", "Imports", ".", "TrackImport", "(", "n", ")", "\n\n", "for", "_", ",", "rule", ":=", "range", "gosec", ".", "ruleset", ".", "RegisteredFor", "(", "n", ")", "{", "if", "_", ",", "ok", ":=", "ignores", "[", "rule", ".", "ID", "(", ")", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "issue", ",", "err", ":=", "rule", ".", "Match", "(", "n", ",", "gosec", ".", "context", ")", "\n", "if", "err", "!=", "nil", "{", "file", ",", "line", ":=", "GetLocation", "(", "n", ",", "gosec", ".", "context", ")", "\n", "file", "=", "path", ".", "Base", "(", "file", ")", "\n", "gosec", ".", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "reflect", ".", "TypeOf", "(", "rule", ")", ",", "err", ",", "file", ",", "line", ")", "\n", "}", "\n", "if", "issue", "!=", "nil", "{", "gosec", ".", "issues", "=", "append", "(", "gosec", ".", "issues", ",", "issue", ")", "\n", "gosec", ".", "stats", ".", "NumFound", "++", "\n", "}", "\n", "}", "\n", "return", "gosec", "\n", "}" ]
// Visit runs the gosec visitor logic over an AST created by parsing go code. // Rule methods added with AddRule will be invoked as necessary.
[ "Visit", "runs", "the", "gosec", "visitor", "logic", "over", "an", "AST", "created", "by", "parsing", "go", "code", ".", "Rule", "methods", "added", "with", "AddRule", "will", "be", "invoked", "as", "necessary", "." ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L271-L320
train
securego/gosec
analyzer.go
Report
func (gosec *Analyzer) Report() ([]*Issue, *Metrics, map[string][]Error) { return gosec.issues, gosec.stats, gosec.errors }
go
func (gosec *Analyzer) Report() ([]*Issue, *Metrics, map[string][]Error) { return gosec.issues, gosec.stats, gosec.errors }
[ "func", "(", "gosec", "*", "Analyzer", ")", "Report", "(", ")", "(", "[", "]", "*", "Issue", ",", "*", "Metrics", ",", "map", "[", "string", "]", "[", "]", "Error", ")", "{", "return", "gosec", ".", "issues", ",", "gosec", ".", "stats", ",", "gosec", ".", "errors", "\n", "}" ]
// Report returns the current issues discovered and the metrics about the scan
[ "Report", "returns", "the", "current", "issues", "discovered", "and", "the", "metrics", "about", "the", "scan" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L323-L325
train
securego/gosec
analyzer.go
Reset
func (gosec *Analyzer) Reset() { gosec.context = &Context{} gosec.issues = make([]*Issue, 0, 16) gosec.stats = &Metrics{} }
go
func (gosec *Analyzer) Reset() { gosec.context = &Context{} gosec.issues = make([]*Issue, 0, 16) gosec.stats = &Metrics{} }
[ "func", "(", "gosec", "*", "Analyzer", ")", "Reset", "(", ")", "{", "gosec", ".", "context", "=", "&", "Context", "{", "}", "\n", "gosec", ".", "issues", "=", "make", "(", "[", "]", "*", "Issue", ",", "0", ",", "16", ")", "\n", "gosec", ".", "stats", "=", "&", "Metrics", "{", "}", "\n", "}" ]
// Reset clears state such as context, issues and metrics from the configured analyzer
[ "Reset", "clears", "state", "such", "as", "context", "issues", "and", "metrics", "from", "the", "configured", "analyzer" ]
29cec138dcc94f347e6d41550a5223571dc7d6cf
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L328-L332
train
Shopify/toxiproxy
client/client.go
Proxies
func (client *Client) Proxies() (map[string]*Proxy, error) { resp, err := http.Get(client.endpoint + "/proxies") if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "Proxies") if err != nil { return nil, err } proxies := make(map[string]*Proxy) err = json.NewDecoder(resp.Body).Decode(&proxies) if err != nil { return nil, err } for _, proxy := range proxies { proxy.client = client proxy.created = true } return proxies, nil }
go
func (client *Client) Proxies() (map[string]*Proxy, error) { resp, err := http.Get(client.endpoint + "/proxies") if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "Proxies") if err != nil { return nil, err } proxies := make(map[string]*Proxy) err = json.NewDecoder(resp.Body).Decode(&proxies) if err != nil { return nil, err } for _, proxy := range proxies { proxy.client = client proxy.created = true } return proxies, nil }
[ "func", "(", "client", "*", "Client", ")", "Proxies", "(", ")", "(", "map", "[", "string", "]", "*", "Proxy", ",", "error", ")", "{", "resp", ",", "err", ":=", "http", ".", "Get", "(", "client", ".", "endpoint", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "checkError", "(", "resp", ",", "http", ".", "StatusOK", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "proxies", ":=", "make", "(", "map", "[", "string", "]", "*", "Proxy", ")", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "proxies", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "proxy", ":=", "range", "proxies", "{", "proxy", ".", "client", "=", "client", "\n", "proxy", ".", "created", "=", "true", "\n", "}", "\n\n", "return", "proxies", ",", "nil", "\n", "}" ]
// Proxies returns a map with all the proxies and their toxics.
[ "Proxies", "returns", "a", "map", "with", "all", "the", "proxies", "and", "their", "toxics", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L60-L82
train
Shopify/toxiproxy
client/client.go
Proxy
func (client *Client) Proxy(name string) (*Proxy, error) { // TODO url encode resp, err := http.Get(client.endpoint + "/proxies/" + name) if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "Proxy") if err != nil { return nil, err } proxy := new(Proxy) err = json.NewDecoder(resp.Body).Decode(proxy) if err != nil { return nil, err } proxy.client = client proxy.created = true return proxy, nil }
go
func (client *Client) Proxy(name string) (*Proxy, error) { // TODO url encode resp, err := http.Get(client.endpoint + "/proxies/" + name) if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "Proxy") if err != nil { return nil, err } proxy := new(Proxy) err = json.NewDecoder(resp.Body).Decode(proxy) if err != nil { return nil, err } proxy.client = client proxy.created = true return proxy, nil }
[ "func", "(", "client", "*", "Client", ")", "Proxy", "(", "name", "string", ")", "(", "*", "Proxy", ",", "error", ")", "{", "// TODO url encode", "resp", ",", "err", ":=", "http", ".", "Get", "(", "client", ".", "endpoint", "+", "\"", "\"", "+", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "checkError", "(", "resp", ",", "http", ".", "StatusOK", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "proxy", ":=", "new", "(", "Proxy", ")", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "proxy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "proxy", ".", "client", "=", "client", "\n", "proxy", ".", "created", "=", "true", "\n\n", "return", "proxy", ",", "nil", "\n", "}" ]
// Proxy returns a proxy by name.
[ "Proxy", "returns", "a", "proxy", "by", "name", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L112-L133
train
Shopify/toxiproxy
client/client.go
Populate
func (client *Client) Populate(config []Proxy) ([]*Proxy, error) { proxies := struct { Proxies []*Proxy `json:"proxies"` }{} request, err := json.Marshal(config) if err != nil { return nil, err } resp, err := http.Post(client.endpoint+"/populate", "application/json", bytes.NewReader(request)) if err != nil { return nil, err } // Response body may need to be read twice, we want to return both the proxy list and any errors var body bytes.Buffer tee := io.TeeReader(resp.Body, &body) err = json.NewDecoder(tee).Decode(&proxies) if err != nil { return nil, err } resp.Body = ioutil.NopCloser(&body) err = checkError(resp, http.StatusCreated, "Populate") return proxies.Proxies, err }
go
func (client *Client) Populate(config []Proxy) ([]*Proxy, error) { proxies := struct { Proxies []*Proxy `json:"proxies"` }{} request, err := json.Marshal(config) if err != nil { return nil, err } resp, err := http.Post(client.endpoint+"/populate", "application/json", bytes.NewReader(request)) if err != nil { return nil, err } // Response body may need to be read twice, we want to return both the proxy list and any errors var body bytes.Buffer tee := io.TeeReader(resp.Body, &body) err = json.NewDecoder(tee).Decode(&proxies) if err != nil { return nil, err } resp.Body = ioutil.NopCloser(&body) err = checkError(resp, http.StatusCreated, "Populate") return proxies.Proxies, err }
[ "func", "(", "client", "*", "Client", ")", "Populate", "(", "config", "[", "]", "Proxy", ")", "(", "[", "]", "*", "Proxy", ",", "error", ")", "{", "proxies", ":=", "struct", "{", "Proxies", "[", "]", "*", "Proxy", "`json:\"proxies\"`", "\n", "}", "{", "}", "\n", "request", ",", "err", ":=", "json", ".", "Marshal", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "http", ".", "Post", "(", "client", ".", "endpoint", "+", "\"", "\"", ",", "\"", "\"", ",", "bytes", ".", "NewReader", "(", "request", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Response body may need to be read twice, we want to return both the proxy list and any errors", "var", "body", "bytes", ".", "Buffer", "\n", "tee", ":=", "io", ".", "TeeReader", "(", "resp", ".", "Body", ",", "&", "body", ")", "\n", "err", "=", "json", ".", "NewDecoder", "(", "tee", ")", ".", "Decode", "(", "&", "proxies", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "resp", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "&", "body", ")", "\n", "err", "=", "checkError", "(", "resp", ",", "http", ".", "StatusCreated", ",", "\"", "\"", ")", "\n", "return", "proxies", ".", "Proxies", ",", "err", "\n", "}" ]
// Create a list of proxies using a configuration list. If a proxy already exists, it will be replaced // with the specified configuration. For large amounts of proxies, `config` can be loaded from a file. // Returns a list of the successfully created proxies.
[ "Create", "a", "list", "of", "proxies", "using", "a", "configuration", "list", ".", "If", "a", "proxy", "already", "exists", "it", "will", "be", "replaced", "with", "the", "specified", "configuration", ".", "For", "large", "amounts", "of", "proxies", "config", "can", "be", "loaded", "from", "a", "file", ".", "Returns", "a", "list", "of", "the", "successfully", "created", "proxies", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L138-L163
train
Shopify/toxiproxy
client/client.go
Save
func (proxy *Proxy) Save() error { request, err := json.Marshal(proxy) if err != nil { return err } var resp *http.Response if proxy.created { resp, err = http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name, "text/plain", bytes.NewReader(request)) } else { resp, err = http.Post(proxy.client.endpoint+"/proxies", "application/json", bytes.NewReader(request)) } if err != nil { return err } if proxy.created { err = checkError(resp, http.StatusOK, "Save") } else { err = checkError(resp, http.StatusCreated, "Create") } if err != nil { return err } err = json.NewDecoder(resp.Body).Decode(proxy) if err != nil { return err } proxy.created = true return nil }
go
func (proxy *Proxy) Save() error { request, err := json.Marshal(proxy) if err != nil { return err } var resp *http.Response if proxy.created { resp, err = http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name, "text/plain", bytes.NewReader(request)) } else { resp, err = http.Post(proxy.client.endpoint+"/proxies", "application/json", bytes.NewReader(request)) } if err != nil { return err } if proxy.created { err = checkError(resp, http.StatusOK, "Save") } else { err = checkError(resp, http.StatusCreated, "Create") } if err != nil { return err } err = json.NewDecoder(resp.Body).Decode(proxy) if err != nil { return err } proxy.created = true return nil }
[ "func", "(", "proxy", "*", "Proxy", ")", "Save", "(", ")", "error", "{", "request", ",", "err", ":=", "json", ".", "Marshal", "(", "proxy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "resp", "*", "http", ".", "Response", "\n", "if", "proxy", ".", "created", "{", "resp", ",", "err", "=", "http", ".", "Post", "(", "proxy", ".", "client", ".", "endpoint", "+", "\"", "\"", "+", "proxy", ".", "Name", ",", "\"", "\"", ",", "bytes", ".", "NewReader", "(", "request", ")", ")", "\n", "}", "else", "{", "resp", ",", "err", "=", "http", ".", "Post", "(", "proxy", ".", "client", ".", "endpoint", "+", "\"", "\"", ",", "\"", "\"", ",", "bytes", ".", "NewReader", "(", "request", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "proxy", ".", "created", "{", "err", "=", "checkError", "(", "resp", ",", "http", ".", "StatusOK", ",", "\"", "\"", ")", "\n", "}", "else", "{", "err", "=", "checkError", "(", "resp", ",", "http", ".", "StatusCreated", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "proxy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "proxy", ".", "created", "=", "true", "\n\n", "return", "nil", "\n", "}" ]
// Save saves changes to a proxy such as its enabled status or upstream port.
[ "Save", "saves", "changes", "to", "a", "proxy", "such", "as", "its", "enabled", "status", "or", "upstream", "port", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L166-L198
train
Shopify/toxiproxy
client/client.go
Toxics
func (proxy *Proxy) Toxics() (Toxics, error) { resp, err := http.Get(proxy.client.endpoint + "/proxies/" + proxy.Name + "/toxics") if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "Toxics") if err != nil { return nil, err } toxics := make(Toxics, 0) err = json.NewDecoder(resp.Body).Decode(&toxics) if err != nil { return nil, err } return toxics, nil }
go
func (proxy *Proxy) Toxics() (Toxics, error) { resp, err := http.Get(proxy.client.endpoint + "/proxies/" + proxy.Name + "/toxics") if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "Toxics") if err != nil { return nil, err } toxics := make(Toxics, 0) err = json.NewDecoder(resp.Body).Decode(&toxics) if err != nil { return nil, err } return toxics, nil }
[ "func", "(", "proxy", "*", "Proxy", ")", "Toxics", "(", ")", "(", "Toxics", ",", "error", ")", "{", "resp", ",", "err", ":=", "http", ".", "Get", "(", "proxy", ".", "client", ".", "endpoint", "+", "\"", "\"", "+", "proxy", ".", "Name", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "checkError", "(", "resp", ",", "http", ".", "StatusOK", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "toxics", ":=", "make", "(", "Toxics", ",", "0", ")", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "toxics", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "toxics", ",", "nil", "\n", "}" ]
// Toxics returns a map of all the active toxics and their attributes.
[ "Toxics", "returns", "a", "map", "of", "all", "the", "active", "toxics", "and", "their", "attributes", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L232-L250
train
Shopify/toxiproxy
client/client.go
ResetState
func (client *Client) ResetState() error { resp, err := http.Post(client.endpoint+"/reset", "text/plain", bytes.NewReader([]byte{})) if err != nil { return err } return checkError(resp, http.StatusNoContent, "ResetState") }
go
func (client *Client) ResetState() error { resp, err := http.Post(client.endpoint+"/reset", "text/plain", bytes.NewReader([]byte{})) if err != nil { return err } return checkError(resp, http.StatusNoContent, "ResetState") }
[ "func", "(", "client", "*", "Client", ")", "ResetState", "(", ")", "error", "{", "resp", ",", "err", ":=", "http", ".", "Post", "(", "client", ".", "endpoint", "+", "\"", "\"", ",", "\"", "\"", ",", "bytes", ".", "NewReader", "(", "[", "]", "byte", "{", "}", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "checkError", "(", "resp", ",", "http", ".", "StatusNoContent", ",", "\"", "\"", ")", "\n", "}" ]
// ResetState resets the state of all proxies and toxics in Toxiproxy.
[ "ResetState", "resets", "the", "state", "of", "all", "proxies", "and", "toxics", "in", "Toxiproxy", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L336-L343
train
Shopify/toxiproxy
link.go
Start
func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser) { go func() { bytes, err := io.Copy(link.input, source) if err != nil { logrus.WithFields(logrus.Fields{ "name": link.proxy.Name, "bytes": bytes, "err": err, }).Warn("Source terminated") } link.input.Close() }() for i, toxic := range link.toxics.chain[link.direction] { if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok { link.stubs[i].State = stateful.NewState() } go link.stubs[i].Run(toxic) } go func() { bytes, err := io.Copy(dest, link.output) if err != nil { logrus.WithFields(logrus.Fields{ "name": link.proxy.Name, "bytes": bytes, "err": err, }).Warn("Destination terminated") } dest.Close() link.toxics.RemoveLink(name) link.proxy.RemoveConnection(name) }() }
go
func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser) { go func() { bytes, err := io.Copy(link.input, source) if err != nil { logrus.WithFields(logrus.Fields{ "name": link.proxy.Name, "bytes": bytes, "err": err, }).Warn("Source terminated") } link.input.Close() }() for i, toxic := range link.toxics.chain[link.direction] { if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok { link.stubs[i].State = stateful.NewState() } go link.stubs[i].Run(toxic) } go func() { bytes, err := io.Copy(dest, link.output) if err != nil { logrus.WithFields(logrus.Fields{ "name": link.proxy.Name, "bytes": bytes, "err": err, }).Warn("Destination terminated") } dest.Close() link.toxics.RemoveLink(name) link.proxy.RemoveConnection(name) }() }
[ "func", "(", "link", "*", "ToxicLink", ")", "Start", "(", "name", "string", ",", "source", "io", ".", "Reader", ",", "dest", "io", ".", "WriteCloser", ")", "{", "go", "func", "(", ")", "{", "bytes", ",", "err", ":=", "io", ".", "Copy", "(", "link", ".", "input", ",", "source", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "link", ".", "proxy", ".", "Name", ",", "\"", "\"", ":", "bytes", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "link", ".", "input", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "for", "i", ",", "toxic", ":=", "range", "link", ".", "toxics", ".", "chain", "[", "link", ".", "direction", "]", "{", "if", "stateful", ",", "ok", ":=", "toxic", ".", "Toxic", ".", "(", "toxics", ".", "StatefulToxic", ")", ";", "ok", "{", "link", ".", "stubs", "[", "i", "]", ".", "State", "=", "stateful", ".", "NewState", "(", ")", "\n", "}", "\n\n", "go", "link", ".", "stubs", "[", "i", "]", ".", "Run", "(", "toxic", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "bytes", ",", "err", ":=", "io", ".", "Copy", "(", "dest", ",", "link", ".", "output", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "link", ".", "proxy", ".", "Name", ",", "\"", "\"", ":", "bytes", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "dest", ".", "Close", "(", ")", "\n", "link", ".", "toxics", ".", "RemoveLink", "(", "name", ")", "\n", "link", ".", "proxy", ".", "RemoveConnection", "(", "name", ")", "\n", "}", "(", ")", "\n", "}" ]
// Start the link with the specified toxics
[ "Start", "the", "link", "with", "the", "specified", "toxics" ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L56-L88
train
Shopify/toxiproxy
link.go
AddToxic
func (link *ToxicLink) AddToxic(toxic *toxics.ToxicWrapper) { i := len(link.stubs) newin := make(chan *stream.StreamChunk, toxic.BufferSize) link.stubs = append(link.stubs, toxics.NewToxicStub(newin, link.stubs[i-1].Output)) // Interrupt the last toxic so that we don't have a race when moving channels if link.stubs[i-1].InterruptToxic() { link.stubs[i-1].Output = newin if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok { link.stubs[i].State = stateful.NewState() } go link.stubs[i].Run(toxic) go link.stubs[i-1].Run(link.toxics.chain[link.direction][i-1]) } else { // This link is already closed, make sure the new toxic matches link.stubs[i].Output = newin // The real output is already closed, close this instead link.stubs[i].Close() } }
go
func (link *ToxicLink) AddToxic(toxic *toxics.ToxicWrapper) { i := len(link.stubs) newin := make(chan *stream.StreamChunk, toxic.BufferSize) link.stubs = append(link.stubs, toxics.NewToxicStub(newin, link.stubs[i-1].Output)) // Interrupt the last toxic so that we don't have a race when moving channels if link.stubs[i-1].InterruptToxic() { link.stubs[i-1].Output = newin if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok { link.stubs[i].State = stateful.NewState() } go link.stubs[i].Run(toxic) go link.stubs[i-1].Run(link.toxics.chain[link.direction][i-1]) } else { // This link is already closed, make sure the new toxic matches link.stubs[i].Output = newin // The real output is already closed, close this instead link.stubs[i].Close() } }
[ "func", "(", "link", "*", "ToxicLink", ")", "AddToxic", "(", "toxic", "*", "toxics", ".", "ToxicWrapper", ")", "{", "i", ":=", "len", "(", "link", ".", "stubs", ")", "\n\n", "newin", ":=", "make", "(", "chan", "*", "stream", ".", "StreamChunk", ",", "toxic", ".", "BufferSize", ")", "\n", "link", ".", "stubs", "=", "append", "(", "link", ".", "stubs", ",", "toxics", ".", "NewToxicStub", "(", "newin", ",", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "Output", ")", ")", "\n\n", "// Interrupt the last toxic so that we don't have a race when moving channels", "if", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "InterruptToxic", "(", ")", "{", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "Output", "=", "newin", "\n\n", "if", "stateful", ",", "ok", ":=", "toxic", ".", "Toxic", ".", "(", "toxics", ".", "StatefulToxic", ")", ";", "ok", "{", "link", ".", "stubs", "[", "i", "]", ".", "State", "=", "stateful", ".", "NewState", "(", ")", "\n", "}", "\n\n", "go", "link", ".", "stubs", "[", "i", "]", ".", "Run", "(", "toxic", ")", "\n", "go", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "Run", "(", "link", ".", "toxics", ".", "chain", "[", "link", ".", "direction", "]", "[", "i", "-", "1", "]", ")", "\n", "}", "else", "{", "// This link is already closed, make sure the new toxic matches", "link", ".", "stubs", "[", "i", "]", ".", "Output", "=", "newin", "// The real output is already closed, close this instead", "\n", "link", ".", "stubs", "[", "i", "]", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Add a toxic to the end of the chain.
[ "Add", "a", "toxic", "to", "the", "end", "of", "the", "chain", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L91-L112
train
Shopify/toxiproxy
link.go
UpdateToxic
func (link *ToxicLink) UpdateToxic(toxic *toxics.ToxicWrapper) { if link.stubs[toxic.Index].InterruptToxic() { go link.stubs[toxic.Index].Run(toxic) } }
go
func (link *ToxicLink) UpdateToxic(toxic *toxics.ToxicWrapper) { if link.stubs[toxic.Index].InterruptToxic() { go link.stubs[toxic.Index].Run(toxic) } }
[ "func", "(", "link", "*", "ToxicLink", ")", "UpdateToxic", "(", "toxic", "*", "toxics", ".", "ToxicWrapper", ")", "{", "if", "link", ".", "stubs", "[", "toxic", ".", "Index", "]", ".", "InterruptToxic", "(", ")", "{", "go", "link", ".", "stubs", "[", "toxic", ".", "Index", "]", ".", "Run", "(", "toxic", ")", "\n", "}", "\n", "}" ]
// Update an existing toxic in the chain.
[ "Update", "an", "existing", "toxic", "in", "the", "chain", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L115-L119
train
Shopify/toxiproxy
link.go
RemoveToxic
func (link *ToxicLink) RemoveToxic(toxic *toxics.ToxicWrapper) { i := toxic.Index if link.stubs[i].InterruptToxic() { cleanup, ok := toxic.Toxic.(toxics.CleanupToxic) if ok { cleanup.Cleanup(link.stubs[i]) // Cleanup could have closed the stub. if link.stubs[i].Closed() { return } } stop := make(chan bool) // Interrupt the previous toxic to update its output go func() { stop <- link.stubs[i-1].InterruptToxic() }() // Unblock the previous toxic if it is trying to flush // If the previous toxic is closed, continue flusing until we reach the end. interrupted := false stopped := false for !interrupted { select { case interrupted = <-stop: stopped = true case tmp := <-link.stubs[i].Input: if tmp == nil { link.stubs[i].Close() if !stopped { <-stop } return } link.stubs[i].Output <- tmp } } // Empty the toxic's buffer if necessary for len(link.stubs[i].Input) > 0 { tmp := <-link.stubs[i].Input if tmp == nil { link.stubs[i].Close() return } link.stubs[i].Output <- tmp } link.stubs[i-1].Output = link.stubs[i].Output link.stubs = append(link.stubs[:i], link.stubs[i+1:]...) go link.stubs[i-1].Run(link.toxics.chain[link.direction][i-1]) } }
go
func (link *ToxicLink) RemoveToxic(toxic *toxics.ToxicWrapper) { i := toxic.Index if link.stubs[i].InterruptToxic() { cleanup, ok := toxic.Toxic.(toxics.CleanupToxic) if ok { cleanup.Cleanup(link.stubs[i]) // Cleanup could have closed the stub. if link.stubs[i].Closed() { return } } stop := make(chan bool) // Interrupt the previous toxic to update its output go func() { stop <- link.stubs[i-1].InterruptToxic() }() // Unblock the previous toxic if it is trying to flush // If the previous toxic is closed, continue flusing until we reach the end. interrupted := false stopped := false for !interrupted { select { case interrupted = <-stop: stopped = true case tmp := <-link.stubs[i].Input: if tmp == nil { link.stubs[i].Close() if !stopped { <-stop } return } link.stubs[i].Output <- tmp } } // Empty the toxic's buffer if necessary for len(link.stubs[i].Input) > 0 { tmp := <-link.stubs[i].Input if tmp == nil { link.stubs[i].Close() return } link.stubs[i].Output <- tmp } link.stubs[i-1].Output = link.stubs[i].Output link.stubs = append(link.stubs[:i], link.stubs[i+1:]...) go link.stubs[i-1].Run(link.toxics.chain[link.direction][i-1]) } }
[ "func", "(", "link", "*", "ToxicLink", ")", "RemoveToxic", "(", "toxic", "*", "toxics", ".", "ToxicWrapper", ")", "{", "i", ":=", "toxic", ".", "Index", "\n\n", "if", "link", ".", "stubs", "[", "i", "]", ".", "InterruptToxic", "(", ")", "{", "cleanup", ",", "ok", ":=", "toxic", ".", "Toxic", ".", "(", "toxics", ".", "CleanupToxic", ")", "\n", "if", "ok", "{", "cleanup", ".", "Cleanup", "(", "link", ".", "stubs", "[", "i", "]", ")", "\n", "// Cleanup could have closed the stub.", "if", "link", ".", "stubs", "[", "i", "]", ".", "Closed", "(", ")", "{", "return", "\n", "}", "\n", "}", "\n\n", "stop", ":=", "make", "(", "chan", "bool", ")", "\n", "// Interrupt the previous toxic to update its output", "go", "func", "(", ")", "{", "stop", "<-", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "InterruptToxic", "(", ")", "\n", "}", "(", ")", "\n\n", "// Unblock the previous toxic if it is trying to flush", "// If the previous toxic is closed, continue flusing until we reach the end.", "interrupted", ":=", "false", "\n", "stopped", ":=", "false", "\n", "for", "!", "interrupted", "{", "select", "{", "case", "interrupted", "=", "<-", "stop", ":", "stopped", "=", "true", "\n", "case", "tmp", ":=", "<-", "link", ".", "stubs", "[", "i", "]", ".", "Input", ":", "if", "tmp", "==", "nil", "{", "link", ".", "stubs", "[", "i", "]", ".", "Close", "(", ")", "\n", "if", "!", "stopped", "{", "<-", "stop", "\n", "}", "\n", "return", "\n", "}", "\n", "link", ".", "stubs", "[", "i", "]", ".", "Output", "<-", "tmp", "\n", "}", "\n", "}", "\n\n", "// Empty the toxic's buffer if necessary", "for", "len", "(", "link", ".", "stubs", "[", "i", "]", ".", "Input", ")", ">", "0", "{", "tmp", ":=", "<-", "link", ".", "stubs", "[", "i", "]", ".", "Input", "\n", "if", "tmp", "==", "nil", "{", "link", ".", "stubs", "[", "i", "]", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "link", ".", "stubs", "[", "i", "]", ".", "Output", "<-", "tmp", "\n", "}", "\n\n", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "Output", "=", "link", ".", "stubs", "[", "i", "]", ".", "Output", "\n", "link", ".", "stubs", "=", "append", "(", "link", ".", "stubs", "[", ":", "i", "]", ",", "link", ".", "stubs", "[", "i", "+", "1", ":", "]", "...", ")", "\n\n", "go", "link", ".", "stubs", "[", "i", "-", "1", "]", ".", "Run", "(", "link", ".", "toxics", ".", "chain", "[", "link", ".", "direction", "]", "[", "i", "-", "1", "]", ")", "\n", "}", "\n", "}" ]
// Remove an existing toxic from the chain.
[ "Remove", "an", "existing", "toxic", "from", "the", "chain", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L122-L176
train
Shopify/toxiproxy
toxics/toxic.go
Run
func (s *ToxicStub) Run(toxic *ToxicWrapper) { s.running = make(chan struct{}) defer close(s.running) if rand.Float32() < toxic.Toxicity { toxic.Pipe(s) } else { new(NoopToxic).Pipe(s) } }
go
func (s *ToxicStub) Run(toxic *ToxicWrapper) { s.running = make(chan struct{}) defer close(s.running) if rand.Float32() < toxic.Toxicity { toxic.Pipe(s) } else { new(NoopToxic).Pipe(s) } }
[ "func", "(", "s", "*", "ToxicStub", ")", "Run", "(", "toxic", "*", "ToxicWrapper", ")", "{", "s", ".", "running", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "defer", "close", "(", "s", ".", "running", ")", "\n", "if", "rand", ".", "Float32", "(", ")", "<", "toxic", ".", "Toxicity", "{", "toxic", ".", "Pipe", "(", "s", ")", "\n", "}", "else", "{", "new", "(", "NoopToxic", ")", ".", "Pipe", "(", "s", ")", "\n", "}", "\n", "}" ]
// Begin running a toxic on this stub, can be interrupted. // Runs a noop toxic randomly depending on toxicity
[ "Begin", "running", "a", "toxic", "on", "this", "stub", "can", "be", "interrupted", ".", "Runs", "a", "noop", "toxic", "randomly", "depending", "on", "toxicity" ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxics/toxic.go#L78-L86
train
Shopify/toxiproxy
toxics/toxic.go
InterruptToxic
func (s *ToxicStub) InterruptToxic() bool { select { case <-s.closed: return false case s.Interrupt <- struct{}{}: <-s.running // Wait for the running toxic to exit return true } }
go
func (s *ToxicStub) InterruptToxic() bool { select { case <-s.closed: return false case s.Interrupt <- struct{}{}: <-s.running // Wait for the running toxic to exit return true } }
[ "func", "(", "s", "*", "ToxicStub", ")", "InterruptToxic", "(", ")", "bool", "{", "select", "{", "case", "<-", "s", ".", "closed", ":", "return", "false", "\n", "case", "s", ".", "Interrupt", "<-", "struct", "{", "}", "{", "}", ":", "<-", "s", ".", "running", "// Wait for the running toxic to exit", "\n", "return", "true", "\n", "}", "\n", "}" ]
// Interrupt the flow of data so that the toxic controlling the stub can be replaced. // Returns true if the stream was successfully interrupted, or false if the stream is closed.
[ "Interrupt", "the", "flow", "of", "data", "so", "that", "the", "toxic", "controlling", "the", "stub", "can", "be", "replaced", ".", "Returns", "true", "if", "the", "stream", "was", "successfully", "interrupted", "or", "false", "if", "the", "stream", "is", "closed", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxics/toxic.go#L90-L98
train
Shopify/toxiproxy
toxic_collection.go
findToxicByName
func (c *ToxicCollection) findToxicByName(name string) *toxics.ToxicWrapper { for dir := range c.chain { for i, toxic := range c.chain[dir] { if i == 0 { // Skip the first noop toxic, it has no name continue } if toxic.Name == name { return toxic } } } return nil }
go
func (c *ToxicCollection) findToxicByName(name string) *toxics.ToxicWrapper { for dir := range c.chain { for i, toxic := range c.chain[dir] { if i == 0 { // Skip the first noop toxic, it has no name continue } if toxic.Name == name { return toxic } } } return nil }
[ "func", "(", "c", "*", "ToxicCollection", ")", "findToxicByName", "(", "name", "string", ")", "*", "toxics", ".", "ToxicWrapper", "{", "for", "dir", ":=", "range", "c", ".", "chain", "{", "for", "i", ",", "toxic", ":=", "range", "c", ".", "chain", "[", "dir", "]", "{", "if", "i", "==", "0", "{", "// Skip the first noop toxic, it has no name", "continue", "\n", "}", "\n", "if", "toxic", ".", "Name", "==", "name", "{", "return", "toxic", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// All following functions assume the lock is already grabbed
[ "All", "following", "functions", "assume", "the", "lock", "is", "already", "grabbed" ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxic_collection.go#L188-L201
train
Shopify/toxiproxy
proxy.go
server
func (proxy *Proxy) server() { ln, err := net.Listen("tcp", proxy.Listen) if err != nil { proxy.started <- err return } proxy.Listen = ln.Addr().String() proxy.started <- nil logrus.WithFields(logrus.Fields{ "name": proxy.Name, "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Started proxy") acceptTomb := tomb.Tomb{} defer acceptTomb.Done() // This channel is to kill the blocking Accept() call below by closing the // net.Listener. go func() { <-proxy.tomb.Dying() // Notify ln.Accept() that the shutdown was safe acceptTomb.Killf("Shutting down from stop()") // Unblock ln.Accept() err := ln.Close() if err != nil { logrus.WithFields(logrus.Fields{ "proxy": proxy.Name, "listen": proxy.Listen, "err": err, }).Warn("Attempted to close an already closed proxy server") } // Wait for the accept loop to finish processing acceptTomb.Wait() proxy.tomb.Done() }() for { client, err := ln.Accept() if err != nil { // This is to confirm we're being shut down in a legit way. Unfortunately, // Go doesn't export the error when it's closed from Close() so we have to // sync up with a channel here. // // See http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/ select { case <-acceptTomb.Dying(): default: logrus.WithFields(logrus.Fields{ "proxy": proxy.Name, "listen": proxy.Listen, "err": err, }).Warn("Error while accepting client") } return } logrus.WithFields(logrus.Fields{ "name": proxy.Name, "client": client.RemoteAddr(), "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Accepted client") upstream, err := net.Dial("tcp", proxy.Upstream) if err != nil { logrus.WithFields(logrus.Fields{ "name": proxy.Name, "client": client.RemoteAddr(), "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Error("Unable to open connection to upstream") client.Close() continue } name := client.RemoteAddr().String() proxy.connections.Lock() proxy.connections.list[name+"upstream"] = upstream proxy.connections.list[name+"downstream"] = client proxy.connections.Unlock() proxy.Toxics.StartLink(name+"upstream", client, upstream, stream.Upstream) proxy.Toxics.StartLink(name+"downstream", upstream, client, stream.Downstream) } }
go
func (proxy *Proxy) server() { ln, err := net.Listen("tcp", proxy.Listen) if err != nil { proxy.started <- err return } proxy.Listen = ln.Addr().String() proxy.started <- nil logrus.WithFields(logrus.Fields{ "name": proxy.Name, "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Started proxy") acceptTomb := tomb.Tomb{} defer acceptTomb.Done() // This channel is to kill the blocking Accept() call below by closing the // net.Listener. go func() { <-proxy.tomb.Dying() // Notify ln.Accept() that the shutdown was safe acceptTomb.Killf("Shutting down from stop()") // Unblock ln.Accept() err := ln.Close() if err != nil { logrus.WithFields(logrus.Fields{ "proxy": proxy.Name, "listen": proxy.Listen, "err": err, }).Warn("Attempted to close an already closed proxy server") } // Wait for the accept loop to finish processing acceptTomb.Wait() proxy.tomb.Done() }() for { client, err := ln.Accept() if err != nil { // This is to confirm we're being shut down in a legit way. Unfortunately, // Go doesn't export the error when it's closed from Close() so we have to // sync up with a channel here. // // See http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/ select { case <-acceptTomb.Dying(): default: logrus.WithFields(logrus.Fields{ "proxy": proxy.Name, "listen": proxy.Listen, "err": err, }).Warn("Error while accepting client") } return } logrus.WithFields(logrus.Fields{ "name": proxy.Name, "client": client.RemoteAddr(), "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Accepted client") upstream, err := net.Dial("tcp", proxy.Upstream) if err != nil { logrus.WithFields(logrus.Fields{ "name": proxy.Name, "client": client.RemoteAddr(), "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Error("Unable to open connection to upstream") client.Close() continue } name := client.RemoteAddr().String() proxy.connections.Lock() proxy.connections.list[name+"upstream"] = upstream proxy.connections.list[name+"downstream"] = client proxy.connections.Unlock() proxy.Toxics.StartLink(name+"upstream", client, upstream, stream.Upstream) proxy.Toxics.StartLink(name+"downstream", upstream, client, stream.Downstream) } }
[ "func", "(", "proxy", "*", "Proxy", ")", "server", "(", ")", "{", "ln", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "proxy", ".", "Listen", ")", "\n", "if", "err", "!=", "nil", "{", "proxy", ".", "started", "<-", "err", "\n", "return", "\n", "}", "\n\n", "proxy", ".", "Listen", "=", "ln", ".", "Addr", "(", ")", ".", "String", "(", ")", "\n", "proxy", ".", "started", "<-", "nil", "\n\n", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "proxy", ".", "Name", ",", "\"", "\"", ":", "proxy", ".", "Listen", ",", "\"", "\"", ":", "proxy", ".", "Upstream", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "acceptTomb", ":=", "tomb", ".", "Tomb", "{", "}", "\n", "defer", "acceptTomb", ".", "Done", "(", ")", "\n\n", "// This channel is to kill the blocking Accept() call below by closing the", "// net.Listener.", "go", "func", "(", ")", "{", "<-", "proxy", ".", "tomb", ".", "Dying", "(", ")", "\n\n", "// Notify ln.Accept() that the shutdown was safe", "acceptTomb", ".", "Killf", "(", "\"", "\"", ")", "\n", "// Unblock ln.Accept()", "err", ":=", "ln", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "proxy", ".", "Name", ",", "\"", "\"", ":", "proxy", ".", "Listen", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Wait for the accept loop to finish processing", "acceptTomb", ".", "Wait", "(", ")", "\n", "proxy", ".", "tomb", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "for", "{", "client", ",", "err", ":=", "ln", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// This is to confirm we're being shut down in a legit way. Unfortunately,", "// Go doesn't export the error when it's closed from Close() so we have to", "// sync up with a channel here.", "//", "// See http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/", "select", "{", "case", "<-", "acceptTomb", ".", "Dying", "(", ")", ":", "default", ":", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "proxy", ".", "Name", ",", "\"", "\"", ":", "proxy", ".", "Listen", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "proxy", ".", "Name", ",", "\"", "\"", ":", "client", ".", "RemoteAddr", "(", ")", ",", "\"", "\"", ":", "proxy", ".", "Listen", ",", "\"", "\"", ":", "proxy", ".", "Upstream", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "upstream", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "proxy", ".", "Upstream", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "proxy", ".", "Name", ",", "\"", "\"", ":", "client", ".", "RemoteAddr", "(", ")", ",", "\"", "\"", ":", "proxy", ".", "Listen", ",", "\"", "\"", ":", "proxy", ".", "Upstream", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "client", ".", "Close", "(", ")", "\n", "continue", "\n", "}", "\n\n", "name", ":=", "client", ".", "RemoteAddr", "(", ")", ".", "String", "(", ")", "\n", "proxy", ".", "connections", ".", "Lock", "(", ")", "\n", "proxy", ".", "connections", ".", "list", "[", "name", "+", "\"", "\"", "]", "=", "upstream", "\n", "proxy", ".", "connections", ".", "list", "[", "name", "+", "\"", "\"", "]", "=", "client", "\n", "proxy", ".", "connections", ".", "Unlock", "(", ")", "\n", "proxy", ".", "Toxics", ".", "StartLink", "(", "name", "+", "\"", "\"", ",", "client", ",", "upstream", ",", "stream", ".", "Upstream", ")", "\n", "proxy", ".", "Toxics", ".", "StartLink", "(", "name", "+", "\"", "\"", ",", "upstream", ",", "client", ",", "stream", ".", "Downstream", ")", "\n", "}", "\n", "}" ]
// server runs the Proxy server, accepting new clients and creating Links to // connect them to upstreams.
[ "server", "runs", "the", "Proxy", "server", "accepting", "new", "clients", "and", "creating", "Links", "to", "connect", "them", "to", "upstreams", "." ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L94-L182
train
Shopify/toxiproxy
proxy.go
start
func start(proxy *Proxy) error { if proxy.Enabled { return ErrProxyAlreadyStarted } proxy.tomb = tomb.Tomb{} // Reset tomb, from previous starts/stops go proxy.server() err := <-proxy.started // Only enable the proxy if it successfully started proxy.Enabled = err == nil return err }
go
func start(proxy *Proxy) error { if proxy.Enabled { return ErrProxyAlreadyStarted } proxy.tomb = tomb.Tomb{} // Reset tomb, from previous starts/stops go proxy.server() err := <-proxy.started // Only enable the proxy if it successfully started proxy.Enabled = err == nil return err }
[ "func", "start", "(", "proxy", "*", "Proxy", ")", "error", "{", "if", "proxy", ".", "Enabled", "{", "return", "ErrProxyAlreadyStarted", "\n", "}", "\n\n", "proxy", ".", "tomb", "=", "tomb", ".", "Tomb", "{", "}", "// Reset tomb, from previous starts/stops", "\n", "go", "proxy", ".", "server", "(", ")", "\n", "err", ":=", "<-", "proxy", ".", "started", "\n", "// Only enable the proxy if it successfully started", "proxy", ".", "Enabled", "=", "err", "==", "nil", "\n", "return", "err", "\n", "}" ]
// Starts a proxy, assumes the lock has already been taken
[ "Starts", "a", "proxy", "assumes", "the", "lock", "has", "already", "been", "taken" ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L191-L202
train
Shopify/toxiproxy
proxy.go
stop
func stop(proxy *Proxy) { if !proxy.Enabled { return } proxy.Enabled = false proxy.tomb.Killf("Shutting down from stop()") proxy.tomb.Wait() // Wait until we stop accepting new connections proxy.connections.Lock() defer proxy.connections.Unlock() for _, conn := range proxy.connections.list { conn.Close() } logrus.WithFields(logrus.Fields{ "name": proxy.Name, "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Terminated proxy") }
go
func stop(proxy *Proxy) { if !proxy.Enabled { return } proxy.Enabled = false proxy.tomb.Killf("Shutting down from stop()") proxy.tomb.Wait() // Wait until we stop accepting new connections proxy.connections.Lock() defer proxy.connections.Unlock() for _, conn := range proxy.connections.list { conn.Close() } logrus.WithFields(logrus.Fields{ "name": proxy.Name, "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Terminated proxy") }
[ "func", "stop", "(", "proxy", "*", "Proxy", ")", "{", "if", "!", "proxy", ".", "Enabled", "{", "return", "\n", "}", "\n", "proxy", ".", "Enabled", "=", "false", "\n\n", "proxy", ".", "tomb", ".", "Killf", "(", "\"", "\"", ")", "\n", "proxy", ".", "tomb", ".", "Wait", "(", ")", "// Wait until we stop accepting new connections", "\n\n", "proxy", ".", "connections", ".", "Lock", "(", ")", "\n", "defer", "proxy", ".", "connections", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "conn", ":=", "range", "proxy", ".", "connections", ".", "list", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n\n", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "proxy", ".", "Name", ",", "\"", "\"", ":", "proxy", ".", "Listen", ",", "\"", "\"", ":", "proxy", ".", "Upstream", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// Stops a proxy, assumes the lock has already been taken
[ "Stops", "a", "proxy", "assumes", "the", "lock", "has", "already", "been", "taken" ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L205-L225
train
cweill/gotests
internal/goparser/goparser.go
Parse
func (p *Parser) Parse(srcPath string, files []models.Path) (*Result, error) { b, err := p.readFile(srcPath) if err != nil { return nil, err } fset := token.NewFileSet() f, err := p.parseFile(fset, srcPath) if err != nil { return nil, err } fs, err := p.parseFiles(fset, f, files) if err != nil { return nil, err } return &Result{ Header: &models.Header{ Comments: parsePkgComment(f, f.Package), Package: f.Name.String(), Imports: parseImports(f.Imports), Code: goCode(b, f), }, Funcs: p.parseFunctions(fset, f, fs), }, nil }
go
func (p *Parser) Parse(srcPath string, files []models.Path) (*Result, error) { b, err := p.readFile(srcPath) if err != nil { return nil, err } fset := token.NewFileSet() f, err := p.parseFile(fset, srcPath) if err != nil { return nil, err } fs, err := p.parseFiles(fset, f, files) if err != nil { return nil, err } return &Result{ Header: &models.Header{ Comments: parsePkgComment(f, f.Package), Package: f.Name.String(), Imports: parseImports(f.Imports), Code: goCode(b, f), }, Funcs: p.parseFunctions(fset, f, fs), }, nil }
[ "func", "(", "p", "*", "Parser", ")", "Parse", "(", "srcPath", "string", ",", "files", "[", "]", "models", ".", "Path", ")", "(", "*", "Result", ",", "error", ")", "{", "b", ",", "err", ":=", "p", ".", "readFile", "(", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "f", ",", "err", ":=", "p", ".", "parseFile", "(", "fset", ",", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fs", ",", "err", ":=", "p", ".", "parseFiles", "(", "fset", ",", "f", ",", "files", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Result", "{", "Header", ":", "&", "models", ".", "Header", "{", "Comments", ":", "parsePkgComment", "(", "f", ",", "f", ".", "Package", ")", ",", "Package", ":", "f", ".", "Name", ".", "String", "(", ")", ",", "Imports", ":", "parseImports", "(", "f", ".", "Imports", ")", ",", "Code", ":", "goCode", "(", "b", ",", "f", ")", ",", "}", ",", "Funcs", ":", "p", ".", "parseFunctions", "(", "fset", ",", "f", ",", "fs", ")", ",", "}", ",", "nil", "\n", "}" ]
// Parse parses a given Go file at srcPath, along any files that share the same // package, into a domain model for generating tests.
[ "Parse", "parses", "a", "given", "Go", "file", "at", "srcPath", "along", "any", "files", "that", "share", "the", "same", "package", "into", "a", "domain", "model", "for", "generating", "tests", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/goparser/goparser.go#L38-L61
train
cweill/gotests
internal/goparser/goparser.go
goCode
func goCode(b []byte, f *ast.File) []byte { furthestPos := f.Name.End() for _, node := range f.Imports { if pos := node.End(); pos > furthestPos { furthestPos = pos } } if furthestPos < token.Pos(len(b)) { furthestPos++ // Avoid wrong output on windows-encoded files if b[furthestPos-2] == '\r' && b[furthestPos-1] == '\n' && furthestPos < token.Pos(len(b)) { furthestPos++ } } return b[furthestPos:] }
go
func goCode(b []byte, f *ast.File) []byte { furthestPos := f.Name.End() for _, node := range f.Imports { if pos := node.End(); pos > furthestPos { furthestPos = pos } } if furthestPos < token.Pos(len(b)) { furthestPos++ // Avoid wrong output on windows-encoded files if b[furthestPos-2] == '\r' && b[furthestPos-1] == '\n' && furthestPos < token.Pos(len(b)) { furthestPos++ } } return b[furthestPos:] }
[ "func", "goCode", "(", "b", "[", "]", "byte", ",", "f", "*", "ast", ".", "File", ")", "[", "]", "byte", "{", "furthestPos", ":=", "f", ".", "Name", ".", "End", "(", ")", "\n", "for", "_", ",", "node", ":=", "range", "f", ".", "Imports", "{", "if", "pos", ":=", "node", ".", "End", "(", ")", ";", "pos", ">", "furthestPos", "{", "furthestPos", "=", "pos", "\n", "}", "\n", "}", "\n", "if", "furthestPos", "<", "token", ".", "Pos", "(", "len", "(", "b", ")", ")", "{", "furthestPos", "++", "\n\n", "// Avoid wrong output on windows-encoded files", "if", "b", "[", "furthestPos", "-", "2", "]", "==", "'\\r'", "&&", "b", "[", "furthestPos", "-", "1", "]", "==", "'\\n'", "&&", "furthestPos", "<", "token", ".", "Pos", "(", "len", "(", "b", ")", ")", "{", "furthestPos", "++", "\n", "}", "\n", "}", "\n", "return", "b", "[", "furthestPos", ":", "]", "\n", "}" ]
// Returns the Go code below the imports block.
[ "Returns", "the", "Go", "code", "below", "the", "imports", "block", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/goparser/goparser.go#L163-L179
train
cweill/gotests
internal/input/input.go
Files
func Files(srcPath string) ([]models.Path, error) { srcPath, err := filepath.Abs(srcPath) if err != nil { return nil, fmt.Errorf("filepath.Abs: %v\n", err) } var fi os.FileInfo if fi, err = os.Stat(srcPath); err != nil { return nil, fmt.Errorf("os.Stat: %v\n", err) } if fi.IsDir() { return dirFiles(srcPath) } return file(srcPath) }
go
func Files(srcPath string) ([]models.Path, error) { srcPath, err := filepath.Abs(srcPath) if err != nil { return nil, fmt.Errorf("filepath.Abs: %v\n", err) } var fi os.FileInfo if fi, err = os.Stat(srcPath); err != nil { return nil, fmt.Errorf("os.Stat: %v\n", err) } if fi.IsDir() { return dirFiles(srcPath) } return file(srcPath) }
[ "func", "Files", "(", "srcPath", "string", ")", "(", "[", "]", "models", ".", "Path", ",", "error", ")", "{", "srcPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "var", "fi", "os", ".", "FileInfo", "\n", "if", "fi", ",", "err", "=", "os", ".", "Stat", "(", "srcPath", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "return", "dirFiles", "(", "srcPath", ")", "\n", "}", "\n", "return", "file", "(", "srcPath", ")", "\n", "}" ]
// Files returns all the Golang files for the given path. Ignores hidden files.
[ "Files", "returns", "all", "the", "Golang", "files", "for", "the", "given", "path", ".", "Ignores", "hidden", "files", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/input/input.go#L13-L26
train
cweill/gotests
internal/render/render.go
LoadCustomTemplates
func LoadCustomTemplates(dir string) error { initEmptyTmpls() files, err := ioutil.ReadDir(dir) if err != nil { return fmt.Errorf("ioutil.ReadDir: %v", err) } templateFiles := []string{} for _, f := range files { templateFiles = append(templateFiles, path.Join(dir, f.Name())) } tmpls, err = tmpls.ParseFiles(templateFiles...) if err != nil { return fmt.Errorf("tmpls.ParseFiles: %v", err) } return nil }
go
func LoadCustomTemplates(dir string) error { initEmptyTmpls() files, err := ioutil.ReadDir(dir) if err != nil { return fmt.Errorf("ioutil.ReadDir: %v", err) } templateFiles := []string{} for _, f := range files { templateFiles = append(templateFiles, path.Join(dir, f.Name())) } tmpls, err = tmpls.ParseFiles(templateFiles...) if err != nil { return fmt.Errorf("tmpls.ParseFiles: %v", err) } return nil }
[ "func", "LoadCustomTemplates", "(", "dir", "string", ")", "error", "{", "initEmptyTmpls", "(", ")", "\n\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "templateFiles", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "templateFiles", "=", "append", "(", "templateFiles", ",", "path", ".", "Join", "(", "dir", ",", "f", ".", "Name", "(", ")", ")", ")", "\n", "}", "\n", "tmpls", ",", "err", "=", "tmpls", ".", "ParseFiles", "(", "templateFiles", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LoadCustomTemplates allows to load in custom templates from a specified path.
[ "LoadCustomTemplates", "allows", "to", "load", "in", "custom", "templates", "from", "a", "specified", "path", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/render.go#L30-L47
train
cweill/gotests
internal/render/bindata/esc.go
FSByte
func FSByte(useLocal bool, name string) ([]byte, error) { if useLocal { f, err := _escLocal.Open(name) if err != nil { return nil, err } b, err := ioutil.ReadAll(f) _ = f.Close() return b, err } f, err := _escStatic.prepare(name) if err != nil { return nil, err } return f.data, nil }
go
func FSByte(useLocal bool, name string) ([]byte, error) { if useLocal { f, err := _escLocal.Open(name) if err != nil { return nil, err } b, err := ioutil.ReadAll(f) _ = f.Close() return b, err } f, err := _escStatic.prepare(name) if err != nil { return nil, err } return f.data, nil }
[ "func", "FSByte", "(", "useLocal", "bool", ",", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "useLocal", "{", "f", ",", "err", ":=", "_escLocal", ".", "Open", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "_", "=", "f", ".", "Close", "(", ")", "\n", "return", "b", ",", "err", "\n", "}", "\n", "f", ",", "err", ":=", "_escStatic", ".", "prepare", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "f", ".", "data", ",", "nil", "\n", "}" ]
// FSByte returns the named file from the embedded assets. If useLocal is // true, the filesystem's contents are instead used.
[ "FSByte", "returns", "the", "named", "file", "from", "the", "embedded", "assets", ".", "If", "useLocal", "is", "true", "the", "filesystem", "s", "contents", "are", "instead", "used", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L173-L188
train
cweill/gotests
internal/render/bindata/esc.go
FSMustByte
func FSMustByte(useLocal bool, name string) []byte { b, err := FSByte(useLocal, name) if err != nil { panic(err) } return b }
go
func FSMustByte(useLocal bool, name string) []byte { b, err := FSByte(useLocal, name) if err != nil { panic(err) } return b }
[ "func", "FSMustByte", "(", "useLocal", "bool", ",", "name", "string", ")", "[", "]", "byte", "{", "b", ",", "err", ":=", "FSByte", "(", "useLocal", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "b", "\n", "}" ]
// FSMustByte is the same as FSByte, but panics if name is not present.
[ "FSMustByte", "is", "the", "same", "as", "FSByte", "but", "panics", "if", "name", "is", "not", "present", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L191-L197
train
cweill/gotests
internal/render/bindata/esc.go
FSString
func FSString(useLocal bool, name string) (string, error) { b, err := FSByte(useLocal, name) return string(b), err }
go
func FSString(useLocal bool, name string) (string, error) { b, err := FSByte(useLocal, name) return string(b), err }
[ "func", "FSString", "(", "useLocal", "bool", ",", "name", "string", ")", "(", "string", ",", "error", ")", "{", "b", ",", "err", ":=", "FSByte", "(", "useLocal", ",", "name", ")", "\n", "return", "string", "(", "b", ")", ",", "err", "\n", "}" ]
// FSString is the string version of FSByte.
[ "FSString", "is", "the", "string", "version", "of", "FSByte", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L200-L203
train
cweill/gotests
internal/render/bindata/esc.go
FSMustString
func FSMustString(useLocal bool, name string) string { return string(FSMustByte(useLocal, name)) }
go
func FSMustString(useLocal bool, name string) string { return string(FSMustByte(useLocal, name)) }
[ "func", "FSMustString", "(", "useLocal", "bool", ",", "name", "string", ")", "string", "{", "return", "string", "(", "FSMustByte", "(", "useLocal", ",", "name", ")", ")", "\n", "}" ]
// FSMustString is the string version of FSMustByte.
[ "FSMustString", "is", "the", "string", "version", "of", "FSMustByte", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L206-L208
train
dropbox/godropbox
database/binlog/parsed_event_reader.go
NewParsedV4EventReader
func NewParsedV4EventReader( reader EventReader, parsers V4EventParserMap) EventReader { return &parsedV4EventReader{ reader: reader, eventParsers: parsers, } }
go
func NewParsedV4EventReader( reader EventReader, parsers V4EventParserMap) EventReader { return &parsedV4EventReader{ reader: reader, eventParsers: parsers, } }
[ "func", "NewParsedV4EventReader", "(", "reader", "EventReader", ",", "parsers", "V4EventParserMap", ")", "EventReader", "{", "return", "&", "parsedV4EventReader", "{", "reader", ":", "reader", ",", "eventParsers", ":", "parsers", ",", "}", "\n", "}" ]
// This returns an EventReader which applies the appropriate parser on each // raw v4 event in the stream. If no parser is available for the event, // or if an error occurs during parsing, then the reader will return the // original event along with the error.
[ "This", "returns", "an", "EventReader", "which", "applies", "the", "appropriate", "parser", "on", "each", "raw", "v4", "event", "in", "the", "stream", ".", "If", "no", "parser", "is", "available", "for", "the", "event", "or", "if", "an", "error", "occurs", "during", "parsing", "then", "the", "reader", "will", "return", "the", "original", "event", "along", "with", "the", "error", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/parsed_event_reader.go#L16-L24
train
dropbox/godropbox
io2/writer_to_reader_adapter.go
NewWriterToReaderAdapter
func NewWriterToReaderAdapter(toBeAdapted func(io.Reader) (io.Reader, error), output io.Writer, shouldCloseDownstream bool) io.WriteCloser { retval := privateReaderAdapter{ Writer: WriterToReaderAdapter{ workChan: make(chan *[]byte), doneWorkChan: make(chan *[]byte), errChan: make(chan error, 3), closed: false, }} go copyDataToOutput(toBeAdapted, &retval, output, shouldCloseDownstream) return &retval.Writer }
go
func NewWriterToReaderAdapter(toBeAdapted func(io.Reader) (io.Reader, error), output io.Writer, shouldCloseDownstream bool) io.WriteCloser { retval := privateReaderAdapter{ Writer: WriterToReaderAdapter{ workChan: make(chan *[]byte), doneWorkChan: make(chan *[]byte), errChan: make(chan error, 3), closed: false, }} go copyDataToOutput(toBeAdapted, &retval, output, shouldCloseDownstream) return &retval.Writer }
[ "func", "NewWriterToReaderAdapter", "(", "toBeAdapted", "func", "(", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", ",", "output", "io", ".", "Writer", ",", "shouldCloseDownstream", "bool", ")", "io", ".", "WriteCloser", "{", "retval", ":=", "privateReaderAdapter", "{", "Writer", ":", "WriterToReaderAdapter", "{", "workChan", ":", "make", "(", "chan", "*", "[", "]", "byte", ")", ",", "doneWorkChan", ":", "make", "(", "chan", "*", "[", "]", "byte", ")", ",", "errChan", ":", "make", "(", "chan", "error", ",", "3", ")", ",", "closed", ":", "false", ",", "}", "}", "\n", "go", "copyDataToOutput", "(", "toBeAdapted", ",", "&", "retval", ",", "output", ",", "shouldCloseDownstream", ")", "\n", "return", "&", "retval", ".", "Writer", "\n", "}" ]
// This makes a io.Writer from a io.Reader and begins reading and writing data // The returned class is not thread safe and public methods must be called from a single thread
[ "This", "makes", "a", "io", ".", "Writer", "from", "a", "io", ".", "Reader", "and", "begins", "reading", "and", "writing", "data", "The", "returned", "class", "is", "not", "thread", "safe", "and", "public", "methods", "must", "be", "called", "from", "a", "single", "thread" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L29-L41
train
dropbox/godropbox
io2/writer_to_reader_adapter.go
Read
func (rself *privateReaderAdapter) Read(data []byte) (int, error) { lenToCopy := len(rself.bufferToBeRead) if lenToCopy == 0 { rself.workReceipt = <-rself.Writer.workChan if rself.workReceipt == nil { // no more data to consume rself.closeReceived = true return 0, io.EOF } rself.bufferToBeRead = *rself.workReceipt lenToCopy = len(rself.bufferToBeRead) } if lenToCopy > len(data) { lenToCopy = len(data) } copy(data[:lenToCopy], rself.bufferToBeRead[:lenToCopy]) rself.bufferToBeRead = rself.bufferToBeRead[lenToCopy:] if len(rself.bufferToBeRead) == 0 { rself.Writer.doneWorkChan <- rself.workReceipt rself.workReceipt = nil } return lenToCopy, nil }
go
func (rself *privateReaderAdapter) Read(data []byte) (int, error) { lenToCopy := len(rself.bufferToBeRead) if lenToCopy == 0 { rself.workReceipt = <-rself.Writer.workChan if rself.workReceipt == nil { // no more data to consume rself.closeReceived = true return 0, io.EOF } rself.bufferToBeRead = *rself.workReceipt lenToCopy = len(rself.bufferToBeRead) } if lenToCopy > len(data) { lenToCopy = len(data) } copy(data[:lenToCopy], rself.bufferToBeRead[:lenToCopy]) rself.bufferToBeRead = rself.bufferToBeRead[lenToCopy:] if len(rself.bufferToBeRead) == 0 { rself.Writer.doneWorkChan <- rself.workReceipt rself.workReceipt = nil } return lenToCopy, nil }
[ "func", "(", "rself", "*", "privateReaderAdapter", ")", "Read", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "lenToCopy", ":=", "len", "(", "rself", ".", "bufferToBeRead", ")", "\n", "if", "lenToCopy", "==", "0", "{", "rself", ".", "workReceipt", "=", "<-", "rself", ".", "Writer", ".", "workChan", "\n", "if", "rself", ".", "workReceipt", "==", "nil", "{", "// no more data to consume", "rself", ".", "closeReceived", "=", "true", "\n", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "rself", ".", "bufferToBeRead", "=", "*", "rself", ".", "workReceipt", "\n", "lenToCopy", "=", "len", "(", "rself", ".", "bufferToBeRead", ")", "\n", "}", "\n", "if", "lenToCopy", ">", "len", "(", "data", ")", "{", "lenToCopy", "=", "len", "(", "data", ")", "\n", "}", "\n", "copy", "(", "data", "[", ":", "lenToCopy", "]", ",", "rself", ".", "bufferToBeRead", "[", ":", "lenToCopy", "]", ")", "\n", "rself", ".", "bufferToBeRead", "=", "rself", ".", "bufferToBeRead", "[", "lenToCopy", ":", "]", "\n", "if", "len", "(", "rself", ".", "bufferToBeRead", ")", "==", "0", "{", "rself", ".", "Writer", ".", "doneWorkChan", "<-", "rself", ".", "workReceipt", "\n", "rself", ".", "workReceipt", "=", "nil", "\n", "}", "\n", "return", "lenToCopy", ",", "nil", "\n", "}" ]
// this is the private Read implementation, to be used with io.Copy // on the read thread
[ "this", "is", "the", "private", "Read", "implementation", "to", "be", "used", "with", "io", ".", "Copy", "on", "the", "read", "thread" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L45-L67
train
dropbox/godropbox
io2/writer_to_reader_adapter.go
copyDataToOutput
func copyDataToOutput(inputFactory func(io.Reader) (io.Reader, error), adaptedInput *privateReaderAdapter, output io.Writer, shouldCloseDownstream bool) { input, err := inputFactory(adaptedInput) if err != nil { adaptedInput.Writer.errChan <- err } else { _, err = io.Copy(output, input) if err != nil { adaptedInput.Writer.errChan <- err } } writeCloser, ok := output.(io.WriteCloser) if ok && shouldCloseDownstream { closeErr := writeCloser.Close() if closeErr != nil { adaptedInput.Writer.errChan <- closeErr } } // pulls all the data from the writer until EOF is reached // this is because readers like zlib don't validate the CRC32 // (the last 4 bytes) in the normal codepath adaptedInput.drain() close(adaptedInput.Writer.errChan) }
go
func copyDataToOutput(inputFactory func(io.Reader) (io.Reader, error), adaptedInput *privateReaderAdapter, output io.Writer, shouldCloseDownstream bool) { input, err := inputFactory(adaptedInput) if err != nil { adaptedInput.Writer.errChan <- err } else { _, err = io.Copy(output, input) if err != nil { adaptedInput.Writer.errChan <- err } } writeCloser, ok := output.(io.WriteCloser) if ok && shouldCloseDownstream { closeErr := writeCloser.Close() if closeErr != nil { adaptedInput.Writer.errChan <- closeErr } } // pulls all the data from the writer until EOF is reached // this is because readers like zlib don't validate the CRC32 // (the last 4 bytes) in the normal codepath adaptedInput.drain() close(adaptedInput.Writer.errChan) }
[ "func", "copyDataToOutput", "(", "inputFactory", "func", "(", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", ",", "adaptedInput", "*", "privateReaderAdapter", ",", "output", "io", ".", "Writer", ",", "shouldCloseDownstream", "bool", ")", "{", "input", ",", "err", ":=", "inputFactory", "(", "adaptedInput", ")", "\n\n", "if", "err", "!=", "nil", "{", "adaptedInput", ".", "Writer", ".", "errChan", "<-", "err", "\n", "}", "else", "{", "_", ",", "err", "=", "io", ".", "Copy", "(", "output", ",", "input", ")", "\n", "if", "err", "!=", "nil", "{", "adaptedInput", ".", "Writer", ".", "errChan", "<-", "err", "\n", "}", "\n", "}", "\n", "writeCloser", ",", "ok", ":=", "output", ".", "(", "io", ".", "WriteCloser", ")", "\n", "if", "ok", "&&", "shouldCloseDownstream", "{", "closeErr", ":=", "writeCloser", ".", "Close", "(", ")", "\n", "if", "closeErr", "!=", "nil", "{", "adaptedInput", ".", "Writer", ".", "errChan", "<-", "closeErr", "\n", "}", "\n", "}", "\n\n", "// pulls all the data from the writer until EOF is reached", "// this is because readers like zlib don't validate the CRC32", "// (the last 4 bytes) in the normal codepath", "adaptedInput", ".", "drain", "(", ")", "\n\n", "close", "(", "adaptedInput", ".", "Writer", ".", "errChan", ")", "\n", "}" ]
// This io.Copy's as much data as possible from the wrapped reader // to the corresponding writer output. // When finished it closes the downstream and drains the upstream // writer. Finally it sends any remaining errors to the errChan and // closes that channel
[ "This", "io", ".", "Copy", "s", "as", "much", "data", "as", "possible", "from", "the", "wrapped", "reader", "to", "the", "corresponding", "writer", "output", ".", "When", "finished", "it", "closes", "the", "downstream", "and", "drains", "the", "upstream", "writer", ".", "Finally", "it", "sends", "any", "remaining", "errors", "to", "the", "errChan", "and", "closes", "that", "channel" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L158-L187
train
dropbox/godropbox
caching/generic_storage.go
NewGenericStorage
func NewGenericStorage(name string, options GenericStorageOptions) Storage { return &GenericStorage{ name: name, get: options.GetFunc, getMulti: options.GetMultiFunc, set: options.SetFunc, setMulti: options.SetMultiFunc, del: options.DelFunc, delMulti: options.DelMultiFunc, errorOnFlush: options.ErrorOnFlush, flush: options.FlushFunc, } }
go
func NewGenericStorage(name string, options GenericStorageOptions) Storage { return &GenericStorage{ name: name, get: options.GetFunc, getMulti: options.GetMultiFunc, set: options.SetFunc, setMulti: options.SetMultiFunc, del: options.DelFunc, delMulti: options.DelMultiFunc, errorOnFlush: options.ErrorOnFlush, flush: options.FlushFunc, } }
[ "func", "NewGenericStorage", "(", "name", "string", ",", "options", "GenericStorageOptions", ")", "Storage", "{", "return", "&", "GenericStorage", "{", "name", ":", "name", ",", "get", ":", "options", ".", "GetFunc", ",", "getMulti", ":", "options", ".", "GetMultiFunc", ",", "set", ":", "options", ".", "SetFunc", ",", "setMulti", ":", "options", ".", "SetMultiFunc", ",", "del", ":", "options", ".", "DelFunc", ",", "delMulti", ":", "options", ".", "DelMultiFunc", ",", "errorOnFlush", ":", "options", ".", "ErrorOnFlush", ",", "flush", ":", "options", ".", "FlushFunc", ",", "}", "\n", "}" ]
// This creates a GenericStorage. See GenericStorageOptions for additional // information.
[ "This", "creates", "a", "GenericStorage", ".", "See", "GenericStorageOptions", "for", "additional", "information", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/caching/generic_storage.go#L59-L71
train
dropbox/godropbox
container/set/set.go
Union
func Union(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.Copy() } s3 := s1.Copy() s3.Union(s2) return s3 }
go
func Union(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.Copy() } s3 := s1.Copy() s3.Union(s2) return s3 }
[ "func", "Union", "(", "s1", "Set", ",", "s2", "Set", ")", "Set", "{", "if", "s1", "==", "nil", "{", "if", "s2", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "s2", ".", "Copy", "(", ")", "\n", "}", "\n", "s3", ":=", "s1", ".", "Copy", "(", ")", "\n", "s3", ".", "Union", "(", "s2", ")", "\n", "return", "s3", "\n", "}" ]
// Returns a new set which is the union of s1 and s2. s1 and s2 are unmodified.
[ "Returns", "a", "new", "set", "which", "is", "the", "union", "of", "s1", "and", "s2", ".", "s1", "and", "s2", "are", "unmodified", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L50-L61
train
dropbox/godropbox
container/set/set.go
Intersect
func Intersect(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Intersect(s2) return s3 }
go
func Intersect(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Intersect(s2) return s3 }
[ "func", "Intersect", "(", "s1", "Set", ",", "s2", "Set", ")", "Set", "{", "if", "s1", "==", "nil", "{", "if", "s2", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "s2", ".", "New", "(", ")", "\n", "}", "\n", "s3", ":=", "s1", ".", "Copy", "(", ")", "\n", "s3", ".", "Intersect", "(", "s2", ")", "\n", "return", "s3", "\n", "}" ]
// Returns a new set which is the intersect of s1 and s2. s1 and s2 are // unmodified.
[ "Returns", "a", "new", "set", "which", "is", "the", "intersect", "of", "s1", "and", "s2", ".", "s1", "and", "s2", "are", "unmodified", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L65-L76
train
dropbox/godropbox
container/set/set.go
Subtract
func Subtract(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Subtract(s2) return s3 }
go
func Subtract(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Subtract(s2) return s3 }
[ "func", "Subtract", "(", "s1", "Set", ",", "s2", "Set", ")", "Set", "{", "if", "s1", "==", "nil", "{", "if", "s2", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "s2", ".", "New", "(", ")", "\n", "}", "\n", "s3", ":=", "s1", ".", "Copy", "(", ")", "\n", "s3", ".", "Subtract", "(", "s2", ")", "\n", "return", "s3", "\n", "}" ]
// Returns a new set which is the difference between s1 and s2. s1 and s2 are // unmodified.
[ "Returns", "a", "new", "set", "which", "is", "the", "difference", "between", "s1", "and", "s2", ".", "s1", "and", "s2", "are", "unmodified", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L80-L91
train
dropbox/godropbox
container/set/set.go
equal
func equal(s Set, s2 Set) bool { if s.Len() != s2.Len() { return false } return s.IsSubset(s2) }
go
func equal(s Set, s2 Set) bool { if s.Len() != s2.Len() { return false } return s.IsSubset(s2) }
[ "func", "equal", "(", "s", "Set", ",", "s2", "Set", ")", "bool", "{", "if", "s", ".", "Len", "(", ")", "!=", "s2", ".", "Len", "(", ")", "{", "return", "false", "\n", "}", "\n\n", "return", "s", ".", "IsSubset", "(", "s2", ")", "\n", "}" ]
// Common functions between the two implementations, since go // does not allow for any inheritance.
[ "Common", "functions", "between", "the", "two", "implementations", "since", "go", "does", "not", "allow", "for", "any", "inheritance", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L340-L346
train
dropbox/godropbox
memcache/raw_binary_client.go
NewRawBinaryClient
func NewRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: defaultMaxValueLength, } }
go
func NewRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: defaultMaxValueLength, } }
[ "func", "NewRawBinaryClient", "(", "shard", "int", ",", "channel", "io", ".", "ReadWriter", ")", "ClientShard", "{", "return", "&", "RawBinaryClient", "{", "shard", ":", "shard", ",", "channel", ":", "channel", ",", "validState", ":", "true", ",", "maxValueLength", ":", "defaultMaxValueLength", ",", "}", "\n", "}" ]
// This creates a new memcache RawBinaryClient.
[ "This", "creates", "a", "new", "memcache", "RawBinaryClient", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_binary_client.go#L103-L110
train
dropbox/godropbox
memcache/raw_binary_client.go
NewLargeRawBinaryClient
func NewLargeRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: largeMaxValueLength, } }
go
func NewLargeRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: largeMaxValueLength, } }
[ "func", "NewLargeRawBinaryClient", "(", "shard", "int", ",", "channel", "io", ".", "ReadWriter", ")", "ClientShard", "{", "return", "&", "RawBinaryClient", "{", "shard", ":", "shard", ",", "channel", ":", "channel", ",", "validState", ":", "true", ",", "maxValueLength", ":", "largeMaxValueLength", ",", "}", "\n", "}" ]
// This creates a new memcache RawBinaryClient for use with np-large cluster.
[ "This", "creates", "a", "new", "memcache", "RawBinaryClient", "for", "use", "with", "np", "-", "large", "cluster", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_binary_client.go#L113-L120
train
dropbox/godropbox
memcache/raw_binary_client.go
mutate
func (c *RawBinaryClient) mutate(code opCode, item *Item) MutateResponse { if item == nil { return NewMutateErrorResponse("", errors.New("item is nil")) } c.mutex.Lock() defer c.mutex.Unlock() if resp := c.sendMutateRequest(code, item, true); resp != nil { return resp } return c.receiveMutateResponse(code, item.Key) }
go
func (c *RawBinaryClient) mutate(code opCode, item *Item) MutateResponse { if item == nil { return NewMutateErrorResponse("", errors.New("item is nil")) } c.mutex.Lock() defer c.mutex.Unlock() if resp := c.sendMutateRequest(code, item, true); resp != nil { return resp } return c.receiveMutateResponse(code, item.Key) }
[ "func", "(", "c", "*", "RawBinaryClient", ")", "mutate", "(", "code", "opCode", ",", "item", "*", "Item", ")", "MutateResponse", "{", "if", "item", "==", "nil", "{", "return", "NewMutateErrorResponse", "(", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "resp", ":=", "c", ".", "sendMutateRequest", "(", "code", ",", "item", ",", "true", ")", ";", "resp", "!=", "nil", "{", "return", "resp", "\n", "}", "\n\n", "return", "c", ".", "receiveMutateResponse", "(", "code", ",", "item", ".", "Key", ")", "\n", "}" ]
// Perform a mutation operation specified by the given code.
[ "Perform", "a", "mutation", "operation", "specified", "by", "the", "given", "code", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_binary_client.go#L443-L456
train
dropbox/godropbox
rate_limiter/rate_limiter.go
MaxQuota
func (l *rateLimiterImpl) MaxQuota() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.maxQuota }
go
func (l *rateLimiterImpl) MaxQuota() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.maxQuota }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "MaxQuota", "(", ")", "float64", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "maxQuota", "\n", "}" ]
// This returns the leaky bucket's maximum capacity.
[ "This", "returns", "the", "leaky", "bucket", "s", "maximum", "capacity", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L147-L151
train