Debian Codegraph @

go/analysis/passes/hostport/hostport.go

raw symbols SCIP
1 // Copyright 2024 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package hostport defines an analyzer for calls to net.Dial with
6 // addresses of the form "%s:%d" or "%s:%s", which work only with IPv4.
7 package hostport
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/token"
14 "go/types"
15 "strconv"
16
17 "golang.org/x/tools/go/analysis"
18 "golang.org/x/tools/go/analysis/passes/inspect"
19 "golang.org/x/tools/go/types/typeutil"
20 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
21 "golang.org/x/tools/internal/typesinternal/typeindex"
22 )
23
24 const Doc = `check format of addresses passed to net.Dial
25
26 This analyzer flags code that produce network address strings using
27 fmt.Sprintf, as in this example:
28
29 addr := fmt.Sprintf("%s:%d", host, 12345) // "will not work with IPv6"
30 ...
31 conn, err := net.Dial("tcp", addr) // "when passed to dial here"
32
33 The analyzer suggests a fix to use the correct approach, a call to
34 net.JoinHostPort:
35
36 addr := net.JoinHostPort(host, "12345")
37 ...
38 conn, err := net.Dial("tcp", addr)
39
40 A similar diagnostic and fix are produced for a format string of "%s:%s".
41 `
42
43 var Analyzer = &analysis.Analyzer{
44 Name: "hostport",
45 Doc: Doc,
46 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/hostport",
47 Requires: []*analysis.Analyzer{inspect.Analyzer, typeindexanalyzer.Analyzer},
48 Run: run,
49 }
50
51 func run(pass *analysis.Pass) (any, error) {
52 var (
53 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
54 info = pass.TypesInfo
55 fmtSprintf = index.Object("fmt", "Sprintf")
56 )
57 if !index.Used(fmtSprintf) {
58 return nil, nil // fast path: package doesn't use fmt.Sprintf
59 }
60
61 // checkAddr reports a diagnostic (and returns true) if e
62 // is a call of the form fmt.Sprintf("%s:%d", ...).
63 // The diagnostic includes a fix.
64 //
65 // dialCall is non-nil if the Dial call is non-local
66 // but within the same file.
67 checkAddr := func(e ast.Expr, dialCall *ast.CallExpr) {
68 if call, ok := e.(*ast.CallExpr); ok &&
69 len(call.Args) == 3 &&
70 typeutil.Callee(info, call) == fmtSprintf {
71
72 // Examine format string.
73 formatArg := call.Args[0]
74 if tv := info.Types[formatArg]; tv.Value != nil {
75 numericPort := false
76 format := constant.StringVal(tv.Value)
77 switch format {
78 case "%s:%d":
79 // Have: fmt.Sprintf("%s:%d", host, port)
80 numericPort = true
81
82 case "%s:%s":
83 // Have: fmt.Sprintf("%s:%s", host, portStr)
84 // Keep port string as is.
85
86 default:
87 return
88 }
89
90 // Use granular edits to preserve original formatting.
91 edits := []analysis.TextEdit{
92 {
93 // Replace fmt.Sprintf with net.JoinHostPort.
94 Pos: call.Fun.Pos(),
95 End: call.Fun.End(),
96 NewText: []byte("net.JoinHostPort"),
97 },
98 {
99 // Delete format string.
100 Pos: formatArg.Pos(),
101 End: call.Args[1].Pos(),
102 },
103 }
104
105 // Turn numeric port into a string.
106 if numericPort {
107 port := call.Args[2]
108
109 // Is port an integer literal?
110 //
111 // (Don't allow arbitrary constants k otherwise the
112 // transformation k => fmt.Sprintf("%d", "123")
113 // loses the symbolic connection to k.)
114 var kPort int64 = -1
115 if lit, ok := port.(*ast.BasicLit); ok && lit.Kind == token.INT {
116 if v, err := strconv.ParseInt(lit.Value, 0, 64); err == nil {
117 kPort = v
118 }
119 }
120 if kPort >= 0 {
121 // literal: 0x7B => "123"
122 edits = append(edits, analysis.TextEdit{
123 Pos: port.Pos(),
124 End: port.End(),
125 NewText: fmt.Appendf(nil, `"%d"`, kPort), // (decimal)
126 })
127 } else {
128 // non-literal: port => fmt.Sprintf("%d", port)
129 edits = append(edits, []analysis.TextEdit{
130 {
131 Pos: port.Pos(),
132 End: port.Pos(),
133 NewText: []byte(`fmt.Sprintf("%d", `),
134 },
135 {
136 Pos: port.End(),
137 End: port.End(),
138 NewText: []byte(`)`),
139 },
140 }...)
141 }
142 }
143
144 // Refer to Dial call, if not adjacent.
145 suffix := ""
146 if dialCall != nil {
147 suffix = fmt.Sprintf(" (passed to net.Dial at L%d)",
148 pass.Fset.Position(dialCall.Pos()).Line)
149 }
150
151 pass.Report(analysis.Diagnostic{
152 // Highlight the format string.
153 Pos: formatArg.Pos(),
154 End: formatArg.End(),
155 Message: fmt.Sprintf("address format %q does not work with IPv6%s", format, suffix),
156 SuggestedFixes: []analysis.SuggestedFix{{
157 Message: "Replace fmt.Sprintf with net.JoinHostPort",
158 TextEdits: edits,
159 }},
160 })
161 }
162 }
163 }
164
165 // Check address argument of each call to net.Dial et al.
166 for _, callee := range []types.Object{
167 index.Object("net", "Dial"),
168 index.Object("net", "DialTimeout"),
169 index.Selection("net", "Dialer", "Dial"),
170 } {
171 for curCall := range index.Calls(callee) {
172 call := curCall.Node().(*ast.CallExpr)
173 switch address := call.Args[1].(type) {
174 case *ast.CallExpr:
175 if len(call.Args) == 2 { // avoid spread-call edge case
176 // net.Dial("tcp", fmt.Sprintf("%s:%d", ...))
177 checkAddr(address, nil)
178 }
179
180 case *ast.Ident:
181 // addr := fmt.Sprintf("%s:%d", ...)
182 // ...
183 // net.Dial("tcp", addr)
184
185 // Search for decl of addrVar within common ancestor of addrVar and Dial call.
186 // TODO(adonovan): abstract "find RHS of statement that assigns var v".
187 // TODO(adonovan): reject if there are other assignments to var v.
188 if addrVar, ok := info.Uses[address].(*types.Var); ok {
189 if curId, ok := index.Def(addrVar); ok {
190 // curIdent is the declaring ast.Ident of addr.
191 switch parent := curId.Parent().Node().(type) {
192 case *ast.AssignStmt:
193 if len(parent.Rhs) == 1 {
194 // Have: addr := fmt.Sprintf("%s:%d", ...)
195 checkAddr(parent.Rhs[0], call)
196 }
197
198 case *ast.ValueSpec:
199 if len(parent.Values) == 1 {
200 // Have: var addr = fmt.Sprintf("%s:%d", ...)
201 checkAddr(parent.Values[0], call)
202 }
203 }
204 }
205 }
206 }
207 }
208 }
209 return nil, nil
210 }