interrupt_dials_test.go 5.4 KB

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