github.com/rajeev159/opa@v0.45.0/topdown/net.go (about) 1 // Copyright 2021 The OPA Authors. All rights reserved. 2 // Use of this source code is governed by an Apache2 3 // license that can be found in the LICENSE file. 4 5 package topdown 6 7 import ( 8 "net" 9 "strings" 10 11 "github.com/open-policy-agent/opa/ast" 12 "github.com/open-policy-agent/opa/topdown/builtins" 13 ) 14 15 type lookupIPAddrCacheKey string 16 17 // resolv is the same as net.DefaultResolver -- this is for mocking it out in tests 18 var resolv = &net.Resolver{} 19 20 func builtinLookupIPAddr(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { 21 a, err := builtins.StringOperand(operands[0].Value, 1) 22 if err != nil { 23 return err 24 } 25 name := string(a) 26 27 err = verifyHost(bctx, name) 28 if err != nil { 29 return err 30 } 31 32 key := lookupIPAddrCacheKey(name) 33 if val, ok := bctx.Cache.Get(key); ok { 34 return iter(val.(*ast.Term)) 35 } 36 37 addrs, err := resolv.LookupIPAddr(bctx.Context, name) 38 if err != nil { 39 // NOTE(sr): We can't do better than this right now, see https://github.com/golang/go/issues/36208 40 if strings.Contains(err.Error(), "operation was canceled") || strings.Contains(err.Error(), "i/o timeout") { 41 return Halt{ 42 Err: &Error{ 43 Code: CancelErr, 44 Message: ast.NetLookupIPAddr.Name + ": " + err.Error(), 45 Location: bctx.Location, 46 }, 47 } 48 } 49 return err 50 } 51 52 ret := ast.NewSet() 53 for _, a := range addrs { 54 ret.Add(ast.StringTerm(a.String())) 55 56 } 57 t := ast.NewTerm(ret) 58 bctx.Cache.Put(key, t) 59 return iter(t) 60 } 61 62 func init() { 63 RegisterBuiltinFunc(ast.NetLookupIPAddr.Name, builtinLookupIPAddr) 64 }