interrupt_dials_test.go 6.0 KB

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