repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L235-L242
go
train
// GetImportPath resolves the full import path of an identifier based on // the imports in the current context.
func GetImportPath(name string, ctx *Context) (string, bool)
// GetImportPath resolves the full import path of an identifier based on // the imports in the current context. 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L245-L248
go
train
// GetLocation returns the filename and line number of an ast.Node
func GetLocation(n ast.Node, ctx *Context) (string, int)
// GetLocation returns the filename and line number of an ast.Node func GetLocation(n ast.Node, ctx *Context) (string, int)
{ fobj := ctx.FileSet.File(n.Pos()) return fobj.Name(), fobj.Line(n.Pos()) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L251-L264
go
train
// Gopath returns all GOPATHs
func Gopath() []string
// Gopath returns all GOPATHs 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L268-L273
go
train
// Getenv returns the values of the environment variable, otherwise //returns the default if variable is not set
func Getenv(key, userDefault string) string
// Getenv returns the values of the environment variable, otherwise //returns the default if variable is not set func Getenv(key, userDefault string) string
{ if val := os.Getenv(key); val != "" { return val } return userDefault }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L277-L292
go
train
// GetPkgRelativePath returns the Go relative relative path derived // form the given path
func GetPkgRelativePath(path string) (string, error)
// GetPkgRelativePath returns the Go relative relative path derived // form the given path 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") }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L296-L305
go
train
// GetPkgAbsPath returns the Go package absolute path derived from // the given path
func GetPkgAbsPath(pkgPath string) (string, error)
// GetPkgAbsPath returns the Go package absolute path derived from // the given path 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L308-L330
go
train
// ConcatString recursively concatenates strings from a binary expression
func ConcatString(n *ast.BinaryExpr) (string, bool)
// ConcatString recursively concatenates strings from a binary expression 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L333-L360
go
train
// FindVarIdentities returns array of all variable identities in a given binary expression
func FindVarIdentities(n *ast.BinaryExpr, c *Context) ([]*ast.Ident, bool)
// FindVarIdentities returns array of all variable identities in a given binary expression 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
helpers.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/helpers.go#L363-L389
go
train
// PackagePaths returns a slice with all packages path at given root directory
func PackagePaths(root string, exclude *regexp.Regexp) ([]string, error)
// PackagePaths returns a slice with all packages path at given root directory 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/tls_config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/tls_config.go#L11-L30
go
train
// NewModernTLSCheck creates a check for Modern TLS ciphers // DO NOT EDIT - generated by tlsconfig tool
func NewModernTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewModernTLSCheck creates a check for Modern TLS ciphers // DO NOT EDIT - generated by tlsconfig tool 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rule.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rule.go#L41-L50
go
train
// Register adds a trigger for the supplied rule for the the // specified ast nodes.
func (r RuleSet) Register(rule Rule, nodes ...ast.Node)
// Register adds a trigger for the supplied rule for the the // specified ast nodes. 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} } } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rule.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rule.go#L54-L59
go
train
// RegisteredFor will return all rules that are registered for a // specified ast node.
func (r RuleSet) RegisteredFor(n ast.Node) []Rule
// RegisteredFor will return all rules that are registered for a // specified ast node. func (r RuleSet) RegisteredFor(n ast.Node) []Rule
{ if rules, found := r[reflect.TypeOf(n)]; found { return rules } return []Rule{} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/sql.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L36-L43
go
train
// See if the string matches the patterns for the statement.
func (s *sqlStatement) MatchPatterns(str string) bool
// See if the string matches the patterns for the statement. func (s *sqlStatement) MatchPatterns(str string) bool
{ for _, pattern := range s.patterns { if !pattern.MatchString(str) { return false } } return true }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/sql.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L54-L66
go
train
// see if we can figure out what it is
func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool
// see if we can figure out what it is 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/sql.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L69-L87
go
train
// Look for "SELECT * FROM table WHERE " + " ' OR 1=1"
func (s *sqlStrConcat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
// Look for "SELECT * FROM table WHERE " + " ' OR 1=1" func (s *sqlStrConcat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
{ if node, ok := n.(*ast.BinaryExpr); ok { if start, ok := node.X.(*ast.BasicLit); ok { if str, e := gosec.GetString(start); e == nil { if !s.MatchPatterns(str) { return nil, nil } if _, ok := node.Y.(*ast.BasicLit); ok { return nil, nil // string cat OK } if second, ok := node.Y.(*ast.Ident); ok && s.checkObject(second, c) { return nil, nil } return gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil } } } return nil, nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/sql.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L90-L104
go
train
// NewSQLStrConcat looks for cases where we are building SQL strings via concatenation
func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewSQLStrConcat looks for cases where we are building SQL strings via concatenation 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/sql.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L114-L174
go
train
// Looks for "fmt.Sprintf("SELECT * FROM foo where '%s', userInput)"
func (s *sqlStrFormat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
// Looks for "fmt.Sprintf("SELECT * FROM foo where '%s', userInput)" func (s *sqlStrFormat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
{ // argIndex changes the function argument which gets matched to the regex argIndex := 0 // TODO(gm) improve confidence if database/sql is being used if node := s.calls.ContainsCallExpr(n, c, false); node != nil { // if the function is fmt.Fprintf, search for SQL statement in Args[1] instead if sel, ok := node.Fun.(*ast.SelectorExpr); ok { if sel.Sel.Name == "Fprintf" { // if os.Stderr or os.Stdout is in Arg[0], mark as no issue if arg, ok := node.Args[0].(*ast.SelectorExpr); ok { if ident, ok := arg.X.(*ast.Ident); ok { if s.noIssue.Contains(ident.Name, arg.Sel.Name) { return nil, nil } } } // the function is Fprintf so set argIndex = 1 argIndex = 1 } } // no formatter if len(node.Args) == 0 { return nil, nil } var formatter string // concats callexpr arg strings together if needed before regex evaluation if argExpr, ok := node.Args[argIndex].(*ast.BinaryExpr); ok { if fullStr, ok := gosec.ConcatString(argExpr); ok { formatter = fullStr } } else if arg, e := gosec.GetString(node.Args[argIndex]); e == nil { formatter = arg } if len(formatter) <= 0 { return nil, nil } // If all formatter args are quoted, then the SQL construction is safe if argIndex+1 < len(node.Args) { allQuoted := true for _, arg := range node.Args[argIndex+1:] { if n := s.noIssueQuoted.ContainsCallExpr(arg, c, true); n == nil { allQuoted = false break } } if allQuoted { return nil, nil } } if s.MatchPatterns(formatter) { return gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil } } return nil, nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/sql.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/sql.go#L177-L199
go
train
// NewSQLStrFormat looks for cases where we're building SQL query strings using format strings
func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewSQLStrFormat looks for cases where we're building SQL query strings using format strings 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L33-L37
go
train
// NewConfig initializes a new configuration instance. The configuration data then // needs to be loaded via c.ReadFrom(strings.NewReader("config data")) // or from a *os.File.
func NewConfig() Config
// NewConfig initializes a new configuration instance. The configuration data then // needs to be loaded via c.ReadFrom(strings.NewReader("config data")) // or from a *os.File. func NewConfig() Config
{ cfg := make(Config) cfg[Globals] = make(map[GlobalOption]string) return cfg }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L42-L51
go
train
// ReadFrom implements the io.ReaderFrom interface. This // should be used with io.Reader to load configuration from //file or from string etc.
func (c Config) ReadFrom(r io.Reader) (int64, error)
// ReadFrom implements the io.ReaderFrom interface. This // should be used with io.Reader to load configuration from //file or from string etc. 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L55-L61
go
train
// WriteTo implements the io.WriteTo interface. This should // be used to save or print out the configuration information.
func (c Config) WriteTo(w io.Writer) (int64, error)
// WriteTo implements the io.WriteTo interface. This should // be used to save or print out the configuration information. 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)) }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L64-L70
go
train
// Get returns the configuration section for the supplied key
func (c Config) Get(section string) (interface{}, error)
// Get returns the configuration section for the supplied key 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L78-L89
go
train
// GetGlobal returns value associated with global configuration option
func (c Config) GetGlobal(option GlobalOption) (string, error)
// GetGlobal returns value associated with global configuration option 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") }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L92-L98
go
train
// SetGlobal associates a value with a global configuration option
func (c Config) SetGlobal(option GlobalOption, value string)
// SetGlobal associates a value with a global configuration option 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 } } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
config.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/config.go#L101-L107
go
train
// IsGlobalEnabled checks if a global option is enabled
func (c Config) IsGlobalEnabled(option GlobalOption) (bool, error)
// IsGlobalEnabled checks if a global option is enabled 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/rand.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rand.go#L44-L55
go
train
// NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure
func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/ssh.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssh.go#L27-L38
go
train
// NewSSHHostKey rule detects the use of insecure ssh HostKeyCallback.
func NewSSHHostKey(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewSSHHostKey rule detects the use of insecure ssh HostKeyCallback. 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/errors.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/errors.go#L81-L106
go
train
// NewNoErrorCheck detects if the returned error is unchecked
func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewNoErrorCheck detects if the returned error is unchecked 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/big.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/big.go#L41-L52
go
train
// NewUsingBigExp detects issues with modulus == 0 for Bignum
func NewUsingBigExp(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewUsingBigExp detects issues with modulus == 0 for Bignum 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/weakcrypto.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/weakcrypto.go#L42-L58
go
train
// NewUsesWeakCryptography detects uses of des.* md5.* or rc4.*
func NewUsesWeakCryptography(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewUsesWeakCryptography detects uses of des.* md5.* or rc4.* func NewUsesWeakCryptography(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ calls := make(map[string][]string) calls["crypto/des"] = []string{"NewCipher", "NewTripleDESCipher"} calls["crypto/md5"] = []string{"New", "Sum"} calls["crypto/sha1"] = []string{"New", "Sum"} calls["crypto/rc4"] = []string{"NewCipher"} rule := &usesWeakCryptography{ blacklist: calls, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.High, What: "Use of weak cryptographic primitive", }, } return rule, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/rulelist.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rulelist.go#L31-L37
go
train
// Builders returns all the create methods for a given rule list
func (rl RuleList) Builders() map[string]gosec.RuleBuilder
// Builders returns all the create methods for a given rule list 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/rulelist.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rulelist.go#L45-L56
go
train
// NewRuleFilter is a closure that will include/exclude the rule ID's based on // the supplied boolean value.
func NewRuleFilter(action bool, ruleIDs ...string) RuleFilter
// NewRuleFilter is a closure that will include/exclude the rule ID's based on // the supplied boolean value. func NewRuleFilter(action bool, ruleIDs ...string) RuleFilter
{ rulelist := make(map[string]bool) for _, rule := range ruleIDs { rulelist[rule] = true } return func(rule string) bool { if _, found := rulelist[rule]; found { return action } return !action } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/rulelist.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rulelist.go#L59-L109
go
train
// Generate the list of rules to use
func Generate(filters ...RuleFilter) RuleList
// Generate the list of rules to use 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
errors.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/errors.go#L15-L21
go
train
// NewError creates Error object
func NewError(line, column int, err string) *Error
// NewError creates Error object func NewError(line, column int, err string) *Error
{ return &Error{ Line: line, Column: column, Err: err, } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
errors.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/errors.go#L24-L33
go
train
// sortErros sorts the golang erros by line
func sortErrors(allErrors map[string][]Error)
// sortErros sorts the golang erros by 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 } return errors[i].Line < errors[j].Line }) } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
cmd/gosec/main.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/cmd/gosec/main.go#L108-L127
go
train
// #nosec
func usage()
// #nosec func usage()
{ usageText := fmt.Sprintf(usageText, Version, GitTag, BuildDate) fmt.Fprintln(os.Stderr, usageText) fmt.Fprint(os.Stderr, "OPTIONS:\n\n") flag.PrintDefaults() fmt.Fprint(os.Stderr, "\n\nRULES:\n\n") // sorted rule list for ease of reading rl := rules.Generate() keys := make([]string, 0, len(rl)) for key := range rl { keys = append(keys, key) } sort.Strings(keys) for _, k := range keys { v := rl[k] fmt.Fprintf(os.Stderr, "\t%s: %s\n", k, v.Description) } fmt.Fprint(os.Stderr, "\n") }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/tempfiles.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/tempfiles.go#L44-L58
go
train
// NewBadTempFile detects direct writes to predictable path in temporary directory
func NewBadTempFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewBadTempFile detects direct writes to predictable path in temporary directory 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
output/formatter.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/output/formatter.go#L79-L105
go
train
// CreateReport generates a report based for the supplied issues and metrics given // the specified format. The formats currently accepted are: json, csv, html and text.
func CreateReport(w io.Writer, format, rootPath string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error
// CreateReport generates a report based for the supplied issues and metrics given // the specified format. The formats currently accepted are: json, csv, html and text. func CreateReport(w io.Writer, format, rootPath string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error
{ data := &reportInfo{ Errors: errors, Issues: issues, Stats: metrics, } var err error switch format { case "json": err = reportJSON(w, data) case "yaml": err = reportYAML(w, data) case "csv": err = reportCSV(w, data) case "junit-xml": err = reportJUnitXML(w, data) case "html": err = reportFromHTMLTemplate(w, html, data) case "text": err = reportFromPlaintextTemplate(w, text, data) case "sonarqube": err = reportSonarqube(rootPath, w, data) default: err = reportFromPlaintextTemplate(w, text, data) } return err }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
import_tracker.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L31-L37
go
train
// NewImportTracker creates an empty Import tracker instance
func NewImportTracker() *ImportTracker
// NewImportTracker creates an empty Import tracker instance func NewImportTracker() *ImportTracker
{ return &ImportTracker{ make(map[string]string), make(map[string]string), make(map[string]bool), } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
import_tracker.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L40-L49
go
train
// TrackFile track all the imports used by the supplied file
func (t *ImportTracker) TrackFile(file *ast.File)
// TrackFile track all the imports used by the supplied file 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 } } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
import_tracker.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L52-L56
go
train
// TrackPackages tracks all the imports used by the supplied packages
func (t *ImportTracker) TrackPackages(pkgs ...*types.Package)
// TrackPackages tracks all the imports used by the supplied packages func (t *ImportTracker) TrackPackages(pkgs ...*types.Package)
{ for _, pkg := range pkgs { t.Imported[pkg.Path()] = pkg.Name() } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
import_tracker.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/import_tracker.go#L59-L75
go
train
// TrackImport tracks imports and handles the 'unsafe' import
func (t *ImportTracker) TrackImport(n ast.Node)
// TrackImport tracks imports and handles the 'unsafe' import 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 } } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/readfile.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/readfile.go#L36-L57
go
train
// isJoinFunc checks if there is a filepath.Join or other join function
func (r *readfile) isJoinFunc(n ast.Node, c *gosec.Context) bool
// isJoinFunc checks if there is a filepath.Join or other join function 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/readfile.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/readfile.go#L60-L87
go
train
// Match inspects AST nodes to determine if the match the methods `os.Open` or `ioutil.ReadFile`
func (r *readfile) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
// Match inspects AST nodes to determine if the match the methods `os.Open` or `ioutil.ReadFile` 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/readfile.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/readfile.go#L90-L106
go
train
// NewReadFile detects cases where we read files
func NewReadFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewReadFile detects cases where we read files 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/ssrf.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssrf.go#L22-L33
go
train
// ResolveVar tries to resolve the first argument of a call expression // The first argument is the url
func (r *ssrf) ResolveVar(n *ast.CallExpr, c *gosec.Context) bool
// ResolveVar tries to resolve the first argument of a call expression // The first argument is the url 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/ssrf.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssrf.go#L36-L44
go
train
// Match inspects AST nodes to determine if certain net/http methods are called with variable input
func (r *ssrf) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
// Match inspects AST nodes to determine if certain net/http methods are called with variable input func (r *ssrf) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error)
{ // Call expression is using http package directly if node := r.ContainsCallExpr(n, c, false); node != nil { if r.ResolveVar(node, c) { return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil } } return nil, nil }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/ssrf.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/ssrf.go#L47-L59
go
train
// NewSSRFCheck detects cases where HTTP requests are sent
func NewSSRFCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewSSRFCheck detects cases where HTTP requests are sent 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)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
resolve.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/resolve.go#L60-L82
go
train
// 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.
func TryResolve(n ast.Node, c *Context) bool
// 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. 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
rules/templates.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/templates.go#L45-L61
go
train
// NewTemplateCheck constructs the template check rule. This rule is used to // find use of templates where HTML/JS escaping is not being used
func NewTemplateCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
// NewTemplateCheck constructs the template check rule. This rule is used to // find use of templates where HTML/JS escaping is not being used func NewTemplateCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node)
{ calls := gosec.NewCallList() calls.Add("html/template", "HTML") calls.Add("html/template", "HTMLAttr") calls.Add("html/template", "JS") calls.Add("html/template", "URL") return &templateCheck{ calls: calls, MetaData: gosec.MetaData{ ID: id, Severity: gosec.Medium, Confidence: gosec.Low, What: "this method will not auto-escape HTML. Verify data is well formed.", }, }, []ast.Node{(*ast.CallExpr)(nil)} }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
issue.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/issue.go#L94-L125
go
train
// NewIssue creates a new Issue
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue
// NewIssue creates a new Issue 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, } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L74-L93
go
train
// NewAnalyzer builds a new analyzer.
func NewAnalyzer(conf Config, tests bool, logger *log.Logger) *Analyzer
// NewAnalyzer builds a new analyzer. 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, } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L97-L102
go
train
// LoadRules instantiates all the rules to be used when analyzing source // packages
func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder)
// LoadRules instantiates all the rules to be used when analyzing source // packages func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder)
{ for id, def := range ruleDefinitions { r, nodes := def(id, gosec.config) gosec.ruleset.Register(r, nodes...) } }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L105-L124
go
train
// Process kicks off the analysis process for a given package
func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error
// Process kicks off the analysis process for a given package 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L193-L223
go
train
// ParseErrors parses the errors from given package
func (gosec *Analyzer) ParseErrors(pkg *packages.Package) error
// ParseErrors parses the errors from given package 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L226-L239
go
train
// AppendError appends an error to the file errors
func (gosec *Analyzer) AppendError(file string, err error)
// AppendError appends an error to the 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`) 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L242-L267
go
train
// ignore a node (and sub-tree) if it is tagged with a "#nosec" comment
func (gosec *Analyzer) ignore(n ast.Node) ([]string, bool)
// ignore a node (and sub-tree) if it is tagged with a "#nosec" comment func (gosec *Analyzer) ignore(n ast.Node) ([]string, bool)
{ if groups, ok := gosec.context.Comments[n]; ok && !gosec.ignoreNosec { for _, group := range groups { if strings.Contains(group.Text(), "#nosec") { gosec.stats.NumNosec++ // Pull out the specific rules that are listed to be ignored. re := regexp.MustCompile(`(G\d{3})`) matches := re.FindAllStringSubmatch(group.Text(), -1) // If no specific rules were given, ignore everything. if len(matches) == 0 { return nil, true } // Find the rule IDs to ignore. var ignores []string for _, v := range matches { ignores = append(ignores, v[1]) } return ignores, false } } } return nil, false }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L271-L320
go
train
// Visit runs the gosec visitor logic over an AST created by parsing go code. // Rule methods added with AddRule will be invoked as necessary.
func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor
// Visit runs the gosec visitor logic over an AST created by parsing go code. // Rule methods added with AddRule will be invoked as necessary. 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 }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L323-L325
go
train
// Report returns the current issues discovered and the metrics about the scan
func (gosec *Analyzer) Report() ([]*Issue, *Metrics, map[string][]Error)
// Report returns the current issues discovered and the metrics about the scan func (gosec *Analyzer) Report() ([]*Issue, *Metrics, map[string][]Error)
{ return gosec.issues, gosec.stats, gosec.errors }
securego/gosec
29cec138dcc94f347e6d41550a5223571dc7d6cf
analyzer.go
https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/analyzer.go#L328-L332
go
train
// Reset clears state such as context, issues and metrics from the configured analyzer
func (gosec *Analyzer) Reset()
// Reset clears state such as context, issues and metrics from the configured analyzer func (gosec *Analyzer) Reset()
{ gosec.context = &Context{} gosec.issues = make([]*Issue, 0, 16) gosec.stats = &Metrics{} }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L50-L57
go
train
// NewClient creates a new client which provides the base of all communication // with Toxiproxy. Endpoint is the address to the proxy (e.g. localhost:8474 if // not overriden)
func NewClient(endpoint string) *Client
// NewClient creates a new client which provides the base of all communication // with Toxiproxy. Endpoint is the address to the proxy (e.g. localhost:8474 if // not overriden) func NewClient(endpoint string) *Client
{ if strings.HasPrefix(endpoint, "https://") { log.Fatal("the toxiproxy client does not support https") } else if !strings.HasPrefix(endpoint, "http://") { endpoint = "http://" + endpoint } return &Client{endpoint: endpoint} }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L60-L82
go
train
// Proxies returns a map with all the proxies and their toxics.
func (client *Client) Proxies() (map[string]*Proxy, error)
// Proxies returns a map with all the proxies and their toxics. 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L94-L109
go
train
// CreateProxy instantiates a new proxy and starts listening on the specified address. // This is an alias for `NewProxy()` + `proxy.Save()`
func (client *Client) CreateProxy(name, listen, upstream string) (*Proxy, error)
// CreateProxy instantiates a new proxy and starts listening on the specified address. // This is an alias for `NewProxy()` + `proxy.Save()` func (client *Client) CreateProxy(name, listen, upstream string) (*Proxy, error)
{ proxy := &Proxy{ Name: name, Listen: listen, Upstream: upstream, Enabled: true, client: client, } err := proxy.Save() if err != nil { return nil, err } return proxy, nil }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L112-L133
go
train
// Proxy returns a proxy by name.
func (client *Client) Proxy(name string) (*Proxy, error)
// Proxy returns a proxy by name. 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L138-L163
go
train
// 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.
func (client *Client) Populate(config []Proxy) ([]*Proxy, error)
// 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. 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L166-L198
go
train
// Save saves changes to a proxy such as its enabled status or upstream port.
func (proxy *Proxy) Save() error
// Save saves changes to a proxy such as its enabled status or upstream port. 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L215-L229
go
train
// Delete a proxy complete and close all existing connections through it. All information about // the proxy such as listen port and active toxics will be deleted as well. If you just wish to // stop and later enable a proxy, use `Enable()` and `Disable()`.
func (proxy *Proxy) Delete() error
// Delete a proxy complete and close all existing connections through it. All information about // the proxy such as listen port and active toxics will be deleted as well. If you just wish to // stop and later enable a proxy, use `Enable()` and `Disable()`. func (proxy *Proxy) Delete() error
{ httpClient := &http.Client{} req, err := http.NewRequest("DELETE", proxy.client.endpoint+"/proxies/"+proxy.Name, nil) if err != nil { return err } resp, err := httpClient.Do(req) if err != nil { return err } return checkError(resp, http.StatusNoContent, "Delete") }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L232-L250
go
train
// Toxics returns a map of all the active toxics and their attributes.
func (proxy *Proxy) Toxics() (Toxics, error)
// Toxics returns a map of all the active toxics and their attributes. 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L256-L284
go
train
// AddToxic adds a toxic to the given stream direction. // If a name is not specified, it will default to <type>_<stream>. // If a stream is not specified, it will default to downstream. // See https://github.com/Shopify/toxiproxy#toxics for a list of all Toxic types.
func (proxy *Proxy) AddToxic(name, typeName, stream string, toxicity float32, attrs Attributes) (*Toxic, error)
// AddToxic adds a toxic to the given stream direction. // If a name is not specified, it will default to <type>_<stream>. // If a stream is not specified, it will default to downstream. // See https://github.com/Shopify/toxiproxy#toxics for a list of all Toxic types. func (proxy *Proxy) AddToxic(name, typeName, stream string, toxicity float32, attrs Attributes) (*Toxic, error)
{ toxic := Toxic{name, typeName, stream, toxicity, attrs} if toxic.Toxicity == -1 { toxic.Toxicity = 1 // Just to be consistent with a toxicity of -1 using the default } request, err := json.Marshal(&toxic) if err != nil { return nil, err } resp, err := http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name+"/toxics", "application/json", bytes.NewReader(request)) if err != nil { return nil, err } err = checkError(resp, http.StatusOK, "AddToxic") if err != nil { return nil, err } result := &Toxic{} err = json.NewDecoder(resp.Body).Decode(result) if err != nil { return nil, err } return result, nil }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
client/client.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/client/client.go#L336-L343
go
train
// ResetState resets the state of all proxies and toxics in Toxiproxy.
func (client *Client) ResetState() error
// ResetState resets the state of all proxies and toxics in Toxiproxy. 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") }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
link.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L56-L88
go
train
// Start the link with the specified toxics
func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser)
// Start the link with the specified toxics 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) }() }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
link.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L91-L112
go
train
// Add a toxic to the end of the chain.
func (link *ToxicLink) AddToxic(toxic *toxics.ToxicWrapper)
// Add a toxic to the end of the chain. 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() } }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
link.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L115-L119
go
train
// Update an existing toxic in the chain.
func (link *ToxicLink) UpdateToxic(toxic *toxics.ToxicWrapper)
// Update an existing toxic in the chain. func (link *ToxicLink) UpdateToxic(toxic *toxics.ToxicWrapper)
{ if link.stubs[toxic.Index].InterruptToxic() { go link.stubs[toxic.Index].Run(toxic) } }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
link.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/link.go#L122-L176
go
train
// Remove an existing toxic from the chain.
func (link *ToxicLink) RemoveToxic(toxic *toxics.ToxicWrapper)
// Remove an existing toxic from the chain. 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]) } }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
toxics/toxic.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxics/toxic.go#L78-L86
go
train
// Begin running a toxic on this stub, can be interrupted. // Runs a noop toxic randomly depending on toxicity
func (s *ToxicStub) Run(toxic *ToxicWrapper)
// Begin running a toxic on this stub, can be interrupted. // Runs a noop toxic randomly depending on toxicity 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) } }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
toxics/toxic.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxics/toxic.go#L90-L98
go
train
// 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.
func (s *ToxicStub) InterruptToxic() bool
// 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. 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 } }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
toxic_collection.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxic_collection.go#L188-L201
go
train
// All following functions assume the lock is already grabbed
func (c *ToxicCollection) findToxicByName(name string) *toxics.ToxicWrapper
// All following functions assume the lock is already grabbed 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
proxy_collection.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy_collection.go#L160-L166
go
train
// getByName returns a proxy by its name. Its used from #remove and #get. // It assumes the lock has already been acquired.
func (collection *ProxyCollection) getByName(name string) (*Proxy, error)
// getByName returns a proxy by its name. Its used from #remove and #get. // It assumes the lock has already been acquired. func (collection *ProxyCollection) getByName(name string) (*Proxy, error)
{ proxy, exists := collection.proxies[name] if !exists { return nil, ErrProxyNotFound } return proxy, nil }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
stream/io_chan.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/stream/io_chan.go#L34-L39
go
train
// Write `buf` as a StreamChunk to the channel. The full buffer is always written, and error // will always be nil. Calling `Write()` after closing the channel will panic.
func (c *ChanWriter) Write(buf []byte) (int, error)
// Write `buf` as a StreamChunk to the channel. The full buffer is always written, and error // will always be nil. Calling `Write()` after closing the channel will panic. func (c *ChanWriter) Write(buf []byte) (int, error)
{ packet := &StreamChunk{make([]byte, len(buf)), time.Now()} copy(packet.Data, buf) // Make a copy before sending it to the channel c.output <- packet return len(buf), nil }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
stream/io_chan.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/stream/io_chan.go#L68-L108
go
train
// Read from the channel into `out`. This will block until data is available, // and can be interrupted with a channel using `SetInterrupt()`. If the read // was interrupted, `ErrInterrupted` will be returned.
func (c *ChanReader) Read(out []byte) (int, error)
// Read from the channel into `out`. This will block until data is available, // and can be interrupted with a channel using `SetInterrupt()`. If the read // was interrupted, `ErrInterrupted` will be returned. func (c *ChanReader) Read(out []byte) (int, error)
{ if c.buffer == nil { return 0, io.EOF } n := copy(out, c.buffer) c.buffer = c.buffer[n:] if len(out) <= len(c.buffer) { return n, nil } else if n > 0 { // We have some data to return, so make the channel read optional select { case p := <-c.input: if p == nil { // Stream was closed c.buffer = nil if n > 0 { return n, nil } return 0, io.EOF } n2 := copy(out[n:], p.Data) c.buffer = p.Data[n2:] return n + n2, nil default: return n, nil } } var p *StreamChunk select { case p = <-c.input: case <-c.interrupt: c.buffer = c.buffer[:0] return n, ErrInterrupted } if p == nil { // Stream was closed c.buffer = nil return 0, io.EOF } n2 := copy(out[n:], p.Data) c.buffer = p.Data[n2:] return n + n2, nil }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
proxy.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L94-L182
go
train
// server runs the Proxy server, accepting new clients and creating Links to // connect them to upstreams.
func (proxy *Proxy) server()
// server runs the Proxy server, accepting new clients and creating Links to // connect them to upstreams. 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) } }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
proxy.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L191-L202
go
train
// Starts a proxy, assumes the lock has already been taken
func start(proxy *Proxy) error
// Starts a proxy, assumes the lock has already been taken 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 }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
proxy.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L205-L225
go
train
// Stops a proxy, assumes the lock has already been taken
func stop(proxy *Proxy)
// Stops a proxy, assumes the lock has already been taken 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") }
Shopify/toxiproxy
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
toxics/slicer.go
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/toxics/slicer.go#L31-L47
go
train
// Returns a list of chunk offsets to slice up a packet of the // given total size. For example, for a size of 100, output might be: // // []int{0, 18, 18, 43, 43, 67, 67, 77, 77, 100} // ^---^ ^----^ ^----^ ^----^ ^-----^ // // This tries to get fairly evenly-varying chunks (no tendency // to have a small/large chunk at the start/end).
func (t *SlicerToxic) chunk(start int, end int) []int
// Returns a list of chunk offsets to slice up a packet of the // given total size. For example, for a size of 100, output might be: // // []int{0, 18, 18, 43, 43, 67, 67, 77, 77, 100} // ^---^ ^----^ ^----^ ^----^ ^-----^ // // This tries to get fairly evenly-varying chunks (no tendency // to have a small/large chunk at the start/end). func (t *SlicerToxic) chunk(start int, end int) []int
{ // Base case: // If the size is within the random varation, _or already // less than the average size_, just return it. // Otherwise split the chunk in about two, and recurse. if (end-start)-t.AverageSize <= t.SizeVariation { return []int{start, end} } // +1 in the size variation to offset favoring of smaller // numbers by integer division mid := start + (end-start)/2 + (rand.Intn(t.SizeVariation*2) - t.SizeVariation) + rand.Intn(1) left := t.chunk(start, mid) right := t.chunk(mid, end) return append(left, right...) }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/goparser/goparser.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/goparser/goparser.go#L38-L61
go
train
// Parse parses a given Go file at srcPath, along any files that share the same // package, into a domain model for generating tests.
func (p *Parser) Parse(srcPath string, files []models.Path) (*Result, error)
// Parse parses a given Go file at srcPath, along any files that share the same // package, into a domain model for generating tests. 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 }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/goparser/goparser.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/goparser/goparser.go#L163-L179
go
train
// Returns the Go code below the imports block.
func goCode(b []byte, f *ast.File) []byte
// Returns the Go code below the imports block. 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:] }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/render/bindata/helper.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/helper.go#L17-L23
go
train
// AssetNames returns the names of the assets. (for compatible with go-bindata)
func AssetNames() []string
// AssetNames returns the names of the assets. (for compatible with go-bindata) func AssetNames() []string
{ names := make([]string, 0, len(_escData)) for name := range _escData { names = append(names, name) } return names }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/input/input.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/input/input.go#L13-L26
go
train
// Files returns all the Golang files for the given path. Ignores hidden files.
func Files(srcPath string) ([]models.Path, error)
// Files returns all the Golang files for the given path. Ignores hidden 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) }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/render/render.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/render.go#L30-L47
go
train
// LoadCustomTemplates allows to load in custom templates from a specified path.
func LoadCustomTemplates(dir string) error
// LoadCustomTemplates allows to load in custom templates from a specified path. 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 }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/render/bindata/esc.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L173-L188
go
train
// FSByte returns the named file from the embedded assets. If useLocal is // true, the filesystem's contents are instead used.
func FSByte(useLocal bool, name string) ([]byte, error)
// FSByte returns the named file from the embedded assets. If useLocal is // true, the filesystem's contents are instead used. 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 }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/render/bindata/esc.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L191-L197
go
train
// FSMustByte is the same as FSByte, but panics if name is not present.
func FSMustByte(useLocal bool, name string) []byte
// FSMustByte is the same as FSByte, but panics if name is not present. func FSMustByte(useLocal bool, name string) []byte
{ b, err := FSByte(useLocal, name) if err != nil { panic(err) } return b }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/render/bindata/esc.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L200-L203
go
train
// FSString is the string version of FSByte.
func FSString(useLocal bool, name string) (string, error)
// FSString is the string version of FSByte. func FSString(useLocal bool, name string) (string, error)
{ b, err := FSByte(useLocal, name) return string(b), err }
cweill/gotests
afa0a378663a63a98287714c3f3359e22a4ab29e
internal/render/bindata/esc.go
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L206-L208
go
train
// FSMustString is the string version of FSMustByte.
func FSMustString(useLocal bool, name string) string
// FSMustString is the string version of FSMustByte. func FSMustString(useLocal bool, name string) string
{ return string(FSMustByte(useLocal, name)) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/parsed_event_reader.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/parsed_event_reader.go#L16-L24
go
train
// 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.
func NewParsedV4EventReader( reader EventReader, parsers V4EventParserMap) EventReader
// 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. func NewParsedV4EventReader( reader EventReader, parsers V4EventParserMap) EventReader
{ return &parsedV4EventReader{ reader: reader, eventParsers: parsers, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
io2/writer_to_reader_adapter.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L29-L41
go
train
// 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
func NewWriterToReaderAdapter(toBeAdapted func(io.Reader) (io.Reader, error), output io.Writer, shouldCloseDownstream bool) io.WriteCloser
// 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 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 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
io2/writer_to_reader_adapter.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L45-L67
go
train
// this is the private Read implementation, to be used with io.Copy // on the read thread
func (rself *privateReaderAdapter) Read(data []byte) (int, error)
// this is the private Read implementation, to be used with io.Copy // on the read thread 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 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
io2/writer_to_reader_adapter.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L75-L90
go
train
// this is the public Write interface that presents any data to the // companion goroutine (copyDataToOutput) // This function is unbuffered and blocks until the companion goroutine // consumes the data and returns a receipt. // This means that there are no extraneous allocations since the receipt is the data // that was consumed (sent) and the Write can now return
func (wrself *WriterToReaderAdapter) Write(data []byte) (int, error)
// this is the public Write interface that presents any data to the // companion goroutine (copyDataToOutput) // This function is unbuffered and blocks until the companion goroutine // consumes the data and returns a receipt. // This means that there are no extraneous allocations since the receipt is the data // that was consumed (sent) and the Write can now return func (wrself *WriterToReaderAdapter) Write(data []byte) (int, error)
{ if len(data) == 0 { return 0, nil } wrself.workChan <- &data var err error select { case err = <-wrself.errChan: default: } receipt := <-wrself.doneWorkChan if receipt != &data { panic("Only one thread allowed to use io.Writer") } return len(data), err }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
io2/writer_to_reader_adapter.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L108-L118
go
train
// Close must be called, even if there's an error during Write, // to clean up all goroutines and resources // This function shuts down the Writer, which will deliver // an io.EOF to the reader class. It then blocks until the // downstream writer has been passed a close and returns any errors // from the downstream Close (or any pending errors from final reads // that were triggered by the io.Reader to be adapted)
func (wrself *WriterToReaderAdapter) Close() error
// Close must be called, even if there's an error during Write, // to clean up all goroutines and resources // This function shuts down the Writer, which will deliver // an io.EOF to the reader class. It then blocks until the // downstream writer has been passed a close and returns any errors // from the downstream Close (or any pending errors from final reads // that were triggered by the io.Reader to be adapted) func (wrself *WriterToReaderAdapter) Close() error
{ if wrself.closed { panic("Double close on WriterToReaderAdapter") } wrself.workChan <- nil close(wrself.workChan) wrself.closed = true closeErr := wrself.getErrors() close(wrself.doneWorkChan) // once they've sent closing err, they won't be touching this return closeErr }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
io2/writer_to_reader_adapter.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L127-L151
go
train
// drain // // This is the final function called when the wrapped io.Reader shuts down and // stops accepting more input. // // this is because readers like zlib don't validate the CRC32 // (the last 4 bytes) in the normal codepath and leave the final buffer unconsumed
func (rself *privateReaderAdapter) drain()
// drain // // This is the final function called when the wrapped io.Reader shuts down and // stops accepting more input. // // this is because readers like zlib don't validate the CRC32 // (the last 4 bytes) in the normal codepath and leave the final buffer unconsumed func (rself *privateReaderAdapter) drain()
{ if rself.closeReceived { return // we have already drained } if len(rself.bufferToBeRead) != 0 { if rself.workReceipt == nil { panic("Logic error: if there's data to be read, we must still have the receipt") } rself.Writer.doneWorkChan <- rself.workReceipt rself.workReceipt = nil } else { if rself.workReceipt != nil { panic("Logic error: work receipt should be nil if there's no buffer to drain") } } for toDrain := range rself.Writer.workChan { if toDrain == nil { break } else { rself.Writer.doneWorkChan <- toDrain } } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
io2/writer_to_reader_adapter.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L158-L187
go
train
// 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
func copyDataToOutput(inputFactory func(io.Reader) (io.Reader, error), adaptedInput *privateReaderAdapter, output io.Writer, shouldCloseDownstream bool)
// 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 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) }