upnp.go 12 KB

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