upnp.go 20 KB

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