upnp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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 "unsupported UPnP device of type " + 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. var e net.Error
  200. if !errors.As(err, &e) || !e.Timeout() {
  201. l.Debugln("UPnP discovery: sending search request:", err)
  202. }
  203. return
  204. }
  205. l.Debugln("Listening for UPnP response for device type", deviceType, "on", intf.Name)
  206. ctx, cancel := context.WithTimeout(ctx, timeout)
  207. defer cancel()
  208. // Listen for responses until a timeout is reached or the context is
  209. // cancelled
  210. resp := make([]byte, 65536)
  211. loop:
  212. for {
  213. if err := socket.SetDeadline(time.Now().Add(250 * time.Millisecond)); err != nil {
  214. slog.WarnContext(ctx, "Failed to set UPnP socket deadline", slogutil.Error(err))
  215. break
  216. }
  217. n, udpAddr, err := socket.ReadFromUDP(resp)
  218. if err != nil {
  219. select {
  220. case <-ctx.Done():
  221. break loop
  222. default:
  223. }
  224. var ne net.Error
  225. if ok := errors.As(err, &ne); ok && ne.Timeout() {
  226. continue // continue reading
  227. }
  228. slog.WarnContext(ctx, "Failed to read from UPnP socket", slogutil.Error(err)) // legitimate error, not a timeout.
  229. break
  230. }
  231. igds, err := parseResponse(ctx, deviceType, udpAddr, resp[:n], intf)
  232. if err != nil {
  233. var unsupp *UnsupportedDeviceTypeError
  234. if errors.As(err, &unsupp) {
  235. l.Debugln(err.Error())
  236. } else if !errors.Is(err, context.Canceled) {
  237. slog.WarnContext(ctx, "Failed to parse UPnP response", slogutil.Error(err))
  238. }
  239. continue
  240. }
  241. for _, igd := range igds {
  242. igd := igd // Copy before sending pointer to the channel.
  243. select {
  244. case results <- &igd:
  245. case <-ctx.Done():
  246. return
  247. }
  248. }
  249. }
  250. l.Debugln("Discovery for device type", deviceType, "on", intf.Name, "finished.")
  251. }
  252. func parseResponse(ctx context.Context, deviceType string, addr *net.UDPAddr, resp []byte, netInterface *net.Interface) ([]IGDService, error) {
  253. l.Debugln("Handling UPnP response:\n\n" + string(resp))
  254. reader := bufio.NewReader(bytes.NewBuffer(resp))
  255. request := &http.Request{}
  256. response, err := http.ReadResponse(reader, request)
  257. if err != nil {
  258. return nil, err
  259. }
  260. respondingDeviceType := response.Header.Get("St")
  261. if respondingDeviceType != deviceType {
  262. return nil, &UnsupportedDeviceTypeError{deviceType: respondingDeviceType}
  263. }
  264. deviceDescriptionLocation := response.Header.Get("Location")
  265. if deviceDescriptionLocation == "" {
  266. return nil, errors.New("invalid IGD response: no location specified")
  267. }
  268. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  269. if err != nil {
  270. slog.WarnContext(ctx, "Got invalid IGD location", slogutil.Error(err))
  271. return nil, err
  272. }
  273. deviceUSN := response.Header.Get("Usn")
  274. if deviceUSN == "" {
  275. return nil, errors.New("invalid IGD response: USN not specified")
  276. }
  277. deviceIP := net.ParseIP(deviceDescriptionURL.Hostname())
  278. // If the hostname of the device parses as an IPv6 link-local address, we need
  279. // to use the source IP address of the response as the hostname
  280. // instead of the one given, since only the former contains the zone index,
  281. // while the URL returned from the gateway cannot contain the zone index.
  282. // (It can't know how interfaces are named/numbered on our machine)
  283. if deviceIP != nil && deviceIP.To4() == nil && deviceIP.IsLinkLocalUnicast() {
  284. ipAddr := net.IPAddr{
  285. IP: addr.IP,
  286. Zone: addr.Zone,
  287. }
  288. deviceDescriptionPort := deviceDescriptionURL.Port()
  289. deviceDescriptionURL.Host = "[" + ipAddr.String() + "]"
  290. if deviceDescriptionPort != "" {
  291. deviceDescriptionURL.Host += ":" + deviceDescriptionPort
  292. }
  293. deviceDescriptionLocation = deviceDescriptionURL.String()
  294. }
  295. deviceUUID := strings.TrimPrefix(strings.Split(deviceUSN, "::")[0], "uuid:")
  296. response, err = http.Get(deviceDescriptionLocation)
  297. if err != nil {
  298. return nil, err
  299. }
  300. defer response.Body.Close()
  301. if response.StatusCode >= 400 {
  302. return nil, errors.New("bad status code:" + response.Status)
  303. }
  304. var upnpRoot upnpRoot
  305. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  306. if err != nil {
  307. return nil, err
  308. }
  309. // Figure out our IPv4 address on the interface used to reach the IGD.
  310. localIPv4Address, err := localIPv4(netInterface)
  311. if err != nil {
  312. // On Android, we cannot enumerate IP addresses on interfaces directly.
  313. // Therefore, we just try to connect to the IGD and look at which source IP
  314. // address was used. This is not ideal, but it's the best we can do. Maybe
  315. // we are on an IPv6-only network though, so don't error out in case pinholing is available.
  316. localIPv4Address, err = localIPv4Fallback(ctx, deviceDescriptionURL)
  317. if err != nil {
  318. slog.WarnContext(ctx, "Unable to determine local IPv4 address for IGD", slogutil.Error(err))
  319. }
  320. }
  321. // This differs from IGDService.SupportsIPVersion(). While that method
  322. // determines whether an already completely discovered device uses the IPv6
  323. // firewall protocol, this just checks if the gateway's is IPv6. Currently we
  324. // only want to discover IPv6 UPnP endpoints on IPv6 gateways and vice versa,
  325. // which is why this needs to be stored but technically we could forgo this check
  326. // and try WANIPv6FirewallControl via IPv4. This leads to errors though so we don't do it.
  327. upnpRoot.Device.IsIPv6 = addr.IP.To4() == nil
  328. services, err := getServiceDescriptions(deviceUUID, localIPv4Address, deviceDescriptionLocation, upnpRoot.Device, netInterface)
  329. if err != nil {
  330. return nil, err
  331. }
  332. return services, nil
  333. }
  334. func localIPv4(netInterface *net.Interface) (net.IP, error) {
  335. addrs, err := netutil.InterfaceAddrsByInterface(netInterface)
  336. if err != nil {
  337. return nil, err
  338. }
  339. for _, addr := range addrs {
  340. ip, _, err := net.ParseCIDR(addr.String())
  341. if err != nil {
  342. continue
  343. }
  344. if ip.To4() != nil {
  345. return ip, nil
  346. }
  347. }
  348. return nil, errors.New("no IPv4 address found for interface " + netInterface.Name)
  349. }
  350. func localIPv4Fallback(ctx context.Context, url *url.URL) (net.IP, error) {
  351. timeoutCtx, cancel := context.WithTimeout(ctx, time.Second)
  352. defer cancel()
  353. conn, err := dialer.DialContext(timeoutCtx, "udp4", url.Host)
  354. if err != nil {
  355. return nil, err
  356. }
  357. defer conn.Close()
  358. ip, err := osutil.IPFromAddr(conn.LocalAddr())
  359. if err != nil {
  360. return nil, err
  361. }
  362. if ip.To4() == nil {
  363. return nil, errors.New("tried to obtain IPv4 through fallback but got IPv6 address")
  364. }
  365. return ip, nil
  366. }
  367. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  368. var result []upnpDevice
  369. for _, dev := range d.Devices {
  370. if dev.DeviceType == deviceType {
  371. result = append(result, dev)
  372. }
  373. }
  374. return result
  375. }
  376. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  377. var result []upnpService
  378. for _, service := range d.Services {
  379. if service.Type == serviceType {
  380. result = append(result, service)
  381. }
  382. }
  383. return result
  384. }
  385. func getServiceDescriptions(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice, netInterface *net.Interface) ([]IGDService, error) {
  386. var result []IGDService
  387. if device.IsIPv6 && device.DeviceType == urnIgdV1 {
  388. // IPv6 UPnP is only standardized for IGDv2. Furthermore, any WANIPConn services for IPv4 that
  389. // we may discover here are likely to be broken because many routers make the choice to not allow
  390. // port mappings for IPs differing from the source IP of the device making the request (which would be v6 here)
  391. return nil, nil
  392. } else if device.IsIPv6 && device.DeviceType == urnIgdV2 {
  393. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  394. urnWANDeviceV2,
  395. urnWANConnectionDeviceV2,
  396. []string{urnWANIPv6FirewallControlV1},
  397. netInterface)
  398. result = append(result, descriptions...)
  399. } else if device.DeviceType == urnIgdV1 {
  400. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  401. urnWANDeviceV1,
  402. urnWANConnectionDeviceV1,
  403. []string{urnWANIPConnectionV1, urnWANPPPConnectionV1},
  404. netInterface)
  405. result = append(result, descriptions...)
  406. } else if device.DeviceType == urnIgdV2 {
  407. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  408. urnWANDeviceV2,
  409. urnWANConnectionDeviceV2,
  410. []string{urnWANIPConnectionV2, urnWANPPPConnectionV2},
  411. netInterface)
  412. result = append(result, descriptions...)
  413. } else {
  414. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  415. }
  416. if len(result) < 1 {
  417. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  418. }
  419. return result, nil
  420. }
  421. func getIGDServices(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice, wanDeviceURN string, wanConnectionURN string, URNs []string, netInterface *net.Interface) []IGDService {
  422. var result []IGDService
  423. devices := getChildDevices(device, wanDeviceURN)
  424. if len(devices) < 1 {
  425. slog.Warn("Got malformed InternetGatewayDevice description: no WANDevices specified")
  426. return result
  427. }
  428. for _, device := range devices {
  429. connections := getChildDevices(device, wanConnectionURN)
  430. if len(connections) < 1 {
  431. slog.Warn("Got malformed WAN device description: no WANConnectionDevices specified", "urn", wanDeviceURN)
  432. }
  433. for _, connection := range connections {
  434. for _, urn := range URNs {
  435. services := getChildServices(connection, urn)
  436. if len(services) == 0 {
  437. l.Debugln(rootURL, "- no services of type", urn, " found on connection.")
  438. }
  439. for _, service := range services {
  440. if service.ControlURL == "" {
  441. slog.Warn("Gor malformed service description: no control URL", "service", service.Type)
  442. } else {
  443. u, _ := url.Parse(rootURL)
  444. replaceRawPath(u, service.ControlURL)
  445. l.Debugln(rootURL, "- found", service.Type, "with URL", u)
  446. service := IGDService{
  447. UUID: deviceUUID,
  448. Device: device,
  449. ServiceID: service.ID,
  450. URL: u.String(),
  451. URN: service.Type,
  452. Interface: netInterface,
  453. LocalIPv4: localIPAddress,
  454. }
  455. result = append(result, service)
  456. }
  457. }
  458. }
  459. }
  460. }
  461. return result
  462. }
  463. func replaceRawPath(u *url.URL, rp string) {
  464. asURL, err := url.Parse(rp)
  465. if err != nil {
  466. return
  467. } else if asURL.IsAbs() {
  468. u.Path = asURL.Path
  469. u.RawQuery = asURL.RawQuery
  470. } else {
  471. var p, q string
  472. fs := strings.Split(rp, "?")
  473. p = fs[0]
  474. if len(fs) > 1 {
  475. q = fs[1]
  476. }
  477. if p[0] == '/' {
  478. u.Path = p
  479. } else {
  480. u.Path += p
  481. }
  482. u.RawQuery = q
  483. }
  484. }
  485. func soapRequest(ctx context.Context, url, service, function, message string) ([]byte, error) {
  486. return soapRequestWithIP(ctx, url, service, function, message, nil)
  487. }
  488. func soapRequestWithIP(ctx context.Context, url, service, function, message string, localIP *net.TCPAddr) ([]byte, error) {
  489. const template = `<?xml version="1.0" ?>
  490. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  491. <s:Body>%s</s:Body>
  492. </s:Envelope>
  493. `
  494. var resp []byte
  495. body := fmt.Sprintf(template, message)
  496. req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body))
  497. if err != nil {
  498. return resp, err
  499. }
  500. req.Close = true
  501. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  502. req.Header.Set("User-Agent", "syncthing/1.0")
  503. req.Header["SOAPAction"] = []string{fmt.Sprintf(`"%s#%s"`, service, function)} // Enforce capitalization in header-entry for sensitive routers. See issue #1696
  504. req.Header.Set("Connection", "Close")
  505. req.Header.Set("Cache-Control", "no-cache")
  506. req.Header.Set("Pragma", "no-cache")
  507. l.Debugln("SOAP Request URL: " + url)
  508. l.Debugln("SOAP Action: " + req.Header.Get("SOAPAction"))
  509. l.Debugln("SOAP Request:\n\n" + body)
  510. dialer := net.Dialer{
  511. LocalAddr: localIP,
  512. }
  513. transport := &http.Transport{
  514. DialContext: dialer.DialContext,
  515. }
  516. httpClient := &http.Client{
  517. Transport: transport,
  518. }
  519. r, err := httpClient.Do(req)
  520. if err != nil {
  521. l.Debugln("SOAP do:", err)
  522. return resp, err
  523. }
  524. resp, err = io.ReadAll(r.Body)
  525. if err != nil {
  526. l.Debugf("Error reading SOAP response: %v, partial response (if present):\n\n%s", err, resp)
  527. return resp, err
  528. }
  529. l.Debugf("SOAP Response: %s\n\n%s\n\n", r.Status, resp)
  530. r.Body.Close()
  531. if r.StatusCode >= 400 {
  532. return resp, errors.New(function + ": " + r.Status)
  533. }
  534. return resp, nil
  535. }
  536. func interfaceHasGUAIPv6(intf net.Interface) (bool, error) {
  537. addrs, err := netutil.InterfaceAddrsByInterface(&intf)
  538. if err != nil {
  539. return false, err
  540. }
  541. for _, addr := range addrs {
  542. ip, _, err := net.ParseCIDR(addr.String())
  543. if err != nil {
  544. return false, err
  545. }
  546. // IsGlobalUnicast returns true for ULAs, so check for those separately.
  547. if ip.To4() == nil && ip.IsGlobalUnicast() && !ip.IsPrivate() {
  548. return true, nil
  549. }
  550. }
  551. return false, nil
  552. }
  553. type soapGetExternalIPAddressResponseEnvelope struct {
  554. XMLName xml.Name
  555. Body soapGetExternalIPAddressResponseBody `xml:"Body"`
  556. }
  557. type soapGetExternalIPAddressResponseBody struct {
  558. XMLName xml.Name
  559. GetExternalIPAddressResponse getExternalIPAddressResponse `xml:"GetExternalIPAddressResponse"`
  560. }
  561. type getExternalIPAddressResponse struct {
  562. NewExternalIPAddress string `xml:"NewExternalIPAddress"`
  563. }
  564. type soapErrorResponse struct {
  565. ErrorCode int `xml:"Body>Fault>detail>UPnPError>errorCode"`
  566. ErrorDescription string `xml:"Body>Fault>detail>UPnPError>errorDescription"`
  567. }
  568. type soapAddPinholeResponse struct {
  569. UniqueID int `xml:"Body>AddPinholeResponse>UniqueID"`
  570. }