upnp.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. "regexp"
  44. "runtime"
  45. "strings"
  46. "time"
  47. "github.com/syncthing/syncthing/lib/dialer"
  48. "github.com/syncthing/syncthing/lib/nat"
  49. "github.com/syncthing/syncthing/lib/sync"
  50. )
  51. func init() {
  52. nat.Register(Discover)
  53. }
  54. type upnpService struct {
  55. ID string `xml:"serviceId"`
  56. Type string `xml:"serviceType"`
  57. ControlURL string `xml:"controlURL"`
  58. }
  59. type upnpDevice struct {
  60. DeviceType string `xml:"deviceType"`
  61. FriendlyName string `xml:"friendlyName"`
  62. Devices []upnpDevice `xml:"deviceList>device"`
  63. Services []upnpService `xml:"serviceList>service"`
  64. }
  65. type upnpRoot struct {
  66. Device upnpDevice `xml:"device"`
  67. }
  68. // Discover discovers UPnP InternetGatewayDevices.
  69. // The order in which the devices appear in the results list is not deterministic.
  70. func Discover(renewal, timeout time.Duration) []nat.Device {
  71. var results []nat.Device
  72. interfaces, err := net.Interfaces()
  73. if err != nil {
  74. l.Infoln("Listing network interfaces:", err)
  75. return results
  76. }
  77. resultChan := make(chan IGD)
  78. wg := sync.NewWaitGroup()
  79. for _, intf := range interfaces {
  80. // Interface flags seem to always be 0 on Windows
  81. if runtime.GOOS != "windows" && (intf.Flags&net.FlagUp == 0 || intf.Flags&net.FlagMulticast == 0) {
  82. continue
  83. }
  84. for _, deviceType := range []string{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:device:InternetGatewayDevice:2"} {
  85. wg.Add(1)
  86. go func(intf net.Interface, deviceType string) {
  87. discover(&intf, deviceType, timeout, resultChan)
  88. wg.Done()
  89. }(intf, deviceType)
  90. }
  91. }
  92. go func() {
  93. wg.Wait()
  94. close(resultChan)
  95. }()
  96. seenResults := make(map[string]bool)
  97. nextResult:
  98. for result := range resultChan {
  99. if seenResults[result.ID()] {
  100. l.Debugf("Skipping duplicate result %s with services:", result.uuid)
  101. for _, service := range result.services {
  102. l.Debugf("* [%s] %s", service.ID, service.URL)
  103. }
  104. continue nextResult
  105. }
  106. result := result // Reallocate as we need to keep a pointer
  107. results = append(results, &result)
  108. seenResults[result.ID()] = true
  109. l.Debugf("UPnP discovery result %s with services:", result.uuid)
  110. for _, service := range result.services {
  111. l.Debugf("* [%s] %s", service.ID, service.URL)
  112. }
  113. }
  114. return results
  115. }
  116. // Search for UPnP InternetGatewayDevices for <timeout> seconds, ignoring responses from any devices listed in knownDevices.
  117. // The order in which the devices appear in the result list is not deterministic
  118. func discover(intf *net.Interface, deviceType string, timeout time.Duration, results chan<- IGD) {
  119. ssdp := &net.UDPAddr{IP: []byte{239, 255, 255, 250}, Port: 1900}
  120. tpl := `M-SEARCH * HTTP/1.1
  121. HOST: 239.255.255.250:1900
  122. ST: %s
  123. MAN: "ssdp:discover"
  124. MX: %d
  125. USER-AGENT: syncthing/1.0
  126. `
  127. searchStr := fmt.Sprintf(tpl, deviceType, timeout/time.Second)
  128. search := []byte(strings.Replace(searchStr, "\n", "\r\n", -1))
  129. l.Debugln("Starting discovery of device type", deviceType, "on", intf.Name)
  130. socket, err := net.ListenMulticastUDP("udp4", intf, &net.UDPAddr{IP: ssdp.IP})
  131. if err != nil {
  132. l.Debugln(err)
  133. return
  134. }
  135. defer socket.Close() // Make sure our socket gets closed
  136. err = socket.SetDeadline(time.Now().Add(timeout))
  137. if err != nil {
  138. l.Infoln(err)
  139. return
  140. }
  141. l.Debugln("Sending search request for device type", deviceType, "on", intf.Name)
  142. _, err = socket.WriteTo(search, ssdp)
  143. if err != nil {
  144. l.Infoln(err)
  145. return
  146. }
  147. l.Debugln("Listening for UPnP response for device type", deviceType, "on", intf.Name)
  148. // Listen for responses until a timeout is reached
  149. for {
  150. resp := make([]byte, 65536)
  151. n, _, err := socket.ReadFrom(resp)
  152. if err != nil {
  153. if e, ok := err.(net.Error); !ok || !e.Timeout() {
  154. l.Infoln("UPnP read:", err) //legitimate error, not a timeout.
  155. }
  156. break
  157. }
  158. igd, err := parseResponse(deviceType, resp[:n])
  159. if err != nil {
  160. l.Infoln("UPnP parse:", err)
  161. continue
  162. }
  163. results <- igd
  164. }
  165. l.Debugln("Discovery for device type", deviceType, "on", intf.Name, "finished.")
  166. }
  167. func parseResponse(deviceType string, resp []byte) (IGD, error) {
  168. l.Debugln("Handling UPnP response:\n\n" + string(resp))
  169. reader := bufio.NewReader(bytes.NewBuffer(resp))
  170. request := &http.Request{}
  171. response, err := http.ReadResponse(reader, request)
  172. if err != nil {
  173. return IGD{}, err
  174. }
  175. respondingDeviceType := response.Header.Get("St")
  176. if respondingDeviceType != deviceType {
  177. return IGD{}, errors.New("unrecognized UPnP device of type " + respondingDeviceType)
  178. }
  179. deviceDescriptionLocation := response.Header.Get("Location")
  180. if deviceDescriptionLocation == "" {
  181. return IGD{}, errors.New("invalid IGD response: no location specified")
  182. }
  183. deviceDescriptionURL, err := url.Parse(deviceDescriptionLocation)
  184. if err != nil {
  185. l.Infoln("Invalid IGD location: " + err.Error())
  186. }
  187. deviceUSN := response.Header.Get("USN")
  188. if deviceUSN == "" {
  189. return IGD{}, errors.New("invalid IGD response: USN not specified")
  190. }
  191. deviceUUID := strings.TrimPrefix(strings.Split(deviceUSN, "::")[0], "uuid:")
  192. matched, _ := 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)
  193. if !matched {
  194. l.Infoln("Invalid IGD response: invalid device UUID", deviceUUID, "(continuing anyway)")
  195. }
  196. response, err = http.Get(deviceDescriptionLocation)
  197. if err != nil {
  198. return IGD{}, err
  199. }
  200. defer response.Body.Close()
  201. if response.StatusCode >= 400 {
  202. return IGD{}, errors.New("bad status code:" + response.Status)
  203. }
  204. var upnpRoot upnpRoot
  205. err = xml.NewDecoder(response.Body).Decode(&upnpRoot)
  206. if err != nil {
  207. return IGD{}, err
  208. }
  209. services, err := getServiceDescriptions(deviceDescriptionLocation, upnpRoot.Device)
  210. if err != nil {
  211. return IGD{}, err
  212. }
  213. // Figure out our IP number, on the network used to reach the IGD.
  214. // We do this in a fairly roundabout way by connecting to the IGD and
  215. // checking the address of the local end of the socket. I'm open to
  216. // suggestions on a better way to do this...
  217. localIPAddress, err := localIP(deviceDescriptionURL)
  218. if err != nil {
  219. return IGD{}, err
  220. }
  221. return IGD{
  222. uuid: deviceUUID,
  223. friendlyName: upnpRoot.Device.FriendlyName,
  224. url: deviceDescriptionURL,
  225. services: services,
  226. localIPAddress: localIPAddress,
  227. }, nil
  228. }
  229. func localIP(url *url.URL) (net.IP, error) {
  230. conn, err := dialer.DialTimeout("tcp", url.Host, time.Second)
  231. if err != nil {
  232. return nil, err
  233. }
  234. defer conn.Close()
  235. localIPAddress, _, err := net.SplitHostPort(conn.LocalAddr().String())
  236. if err != nil {
  237. return nil, err
  238. }
  239. return net.ParseIP(localIPAddress), nil
  240. }
  241. func getChildDevices(d upnpDevice, deviceType string) []upnpDevice {
  242. var result []upnpDevice
  243. for _, dev := range d.Devices {
  244. if dev.DeviceType == deviceType {
  245. result = append(result, dev)
  246. }
  247. }
  248. return result
  249. }
  250. func getChildServices(d upnpDevice, serviceType string) []upnpService {
  251. var result []upnpService
  252. for _, service := range d.Services {
  253. if service.Type == serviceType {
  254. result = append(result, service)
  255. }
  256. }
  257. return result
  258. }
  259. func getServiceDescriptions(rootURL string, device upnpDevice) ([]IGDService, error) {
  260. var result []IGDService
  261. if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  262. descriptions := getIGDServices(rootURL, device,
  263. "urn:schemas-upnp-org:device:WANDevice:1",
  264. "urn:schemas-upnp-org:device:WANConnectionDevice:1",
  265. []string{"urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"})
  266. result = append(result, descriptions...)
  267. } else if device.DeviceType == "urn:schemas-upnp-org:device:InternetGatewayDevice:2" {
  268. descriptions := getIGDServices(rootURL, device,
  269. "urn:schemas-upnp-org:device:WANDevice:2",
  270. "urn:schemas-upnp-org:device:WANConnectionDevice:2",
  271. []string{"urn:schemas-upnp-org:service:WANIPConnection:2", "urn:schemas-upnp-org:service:WANPPPConnection:2"})
  272. result = append(result, descriptions...)
  273. } else {
  274. return result, errors.New("[" + rootURL + "] Malformed root device description: not an InternetGatewayDevice.")
  275. }
  276. if len(result) < 1 {
  277. return result, errors.New("[" + rootURL + "] Malformed device description: no compatible service descriptions found.")
  278. }
  279. return result, nil
  280. }
  281. func getIGDServices(rootURL string, device upnpDevice, wanDeviceURN string, wanConnectionURN string, URNs []string) []IGDService {
  282. var result []IGDService
  283. devices := getChildDevices(device, wanDeviceURN)
  284. if len(devices) < 1 {
  285. l.Infoln(rootURL, "- malformed InternetGatewayDevice description: no WANDevices specified.")
  286. return result
  287. }
  288. for _, device := range devices {
  289. connections := getChildDevices(device, wanConnectionURN)
  290. if len(connections) < 1 {
  291. l.Infoln(rootURL, "- malformed ", wanDeviceURN, "description: no WANConnectionDevices specified.")
  292. }
  293. for _, connection := range connections {
  294. for _, URN := range URNs {
  295. services := getChildServices(connection, URN)
  296. l.Debugln(rootURL, "- no services of type", URN, " found on connection.")
  297. for _, service := range services {
  298. if len(service.ControlURL) == 0 {
  299. l.Infoln(rootURL+"- malformed", service.Type, "description: no control URL.")
  300. } else {
  301. u, _ := url.Parse(rootURL)
  302. replaceRawPath(u, service.ControlURL)
  303. l.Debugln(rootURL, "- found", service.Type, "with URL", u)
  304. service := IGDService{ID: service.ID, URL: u.String(), URN: service.Type}
  305. result = append(result, service)
  306. }
  307. }
  308. }
  309. }
  310. }
  311. return result
  312. }
  313. func replaceRawPath(u *url.URL, rp string) {
  314. asURL, err := url.Parse(rp)
  315. if err != nil {
  316. return
  317. } else if asURL.IsAbs() {
  318. u.Path = asURL.Path
  319. u.RawQuery = asURL.RawQuery
  320. } else {
  321. var p, q string
  322. fs := strings.Split(rp, "?")
  323. p = fs[0]
  324. if len(fs) > 1 {
  325. q = fs[1]
  326. }
  327. if p[0] == '/' {
  328. u.Path = p
  329. } else {
  330. u.Path += p
  331. }
  332. u.RawQuery = q
  333. }
  334. }
  335. func soapRequest(url, service, function, message string) ([]byte, error) {
  336. tpl := `<?xml version="1.0" ?>
  337. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  338. <s:Body>%s</s:Body>
  339. </s:Envelope>
  340. `
  341. var resp []byte
  342. body := fmt.Sprintf(tpl, message)
  343. req, err := http.NewRequest("POST", url, strings.NewReader(body))
  344. if err != nil {
  345. return resp, err
  346. }
  347. req.Close = true
  348. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  349. req.Header.Set("User-Agent", "syncthing/1.0")
  350. req.Header["SOAPAction"] = []string{fmt.Sprintf(`"%s#%s"`, service, function)} // Enforce capitalization in header-entry for sensitive routers. See issue #1696
  351. req.Header.Set("Connection", "Close")
  352. req.Header.Set("Cache-Control", "no-cache")
  353. req.Header.Set("Pragma", "no-cache")
  354. l.Debugln("SOAP Request URL: " + url)
  355. l.Debugln("SOAP Action: " + req.Header.Get("SOAPAction"))
  356. l.Debugln("SOAP Request:\n\n" + body)
  357. r, err := http.DefaultClient.Do(req)
  358. if err != nil {
  359. l.Debugln(err)
  360. return resp, err
  361. }
  362. resp, _ = ioutil.ReadAll(r.Body)
  363. l.Debugf("SOAP Response: %s\n\n%s\n\n", r.Status, resp)
  364. r.Body.Close()
  365. if r.StatusCode >= 400 {
  366. return resp, errors.New(function + ": " + r.Status)
  367. }
  368. return resp, nil
  369. }
  370. type soapGetExternalIPAddressResponseEnvelope struct {
  371. XMLName xml.Name
  372. Body soapGetExternalIPAddressResponseBody `xml:"Body"`
  373. }
  374. type soapGetExternalIPAddressResponseBody struct {
  375. XMLName xml.Name
  376. GetExternalIPAddressResponse getExternalIPAddressResponse `xml:"GetExternalIPAddressResponse"`
  377. }
  378. type getExternalIPAddressResponse struct {
  379. NewExternalIPAddress string `xml:"NewExternalIPAddress"`
  380. }
  381. type soapErrorResponse struct {
  382. ErrorCode int `xml:"Body>Fault>detail>UPnPError>errorCode"`
  383. ErrorDescription string `xml:"Body>Fault>detail>UPnPError>errorDescription"`
  384. }