upnp.go 20 KB

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