repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
nats-io/go-nats | bench/bench.go | CSV | func (bm *Benchmark) CSV() string {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
headers := []string{"#RunID", "ClientID", "MsgCount", "MsgBytes", "MsgsPerSec", "BytesPerSec", "DurationSecs"}
if err := writer.Write(headers); err != nil {
log.Fatalf("Error while serializing headers %q: %v", headers, err)
}
groups := []*SampleGroup{bm.Subs, bm.Pubs}
pre := "S"
for i, g := range groups {
if i == 1 {
pre = "P"
}
for j, c := range g.Samples {
r := []string{bm.RunID, fmt.Sprintf("%s%d", pre, j), fmt.Sprintf("%d", c.MsgCnt), fmt.Sprintf("%d", c.MsgBytes), fmt.Sprintf("%d", c.Rate()), fmt.Sprintf("%f", c.Throughput()), fmt.Sprintf("%f", c.Duration().Seconds())}
if err := writer.Write(r); err != nil {
log.Fatalf("Error while serializing %v: %v", c, err)
}
}
}
writer.Flush()
return buffer.String()
} | go | func (bm *Benchmark) CSV() string {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
headers := []string{"#RunID", "ClientID", "MsgCount", "MsgBytes", "MsgsPerSec", "BytesPerSec", "DurationSecs"}
if err := writer.Write(headers); err != nil {
log.Fatalf("Error while serializing headers %q: %v", headers, err)
}
groups := []*SampleGroup{bm.Subs, bm.Pubs}
pre := "S"
for i, g := range groups {
if i == 1 {
pre = "P"
}
for j, c := range g.Samples {
r := []string{bm.RunID, fmt.Sprintf("%s%d", pre, j), fmt.Sprintf("%d", c.MsgCnt), fmt.Sprintf("%d", c.MsgBytes), fmt.Sprintf("%d", c.Rate()), fmt.Sprintf("%f", c.Throughput()), fmt.Sprintf("%f", c.Duration().Seconds())}
if err := writer.Write(r); err != nil {
log.Fatalf("Error while serializing %v: %v", c, err)
}
}
}
writer.Flush()
return buffer.String()
} | [
"func",
"(",
"bm",
"*",
"Benchmark",
")",
"CSV",
"(",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"writer",
":=",
"csv",
".",
"NewWriter",
"(",
"&",
"buffer",
")",
"\n",
"headers",
":=",
"[",
"]",
"string",
"{",
"\"#RunID\"",
",",
"\"ClientID\"",
",",
"\"MsgCount\"",
",",
"\"MsgBytes\"",
",",
"\"MsgsPerSec\"",
",",
"\"BytesPerSec\"",
",",
"\"DurationSecs\"",
"}",
"\n",
"if",
"err",
":=",
"writer",
".",
"Write",
"(",
"headers",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Error while serializing headers %q: %v\"",
",",
"headers",
",",
"err",
")",
"\n",
"}",
"\n",
"groups",
":=",
"[",
"]",
"*",
"SampleGroup",
"{",
"bm",
".",
"Subs",
",",
"bm",
".",
"Pubs",
"}",
"\n",
"pre",
":=",
"\"S\"",
"\n",
"for",
"i",
",",
"g",
":=",
"range",
"groups",
"{",
"if",
"i",
"==",
"1",
"{",
"pre",
"=",
"\"P\"",
"\n",
"}",
"\n",
"for",
"j",
",",
"c",
":=",
"range",
"g",
".",
"Samples",
"{",
"r",
":=",
"[",
"]",
"string",
"{",
"bm",
".",
"RunID",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s%d\"",
",",
"pre",
",",
"j",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%d\"",
",",
"c",
".",
"MsgCnt",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%d\"",
",",
"c",
".",
"MsgBytes",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%d\"",
",",
"c",
".",
"Rate",
"(",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%f\"",
",",
"c",
".",
"Throughput",
"(",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%f\"",
",",
"c",
".",
"Duration",
"(",
")",
".",
"Seconds",
"(",
")",
")",
"}",
"\n",
"if",
"err",
":=",
"writer",
".",
"Write",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Error while serializing %v: %v\"",
",",
"c",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"writer",
".",
"Flush",
"(",
")",
"\n",
"return",
"buffer",
".",
"String",
"(",
")",
"\n",
"}"
] | // CSV generates a csv report of all the samples collected | [
"CSV",
"generates",
"a",
"csv",
"report",
"of",
"all",
"the",
"samples",
"collected"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L120-L143 | train |
nats-io/go-nats | bench/bench.go | NewSample | func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample {
s := Sample{JobMsgCnt: jobCount, Start: start, End: end}
s.MsgBytes = uint64(msgSize * jobCount)
s.MsgCnt = nc.OutMsgs + nc.InMsgs
s.IOBytes = nc.OutBytes + nc.InBytes
return &s
} | go | func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample {
s := Sample{JobMsgCnt: jobCount, Start: start, End: end}
s.MsgBytes = uint64(msgSize * jobCount)
s.MsgCnt = nc.OutMsgs + nc.InMsgs
s.IOBytes = nc.OutBytes + nc.InBytes
return &s
} | [
"func",
"NewSample",
"(",
"jobCount",
"int",
",",
"msgSize",
"int",
",",
"start",
",",
"end",
"time",
".",
"Time",
",",
"nc",
"*",
"nats",
".",
"Conn",
")",
"*",
"Sample",
"{",
"s",
":=",
"Sample",
"{",
"JobMsgCnt",
":",
"jobCount",
",",
"Start",
":",
"start",
",",
"End",
":",
"end",
"}",
"\n",
"s",
".",
"MsgBytes",
"=",
"uint64",
"(",
"msgSize",
"*",
"jobCount",
")",
"\n",
"s",
".",
"MsgCnt",
"=",
"nc",
".",
"OutMsgs",
"+",
"nc",
".",
"InMsgs",
"\n",
"s",
".",
"IOBytes",
"=",
"nc",
".",
"OutBytes",
"+",
"nc",
".",
"InBytes",
"\n",
"return",
"&",
"s",
"\n",
"}"
] | // NewSample creates a new Sample initialized to the provided values. The nats.Conn information captured | [
"NewSample",
"creates",
"a",
"new",
"Sample",
"initialized",
"to",
"the",
"provided",
"values",
".",
"The",
"nats",
".",
"Conn",
"information",
"captured"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L146-L152 | train |
nats-io/go-nats | bench/bench.go | Throughput | func (s *Sample) Throughput() float64 {
return float64(s.MsgBytes) / s.Duration().Seconds()
} | go | func (s *Sample) Throughput() float64 {
return float64(s.MsgBytes) / s.Duration().Seconds()
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Throughput",
"(",
")",
"float64",
"{",
"return",
"float64",
"(",
"s",
".",
"MsgBytes",
")",
"/",
"s",
".",
"Duration",
"(",
")",
".",
"Seconds",
"(",
")",
"\n",
"}"
] | // Throughput of bytes per second | [
"Throughput",
"of",
"bytes",
"per",
"second"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L155-L157 | train |
nats-io/go-nats | bench/bench.go | Rate | func (s *Sample) Rate() int64 {
return int64(float64(s.JobMsgCnt) / s.Duration().Seconds())
} | go | func (s *Sample) Rate() int64 {
return int64(float64(s.JobMsgCnt) / s.Duration().Seconds())
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Rate",
"(",
")",
"int64",
"{",
"return",
"int64",
"(",
"float64",
"(",
"s",
".",
"JobMsgCnt",
")",
"/",
"s",
".",
"Duration",
"(",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}"
] | // Rate of meessages in the job per second | [
"Rate",
"of",
"meessages",
"in",
"the",
"job",
"per",
"second"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L160-L162 | train |
nats-io/go-nats | bench/bench.go | Duration | func (s *Sample) Duration() time.Duration {
return s.End.Sub(s.Start)
} | go | func (s *Sample) Duration() time.Duration {
return s.End.Sub(s.Start)
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Duration",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"s",
".",
"End",
".",
"Sub",
"(",
"s",
".",
"Start",
")",
"\n",
"}"
] | // Duration that the sample was active | [
"Duration",
"that",
"the",
"sample",
"was",
"active"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L171-L173 | train |
nats-io/go-nats | bench/bench.go | MinRate | func (sg *SampleGroup) MinRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = min(m, s.Rate())
}
return m
} | go | func (sg *SampleGroup) MinRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = min(m, s.Rate())
}
return m
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"MinRate",
"(",
")",
"int64",
"{",
"m",
":=",
"int64",
"(",
"0",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"sg",
".",
"Samples",
"{",
"if",
"i",
"==",
"0",
"{",
"m",
"=",
"s",
".",
"Rate",
"(",
")",
"\n",
"}",
"\n",
"m",
"=",
"min",
"(",
"m",
",",
"s",
".",
"Rate",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // MinRate returns the smallest message rate in the SampleGroup | [
"MinRate",
"returns",
"the",
"smallest",
"message",
"rate",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L193-L202 | train |
nats-io/go-nats | bench/bench.go | MaxRate | func (sg *SampleGroup) MaxRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = max(m, s.Rate())
}
return m
} | go | func (sg *SampleGroup) MaxRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = max(m, s.Rate())
}
return m
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"MaxRate",
"(",
")",
"int64",
"{",
"m",
":=",
"int64",
"(",
"0",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"sg",
".",
"Samples",
"{",
"if",
"i",
"==",
"0",
"{",
"m",
"=",
"s",
".",
"Rate",
"(",
")",
"\n",
"}",
"\n",
"m",
"=",
"max",
"(",
"m",
",",
"s",
".",
"Rate",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // MaxRate returns the largest message rate in the SampleGroup | [
"MaxRate",
"returns",
"the",
"largest",
"message",
"rate",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L205-L214 | train |
nats-io/go-nats | bench/bench.go | AvgRate | func (sg *SampleGroup) AvgRate() int64 {
sum := uint64(0)
for _, s := range sg.Samples {
sum += uint64(s.Rate())
}
return int64(sum / uint64(len(sg.Samples)))
} | go | func (sg *SampleGroup) AvgRate() int64 {
sum := uint64(0)
for _, s := range sg.Samples {
sum += uint64(s.Rate())
}
return int64(sum / uint64(len(sg.Samples)))
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"AvgRate",
"(",
")",
"int64",
"{",
"sum",
":=",
"uint64",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"sg",
".",
"Samples",
"{",
"sum",
"+=",
"uint64",
"(",
"s",
".",
"Rate",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"sum",
"/",
"uint64",
"(",
"len",
"(",
"sg",
".",
"Samples",
")",
")",
")",
"\n",
"}"
] | // AvgRate returns the average of all the message rates in the SampleGroup | [
"AvgRate",
"returns",
"the",
"average",
"of",
"all",
"the",
"message",
"rates",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L217-L223 | train |
nats-io/go-nats | bench/bench.go | StdDev | func (sg *SampleGroup) StdDev() float64 {
avg := float64(sg.AvgRate())
sum := float64(0)
for _, c := range sg.Samples {
sum += math.Pow(float64(c.Rate())-avg, 2)
}
variance := sum / float64(len(sg.Samples))
return math.Sqrt(variance)
} | go | func (sg *SampleGroup) StdDev() float64 {
avg := float64(sg.AvgRate())
sum := float64(0)
for _, c := range sg.Samples {
sum += math.Pow(float64(c.Rate())-avg, 2)
}
variance := sum / float64(len(sg.Samples))
return math.Sqrt(variance)
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"StdDev",
"(",
")",
"float64",
"{",
"avg",
":=",
"float64",
"(",
"sg",
".",
"AvgRate",
"(",
")",
")",
"\n",
"sum",
":=",
"float64",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"sg",
".",
"Samples",
"{",
"sum",
"+=",
"math",
".",
"Pow",
"(",
"float64",
"(",
"c",
".",
"Rate",
"(",
")",
")",
"-",
"avg",
",",
"2",
")",
"\n",
"}",
"\n",
"variance",
":=",
"sum",
"/",
"float64",
"(",
"len",
"(",
"sg",
".",
"Samples",
")",
")",
"\n",
"return",
"math",
".",
"Sqrt",
"(",
"variance",
")",
"\n",
"}"
] | // StdDev returns the standard deviation the message rates in the SampleGroup | [
"StdDev",
"returns",
"the",
"standard",
"deviation",
"the",
"message",
"rates",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L226-L234 | train |
nats-io/go-nats | bench/bench.go | AddSample | func (sg *SampleGroup) AddSample(e *Sample) {
sg.Samples = append(sg.Samples, e)
if len(sg.Samples) == 1 {
sg.Start = e.Start
sg.End = e.End
}
sg.IOBytes += e.IOBytes
sg.JobMsgCnt += e.JobMsgCnt
sg.MsgCnt += e.MsgCnt
sg.MsgBytes += e.MsgBytes
if e.Start.Before(sg.Start) {
sg.Start = e.Start
}
if e.End.After(sg.End) {
sg.End = e.End
}
} | go | func (sg *SampleGroup) AddSample(e *Sample) {
sg.Samples = append(sg.Samples, e)
if len(sg.Samples) == 1 {
sg.Start = e.Start
sg.End = e.End
}
sg.IOBytes += e.IOBytes
sg.JobMsgCnt += e.JobMsgCnt
sg.MsgCnt += e.MsgCnt
sg.MsgBytes += e.MsgBytes
if e.Start.Before(sg.Start) {
sg.Start = e.Start
}
if e.End.After(sg.End) {
sg.End = e.End
}
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"AddSample",
"(",
"e",
"*",
"Sample",
")",
"{",
"sg",
".",
"Samples",
"=",
"append",
"(",
"sg",
".",
"Samples",
",",
"e",
")",
"\n",
"if",
"len",
"(",
"sg",
".",
"Samples",
")",
"==",
"1",
"{",
"sg",
".",
"Start",
"=",
"e",
".",
"Start",
"\n",
"sg",
".",
"End",
"=",
"e",
".",
"End",
"\n",
"}",
"\n",
"sg",
".",
"IOBytes",
"+=",
"e",
".",
"IOBytes",
"\n",
"sg",
".",
"JobMsgCnt",
"+=",
"e",
".",
"JobMsgCnt",
"\n",
"sg",
".",
"MsgCnt",
"+=",
"e",
".",
"MsgCnt",
"\n",
"sg",
".",
"MsgBytes",
"+=",
"e",
".",
"MsgBytes",
"\n",
"if",
"e",
".",
"Start",
".",
"Before",
"(",
"sg",
".",
"Start",
")",
"{",
"sg",
".",
"Start",
"=",
"e",
".",
"Start",
"\n",
"}",
"\n",
"if",
"e",
".",
"End",
".",
"After",
"(",
"sg",
".",
"End",
")",
"{",
"sg",
".",
"End",
"=",
"e",
".",
"End",
"\n",
"}",
"\n",
"}"
] | // AddSample adds a Sample to the SampleGroup. After adding a Sample it shouldn't be modified. | [
"AddSample",
"adds",
"a",
"Sample",
"to",
"the",
"SampleGroup",
".",
"After",
"adding",
"a",
"Sample",
"it",
"shouldn",
"t",
"be",
"modified",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L237-L256 | train |
nats-io/go-nats | bench/bench.go | Report | func (bm *Benchmark) Report() string {
var buffer bytes.Buffer
indent := ""
if !bm.Pubs.HasSamples() && !bm.Subs.HasSamples() {
return "No publisher or subscribers. Nothing to report."
}
if bm.Pubs.HasSamples() && bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%s Pub/Sub stats: %s\n", bm.Name, bm))
indent += " "
}
if bm.Pubs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sPub stats: %s\n", indent, bm.Pubs))
if len(bm.Pubs.Samples) > 1 {
for i, stat := range bm.Pubs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Pubs.Statistics()))
}
}
if bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sSub stats: %s\n", indent, bm.Subs))
if len(bm.Subs.Samples) > 1 {
for i, stat := range bm.Subs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Subs.Statistics()))
}
}
return buffer.String()
} | go | func (bm *Benchmark) Report() string {
var buffer bytes.Buffer
indent := ""
if !bm.Pubs.HasSamples() && !bm.Subs.HasSamples() {
return "No publisher or subscribers. Nothing to report."
}
if bm.Pubs.HasSamples() && bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%s Pub/Sub stats: %s\n", bm.Name, bm))
indent += " "
}
if bm.Pubs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sPub stats: %s\n", indent, bm.Pubs))
if len(bm.Pubs.Samples) > 1 {
for i, stat := range bm.Pubs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Pubs.Statistics()))
}
}
if bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sSub stats: %s\n", indent, bm.Subs))
if len(bm.Subs.Samples) > 1 {
for i, stat := range bm.Subs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Subs.Statistics()))
}
}
return buffer.String()
} | [
"func",
"(",
"bm",
"*",
"Benchmark",
")",
"Report",
"(",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"indent",
":=",
"\"\"",
"\n",
"if",
"!",
"bm",
".",
"Pubs",
".",
"HasSamples",
"(",
")",
"&&",
"!",
"bm",
".",
"Subs",
".",
"HasSamples",
"(",
")",
"{",
"return",
"\"No publisher or subscribers. Nothing to report.\"",
"\n",
"}",
"\n",
"if",
"bm",
".",
"Pubs",
".",
"HasSamples",
"(",
")",
"&&",
"bm",
".",
"Subs",
".",
"HasSamples",
"(",
")",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s Pub/Sub stats: %s\\n\"",
",",
"\\n",
",",
"bm",
".",
"Name",
")",
")",
"\n",
"bm",
"\n",
"}",
"\n",
"indent",
"+=",
"\" \"",
"\n",
"if",
"bm",
".",
"Pubs",
".",
"HasSamples",
"(",
")",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%sPub stats: %s\\n\"",
",",
"\\n",
",",
"indent",
")",
")",
"\n",
"bm",
".",
"Pubs",
"\n",
"}",
"\n",
"if",
"len",
"(",
"bm",
".",
"Pubs",
".",
"Samples",
")",
">",
"1",
"{",
"for",
"i",
",",
"stat",
":=",
"range",
"bm",
".",
"Pubs",
".",
"Samples",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s [%d] %v (%d msgs)\\n\"",
",",
"\\n",
",",
"indent",
",",
"i",
"+",
"1",
",",
"stat",
")",
")",
"\n",
"}",
"\n",
"stat",
".",
"JobMsgCnt",
"\n",
"}",
"\n",
"}"
] | // Report returns a human readable report of the samples taken in the Benchmark | [
"Report",
"returns",
"a",
"human",
"readable",
"report",
"of",
"the",
"samples",
"taken",
"in",
"the",
"Benchmark"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L264-L296 | train |
nats-io/go-nats | bench/bench.go | HumanBytes | func HumanBytes(bytes float64, si bool) string {
var base = 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
var post = "B"
if si {
base = 1000
pre = []string{"k", "M", "G", "T", "P", "E"}
post = "iB"
}
if bytes < float64(base) {
return fmt.Sprintf("%.2f B", bytes)
}
exp := int(math.Log(bytes) / math.Log(float64(base)))
index := exp - 1
units := pre[index] + post
return fmt.Sprintf("%.2f %s", bytes/math.Pow(float64(base), float64(exp)), units)
} | go | func HumanBytes(bytes float64, si bool) string {
var base = 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
var post = "B"
if si {
base = 1000
pre = []string{"k", "M", "G", "T", "P", "E"}
post = "iB"
}
if bytes < float64(base) {
return fmt.Sprintf("%.2f B", bytes)
}
exp := int(math.Log(bytes) / math.Log(float64(base)))
index := exp - 1
units := pre[index] + post
return fmt.Sprintf("%.2f %s", bytes/math.Pow(float64(base), float64(exp)), units)
} | [
"func",
"HumanBytes",
"(",
"bytes",
"float64",
",",
"si",
"bool",
")",
"string",
"{",
"var",
"base",
"=",
"1024",
"\n",
"pre",
":=",
"[",
"]",
"string",
"{",
"\"K\"",
",",
"\"M\"",
",",
"\"G\"",
",",
"\"T\"",
",",
"\"P\"",
",",
"\"E\"",
"}",
"\n",
"var",
"post",
"=",
"\"B\"",
"\n",
"if",
"si",
"{",
"base",
"=",
"1000",
"\n",
"pre",
"=",
"[",
"]",
"string",
"{",
"\"k\"",
",",
"\"M\"",
",",
"\"G\"",
",",
"\"T\"",
",",
"\"P\"",
",",
"\"E\"",
"}",
"\n",
"post",
"=",
"\"iB\"",
"\n",
"}",
"\n",
"if",
"bytes",
"<",
"float64",
"(",
"base",
")",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%.2f B\"",
",",
"bytes",
")",
"\n",
"}",
"\n",
"exp",
":=",
"int",
"(",
"math",
".",
"Log",
"(",
"bytes",
")",
"/",
"math",
".",
"Log",
"(",
"float64",
"(",
"base",
")",
")",
")",
"\n",
"index",
":=",
"exp",
"-",
"1",
"\n",
"units",
":=",
"pre",
"[",
"index",
"]",
"+",
"post",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%.2f %s\"",
",",
"bytes",
"/",
"math",
".",
"Pow",
"(",
"float64",
"(",
"base",
")",
",",
"float64",
"(",
"exp",
")",
")",
",",
"units",
")",
"\n",
"}"
] | // HumanBytes formats bytes as a human readable string | [
"HumanBytes",
"formats",
"bytes",
"as",
"a",
"human",
"readable",
"string"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L317-L333 | train |
nats-io/go-nats | bench/bench.go | MsgsPerClient | func MsgsPerClient(numMsgs, numClients int) []int {
var counts []int
if numClients == 0 || numMsgs == 0 {
return counts
}
counts = make([]int, numClients)
mc := numMsgs / numClients
for i := 0; i < numClients; i++ {
counts[i] = mc
}
extra := numMsgs % numClients
for i := 0; i < extra; i++ {
counts[i]++
}
return counts
} | go | func MsgsPerClient(numMsgs, numClients int) []int {
var counts []int
if numClients == 0 || numMsgs == 0 {
return counts
}
counts = make([]int, numClients)
mc := numMsgs / numClients
for i := 0; i < numClients; i++ {
counts[i] = mc
}
extra := numMsgs % numClients
for i := 0; i < extra; i++ {
counts[i]++
}
return counts
} | [
"func",
"MsgsPerClient",
"(",
"numMsgs",
",",
"numClients",
"int",
")",
"[",
"]",
"int",
"{",
"var",
"counts",
"[",
"]",
"int",
"\n",
"if",
"numClients",
"==",
"0",
"||",
"numMsgs",
"==",
"0",
"{",
"return",
"counts",
"\n",
"}",
"\n",
"counts",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"numClients",
")",
"\n",
"mc",
":=",
"numMsgs",
"/",
"numClients",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numClients",
";",
"i",
"++",
"{",
"counts",
"[",
"i",
"]",
"=",
"mc",
"\n",
"}",
"\n",
"extra",
":=",
"numMsgs",
"%",
"numClients",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"extra",
";",
"i",
"++",
"{",
"counts",
"[",
"i",
"]",
"++",
"\n",
"}",
"\n",
"return",
"counts",
"\n",
"}"
] | // MsgsPerClient divides the number of messages by the number of clients and tries to distribute them as evenly as possible | [
"MsgsPerClient",
"divides",
"the",
"number",
"of",
"messages",
"by",
"the",
"number",
"of",
"clients",
"and",
"tries",
"to",
"distribute",
"them",
"as",
"evenly",
"as",
"possible"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L350-L365 | train |
nats-io/go-nats | timer.go | Get | func (tp *timerPool) Get(d time.Duration) *time.Timer {
if t, _ := tp.p.Get().(*time.Timer); t != nil {
t.Reset(d)
return t
}
return time.NewTimer(d)
} | go | func (tp *timerPool) Get(d time.Duration) *time.Timer {
if t, _ := tp.p.Get().(*time.Timer); t != nil {
t.Reset(d)
return t
}
return time.NewTimer(d)
} | [
"func",
"(",
"tp",
"*",
"timerPool",
")",
"Get",
"(",
"d",
"time",
".",
"Duration",
")",
"*",
"time",
".",
"Timer",
"{",
"if",
"t",
",",
"_",
":=",
"tp",
".",
"p",
".",
"Get",
"(",
")",
".",
"(",
"*",
"time",
".",
"Timer",
")",
";",
"t",
"!=",
"nil",
"{",
"t",
".",
"Reset",
"(",
"d",
")",
"\n",
"return",
"t",
"\n",
"}",
"\n",
"return",
"time",
".",
"NewTimer",
"(",
"d",
")",
"\n",
"}"
] | // Get returns a timer that completes after the given duration. | [
"Get",
"returns",
"a",
"timer",
"that",
"completes",
"after",
"the",
"given",
"duration",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/timer.go#L31-L38 | train |
securego/gosec | rules/blacklist.go | NewBlacklistedImports | func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node) {
return &blacklistedImport{
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
},
Blacklisted: blacklist,
}, []ast.Node{(*ast.ImportSpec)(nil)}
} | go | func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node) {
return &blacklistedImport{
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
},
Blacklisted: blacklist,
}, []ast.Node{(*ast.ImportSpec)(nil)}
} | [
"func",
"NewBlacklistedImports",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
",",
"blacklist",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"return",
"&",
"blacklistedImport",
"{",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"}",
",",
"Blacklisted",
":",
"blacklist",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"ImportSpec",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewBlacklistedImports reports when a blacklisted import is being used.
// Typically when a deprecated technology is being used. | [
"NewBlacklistedImports",
"reports",
"when",
"a",
"blacklisted",
"import",
"is",
"being",
"used",
".",
"Typically",
"when",
"a",
"deprecated",
"technology",
"is",
"being",
"used",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/blacklist.go#L50-L59 | train |
securego/gosec | rules/blacklist.go | NewBlacklistedImportRC4 | func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
return NewBlacklistedImports(id, conf, map[string]string{
"crypto/rc4": "Blacklisted import crypto/rc4: weak cryptographic primitive",
})
} | go | func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
return NewBlacklistedImports(id, conf, map[string]string{
"crypto/rc4": "Blacklisted import crypto/rc4: weak cryptographic primitive",
})
} | [
"func",
"NewBlacklistedImportRC4",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"return",
"NewBlacklistedImports",
"(",
"id",
",",
"conf",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"\"crypto/rc4\"",
":",
"\"Blacklisted import crypto/rc4: weak cryptographic primitive\"",
",",
"}",
")",
"\n",
"}"
] | // NewBlacklistedImportRC4 fails if DES is imported | [
"NewBlacklistedImportRC4",
"fails",
"if",
"DES",
"is",
"imported"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/blacklist.go#L76-L80 | train |
securego/gosec | rules/hardcoded_credentials.go | NewHardcodedCredentials | func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
pattern := `(?i)passwd|pass|password|pwd|secret|token`
entropyThreshold := 80.0
perCharThreshold := 3.0
ignoreEntropy := false
var truncateString = 16
if val, ok := conf["G101"]; ok {
conf := val.(map[string]string)
if configPattern, ok := conf["pattern"]; ok {
pattern = configPattern
}
if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok {
if parsedBool, err := strconv.ParseBool(configIgnoreEntropy); err == nil {
ignoreEntropy = parsedBool
}
}
if configEntropyThreshold, ok := conf["entropy_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configEntropyThreshold, 64); err == nil {
entropyThreshold = parsedNum
}
}
if configCharThreshold, ok := conf["per_char_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configCharThreshold, 64); err == nil {
perCharThreshold = parsedNum
}
}
if configTruncate, ok := conf["truncate"]; ok {
if parsedInt, err := strconv.Atoi(configTruncate); err == nil {
truncateString = parsedInt
}
}
}
return &credentials{
pattern: regexp.MustCompile(pattern),
entropyThreshold: entropyThreshold,
perCharThreshold: perCharThreshold,
ignoreEntropy: ignoreEntropy,
truncate: truncateString,
MetaData: gosec.MetaData{
ID: id,
What: "Potential hardcoded credentials",
Confidence: gosec.Low,
Severity: gosec.High,
},
}, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)}
} | go | func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
pattern := `(?i)passwd|pass|password|pwd|secret|token`
entropyThreshold := 80.0
perCharThreshold := 3.0
ignoreEntropy := false
var truncateString = 16
if val, ok := conf["G101"]; ok {
conf := val.(map[string]string)
if configPattern, ok := conf["pattern"]; ok {
pattern = configPattern
}
if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok {
if parsedBool, err := strconv.ParseBool(configIgnoreEntropy); err == nil {
ignoreEntropy = parsedBool
}
}
if configEntropyThreshold, ok := conf["entropy_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configEntropyThreshold, 64); err == nil {
entropyThreshold = parsedNum
}
}
if configCharThreshold, ok := conf["per_char_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configCharThreshold, 64); err == nil {
perCharThreshold = parsedNum
}
}
if configTruncate, ok := conf["truncate"]; ok {
if parsedInt, err := strconv.Atoi(configTruncate); err == nil {
truncateString = parsedInt
}
}
}
return &credentials{
pattern: regexp.MustCompile(pattern),
entropyThreshold: entropyThreshold,
perCharThreshold: perCharThreshold,
ignoreEntropy: ignoreEntropy,
truncate: truncateString,
MetaData: gosec.MetaData{
ID: id,
What: "Potential hardcoded credentials",
Confidence: gosec.Low,
Severity: gosec.High,
},
}, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)}
} | [
"func",
"NewHardcodedCredentials",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"pattern",
":=",
"`(?i)passwd|pass|password|pwd|secret|token`",
"\n",
"entropyThreshold",
":=",
"80.0",
"\n",
"perCharThreshold",
":=",
"3.0",
"\n",
"ignoreEntropy",
":=",
"false",
"\n",
"var",
"truncateString",
"=",
"16",
"\n",
"if",
"val",
",",
"ok",
":=",
"conf",
"[",
"\"G101\"",
"]",
";",
"ok",
"{",
"conf",
":=",
"val",
".",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"if",
"configPattern",
",",
"ok",
":=",
"conf",
"[",
"\"pattern\"",
"]",
";",
"ok",
"{",
"pattern",
"=",
"configPattern",
"\n",
"}",
"\n",
"if",
"configIgnoreEntropy",
",",
"ok",
":=",
"conf",
"[",
"\"ignore_entropy\"",
"]",
";",
"ok",
"{",
"if",
"parsedBool",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"configIgnoreEntropy",
")",
";",
"err",
"==",
"nil",
"{",
"ignoreEntropy",
"=",
"parsedBool",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"configEntropyThreshold",
",",
"ok",
":=",
"conf",
"[",
"\"entropy_threshold\"",
"]",
";",
"ok",
"{",
"if",
"parsedNum",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"configEntropyThreshold",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"entropyThreshold",
"=",
"parsedNum",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"configCharThreshold",
",",
"ok",
":=",
"conf",
"[",
"\"per_char_threshold\"",
"]",
";",
"ok",
"{",
"if",
"parsedNum",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"configCharThreshold",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"perCharThreshold",
"=",
"parsedNum",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"configTruncate",
",",
"ok",
":=",
"conf",
"[",
"\"truncate\"",
"]",
";",
"ok",
"{",
"if",
"parsedInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"configTruncate",
")",
";",
"err",
"==",
"nil",
"{",
"truncateString",
"=",
"parsedInt",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"credentials",
"{",
"pattern",
":",
"regexp",
".",
"MustCompile",
"(",
"pattern",
")",
",",
"entropyThreshold",
":",
"entropyThreshold",
",",
"perCharThreshold",
":",
"perCharThreshold",
",",
"ignoreEntropy",
":",
"ignoreEntropy",
",",
"truncate",
":",
"truncateString",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"What",
":",
"\"Potential hardcoded credentials\"",
",",
"Confidence",
":",
"gosec",
".",
"Low",
",",
"Severity",
":",
"gosec",
".",
"High",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"AssignStmt",
")",
"(",
"nil",
")",
",",
"(",
"*",
"ast",
".",
"ValueSpec",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewHardcodedCredentials attempts to find high entropy string constants being
// assigned to variables that appear to be related to credentials. | [
"NewHardcodedCredentials",
"attempts",
"to",
"find",
"high",
"entropy",
"string",
"constants",
"being",
"assigned",
"to",
"variables",
"that",
"appear",
"to",
"be",
"related",
"to",
"credentials",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/hardcoded_credentials.go#L101-L147 | train |
securego/gosec | rules/bind.go | NewBindsToAllNetworkInterfaces | func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("net", "Listen")
calls.Add("crypto/tls", "Listen")
return &bindsToAllNetworkInterfaces{
calls: calls,
pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`),
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: "Binds to all network interfaces",
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("net", "Listen")
calls.Add("crypto/tls", "Listen")
return &bindsToAllNetworkInterfaces{
calls: calls,
pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`),
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: "Binds to all network interfaces",
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewBindsToAllNetworkInterfaces",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"calls",
":=",
"gosec",
".",
"NewCallList",
"(",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"net\"",
",",
"\"Listen\"",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"crypto/tls\"",
",",
"\"Listen\"",
")",
"\n",
"return",
"&",
"bindsToAllNetworkInterfaces",
"{",
"calls",
":",
"calls",
",",
"pattern",
":",
"regexp",
".",
"MustCompile",
"(",
"`^(0.0.0.0|:).*$`",
")",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"What",
":",
"\"Binds to all network interfaces\"",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewBindsToAllNetworkInterfaces detects socket connections that are setup to
// listen on all network interfaces. | [
"NewBindsToAllNetworkInterfaces",
"detects",
"socket",
"connections",
"that",
"are",
"setup",
"to",
"listen",
"on",
"all",
"network",
"interfaces",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/bind.go#L69-L83 | train |
securego/gosec | rules/fileperms.go | NewFilePerms | func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
mode := getConfiguredMode(conf, "G302", 0600)
return &filePermissions{
mode: mode,
pkg: "os",
calls: []string{"OpenFile", "Chmod"},
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("Expect file permissions to be %#o or less", mode),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
mode := getConfiguredMode(conf, "G302", 0600)
return &filePermissions{
mode: mode,
pkg: "os",
calls: []string{"OpenFile", "Chmod"},
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("Expect file permissions to be %#o or less", mode),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewFilePerms",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"mode",
":=",
"getConfiguredMode",
"(",
"conf",
",",
"\"G302\"",
",",
"0600",
")",
"\n",
"return",
"&",
"filePermissions",
"{",
"mode",
":",
"mode",
",",
"pkg",
":",
"\"os\"",
",",
"calls",
":",
"[",
"]",
"string",
"{",
"\"OpenFile\"",
",",
"\"Chmod\"",
"}",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"What",
":",
"fmt",
".",
"Sprintf",
"(",
"\"Expect file permissions to be %#o or less\"",
",",
"mode",
")",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewFilePerms creates a rule to detect file creation with a more permissive than configured
// permission mask. | [
"NewFilePerms",
"creates",
"a",
"rule",
"to",
"detect",
"file",
"creation",
"with",
"a",
"more",
"permissive",
"than",
"configured",
"permission",
"mask",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/fileperms.go#L65-L78 | train |
securego/gosec | rules/rsa.go | NewWeakKeyStrength | func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("crypto/rsa", "GenerateKey")
bits := 2048
return &weakKeyStrength{
calls: calls,
bits: bits,
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("RSA keys should be at least %d bits", bits),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("crypto/rsa", "GenerateKey")
bits := 2048
return &weakKeyStrength{
calls: calls,
bits: bits,
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("RSA keys should be at least %d bits", bits),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewWeakKeyStrength",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"calls",
":=",
"gosec",
".",
"NewCallList",
"(",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"crypto/rsa\"",
",",
"\"GenerateKey\"",
")",
"\n",
"bits",
":=",
"2048",
"\n",
"return",
"&",
"weakKeyStrength",
"{",
"calls",
":",
"calls",
",",
"bits",
":",
"bits",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"What",
":",
"fmt",
".",
"Sprintf",
"(",
"\"RSA keys should be at least %d bits\"",
",",
"bits",
")",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewWeakKeyStrength builds a rule that detects RSA keys < 2048 bits | [
"NewWeakKeyStrength",
"builds",
"a",
"rule",
"that",
"detects",
"RSA",
"keys",
"<",
"2048",
"bits"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rsa.go#L44-L58 | train |
securego/gosec | rules/subproc.go | NewSubproc | func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
rule.Add("os/exec", "Command")
rule.Add("os/exec", "CommandContext")
rule.Add("syscall", "Exec")
return rule, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
rule.Add("os/exec", "Command")
rule.Add("os/exec", "CommandContext")
rule.Add("syscall", "Exec")
return rule, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewSubproc",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"rule",
":=",
"&",
"subprocess",
"{",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
"}",
",",
"gosec",
".",
"NewCallList",
"(",
")",
"}",
"\n",
"rule",
".",
"Add",
"(",
"\"os/exec\"",
",",
"\"Command\"",
")",
"\n",
"rule",
".",
"Add",
"(",
"\"os/exec\"",
",",
"\"CommandContext\"",
")",
"\n",
"rule",
".",
"Add",
"(",
"\"syscall\"",
",",
"\"Exec\"",
")",
"\n",
"return",
"rule",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewSubproc detects cases where we are forking out to an external process | [
"NewSubproc",
"detects",
"cases",
"where",
"we",
"are",
"forking",
"out",
"to",
"an",
"external",
"process"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/subproc.go#L58-L64 | train |
securego/gosec | rules/archive.go | Match | func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
if node := a.calls.ContainsCallExpr(n, c, false); node != nil {
for _, arg := range node.Args {
var argType types.Type
if selector, ok := arg.(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
} else if ident, ok := arg.(*ast.Ident); ok {
if ident.Obj != nil && ident.Obj.Kind == ast.Var {
decl := ident.Obj.Decl
if assign, ok := decl.(*ast.AssignStmt); ok {
if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
}
}
}
}
if argType != nil && argType.String() == a.argType {
return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil
}
}
}
return nil, nil
} | go | func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
if node := a.calls.ContainsCallExpr(n, c, false); node != nil {
for _, arg := range node.Args {
var argType types.Type
if selector, ok := arg.(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
} else if ident, ok := arg.(*ast.Ident); ok {
if ident.Obj != nil && ident.Obj.Kind == ast.Var {
decl := ident.Obj.Decl
if assign, ok := decl.(*ast.AssignStmt); ok {
if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
}
}
}
}
if argType != nil && argType.String() == a.argType {
return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil
}
}
}
return nil, nil
} | [
"func",
"(",
"a",
"*",
"archive",
")",
"Match",
"(",
"n",
"ast",
".",
"Node",
",",
"c",
"*",
"gosec",
".",
"Context",
")",
"(",
"*",
"gosec",
".",
"Issue",
",",
"error",
")",
"{",
"if",
"node",
":=",
"a",
".",
"calls",
".",
"ContainsCallExpr",
"(",
"n",
",",
"c",
",",
"false",
")",
";",
"node",
"!=",
"nil",
"{",
"for",
"_",
",",
"arg",
":=",
"range",
"node",
".",
"Args",
"{",
"var",
"argType",
"types",
".",
"Type",
"\n",
"if",
"selector",
",",
"ok",
":=",
"arg",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
";",
"ok",
"{",
"argType",
"=",
"c",
".",
"Info",
".",
"TypeOf",
"(",
"selector",
".",
"X",
")",
"\n",
"}",
"else",
"if",
"ident",
",",
"ok",
":=",
"arg",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"{",
"if",
"ident",
".",
"Obj",
"!=",
"nil",
"&&",
"ident",
".",
"Obj",
".",
"Kind",
"==",
"ast",
".",
"Var",
"{",
"decl",
":=",
"ident",
".",
"Obj",
".",
"Decl",
"\n",
"if",
"assign",
",",
"ok",
":=",
"decl",
".",
"(",
"*",
"ast",
".",
"AssignStmt",
")",
";",
"ok",
"{",
"if",
"selector",
",",
"ok",
":=",
"assign",
".",
"Rhs",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
";",
"ok",
"{",
"argType",
"=",
"c",
".",
"Info",
".",
"TypeOf",
"(",
"selector",
".",
"X",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"argType",
"!=",
"nil",
"&&",
"argType",
".",
"String",
"(",
")",
"==",
"a",
".",
"argType",
"{",
"return",
"gosec",
".",
"NewIssue",
"(",
"c",
",",
"n",
",",
"a",
".",
"ID",
"(",
")",
",",
"a",
".",
"What",
",",
"a",
".",
"Severity",
",",
"a",
".",
"Confidence",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File | [
"Match",
"inspects",
"AST",
"nodes",
"to",
"determine",
"if",
"the",
"filepath",
".",
"Joins",
"uses",
"any",
"argument",
"derived",
"from",
"type",
"zip",
".",
"File"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/archive.go#L21-L44 | train |
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",
"(",
"\"path/filepath\"",
",",
"\"Join\"",
")",
"\n",
"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",
")",
"}",
"\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",
"(",
"\"Unexpected AST node type: %T\"",
",",
"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",
"(",
"\"Unexpected AST node type: %T\"",
",",
"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",
"(",
"\"Unexpected AST node type: %T\"",
",",
"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",
"(",
"\"Unexpected AST node type: %T\"",
",",
"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",
"\"undefined\"",
",",
"fn",
".",
"Sel",
".",
"Name",
",",
"fmt",
".",
"Errorf",
"(",
"\"missing type info\"",
")",
"\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",
"(",
"\"unable to determine call info\"",
")",
"\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",
"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",
"if",
"_",
",",
"initonly",
":=",
"ctx",
".",
"Imports",
".",
"InitOnly",
"[",
"path",
"]",
";",
"initonly",
"{",
"return",
"\"\"",
",",
"false",
"\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",
",",
"\"go\"",
")",
"\n",
"}",
"\n",
"path",
":=",
"Getenv",
"(",
"\"GOPATH\"",
",",
"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",
",",
"\".go\"",
")",
"{",
"abspath",
"=",
"filepath",
".",
"Dir",
"(",
"abspath",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"base",
":=",
"range",
"Gopath",
"(",
")",
"{",
"projectRoot",
":=",
"filepath",
".",
"FromSlash",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s/src/\"",
",",
"base",
")",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"abspath",
",",
"projectRoot",
")",
"{",
"return",
"strings",
".",
"TrimPrefix",
"(",
"abspath",
",",
"projectRoot",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"no project relative path found\"",
")",
"\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",
"(",
"\"no project absolute path found\"",
")",
"\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",
"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",
"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",
"if",
"len",
"(",
"identities",
")",
">",
"0",
"{",
"return",
"identities",
",",
"true",
"\n",
"}",
"\n",
"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",
")",
"==",
"\".go\"",
"{",
"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",
"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",
":",
"\"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",
")",
"}",
"\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",
"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",
":",
"\"SQL string concatenation\"",
",",
"}",
",",
"}",
",",
"}",
",",
"[",
"]",
"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",
"(",
"\"(?)(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\"",
",",
"}",
",",
"}",
",",
"}",
"\n",
"rule",
".",
"calls",
".",
"AddAll",
"(",
"\"fmt\"",
",",
"\"Sprint\"",
",",
"\"Sprintf\"",
",",
"\"Sprintln\"",
",",
"\"Fprintf\"",
")",
"\n",
"rule",
".",
"noIssue",
".",
"AddAll",
"(",
"\"os\"",
",",
"\"Stdout\"",
",",
"\"Stderr\"",
")",
"\n",
"rule",
".",
"noIssueQuoted",
".",
"Add",
"(",
"\"github.com/lib/pq\"",
",",
"\"QuoteIdentifier\"",
")",
"\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 %s not in configuration\"",
",",
"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",
"(",
"\"global setting for %s not found\"",
",",
"option",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"no global config options found\"",
")",
"\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",
"==",
"\"true\"",
"||",
"value",
"==",
"\"enabled\"",
")",
",",
"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",
"{",
"\"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",
")",
"}",
"\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",
":",
"\"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",
")",
"}",
"\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",
")",
"{",
"whitelist",
":=",
"gosec",
".",
"NewCallList",
"(",
")",
"\n",
"whitelist",
".",
"AddAll",
"(",
"\"bytes.Buffer\"",
",",
"\"Write\"",
",",
"\"WriteByte\"",
",",
"\"WriteRune\"",
",",
"\"WriteString\"",
")",
"\n",
"whitelist",
".",
"AddAll",
"(",
"\"fmt\"",
",",
"\"Print\"",
",",
"\"Printf\"",
",",
"\"Println\"",
",",
"\"Fprint\"",
",",
"\"Fprintf\"",
",",
"\"Fprintln\"",
")",
"\n",
"whitelist",
".",
"AddAll",
"(",
"\"strings.Builder\"",
",",
"\"Write\"",
",",
"\"WriteByte\"",
",",
"\"WriteRune\"",
",",
"\"WriteString\"",
")",
"\n",
"whitelist",
".",
"Add",
"(",
"\"io.PipeWriter\"",
",",
"\"CloseWithError\"",
")",
"\n",
"if",
"configured",
",",
"ok",
":=",
"conf",
"[",
"\"G104\"",
"]",
";",
"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",
":",
"\"Errors unhandled.\"",
",",
"}",
",",
"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",
":",
"\"*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",
")",
"}",
"\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",
"{",
"{",
"\"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",
"}",
",",
"{",
"\"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",
"}",
",",
"{",
"\"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",
"}",
",",
"{",
"\"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",
"}",
",",
"{",
"\"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",
"}",
",",
"}",
"\n",
"ruleMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"RuleDefinition",
")",
"\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",
"(",
"\"io/ioutil\"",
",",
"\"WriteFile\"",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"os\"",
",",
"\"Create\"",
")",
"\n",
"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",
")",
"}",
"\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",
"==",
"\"_\"",
"{",
"t",
".",
"InitOnly",
"[",
"path",
"]",
"=",
"true",
"\n",
"}",
"else",
"{",
"t",
".",
"Aliased",
"[",
"path",
"]",
"=",
"imported",
".",
"Name",
".",
"Name",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"path",
"==",
"\"unsafe\"",
"{",
"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",
"{",
"if",
"binExp",
",",
"ok",
":=",
"arg",
".",
"(",
"*",
"ast",
".",
"BinaryExpr",
")",
";",
"ok",
"{",
"if",
"_",
",",
"ok",
":=",
"gosec",
".",
"FindVarIdentities",
"(",
"binExp",
",",
"c",
")",
";",
"ok",
"{",
"return",
"true",
"\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",
"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",
"{",
"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",
"if",
"binExp",
",",
"ok",
":=",
"arg",
".",
"(",
"*",
"ast",
".",
"BinaryExpr",
")",
";",
"ok",
"{",
"if",
"_",
",",
"ok",
":=",
"gosec",
".",
"FindVarIdentities",
"(",
"binExp",
",",
"c",
")",
";",
"ok",
"{",
"return",
"gosec",
".",
"NewIssue",
"(",
"c",
",",
"n",
",",
"r",
".",
"ID",
"(",
")",
",",
"r",
".",
"What",
",",
"r",
".",
"Severity",
",",
"r",
".",
"Confidence",
")",
",",
"nil",
"\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",
":",
"\"Potential file inclusion via variable\"",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"}",
",",
"}",
"\n",
"rule",
".",
"pathJoin",
".",
"Add",
"(",
"\"path/filepath\"",
",",
"\"Join\"",
")",
"\n",
"rule",
".",
"pathJoin",
".",
"Add",
"(",
"\"path\"",
",",
"\"Join\"",
")",
"\n",
"rule",
".",
"Add",
"(",
"\"io/ioutil\"",
",",
"\"ReadFile\"",
")",
"\n",
"rule",
".",
"Add",
"(",
"\"os\"",
",",
"\"Open\"",
")",
"\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",
":",
"\"Potential HTTP request made with variable url\"",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"Medium",
",",
"}",
",",
"}",
"\n",
"rule",
".",
"AddAll",
"(",
"\"net/http\"",
",",
"\"Do\"",
",",
"\"Get\"",
",",
"\"Head\"",
",",
"\"Post\"",
",",
"\"PostForm\"",
",",
"\"RoundTrip\"",
")",
"\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",
"case",
"*",
"ast",
".",
"CompositeLit",
":",
"return",
"resolveCompLit",
"(",
"node",
",",
"c",
")",
"\n",
"case",
"*",
"ast",
".",
"Ident",
":",
"return",
"resolveIdent",
"(",
"node",
",",
"c",
")",
"\n",
"case",
"*",
"ast",
".",
"AssignStmt",
":",
"return",
"resolveAssign",
"(",
"node",
",",
"c",
")",
"\n",
"case",
"*",
"ast",
".",
"CallExpr",
":",
"return",
"resolveCallExpr",
"(",
"node",
",",
"c",
")",
"\n",
"case",
"*",
"ast",
".",
"BinaryExpr",
":",
"return",
"resolveBinExpr",
"(",
"node",
",",
"c",
")",
"\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",
"start",
",",
"end",
":=",
"fobj",
".",
"Line",
"(",
"node",
".",
"Pos",
"(",
")",
")",
",",
"fobj",
".",
"Line",
"(",
"node",
".",
"End",
"(",
")",
")",
"\n",
"line",
":=",
"strconv",
".",
"Itoa",
"(",
"start",
")",
"\n",
"if",
"start",
"!=",
"end",
"{",
"line",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%d-%d\"",
",",
"start",
",",
"end",
")",
"\n",
"}",
"\n",
"if",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fobj",
".",
"Name",
"(",
")",
")",
";",
"err",
"==",
"nil",
"{",
"defer",
"file",
".",
"Close",
"(",
")",
"\n",
"s",
":=",
"(",
"int64",
")",
"(",
"fobj",
".",
"Position",
"(",
"node",
".",
"Pos",
"(",
")",
")",
".",
"Offset",
")",
"\n",
"e",
":=",
"(",
"int64",
")",
"(",
"fobj",
".",
"Position",
"(",
"node",
".",
"End",
"(",
")",
")",
".",
"Offset",
")",
"\n",
"code",
",",
"err",
"=",
"codeSnippet",
"(",
"file",
",",
"s",
",",
"e",
",",
"node",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"code",
"=",
"err",
".",
"Error",
"(",
")",
"\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",
",",
"\"[gosec]\"",
",",
"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",
"(",
"\"parsing errors in pkg %q: %v\"",
",",
"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",
"(",
"\"parsing line: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"column",
"int",
"\n",
"if",
"len",
"(",
"parts",
")",
">",
"2",
"{",
"if",
"column",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"parts",
"[",
"2",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"parsing column: %v\"",
",",
"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",
")",
"{",
"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",
"n",
"==",
"nil",
"{",
"if",
"len",
"(",
"gosec",
".",
"context",
".",
"Ignores",
")",
">",
"0",
"{",
"gosec",
".",
"context",
".",
"Ignores",
"=",
"gosec",
".",
"context",
".",
"Ignores",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"gosec",
"\n",
"}",
"\n",
"ignoredRules",
",",
"ignoreAll",
":=",
"gosec",
".",
"ignore",
"(",
"n",
")",
"\n",
"if",
"ignoreAll",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"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",
"for",
"_",
",",
"v",
":=",
"range",
"ignoredRules",
"{",
"ignores",
"[",
"v",
"]",
"=",
"true",
"\n",
"}",
"\n",
"gosec",
".",
"context",
".",
"Ignores",
"=",
"append",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"bool",
"{",
"ignores",
"}",
",",
"gosec",
".",
"context",
".",
"Ignores",
"...",
")",
"\n",
"gosec",
".",
"context",
".",
"Imports",
".",
"TrackImport",
"(",
"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",
"(",
"\"Rule error: %v => %s (%s:%d)\\n\"",
",",
"\\n",
",",
"reflect",
".",
"TypeOf",
"(",
"rule",
")",
",",
"err",
",",
"file",
")",
"\n",
"}",
"\n",
"line",
"\n",
"}",
"\n",
"if",
"issue",
"!=",
"nil",
"{",
"gosec",
".",
"issues",
"=",
"append",
"(",
"gosec",
".",
"issues",
",",
"issue",
")",
"\n",
"gosec",
".",
"stats",
".",
"NumFound",
"++",
"\n",
"}",
"\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",
"+",
"\"/proxies\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusOK",
",",
"\"Proxies\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"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",
")",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"client",
".",
"endpoint",
"+",
"\"/proxies/\"",
"+",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusOK",
",",
"\"Proxy\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"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",
"resp",
",",
"err",
":=",
"http",
".",
"Post",
"(",
"client",
".",
"endpoint",
"+",
"\"/populate\"",
",",
"\"application/json\"",
",",
"bytes",
".",
"NewReader",
"(",
"request",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"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",
"resp",
".",
"Body",
"=",
"ioutil",
".",
"NopCloser",
"(",
"&",
"body",
")",
"\n",
"err",
"=",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusCreated",
",",
"\"Populate\"",
")",
"\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",
"var",
"resp",
"*",
"http",
".",
"Response",
"\n",
"if",
"proxy",
".",
"created",
"{",
"resp",
",",
"err",
"=",
"http",
".",
"Post",
"(",
"proxy",
".",
"client",
".",
"endpoint",
"+",
"\"/proxies/\"",
"+",
"proxy",
".",
"Name",
",",
"\"text/plain\"",
",",
"bytes",
".",
"NewReader",
"(",
"request",
")",
")",
"\n",
"}",
"else",
"{",
"resp",
",",
"err",
"=",
"http",
".",
"Post",
"(",
"proxy",
".",
"client",
".",
"endpoint",
"+",
"\"/proxies\"",
",",
"\"application/json\"",
",",
"bytes",
".",
"NewReader",
"(",
"request",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"proxy",
".",
"created",
"{",
"err",
"=",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusOK",
",",
"\"Save\"",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusCreated",
",",
"\"Create\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"proxy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"proxy",
".",
"created",
"=",
"true",
"\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",
"+",
"\"/proxies/\"",
"+",
"proxy",
".",
"Name",
"+",
"\"/toxics\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusOK",
",",
"\"Toxics\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"toxics",
":=",
"make",
"(",
"Toxics",
",",
"0",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"toxics",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\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",
"+",
"\"/reset\"",
",",
"\"text/plain\"",
",",
"bytes",
".",
"NewReader",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"checkError",
"(",
"resp",
",",
"http",
".",
"StatusNoContent",
",",
"\"ResetState\"",
")",
"\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",
"{",
"\"name\"",
":",
"link",
".",
"proxy",
".",
"Name",
",",
"\"bytes\"",
":",
"bytes",
",",
"\"err\"",
":",
"err",
",",
"}",
")",
".",
"Warn",
"(",
"\"Source terminated\"",
")",
"\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",
"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",
"{",
"\"name\"",
":",
"link",
".",
"proxy",
".",
"Name",
",",
"\"bytes\"",
":",
"bytes",
",",
"\"err\"",
":",
"err",
",",
"}",
")",
".",
"Warn",
"(",
"\"Destination terminated\"",
")",
"\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",
"newin",
":=",
"make",
"(",
"chan",
"*",
"stream",
".",
"StreamChunk",
",",
"toxic",
".",
"BufferSize",
")",
"\n",
"link",
".",
"stubs",
"=",
"append",
"(",
"link",
".",
"stubs",
",",
"toxics",
".",
"NewToxicStub",
"(",
"newin",
",",
"link",
".",
"stubs",
"[",
"i",
"-",
"1",
"]",
".",
"Output",
")",
")",
"\n",
"if",
"link",
".",
"stubs",
"[",
"i",
"-",
"1",
"]",
".",
"InterruptToxic",
"(",
")",
"{",
"link",
".",
"stubs",
"[",
"i",
"-",
"1",
"]",
".",
"Output",
"=",
"newin",
"\n",
"if",
"stateful",
",",
"ok",
":=",
"toxic",
".",
"Toxic",
".",
"(",
"toxics",
".",
"StatefulToxic",
")",
";",
"ok",
"{",
"link",
".",
"stubs",
"[",
"i",
"]",
".",
"State",
"=",
"stateful",
".",
"NewState",
"(",
")",
"\n",
"}",
"\n",
"go",
"link",
".",
"stubs",
"[",
"i",
"]",
".",
"Run",
"(",
"toxic",
")",
"\n",
"go",
"link",
".",
"stubs",
"[",
"i",
"-",
"1",
"]",
".",
"Run",
"(",
"link",
".",
"toxics",
".",
"chain",
"[",
"link",
".",
"direction",
"]",
"[",
"i",
"-",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"link",
".",
"stubs",
"[",
"i",
"]",
".",
"Output",
"=",
"newin",
"\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",
"if",
"link",
".",
"stubs",
"[",
"i",
"]",
".",
"InterruptToxic",
"(",
")",
"{",
"cleanup",
",",
"ok",
":=",
"toxic",
".",
"Toxic",
".",
"(",
"toxics",
".",
"CleanupToxic",
")",
"\n",
"if",
"ok",
"{",
"cleanup",
".",
"Cleanup",
"(",
"link",
".",
"stubs",
"[",
"i",
"]",
")",
"\n",
"if",
"link",
".",
"stubs",
"[",
"i",
"]",
".",
"Closed",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"stop",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"stop",
"<-",
"link",
".",
"stubs",
"[",
"i",
"-",
"1",
"]",
".",
"InterruptToxic",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"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",
"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",
"link",
".",
"stubs",
"[",
"i",
"-",
"1",
"]",
".",
"Output",
"=",
"link",
".",
"stubs",
"[",
"i",
"]",
".",
"Output",
"\n",
"link",
".",
"stubs",
"=",
"append",
"(",
"link",
".",
"stubs",
"[",
":",
"i",
"]",
",",
"link",
".",
"stubs",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\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",
"\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",
"{",
"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",
"(",
"\"tcp\"",
",",
"proxy",
".",
"Listen",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"proxy",
".",
"started",
"<-",
"err",
"\n",
"return",
"\n",
"}",
"\n",
"proxy",
".",
"Listen",
"=",
"ln",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"proxy",
".",
"started",
"<-",
"nil",
"\n",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"name\"",
":",
"proxy",
".",
"Name",
",",
"\"proxy\"",
":",
"proxy",
".",
"Listen",
",",
"\"upstream\"",
":",
"proxy",
".",
"Upstream",
",",
"}",
")",
".",
"Info",
"(",
"\"Started proxy\"",
")",
"\n",
"acceptTomb",
":=",
"tomb",
".",
"Tomb",
"{",
"}",
"\n",
"defer",
"acceptTomb",
".",
"Done",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"<-",
"proxy",
".",
"tomb",
".",
"Dying",
"(",
")",
"\n",
"acceptTomb",
".",
"Killf",
"(",
"\"Shutting down from stop()\"",
")",
"\n",
"err",
":=",
"ln",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"proxy\"",
":",
"proxy",
".",
"Name",
",",
"\"listen\"",
":",
"proxy",
".",
"Listen",
",",
"\"err\"",
":",
"err",
",",
"}",
")",
".",
"Warn",
"(",
"\"Attempted to close an already closed proxy server\"",
")",
"\n",
"}",
"\n",
"acceptTomb",
".",
"Wait",
"(",
")",
"\n",
"proxy",
".",
"tomb",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"for",
"{",
"client",
",",
"err",
":=",
"ln",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"select",
"{",
"case",
"<-",
"acceptTomb",
".",
"Dying",
"(",
")",
":",
"default",
":",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"proxy\"",
":",
"proxy",
".",
"Name",
",",
"\"listen\"",
":",
"proxy",
".",
"Listen",
",",
"\"err\"",
":",
"err",
",",
"}",
")",
".",
"Warn",
"(",
"\"Error while accepting client\"",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"name\"",
":",
"proxy",
".",
"Name",
",",
"\"client\"",
":",
"client",
".",
"RemoteAddr",
"(",
")",
",",
"\"proxy\"",
":",
"proxy",
".",
"Listen",
",",
"\"upstream\"",
":",
"proxy",
".",
"Upstream",
",",
"}",
")",
".",
"Info",
"(",
"\"Accepted client\"",
")",
"\n",
"upstream",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"tcp\"",
",",
"proxy",
".",
"Upstream",
")",
"\n",
"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\"",
")",
"\n",
"client",
".",
"Close",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"name",
":=",
"client",
".",
"RemoteAddr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"proxy",
".",
"connections",
".",
"Lock",
"(",
")",
"\n",
"proxy",
".",
"connections",
".",
"list",
"[",
"name",
"+",
"\"upstream\"",
"]",
"=",
"upstream",
"\n",
"proxy",
".",
"connections",
".",
"list",
"[",
"name",
"+",
"\"downstream\"",
"]",
"=",
"client",
"\n",
"proxy",
".",
"connections",
".",
"Unlock",
"(",
")",
"\n",
"proxy",
".",
"Toxics",
".",
"StartLink",
"(",
"name",
"+",
"\"upstream\"",
",",
"client",
",",
"upstream",
",",
"stream",
".",
"Upstream",
")",
"\n",
"proxy",
".",
"Toxics",
".",
"StartLink",
"(",
"name",
"+",
"\"downstream\"",
",",
"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",
"proxy",
".",
"tomb",
"=",
"tomb",
".",
"Tomb",
"{",
"}",
"\n",
"go",
"proxy",
".",
"server",
"(",
")",
"\n",
"err",
":=",
"<-",
"proxy",
".",
"started",
"\n",
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.