-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
bodyclose.go
354 lines (318 loc) · 7.54 KB
/
bodyclose.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package bodyclose
import (
"fmt"
"go/ast"
"go/types"
"strconv"
"strings"
"github.com/gostaticanalysis/analysisutil"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/buildssa"
"golang.org/x/tools/go/ssa"
)
var Analyzer = &analysis.Analyzer{
Name: "bodyclose",
Doc: Doc,
Run: new(runner).run,
Requires: []*analysis.Analyzer{
buildssa.Analyzer,
},
}
const (
Doc = "bodyclose checks whether HTTP response body is closed successfully"
nethttpPath = "net/http"
closeMethod = "Close"
)
type runner struct {
pass *analysis.Pass
resObj types.Object
resTyp *types.Pointer
bodyObj types.Object
closeMthd *types.Func
skipFile map[*ast.File]bool
}
// run executes an analysis for the pass. The receiver is passed
// by value because this func is called in parallel for different passes.
func (r runner) run(pass *analysis.Pass) (interface{}, error) {
r.pass = pass
funcs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs
r.resObj = analysisutil.LookupFromImports(pass.Pkg.Imports(), nethttpPath, "Response")
if r.resObj == nil {
// skip checking
return nil, nil
}
resNamed, ok := r.resObj.Type().(*types.Named)
if !ok {
return nil, fmt.Errorf("cannot find http.Response")
}
r.resTyp = types.NewPointer(resNamed)
resStruct, ok := r.resObj.Type().Underlying().(*types.Struct)
if !ok {
return nil, fmt.Errorf("cannot find http.Response")
}
for i := 0; i < resStruct.NumFields(); i++ {
field := resStruct.Field(i)
if field.Id() == "Body" {
r.bodyObj = field
}
}
if r.bodyObj == nil {
return nil, fmt.Errorf("cannot find the object http.Response.Body")
}
bodyNamed := r.bodyObj.Type().(*types.Named)
bodyItrf := bodyNamed.Underlying().(*types.Interface)
for i := 0; i < bodyItrf.NumMethods(); i++ {
bmthd := bodyItrf.Method(i)
if bmthd.Id() == closeMethod {
r.closeMthd = bmthd
}
}
r.skipFile = map[*ast.File]bool{}
for _, f := range funcs {
if r.noImportedNetHTTP(f) {
// skip this
continue
}
// skip if the function is just referenced
var isreffunc bool
for i := 0; i < f.Signature.Results().Len(); i++ {
if f.Signature.Results().At(i).Type().String() == r.resTyp.String() {
isreffunc = true
}
}
if isreffunc {
continue
}
for _, b := range f.Blocks {
for i := range b.Instrs {
pos := b.Instrs[i].Pos()
if r.isopen(b, i) {
pass.Reportf(pos, "response body must be closed")
}
}
}
}
return nil, nil
}
func (r *runner) isopen(b *ssa.BasicBlock, i int) bool {
call, ok := r.getReqCall(b.Instrs[i])
if !ok {
return false
}
if len(*call.Referrers()) == 0 {
return true
}
cRefs := *call.Referrers()
for _, cRef := range cRefs {
val, ok := r.getResVal(cRef)
if !ok {
continue
}
if len(*val.Referrers()) == 0 {
return true
}
resRefs := *val.Referrers()
for _, resRef := range resRefs {
switch resRef := resRef.(type) {
case *ssa.Store: // Call in Closure function
if len(*resRef.Addr.Referrers()) == 0 {
return true
}
for _, aref := range *resRef.Addr.Referrers() {
if c, ok := aref.(*ssa.MakeClosure); ok {
f := c.Fn.(*ssa.Function)
if r.noImportedNetHTTP(f) {
// skip this
return false
}
called := r.isClosureCalled(c)
return r.calledInFunc(f, called)
}
}
case *ssa.Call: // Indirect function call
if f, ok := resRef.Call.Value.(*ssa.Function); ok {
for _, b := range f.Blocks {
for i := range b.Instrs {
return r.isopen(b, i)
}
}
}
case *ssa.FieldAddr: // Normal reference to response entity
if resRef.Referrers() == nil {
return true
}
bRefs := *resRef.Referrers()
for _, bRef := range bRefs {
bOp, ok := r.getBodyOp(bRef)
if !ok {
continue
}
if len(*bOp.Referrers()) == 0 {
return true
}
ccalls := *bOp.Referrers()
for _, ccall := range ccalls {
if r.isCloseCall(ccall) {
return false
}
}
}
}
}
}
return true
}
func (r *runner) getReqCall(instr ssa.Instruction) (*ssa.Call, bool) {
call, ok := instr.(*ssa.Call)
if !ok {
return nil, false
}
if !strings.Contains(call.Type().String(), r.resTyp.String()) {
return nil, false
}
return call, true
}
func (r *runner) getResVal(instr ssa.Instruction) (ssa.Value, bool) {
switch instr := instr.(type) {
case *ssa.FieldAddr:
if instr.X.Type().String() == r.resTyp.String() {
return instr.X.(ssa.Value), true
}
case ssa.Value:
if instr.Type().String() == r.resTyp.String() {
return instr, true
}
}
return nil, false
}
func (r *runner) getBodyOp(instr ssa.Instruction) (*ssa.UnOp, bool) {
op, ok := instr.(*ssa.UnOp)
if !ok {
return nil, false
}
if op.Type() != r.bodyObj.Type() {
return nil, false
}
return op, true
}
func (r *runner) isCloseCall(ccall ssa.Instruction) bool {
switch ccall := ccall.(type) {
case *ssa.Defer:
if ccall.Call.Method.Name() == r.closeMthd.Name() {
return true
}
case *ssa.Call:
if ccall.Call.Method != nil && ccall.Call.Method.Name() == r.closeMthd.Name() {
return true
}
case *ssa.ChangeInterface:
if ccall.Type().String() == "io.Closer" {
closeMtd := ccall.Type().Underlying().(*types.Interface).Method(0)
crs := *ccall.Referrers()
for _, cs := range crs {
if cs, ok := cs.(*ssa.Defer); ok {
if val, ok := cs.Common().Value.(*ssa.Function); ok {
for _, b := range val.Blocks {
for _, instr := range b.Instrs {
if c, ok := instr.(*ssa.Call); ok {
if c.Call.Method == closeMtd {
return true
}
}
}
}
}
}
}
}
}
return false
}
func (r *runner) isClosureCalled(c *ssa.MakeClosure) bool {
refs := *c.Referrers()
if len(refs) == 0 {
return false
}
for _, ref := range refs {
switch ref.(type) {
case *ssa.Call, *ssa.Defer:
return true
}
}
return false
}
func (r *runner) noImportedNetHTTP(f *ssa.Function) (ret bool) {
obj := f.Object()
if obj == nil {
return false
}
file := analysisutil.File(r.pass, obj.Pos())
if file == nil {
return false
}
if skip, has := r.skipFile[file]; has {
return skip
}
defer func() {
r.skipFile[file] = ret
}()
for _, impt := range file.Imports {
path, err := strconv.Unquote(impt.Path.Value)
if err != nil {
continue
}
path = analysisutil.RemoveVendor(path)
if path == nethttpPath {
return false
}
}
return true
}
func (r *runner) calledInFunc(f *ssa.Function, called bool) bool {
for _, b := range f.Blocks {
for i, instr := range b.Instrs {
switch instr := instr.(type) {
case *ssa.UnOp:
refs := *instr.Referrers()
if len(refs) == 0 {
return true
}
for _, r := range refs {
if v, ok := r.(ssa.Value); ok {
if ptr, ok := v.Type().(*types.Pointer); !ok || !isNamedType(ptr.Elem(), "io", "ReadCloser") {
return true
}
vrefs := *v.Referrers()
for _, vref := range vrefs {
if vref, ok := vref.(*ssa.UnOp); ok {
vrefs := *vref.Referrers()
if len(vrefs) == 0 {
return true
}
for _, vref := range vrefs {
if c, ok := vref.(*ssa.Call); ok {
if c.Call.Method.Name() == closeMethod {
return !called
}
}
}
}
}
}
}
default:
return r.isopen(b, i) || !called
}
}
}
return false
}
// isNamedType reports whether t is the named type path.name.
func isNamedType(t types.Type, path, name string) bool {
n, ok := t.(*types.Named)
if !ok {
return false
}
obj := n.Obj()
return obj.Name() == name && obj.Pkg() != nil && obj.Pkg().Path() == path
}