upnp.go 14 KB

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