server_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. serverConfigFileContents, serverEntryFileContents, 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(serverConfigFileContents, &serverConfig)
  95. serverConfig.(map[string]interface{})["GeoIPDatabaseFilename"] = ""
  96. serverConfigFileContents, _ = json.Marshal(serverConfig)
  97. // run server
  98. serverWaitGroup := new(sync.WaitGroup)
  99. serverWaitGroup.Add(1)
  100. go func() {
  101. defer serverWaitGroup.Done()
  102. err := RunServices([][]byte{serverConfigFileContents})
  103. if err != nil {
  104. // TODO: wrong goroutine for t.FatalNow()
  105. t.Fatalf("error running server: %s", err)
  106. }
  107. }()
  108. defer func() {
  109. // Test: orderly server shutdown
  110. p, _ := os.FindProcess(os.Getpid())
  111. p.Signal(os.Interrupt)
  112. shutdownTimeout := time.NewTimer(5 * time.Second)
  113. shutdownOk := make(chan struct{}, 1)
  114. go func() {
  115. serverWaitGroup.Wait()
  116. shutdownOk <- *new(struct{})
  117. }()
  118. select {
  119. case <-shutdownOk:
  120. case <-shutdownTimeout.C:
  121. t.Fatalf("server shutdown timeout exceeded")
  122. }
  123. }()
  124. // connect to server with client
  125. // TODO: currently, TargetServerEntry only works with one tunnel
  126. numTunnels := 1
  127. localHTTPProxyPort := 8080
  128. establishTunnelPausePeriodSeconds := 1
  129. // Note: calling LoadConfig ensures all *int config fields are initialized
  130. configJson := `
  131. {
  132. "ClientVersion": "0",
  133. "PropagationChannelId": "0",
  134. "SponsorId": "0"
  135. }`
  136. clientConfig, _ := psiphon.LoadConfig([]byte(configJson))
  137. clientConfig.ConnectionWorkerPoolSize = numTunnels
  138. clientConfig.TunnelPoolSize = numTunnels
  139. clientConfig.DisableRemoteServerListFetcher = true
  140. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  141. clientConfig.TargetServerEntry = string(serverEntryFileContents)
  142. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  143. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  144. err = psiphon.InitDataStore(clientConfig)
  145. if err != nil {
  146. t.Fatalf("error initializing client datastore: %s", err)
  147. }
  148. controller, err := psiphon.NewController(clientConfig)
  149. if err != nil {
  150. t.Fatalf("error creating client controller: %s", err)
  151. }
  152. tunnelsEstablished := make(chan struct{}, 1)
  153. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  154. func(notice []byte) {
  155. //fmt.Printf("%s\n", string(notice))
  156. noticeType, payload, err := psiphon.GetNotice(notice)
  157. if err != nil {
  158. return
  159. }
  160. switch noticeType {
  161. case "Tunnels":
  162. count := int(payload["count"].(float64))
  163. if count >= numTunnels {
  164. select {
  165. case tunnelsEstablished <- *new(struct{}):
  166. default:
  167. }
  168. }
  169. }
  170. }))
  171. controllerShutdownBroadcast := make(chan struct{})
  172. controllerWaitGroup := new(sync.WaitGroup)
  173. controllerWaitGroup.Add(1)
  174. go func() {
  175. defer controllerWaitGroup.Done()
  176. controller.Run(controllerShutdownBroadcast)
  177. }()
  178. defer func() {
  179. close(controllerShutdownBroadcast)
  180. shutdownTimeout := time.NewTimer(20 * time.Second)
  181. shutdownOk := make(chan struct{}, 1)
  182. go func() {
  183. controllerWaitGroup.Wait()
  184. shutdownOk <- *new(struct{})
  185. }()
  186. select {
  187. case <-shutdownOk:
  188. case <-shutdownTimeout.C:
  189. t.Fatalf("controller shutdown timeout exceeded")
  190. }
  191. }()
  192. // Test: tunnels must be established within 30 seconds
  193. establishTimeout := time.NewTimer(30 * time.Second)
  194. select {
  195. case <-tunnelsEstablished:
  196. case <-establishTimeout.C:
  197. t.Fatalf("tunnel establish timeout exceeded")
  198. }
  199. // Test: tunneled web site fetch
  200. testUrl := "https://psiphon.ca"
  201. roundTripTimeout := 30 * time.Second
  202. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  203. if err != nil {
  204. t.Fatalf("error initializing proxied HTTP request: %s", err)
  205. }
  206. httpClient := &http.Client{
  207. Transport: &http.Transport{
  208. Proxy: http.ProxyURL(proxyUrl),
  209. },
  210. Timeout: roundTripTimeout,
  211. }
  212. response, err := httpClient.Get(testUrl)
  213. if err != nil {
  214. t.Fatalf("error sending proxied HTTP request: %s", err)
  215. }
  216. _, err = ioutil.ReadAll(response.Body)
  217. if err != nil {
  218. t.Fatalf("error reading proxied HTTP response: %s", err)
  219. }
  220. response.Body.Close()
  221. }