sessionID_test.go 6.9 KB

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