upnp.go 16 KB

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