David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | //+build go1.7 |
| 5 | |
| 6 | package utils |
| 7 | |
| 8 | import ( |
| 9 | "context" |
| 10 | "fmt" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | var ctxtDialer = &net.Dialer{ |
| 17 | Timeout: 30 * time.Second, |
| 18 | KeepAlive: 30 * time.Second, |
| 19 | } |
| 20 | |
| 21 | // installHTTPDialShim patches the default HTTP transport so |
| 22 | // that it fails when an attempt is made to dial a non-local |
| 23 | // host. |
| 24 | // |
| 25 | // Note that this is Go version dependent because in Go 1.7 and above, |
| 26 | // the DialContext field was introduced (and set in http.DefaultTransport) |
| 27 | // which overrides the Dial field. |
| 28 | func installHTTPDialShim(t *http.Transport) { |
| 29 | t.DialContext = func(ctxt context.Context, network, addr string) (net.Conn, error) { |
| 30 | if !OutgoingAccessAllowed && !isLocalAddr(addr) { |
| 31 | return nil, fmt.Errorf("access to address %q not allowed", addr) |
| 32 | } |
| 33 | return ctxtDialer.DialContext(ctxt, network, addr) |
| 34 | } |
| 35 | } |