websocketproxy_server.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package server
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "net/http"
  19. "net/url"
  20. "time"
  21. "github.com/gorilla/websocket"
  22. "github.com/koding/websocketproxy"
  23. "yunion.io/x/onecloud/pkg/webconsole/session"
  24. )
  25. type WebsocketProxyServer struct {
  26. Session *session.SSession
  27. proxy *websocketproxy.WebsocketProxy
  28. cookie string
  29. }
  30. func NewWebsocketProxyServer(s *session.SSession) (*WebsocketProxyServer, error) {
  31. info := s.ISessionData.(*session.RemoteConsoleInfo)
  32. if info.Url == "" {
  33. return nil, fmt.Errorf("Empty proxy url")
  34. }
  35. u, err := url.Parse(info.Url)
  36. if err != nil {
  37. return nil, fmt.Errorf("Parse url %s: %v", info.Url, err)
  38. }
  39. proxySrv := websocketproxy.NewProxy(u)
  40. proxySrv.Dialer = &websocket.Dialer{
  41. Proxy: http.ProxyFromEnvironment,
  42. HandshakeTimeout: 45 * time.Second,
  43. TLSClientConfig: &tls.Config{
  44. InsecureSkipVerify: true,
  45. },
  46. }
  47. proxySrv.Backend = func(_ *http.Request) *url.URL {
  48. return u
  49. }
  50. proxySrv.Upgrader = &upgrader
  51. return &WebsocketProxyServer{
  52. Session: s,
  53. proxy: proxySrv,
  54. cookie: info.Cookie,
  55. }, nil
  56. }
  57. func (s *WebsocketProxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  58. if len(s.cookie) > 0 {
  59. r.Header.Set("Cookie", s.cookie)
  60. }
  61. s.proxy.ServeHTTP(w, r)
  62. }