upnp.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. // Adapted from https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/IGD.go
  16. // Copyright (c) 2010 Jack Palevich (https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/LICENSE)
  17. // Package upnp implements UPnP Internet Gateway upnpDevice port mappings
  18. package upnp
  19. import (
  20. "bufio"
  21. "bytes"
  22. "encoding/xml"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "strings"
  31. "time"
  32. )
  33. type IGD struct {
  34. serviceURL string
  35. device string
  36. ourIP string
  37. }
  38. type Protocol string
  39. const (
  40. TCP Protocol = "TCP"
  41. UDP = "UDP"
  42. )
  43. type upnpService struct {
  44. ServiceType string `xml:"serviceType"`
  45. ControlURL string `xml:"controlURL"`
  46. }
  47. type upnpDevice struct {
  48. DeviceType string `xml:"deviceType"`
  49. Devices []upnpDevice `xml:"deviceList>device"`
  50. Services []upnpService `xml:"serviceList>service"`
  51. }
  52. type upnpRoot struct {
  53. Device upnpDevice `xml:"device"`
  54. }
  55. func Discover() (*IGD, error) {
  56. ssdp := &net.UDPAddr{IP: []byte{239, 255, 255, 250}, Port: 1900}
  57. socket, err := net.ListenUDP("udp4", &net.UDPAddr{})
  58. if err != nil {
  59. return nil, err
  60. }
  61. defer socket.Close()
  62. err = socket.SetDeadline(time.Now().Add(3 * time.Second))
  63. if err != nil {
  64. return nil, err
  65. }
  66. searchStr := `M-SEARCH * HTTP/1.1
  67. Host: 239.255.255.250:1900
  68. St: urn:schemas-upnp-org:device:InternetGatewayDevice:1
  69. Man: "ssdp:discover"
  70. Mx: 3
  71. `
  72. search := []byte(strings.Replace(searchStr, "\n", "\r\n", -1))
  73. _, err = socket.WriteTo(search, ssdp)
  74. if err != nil {
  75. return nil, err
  76. }
  77. resp := make([]byte, 1500)
  78. n, _, err := socket.ReadFrom(resp)
  79. if err != nil {
  80. return nil, err
  81. }
  82. if debug {
  83. l.Debugln(string(resp[:n]))
  84. }
  85. reader := bufio.NewReader(bytes.NewBuffer(resp[:n]))
  86. request := &http.Request{}
  87. response, err := http.ReadResponse(reader, request)
  88. if err != nil {
  89. return nil, err
  90. }
  91. if response.Header.Get("St") != "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  92. return nil, errors.New("no igd")
  93. }
  94. locURL := response.Header.Get("Location")
  95. if locURL == "" {
  96. return nil, errors.New("no location")
  97. }
  98. serviceURL, device, err := getServiceURL(locURL)
  99. if err != nil {
  100. return nil, err
  101. }
  102. // Figure out our IP number, on the network used to reach the IGD. We
  103. // do this in a fairly roundabout way by connecting to the IGD and
  104. // checking the address of the local end of the socket. I'm open to
  105. // suggestions on a better way to do this...
  106. ourIP, err := localIP(locURL)
  107. if err != nil {
  108. return nil, err
  109. }
  110. igd := &IGD{
  111. serviceURL: serviceURL,
  112. device: device,
  113. ourIP: ourIP,
  114. }
  115. return igd, nil
  116. }
  117. func localIP(tgt string) (string, error) {
  118. url, err := url.Parse(tgt)
  119. if err != nil {
  120. return "", err
  121. }
  122. conn, err := net.Dial("tcp", url.Host)
  123. if err != nil {
  124. return "", err
  125. }
  126. defer conn.Close()
  127. ourIP, _, err := net.SplitHostPort(conn.LocalAddr().String())
  128. if err != nil {
  129. return "", err
  130. }
  131. return ourIP, nil
  132. }
  133. func getChildDevice(d upnpDevice, deviceType string) (upnpDevice, bool) {
  134. for _, dev := range d.Devices {
  135. if dev.DeviceType == deviceType {
  136. return dev, true
  137. }
  138. }
  139. return upnpDevice{}, false
  140. }
  141. func getChildService(d upnpDevice, serviceType string) (upnpService, bool) {
  142. for _, svc := range d.Services {
  143. if svc.ServiceType == serviceType {
  144. return svc, true
  145. }
  146. }
  147. return upnpService{}, false
  148. }
  149. func getServiceURL(rootURL string) (string, string, error) {
  150. r, err := http.Get(rootURL)
  151. if err != nil {
  152. return "", "", err
  153. }
  154. defer r.Body.Close()
  155. if r.StatusCode >= 400 {
  156. return "", "", errors.New(r.Status)
  157. }
  158. return getServiceURLReader(rootURL, r.Body)
  159. }
  160. func getServiceURLReader(rootURL string, r io.Reader) (string, string, error) {
  161. var upnpRoot upnpRoot
  162. err := xml.NewDecoder(r).Decode(&upnpRoot)
  163. if err != nil {
  164. return "", "", err
  165. }
  166. dev := upnpRoot.Device
  167. if dev.DeviceType != "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
  168. return "", "", errors.New("No InternetGatewayDevice")
  169. }
  170. dev, ok := getChildDevice(dev, "urn:schemas-upnp-org:device:WANDevice:1")
  171. if !ok {
  172. return "", "", errors.New("No WANDevice")
  173. }
  174. dev, ok = getChildDevice(dev, "urn:schemas-upnp-org:device:WANConnectionDevice:1")
  175. if !ok {
  176. return "", "", errors.New("No WANConnectionDevice")
  177. }
  178. device := "urn:schemas-upnp-org:service:WANIPConnection:1"
  179. svc, ok := getChildService(dev, device)
  180. if !ok {
  181. device = "urn:schemas-upnp-org:service:WANPPPConnection:1"
  182. }
  183. svc, ok = getChildService(dev, device)
  184. if !ok {
  185. return "", "", errors.New("No WANIPConnection nor WANPPPConnection")
  186. }
  187. if len(svc.ControlURL) == 0 {
  188. return "", "", errors.New("no controlURL")
  189. }
  190. u, _ := url.Parse(rootURL)
  191. replaceRawPath(u, svc.ControlURL)
  192. return u.String(), device, nil
  193. }
  194. func replaceRawPath(u *url.URL, rp string) {
  195. var p, q string
  196. fs := strings.Split(rp, "?")
  197. p = fs[0]
  198. if len(fs) > 1 {
  199. q = fs[1]
  200. }
  201. if p[0] == '/' {
  202. u.Path = p
  203. } else {
  204. u.Path += p
  205. }
  206. u.RawQuery = q
  207. }
  208. func soapRequest(url, device, function, message string) error {
  209. tpl := `<?xml version="1.0" ?>
  210. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  211. <s:Body>%s</s:Body>
  212. </s:Envelope>
  213. `
  214. body := fmt.Sprintf(tpl, message)
  215. req, err := http.NewRequest("POST", url, strings.NewReader(body))
  216. if err != nil {
  217. return err
  218. }
  219. req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
  220. req.Header.Set("User-Agent", "syncthing/1.0")
  221. req.Header.Set("SOAPAction", fmt.Sprintf(`"%s#%s"`, device, function))
  222. req.Header.Set("Connection", "Close")
  223. req.Header.Set("Cache-Control", "no-cache")
  224. req.Header.Set("Pragma", "no-cache")
  225. if debug {
  226. l.Debugln(req.Header.Get("SOAPAction"))
  227. l.Debugln(body)
  228. }
  229. r, err := http.DefaultClient.Do(req)
  230. if err != nil {
  231. return err
  232. }
  233. if debug {
  234. resp, _ := ioutil.ReadAll(r.Body)
  235. l.Debugln(string(resp))
  236. }
  237. r.Body.Close()
  238. if r.StatusCode >= 400 {
  239. return errors.New(function + ": " + r.Status)
  240. }
  241. return nil
  242. }
  243. func (n *IGD) AddPortMapping(protocol Protocol, externalPort, internalPort int, description string, timeout int) error {
  244. tpl := `<u:AddPortMapping xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
  245. <NewRemoteHost></NewRemoteHost>
  246. <NewExternalPort>%d</NewExternalPort>
  247. <NewProtocol>%s</NewProtocol>
  248. <NewInternalPort>%d</NewInternalPort>
  249. <NewInternalClient>%s</NewInternalClient>
  250. <NewEnabled>1</NewEnabled>
  251. <NewPortMappingDescription>%s</NewPortMappingDescription>
  252. <NewLeaseDuration>%d</NewLeaseDuration>
  253. </u:AddPortMapping>
  254. `
  255. body := fmt.Sprintf(tpl, externalPort, protocol, internalPort, n.ourIP, description, timeout)
  256. return soapRequest(n.serviceURL, n.device, "AddPortMapping", body)
  257. }
  258. func (n *IGD) DeletePortMapping(protocol Protocol, externalPort int) (err error) {
  259. tpl := `<u:DeletePortMapping xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
  260. <NewRemoteHost></NewRemoteHost>
  261. <NewExternalPort>%d</NewExternalPort>
  262. <NewProtocol>%s</NewProtocol>
  263. </u:DeletePortMapping>
  264. `
  265. body := fmt.Sprintf(tpl, externalPort, protocol)
  266. return soapRequest(n.serviceURL, n.device, "DeletePortMapping", body)
  267. }