server_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "encoding/json"
  22. "flag"
  23. "fmt"
  24. "io/ioutil"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "sync"
  29. "testing"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  32. )
  33. func TestMain(m *testing.M) {
  34. flag.Parse()
  35. os.Remove(psiphon.DATA_STORE_FILENAME)
  36. psiphon.SetEmitDiagnosticNotices(true)
  37. os.Exit(m.Run())
  38. }
  39. // Note: not testing fronting meek protocols, which client is
  40. // hard-wired to except running on privileged ports 80 and 443.
  41. func TestSSH(t *testing.T) {
  42. runServer(t, "SSH")
  43. }
  44. func TestOSSH(t *testing.T) {
  45. runServer(t, "OSSH")
  46. }
  47. func TestUnfrontedMeek(t *testing.T) {
  48. runServer(t, "UNFRONTED-MEEK-OSSH")
  49. }
  50. func TestUnfrontedMeekHTTPS(t *testing.T) {
  51. runServer(t, "UNFRONTED-MEEK-HTTPS-OSSH")
  52. }
  53. func runServer(t *testing.T, tunnelProtocol string) {
  54. // create a server
  55. serverConfigFileContents, serverEntryFileContents, err := GenerateConfig(
  56. "127.0.0.1",
  57. 8000,
  58. map[string]int{tunnelProtocol: 4000})
  59. if err != nil {
  60. t.Fatalf("error generating server config: %s", err)
  61. }
  62. // customize server config
  63. var serverConfig interface{}
  64. json.Unmarshal(serverConfigFileContents, &serverConfig)
  65. serverConfig.(map[string]interface{})["GeoIPDatabaseFilename"] = ""
  66. serverConfigFileContents, _ = json.Marshal(serverConfig)
  67. // run server
  68. serverWaitGroup := new(sync.WaitGroup)
  69. serverWaitGroup.Add(1)
  70. go func() {
  71. defer serverWaitGroup.Done()
  72. err := RunServices([][]byte{serverConfigFileContents})
  73. if err != nil {
  74. // TODO: wrong goroutine for t.FatalNow()
  75. t.Fatalf("error running server: %s", err)
  76. }
  77. }()
  78. defer func() {
  79. // Test: orderly server shutdown
  80. p, _ := os.FindProcess(os.Getpid())
  81. p.Signal(os.Interrupt)
  82. shutdownTimeout := time.NewTimer(5 * time.Second)
  83. shutdownOk := make(chan struct{}, 1)
  84. go func() {
  85. serverWaitGroup.Wait()
  86. shutdownOk <- *new(struct{})
  87. }()
  88. select {
  89. case <-shutdownOk:
  90. case <-shutdownTimeout.C:
  91. t.Fatalf("server shutdown timeout exceeded")
  92. }
  93. }()
  94. // connect to server with client
  95. // TODO: currently, TargetServerEntry only works with one tunnel
  96. numTunnels := 1
  97. localHTTPProxyPort := 8080
  98. establishTunnelPausePeriodSeconds := 1
  99. // Note: calling LoadConfig ensures all *int config fields are initialized
  100. configJson := `
  101. {
  102. "ClientVersion": "0",
  103. "PropagationChannelId": "0",
  104. "SponsorId": "0"
  105. }`
  106. clientConfig, _ := psiphon.LoadConfig([]byte(configJson))
  107. clientConfig.ConnectionWorkerPoolSize = numTunnels
  108. clientConfig.TunnelPoolSize = numTunnels
  109. clientConfig.DisableRemoteServerListFetcher = true
  110. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  111. clientConfig.TargetServerEntry = string(serverEntryFileContents)
  112. clientConfig.TunnelProtocol = tunnelProtocol
  113. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  114. err = psiphon.InitDataStore(clientConfig)
  115. if err != nil {
  116. t.Fatalf("error initializing client datastore: %s", err)
  117. }
  118. controller, err := psiphon.NewController(clientConfig)
  119. if err != nil {
  120. t.Fatalf("error creating client controller: %s", err)
  121. }
  122. tunnelsEstablished := make(chan struct{}, 1)
  123. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  124. func(notice []byte) {
  125. fmt.Printf("%s\n", string(notice))
  126. noticeType, payload, err := psiphon.GetNotice(notice)
  127. if err != nil {
  128. return
  129. }
  130. switch noticeType {
  131. case "Tunnels":
  132. count := int(payload["count"].(float64))
  133. if count >= numTunnels {
  134. select {
  135. case tunnelsEstablished <- *new(struct{}):
  136. default:
  137. }
  138. }
  139. }
  140. }))
  141. controllerShutdownBroadcast := make(chan struct{})
  142. controllerWaitGroup := new(sync.WaitGroup)
  143. controllerWaitGroup.Add(1)
  144. go func() {
  145. defer controllerWaitGroup.Done()
  146. controller.Run(controllerShutdownBroadcast)
  147. }()
  148. defer func() {
  149. close(controllerShutdownBroadcast)
  150. shutdownTimeout := time.NewTimer(20 * time.Second)
  151. shutdownOk := make(chan struct{}, 1)
  152. go func() {
  153. controllerWaitGroup.Wait()
  154. shutdownOk <- *new(struct{})
  155. }()
  156. select {
  157. case <-shutdownOk:
  158. case <-shutdownTimeout.C:
  159. t.Fatalf("controller shutdown timeout exceeded")
  160. }
  161. }()
  162. // Test: tunnels must be established within 30 seconds
  163. establishTimeout := time.NewTimer(30 * time.Second)
  164. select {
  165. case <-tunnelsEstablished:
  166. case <-establishTimeout.C:
  167. t.Fatalf("tunnel establish timeout exceeded")
  168. }
  169. // Test: tunneled web site fetch
  170. testUrl := "https://psiphon.ca"
  171. roundTripTimeout := 30 * time.Second
  172. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  173. if err != nil {
  174. t.Fatalf("error initializing proxied HTTP request: %s", err)
  175. }
  176. httpClient := &http.Client{
  177. Transport: &http.Transport{
  178. Proxy: http.ProxyURL(proxyUrl),
  179. },
  180. Timeout: roundTripTimeout,
  181. }
  182. response, err := httpClient.Get(testUrl)
  183. if err != nil {
  184. t.Fatalf("error sending proxied HTTP request: %s", err)
  185. }
  186. _, err = ioutil.ReadAll(response.Body)
  187. if err != nil {
  188. t.Fatalf("error reading proxied HTTP response: %s", err)
  189. }
  190. response.Body.Close()
  191. }