upnp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // Adapted from https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/IGD.go
  4. // Copyright (c) 2010 Jack Palevich (https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/LICENSE)
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. // Package upnp implements UPnP InternetGatewayDevice discovery, querying, and port mapping.
  32. package upnp
  33. import (
  34. "bufio"
  35. "bytes"
  36. "context"
  37. "encoding/xml"
  38. "errors"
  39. "fmt"
  40. "io"
  41. "net"
  42. "net/http"
  43. "net/url"
  44. "runtime"
  45. "strings"
  46. "sync"
  47. "time"
  48. "github.com/syncthing/syncthing/lib/netutil"
  49. "github.com/syncthing/syncthing/lib/build"
  50. "github.com/syncthing/syncthing/lib/dialer"
  51. "github.com/syncthing/syncthing/lib/nat"
  52. "github.com/syncthing/syncthing/lib/osutil"
  53. )
  54. func init() {
  55. nat.Register(Discover)
  56. }
  57. type upnpService struct {
  58. ID string `xml:"serviceId"`
  59. Type string `xml:"serviceType"`
  60. ControlURL string `xml:"controlURL"`
  61. }
  62. type upnpDevice struct {
  63. IsIPv6 bool
  64. DeviceType string `xml:"deviceType"`
  65. FriendlyName string `xml:"friendlyName"`
  66. Devices []upnpDevice `xml:"deviceList>device"`
  67. Services []upnpService `xml:"serviceList>service"`
  68. }
  69. type upnpRoot struct {
  70. Device upnpDevice `xml:"device"`
  71. }
  72. // UnsupportedDeviceTypeError for unsupported UPnP device types (i.e upnp:rootdevice)
  73. type UnsupportedDeviceTypeError struct {
  74. deviceType string
  75. }
  76. func (e *UnsupportedDeviceTypeError) Error() string {
  77. return fmt.Sprintf("Unsupported UPnP device of type %s", e.deviceType)
  78. }
  79. const (
  80. urnIgdV1 = "urn:schemas-upnp-org:device:InternetGatewayDevice:1"
  81. urnIgdV2 = "urn:schemas-upnp-org:device:InternetGatewayDevice:2"
  82. urnWANDeviceV1 = "urn:schemas-upnp-org:device:WANDevice:1"
  83. urnWANDeviceV2 = "urn:schemas-upnp-org:device:WANDevice:2"
  84. urnWANConnectionDeviceV1 = "urn:schemas-upnp-org:device:WANConnectionDevice:1"
  85. urnWANConnectionDeviceV2 = "urn:schemas-upnp-org:device:WANConnectionDevice:2"
  86. urnWANIPConnectionV1 = "urn:schemas-upnp-org:service:WANIPConnection:1"
  87. urnWANIPConnectionV2 = "urn:schemas-upnp-org:service:WANIPConnection:2"
  88. urnWANIPv6FirewallControlV1 = "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"
  89. urnWANPPPConnectionV1 = "urn:schemas-upnp-org:service:WANPPPConnection:1"
  90. urnWANPPPConnectionV2 = "urn:schemas-upnp-org:service:WANPPPConnection:2"
  91. )
  92. // Discover discovers UPnP InternetGatewayDevices.
  93. // The order in which the devices appear in the results list is not deterministic.
  94. func Discover(ctx context.Context, _, timeout time.Duration) []nat.Device {
  95. var results []nat.Device
  96. interfaces, err := netutil.Interfaces()
  97. if err != nil {
  98. l.Infoln("Listing network interfaces:", err)
  99. return results
  100. }
  101. resultChan := make(chan nat.Device)
  102. wg := &sync.WaitGroup{}
  103. for _, intf := range interfaces {
  104. if intf.Flags&net.FlagRunning == 0 || intf.Flags&net.FlagMulticast == 0 {
  105. continue
  106. }
  107. wg.Add(1)
  108. // Discovery is done sequentially per interface because we discovered that
  109. // FritzBox routers return a broken result sometimes if the IPv4 and IPv6
  110. // request arrive at the same time.
  111. go func(iface net.Interface) {
  112. defer wg.Done()
  113. hasGUA, err := interfaceHasGUAIPv6(iface)
  114. if err != nil {
  115. l.Debugf("Couldn't check for IPv6 GUAs on %s: %s", iface.Name, err)
  116. } else if hasGUA {
  117. // Discover IPv6 gateways on interface. Only discover IGDv2, since IGDv1
  118. // + IPv6 is not standardized and will lead to duplicates on routers.
  119. // Only do this when a non-link-local IPv6 is available. if we can't
  120. // enumerate the interface, the IPv6 code will not work anyway
  121. discover(ctx, &iface, urnIgdV2, timeout, resultChan, true)
  122. }
  123. // Discover IPv4 gateways on interface.
  124. for _, deviceType := range []string{urnIgdV2, urnIgdV1} {
  125. discover(ctx, &iface, deviceType, timeout, resultChan, false)
  126. }
  127. }(intf)
  128. }
  129. go func() {
  130. wg.Wait()
  131. close(resultChan)
  132. }()
  133. seenResults := make(map[string]bool)
  134. for {
  135. select {
  136. case result, ok := <-resultChan:
  137. if !ok {
  138. return results
  139. }
  140. if seenResults[result.ID()] {
  141. l.Debugf("Skipping duplicate result %s", result.ID())
  142. continue
  143. }
  144. results = append(results, result)
  145. seenResults[result.ID()] = true
  146. l.Debugf("UPnP discovery result %s", result.ID())
  147. case <-ctx.Done():
  148. return nil
  149. }
  150. }
  151. }
  152. // Search for UPnP InternetGatewayDevices for <timeout> seconds.
  153. // The order in which the devices appear in the result list is not deterministic
  154. func discover(ctx context.Context, intf *net.Interface, deviceType string, timeout time.Duration, results chan<- nat.Device, ip6 bool) {
  155. var ssdp net.UDPAddr
  156. var template string
  157. if ip6 {
  158. ssdp = net.UDPAddr{IP: []byte{0xFF, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C}, Port: 1900}
  159. template = `M-SEARCH * HTTP/1.1
  160. HOST: [FF05::C]:1900
  161. ST: %s
  162. MAN: "ssdp:discover"
  163. MX: %d
  164. USER-AGENT: syncthing/%s
  165. `
  166. } else {
  167. ssdp = net.UDPAddr{IP: []byte{239, 255, 255, 250}, Port: 1900}
  168. template = `M-SEARCH * HTTP/1.1
  169. HOST: 239.255.255.250:1900
  170. ST: %s
  171. MAN: "ssdp:discover"
  172. MX: %d
  173. USER-AGENT: syncthing/%s
  174. `
  175. }
  176. searchStr := fmt.Sprintf(template, deviceType, timeout/time.Second, build.Version)
  177. search := []byte(strings.ReplaceAll(searchStr, "\n", "\r\n") + "\r\n")
  178. l.Debugln("Starting discovery of device type", deviceType, "on", intf.Name)
  179. proto := "udp4"
  180. if ip6 {
  181. proto = "udp6"
  182. }
  183. socket, err := net.ListenMulticastUDP(proto, intf, &net.UDPAddr{IP: ssdp.IP})
  184. if err != nil {
  185. if runtime.GOOS == "windows" && ip6 {
  186. // Requires https://github.com/golang/go/issues/63529 to be fixed.
  187. l.Infoln("Support for IPv6 UPnP is currently not available on Windows:", err)
  188. } else {
  189. l.Debugln("UPnP discovery: listening to udp multicast:", err)
  190. }
  191. return
  192. }
  193. defer socket.Close() // Make sure our socket gets closed
  194. l.Debugln("Sending search request for device type", deviceType, "on", intf.Name)
  195. _, err = socket.WriteTo(search, &ssdp)
  196. if err != nil {
  197. if e, ok := err.(net.Error); !ok || !e.Timeout() {
  198. l.Debugln("UPnP discovery: sending search request:", err)
  199. }
  200. return
  201. }
  202. l.Debugln("Listening for UPnP response for device type", deviceType, "on", intf.Name)
  203. ctx, cancel := context.WithTimeout(ctx, timeout)
  204. defer cancel()
  205. // Listen for responses until a timeout is reached or the context is
  206. // cancelled
  207. resp := make([]byte, 65536)
  208. loop:
  209. for {
  210. if err := socket.SetDeadline(time.Now().Add(250 * time.Millisecond)); err != nil {
  211. l.Infoln("UPnP socket:", err)
  212. break
  213. }
  214. n, udpAddr, err := socket.ReadFromUDP(resp)
  215. if err != nil {
  216. select {
  217. case <-ctx.Done():
  218. break loop
  219. default:
  220. }
  221. if e, ok := err.(net.Error); ok && e.Timeout() {
  222. continue // continue reading
  223. }
  224. l.Infoln("UPnP read:", err) // legitimate error, not a timeout.
  225. break
  226. }
  227. igds, err := parseResponse(ctx, deviceType, udpAddr, resp[:n], intf)
  228. if err != nil {
  229. switch err.(type) {
  230. case *UnsupportedDeviceTypeError:
  231. l.Debugln(err.Error())
  232. default:
  233. if !errors.Is(err, context.Canceled) {
  234. l.Infoln("UPnP parse:", err)
  235. }
  236. }
  237. continue
  238. }
  239. for _, igd := range igds {
  240. igd := igd // Copy before sending pointer to the channel.
  241. select {
  242. case results <- &igd:
  243. case <-ctx.Done():
  244. return
  245. }
  246. }
  247. }
  248. l.Debugln("Discovery for device type", deviceType, "on", intf.Name, "finished.")
  249. }
  250. func parseResponse(ctx context.Context, deviceType string, addr *net.UDPAddr, resp []byte, netInterface *net.Interface) ([]IGDService, error) {
  251. l.Debugln("Handling UPnP response:\n\n" + string(resp))
  252. reader := bufio.NewReader(bytes.NewBuffer(resp))
  253. request := &http.Request{}
  254. response, err := http.ReadResponse(reader, request)
  255. if err != nil {
  256. return nil, err
  257. }
  258. respondingDeviceType := response.Header.Get("St")
  259. if respondingDeviceType != deviceType {
  260. return nil, &UnsupportedDeviceTypeError{deviceType: respondingDeviceType}
  261. }
  262. deviceDescriptionLocation := response.Header.Get("Location")
  263. if deviceDescriptionLocation == "" {
  264. return nil, errors.New("invalid IGD response: no location specified")
  265. }
  266. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  267. if err != nil {
  268. l.Infoln("Invalid IGD location: " + err.Error())
  269. return nil, err
  270. }
  271. if err != nil {
  272. l.Infoln("Invalid source IP for IGD: " + err.Error())
  273. return nil, err
  274. }
  275. deviceUSN := response.Header.Get("USN")
  276. if deviceUSN == "" {
  277. return nil, errors.New("invalid IGD response: USN not specified")
  278. }
  279. deviceIP := net.ParseIP(deviceDescriptionURL.Hostname())
  280. // If the hostname of the device parses as an IPv6 link-local address, we need
  281. // to use the source IP address of the response as the hostname
  282. // instead of the one given, since only the former contains the zone index,
  283. // while the URL returned from the gateway cannot contain the zone index.
  284. // (It can't know how interfaces are named/numbered on our machine)
  285. if deviceIP != nil && deviceIP.To4() == nil && deviceIP.IsLinkLocalUnicast() {
  286. ipAddr := net.IPAddr{
  287. IP: addr.IP,
  288. Zone: addr.Zone,
  289. }
  290. deviceDescriptionPort := deviceDescriptionURL.Port()
  291. deviceDescriptionURL.Host = "[" + ipAddr.String() + "]"
  292. if deviceDescriptionPort != "" {
  293. deviceDescriptionURL.Host += ":" + deviceDescriptionPort
  294. }
  295. deviceDescriptionLocation = deviceDescriptionURL.String()
  296. }
  297. deviceUUID := strings.TrimPrefix(strings.Split(deviceUSN, "::")[0], "uuid:")
  298. response, err = http.Get(deviceDescriptionLocation)
  299. if err != nil {
  300. return nil, err
  301. }
  302. defer response.Body.Close()
  303. if response.StatusCode >= 400 {
  304. return nil, errors.New("bad status code:" + response.Status)
  305. }
  306. var upnpRoot upnpRoot
  307. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  308. if err != nil {
  309. return nil, err
  310. }
  311. // Figure out our IPv4 address on the interface used to reach the IGD.
  312. localIPv4Address, err := localIPv4(netInterface)
  313. if err != nil {
  314. // On Android, we cannot enumerate IP addresses on interfaces directly.
  315. // Therefore, we just try to connect to the IGD and look at which source IP
  316. // address was used. This is not ideal, but it's the best we can do. Maybe
  317. // we are on an IPv6-only network though, so don't error out in case pinholing is available.
  318. localIPv4Address, err = localIPv4Fallback(ctx, deviceDescriptionURL)
  319. if err != nil {
  320. l.Infoln("Unable to determine local IPv4 address for IGD: " + err.Error())
  321. }
  322. }
  323. // This differs from IGDService.SupportsIPVersion(). While that method
  324. // determines whether an already completely discovered device uses the IPv6
  325. // firewall protocol, this just checks if the gateway's is IPv6. Currently we
  326. // only want to discover IPv6 UPnP endpoints on IPv6 gateways and vice versa,
  327. // which is why this needs to be stored but technically we could forgo this check
  328. // and try WANIPv6FirewallControl via IPv4. This leads to errors though so we don't do it.
  329. upnpRoot.Device.IsIPv6 = addr.IP.To4() == nil
  330. services, err := getServiceDescriptions(deviceUUID, localIPv4Address, deviceDescriptionLocation, upnpRoot.Device, netInterface)
  331. if err != nil {
  332. return nil, err
  333. }
  334. return services, nil
  335. }
  336. func localIPv4(netInterface *net.Interface) (net.IP, error) {
  337. addrs, err := netutil.InterfaceAddrsByInterface(netInterface)
  338. if err != nil {
  339. return nil, err
  340. }
  341. for _, addr := range addrs {
  342. ip, _, err := net.ParseCIDR(addr.String())
  343. if err != nil {
  344. continue
  345. }
  346. if ip.To4() != nil {
  347. return ip, nil
  348. }
  349. }
  350. return nil, errors.New("no IPv4 address found for interface " + netInterface.Name)
  351. }
  352. func localIPv4Fallback(ctx context.Context, url *url.URL) (net.IP, error) {
  353. timeoutCtx, cancel := context.WithTimeout(ctx, time.Second)
  354. defer cancel()
  355. conn, err := dialer.DialContext(timeoutCtx, "udp4", url.Host)
  356. if err != nil {
  357. return nil, err
  358. }
  359. defer conn.Close()
  360. ip, err := osutil.IPFromAddr(conn.LocalAddr())
  361. if err != nil {
  362. return nil, err
  363. }
  364. if ip.To4() == nil {
  365. return nil, errors.New("tried to obtain IPv4 through fallback but got IPv6 address")
  366. }
  367. return ip, nil
  368. }
  369. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  370. var result []upnpDevice
  371. for _, dev := range d.Devices {
  372. if dev.DeviceType == deviceType {
  373. result = append(result, dev)
  374. }
  375. }
  376. return result
  377. }
  378. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  379. var result []upnpService
  380. for _, service := range d.Services {
  381. if service.Type == serviceType {
  382. result = append(result, service)
  383. }
  384. }
  385. return result
  386. }
  387. func getServiceDescriptions(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice, netInterface *net.Interface) ([]IGDService, error) {
  388. var result []IGDService
  389. if device.IsIPv6 && device.DeviceType == urnIgdV1 {
  390. // IPv6 UPnP is only standardized for IGDv2. Furthermore, any WANIPConn services for IPv4 that
  391. // we may discover here are likely to be broken because many routers make the choice to not allow
  392. // port mappings for IPs differing from the source IP of the device making the request (which would be v6 here)
  393. return nil, nil
  394. } else if device.IsIPv6 && device.DeviceType == urnIgdV2 {
  395. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  396. urnWANDeviceV2,
  397. urnWANConnectionDeviceV2,
  398. []string{urnWANIPv6FirewallControlV1},
  399. netInterface)
  400. result = append(result, descriptions...)
  401. } else if device.DeviceType == urnIgdV1 {
  402. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  403. urnWANDeviceV1,
  404. urnWANConnectionDeviceV1,
  405. []string{urnWANIPConnectionV1, urnWANPPPConnectionV1},
  406. netInterface)
  407. result = append(result, descriptions...)
  408. } else if device.DeviceType == urnIgdV2 {
  409. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  410. urnWANDeviceV2,
  411. urnWANConnectionDeviceV2,
  412. []string{urnWANIPConnectionV2, urnWANPPPConnectionV2},
  413. netInterface)
  414. result = append(result, descriptions...)
  415. } else {
  416. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  417. }
  418. if len(result) < 1 {
  419. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  420. }
  421. return result, nil
  422. }
  423. func getIGDServices(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice, wanDeviceURN string, wanConnectionURN string, URNs []string, netInterface *net.Interface) []IGDService {
  424. var result []IGDService
  425. devices := getChildDevices(device, wanDeviceURN)
  426. if len(devices) < 1 {
  427. l.Infoln(rootURL, "- malformed InternetGatewayDevice description: no WANDevices specified.")
  428. return result
  429. }
  430. for _, device := range devices {
  431. connections := getChildDevices(device, wanConnectionURN)
  432. if len(connections) < 1 {
  433. l.Infoln(rootURL, "- malformed ", wanDeviceURN, "description: no WANConnectionDevices specified.")
  434. }
  435. for _, connection := range connections {
  436. for _, URN := range URNs {
  437. services := getChildServices(connection, URN)
  438. if len(services) == 0 {
  439. l.Debugln(rootURL, "- no services of type", URN, " found on connection.")
  440. }
  441. for _, service := range services {
  442. if service.ControlURL == "" {
  443. l.Infoln(rootURL+"- malformed", service.Type, "description: no control URL.")
  444. } else {
  445. u, _ := url.Parse(rootURL)
  446. replaceRawPath(u, service.ControlURL)
  447. l.Debugln(rootURL, "- found", service.Type, "with URL", u)
  448. service := IGDService{
  449. UUID: deviceUUID,
  450. Device: device,
  451. ServiceID: service.ID,
  452. URL: u.String(),
  453. URN: service.Type,
  454. Interface: netInterface,
  455. LocalIPv4: localIPAddress,
  456. }
  457. result = append(result, service)
  458. }
  459. }
  460. }
  461. }
  462. }
  463. return result
  464. }
  465. func replaceRawPath(u *url.URL, rp string) {
  466. asURL, err := url.Parse(rp)
  467. if err != nil {
  468. return
  469. } else if asURL.IsAbs() {
  470. u.Path = asURL.Path
  471. u.RawQuery = asURL.RawQuery
  472. } else {
  473. var p, q string
  474. fs := strings.Split(rp, "?")
  475. p = fs[0]
  476. if len(fs) > 1 {
  477. q = fs[1]
  478. }
  479. if p[0] == '/' {
  480. u.Path = p
  481. } else {
  482. u.Path += p
  483. }
  484. u.RawQuery = q
  485. }
  486. }
  487. func soapRequest(ctx context.Context, url, service, function, message string) ([]byte, error) {
  488. return soapRequestWithIP(ctx, url, service, function, message, nil)
  489. }
  490. func soapRequestWithIP(ctx context.Context, url, service, function, message string, localIP *net.TCPAddr) ([]byte, error) {
  491. const template = `<?xml version="1.0" ?>
  492. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  493. <s:Body>%s</s:Body>
  494. </s:Envelope>
  495. `
  496. var resp []byte
  497. body := fmt.Sprintf(template, message)
  498. req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(body))
  499. if err != nil {
  500. return resp, err
  501. }
  502. req.Close = true
  503. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  504. req.Header.Set("User-Agent", "syncthing/1.0")
  505. req.Header["SOAPAction"] = []string{fmt.Sprintf(`"%s#%s"`, service, function)} // Enforce capitalization in header-entry for sensitive routers. See issue #1696
  506. req.Header.Set("Connection", "Close")
  507. req.Header.Set("Cache-Control", "no-cache")
  508. req.Header.Set("Pragma", "no-cache")
  509. l.Debugln("SOAP Request URL: " + url)
  510. l.Debugln("SOAP Action: " + req.Header.Get("SOAPAction"))
  511. l.Debugln("SOAP Request:\n\n" + body)
  512. dialer := net.Dialer{
  513. LocalAddr: localIP,
  514. }
  515. transport := &http.Transport{
  516. DialContext: dialer.DialContext,
  517. }
  518. httpClient := &http.Client{
  519. Transport: transport,
  520. }
  521. r, err := httpClient.Do(req)
  522. if err != nil {
  523. l.Debugln("SOAP do:", err)
  524. return resp, err
  525. }
  526. resp, err = io.ReadAll(r.Body)
  527. if err != nil {
  528. l.Debugf("Error reading SOAP response: %s, partial response (if present):\n\n%s", resp)
  529. return resp, err
  530. }
  531. l.Debugf("SOAP Response: %s\n\n%s\n\n", r.Status, resp)
  532. r.Body.Close()
  533. if r.StatusCode >= 400 {
  534. return resp, errors.New(function + ": " + r.Status)
  535. }
  536. return resp, nil
  537. }
  538. func interfaceHasGUAIPv6(intf net.Interface) (bool, error) {
  539. addrs, err := netutil.InterfaceAddrsByInterface(&intf)
  540. if err != nil {
  541. return false, err
  542. }
  543. for _, addr := range addrs {
  544. ip, _, err := net.ParseCIDR(addr.String())
  545. if err != nil {
  546. return false, err
  547. }
  548. // IsGlobalUnicast returns true for ULAs, so check for those separately.
  549. if ip.To4() == nil && ip.IsGlobalUnicast() && !ip.IsPrivate() {
  550. return true, nil
  551. }
  552. }
  553. return false, nil
  554. }
  555. type soapGetExternalIPAddressResponseEnvelope struct {
  556. XMLName xml.Name
  557. Body soapGetExternalIPAddressResponseBody `xml:"Body"`
  558. }
  559. type soapGetExternalIPAddressResponseBody struct {
  560. XMLName xml.Name
  561. GetExternalIPAddressResponse getExternalIPAddressResponse `xml:"GetExternalIPAddressResponse"`
  562. }
  563. type getExternalIPAddressResponse struct {
  564. NewExternalIPAddress string `xml:"NewExternalIPAddress"`
  565. }
  566. type soapErrorResponse struct {
  567. ErrorCode int `xml:"Body>Fault>detail>UPnPError>errorCode"`
  568. ErrorDescription string `xml:"Body>Fault>detail>UPnPError>errorDescription"`
  569. }
  570. type soapAddPinholeResponse struct {
  571. UniqueID int `xml:"Body>AddPinholeResponse>UniqueID"`
  572. }