upnp.go 17 KB

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