PageRenderTime 137ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/upnp/upnp.go

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