interrupt_dials_test.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * Copyright (c) 2017, 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 psiphon
  20. import (
  21. "context"
  22. "fmt"
  23. "net"
  24. "runtime"
  25. "strings"
  26. "sync"
  27. "testing"
  28. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  31. )
  32. func TestInterruptDials(t *testing.T) {
  33. makeDialers := make(map[string]func(string) Dialer)
  34. makeDialers["TCP"] = func(string) Dialer {
  35. return NewTCPDialer(&DialConfig{})
  36. }
  37. makeDialers["SOCKS4-Proxied"] = func(mockServerAddr string) Dialer {
  38. return NewTCPDialer(
  39. &DialConfig{
  40. UpstreamProxyURL: "socks4a://" + mockServerAddr,
  41. })
  42. }
  43. makeDialers["SOCKS5-Proxied"] = func(mockServerAddr string) Dialer {
  44. return NewTCPDialer(
  45. &DialConfig{
  46. UpstreamProxyURL: "socks5://" + mockServerAddr,
  47. })
  48. }
  49. makeDialers["HTTP-CONNECT-Proxied"] = func(mockServerAddr string) Dialer {
  50. return NewTCPDialer(
  51. &DialConfig{
  52. UpstreamProxyURL: "http://" + mockServerAddr,
  53. })
  54. }
  55. // TODO: test upstreamproxy.ProxyAuthTransport
  56. clientParameters, err := parameters.NewClientParameters(nil)
  57. if err != nil {
  58. t.Fatalf("NewClientParameters failed: %s", err)
  59. }
  60. seed, err := prng.NewSeed()
  61. if err != nil {
  62. t.Fatalf("NewSeed failed: %s", err)
  63. }
  64. makeDialers["TLS"] = func(string) Dialer {
  65. return NewCustomTLSDialer(
  66. &CustomTLSConfig{
  67. ClientParameters: clientParameters,
  68. Dial: NewTCPDialer(&DialConfig{}),
  69. RandomizedTLSProfileSeed: seed,
  70. })
  71. }
  72. dialGoroutineFunctionNames := []string{"NewTCPDialer", "NewCustomTLSDialer"}
  73. for dialerName, makeDialer := range makeDialers {
  74. for _, doTimeout := range []bool{true, false} {
  75. t.Run(
  76. fmt.Sprintf("%s-timeout-%+v", dialerName, doTimeout),
  77. func(t *testing.T) {
  78. runInterruptDials(
  79. t,
  80. doTimeout,
  81. makeDialer,
  82. dialGoroutineFunctionNames)
  83. })
  84. }
  85. }
  86. }
  87. func runInterruptDials(
  88. t *testing.T,
  89. doTimeout bool,
  90. makeDialer func(string) Dialer,
  91. dialGoroutineFunctionNames []string) {
  92. t.Logf("Test timeout: %+v", doTimeout)
  93. noAcceptListener, err := net.Listen("tcp", "127.0.0.1:0")
  94. if err != nil {
  95. t.Fatalf("Listen failed: %s", err)
  96. }
  97. defer noAcceptListener.Close()
  98. noResponseListener, err := net.Listen("tcp", "127.0.0.1:0")
  99. if err != nil {
  100. t.Fatalf("Listen failed: %s", err)
  101. }
  102. defer noResponseListener.Close()
  103. listenerAccepted := make(chan struct{}, 1)
  104. noResponseListenerWaitGroup := new(sync.WaitGroup)
  105. noResponseListenerWaitGroup.Add(1)
  106. defer noResponseListenerWaitGroup.Wait()
  107. go func() {
  108. defer noResponseListenerWaitGroup.Done()
  109. for {
  110. conn, err := noResponseListener.Accept()
  111. if err != nil {
  112. return
  113. }
  114. listenerAccepted <- struct{}{}
  115. var b [1024]byte
  116. for {
  117. _, err := conn.Read(b[:])
  118. if err != nil {
  119. conn.Close()
  120. return
  121. }
  122. }
  123. }
  124. }()
  125. var ctx context.Context
  126. var cancelFunc context.CancelFunc
  127. timeout := 100 * time.Millisecond
  128. if doTimeout {
  129. ctx, cancelFunc = context.WithTimeout(context.Background(), timeout)
  130. } else {
  131. ctx, cancelFunc = context.WithCancel(context.Background())
  132. }
  133. addrs := []string{
  134. noAcceptListener.Addr().String(),
  135. noResponseListener.Addr().String()}
  136. dialTerminated := make(chan struct{}, len(addrs))
  137. for _, addr := range addrs {
  138. go func(addr string) {
  139. conn, err := makeDialer(addr)(ctx, "tcp", addr)
  140. if err == nil {
  141. conn.Close()
  142. }
  143. dialTerminated <- struct{}{}
  144. }(addr)
  145. }
  146. // Wait for noResponseListener to accept to ensure that we exercise
  147. // post-TCP-dial interruption in the case of TLS and proxy dialers that
  148. // do post-TCP-dial handshake I/O as part of their dial.
  149. <-listenerAccepted
  150. if doTimeout {
  151. time.Sleep(timeout)
  152. defer cancelFunc()
  153. } else {
  154. // No timeout, so interrupt with cancel
  155. cancelFunc()
  156. }
  157. startWaiting := time.Now()
  158. for range addrs {
  159. <-dialTerminated
  160. }
  161. // Test: dial interrupt must complete quickly
  162. interruptDuration := time.Since(startWaiting)
  163. if interruptDuration > 100*time.Millisecond {
  164. t.Fatalf("interrupt duration too long: %s", interruptDuration)
  165. }
  166. // Test: interrupted dialers must not leave goroutines running
  167. if findGoroutines(t, dialGoroutineFunctionNames) {
  168. t.Fatalf("unexpected dial goroutines")
  169. }
  170. }
  171. func findGoroutines(t *testing.T, targets []string) bool {
  172. n, _ := runtime.GoroutineProfile(nil)
  173. r := make([]runtime.StackRecord, n)
  174. runtime.GoroutineProfile(r)
  175. found := false
  176. for _, g := range r {
  177. stack := g.Stack()
  178. funcNames := make([]string, len(stack))
  179. for i := 0; i < len(stack); i++ {
  180. funcNames[i] = getFunctionName(stack[i])
  181. }
  182. s := strings.Join(funcNames, ", ")
  183. for _, target := range targets {
  184. if strings.Contains(s, target) {
  185. t.Logf("found dial goroutine: %s", s)
  186. found = true
  187. }
  188. }
  189. }
  190. return found
  191. }
  192. func getFunctionName(pc uintptr) string {
  193. funcName := runtime.FuncForPC(pc).Name()
  194. index := strings.LastIndex(funcName, "/")
  195. if index != -1 {
  196. funcName = funcName[index+1:]
  197. }
  198. return funcName
  199. }