controller_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "flag"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "net"
  26. "net/http"
  27. "net/url"
  28. "os"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "testing"
  33. "time"
  34. socks "github.com/Psiphon-Inc/goptlib"
  35. "github.com/elazarl/goproxy"
  36. )
  37. func TestMain(m *testing.M) {
  38. flag.Parse()
  39. os.Remove(DATA_STORE_FILENAME)
  40. initDisruptor()
  41. initUpstreamProxy()
  42. SetEmitDiagnosticNotices(true)
  43. os.Exit(m.Run())
  44. }
  45. // Test case notes/limitations/dependencies:
  46. //
  47. // * Untunneled upgrade tests must execute before
  48. // the other tests to ensure no tunnel is established.
  49. // We need a way to reset the datastore after it's been
  50. // initialized in order to to clear out its data entries
  51. // and be able to arbitrarily order the tests.
  52. //
  53. // * The resumable download tests using disruptNetwork
  54. // depend on the download object being larger than the
  55. // disruptorMax limits so that the disruptor will actually
  56. // interrupt the first download attempt. Specifically, the
  57. // upgrade and remote server list at the URLs specified in
  58. // controller_test.config.enc.
  59. //
  60. // * The protocol tests assume there is at least one server
  61. // supporting each protocol in the server list at the URL
  62. // specified in controller_test.config.enc, and that these
  63. // servers are not overloaded.
  64. //
  65. // * fetchAndVerifyWebsite depends on the target URL being
  66. // available and responding.
  67. //
  68. func TestUntunneledUpgradeDownload(t *testing.T) {
  69. controllerRun(t,
  70. &controllerRunConfig{
  71. expectNoServerEntries: true,
  72. protocol: "",
  73. clientIsLatestVersion: false,
  74. disableUntunneledUpgrade: false,
  75. disableEstablishing: true,
  76. disableApi: false,
  77. tunnelPoolSize: 1,
  78. useUpstreamProxy: false,
  79. disruptNetwork: false,
  80. useHostNameTransformer: false,
  81. runDuration: 0,
  82. })
  83. }
  84. func TestUntunneledResumableUpgradeDownload(t *testing.T) {
  85. controllerRun(t,
  86. &controllerRunConfig{
  87. expectNoServerEntries: true,
  88. protocol: "",
  89. clientIsLatestVersion: false,
  90. disableUntunneledUpgrade: false,
  91. disableEstablishing: true,
  92. disableApi: false,
  93. tunnelPoolSize: 1,
  94. useUpstreamProxy: false,
  95. disruptNetwork: true,
  96. useHostNameTransformer: false,
  97. runDuration: 0,
  98. })
  99. }
  100. func TestUntunneledUpgradeClientIsLatestVersion(t *testing.T) {
  101. controllerRun(t,
  102. &controllerRunConfig{
  103. expectNoServerEntries: true,
  104. protocol: "",
  105. clientIsLatestVersion: true,
  106. disableUntunneledUpgrade: false,
  107. disableEstablishing: true,
  108. disableApi: false,
  109. tunnelPoolSize: 1,
  110. useUpstreamProxy: false,
  111. disruptNetwork: false,
  112. useHostNameTransformer: false,
  113. runDuration: 0,
  114. })
  115. }
  116. func TestUntunneledResumableFetchRemoveServerList(t *testing.T) {
  117. controllerRun(t,
  118. &controllerRunConfig{
  119. expectNoServerEntries: true,
  120. protocol: "",
  121. clientIsLatestVersion: true,
  122. disableUntunneledUpgrade: false,
  123. disableEstablishing: false,
  124. disableApi: false,
  125. tunnelPoolSize: 1,
  126. useUpstreamProxy: false,
  127. disruptNetwork: true,
  128. useHostNameTransformer: false,
  129. runDuration: 0,
  130. })
  131. }
  132. func TestTunneledUpgradeClientIsLatestVersion(t *testing.T) {
  133. controllerRun(t,
  134. &controllerRunConfig{
  135. expectNoServerEntries: false,
  136. protocol: "",
  137. clientIsLatestVersion: true,
  138. disableUntunneledUpgrade: true,
  139. disableEstablishing: false,
  140. disableApi: false,
  141. tunnelPoolSize: 1,
  142. useUpstreamProxy: false,
  143. disruptNetwork: false,
  144. useHostNameTransformer: false,
  145. runDuration: 0,
  146. })
  147. }
  148. func TestImpairedProtocols(t *testing.T) {
  149. // This test sets a tunnelPoolSize of 40 and runs
  150. // the session for 1 minute with network disruption
  151. // on. All 40 tunnels being disrupted every 10
  152. // seconds (followed by ssh keep alive probe timeout)
  153. // should be sufficient to trigger at least one
  154. // impaired protocol classification.
  155. controllerRun(t,
  156. &controllerRunConfig{
  157. expectNoServerEntries: false,
  158. protocol: "",
  159. clientIsLatestVersion: true,
  160. disableUntunneledUpgrade: true,
  161. disableEstablishing: false,
  162. disableApi: false,
  163. tunnelPoolSize: 40,
  164. useUpstreamProxy: false,
  165. disruptNetwork: true,
  166. useHostNameTransformer: false,
  167. runDuration: 1 * time.Minute,
  168. })
  169. }
  170. func TestSSH(t *testing.T) {
  171. controllerRun(t,
  172. &controllerRunConfig{
  173. expectNoServerEntries: false,
  174. protocol: TUNNEL_PROTOCOL_SSH,
  175. clientIsLatestVersion: false,
  176. disableUntunneledUpgrade: true,
  177. disableEstablishing: false,
  178. disableApi: false,
  179. tunnelPoolSize: 1,
  180. useUpstreamProxy: false,
  181. disruptNetwork: false,
  182. useHostNameTransformer: false,
  183. runDuration: 0,
  184. })
  185. }
  186. func TestObfuscatedSSH(t *testing.T) {
  187. controllerRun(t,
  188. &controllerRunConfig{
  189. expectNoServerEntries: false,
  190. protocol: TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  191. clientIsLatestVersion: false,
  192. disableUntunneledUpgrade: true,
  193. disableEstablishing: false,
  194. disableApi: false,
  195. tunnelPoolSize: 1,
  196. useUpstreamProxy: false,
  197. disruptNetwork: false,
  198. useHostNameTransformer: false,
  199. runDuration: 0,
  200. })
  201. }
  202. func TestUnfrontedMeek(t *testing.T) {
  203. controllerRun(t,
  204. &controllerRunConfig{
  205. expectNoServerEntries: false,
  206. protocol: TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  207. clientIsLatestVersion: false,
  208. disableUntunneledUpgrade: true,
  209. disableEstablishing: false,
  210. disableApi: false,
  211. tunnelPoolSize: 1,
  212. useUpstreamProxy: false,
  213. disruptNetwork: false,
  214. useHostNameTransformer: false,
  215. runDuration: 0,
  216. })
  217. }
  218. func TestUnfrontedMeekWithTransformer(t *testing.T) {
  219. controllerRun(t,
  220. &controllerRunConfig{
  221. expectNoServerEntries: false,
  222. protocol: TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  223. clientIsLatestVersion: true,
  224. disableUntunneledUpgrade: true,
  225. disableEstablishing: false,
  226. disableApi: false,
  227. tunnelPoolSize: 1,
  228. useUpstreamProxy: false,
  229. disruptNetwork: false,
  230. useHostNameTransformer: true,
  231. runDuration: 0,
  232. })
  233. }
  234. func TestFrontedMeek(t *testing.T) {
  235. controllerRun(t,
  236. &controllerRunConfig{
  237. expectNoServerEntries: false,
  238. protocol: TUNNEL_PROTOCOL_FRONTED_MEEK,
  239. clientIsLatestVersion: false,
  240. disableUntunneledUpgrade: true,
  241. disableEstablishing: false,
  242. disableApi: false,
  243. tunnelPoolSize: 1,
  244. useUpstreamProxy: false,
  245. disruptNetwork: false,
  246. useHostNameTransformer: false,
  247. runDuration: 0,
  248. })
  249. }
  250. func TestFrontedMeekWithTransformer(t *testing.T) {
  251. controllerRun(t,
  252. &controllerRunConfig{
  253. expectNoServerEntries: false,
  254. protocol: TUNNEL_PROTOCOL_FRONTED_MEEK,
  255. clientIsLatestVersion: true,
  256. disableUntunneledUpgrade: true,
  257. disableEstablishing: false,
  258. disableApi: false,
  259. tunnelPoolSize: 1,
  260. useUpstreamProxy: false,
  261. disruptNetwork: false,
  262. useHostNameTransformer: true,
  263. runDuration: 0,
  264. })
  265. }
  266. func TestFrontedMeekHTTP(t *testing.T) {
  267. controllerRun(t,
  268. &controllerRunConfig{
  269. expectNoServerEntries: false,
  270. protocol: TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP,
  271. clientIsLatestVersion: true,
  272. disableUntunneledUpgrade: true,
  273. disableEstablishing: false,
  274. disableApi: false,
  275. tunnelPoolSize: 1,
  276. useUpstreamProxy: false,
  277. disruptNetwork: false,
  278. useHostNameTransformer: false,
  279. runDuration: 0,
  280. })
  281. }
  282. func TestUnfrontedMeekHTTPS(t *testing.T) {
  283. controllerRun(t,
  284. &controllerRunConfig{
  285. expectNoServerEntries: false,
  286. protocol: TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  287. clientIsLatestVersion: false,
  288. disableUntunneledUpgrade: true,
  289. disableEstablishing: false,
  290. disableApi: false,
  291. tunnelPoolSize: 1,
  292. useUpstreamProxy: false,
  293. disruptNetwork: false,
  294. useHostNameTransformer: false,
  295. runDuration: 0,
  296. })
  297. }
  298. func TestUnfrontedMeekHTTPSWithTransformer(t *testing.T) {
  299. controllerRun(t,
  300. &controllerRunConfig{
  301. expectNoServerEntries: false,
  302. protocol: TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  303. clientIsLatestVersion: true,
  304. disableUntunneledUpgrade: true,
  305. disableEstablishing: false,
  306. disableApi: false,
  307. tunnelPoolSize: 1,
  308. useUpstreamProxy: false,
  309. disruptNetwork: false,
  310. useHostNameTransformer: true,
  311. runDuration: 0,
  312. })
  313. }
  314. func TestDisabledApi(t *testing.T) {
  315. controllerRun(t,
  316. &controllerRunConfig{
  317. expectNoServerEntries: false,
  318. protocol: "",
  319. clientIsLatestVersion: true,
  320. disableUntunneledUpgrade: true,
  321. disableEstablishing: false,
  322. disableApi: true,
  323. tunnelPoolSize: 1,
  324. useUpstreamProxy: false,
  325. disruptNetwork: false,
  326. useHostNameTransformer: false,
  327. runDuration: 0,
  328. })
  329. }
  330. func TestObfuscatedSSHWithUpstreamProxy(t *testing.T) {
  331. controllerRun(t,
  332. &controllerRunConfig{
  333. expectNoServerEntries: false,
  334. protocol: TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  335. clientIsLatestVersion: false,
  336. disableUntunneledUpgrade: true,
  337. disableEstablishing: false,
  338. disableApi: false,
  339. tunnelPoolSize: 1,
  340. useUpstreamProxy: true,
  341. disruptNetwork: false,
  342. useHostNameTransformer: false,
  343. runDuration: 0,
  344. })
  345. }
  346. func TestUnfrontedMeekWithUpstreamProxy(t *testing.T) {
  347. controllerRun(t,
  348. &controllerRunConfig{
  349. expectNoServerEntries: false,
  350. protocol: TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  351. clientIsLatestVersion: false,
  352. disableUntunneledUpgrade: true,
  353. disableEstablishing: false,
  354. disableApi: false,
  355. tunnelPoolSize: 1,
  356. useUpstreamProxy: true,
  357. disruptNetwork: false,
  358. useHostNameTransformer: false,
  359. runDuration: 0,
  360. })
  361. }
  362. func TestUnfrontedMeekHTTPSWithUpstreamProxy(t *testing.T) {
  363. controllerRun(t,
  364. &controllerRunConfig{
  365. expectNoServerEntries: false,
  366. protocol: TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  367. clientIsLatestVersion: false,
  368. disableUntunneledUpgrade: true,
  369. disableEstablishing: false,
  370. disableApi: false,
  371. tunnelPoolSize: 1,
  372. useUpstreamProxy: true,
  373. disruptNetwork: false,
  374. useHostNameTransformer: false,
  375. runDuration: 0,
  376. })
  377. }
  378. type controllerRunConfig struct {
  379. expectNoServerEntries bool
  380. protocol string
  381. clientIsLatestVersion bool
  382. disableUntunneledUpgrade bool
  383. disableEstablishing bool
  384. disableApi bool
  385. tunnelPoolSize int
  386. useUpstreamProxy bool
  387. disruptNetwork bool
  388. useHostNameTransformer bool
  389. runDuration time.Duration
  390. }
  391. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  392. configFileContents, err := ioutil.ReadFile("controller_test.config")
  393. if err != nil {
  394. // Skip, don't fail, if config file is not present
  395. t.Skipf("error loading configuration file: %s", err)
  396. }
  397. config, err := LoadConfig(configFileContents)
  398. if err != nil {
  399. t.Fatalf("error processing configuration file: %s", err)
  400. }
  401. if runConfig.clientIsLatestVersion {
  402. config.ClientVersion = "999999999"
  403. }
  404. if runConfig.disableEstablishing {
  405. // Clear remote server list so tunnel cannot be established.
  406. // TODO: also delete all server entries in the datastore.
  407. config.RemoteServerListUrl = ""
  408. }
  409. if runConfig.disableApi {
  410. config.DisableApi = true
  411. }
  412. config.TunnelPoolSize = runConfig.tunnelPoolSize
  413. if runConfig.disableUntunneledUpgrade {
  414. // Disable untunneled upgrade downloader to ensure tunneled case is tested
  415. config.UpgradeDownloadClientVersionHeader = ""
  416. }
  417. if runConfig.useUpstreamProxy && runConfig.disruptNetwork {
  418. t.Fatalf("cannot use multiple upstream proxies")
  419. }
  420. if runConfig.disruptNetwork {
  421. config.UpstreamProxyUrl = disruptorProxyURL
  422. } else if runConfig.useUpstreamProxy {
  423. config.UpstreamProxyUrl = upstreamProxyURL
  424. }
  425. if runConfig.useHostNameTransformer {
  426. config.HostNameTransformer = &TestHostNameTransformer{}
  427. }
  428. // Override client retry throttle values to speed up automated
  429. // tests and ensure tests complete within fixed deadlines.
  430. fetchRemoteServerListRetryPeriodSeconds := 0
  431. config.FetchRemoteServerListRetryPeriodSeconds = &fetchRemoteServerListRetryPeriodSeconds
  432. downloadUpgradeRetryPeriodSeconds := 0
  433. config.DownloadUpgradeRetryPeriodSeconds = &downloadUpgradeRetryPeriodSeconds
  434. establishTunnelPausePeriodSeconds := 1
  435. config.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  436. os.Remove(config.UpgradeDownloadFilename)
  437. config.TunnelProtocol = runConfig.protocol
  438. err = InitDataStore(config)
  439. if err != nil {
  440. t.Fatalf("error initializing datastore: %s", err)
  441. }
  442. serverEntryCount := CountServerEntries("", "")
  443. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  444. // TODO: replace expectNoServerEntries with resetServerEntries
  445. // so tests can run in arbitrary order
  446. t.Fatalf("unexpected server entries")
  447. }
  448. controller, err := NewController(config)
  449. if err != nil {
  450. t.Fatalf("error creating controller: %s", err)
  451. }
  452. // Monitor notices for "Tunnels" with count > 1, the
  453. // indication of tunnel establishment success.
  454. // Also record the selected HTTP proxy port to use
  455. // when fetching websites through the tunnel.
  456. httpProxyPort := 0
  457. tunnelEstablished := make(chan struct{}, 1)
  458. upgradeDownloaded := make(chan struct{}, 1)
  459. remoteServerListDownloaded := make(chan struct{}, 1)
  460. confirmedLatestVersion := make(chan struct{}, 1)
  461. var clientUpgradeDownloadedBytesCount int32
  462. var remoteServerListDownloadedBytesCount int32
  463. var impairedProtocolCount int32
  464. var impairedProtocolClassification = struct {
  465. sync.RWMutex
  466. classification map[string]int
  467. }{classification: make(map[string]int)}
  468. SetNoticeOutput(NewNoticeReceiver(
  469. func(notice []byte) {
  470. // TODO: log notices without logging server IPs:
  471. // fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  472. noticeType, payload, err := GetNotice(notice)
  473. if err != nil {
  474. return
  475. }
  476. switch noticeType {
  477. case "ListeningHttpProxyPort":
  478. httpProxyPort = int(payload["port"].(float64))
  479. case "ConnectingServer":
  480. serverProtocol := payload["protocol"].(string)
  481. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  482. // TODO: wrong goroutine for t.FatalNow()
  483. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  484. }
  485. case "Tunnels":
  486. count := int(payload["count"].(float64))
  487. if count > 0 {
  488. if runConfig.disableEstablishing {
  489. // TODO: wrong goroutine for t.FatalNow()
  490. t.Fatalf("tunnel established unexpectedly")
  491. } else {
  492. select {
  493. case tunnelEstablished <- *new(struct{}):
  494. default:
  495. }
  496. }
  497. }
  498. case "ClientUpgradeDownloadedBytes":
  499. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  500. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  501. case "ClientUpgradeDownloaded":
  502. select {
  503. case upgradeDownloaded <- *new(struct{}):
  504. default:
  505. }
  506. case "ClientIsLatestVersion":
  507. select {
  508. case confirmedLatestVersion <- *new(struct{}):
  509. default:
  510. }
  511. case "RemoteServerListDownloadedBytes":
  512. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  513. t.Logf("RemoteServerListDownloadedBytes: %d", int(payload["bytes"].(float64)))
  514. case "RemoteServerListDownloaded":
  515. select {
  516. case remoteServerListDownloaded <- *new(struct{}):
  517. default:
  518. }
  519. case "ImpairedProtocolClassification":
  520. classification := payload["classification"].(map[string]interface{})
  521. impairedProtocolClassification.Lock()
  522. impairedProtocolClassification.classification = make(map[string]int)
  523. for k, v := range classification {
  524. count := int(v.(float64))
  525. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  526. atomic.AddInt32(&impairedProtocolCount, 1)
  527. }
  528. impairedProtocolClassification.classification[k] = count
  529. }
  530. impairedProtocolClassification.Unlock()
  531. case "ActiveTunnel":
  532. serverProtocol := payload["protocol"].(string)
  533. classification := make(map[string]int)
  534. impairedProtocolClassification.RLock()
  535. for k, v := range impairedProtocolClassification.classification {
  536. classification[k] = v
  537. }
  538. impairedProtocolClassification.RUnlock()
  539. count, ok := classification[serverProtocol]
  540. if ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  541. // TODO: wrong goroutine for t.FatalNow()
  542. t.Fatalf("unexpected tunnel using impaired protocol: %s, %+v",
  543. serverProtocol, classification)
  544. }
  545. }
  546. }))
  547. // Run controller, which establishes tunnels
  548. shutdownBroadcast := make(chan struct{})
  549. controllerWaitGroup := new(sync.WaitGroup)
  550. controllerWaitGroup.Add(1)
  551. go func() {
  552. defer controllerWaitGroup.Done()
  553. controller.Run(shutdownBroadcast)
  554. }()
  555. defer func() {
  556. // Test: shutdown must complete within 20 seconds
  557. close(shutdownBroadcast)
  558. shutdownTimeout := time.NewTimer(20 * time.Second)
  559. shutdownOk := make(chan struct{}, 1)
  560. go func() {
  561. controllerWaitGroup.Wait()
  562. shutdownOk <- *new(struct{})
  563. }()
  564. select {
  565. case <-shutdownOk:
  566. case <-shutdownTimeout.C:
  567. t.Fatalf("controller shutdown timeout exceeded")
  568. }
  569. }()
  570. if !runConfig.disableEstablishing {
  571. // Test: tunnel must be established within 120 seconds
  572. establishTimeout := time.NewTimer(120 * time.Second)
  573. select {
  574. case <-tunnelEstablished:
  575. case <-establishTimeout.C:
  576. t.Fatalf("tunnel establish timeout exceeded")
  577. }
  578. // Test: if starting with no server entries, a fetch remote
  579. // server list must have succeeded. With disruptNetwork, the
  580. // fetch must have been resumed at least once.
  581. if serverEntryCount == 0 {
  582. select {
  583. case <-remoteServerListDownloaded:
  584. default:
  585. t.Fatalf("expected remote server list downloaded")
  586. }
  587. if runConfig.disruptNetwork {
  588. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  589. if count <= 1 {
  590. t.Fatalf("unexpected remote server list download progress: %d", count)
  591. }
  592. }
  593. }
  594. // Test: fetch website through tunnel
  595. // Allow for known race condition described in NewHttpProxy():
  596. time.Sleep(1 * time.Second)
  597. fetchAndVerifyWebsite(t, httpProxyPort)
  598. // Test: run for duration, periodically using the tunnel to
  599. // ensure failed tunnel detection, and ultimately hitting
  600. // impaired protocol checks.
  601. startTime := time.Now()
  602. for {
  603. time.Sleep(1 * time.Second)
  604. useTunnel(t, httpProxyPort)
  605. if startTime.Add(runConfig.runDuration).Before(time.Now()) {
  606. break
  607. }
  608. }
  609. // Test: with disruptNetwork, impaired protocols should be exercised
  610. if runConfig.runDuration > 0 && runConfig.disruptNetwork {
  611. count := atomic.LoadInt32(&impairedProtocolCount)
  612. if count <= 0 {
  613. t.Fatalf("unexpected impaired protocol count: %d", count)
  614. } else {
  615. impairedProtocolClassification.RLock()
  616. t.Logf("impaired protocol classification: %+v",
  617. impairedProtocolClassification.classification)
  618. impairedProtocolClassification.RUnlock()
  619. }
  620. }
  621. }
  622. // Test: upgrade check/download must be downloaded within 180 seconds
  623. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  624. if expectUpgrade {
  625. upgradeTimeout := time.NewTimer(180 * time.Second)
  626. select {
  627. case <-upgradeDownloaded:
  628. // TODO: verify downloaded file
  629. if runConfig.clientIsLatestVersion {
  630. t.Fatalf("upgrade downloaded unexpectedly")
  631. }
  632. // Test: with disruptNetwork, must be multiple download progress notices
  633. if runConfig.disruptNetwork {
  634. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  635. if count <= 1 {
  636. t.Fatalf("unexpected upgrade download progress: %d", count)
  637. }
  638. }
  639. case <-confirmedLatestVersion:
  640. if !runConfig.clientIsLatestVersion {
  641. t.Fatalf("confirmed latest version unexpectedly")
  642. }
  643. case <-upgradeTimeout.C:
  644. t.Fatalf("upgrade download timeout exceeded")
  645. }
  646. }
  647. }
  648. type TestHostNameTransformer struct {
  649. }
  650. func (TestHostNameTransformer) TransformHostName(string) (string, bool) {
  651. return "example.com", true
  652. }
  653. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) {
  654. testUrl := "https://raw.githubusercontent.com/Psiphon-Labs/psiphon-tunnel-core/master/LICENSE"
  655. roundTripTimeout := 10 * time.Second
  656. expectedResponsePrefix := " GNU GENERAL PUBLIC LICENSE"
  657. expectedResponseSize := 35148
  658. checkResponse := func(responseBody string) bool {
  659. return strings.HasPrefix(responseBody, expectedResponsePrefix) && len(responseBody) == expectedResponseSize
  660. }
  661. // Test: use HTTP proxy
  662. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  663. if err != nil {
  664. t.Fatalf("error initializing proxied HTTP request: %s", err)
  665. }
  666. httpClient := &http.Client{
  667. Transport: &http.Transport{
  668. Proxy: http.ProxyURL(proxyUrl),
  669. },
  670. Timeout: roundTripTimeout,
  671. }
  672. response, err := httpClient.Get(testUrl)
  673. if err != nil {
  674. t.Fatalf("error sending proxied HTTP request: %s", err)
  675. }
  676. body, err := ioutil.ReadAll(response.Body)
  677. if err != nil {
  678. t.Fatalf("error reading proxied HTTP response: %s", err)
  679. }
  680. response.Body.Close()
  681. if !checkResponse(string(body)) {
  682. t.Fatalf("unexpected proxied HTTP response")
  683. }
  684. // Test: use direct URL proxy
  685. httpClient = &http.Client{
  686. Transport: http.DefaultTransport,
  687. Timeout: roundTripTimeout,
  688. }
  689. response, err = httpClient.Get(
  690. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  691. httpProxyPort, url.QueryEscape(testUrl)))
  692. if err != nil {
  693. t.Fatalf("error sending direct URL request: %s", err)
  694. }
  695. body, err = ioutil.ReadAll(response.Body)
  696. if err != nil {
  697. t.Fatalf("error reading direct URL response: %s", err)
  698. }
  699. response.Body.Close()
  700. if !checkResponse(string(body)) {
  701. t.Fatalf("unexpected direct URL response")
  702. }
  703. // Test: use tunneled URL proxy
  704. response, err = httpClient.Get(
  705. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  706. httpProxyPort, url.QueryEscape(testUrl)))
  707. if err != nil {
  708. t.Fatalf("error sending tunneled URL request: %s", err)
  709. }
  710. body, err = ioutil.ReadAll(response.Body)
  711. if err != nil {
  712. t.Fatalf("error reading tunneled URL response: %s", err)
  713. }
  714. response.Body.Close()
  715. if !checkResponse(string(body)) {
  716. t.Fatalf("unexpected tunneled URL response")
  717. }
  718. }
  719. func useTunnel(t *testing.T, httpProxyPort int) {
  720. // No action on errors as the tunnel is expected to fail sometimes
  721. testUrl := "https://psiphon3.com"
  722. roundTripTimeout := 1 * time.Second
  723. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  724. if err != nil {
  725. return
  726. }
  727. httpClient := &http.Client{
  728. Transport: &http.Transport{
  729. Proxy: http.ProxyURL(proxyUrl),
  730. },
  731. Timeout: roundTripTimeout,
  732. }
  733. response, err := httpClient.Get(testUrl)
  734. if err != nil {
  735. return
  736. }
  737. response.Body.Close()
  738. }
  739. const disruptorProxyAddress = "127.0.0.1:2160"
  740. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  741. const disruptorMaxConnectionBytes = 500000
  742. const disruptorMaxConnectionTime = 10 * time.Second
  743. func initDisruptor() {
  744. go func() {
  745. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  746. if err != nil {
  747. fmt.Errorf("disruptor proxy listen error: %s", err)
  748. return
  749. }
  750. for {
  751. localConn, err := listener.AcceptSocks()
  752. if err != nil {
  753. fmt.Errorf("disruptor proxy accept error: %s", err)
  754. return
  755. }
  756. go func() {
  757. defer localConn.Close()
  758. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  759. if err != nil {
  760. fmt.Errorf("disruptor proxy dial error: %s", err)
  761. return
  762. }
  763. defer remoteConn.Close()
  764. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  765. if err != nil {
  766. fmt.Errorf("disruptor proxy grant error: %s", err)
  767. return
  768. }
  769. // Cut connection after disruptorMaxConnectionTime
  770. time.AfterFunc(disruptorMaxConnectionTime, func() {
  771. localConn.Close()
  772. remoteConn.Close()
  773. })
  774. // Relay connection, but only up to disruptorMaxConnectionBytes
  775. waitGroup := new(sync.WaitGroup)
  776. waitGroup.Add(1)
  777. go func() {
  778. defer waitGroup.Done()
  779. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  780. }()
  781. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  782. waitGroup.Wait()
  783. }()
  784. }
  785. }()
  786. }
  787. const upstreamProxyURL = "http://127.0.0.1:2161"
  788. func initUpstreamProxy() {
  789. go func() {
  790. proxy := goproxy.NewProxyHttpServer()
  791. err := http.ListenAndServe(":2161", proxy)
  792. if err != nil {
  793. fmt.Printf("upstream proxy failed: %s", err)
  794. }
  795. }()
  796. // TODO: wait until listener is active?
  797. }