upnp.go 16 KB

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