upnp.go 20 KB

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