github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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/ethereum/go-ethereum/log" 29 "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) //외부 공인 IP를 가져옴 47 //LocalIP() (net.IP, error) // local IP for development, 192.168.0.2 48 49 // Should return name of the method. This is used for logging. 50 String() string 51 } 52 53 // Parse parses a NAT interface description. 54 // The following formats are currently accepted. 55 // Note that mechanism names are not case-sensitive. 56 // 57 // "" or "none" return nil 58 // "extip:77.12.33.4" will assume the local machine is reachable on the given IP 59 // "any" uses the first auto-detected mechanism 60 // "upnp" uses the Universal Plug and Play protocol 61 // "pmp" uses NAT-PMP with an auto-detected gateway address 62 // "pmp:192.168.0.1" uses NAT-PMP with the given gateway address 63 func Parse(spec string) (Interface, error) { 64 var ( 65 parts = strings.SplitN(spec, ":", 2) 66 mech = strings.ToLower(parts[0]) 67 ip net.IP 68 ) 69 if len(parts) > 1 { 70 ip = net.ParseIP(parts[1]) 71 if ip == nil { 72 return nil, errors.New("invalid IP address") 73 } 74 } 75 switch mech { 76 case "", "none", "off": 77 return nil, nil 78 case "any", "auto", "on": 79 return Any(), nil 80 case "extip", "ip": 81 if ip == nil { 82 return nil, errors.New("missing IP address") 83 } 84 return ExtIP(ip), nil //중요 85 case "upnp": 86 return UPnP(), nil 87 case "pmp", "natpmp", "nat-pmp": 88 return PMP(ip), nil 89 90 case "local": 91 if ip == nil { 92 return nil, errors.New("missing IP address") 93 } 94 return ExtIP(ip), nil //중요 95 96 default: 97 return nil, fmt.Errorf("unknown mechanism %q", parts[0]) 98 } 99 } 100 101 const ( 102 mapTimeout = 20 * time.Minute 103 mapUpdateInterval = 15 * time.Minute 104 ) 105 106 // Map adds a port mapping on m and keeps it alive until c is closed. 107 // This function is typically invoked in its own goroutine. 108 func Map(m Interface, c chan struct{}, protocol string, extport, intport int, name string) { 109 log := log.New("proto", protocol, "extport", extport, "intport", intport, "interface", m) 110 refresh := time.NewTimer(mapUpdateInterval) 111 defer func() { 112 refresh.Stop() 113 log.Debug("Deleting port mapping") 114 m.DeleteMapping(protocol, extport, intport) 115 }() 116 if err := m.AddMapping(protocol, extport, intport, name, mapTimeout); err != nil { 117 log.Debug("Couldn't add port mapping", "err", err) 118 } else { 119 log.Info("Mapped network port") 120 } 121 for { 122 select { 123 case _, ok := <-c: 124 if !ok { 125 return 126 } 127 case <-refresh.C: 128 log.Trace("Refreshing port mapping") 129 if err := m.AddMapping(protocol, extport, intport, name, mapTimeout); err != nil { 130 log.Debug("Couldn't add port mapping", "err", err) 131 } 132 refresh.Reset(mapUpdateInterval) 133 } 134 } 135 } 136 137 // ExtIP assumes that the local machine is reachable on the given 138 // external IP address, and that any required ports were mapped manually. 139 // Mapping operations will not return an error but won't actually do anything. 140 func ExtIP(ip net.IP) Interface { 141 if ip == nil { 142 panic("IP must not be nil") 143 } 144 return extIP(ip) 145 } 146 /* 147 func LocIP(ip net.IP) Interface { 148 if ip == nil { 149 panic("IP must not be nil") 150 } 151 return locIP(ip) 152 } */ 153 154 155 type extIP net.IP 156 //type locIP net.IP // 157 158 func (n extIP) ExternalIP() (net.IP, error) { return net.IP(n), nil } 159 //func (n extIP) LocalIP() (net.IP, error) { return net.IP(n), nil } 160 func (n extIP) String() string { return fmt.Sprintf("ExtIP(%v)", net.IP(n)) } 161 162 // These do nothing. 163 func (extIP) AddMapping(string, int, int, string, time.Duration) error { return nil } 164 func (extIP) DeleteMapping(string, int, int) error { return nil } 165 166 // Any returns a port mapper that tries to discover any supported 167 // mechanism on the local network. 168 func Any() Interface { 169 // TODO: attempt to discover whether the local machine has an 170 // Internet-class address. Return ExtIP in this case. 171 return startautodisc("UPnP or NAT-PMP", func() Interface { 172 found := make(chan Interface, 2) 173 go func() { found <- discoverUPnP() }() /* gateway device search */ 174 go func() { found <- discoverPMP() }() /* run external address lookups on all potential gateways */ 175 for i := 0; i < cap(found); i++ { 176 if c := <-found; c != nil { 177 return c 178 } 179 } 180 return nil 181 }) 182 } 183 /* func Local() Interface { 184 // TODO: attempt to discover whether the local machine has an 185 c:= internaladdress() 186 return c 187 } */ 188 // UPnP returns a port mapper that uses UPnP. It will attempt to 189 // discover the address of your router using UDP broadcasts. 190 func UPnP() Interface { 191 return startautodisc("UPnP", discoverUPnP) 192 } 193 194 // PMP returns a port mapper that uses NAT-PMP. The provided gateway 195 // address should be the IP of your router. If the given gateway 196 // address is nil, PMP will attempt to auto-discover the router. 197 func PMP(gateway net.IP) Interface { 198 if gateway != nil { 199 return &pmp{gw: gateway, c: natpmp.NewClient(gateway)} 200 } 201 return startautodisc("NAT-PMP", discoverPMP) 202 } 203 204 // autodisc represents a port mapping mechanism that is still being 205 // auto-discovered. Calls to the Interface methods on this type will 206 // wait until the discovery is done and then call the method on the 207 // discovered mechanism. 208 // 209 // This type is useful because discovery can take a while but we 210 // want return an Interface value from UPnP, PMP and Auto immediately. 211 type autodisc struct { 212 what string // type of interface being autodiscovered 213 once sync.Once 214 doit func() Interface 215 216 mu sync.Mutex 217 found Interface 218 } 219 220 func startautodisc(what string, doit func() Interface) Interface { 221 // TODO: monitor network configuration and rerun doit when it changes. 222 return &autodisc{what: what, doit: doit} 223 } 224 225 func (n *autodisc) AddMapping(protocol string, extport, intport int, name string, lifetime time.Duration) error { 226 if err := n.wait(); err != nil { 227 return err 228 } 229 return n.found.AddMapping(protocol, extport, intport, name, lifetime) 230 } 231 232 func (n *autodisc) DeleteMapping(protocol string, extport, intport int) error { 233 if err := n.wait(); err != nil { 234 return err 235 } 236 return n.found.DeleteMapping(protocol, extport, intport) 237 } 238 239 func (n *autodisc) ExternalIP() (net.IP, error) { 240 if err := n.wait(); err != nil { 241 return nil, err 242 } 243 return n.found.ExternalIP() 244 } 245 246 func (n *autodisc) String() string { 247 n.mu.Lock() 248 defer n.mu.Unlock() 249 if n.found == nil { 250 return n.what 251 } else { 252 return n.found.String() 253 } 254 } 255 256 // wait blocks until auto-discovery has been performed. 257 func (n *autodisc) wait() error { 258 n.once.Do(func() { 259 n.mu.Lock() 260 n.found = n.doit() 261 n.mu.Unlock() 262 }) 263 if n.found == nil { 264 return fmt.Errorf("no %s router discovered", n.what) 265 } 266 return nil 267 }