upnp.go 16 KB

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