select_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package portmapper
  4. import (
  5. "context"
  6. "encoding/xml"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "testing"
  11. "github.com/tailscale/goupnp"
  12. "github.com/tailscale/goupnp/dcps/internetgateway2"
  13. )
  14. // NOTE: this is in a distinct file because the various string constants are
  15. // pretty verbose.
  16. func TestSelectBestService(t *testing.T) {
  17. mustParseURL := func(ss string) *url.URL {
  18. u, err := url.Parse(ss)
  19. if err != nil {
  20. t.Fatalf("error parsing URL %q: %v", ss, err)
  21. }
  22. return u
  23. }
  24. // Run a fake IGD server to respond to UPnP requests.
  25. igd, err := NewTestIGD(t, TestIGDOptions{UPnP: true})
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. defer igd.Close()
  30. testCases := []struct {
  31. name string
  32. rootDesc string
  33. control map[string]map[string]any
  34. want string // controlURL field
  35. }{
  36. {
  37. name: "single_device",
  38. rootDesc: testRootDesc,
  39. control: map[string]map[string]any{
  40. // Service that's up and should be selected.
  41. "/ctl/IPConn": {
  42. "GetExternalIPAddress": testGetExternalIPAddressResponse,
  43. "GetStatusInfo": testGetStatusInfoResponse,
  44. },
  45. },
  46. want: "/ctl/IPConn",
  47. },
  48. {
  49. name: "first_device_disconnected",
  50. rootDesc: testSelectRootDesc,
  51. control: map[string]map[string]any{
  52. // Service that's down; it's important that this is the
  53. // one that's down since it's ordered first in the XML
  54. // and we want to verify that our code properly queries
  55. // and then skips it.
  56. "/upnp/control/yomkmsnooi/wanipconn-1": {
  57. "GetStatusInfo": testGetStatusInfoResponseDisconnected,
  58. // NOTE: nothing else should be called
  59. // if GetStatusInfo returns a
  60. // disconnected result
  61. },
  62. // Service that's up and should be selected.
  63. "/upnp/control/xstnsgeuyh/wanipconn-7": {
  64. "GetExternalIPAddress": testGetExternalIPAddressResponse,
  65. "GetStatusInfo": testGetStatusInfoResponse,
  66. },
  67. },
  68. want: "/upnp/control/xstnsgeuyh/wanipconn-7",
  69. },
  70. {
  71. name: "prefer_public_external_IP",
  72. rootDesc: testSelectRootDesc,
  73. control: map[string]map[string]any{
  74. // Service with a private external IP; order matters as above.
  75. "/upnp/control/yomkmsnooi/wanipconn-1": {
  76. "GetStatusInfo": testGetStatusInfoResponse,
  77. "GetExternalIPAddress": testGetExternalIPAddressResponsePrivate,
  78. },
  79. // Service that's up and should be selected.
  80. "/upnp/control/xstnsgeuyh/wanipconn-7": {
  81. "GetExternalIPAddress": testGetExternalIPAddressResponse,
  82. "GetStatusInfo": testGetStatusInfoResponse,
  83. },
  84. },
  85. want: "/upnp/control/xstnsgeuyh/wanipconn-7",
  86. },
  87. {
  88. name: "all_private_external_IPs",
  89. rootDesc: testSelectRootDesc,
  90. control: map[string]map[string]any{
  91. "/upnp/control/yomkmsnooi/wanipconn-1": {
  92. "GetStatusInfo": testGetStatusInfoResponse,
  93. "GetExternalIPAddress": testGetExternalIPAddressResponsePrivate,
  94. },
  95. "/upnp/control/xstnsgeuyh/wanipconn-7": {
  96. "GetStatusInfo": testGetStatusInfoResponse,
  97. "GetExternalIPAddress": testGetExternalIPAddressResponsePrivate,
  98. },
  99. },
  100. want: "/upnp/control/yomkmsnooi/wanipconn-1", // since this is first in the XML
  101. },
  102. {
  103. name: "nothing_connected",
  104. rootDesc: testSelectRootDesc,
  105. control: map[string]map[string]any{
  106. "/upnp/control/yomkmsnooi/wanipconn-1": {
  107. "GetStatusInfo": testGetStatusInfoResponseDisconnected,
  108. },
  109. "/upnp/control/xstnsgeuyh/wanipconn-7": {
  110. "GetStatusInfo": testGetStatusInfoResponseDisconnected,
  111. },
  112. },
  113. want: "/upnp/control/yomkmsnooi/wanipconn-1", // since this is first in the XML
  114. },
  115. {
  116. name: "GetStatusInfo_errors",
  117. rootDesc: testSelectRootDesc,
  118. control: map[string]map[string]any{
  119. "/upnp/control/yomkmsnooi/wanipconn-1": {
  120. "GetStatusInfo": func(_ string) (int, string) {
  121. return http.StatusInternalServerError, "internal error"
  122. },
  123. },
  124. "/upnp/control/xstnsgeuyh/wanipconn-7": {
  125. "GetStatusInfo": func(_ string) (int, string) {
  126. return http.StatusNotFound, "not found"
  127. },
  128. },
  129. },
  130. want: "/upnp/control/yomkmsnooi/wanipconn-1", // since this is first in the XML
  131. },
  132. {
  133. name: "GetExternalIPAddress_bad_ip",
  134. rootDesc: testSelectRootDesc,
  135. control: map[string]map[string]any{
  136. "/upnp/control/yomkmsnooi/wanipconn-1": {
  137. "GetStatusInfo": testGetStatusInfoResponse,
  138. "GetExternalIPAddress": testGetExternalIPAddressResponseInvalid,
  139. },
  140. "/upnp/control/xstnsgeuyh/wanipconn-7": {
  141. "GetStatusInfo": testGetStatusInfoResponse,
  142. "GetExternalIPAddress": testGetExternalIPAddressResponse,
  143. },
  144. },
  145. want: "/upnp/control/xstnsgeuyh/wanipconn-7",
  146. },
  147. }
  148. for _, tt := range testCases {
  149. t.Run(tt.name, func(t *testing.T) {
  150. // Ensure that we're using our test IGD server for all requests.
  151. rootDesc := strings.ReplaceAll(tt.rootDesc, "@SERVERURL@", igd.ts.URL)
  152. igd.SetUPnPHandler(&upnpServer{
  153. t: t,
  154. Desc: rootDesc,
  155. Control: tt.control,
  156. })
  157. c := newTestClient(t, igd, nil)
  158. t.Logf("Listening on upnp=%v", c.testUPnPPort)
  159. // Ensure that we're using the HTTP client that talks to our test IGD server
  160. ctx := context.Background()
  161. ctx = goupnp.WithHTTPClient(ctx, c.upnpHTTPClientLocked())
  162. loc := mustParseURL(igd.ts.URL)
  163. rootDev := mustParseRootDev(t, rootDesc, loc)
  164. svc, err := selectBestService(ctx, t.Logf, rootDev, loc)
  165. if err != nil {
  166. t.Fatal(err)
  167. }
  168. var controlURL string
  169. switch v := svc.(type) {
  170. case *internetgateway2.WANIPConnection2:
  171. controlURL = v.ServiceClient.Service.ControlURL.Str
  172. case *internetgateway2.WANIPConnection1:
  173. controlURL = v.ServiceClient.Service.ControlURL.Str
  174. case *internetgateway2.WANPPPConnection1:
  175. controlURL = v.ServiceClient.Service.ControlURL.Str
  176. default:
  177. t.Fatalf("unknown client type: %T", v)
  178. }
  179. if controlURL != tt.want {
  180. t.Errorf("mismatched controlURL: got=%q want=%q", controlURL, tt.want)
  181. }
  182. })
  183. }
  184. }
  185. func mustParseRootDev(t *testing.T, devXML string, loc *url.URL) *goupnp.RootDevice {
  186. decoder := xml.NewDecoder(strings.NewReader(devXML))
  187. decoder.DefaultSpace = goupnp.DeviceXMLNamespace
  188. decoder.CharsetReader = goupnp.CharsetReaderDefault
  189. root := new(goupnp.RootDevice)
  190. if err := decoder.Decode(root); err != nil {
  191. t.Fatalf("error decoding device XML: %v", err)
  192. }
  193. // Ensure the URLBase is set properly; this is how DeviceByURL does it.
  194. var urlBaseStr string
  195. if root.URLBaseStr != "" {
  196. urlBaseStr = root.URLBaseStr
  197. } else {
  198. urlBaseStr = loc.String()
  199. }
  200. urlBase, err := url.Parse(urlBaseStr)
  201. if err != nil {
  202. t.Fatalf("error parsing URL %q: %v", urlBaseStr, err)
  203. }
  204. root.SetURLBase(urlBase)
  205. return root
  206. }
  207. // Note: adapted from mikrotikRootDescXML with addresses replaced with
  208. // localhost, and unnecessary fields removed.
  209. const testSelectRootDesc = `<?xml version="1.0"?>
  210. <root xmlns="urn:schemas-upnp-org:device-1-0">
  211. <specVersion>
  212. <major>1</major>
  213. <minor>0</minor>
  214. </specVersion>
  215. <device>
  216. <deviceType>urn:schemas-upnp-org:device:InternetGatewayDevice:1</deviceType>
  217. <friendlyName>MikroTik Router</friendlyName>
  218. <manufacturer>MikroTik</manufacturer>
  219. <manufacturerURL>https://www.mikrotik.com/</manufacturerURL>
  220. <modelName>Router OS</modelName>
  221. <UDN>uuid:UUID-MIKROTIK-INTERNET-GATEWAY-DEVICE-</UDN>
  222. <serviceList>
  223. <service>
  224. <serviceType>urn:schemas-microsoft-com:service:OSInfo:1</serviceType>
  225. <serviceId>urn:microsoft-com:serviceId:OSInfo1</serviceId>
  226. <SCPDURL>/osinfo.xml</SCPDURL>
  227. <controlURL>/upnp/control/oqjsxqshhz/osinfo</controlURL>
  228. <eventSubURL>/upnp/event/cwzcyndrjf/osinfo</eventSubURL>
  229. </service>
  230. </serviceList>
  231. <deviceList>
  232. <device>
  233. <deviceType>urn:schemas-upnp-org:device:WANDevice:1</deviceType>
  234. <friendlyName>WAN Device</friendlyName>
  235. <manufacturer>MikroTik</manufacturer>
  236. <manufacturerURL>https://www.mikrotik.com/</manufacturerURL>
  237. <modelName>Router OS</modelName>
  238. <UDN>uuid:UUID-MIKROTIK-WAN-DEVICE--1</UDN>
  239. <serviceList>
  240. <service>
  241. <serviceType>urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1</serviceType>
  242. <serviceId>urn:upnp-org:serviceId:WANCommonIFC1</serviceId>
  243. <SCPDURL>/wancommonifc-1.xml</SCPDURL>
  244. <controlURL>/upnp/control/ivvmxhunyq/wancommonifc-1</controlURL>
  245. <eventSubURL>/upnp/event/mkjzdqvryf/wancommonifc-1</eventSubURL>
  246. </service>
  247. </serviceList>
  248. <deviceList>
  249. <device>
  250. <deviceType>urn:schemas-upnp-org:device:WANConnectionDevice:1</deviceType>
  251. <friendlyName>WAN Connection Device</friendlyName>
  252. <manufacturer>MikroTik</manufacturer>
  253. <manufacturerURL>https://www.mikrotik.com/</manufacturerURL>
  254. <modelName>Router OS</modelName>
  255. <UDN>uuid:UUID-MIKROTIK-WAN-CONNECTION-DEVICE--1</UDN>
  256. <serviceList>
  257. <service>
  258. <serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>
  259. <serviceId>urn:upnp-org:serviceId:WANIPConn1</serviceId>
  260. <SCPDURL>/wanipconn-1.xml</SCPDURL>
  261. <controlURL>/upnp/control/yomkmsnooi/wanipconn-1</controlURL>
  262. <eventSubURL>/upnp/event/veeabhzzva/wanipconn-1</eventSubURL>
  263. </service>
  264. </serviceList>
  265. </device>
  266. </deviceList>
  267. </device>
  268. <device>
  269. <deviceType>urn:schemas-upnp-org:device:WANDevice:1</deviceType>
  270. <friendlyName>WAN Device</friendlyName>
  271. <manufacturer>MikroTik</manufacturer>
  272. <manufacturerURL>https://www.mikrotik.com/</manufacturerURL>
  273. <modelName>Router OS</modelName>
  274. <UDN>uuid:UUID-MIKROTIK-WAN-DEVICE--7</UDN>
  275. <serviceList>
  276. <service>
  277. <serviceType>urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1</serviceType>
  278. <serviceId>urn:upnp-org:serviceId:WANCommonIFC1</serviceId>
  279. <SCPDURL>/wancommonifc-7.xml</SCPDURL>
  280. <controlURL>/upnp/control/vzcyyzzttz/wancommonifc-7</controlURL>
  281. <eventSubURL>/upnp/event/womwbqtbkq/wancommonifc-7</eventSubURL>
  282. </service>
  283. </serviceList>
  284. <deviceList>
  285. <device>
  286. <deviceType>urn:schemas-upnp-org:device:WANConnectionDevice:1</deviceType>
  287. <friendlyName>WAN Connection Device</friendlyName>
  288. <manufacturer>MikroTik</manufacturer>
  289. <manufacturerURL>https://www.mikrotik.com/</manufacturerURL>
  290. <modelName>Router OS</modelName>
  291. <UDN>uuid:UUID-MIKROTIK-WAN-CONNECTION-DEVICE--7</UDN>
  292. <serviceList>
  293. <service>
  294. <serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>
  295. <serviceId>urn:upnp-org:serviceId:WANIPConn1</serviceId>
  296. <SCPDURL>/wanipconn-7.xml</SCPDURL>
  297. <controlURL>/upnp/control/xstnsgeuyh/wanipconn-7</controlURL>
  298. <eventSubURL>/upnp/event/rscixkusbs/wanipconn-7</eventSubURL>
  299. </service>
  300. </serviceList>
  301. </device>
  302. </deviceList>
  303. </device>
  304. </deviceList>
  305. <presentationURL>@SERVERURL@</presentationURL>
  306. </device>
  307. <URLBase>@SERVERURL@</URLBase>
  308. </root>`
  309. const testGetStatusInfoResponseDisconnected = `<?xml version="1.0"?>
  310. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  311. <s:Body>
  312. <u:GetStatusInfoResponse xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
  313. <NewConnectionStatus>Disconnected</NewConnectionStatus>
  314. <NewLastConnectionError>ERROR_NONE</NewLastConnectionError>
  315. <NewUptime>0</NewUptime>
  316. </u:GetStatusInfoResponse>
  317. </s:Body>
  318. </s:Envelope>
  319. `
  320. const testGetExternalIPAddressResponsePrivate = `<?xml version="1.0"?>
  321. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  322. <s:Body>
  323. <u:GetExternalIPAddressResponse xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
  324. <NewExternalIPAddress>10.9.8.7</NewExternalIPAddress>
  325. </u:GetExternalIPAddressResponse>
  326. </s:Body>
  327. </s:Envelope>
  328. `
  329. const testGetExternalIPAddressResponseInvalid = `<?xml version="1.0"?>
  330. <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  331. <s:Body>
  332. <u:GetExternalIPAddressResponse xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
  333. <NewExternalIPAddress>not-an-ip-addr</NewExternalIPAddress>
  334. </u:GetExternalIPAddressResponse>
  335. </s:Body>
  336. </s:Envelope>
  337. `