server_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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,
  43. &runServerConfig{
  44. tunnelProtocol: "SSH",
  45. enableSSHAPIRequests: true,
  46. })
  47. }
  48. func TestOSSH(t *testing.T) {
  49. runServer(t,
  50. &runServerConfig{
  51. tunnelProtocol: "OSSH",
  52. enableSSHAPIRequests: true,
  53. })
  54. }
  55. func TestUnfrontedMeek(t *testing.T) {
  56. runServer(t,
  57. &runServerConfig{
  58. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  59. enableSSHAPIRequests: true,
  60. })
  61. }
  62. func TestUnfrontedMeekHTTPS(t *testing.T) {
  63. runServer(t,
  64. &runServerConfig{
  65. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  66. enableSSHAPIRequests: true,
  67. })
  68. }
  69. func TestWebTransportAPIRequests(t *testing.T) {
  70. runServer(t,
  71. &runServerConfig{
  72. tunnelProtocol: "OSSH",
  73. enableSSHAPIRequests: false,
  74. })
  75. }
  76. type runServerConfig struct {
  77. tunnelProtocol string
  78. enableSSHAPIRequests bool
  79. }
  80. func runServer(t *testing.T, runConfig *runServerConfig) {
  81. // create a server
  82. serverConfigJSON, _, encodedServerEntry, err := GenerateConfig(
  83. &GenerateConfigParams{
  84. ServerIPAddress: "127.0.0.1",
  85. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  86. WebServerPort: 8000,
  87. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  88. })
  89. if err != nil {
  90. t.Fatalf("error generating server config: %s", err)
  91. }
  92. // customize server config
  93. var serverConfig interface{}
  94. json.Unmarshal(serverConfigJSON, &serverConfig)
  95. serverConfig.(map[string]interface{})["GeoIPDatabaseFilename"] = ""
  96. serverConfig.(map[string]interface{})["TrafficRulesFilename"] = ""
  97. serverConfigJSON, _ = json.Marshal(serverConfig)
  98. // run server
  99. serverWaitGroup := new(sync.WaitGroup)
  100. serverWaitGroup.Add(1)
  101. go func() {
  102. defer serverWaitGroup.Done()
  103. err := RunServices(serverConfigJSON)
  104. if err != nil {
  105. // TODO: wrong goroutine for t.FatalNow()
  106. t.Fatalf("error running server: %s", err)
  107. }
  108. }()
  109. defer func() {
  110. // Test: orderly server shutdown
  111. p, _ := os.FindProcess(os.Getpid())
  112. p.Signal(os.Interrupt)
  113. shutdownTimeout := time.NewTimer(5 * time.Second)
  114. shutdownOk := make(chan struct{}, 1)
  115. go func() {
  116. serverWaitGroup.Wait()
  117. shutdownOk <- *new(struct{})
  118. }()
  119. select {
  120. case <-shutdownOk:
  121. case <-shutdownTimeout.C:
  122. t.Fatalf("server shutdown timeout exceeded")
  123. }
  124. }()
  125. // connect to server with client
  126. // TODO: currently, TargetServerEntry only works with one tunnel
  127. numTunnels := 1
  128. localHTTPProxyPort := 8081
  129. establishTunnelPausePeriodSeconds := 1
  130. // Note: calling LoadConfig ensures all *int config fields are initialized
  131. clientConfigJSON := `
  132. {
  133. "ClientVersion": "0",
  134. "PropagationChannelId": "0",
  135. "SponsorId": "0"
  136. }`
  137. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  138. clientConfig.ConnectionWorkerPoolSize = numTunnels
  139. clientConfig.TunnelPoolSize = numTunnels
  140. clientConfig.DisableRemoteServerListFetcher = true
  141. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  142. clientConfig.TargetServerEntry = string(encodedServerEntry)
  143. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  144. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  145. err = psiphon.InitDataStore(clientConfig)
  146. if err != nil {
  147. t.Fatalf("error initializing client datastore: %s", err)
  148. }
  149. controller, err := psiphon.NewController(clientConfig)
  150. if err != nil {
  151. t.Fatalf("error creating client controller: %s", err)
  152. }
  153. tunnelsEstablished := make(chan struct{}, 1)
  154. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  155. func(notice []byte) {
  156. //fmt.Printf("%s\n", string(notice))
  157. noticeType, payload, err := psiphon.GetNotice(notice)
  158. if err != nil {
  159. return
  160. }
  161. switch noticeType {
  162. case "Tunnels":
  163. count := int(payload["count"].(float64))
  164. if count >= numTunnels {
  165. select {
  166. case tunnelsEstablished <- *new(struct{}):
  167. default:
  168. }
  169. }
  170. }
  171. }))
  172. controllerShutdownBroadcast := make(chan struct{})
  173. controllerWaitGroup := new(sync.WaitGroup)
  174. controllerWaitGroup.Add(1)
  175. go func() {
  176. defer controllerWaitGroup.Done()
  177. controller.Run(controllerShutdownBroadcast)
  178. }()
  179. defer func() {
  180. close(controllerShutdownBroadcast)
  181. shutdownTimeout := time.NewTimer(20 * time.Second)
  182. shutdownOk := make(chan struct{}, 1)
  183. go func() {
  184. controllerWaitGroup.Wait()
  185. shutdownOk <- *new(struct{})
  186. }()
  187. select {
  188. case <-shutdownOk:
  189. case <-shutdownTimeout.C:
  190. t.Fatalf("controller shutdown timeout exceeded")
  191. }
  192. }()
  193. // Test: tunnels must be established within 30 seconds
  194. establishTimeout := time.NewTimer(30 * time.Second)
  195. select {
  196. case <-tunnelsEstablished:
  197. case <-establishTimeout.C:
  198. t.Fatalf("tunnel establish timeout exceeded")
  199. }
  200. // Test: tunneled web site fetch
  201. testUrl := "https://psiphon.ca"
  202. roundTripTimeout := 30 * time.Second
  203. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  204. if err != nil {
  205. t.Fatalf("error initializing proxied HTTP request: %s", err)
  206. }
  207. httpClient := &http.Client{
  208. Transport: &http.Transport{
  209. Proxy: http.ProxyURL(proxyUrl),
  210. },
  211. Timeout: roundTripTimeout,
  212. }
  213. response, err := httpClient.Get(testUrl)
  214. if err != nil {
  215. t.Fatalf("error sending proxied HTTP request: %s", err)
  216. }
  217. _, err = ioutil.ReadAll(response.Body)
  218. if err != nil {
  219. t.Fatalf("error reading proxied HTTP response: %s", err)
  220. }
  221. response.Body.Close()
  222. }