1
0

client_server_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package websocket
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "encoding/base64"
  10. "encoding/binary"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "net/http"
  15. "net/http/cookiejar"
  16. "net/http/httptest"
  17. "net/url"
  18. "reflect"
  19. "strings"
  20. "testing"
  21. "time"
  22. )
  23. var cstUpgrader = Upgrader{
  24. Subprotocols: []string{"p0", "p1"},
  25. ReadBufferSize: 1024,
  26. WriteBufferSize: 1024,
  27. EnableCompression: true,
  28. Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) {
  29. http.Error(w, reason.Error(), status)
  30. },
  31. }
  32. var cstDialer = Dialer{
  33. Subprotocols: []string{"p1", "p2"},
  34. ReadBufferSize: 1024,
  35. WriteBufferSize: 1024,
  36. HandshakeTimeout: 30 * time.Second,
  37. }
  38. type cstHandler struct{ *testing.T }
  39. type cstServer struct {
  40. *httptest.Server
  41. URL string
  42. }
  43. const (
  44. cstPath = "/a/b"
  45. cstRawQuery = "x=y"
  46. cstRequestURI = cstPath + "?" + cstRawQuery
  47. )
  48. func newServer(t *testing.T) *cstServer {
  49. var s cstServer
  50. s.Server = httptest.NewServer(cstHandler{t})
  51. s.Server.URL += cstRequestURI
  52. s.URL = makeWsProto(s.Server.URL)
  53. return &s
  54. }
  55. func newTLSServer(t *testing.T) *cstServer {
  56. var s cstServer
  57. s.Server = httptest.NewTLSServer(cstHandler{t})
  58. s.Server.URL += cstRequestURI
  59. s.URL = makeWsProto(s.Server.URL)
  60. return &s
  61. }
  62. func (t cstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  63. if r.URL.Path != cstPath {
  64. t.Logf("path=%v, want %v", r.URL.Path, cstPath)
  65. http.Error(w, "bad path", 400)
  66. return
  67. }
  68. if r.URL.RawQuery != cstRawQuery {
  69. t.Logf("query=%v, want %v", r.URL.RawQuery, cstRawQuery)
  70. http.Error(w, "bad path", 400)
  71. return
  72. }
  73. subprotos := Subprotocols(r)
  74. if !reflect.DeepEqual(subprotos, cstDialer.Subprotocols) {
  75. t.Logf("subprotols=%v, want %v", subprotos, cstDialer.Subprotocols)
  76. http.Error(w, "bad protocol", 400)
  77. return
  78. }
  79. ws, err := cstUpgrader.Upgrade(w, r, http.Header{"Set-Cookie": {"sessionID=1234"}})
  80. if err != nil {
  81. t.Logf("Upgrade: %v", err)
  82. return
  83. }
  84. defer ws.Close()
  85. if ws.Subprotocol() != "p1" {
  86. t.Logf("Subprotocol() = %s, want p1", ws.Subprotocol())
  87. ws.Close()
  88. return
  89. }
  90. op, rd, err := ws.NextReader()
  91. if err != nil {
  92. t.Logf("NextReader: %v", err)
  93. return
  94. }
  95. wr, err := ws.NextWriter(op)
  96. if err != nil {
  97. t.Logf("NextWriter: %v", err)
  98. return
  99. }
  100. if _, err = io.Copy(wr, rd); err != nil {
  101. t.Logf("NextWriter: %v", err)
  102. return
  103. }
  104. if err := wr.Close(); err != nil {
  105. t.Logf("Close: %v", err)
  106. return
  107. }
  108. }
  109. func makeWsProto(s string) string {
  110. return "ws" + strings.TrimPrefix(s, "http")
  111. }
  112. func sendRecv(t *testing.T, ws *Conn) {
  113. const message = "Hello World!"
  114. if err := ws.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
  115. t.Fatalf("SetWriteDeadline: %v", err)
  116. }
  117. if err := ws.WriteMessage(TextMessage, []byte(message)); err != nil {
  118. t.Fatalf("WriteMessage: %v", err)
  119. }
  120. if err := ws.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
  121. t.Fatalf("SetReadDeadline: %v", err)
  122. }
  123. _, p, err := ws.ReadMessage()
  124. if err != nil {
  125. t.Fatalf("ReadMessage: %v", err)
  126. }
  127. if string(p) != message {
  128. t.Fatalf("message=%s, want %s", p, message)
  129. }
  130. }
  131. func TestProxyDial(t *testing.T) {
  132. s := newServer(t)
  133. defer s.Close()
  134. surl, _ := url.Parse(s.Server.URL)
  135. cstDialer := cstDialer // make local copy for modification on next line.
  136. cstDialer.Proxy = http.ProxyURL(surl)
  137. connect := false
  138. origHandler := s.Server.Config.Handler
  139. // Capture the request Host header.
  140. s.Server.Config.Handler = http.HandlerFunc(
  141. func(w http.ResponseWriter, r *http.Request) {
  142. if r.Method == "CONNECT" {
  143. connect = true
  144. w.WriteHeader(200)
  145. return
  146. }
  147. if !connect {
  148. t.Log("connect not received")
  149. http.Error(w, "connect not received", 405)
  150. return
  151. }
  152. origHandler.ServeHTTP(w, r)
  153. })
  154. ws, _, err := cstDialer.Dial(s.URL, nil)
  155. if err != nil {
  156. t.Fatalf("Dial: %v", err)
  157. }
  158. defer ws.Close()
  159. sendRecv(t, ws)
  160. }
  161. func TestProxyAuthorizationDial(t *testing.T) {
  162. s := newServer(t)
  163. defer s.Close()
  164. surl, _ := url.Parse(s.Server.URL)
  165. surl.User = url.UserPassword("username", "password")
  166. cstDialer := cstDialer // make local copy for modification on next line.
  167. cstDialer.Proxy = http.ProxyURL(surl)
  168. connect := false
  169. origHandler := s.Server.Config.Handler
  170. // Capture the request Host header.
  171. s.Server.Config.Handler = http.HandlerFunc(
  172. func(w http.ResponseWriter, r *http.Request) {
  173. proxyAuth := r.Header.Get("Proxy-Authorization")
  174. expectedProxyAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("username:password"))
  175. if r.Method == "CONNECT" && proxyAuth == expectedProxyAuth {
  176. connect = true
  177. w.WriteHeader(200)
  178. return
  179. }
  180. if !connect {
  181. t.Log("connect with proxy authorization not received")
  182. http.Error(w, "connect with proxy authorization not received", 405)
  183. return
  184. }
  185. origHandler.ServeHTTP(w, r)
  186. })
  187. ws, _, err := cstDialer.Dial(s.URL, nil)
  188. if err != nil {
  189. t.Fatalf("Dial: %v", err)
  190. }
  191. defer ws.Close()
  192. sendRecv(t, ws)
  193. }
  194. func TestDial(t *testing.T) {
  195. s := newServer(t)
  196. defer s.Close()
  197. ws, _, err := cstDialer.Dial(s.URL, nil)
  198. if err != nil {
  199. t.Fatalf("Dial: %v", err)
  200. }
  201. defer ws.Close()
  202. sendRecv(t, ws)
  203. }
  204. func TestDialCookieJar(t *testing.T) {
  205. s := newServer(t)
  206. defer s.Close()
  207. jar, _ := cookiejar.New(nil)
  208. d := cstDialer
  209. d.Jar = jar
  210. u, _ := url.Parse(s.URL)
  211. switch u.Scheme {
  212. case "ws":
  213. u.Scheme = "http"
  214. case "wss":
  215. u.Scheme = "https"
  216. }
  217. cookies := []*http.Cookie{{Name: "gorilla", Value: "ws", Path: "/"}}
  218. d.Jar.SetCookies(u, cookies)
  219. ws, _, err := d.Dial(s.URL, nil)
  220. if err != nil {
  221. t.Fatalf("Dial: %v", err)
  222. }
  223. defer ws.Close()
  224. var gorilla string
  225. var sessionID string
  226. for _, c := range d.Jar.Cookies(u) {
  227. if c.Name == "gorilla" {
  228. gorilla = c.Value
  229. }
  230. if c.Name == "sessionID" {
  231. sessionID = c.Value
  232. }
  233. }
  234. if gorilla != "ws" {
  235. t.Error("Cookie not present in jar.")
  236. }
  237. if sessionID != "1234" {
  238. t.Error("Set-Cookie not received from the server.")
  239. }
  240. sendRecv(t, ws)
  241. }
  242. func TestDialTLS(t *testing.T) {
  243. s := newTLSServer(t)
  244. defer s.Close()
  245. certs := x509.NewCertPool()
  246. for _, c := range s.TLS.Certificates {
  247. roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
  248. if err != nil {
  249. t.Fatalf("error parsing server's root cert: %v", err)
  250. }
  251. for _, root := range roots {
  252. certs.AddCert(root)
  253. }
  254. }
  255. d := cstDialer
  256. d.TLSClientConfig = &tls.Config{RootCAs: certs}
  257. ws, _, err := d.Dial(s.URL, nil)
  258. if err != nil {
  259. t.Fatalf("Dial: %v", err)
  260. }
  261. defer ws.Close()
  262. sendRecv(t, ws)
  263. }
  264. func xTestDialTLSBadCert(t *testing.T) {
  265. // This test is deactivated because of noisy logging from the net/http package.
  266. s := newTLSServer(t)
  267. defer s.Close()
  268. ws, _, err := cstDialer.Dial(s.URL, nil)
  269. if err == nil {
  270. ws.Close()
  271. t.Fatalf("Dial: nil")
  272. }
  273. }
  274. func TestDialTLSNoVerify(t *testing.T) {
  275. s := newTLSServer(t)
  276. defer s.Close()
  277. d := cstDialer
  278. d.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  279. ws, _, err := d.Dial(s.URL, nil)
  280. if err != nil {
  281. t.Fatalf("Dial: %v", err)
  282. }
  283. defer ws.Close()
  284. sendRecv(t, ws)
  285. }
  286. func TestDialTimeout(t *testing.T) {
  287. s := newServer(t)
  288. defer s.Close()
  289. d := cstDialer
  290. d.HandshakeTimeout = -1
  291. ws, _, err := d.Dial(s.URL, nil)
  292. if err == nil {
  293. ws.Close()
  294. t.Fatalf("Dial: nil")
  295. }
  296. }
  297. func TestDialBadScheme(t *testing.T) {
  298. s := newServer(t)
  299. defer s.Close()
  300. ws, _, err := cstDialer.Dial(s.Server.URL, nil)
  301. if err == nil {
  302. ws.Close()
  303. t.Fatalf("Dial: nil")
  304. }
  305. }
  306. func TestDialBadOrigin(t *testing.T) {
  307. s := newServer(t)
  308. defer s.Close()
  309. ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}})
  310. if err == nil {
  311. ws.Close()
  312. t.Fatalf("Dial: nil")
  313. }
  314. if resp == nil {
  315. t.Fatalf("resp=nil, err=%v", err)
  316. }
  317. if resp.StatusCode != http.StatusForbidden {
  318. t.Fatalf("status=%d, want %d", resp.StatusCode, http.StatusForbidden)
  319. }
  320. }
  321. func TestDialBadHeader(t *testing.T) {
  322. s := newServer(t)
  323. defer s.Close()
  324. for _, k := range []string{"Upgrade",
  325. "Connection",
  326. "Sec-Websocket-Key",
  327. "Sec-Websocket-Version",
  328. "Sec-Websocket-Protocol"} {
  329. h := http.Header{}
  330. h.Set(k, "bad")
  331. ws, _, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}})
  332. if err == nil {
  333. ws.Close()
  334. t.Errorf("Dial with header %s returned nil", k)
  335. }
  336. }
  337. }
  338. func TestBadMethod(t *testing.T) {
  339. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  340. ws, err := cstUpgrader.Upgrade(w, r, nil)
  341. if err == nil {
  342. t.Errorf("handshake succeeded, expect fail")
  343. ws.Close()
  344. }
  345. }))
  346. defer s.Close()
  347. req, err := http.NewRequest("POST", s.URL, strings.NewReader(""))
  348. if err != nil {
  349. t.Fatalf("NewRequest returned error %v", err)
  350. }
  351. req.Header.Set("Connection", "upgrade")
  352. req.Header.Set("Upgrade", "websocket")
  353. req.Header.Set("Sec-Websocket-Version", "13")
  354. resp, err := http.DefaultClient.Do(req)
  355. if err != nil {
  356. t.Fatalf("Do returned error %v", err)
  357. }
  358. resp.Body.Close()
  359. if resp.StatusCode != http.StatusMethodNotAllowed {
  360. t.Errorf("Status = %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed)
  361. }
  362. }
  363. func TestHandshake(t *testing.T) {
  364. s := newServer(t)
  365. defer s.Close()
  366. ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Origin": {s.URL}})
  367. if err != nil {
  368. t.Fatalf("Dial: %v", err)
  369. }
  370. defer ws.Close()
  371. var sessionID string
  372. for _, c := range resp.Cookies() {
  373. if c.Name == "sessionID" {
  374. sessionID = c.Value
  375. }
  376. }
  377. if sessionID != "1234" {
  378. t.Error("Set-Cookie not received from the server.")
  379. }
  380. if ws.Subprotocol() != "p1" {
  381. t.Errorf("ws.Subprotocol() = %s, want p1", ws.Subprotocol())
  382. }
  383. sendRecv(t, ws)
  384. }
  385. func TestRespOnBadHandshake(t *testing.T) {
  386. const expectedStatus = http.StatusGone
  387. const expectedBody = "This is the response body."
  388. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  389. w.WriteHeader(expectedStatus)
  390. io.WriteString(w, expectedBody)
  391. }))
  392. defer s.Close()
  393. ws, resp, err := cstDialer.Dial(makeWsProto(s.URL), nil)
  394. if err == nil {
  395. ws.Close()
  396. t.Fatalf("Dial: nil")
  397. }
  398. if resp == nil {
  399. t.Fatalf("resp=nil, err=%v", err)
  400. }
  401. if resp.StatusCode != expectedStatus {
  402. t.Errorf("resp.StatusCode=%d, want %d", resp.StatusCode, expectedStatus)
  403. }
  404. p, err := ioutil.ReadAll(resp.Body)
  405. if err != nil {
  406. t.Fatalf("ReadFull(resp.Body) returned error %v", err)
  407. }
  408. if string(p) != expectedBody {
  409. t.Errorf("resp.Body=%s, want %s", p, expectedBody)
  410. }
  411. }
  412. // TestHostHeader confirms that the host header provided in the call to Dial is
  413. // sent to the server.
  414. func TestHostHeader(t *testing.T) {
  415. s := newServer(t)
  416. defer s.Close()
  417. specifiedHost := make(chan string, 1)
  418. origHandler := s.Server.Config.Handler
  419. // Capture the request Host header.
  420. s.Server.Config.Handler = http.HandlerFunc(
  421. func(w http.ResponseWriter, r *http.Request) {
  422. specifiedHost <- r.Host
  423. origHandler.ServeHTTP(w, r)
  424. })
  425. ws, _, err := cstDialer.Dial(s.URL, http.Header{"Host": {"testhost"}})
  426. if err != nil {
  427. t.Fatalf("Dial: %v", err)
  428. }
  429. defer ws.Close()
  430. if gotHost := <-specifiedHost; gotHost != "testhost" {
  431. t.Fatalf("gotHost = %q, want \"testhost\"", gotHost)
  432. }
  433. sendRecv(t, ws)
  434. }
  435. func TestDialCompression(t *testing.T) {
  436. s := newServer(t)
  437. defer s.Close()
  438. dialer := cstDialer
  439. dialer.EnableCompression = true
  440. ws, _, err := dialer.Dial(s.URL, nil)
  441. if err != nil {
  442. t.Fatalf("Dial: %v", err)
  443. }
  444. defer ws.Close()
  445. sendRecv(t, ws)
  446. }
  447. func TestSocksProxyDial(t *testing.T) {
  448. s := newServer(t)
  449. defer s.Close()
  450. proxyListener, err := net.Listen("tcp", "127.0.0.1:0")
  451. if err != nil {
  452. t.Fatalf("listen failed: %v", err)
  453. }
  454. defer proxyListener.Close()
  455. go func() {
  456. c1, err := proxyListener.Accept()
  457. if err != nil {
  458. t.Errorf("proxy accept failed: %v", err)
  459. return
  460. }
  461. defer c1.Close()
  462. c1.SetDeadline(time.Now().Add(30 * time.Second))
  463. buf := make([]byte, 32)
  464. if _, err := io.ReadFull(c1, buf[:3]); err != nil {
  465. t.Errorf("read failed: %v", err)
  466. return
  467. }
  468. if want := []byte{5, 1, 0}; !bytes.Equal(want, buf[:len(want)]) {
  469. t.Errorf("read %x, want %x", buf[:len(want)], want)
  470. }
  471. if _, err := c1.Write([]byte{5, 0}); err != nil {
  472. t.Errorf("write failed: %v", err)
  473. return
  474. }
  475. if _, err := io.ReadFull(c1, buf[:10]); err != nil {
  476. t.Errorf("read failed: %v", err)
  477. return
  478. }
  479. if want := []byte{5, 1, 0, 1}; !bytes.Equal(want, buf[:len(want)]) {
  480. t.Errorf("read %x, want %x", buf[:len(want)], want)
  481. return
  482. }
  483. buf[1] = 0
  484. if _, err := c1.Write(buf[:10]); err != nil {
  485. t.Errorf("write failed: %v", err)
  486. return
  487. }
  488. ip := net.IP(buf[4:8])
  489. port := binary.BigEndian.Uint16(buf[8:10])
  490. c2, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: ip, Port: int(port)})
  491. if err != nil {
  492. t.Errorf("dial failed; %v", err)
  493. return
  494. }
  495. defer c2.Close()
  496. done := make(chan struct{})
  497. go func() {
  498. io.Copy(c1, c2)
  499. close(done)
  500. }()
  501. io.Copy(c2, c1)
  502. <-done
  503. }()
  504. purl, err := url.Parse("socks5://" + proxyListener.Addr().String())
  505. if err != nil {
  506. t.Fatalf("parse failed: %v", err)
  507. }
  508. cstDialer := cstDialer // make local copy for modification on next line.
  509. cstDialer.Proxy = http.ProxyURL(purl)
  510. ws, _, err := cstDialer.Dial(s.URL, nil)
  511. if err != nil {
  512. t.Fatalf("Dial: %v", err)
  513. }
  514. defer ws.Close()
  515. sendRecv(t, ws)
  516. }