upnp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. "fmt"
  39. "io"
  40. "net"
  41. "net/http"
  42. "net/url"
  43. "runtime"
  44. "strings"
  45. "sync"
  46. "time"
  47. "github.com/pkg/errors"
  48. "github.com/syncthing/syncthing/lib/dialer"
  49. "github.com/syncthing/syncthing/lib/nat"
  50. )
  51. func init() {
  52. nat.Register(Discover)
  53. }
  54. type upnpService struct {
  55. ID string `xml:"serviceId"`
  56. Type string `xml:"serviceType"`
  57. ControlURL string `xml:"controlURL"`
  58. }
  59. type upnpDevice struct {
  60. DeviceType string `xml:"deviceType"`
  61. FriendlyName string `xml:"friendlyName"`
  62. Devices []upnpDevice `xml:"deviceList>device"`
  63. Services []upnpService `xml:"serviceList>service"`
  64. }
  65. type upnpRoot struct {
  66. Device upnpDevice `xml:"device"`
  67. }
  68. // UnsupportedDeviceTypeError for unsupported UPnP device types (i.e upnp:rootdevice)
  69. type UnsupportedDeviceTypeError struct {
  70. deviceType string
  71. }
  72. func (e *UnsupportedDeviceTypeError) Error() string {
  73. return fmt.Sprintf("Unsupported UPnP device of type %s", e.deviceType)
  74. }
  75. // Discover discovers UPnP InternetGatewayDevices.
  76. // The order in which the devices appear in the results list is not deterministic.
  77. func Discover(ctx context.Context, renewal, timeout time.Duration) []nat.Device {
  78. var results []nat.Device
  79. interfaces, err := net.Interfaces()
  80. if err != nil {
  81. l.Infoln("Listing network interfaces:", err)
  82. return results
  83. }
  84. resultChan := make(chan nat.Device)
  85. wg := &sync.WaitGroup{}
  86. for _, intf := range interfaces {
  87. // Interface flags seem to always be 0 on Windows
  88. if runtime.GOOS != "windows" && (intf.Flags&net.FlagUp == 0 || intf.Flags&net.FlagMulticast == 0) {
  89. continue
  90. }
  91. for _, deviceType := range []string{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:device:InternetGatewayDevice:2"} {
  92. wg.Add(1)
  93. go func(intf net.Interface, deviceType string) {
  94. discover(ctx, &intf, deviceType, timeout, resultChan)
  95. wg.Done()
  96. }(intf, deviceType)
  97. }
  98. }
  99. go func() {
  100. wg.Wait()
  101. close(resultChan)
  102. }()
  103. seenResults := make(map[string]bool)
  104. for {
  105. select {
  106. case result, ok := <-resultChan:
  107. if !ok {
  108. return results
  109. }
  110. if seenResults[result.ID()] {
  111. l.Debugf("Skipping duplicate result %s", result.ID())
  112. continue
  113. }
  114. results = append(results, result)
  115. seenResults[result.ID()] = true
  116. l.Debugf("UPnP discovery result %s", result.ID())
  117. case <-ctx.Done():
  118. return nil
  119. }
  120. }
  121. }
  122. // Search for UPnP InternetGatewayDevices for <timeout> seconds.
  123. // The order in which the devices appear in the result list is not deterministic
  124. func discover(ctx context.Context, intf *net.Interface, deviceType string, timeout time.Duration, results chan<- nat.Device) {
  125. ssdp := &net.UDPAddr{IP: []byte{239, 255, 255, 250}, Port: 1900}
  126. tpl := `M-SEARCH * HTTP/1.1
  127. HOST: 239.255.255.250:1900
  128. ST: %s
  129. MAN: "ssdp:discover"
  130. MX: %d
  131. USER-AGENT: syncthing/1.0
  132. `
  133. searchStr := fmt.Sprintf(tpl, deviceType, timeout/time.Second)
  134. search := []byte(strings.ReplaceAll(searchStr, "\n", "\r\n") + "\r\n")
  135. l.Debugln("Starting discovery of device type", deviceType, "on", intf.Name)
  136. socket, err := net.ListenMulticastUDP("udp4", intf, &net.UDPAddr{IP: ssdp.IP})
  137. if err != nil {
  138. l.Debugln("UPnP discovery: listening to udp multicast:", err)
  139. return
  140. }
  141. defer socket.Close() // Make sure our socket gets closed
  142. l.Debugln("Sending search request for device type", deviceType, "on", intf.Name)
  143. _, err = socket.WriteTo(search, ssdp)
  144. if err != nil {
  145. if e, ok := err.(net.Error); !ok || !e.Timeout() {
  146. l.Debugln("UPnP discovery: sending search request:", err)
  147. }
  148. return
  149. }
  150. l.Debugln("Listening for UPnP response for device type", deviceType, "on", intf.Name)
  151. ctx, cancel := context.WithTimeout(ctx, timeout)
  152. defer cancel()
  153. // Listen for responses until a timeout is reached or the context is
  154. // cancelled
  155. resp := make([]byte, 65536)
  156. loop:
  157. for {
  158. if err := socket.SetDeadline(time.Now().Add(250 * time.Millisecond)); err != nil {
  159. l.Infoln("UPnP socket:", err)
  160. break
  161. }
  162. n, _, err := socket.ReadFrom(resp)
  163. if err != nil {
  164. select {
  165. case <-ctx.Done():
  166. break loop
  167. default:
  168. }
  169. if e, ok := err.(net.Error); ok && e.Timeout() {
  170. continue // continue reading
  171. }
  172. l.Infoln("UPnP read:", err) //legitimate error, not a timeout.
  173. break
  174. }
  175. igds, err := parseResponse(ctx, deviceType, resp[:n])
  176. if err != nil {
  177. switch err.(type) {
  178. case *UnsupportedDeviceTypeError:
  179. l.Debugln(err.Error())
  180. default:
  181. if errors.Cause(err) != context.Canceled {
  182. l.Infoln("UPnP parse:", err)
  183. }
  184. }
  185. continue
  186. }
  187. for _, igd := range igds {
  188. igd := igd // Copy before sending pointer to the channel.
  189. select {
  190. case results <- &igd:
  191. case <-ctx.Done():
  192. return
  193. }
  194. }
  195. }
  196. l.Debugln("Discovery for device type", deviceType, "on", intf.Name, "finished.")
  197. }
  198. func parseResponse(ctx context.Context, deviceType string, resp []byte) ([]IGDService, error) {
  199. l.Debugln("Handling UPnP response:\n\n" + string(resp))
  200. reader := bufio.NewReader(bytes.NewBuffer(resp))
  201. request := &http.Request{}
  202. response, err := http.ReadResponse(reader, request)
  203. if err != nil {
  204. return nil, err
  205. }
  206. respondingDeviceType := response.Header.Get("St")
  207. if respondingDeviceType != deviceType {
  208. return nil, &UnsupportedDeviceTypeError{deviceType: respondingDeviceType}
  209. }
  210. deviceDescriptionLocation := response.Header.Get("Location")
  211. if deviceDescriptionLocation == "" {
  212. return nil, errors.New("invalid IGD response: no location specified")
  213. }
  214. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  215. if err != nil {
  216. l.Infoln("Invalid IGD location: " + err.Error())
  217. }
  218. deviceUSN := response.Header.Get("USN")
  219. if deviceUSN == "" {
  220. return nil, errors.New("invalid IGD response: USN not specified")
  221. }
  222. deviceUUID := strings.TrimPrefix(strings.Split(deviceUSN, "::")[0], "uuid:")
  223. response, err = http.Get(deviceDescriptionLocation)
  224. if err != nil {
  225. return nil, err
  226. }
  227. defer response.Body.Close()
  228. if response.StatusCode >= 400 {
  229. return nil, errors.New("bad status code:" + response.Status)
  230. }
  231. var upnpRoot upnpRoot
  232. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  233. if err != nil {
  234. return nil, err
  235. }
  236. // Figure out our IP number, on the network used to reach the IGD.
  237. // We do this in a fairly roundabout way by connecting to the IGD and
  238. // checking the address of the local end of the socket. I'm open to
  239. // suggestions on a better way to do this...
  240. localIPAddress, err := localIP(ctx, deviceDescriptionURL)
  241. if err != nil {
  242. return nil, err
  243. }
  244. services, err := getServiceDescriptions(deviceUUID, localIPAddress, deviceDescriptionLocation, upnpRoot.Device)
  245. if err != nil {
  246. return nil, err
  247. }
  248. return services, nil
  249. }
  250. func localIP(ctx context.Context, url *url.URL) (net.IP, error) {
  251. timeoutCtx, cancel := context.WithTimeout(ctx, time.Second)
  252. defer cancel()
  253. conn, err := dialer.DialContext(timeoutCtx, "tcp", url.Host)
  254. if err != nil {
  255. return nil, err
  256. }
  257. defer conn.Close()
  258. localIPAddress, _, err := net.SplitHostPort(conn.LocalAddr().String())
  259. if err != nil {
  260. return nil, err
  261. }
  262. return net.ParseIP(localIPAddress), nil
  263. }
  264. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  265. var result []upnpDevice
  266. for _, dev := range d.Devices {
  267. if dev.DeviceType == deviceType {
  268. result = append(result, dev)
  269. }
  270. }
  271. return result
  272. }
  273. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  274. var result []upnpService
  275. for _, service := range d.Services {
  276. if service.Type == serviceType {
  277. result = append(result, service)
  278. }
  279. }
  280. return result
  281. }
  282. func getServiceDescriptions(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice) ([]IGDService, error) {
  283. var result []IGDService
  284. if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  285. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  286. "urn:schemas-upnp-org:device:WANDevice:1",
  287. "urn:schemas-upnp-org:device:WANConnectionDevice:1",
  288. []string{"urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"})
  289. result = append(result, descriptions...)
  290. } else if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:2" {
  291. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  292. "urn:schemas-upnp-org:device:WANDevice:2",
  293. "urn:schemas-upnp-org:device:WANConnectionDevice:2",
  294. []string{"urn:schemas-upnp-org:service:WANIPConnection:2", "urn:schemas-upnp-org:service:WANPPPConnection:2"})
  295. result = append(result, descriptions...)
  296. } else {
  297. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  298. }
  299. if len(result) < 1 {
  300. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  301. }
  302. return result, nil
  303. }
  304. func getIGDServices(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice, wanDeviceURN string, wanConnectionURN string, URNs []string) []IGDService {
  305. var result []IGDService
  306. devices := getChildDevices(device, wanDeviceURN)
  307. if len(devices) < 1 {
  308. l.Infoln(rootURL, "- malformed InternetGatewayDevice description: no WANDevices specified.")
  309. return result
  310. }
  311. for _, device := range devices {
  312. connections := getChildDevices(device, wanConnectionURN)
  313. if len(connections) < 1 {
  314. l.Infoln(rootURL, "- malformed ", wanDeviceURN, "description: no WANConnectionDevices specified.")
  315. }
  316. for _, connection := range connections {
  317. for _, URN := range URNs {
  318. services := getChildServices(connection, URN)
  319. l.Debugln(rootURL, "- no services of type", URN, " found on connection.")
  320. for _, service := range services {
  321. if len(service.ControlURL) == 0 {
  322. l.Infoln(rootURL+"- malformed", service.Type, "description: no control URL.")
  323. } else {
  324. u, _ := url.Parse(rootURL)
  325. replaceRawPath(u, service.ControlURL)
  326. l.Debugln(rootURL, "- found", service.Type, "with URL", u)
  327. service := IGDService{
  328. UUID: deviceUUID,
  329. Device: device,
  330. ServiceID: service.ID,
  331. URL: u.String(),
  332. URN: service.Type,
  333. LocalIP: localIPAddress,
  334. }
  335. result = append(result, service)
  336. }
  337. }
  338. }
  339. }
  340. }
  341. return result
  342. }
  343. func replaceRawPath(u *url.URL, rp string) {
  344. asURL, err := url.Parse(rp)
  345. if err != nil {
  346. return
  347. } else if asURL.IsAbs() {
  348. u.Path = asURL.Path
  349. u.RawQuery = asURL.RawQuery
  350. } else {
  351. var p, q string
  352. fs := strings.Split(rp, "?")
  353. p = fs[0]
  354. if len(fs) > 1 {
  355. q = fs[1]
  356. }
  357. if p[0] == '/' {
  358. u.Path = p
  359. } else {
  360. u.Path += p
  361. }
  362. u.RawQuery = q
  363. }
  364. }
  365. func soapRequest(ctx context.Context, url, service, function, message string) ([]byte, error) {
  366. tpl := `<?xml version="1.0" ?>
  367. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  368. <s:Body>%s</s:Body>
  369. </s:Envelope>
  370. `
  371. var resp []byte
  372. body := fmt.Sprintf(tpl, message)
  373. req, err := http.NewRequest("POST", url, strings.NewReader(body))
  374. if err != nil {
  375. return resp, err
  376. }
  377. req.Cancel = ctx.Done()
  378. req.Close = true
  379. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  380. req.Header.Set("User-Agent", "syncthing/1.0")
  381. req.Header["SOAPAction"] = []string{fmt.Sprintf(`"%s#%s"`, service, function)} // Enforce capitalization in header-entry for sensitive routers. See issue #1696
  382. req.Header.Set("Connection", "Close")
  383. req.Header.Set("Cache-Control", "no-cache")
  384. req.Header.Set("Pragma", "no-cache")
  385. l.Debugln("SOAP Request URL: " + url)
  386. l.Debugln("SOAP Action: " + req.Header.Get("SOAPAction"))
  387. l.Debugln("SOAP Request:\n\n" + body)
  388. r, err := http.DefaultClient.Do(req)
  389. if err != nil {
  390. l.Debugln("SOAP do:", err)
  391. return resp, err
  392. }
  393. resp, _ = io.ReadAll(r.Body)
  394. l.Debugf("SOAP Response: %s\n\n%s\n\n", r.Status, resp)
  395. r.Body.Close()
  396. if r.StatusCode >= 400 {
  397. return resp, errors.New(function + ": " + r.Status)
  398. }
  399. return resp, nil
  400. }
  401. type soapGetExternalIPAddressResponseEnvelope struct {
  402. XMLName xml.Name
  403. Body soapGetExternalIPAddressResponseBody `xml:"Body"`
  404. }
  405. type soapGetExternalIPAddressResponseBody struct {
  406. XMLName xml.Name
  407. GetExternalIPAddressResponse getExternalIPAddressResponse `xml:"GetExternalIPAddressResponse"`
  408. }
  409. type getExternalIPAddressResponse struct {
  410. NewExternalIPAddress string `xml:"NewExternalIPAddress"`
  411. }
  412. type soapErrorResponse struct {
  413. ErrorCode int `xml:"Body>Fault>detail>UPnPError>errorCode"`
  414. ErrorDescription string `xml:"Body>Fault>detail>UPnPError>errorDescription"`
  415. }