sessionID_test.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "context"
  22. "encoding/json"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "os"
  27. "path/filepath"
  28. "strings"
  29. "sync"
  30. "testing"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  35. )
  36. func TestDuplicateSessionID(t *testing.T) {
  37. testDataDirName, err := ioutil.TempDir("", "psiphond-duplicate-session-id-test")
  38. if err != nil {
  39. t.Fatalf("TempDir failed: %s", err)
  40. }
  41. defer os.RemoveAll(testDataDirName)
  42. psiphon.SetEmitDiagnosticNotices(true, true)
  43. // Configure server
  44. generateConfigParams := &GenerateConfigParams{
  45. ServerIPAddress: "127.0.0.1",
  46. TunnelProtocolPorts: map[string]int{"OSSH": 4000},
  47. }
  48. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  49. if err != nil {
  50. t.Fatalf("error generating server config: %s", err)
  51. }
  52. var serverConfig map[string]interface{}
  53. json.Unmarshal(serverConfigJSON, &serverConfig)
  54. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  55. serverConfig["LogLevel"] = "debug"
  56. serverConfigJSON, _ = json.Marshal(serverConfig)
  57. numConcurrentClients := 50
  58. stoppingEvent := "stopping existing client with duplicate session ID"
  59. abortingEvent := "aborting new client with duplicate session ID"
  60. // Sufficiently buffer channel so log callback handler doesn't cause server
  61. // operations to block while handling concurrent clients.
  62. duplicateSessionIDEvents := make(chan string, numConcurrentClients)
  63. setLogCallback(func(log []byte) {
  64. strLog := string(log)
  65. var event string
  66. if strings.Contains(strLog, stoppingEvent) {
  67. event = stoppingEvent
  68. } else if strings.Contains(strLog, abortingEvent) {
  69. event = abortingEvent
  70. }
  71. if event != "" {
  72. select {
  73. case duplicateSessionIDEvents <- event:
  74. default:
  75. }
  76. }
  77. })
  78. // Run server
  79. serverWaitGroup := new(sync.WaitGroup)
  80. serverWaitGroup.Add(1)
  81. go func() {
  82. defer serverWaitGroup.Done()
  83. err := RunServices(serverConfigJSON)
  84. if err != nil {
  85. t.Errorf("error running server: %s", err)
  86. }
  87. }()
  88. defer func() {
  89. p, _ := os.FindProcess(os.Getpid())
  90. p.Signal(os.Interrupt)
  91. serverWaitGroup.Wait()
  92. }()
  93. // TODO: monitor logs for more robust wait-until-loaded.
  94. time.Sleep(1 * time.Second)
  95. // Initialize tunnel clients. Bypassing Controller and using Tunnel directly
  96. // to permit multiple concurrent clients.
  97. //
  98. // Limitation: all tunnels still use one singleton datastore and notice
  99. // handler.
  100. err = psiphon.SetNoticeWriter(io.Discard)
  101. if err != nil {
  102. t.Fatalf("error setting notice writer: %s", err)
  103. }
  104. defer psiphon.ResetNoticeWriter()
  105. clientConfigJSONTemplate := `
  106. {
  107. "DataRootDirectory" : "%s",
  108. "SponsorId" : "0000000000000000",
  109. "PropagationChannelId" : "0000000000000000",
  110. "SessionID" : "00000000000000000000000000000000"
  111. }`
  112. clientConfigJSON := fmt.Sprintf(
  113. clientConfigJSONTemplate,
  114. testDataDirName)
  115. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  116. if err != nil {
  117. t.Fatalf("LoadConfig failed: %s", err)
  118. }
  119. err = clientConfig.Commit(false)
  120. if err != nil {
  121. t.Fatalf("Commit failed: %s", err)
  122. }
  123. resolver := psiphon.NewResolver(clientConfig, true)
  124. defer resolver.Stop()
  125. clientConfig.SetResolver(resolver)
  126. err = psiphon.OpenDataStore(clientConfig)
  127. if err != nil {
  128. t.Fatalf("OpenDataStore failed: %s", err)
  129. }
  130. defer psiphon.CloseDataStore()
  131. serverEntry, err := protocol.DecodeServerEntry(
  132. string(encodedServerEntry),
  133. common.GetCurrentTimestamp(),
  134. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  135. if err != nil {
  136. t.Fatalf("DecodeServerEntry failed: %s", err)
  137. }
  138. dialTunnel := func(ctx context.Context) *psiphon.Tunnel {
  139. dialParams, err := psiphon.MakeDialParameters(
  140. clientConfig,
  141. nil,
  142. nil,
  143. nil,
  144. nil,
  145. func(_ *protocol.ServerEntry, _ string) bool { return false },
  146. func(_ *protocol.ServerEntry) (string, bool) { return "OSSH", true },
  147. serverEntry,
  148. nil,
  149. nil,
  150. false,
  151. 0,
  152. 0)
  153. if err != nil {
  154. t.Fatalf("MakeDialParameters failed: %s", err)
  155. }
  156. tunnel, err := psiphon.ConnectTunnel(
  157. ctx,
  158. clientConfig,
  159. time.Now(),
  160. dialParams)
  161. if err != nil {
  162. t.Fatalf("ConnectTunnel failed: %s", err)
  163. }
  164. return tunnel
  165. }
  166. handshakeTunnel := func(tunnel *psiphon.Tunnel, expectSuccess bool) {
  167. _, err = psiphon.NewServerContext(tunnel)
  168. if expectSuccess && err != nil || (!expectSuccess && err == nil) {
  169. t.Fatalf("Unexpected handshake result: %s", err)
  170. }
  171. }
  172. ctx, cancelFunc := context.WithCancel(context.Background())
  173. defer cancelFunc()
  174. // Test: normal case
  175. //
  176. // First tunnel, t1, fully establishes and then is superceded by new tunnel, t2.
  177. t1 := dialTunnel(ctx)
  178. handshakeTunnel(t1, true)
  179. t2 := dialTunnel(ctx)
  180. expectEvent := <-duplicateSessionIDEvents
  181. if expectEvent != stoppingEvent {
  182. t.Fatalf("Unexpected duplicate session ID event")
  183. }
  184. handshakeTunnel(t2, true)
  185. t1.Close(true)
  186. t2.Close(true)
  187. // Test: simultaneous/interleaved case
  188. //
  189. // First tunnel connects but then tries to handshake after second tunnel has
  190. // connected.
  191. t1 = dialTunnel(ctx)
  192. // TODO: await log confirmation that t1 completed registerEstablishedClient?
  193. // Otherwise, there's some small chance that t2 is the "first" tunnel and the
  194. // test could fail (false negative).
  195. t2 = dialTunnel(ctx)
  196. expectEvent = <-duplicateSessionIDEvents
  197. if expectEvent != stoppingEvent {
  198. t.Fatalf("Unexpected duplicate session ID event")
  199. }
  200. handshakeTunnel(t1, false)
  201. handshakeTunnel(t2, true)
  202. t1.Close(true)
  203. t2.Close(true)
  204. // Test: 50 concurrent clients, all with the same session ID.
  205. //
  206. // This should be enough concurrent clients to trigger both the "stopping"
  207. // and "aborting" duplicate session ID cases.
  208. tunnels := make([]*psiphon.Tunnel, numConcurrentClients)
  209. waitGroup := new(sync.WaitGroup)
  210. for i := 0; i < numConcurrentClients; i++ {
  211. waitGroup.Add(1)
  212. go func(i int) {
  213. defer waitGroup.Done()
  214. tunnels[i] = dialTunnel(ctx)
  215. }(i)
  216. }
  217. waitGroup.Wait()
  218. for _, t := range tunnels {
  219. if t == nil {
  220. continue
  221. }
  222. t.Close(true)
  223. }
  224. receivedEvents := make(map[string]int)
  225. for i := 0; i < numConcurrentClients-1; i++ {
  226. receivedEvents[<-duplicateSessionIDEvents] += 1
  227. }
  228. if receivedEvents[stoppingEvent] < 1 {
  229. t.Fatalf("No stopping events received")
  230. }
  231. if receivedEvents[abortingEvent] < 1 {
  232. t.Fatalf("No aborting events received")
  233. }
  234. }