github.com/Gessiux/neatchain@v1.3.1/network/p2p/nat/nat.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package nat provides access to common network port mapping protocols.
    18  package nat
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"net"
    24  	"strings"
    25  	"sync"
    26  	"time"
    27  
    28  	"github.com/Gessiux/neatchain/chain/log"
    29  	natpmp "github.com/jackpal/go-nat-pmp"
    30  )
    31  
    32  // An implementation of nat.Interface can map local ports to ports
    33  // accessible from the Internet.
    34  type Interface interface {
    35  	// These methods manage a mapping between a port on the local
    36  	// machine to a port that can be connected to from the internet.
    37  	//
    38  	// protocol is "UDP" or "TCP". Some implementations allow setting
    39  	// a display name for the mapping. The mapping may be removed by
    40  	// the gateway when its lifetime ends.
    41  	AddMapping(protocol string, extport, intport int, name string, lifetime time.Duration) error
    42  	DeleteMapping(protocol string, extport, intport int) error
    43  
    44  	// This method should return the external (Internet-facing)
    45  	// address of the gateway device.
    46  	ExternalIP() (net.IP, error)
    47  
    48  	// Should return name of the method. This is used for logging.
    49  	String() string
    50  }
    51  
    52  // Parse parses a NAT interface description.
    53  // The following formats are currently accepted.
    54  // Note that mechanism names are not case-sensitive.
    55  //
    56  //     "" or "none"         return nil
    57  //     "extip:77.12.33.4"   will assume the local machine is reachable on the given IP
    58  //     "any"                uses the first auto-detected mechanism
    59  //     "upnp"               uses the Universal Plug and Play protocol
    60  //     "pmp"                uses NAT-PMP with an auto-detected gateway address
    61  //     "pmp:192.168.0.1"    uses NAT-PMP with the given gateway address
    62  func Parse(spec string) (Interface, error) {
    63  	var (
    64  		parts = strings.SplitN(spec, ":", 2)
    65  		mech  = strings.ToLower(parts[0])
    66  		ip    net.IP
    67  	)
    68  	if len(parts) > 1 {
    69  		ip = net.ParseIP(parts[1])
    70  		if ip == nil {
    71  			return nil, errors.New("invalid IP address")
    72  		}
    73  	}
    74  	switch mech {
    75  	case "", "none", "off":
    76  		return nil, nil
    77  	case "any", "auto", "on":
    78  		return Any(), nil
    79  	case "extip", "ip":
    80  		if ip == nil {
    81  			return nil, errors.New("missing IP address")
    82  		}
    83  		return ExtIP(ip), nil
    84  	case "upnp":
    85  		return UPnP(), nil
    86  	case "pmp", "natpmp", "nat-pmp":
    87  		return PMP(ip), nil
    88  	default:
    89  		return nil, fmt.Errorf("unknown mechanism %q", parts[0])
    90  	}
    91  }
    92  
    93  const (
    94  	mapTimeout        = 20 * time.Minute
    95  	mapUpdateInterval = 15 * time.Minute
    96  )
    97  
    98  // Map adds a port mapping on m and keeps it alive until c is closed.
    99  // This function is typically invoked in its own goroutine.
   100  func Map(m Interface, c chan struct{}, protocol string, extport, intport int, name string) {
   101  	log := log.New("proto", protocol, "extport", extport, "intport", intport, "interface", m)
   102  	refresh := time.NewTimer(mapUpdateInterval)
   103  	defer func() {
   104  		refresh.Stop()
   105  		log.Debug("Deleting port mapping")
   106  		m.DeleteMapping(protocol, extport, intport)
   107  	}()
   108  	if err := m.AddMapping(protocol, extport, intport, name, mapTimeout); err != nil {
   109  		log.Debug("Couldn't add port mapping", "err", err)
   110  	}
   111  	// else {
   112  	// log.Info("Mapped network port")
   113  	// }
   114  	for {
   115  		select {
   116  		case _, ok := <-c:
   117  			if !ok {
   118  				return
   119  			}
   120  		case <-refresh.C:
   121  			log.Trace("Refreshing port mapping")
   122  			if err := m.AddMapping(protocol, extport, intport, name, mapTimeout); err != nil {
   123  				log.Debug("Couldn't add port mapping", "err", err)
   124  			}
   125  			refresh.Reset(mapUpdateInterval)
   126  		}
   127  	}
   128  }
   129  
   130  // ExtIP assumes that the local machine is reachable on the given
   131  // external IP address, and that any required ports were mapped manually.
   132  // Mapping operations will not return an error but won't actually do anything.
   133  func ExtIP(ip net.IP) Interface {
   134  	if ip == nil {
   135  		panic("IP must not be nil")
   136  	}
   137  	return extIP(ip)
   138  }
   139  
   140  type extIP net.IP
   141  
   142  func (n extIP) ExternalIP() (net.IP, error) { return net.IP(n), nil }
   143  func (n extIP) String() string              { return fmt.Sprintf("ExtIP(%v)", net.IP(n)) }
   144  
   145  // These do nothing.
   146  func (extIP) AddMapping(string, int, int, string, time.Duration) error { return nil }
   147  func (extIP) DeleteMapping(string, int, int) error                     { return nil }
   148  
   149  // Any returns a port mapper that tries to discover any supported
   150  // mechanism on the local network.
   151  func Any() Interface {
   152  	// TODO: attempt to discover whether the local machine has an
   153  	// Internet-class address. Return ExtIP in this case.
   154  	return startautodisc("UPnP or NAT-PMP", func() Interface {
   155  		found := make(chan Interface, 2)
   156  		go func() { found <- discoverUPnP() }()
   157  		go func() { found <- discoverPMP() }()
   158  		for i := 0; i < cap(found); i++ {
   159  			if c := <-found; c != nil {
   160  				return c
   161  			}
   162  		}
   163  		return nil
   164  	})
   165  }
   166  
   167  // UPnP returns a port mapper that uses UPnP. It will attempt to
   168  // discover the address of your router using UDP broadcasts.
   169  func UPnP() Interface {
   170  	return startautodisc("UPnP", discoverUPnP)
   171  }
   172  
   173  // PMP returns a port mapper that uses NAT-PMP. The provided gateway
   174  // address should be the IP of your router. If the given gateway
   175  // address is nil, PMP will attempt to auto-discover the router.
   176  func PMP(gateway net.IP) Interface {
   177  	if gateway != nil {
   178  		return &pmp{gw: gateway, c: natpmp.NewClient(gateway)}
   179  	}
   180  	return startautodisc("NAT-PMP", discoverPMP)
   181  }
   182  
   183  // autodisc represents a port mapping mechanism that is still being
   184  // auto-discovered. Calls to the Interface methods on this type will
   185  // wait until the discovery is done and then call the method on the
   186  // discovered mechanism.
   187  //
   188  // This type is useful because discovery can take a while but we
   189  // want return an Interface value from UPnP, PMP and Auto immediately.
   190  type autodisc struct {
   191  	what string // type of interface being autodiscovered
   192  	once sync.Once
   193  	doit func() Interface
   194  
   195  	mu    sync.Mutex
   196  	found Interface
   197  }
   198  
   199  func startautodisc(what string, doit func() Interface) Interface {
   200  	// TODO: monitor network configuration and rerun doit when it changes.
   201  	return &autodisc{what: what, doit: doit}
   202  }
   203  
   204  func (n *autodisc) AddMapping(protocol string, extport, intport int, name string, lifetime time.Duration) error {
   205  	if err := n.wait(); err != nil {
   206  		return err
   207  	}
   208  	return n.found.AddMapping(protocol, extport, intport, name, lifetime)
   209  }
   210  
   211  func (n *autodisc) DeleteMapping(protocol string, extport, intport int) error {
   212  	if err := n.wait(); err != nil {
   213  		return err
   214  	}
   215  	return n.found.DeleteMapping(protocol, extport, intport)
   216  }
   217  
   218  func (n *autodisc) ExternalIP() (net.IP, error) {
   219  	if err := n.wait(); err != nil {
   220  		return nil, err
   221  	}
   222  	return n.found.ExternalIP()
   223  }
   224  
   225  func (n *autodisc) String() string {
   226  	n.mu.Lock()
   227  	defer n.mu.Unlock()
   228  	if n.found == nil {
   229  		return n.what
   230  	} else {
   231  		return n.found.String()
   232  	}
   233  }
   234  
   235  // wait blocks until auto-discovery has been performed.
   236  func (n *autodisc) wait() error {
   237  	n.once.Do(func() {
   238  		n.mu.Lock()
   239  		n.found = n.doit()
   240  		n.mu.Unlock()
   241  	})
   242  	if n.found == nil {
   243  		return fmt.Errorf("no %s router discovered", n.what)
   244  	}
   245  	return nil
   246  }