interrupt_dials_test.go 5.9 KB

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