upnp.go 14 KB

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