upnp.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  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. result := make([]*IGD, 0)
  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. results := make([]*IGD, 0)
  129. resultChannel := make(chan *IGD, 8)
  130. socket, err := net.ListenUDP("udp4", &net.UDPAddr{})
  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. results = append(results, result)
  174. }
  175. if debug {
  176. l.Debugln("Discovery for device type " + deviceType + " finished.")
  177. }
  178. return results
  179. }
  180. func handleSearchResponse(deviceType string, knownDevices []*IGD, resp []byte, length int, resultChannel chan<- *IGD, resultWaitGroup *sync.WaitGroup) {
  181. defer resultWaitGroup.Done() // Signal when we've finished processing
  182. if debug {
  183. l.Debugln("Handling UPnP response:\n\n" + string(resp[:length]))
  184. }
  185. reader := bufio.NewReader(bytes.NewBuffer(resp[:length]))
  186. request := &http.Request{}
  187. response, err := http.ReadResponse(reader, request)
  188. if err != nil {
  189. l.Infoln(err)
  190. return
  191. }
  192. respondingDeviceType := response.Header.Get("St")
  193. if respondingDeviceType != deviceType {
  194. l.Infoln("Unrecognized UPnP device of type " + respondingDeviceType)
  195. return
  196. }
  197. deviceDescriptionLocation := response.Header.Get("Location")
  198. if deviceDescriptionLocation == "" {
  199. l.Infoln("Invalid IGD response: no location specified.")
  200. return
  201. }
  202. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  203. if err != nil {
  204. l.Infoln("Invalid IGD location: " + err.Error())
  205. }
  206. deviceUSN := response.Header.Get("USN")
  207. if deviceUSN == "" {
  208. l.Infoln("Invalid IGD response: USN not specified.")
  209. return
  210. }
  211. deviceUUID := strings.TrimLeft(strings.Split(deviceUSN, "::")[0], "uuid:")
  212. 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)
  213. if !matched {
  214. l.Infoln("Invalid IGD response: invalid device UUID", deviceUUID, "(continuing anyway)")
  215. }
  216. // Don't re-add devices that are already known
  217. for _, knownDevice := range knownDevices {
  218. if deviceUUID == knownDevice.uuid {
  219. if debug {
  220. l.Debugln("Ignoring known device with UUID " + deviceUUID)
  221. }
  222. return
  223. }
  224. }
  225. response, err = http.Get(deviceDescriptionLocation)
  226. if err != nil {
  227. l.Infoln(err)
  228. return
  229. }
  230. defer response.Body.Close()
  231. if response.StatusCode >= 400 {
  232. l.Infoln(errors.New(response.Status))
  233. return
  234. }
  235. var upnpRoot upnpRoot
  236. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  237. if err != nil {
  238. l.Infoln(err)
  239. return
  240. }
  241. services, err := getServiceDescriptions(deviceDescriptionLocation, upnpRoot.Device)
  242. if err != nil {
  243. l.Infoln(err)
  244. return
  245. }
  246. // Figure out our IP number, on the network used to reach the IGD.
  247. // We do this in a fairly roundabout way by connecting to the IGD and
  248. // checking the address of the local end of the socket. I'm open to
  249. // suggestions on a better way to do this...
  250. localIPAddress, err := localIP(deviceDescriptionURL)
  251. if err != nil {
  252. l.Infoln(err)
  253. return
  254. }
  255. igd := &IGD{
  256. uuid: deviceUUID,
  257. friendlyName: upnpRoot.Device.FriendlyName,
  258. url: deviceDescriptionURL,
  259. services: services,
  260. localIPAddress: localIPAddress,
  261. }
  262. resultChannel <- igd
  263. if debug {
  264. l.Debugln("Finished handling of UPnP response.")
  265. }
  266. }
  267. func localIP(url *url.URL) (string, error) {
  268. conn, err := net.Dial("tcp", url.Host)
  269. if err != nil {
  270. return "", err
  271. }
  272. defer conn.Close()
  273. localIPAddress, _, err := net.SplitHostPort(conn.LocalAddr().String())
  274. if err != nil {
  275. return "", err
  276. }
  277. return localIPAddress, nil
  278. }
  279. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  280. result := make([]upnpDevice, 0)
  281. for _, dev := range d.Devices {
  282. if dev.DeviceType == deviceType {
  283. result = append(result, dev)
  284. }
  285. }
  286. return result
  287. }
  288. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  289. result := make([]upnpService, 0)
  290. for _, svc := range d.Services {
  291. if svc.ServiceType == serviceType {
  292. result = append(result, svc)
  293. }
  294. }
  295. return result
  296. }
  297. func getServiceDescriptions(rootURL string, device upnpDevice) ([]IGDService, error) {
  298. result := make([]IGDService, 0)
  299. if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  300. descriptions := getIGDServices(rootURL, device,
  301. "urn:schemas-upnp-org:device:WANDevice:1",
  302. "urn:schemas-upnp-org:device:WANConnectionDevice:1",
  303. []string{"urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"})
  304. result = append(result, descriptions...)
  305. } else if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:2" {
  306. descriptions := getIGDServices(rootURL, device,
  307. "urn:schemas-upnp-org:device:WANDevice:2",
  308. "urn:schemas-upnp-org:device:WANConnectionDevice:2",
  309. []string{"urn:schemas-upnp-org:service:WANIPConnection:2", "urn:schemas-upnp-org:service:WANPPPConnection:1"})
  310. result = append(result, descriptions...)
  311. } else {
  312. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  313. }
  314. if len(result) < 1 {
  315. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  316. } else {
  317. return result, nil
  318. }
  319. }
  320. func getIGDServices(rootURL string, device upnpDevice, wanDeviceURN string, wanConnectionURN string, serviceURNs []string) []IGDService {
  321. result := make([]IGDService, 0)
  322. devices := getChildDevices(device, wanDeviceURN)
  323. if len(devices) < 1 {
  324. l.Infoln("[" + rootURL + "] Malformed InternetGatewayDevice description: no WANDevices specified.")
  325. return result
  326. }
  327. for _, device := range devices {
  328. connections := getChildDevices(device, wanConnectionURN)
  329. if len(connections) < 1 {
  330. l.Infoln("[" + rootURL + "] Malformed " + wanDeviceURN + " description: no WANConnectionDevices specified.")
  331. }
  332. for _, connection := range connections {
  333. for _, serviceURN := range serviceURNs {
  334. services := getChildServices(connection, serviceURN)
  335. if len(services) < 1 && debug {
  336. l.Debugln("[" + rootURL + "] No services of type " + serviceURN + " found on connection.")
  337. }
  338. for _, service := range services {
  339. if len(service.ControlURL) == 0 {
  340. l.Infoln("[" + rootURL + "] Malformed " + service.ServiceType + " description: no control URL.")
  341. } else {
  342. u, _ := url.Parse(rootURL)
  343. replaceRawPath(u, service.ControlURL)
  344. if debug {
  345. l.Debugln("[" + rootURL + "] Found " + service.ServiceType + " with URL " + u.String())
  346. }
  347. service := IGDService{serviceID: service.ServiceID, serviceURL: u.String(), serviceURN: service.ServiceType}
  348. result = append(result, service)
  349. }
  350. }
  351. }
  352. }
  353. }
  354. return result
  355. }
  356. func replaceRawPath(u *url.URL, rp string) {
  357. var p, q string
  358. fs := strings.Split(rp, "?")
  359. p = fs[0]
  360. if len(fs) > 1 {
  361. q = fs[1]
  362. }
  363. if p[0] == '/' {
  364. u.Path = p
  365. } else {
  366. u.Path += p
  367. }
  368. u.RawQuery = q
  369. }
  370. func soapRequest(url, device, function, message string) ([]byte, error) {
  371. tpl := ` <?xml version="1.0" ?>
  372. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  373. <s:Body>%s</s:Body>
  374. </s:Envelope>
  375. `
  376. var resp []byte
  377. body := fmt.Sprintf(tpl, message)
  378. req, err := http.NewRequest("POST", url, strings.NewReader(body))
  379. if err != nil {
  380. return resp, err
  381. }
  382. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  383. req.Header.Set("User-Agent", "syncthing/1.0")
  384. req.Header.Set("SOAPAction", fmt.Sprintf(`"%s#%s"`, device, function))
  385. req.Header.Set("Connection", "Close")
  386. req.Header.Set("Cache-Control", "no-cache")
  387. req.Header.Set("Pragma", "no-cache")
  388. if debug {
  389. l.Debugln("SOAP Request URL: " + url)
  390. l.Debugln("SOAP Action: " + req.Header.Get("SOAPAction"))
  391. l.Debugln("SOAP Request:\n\n" + body)
  392. }
  393. r, err := http.DefaultClient.Do(req)
  394. if err != nil {
  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. }