upnp.go 17 KB

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