interrupt_dials_test.go 6.3 KB

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