blob: d676dcb41ca5a3e2ff739fb925f4cc299ca2a458 [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2016 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4//+build go1.7
5
6package utils
7
8import (
9 "context"
10 "fmt"
11 "net"
12 "net/http"
13 "time"
14)
15
16var 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.
28func 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}