interrupt_dials_test.go 5.6 KB

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