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