upnp.go 16 KB

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