upnp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // Ported from https://github.com/syncthing/syncthing/tree/master/lib/upnp
  4. // Adapted from https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/IGD.go
  5. // Copyright (c) 2010 Jack Palevich (https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/LICENSE)
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following disclaimer
  15. // in the documentation and/or other materials provided with the
  16. // distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived from
  19. // this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. // Package upnp implements UPnP InternetGatewayDevice discovery, querying, and port mapping.
  33. package upnp
  34. import (
  35. "bufio"
  36. "bytes"
  37. "encoding/xml"
  38. "errors"
  39. "fmt"
  40. "io/ioutil"
  41. "net"
  42. "net/http"
  43. "net/url"
  44. "runtime"
  45. "strings"
  46. "sync"
  47. "time"
  48. "github.com/anacrolix/log"
  49. )
  50. var (
  51. // Debug Set this to true to print debug information
  52. Debug = true
  53. )
  54. func init() {
  55. Register(Discover)
  56. }
  57. type upnpService struct {
  58. ID string `xml:"serviceId"`
  59. Type string `xml:"serviceType"`
  60. ControlURL string `xml:"controlURL"`
  61. }
  62. type upnpDevice struct {
  63. DeviceType string `xml:"deviceType"`
  64. FriendlyName string `xml:"friendlyName"`
  65. Devices []upnpDevice `xml:"deviceList>device"`
  66. Services []upnpService `xml:"serviceList>service"`
  67. }
  68. type upnpRoot struct {
  69. Device upnpDevice `xml:"device"`
  70. }
  71. // Discover discovers UPnP InternetGatewayDevices.
  72. // The order in which the devices appear in the results list is not deterministic.
  73. func Discover(renewal, timeout time.Duration, logger log.Logger) []Device {
  74. log := levelLogger{logger}
  75. var results []Device
  76. interfaces, err := net.Interfaces()
  77. if err != nil {
  78. log.Errorf("Listing network interfaces: %s", err)
  79. return results
  80. }
  81. resultChan := make(chan Device)
  82. wg := &sync.WaitGroup{}
  83. for _, intf := range interfaces {
  84. // Interface flags seem to always be 0 on Windows
  85. if runtime.GOOS != "windows" && (intf.Flags&net.FlagUp == 0 || intf.Flags&net.FlagMulticast == 0) {
  86. continue
  87. }
  88. for _, deviceType := range []string{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:device:InternetGatewayDevice:2"} {
  89. wg.Add(1)
  90. go func(intf net.Interface, deviceType string) {
  91. discover(&intf, deviceType, timeout, resultChan, log)
  92. wg.Done()
  93. }(intf, deviceType)
  94. }
  95. }
  96. go func() {
  97. wg.Wait()
  98. close(resultChan)
  99. }()
  100. seenResults := make(map[string]bool)
  101. nextResult:
  102. for result := range resultChan {
  103. if seenResults[result.ID()] {
  104. if Debug {
  105. log.Debugf("Skipping duplicate result %s", result.ID())
  106. }
  107. continue nextResult
  108. }
  109. results = append(results, result)
  110. seenResults[result.ID()] = true
  111. log.Debugf("UPnP discovery result %s", result.ID())
  112. }
  113. return results
  114. }
  115. // Search for UPnP InternetGatewayDevices for <timeout> seconds, ignoring responses from any devices listed in knownDevices.
  116. // The order in which the devices appear in the result list is not deterministic
  117. func discover(intf *net.Interface, deviceType string, timeout time.Duration, results chan<- Device, log levelLogger) {
  118. ssdp := &net.UDPAddr{IP: []byte{239, 255, 255, 250}, Port: 1900}
  119. tpl := `M-SEARCH * HTTP/1.1
  120. HOST: 239.255.255.250:1900
  121. ST: %s
  122. MAN: "ssdp:discover"
  123. MX: %d
  124. USER-AGENT: go-torrent/1.0
  125. `
  126. searchStr := fmt.Sprintf(tpl, deviceType, timeout/time.Second)
  127. search := []byte(strings.Replace(searchStr, "\n", "\r\n", -1))
  128. if Debug {
  129. log.Debugf("Starting discovery of device type %s on %s", deviceType, intf.Name)
  130. }
  131. socket, err := net.ListenMulticastUDP("udp4", intf, &net.UDPAddr{IP: ssdp.IP})
  132. if err != nil {
  133. if Debug {
  134. log.Debugf("UPnP discovery: listening to udp multicast: %s", err)
  135. }
  136. return
  137. }
  138. defer socket.Close() // Make sure our socket gets closed
  139. err = socket.SetDeadline(time.Now().Add(timeout))
  140. if err != nil {
  141. if Debug {
  142. log.Debugf("UPnP discovery: setting socket deadline: %s", err)
  143. }
  144. return
  145. }
  146. if Debug {
  147. log.Debugf("Sending search request for device type %s on %s", deviceType, intf.Name)
  148. }
  149. _, err = socket.WriteTo(search, ssdp)
  150. if err != nil {
  151. if e, ok := err.(net.Error); !ok || !e.Timeout() {
  152. if Debug {
  153. log.Debugf("UPnP discovery: sending search request: %s", err)
  154. }
  155. }
  156. return
  157. }
  158. if Debug {
  159. log.Debugf("Listening for UPnP response for device type %s on %s", deviceType, intf.Name)
  160. }
  161. // Listen for responses until a timeout is reached
  162. for {
  163. resp := make([]byte, 65536)
  164. n, _, err := socket.ReadFrom(resp)
  165. if err != nil {
  166. if e, ok := err.(net.Error); !ok || !e.Timeout() {
  167. log.Errorf("UPnP read: %s", err) //legitimate error, not a timeout.
  168. }
  169. break
  170. }
  171. igds, err := parseResponse(deviceType, resp[:n], log)
  172. if err != nil {
  173. // Do we need to print debug info for any device?
  174. // log.Errorf("UPnP parse: %s", err)
  175. continue
  176. }
  177. for _, igd := range igds {
  178. igd := igd // Copy before sending pointer to the channel.
  179. results <- &igd
  180. }
  181. }
  182. if Debug {
  183. log.Debugf("Discovery for device type %s on %s finished.", deviceType, intf.Name)
  184. }
  185. }
  186. func parseResponse(deviceType string, resp []byte, log levelLogger) ([]IGDService, error) {
  187. if Debug {
  188. log.Debugf("Handling UPnP response:\n\n%s", string(resp))
  189. }
  190. reader := bufio.NewReader(bytes.NewBuffer(resp))
  191. request := &http.Request{}
  192. response, err := http.ReadResponse(reader, request)
  193. if err != nil {
  194. return nil, err
  195. }
  196. respondingDeviceType := response.Header.Get("St")
  197. if respondingDeviceType != deviceType {
  198. return nil, errors.New("unrecognized UPnP device of type " + respondingDeviceType)
  199. }
  200. deviceDescriptionLocation := response.Header.Get("Location")
  201. if deviceDescriptionLocation == "" {
  202. return nil, errors.New("invalid IGD response: no location specified")
  203. }
  204. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  205. if err != nil {
  206. log.Errorf("Invalid IGD location: %s", err.Error())
  207. }
  208. deviceUSN := response.Header.Get("USN")
  209. if deviceUSN == "" {
  210. return nil, errors.New("invalid IGD response: USN not specified")
  211. }
  212. deviceUUID := strings.TrimPrefix(strings.Split(deviceUSN, "::")[0], "uuid:")
  213. response, err = http.Get(deviceDescriptionLocation)
  214. if err != nil {
  215. return nil, err
  216. }
  217. defer response.Body.Close()
  218. if response.StatusCode >= 400 {
  219. return nil, errors.New("bad status code:" + response.Status)
  220. }
  221. var upnpRoot upnpRoot
  222. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  223. if err != nil {
  224. return nil, err
  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. return nil, err
  233. }
  234. services, err := getServiceDescriptions(deviceUUID, localIPAddress, deviceDescriptionLocation, upnpRoot.Device, log)
  235. if err != nil {
  236. return nil, err
  237. }
  238. return services, nil
  239. }
  240. func localIP(url *url.URL) (net.IP, error) {
  241. conn, err := net.DialTimeout("tcp", url.Host, time.Second)
  242. if err != nil {
  243. return nil, err
  244. }
  245. defer conn.Close()
  246. localIPAddress, _, err := net.SplitHostPort(conn.LocalAddr().String())
  247. if err != nil {
  248. return nil, err
  249. }
  250. return net.ParseIP(localIPAddress), nil
  251. }
  252. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  253. var result []upnpDevice
  254. for _, dev := range d.Devices {
  255. if dev.DeviceType == deviceType {
  256. result = append(result, dev)
  257. }
  258. }
  259. return result
  260. }
  261. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  262. var result []upnpService
  263. for _, service := range d.Services {
  264. if service.Type == serviceType {
  265. result = append(result, service)
  266. }
  267. }
  268. return result
  269. }
  270. func getServiceDescriptions(deviceUUID string, localIPAddress net.IP, rootURL string, device upnpDevice, ll levelLogger) ([]IGDService, error) {
  271. var result []IGDService
  272. if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  273. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  274. "urn:schemas-upnp-org:device:WANDevice:1",
  275. "urn:schemas-upnp-org:device:WANConnectionDevice:1",
  276. []string{"urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"},
  277. ll)
  278. result = append(result, descriptions...)
  279. } else if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:2" {
  280. descriptions := getIGDServices(deviceUUID, localIPAddress, rootURL, device,
  281. "urn:schemas-upnp-org:device:WANDevice:2",
  282. "urn:schemas-upnp-org:device:WANConnectionDevice:2",
  283. []string{"urn:schemas-upnp-org:service:WANIPConnection:2", "urn:schemas-upnp-org:service:WANPPPConnection:2"},
  284. ll)
  285. result = append(result, descriptions...)
  286. } else {
  287. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  288. }
  289. if len(result) < 1 {
  290. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  291. }
  292. return result, nil
  293. }
  294. func getIGDServices(
  295. deviceUUID string,
  296. localIPAddress net.IP,
  297. rootURL string,
  298. device upnpDevice,
  299. wanDeviceURN string,
  300. wanConnectionURN string,
  301. URNs []string,
  302. logger levelLogger,
  303. ) (ret []IGDService) {
  304. devices := getChildDevices(device, wanDeviceURN)
  305. if len(devices) < 1 {
  306. if Debug {
  307. logger.Debugf("%s - malformed InternetGatewayDevice description: no WANDevices specified.", rootURL)
  308. }
  309. return
  310. }
  311. for _, device := range devices {
  312. connections := getChildDevices(device, wanConnectionURN)
  313. if len(connections) < 1 {
  314. if Debug {
  315. logger.Debugf("%s - malformed %s description: no WANConnectionDevices specified.", rootURL, wanDeviceURN)
  316. }
  317. }
  318. for _, connection := range connections {
  319. for _, URN := range URNs {
  320. services := getChildServices(connection, URN)
  321. if Debug {
  322. logger.Debugf("%s - no services of type %s found on connection.", rootURL, URN)
  323. }
  324. for _, service := range services {
  325. if len(service.ControlURL) == 0 {
  326. if Debug {
  327. logger.Debugf("%s- malformed %s description: no control URL.", rootURL, service.Type)
  328. }
  329. } else {
  330. u, _ := url.Parse(rootURL)
  331. replaceRawPath(u, service.ControlURL)
  332. if Debug {
  333. logger.Debugf("%s- found %s with URL %s", rootURL, service.Type, u)
  334. }
  335. service := IGDService{
  336. UUID: deviceUUID,
  337. Device: device,
  338. ServiceID: service.ID,
  339. URL: u.String(),
  340. URN: service.Type,
  341. LocalIP: localIPAddress,
  342. ll: logger,
  343. }
  344. ret = append(ret, service)
  345. }
  346. }
  347. }
  348. }
  349. }
  350. return
  351. }
  352. func replaceRawPath(u *url.URL, rp string) {
  353. asURL, err := url.Parse(rp)
  354. if err != nil {
  355. return
  356. } else if asURL.IsAbs() {
  357. u.Path = asURL.Path
  358. u.RawQuery = asURL.RawQuery
  359. } else {
  360. var p, q string
  361. fs := strings.Split(rp, "?")
  362. p = fs[0]
  363. if len(fs) > 1 {
  364. q = fs[1]
  365. }
  366. if p[0] == '/' {
  367. u.Path = p
  368. } else {
  369. u.Path += p
  370. }
  371. u.RawQuery = q
  372. }
  373. }
  374. func soapRequest(url, service, function, message string, log levelLogger) ([]byte, error) {
  375. tpl := `<?xml version="1.0" ?>
  376. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  377. <s:Body>%s</s:Body>
  378. </s:Envelope>
  379. `
  380. var resp []byte
  381. body := fmt.Sprintf(tpl, message)
  382. req, err := http.NewRequest("POST", url, strings.NewReader(body))
  383. if err != nil {
  384. return resp, err
  385. }
  386. req.Close = true
  387. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  388. req.Header.Set("User-Agent", "go-torrent/1.0")
  389. req.Header["SOAPAction"] = []string{fmt.Sprintf(`"%s#%s"`, service, function)} // Enforce capitalization in header-entry for sensitive routers. See issue #1696
  390. req.Header.Set("Connection", "Close")
  391. req.Header.Set("Cache-Control", "no-cache")
  392. req.Header.Set("Pragma", "no-cache")
  393. if Debug {
  394. log.Debugf("SOAP Request URL: %s", url)
  395. log.Debugf("SOAP Action: %s", req.Header.Get("SOAPAction"))
  396. log.Debugf("SOAP Request:\n\n%s", body)
  397. }
  398. r, err := http.DefaultClient.Do(req)
  399. if err != nil {
  400. log.Errorf("SOAP do: %s", err)
  401. return resp, err
  402. }
  403. resp, _ = ioutil.ReadAll(r.Body)
  404. if Debug {
  405. log.Debugf("SOAP Response: %s\n\n%s\n\n", r.Status, resp)
  406. }
  407. r.Body.Close()
  408. if r.StatusCode >= 400 {
  409. return resp, errors.New(function + ": " + r.Status)
  410. }
  411. return resp, nil
  412. }
  413. type soapGetExternalIPAddressResponseEnvelope struct {
  414. XMLName xml.Name
  415. Body soapGetExternalIPAddressResponseBody `xml:"Body"`
  416. }
  417. type soapGetExternalIPAddressResponseBody struct {
  418. XMLName xml.Name
  419. GetExternalIPAddressResponse getExternalIPAddressResponse `xml:"GetExternalIPAddressResponse"`
  420. }
  421. type getExternalIPAddressResponse struct {
  422. NewExternalIPAddress string `xml:"NewExternalIPAddress"`
  423. }
  424. type soapErrorResponse struct {
  425. ErrorCode int `xml:"Body>Fault>detail>UPnPError>errorCode"`
  426. ErrorDescription string `xml:"Body>Fault>detail>UPnPError>errorDescription"`
  427. }