PageRenderTime 699ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/internal/upnp/upnp.go

https://gitlab.com/roth1002/syncthing
Go | 607 lines | 466 code | 103 blank | 38 comment | 127 complexity | e89f0530b84a39182cdac35de206b306 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, JSON, LGPL-3.0
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Adapted from https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/IGD.go
  7. // Copyright (c) 2010 Jack Palevich (https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/LICENSE)
  8. // Package upnp implements UPnP InternetGatewayDevice discovery, querying, and port mapping.
  9. package upnp
  10. import (
  11. "bufio"
  12. "bytes"
  13. "encoding/xml"
  14. "errors"
  15. "fmt"
  16. "io/ioutil"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "regexp"
  21. "runtime"
  22. "strings"
  23. "time"
  24. "github.com/syncthing/syncthing/internal/sync"
  25. )
  26. // An IGD is a UPnP InternetGatewayDevice.
  27. type IGD struct {
  28. uuid string
  29. friendlyName string
  30. services []IGDService
  31. url *url.URL
  32. localIPAddress string
  33. }
  34. func (n *IGD) UUID() string {
  35. return n.uuid
  36. }
  37. func (n *IGD) FriendlyName() string {
  38. return n.friendlyName
  39. }
  40. // FriendlyIdentifier returns a friendly identifier (friendly name + IP
  41. // address) for the IGD.
  42. func (n *IGD) FriendlyIdentifier() string {
  43. return "'" + n.FriendlyName() + "' (" + strings.Split(n.URL().Host, ":")[0] + ")"
  44. }
  45. func (n *IGD) URL() *url.URL {
  46. return n.url
  47. }
  48. // An IGDService is a specific service provided by an IGD.
  49. type IGDService struct {
  50. serviceID string
  51. serviceURL string
  52. serviceURN string
  53. }
  54. func (s *IGDService) ID() string {
  55. return s.serviceID
  56. }
  57. type Protocol string
  58. const (
  59. TCP Protocol = "TCP"
  60. UDP = "UDP"
  61. )
  62. type upnpService struct {
  63. ServiceID string `xml:"serviceId"`
  64. ServiceType string `xml:"serviceType"`
  65. ControlURL string `xml:"controlURL"`
  66. }
  67. type upnpDevice struct {
  68. DeviceType string `xml:"deviceType"`
  69. FriendlyName string `xml:"friendlyName"`
  70. Devices []upnpDevice `xml:"deviceList>device"`
  71. Services []upnpService `xml:"serviceList>service"`
  72. }
  73. type upnpRoot struct {
  74. Device upnpDevice `xml:"device"`
  75. }
  76. // Discover discovers UPnP InternetGatewayDevices.
  77. // The order in which the devices appear in the results list is not deterministic.
  78. func Discover(timeout time.Duration) []IGD {
  79. var results []IGD
  80. interfaces, err := net.Interfaces()
  81. if err != nil {
  82. l.Infoln("Listing network interfaces:", err)
  83. return results
  84. }
  85. resultChan := make(chan IGD)
  86. wg := sync.NewWaitGroup()
  87. for _, intf := range interfaces {
  88. // Interface flags seem to always be 0 on Windows
  89. if runtime.GOOS != "windows" && (intf.Flags&net.FlagUp == 0 || intf.Flags&net.FlagMulticast == 0) {
  90. continue
  91. }
  92. for _, deviceType := range []string{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:device:InternetGatewayDevice:2"} {
  93. wg.Add(1)
  94. go func(intf net.Interface, deviceType string) {
  95. discover(&intf, deviceType, timeout, resultChan)
  96. wg.Done()
  97. }(intf, deviceType)
  98. }
  99. }
  100. go func() {
  101. wg.Wait()
  102. close(resultChan)
  103. }()
  104. nextResult:
  105. for result := range resultChan {
  106. for _, existingResult := range results {
  107. if existingResult.uuid == result.uuid {
  108. if debug {
  109. l.Debugf("Skipping duplicate result %s with services:", result.uuid)
  110. for _, svc := range result.services {
  111. l.Debugf("* [%s] %s", svc.serviceID, svc.serviceURL)
  112. }
  113. }
  114. continue nextResult
  115. }
  116. }
  117. results = append(results, result)
  118. if debug {
  119. l.Debugf("UPnP discovery result %s with services:", result.uuid)
  120. for _, svc := range result.services {
  121. l.Debugf("* [%s] %s", svc.serviceID, svc.serviceURL)
  122. }
  123. }
  124. }
  125. return results
  126. }
  127. // Search for UPnP InternetGatewayDevices for <timeout> seconds, ignoring responses from any devices listed in knownDevices.
  128. // The order in which the devices appear in the result list is not deterministic
  129. func discover(intf *net.Interface, deviceType string, timeout time.Duration, results chan<- IGD) {
  130. ssdp := &net.UDPAddr{IP: []byte{239, 255, 255, 250}, Port: 1900}
  131. tpl := `M-SEARCH * HTTP/1.1
  132. Host: 239.255.255.250:1900
  133. St: %s
  134. Man: "ssdp:discover"
  135. Mx: %d
  136. `
  137. searchStr := fmt.Sprintf(tpl, deviceType, timeout/time.Second)
  138. search := []byte(strings.Replace(searchStr, "\n", "\r\n", -1))
  139. if debug {
  140. l.Debugln("Starting discovery of device type " + deviceType + " on " + intf.Name)
  141. }
  142. socket, err := net.ListenMulticastUDP("udp4", intf, &net.UDPAddr{IP: ssdp.IP})
  143. if err != nil {
  144. if debug {
  145. l.Debugln(err)
  146. }
  147. return
  148. }
  149. defer socket.Close() // Make sure our socket gets closed
  150. err = socket.SetDeadline(time.Now().Add(timeout))
  151. if err != nil {
  152. l.Infoln(err)
  153. return
  154. }
  155. if debug {
  156. l.Debugln("Sending search request for device type " + deviceType + " on " + intf.Name)
  157. }
  158. _, err = socket.WriteTo(search, ssdp)
  159. if err != nil {
  160. l.Infoln(err)
  161. return
  162. }
  163. if debug {
  164. l.Debugln("Listening for UPnP response for device type " + deviceType + " on " + intf.Name)
  165. }
  166. // Listen for responses until a timeout is reached
  167. for {
  168. resp := make([]byte, 65536)
  169. n, _, err := socket.ReadFrom(resp)
  170. if err != nil {
  171. if e, ok := err.(net.Error); !ok || !e.Timeout() {
  172. l.Infoln("UPnP read:", err) //legitimate error, not a timeout.
  173. }
  174. break
  175. }
  176. igd, err := parseResponse(deviceType, resp[:n])
  177. if err != nil {
  178. l.Infoln("UPnP parse:", err)
  179. continue
  180. }
  181. results <- igd
  182. }
  183. if debug {
  184. l.Debugln("Discovery for device type " + deviceType + " on " + intf.Name + " finished.")
  185. }
  186. }
  187. func parseResponse(deviceType string, resp []byte) (IGD, error) {
  188. if debug {
  189. l.Debugln("Handling UPnP response:\n\n" + string(resp))
  190. }
  191. reader := bufio.NewReader(bytes.NewBuffer(resp))
  192. request := &http.Request{}
  193. response, err := http.ReadResponse(reader, request)
  194. if err != nil {
  195. return IGD{}, err
  196. }
  197. respondingDeviceType := response.Header.Get("St")
  198. if respondingDeviceType != deviceType {
  199. return IGD{}, errors.New("unrecognized UPnP device of type " + respondingDeviceType)
  200. }
  201. deviceDescriptionLocation := response.Header.Get("Location")
  202. if deviceDescriptionLocation == "" {
  203. return IGD{}, errors.New("invalid IGD response: no location specified")
  204. }
  205. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  206. if err != nil {
  207. l.Infoln("Invalid IGD location: " + err.Error())
  208. }
  209. deviceUSN := response.Header.Get("USN")
  210. if deviceUSN == "" {
  211. return IGD{}, errors.New("invalid IGD response: USN not specified")
  212. }
  213. deviceUUID := strings.TrimPrefix(strings.Split(deviceUSN, "::")[0], "uuid:")
  214. matched, err := regexp.MatchString("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}", deviceUUID)
  215. if !matched {
  216. l.Infoln("Invalid IGD response: invalid device UUID", deviceUUID, "(continuing anyway)")
  217. }
  218. response, err = http.Get(deviceDescriptionLocation)
  219. if err != nil {
  220. return IGD{}, err
  221. }
  222. defer response.Body.Close()
  223. if response.StatusCode >= 400 {
  224. return IGD{}, errors.New("bad status code:" + response.Status)
  225. }
  226. var upnpRoot upnpRoot
  227. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  228. if err != nil {
  229. return IGD{}, err
  230. }
  231. services, err := getServiceDescriptions(deviceDescriptionLocation, upnpRoot.Device)
  232. if err != nil {
  233. return IGD{}, err
  234. }
  235. // Figure out our IP number, on the network used to reach the IGD.
  236. // We do this in a fairly roundabout way by connecting to the IGD and
  237. // checking the address of the local end of the socket. I'm open to
  238. // suggestions on a better way to do this...
  239. localIPAddress, err := localIP(deviceDescriptionURL)
  240. if err != nil {
  241. return IGD{}, err
  242. }
  243. return IGD{
  244. uuid: deviceUUID,
  245. friendlyName: upnpRoot.Device.FriendlyName,
  246. url: deviceDescriptionURL,
  247. services: services,
  248. localIPAddress: localIPAddress,
  249. }, nil
  250. }
  251. func localIP(url *url.URL) (string, error) {
  252. conn, err := net.Dial("tcp", url.Host)
  253. if err != nil {
  254. return "", err
  255. }
  256. defer conn.Close()
  257. localIPAddress, _, err := net.SplitHostPort(conn.LocalAddr().String())
  258. if err != nil {
  259. return "", err
  260. }
  261. return localIPAddress, nil
  262. }
  263. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  264. var result []upnpDevice
  265. for _, dev := range d.Devices {
  266. if dev.DeviceType == deviceType {
  267. result = append(result, dev)
  268. }
  269. }
  270. return result
  271. }
  272. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  273. var result []upnpService
  274. for _, svc := range d.Services {
  275. if svc.ServiceType == serviceType {
  276. result = append(result, svc)
  277. }
  278. }
  279. return result
  280. }
  281. func getServiceDescriptions(rootURL string, device upnpDevice) ([]IGDService, error) {
  282. var result []IGDService
  283. if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  284. descriptions := getIGDServices(rootURL, device,
  285. "urn:schemas-upnp-org:device:WANDevice:1",
  286. "urn:schemas-upnp-org:device:WANConnectionDevice:1",
  287. []string{"urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"})
  288. result = append(result, descriptions...)
  289. } else if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:2" {
  290. descriptions := getIGDServices(rootURL, device,
  291. "urn:schemas-upnp-org:device:WANDevice:2",
  292. "urn:schemas-upnp-org:device:WANConnectionDevice:2",
  293. []string{"urn:schemas-upnp-org:service:WANIPConnection:2", "urn:schemas-upnp-org:service:WANPPPConnection:1"})
  294. result = append(result, descriptions...)
  295. } else {
  296. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  297. }
  298. if len(result) < 1 {
  299. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  300. }
  301. return result, nil
  302. }
  303. func getIGDServices(rootURL string, device upnpDevice, wanDeviceURN string, wanConnectionURN string, serviceURNs []string) []IGDService {
  304. var result []IGDService
  305. devices := getChildDevices(device, wanDeviceURN)
  306. if len(devices) < 1 {
  307. l.Infoln("[" + rootURL + "] Malformed InternetGatewayDevice description: no WANDevices specified.")
  308. return result
  309. }
  310. for _, device := range devices {
  311. connections := getChildDevices(device, wanConnectionURN)
  312. if len(connections) < 1 {
  313. l.Infoln("[" + rootURL + "] Malformed " + wanDeviceURN + " description: no WANConnectionDevices specified.")
  314. }
  315. for _, connection := range connections {
  316. for _, serviceURN := range serviceURNs {
  317. services := getChildServices(connection, serviceURN)
  318. if len(services) < 1 && debug {
  319. l.Debugln("[" + rootURL + "] No services of type " + serviceURN + " found on connection.")
  320. }
  321. for _, service := range services {
  322. if len(service.ControlURL) == 0 {
  323. l.Infoln("[" + rootURL + "] Malformed " + service.ServiceType + " description: no control URL.")
  324. } else {
  325. u, _ := url.Parse(rootURL)
  326. replaceRawPath(u, service.ControlURL)
  327. if debug {
  328. l.Debugln("[" + rootURL + "] Found " + service.ServiceType + " with URL " + u.String())
  329. }
  330. service := IGDService{serviceID: service.ServiceID, serviceURL: u.String(), serviceURN: service.ServiceType}
  331. result = append(result, service)
  332. }
  333. }
  334. }
  335. }
  336. }
  337. return result
  338. }
  339. func replaceRawPath(u *url.URL, rp string) {
  340. asURL, err := url.Parse(rp)
  341. if err != nil {
  342. return
  343. } else if asURL.IsAbs() {
  344. u.Path = asURL.Path
  345. u.RawQuery = asURL.RawQuery
  346. } else {
  347. var p, q string
  348. fs := strings.Split(rp, "?")
  349. p = fs[0]
  350. if len(fs) > 1 {
  351. q = fs[1]
  352. }
  353. if p[0] == '/' {
  354. u.Path = p
  355. } else {
  356. u.Path += p
  357. }
  358. u.RawQuery = q
  359. }
  360. }
  361. func soapRequest(url, service, function, message string) ([]byte, error) {
  362. tpl := `<?xml version="1.0" ?>
  363. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  364. <s:Body>%s</s:Body>
  365. </s:Envelope>
  366. `
  367. var resp []byte
  368. body := fmt.Sprintf(tpl, message)
  369. req, err := http.NewRequest("POST", url, strings.NewReader(body))
  370. if err != nil {
  371. return resp, err
  372. }
  373. req.Close = true
  374. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  375. req.Header.Set("User-Agent", "syncthing/1.0")
  376. req.Header["SOAPAction"] = []string{fmt.Sprintf(`"%s#%s"`, service, function)} // Enforce capitalization in header-entry for sensitive routers. See issue #1696
  377. req.Header.Set("Connection", "Close")
  378. req.Header.Set("Cache-Control", "no-cache")
  379. req.Header.Set("Pragma", "no-cache")
  380. if debug {
  381. l.Debugln("SOAP Request URL: " + url)
  382. l.Debugln("SOAP Action: " + req.Header.Get("SOAPAction"))
  383. l.Debugln("SOAP Request:\n\n" + body)
  384. }
  385. r, err := http.DefaultClient.Do(req)
  386. if err != nil {
  387. if debug {
  388. l.Debugln(err)
  389. }
  390. return resp, err
  391. }
  392. resp, _ = ioutil.ReadAll(r.Body)
  393. if debug {
  394. l.Debugf("SOAP Response: %v\n\n%v\n\n", r.StatusCode, string(resp))
  395. }
  396. r.Body.Close()
  397. if r.StatusCode >= 400 {
  398. return resp, errors.New(function + ": " + r.Status)
  399. }
  400. return resp, nil
  401. }
  402. // AddPortMapping adds a port mapping to all relevant services on the
  403. // specified InternetGatewayDevice. Port mapping will fail and return an error
  404. // if action is fails for _any_ of the relevant services. For this reason, it
  405. // is generally better to configure port mapping for each individual service
  406. // instead.
  407. func (n *IGD) AddPortMapping(protocol Protocol, externalPort, internalPort int, description string, timeout int) error {
  408. for _, service := range n.services {
  409. err := service.AddPortMapping(n.localIPAddress, protocol, externalPort, internalPort, description, timeout)
  410. if err != nil {
  411. return err
  412. }
  413. }
  414. return nil
  415. }
  416. // DeletePortMapping deletes a port mapping from all relevant services on the
  417. // specified InternetGatewayDevice. Port mapping will fail and return an error
  418. // if action is fails for _any_ of the relevant services. For this reason, it
  419. // is generally better to configure port mapping for each individual service
  420. // instead.
  421. func (n *IGD) DeletePortMapping(protocol Protocol, externalPort int) error {
  422. for _, service := range n.services {
  423. err := service.DeletePortMapping(protocol, externalPort)
  424. if err != nil {
  425. return err
  426. }
  427. }
  428. return nil
  429. }
  430. type soapGetExternalIPAddressResponseEnvelope struct {
  431. XMLName xml.Name
  432. Body soapGetExternalIPAddressResponseBody `xml:"Body"`
  433. }
  434. type soapGetExternalIPAddressResponseBody struct {
  435. XMLName xml.Name
  436. GetExternalIPAddressResponse getExternalIPAddressResponse `xml:"GetExternalIPAddressResponse"`
  437. }
  438. type getExternalIPAddressResponse struct {
  439. NewExternalIPAddress string `xml:"NewExternalIPAddress"`
  440. }
  441. type soapErrorResponse struct {
  442. ErrorCode int `xml:"Body>Fault>detail>UPnPError>errorCode"`
  443. ErrorDescription string `xml:"Body>Fault>detail>UPnPError>errorDescription"`
  444. }
  445. // AddPortMapping adds a port mapping to the specified IGD service.
  446. func (s *IGDService) AddPortMapping(localIPAddress string, protocol Protocol, externalPort, internalPort int, description string, timeout int) error {
  447. tpl := `<u:AddPortMapping xmlns:u="%s">
  448. <NewRemoteHost></NewRemoteHost>
  449. <NewExternalPort>%d</NewExternalPort>
  450. <NewProtocol>%s</NewProtocol>
  451. <NewInternalPort>%d</NewInternalPort>
  452. <NewInternalClient>%s</NewInternalClient>
  453. <NewEnabled>1</NewEnabled>
  454. <NewPortMappingDescription>%s</NewPortMappingDescription>
  455. <NewLeaseDuration>%d</NewLeaseDuration>
  456. </u:AddPortMapping>`
  457. body := fmt.Sprintf(tpl, s.serviceURN, externalPort, protocol, internalPort, localIPAddress, description, timeout)
  458. response, err := soapRequest(s.serviceURL, s.serviceURN, "AddPortMapping", body)
  459. if err != nil && timeout > 0 {
  460. // Try to repair error code 725 - OnlyPermanentLeasesSupported
  461. envelope := &soapErrorResponse{}
  462. err = xml.Unmarshal(response, envelope)
  463. if err != nil {
  464. return err
  465. }
  466. if envelope.ErrorCode == 725 {
  467. return s.AddPortMapping(localIPAddress, protocol, externalPort, internalPort, description, 0)
  468. }
  469. }
  470. return err
  471. }
  472. // DeletePortMapping deletes a port mapping from the specified IGD service.
  473. func (s *IGDService) DeletePortMapping(protocol Protocol, externalPort int) error {
  474. tpl := `<u:DeletePortMapping xmlns:u="%s">
  475. <NewRemoteHost></NewRemoteHost>
  476. <NewExternalPort>%d</NewExternalPort>
  477. <NewProtocol>%s</NewProtocol>
  478. </u:DeletePortMapping>`
  479. body := fmt.Sprintf(tpl, s.serviceURN, externalPort, protocol)
  480. _, err := soapRequest(s.serviceURL, s.serviceURN, "DeletePortMapping", body)
  481. if err != nil {
  482. return err
  483. }
  484. return nil
  485. }
  486. // GetExternalIPAddress queries the IGD service for its external IP address.
  487. // Returns nil if the external IP address is invalid or undefined, along with
  488. // any relevant errors
  489. func (s *IGDService) GetExternalIPAddress() (net.IP, error) {
  490. tpl := `<u:GetExternalIPAddress xmlns:u="%s" />`
  491. body := fmt.Sprintf(tpl, s.serviceURN)
  492. response, err := soapRequest(s.serviceURL, s.serviceURN, "GetExternalIPAddress", body)
  493. if err != nil {
  494. return nil, err
  495. }
  496. envelope := &soapGetExternalIPAddressResponseEnvelope{}
  497. err = xml.Unmarshal(response, envelope)
  498. if err != nil {
  499. return nil, err
  500. }
  501. result := net.ParseIP(envelope.Body.GetExternalIPAddressResponse.NewExternalIPAddress)
  502. return result, nil
  503. }