|
| 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/types" |
| 14 | + |
| 15 | + "golang.org/x/tools/go/analysis" |
| 16 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 17 | + "golang.org/x/tools/go/ast/inspector" |
| 18 | + "golang.org/x/tools/go/types/typeutil" |
| 19 | + "golang.org/x/tools/gopls/internal/util/safetoken" |
| 20 | + "golang.org/x/tools/internal/analysisinternal" |
| 21 | + "golang.org/x/tools/internal/astutil/cursor" |
| 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/gopls/internal/analysis/hostport", |
| 47 | + Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 48 | + Run: run, |
| 49 | +} |
| 50 | + |
| 51 | +func run(pass *analysis.Pass) (any, error) { |
| 52 | + // Fast path: if the package doesn't import net and fmt, skip |
| 53 | + // the traversal. |
| 54 | + if !analysisinternal.Imports(pass.Pkg, "net") || |
| 55 | + !analysisinternal.Imports(pass.Pkg, "fmt") { |
| 56 | + return nil, nil |
| 57 | + } |
| 58 | + |
| 59 | + info := pass.TypesInfo |
| 60 | + |
| 61 | + // checkAddr reports a diagnostic (and returns true) if e |
| 62 | + // is a call of the form fmt.Sprintf("%d:%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 | + obj := typeutil.Callee(info, call) |
| 70 | + if analysisinternal.IsFunctionNamed(obj, "fmt", "Sprintf") { |
| 71 | + // Examine format string. |
| 72 | + formatArg := call.Args[0] |
| 73 | + if tv := info.Types[formatArg]; tv.Value != nil { |
| 74 | + numericPort := false |
| 75 | + format := constant.StringVal(tv.Value) |
| 76 | + switch format { |
| 77 | + case "%s:%d": |
| 78 | + // Have: fmt.Sprintf("%s:%d", host, port) |
| 79 | + numericPort = true |
| 80 | + |
| 81 | + case "%s:%s": |
| 82 | + // Have: fmt.Sprintf("%s:%s", host, portStr) |
| 83 | + // Keep port string as is. |
| 84 | + |
| 85 | + default: |
| 86 | + return |
| 87 | + } |
| 88 | + |
| 89 | + // Use granular edits to preserve original formatting. |
| 90 | + edits := []analysis.TextEdit{ |
| 91 | + { |
| 92 | + // Replace fmt.Sprintf with net.JoinHostPort. |
| 93 | + Pos: call.Fun.Pos(), |
| 94 | + End: call.Fun.End(), |
| 95 | + NewText: []byte("net.JoinHostPort"), |
| 96 | + }, |
| 97 | + { |
| 98 | + // Delete format string. |
| 99 | + Pos: formatArg.Pos(), |
| 100 | + End: call.Args[1].Pos(), |
| 101 | + }, |
| 102 | + } |
| 103 | + |
| 104 | + // Turn numeric port into a string. |
| 105 | + if numericPort { |
| 106 | + // port => fmt.Sprintf("%d", port) |
| 107 | + // 123 => "123" |
| 108 | + port := call.Args[2] |
| 109 | + newPort := fmt.Sprintf(`fmt.Sprintf("%%d", %s)`, port) |
| 110 | + if port := info.Types[port].Value; port != nil { |
| 111 | + if i, ok := constant.Int64Val(port); ok { |
| 112 | + newPort = fmt.Sprintf(`"%d"`, i) // numeric constant |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + edits = append(edits, analysis.TextEdit{ |
| 117 | + Pos: port.Pos(), |
| 118 | + End: port.End(), |
| 119 | + NewText: []byte(newPort), |
| 120 | + }) |
| 121 | + } |
| 122 | + |
| 123 | + // Refer to Dial call, if not adjacent. |
| 124 | + suffix := "" |
| 125 | + if dialCall != nil { |
| 126 | + suffix = fmt.Sprintf(" (passed to net.Dial at L%d)", |
| 127 | + safetoken.StartPosition(pass.Fset, dialCall.Pos()).Line) |
| 128 | + } |
| 129 | + |
| 130 | + pass.Report(analysis.Diagnostic{ |
| 131 | + // Highlight the format string. |
| 132 | + Pos: formatArg.Pos(), |
| 133 | + End: formatArg.End(), |
| 134 | + Message: fmt.Sprintf("address format %q does not work with IPv6%s", format, suffix), |
| 135 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 136 | + Message: "Replace fmt.Sprintf with net.JoinHostPort", |
| 137 | + TextEdits: edits, |
| 138 | + }}, |
| 139 | + }) |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + // Check address argument of each call to net.Dial et al. |
| 146 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 147 | + for curCall := range cursor.Root(inspect).Preorder((*ast.CallExpr)(nil)) { |
| 148 | + call := curCall.Node().(*ast.CallExpr) |
| 149 | + |
| 150 | + obj := typeutil.Callee(info, call) |
| 151 | + if analysisinternal.IsFunctionNamed(obj, "net", "Dial", "DialTimeout") || |
| 152 | + analysisinternal.IsMethodNamed(obj, "net", "Dialer", "Dial") { |
| 153 | + |
| 154 | + switch address := call.Args[1].(type) { |
| 155 | + case *ast.CallExpr: |
| 156 | + // net.Dial("tcp", fmt.Sprintf("%s:%d", ...)) |
| 157 | + checkAddr(address, nil) |
| 158 | + |
| 159 | + case *ast.Ident: |
| 160 | + // addr := fmt.Sprintf("%s:%d", ...) |
| 161 | + // ... |
| 162 | + // net.Dial("tcp", addr) |
| 163 | + |
| 164 | + // Search for decl of addrVar within common ancestor of addrVar and Dial call. |
| 165 | + if addrVar, ok := info.Uses[address].(*types.Var); ok { |
| 166 | + pos := addrVar.Pos() |
| 167 | + // TODO(adonovan): use Cursor.Ancestors iterator when available. |
| 168 | + for _, curAncestor := range curCall.Stack(nil) { |
| 169 | + if curIdent, ok := curAncestor.FindPos(pos, pos); ok { |
| 170 | + // curIdent is the declaring ast.Ident of addr. |
| 171 | + switch parent := curIdent.Parent().Node().(type) { |
| 172 | + case *ast.AssignStmt: |
| 173 | + if len(parent.Rhs) == 1 { |
| 174 | + // Have: addr := fmt.Sprintf("%s:%d", ...) |
| 175 | + checkAddr(parent.Rhs[0], call) |
| 176 | + } |
| 177 | + |
| 178 | + case *ast.ValueSpec: |
| 179 | + if len(parent.Values) == 1 { |
| 180 | + // Have: var addr = fmt.Sprintf("%s:%d", ...) |
| 181 | + checkAddr(parent.Values[0], call) |
| 182 | + } |
| 183 | + } |
| 184 | + break |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + return nil, nil |
| 192 | +} |
0 commit comments