interrupt_dials_test.go 5.1 KB

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