예제 #1
1
파일: apiclient.go 프로젝트: bac/juju
// connectStream is the internal version of ConnectStream. It differs from
// ConnectStream only in that it will not retry the connection if it encounters
// discharge-required error.
func (st *state) connectStream(path string, attrs url.Values) (base.Stream, error) {
	path, err := apiPath(st.modelTag, path)
	if err != nil {
		return nil, errors.Trace(err)
	}
	target := url.URL{
		Scheme:   "wss",
		Host:     st.addr,
		Path:     path,
		RawQuery: attrs.Encode(),
	}
	cfg, err := websocket.NewConfig(target.String(), "http://localhost/")
	if st.tag != "" {
		cfg.Header = utils.BasicAuthHeader(st.tag, st.password)
	}
	if st.nonce != "" {
		cfg.Header.Set(params.MachineNonceHeader, st.nonce)
	}
	// Add any cookies because they will not be sent to websocket
	// connections by default.
	st.addCookiesToHeader(cfg.Header)

	cfg.TlsConfig = st.tlsConfig
	connection, err := websocketDialConfig(cfg)
	if err != nil {
		return nil, err
	}
	if err := readInitialStreamError(connection); err != nil {
		return nil, errors.Trace(err)
	}
	return connection, nil
}
예제 #2
0
파일: shell_test.go 프로젝트: tsuru/tsuru
func (s *S) TestAppShellUnauthorizedError(c *check.C) {
	a := app.App{
		Name:      "someapp",
		Platform:  "zend",
		TeamOwner: s.team.Name,
	}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = s.provisioner.AddUnits(&a, 1, "web", nil)
	c.Assert(err, check.IsNil)
	m := RunServer(true)
	server := httptest.NewServer(m)
	defer server.Close()
	testServerURL, err := url.Parse(server.URL)
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("ws://%s/apps/%s/shell?width=140&height=38&term=xterm", testServerURL.Host, a.Name)
	config, err := websocket.NewConfig(url, "ws://localhost/")
	c.Assert(err, check.IsNil)
	wsConn, err := websocket.DialConfig(config)
	c.Assert(err, check.IsNil)
	defer wsConn.Close()
	_, err = wsConn.Write([]byte("echo test"))
	c.Assert(err, check.IsNil)
	var result string
	err = tsurutest.WaitCondition(5*time.Second, func() bool {
		part, readErr := ioutil.ReadAll(wsConn)
		if readErr != nil {
			return false
		}
		result += string(part)
		return result == "Error: no token provided or session expired, please login again\n"
	})
	c.Assert(err, check.IsNil)
}
예제 #3
0
파일: client.go 프로젝트: cleblanc87/rack
func (c *Client) Stream(path string, headers map[string]string, in io.Reader, out io.WriteCloser) error {
	origin := fmt.Sprintf("https://%s", c.Host)
	endpoint := fmt.Sprintf("wss://%s%s", c.Host, path)

	config, err := websocket.NewConfig(endpoint, origin)

	if err != nil {
		return err
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	config.Header.Set("Version", c.Version)

	userpass := fmt.Sprintf("convox:%s", c.Password)
	userpass_encoded := base64.StdEncoding.EncodeToString([]byte(userpass))

	config.Header.Add("Authorization", fmt.Sprintf("Basic %s", userpass_encoded))

	for k, v := range headers {
		config.Header.Add(k, v)
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	var ws *websocket.Conn

	if proxy := os.Getenv("HTTPS_PROXY"); proxy != "" {
		ws, err = c.proxyWebsocket(config, proxy)
	} else {
		ws, err = websocket.DialConfig(config)
	}

	if err != nil {
		return err
	}

	defer ws.Close()

	var wg sync.WaitGroup

	if in != nil {
		go io.Copy(ws, in)
	}

	if out != nil {
		wg.Add(1)
		go copyAsync(out, ws, &wg)
	}

	wg.Wait()

	out.Close()

	return nil
}
예제 #4
0
func (prod *Websocket) serve() {
	defer prod.WorkerDone()

	listen, err := shared.NewStopListener(prod.address)
	if err != nil {
		Log.Error.Print("Websocket: ", err)
		return // ### return, could not connect ###
	}

	config, err := websocket.NewConfig(prod.address, prod.path)
	if err != nil {
		Log.Error.Print("Websocket: ", err)
		return // ### return, could not connect ###
	}

	srv := http.Server{
		Handler: websocket.Server{
			Handler: prod.handleConnection,
			Config:  *config,
		},
		ReadTimeout: prod.readTimeoutSec,
	}

	prod.listen = listen

	err = srv.Serve(prod.listen)
	_, isStopRequest := err.(shared.StopRequestError)
	if err != nil && !isStopRequest {
		Log.Error.Print("Websocket: ", err)
	}
}
예제 #5
0
func main() {
	wsConfig, _ := websocket.NewConfig("wss://www.example2.com/echo", "http://localhost/")
	wsConfig.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "www.example2.com",
	}

	ws, err := websocket.DialConfig(wsConfig)
	if err != nil {
		log.Fatal(err)
	}

	message := []byte("hello, world!")
	_, err = ws.Write(message)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Send: %s\n", message)

	var msg = make([]byte, len(message))
	_, err = ws.Read(msg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Receive: %s\n", msg)
}
예제 #6
0
파일: stream_test.go 프로젝트: ncdc/origin
func readWebSocket(r *Reader, t *testing.T, fn func(*websocket.Conn), protocols ...string) ([]byte, error) {
	errCh := make(chan error, 1)
	s, addr := newServer(func(ws *websocket.Conn) {
		cfg := ws.Config()
		cfg.Protocol = protocols
		go func() {
			err := <-r.err
			errCh <- err
		}()
		r.handle(ws)
	})
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	client, err := websocket.DialConfig(config)
	if err != nil {
		return nil, err
	}
	defer client.Close()

	if fn != nil {
		fn(client)
	}

	data, err := ioutil.ReadAll(client)
	if err != nil {
		return data, err
	}
	return data, <-errCh
}
예제 #7
0
func readWebSocket(r *Reader, t *testing.T, fn func(*websocket.Conn), protocols ...string) ([]byte, error) {
	errCh := make(chan error, 1)
	s, addr := newServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		errCh <- r.Copy(w, req)
	}))
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	config.Protocol = protocols
	client, err := websocket.DialConfig(config)
	if err != nil {
		return nil, err
	}
	defer client.Close()

	if fn != nil {
		fn(client)
	}

	data, err := ioutil.ReadAll(client)
	if err != nil {
		return data, err
	}
	return data, <-errCh
}
예제 #8
0
func expectWebSocketFrames(r *Reader, t *testing.T, fn func(*websocket.Conn), frames [][]byte, protocols ...string) error {
	errCh := make(chan error, 1)
	s, addr := newServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		errCh <- r.Copy(w, req)
	}))
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	config.Protocol = protocols
	ws, err := websocket.DialConfig(config)
	if err != nil {
		return err
	}
	defer ws.Close()

	if fn != nil {
		fn(ws)
	}

	for i := range frames {
		var data []byte
		if err := websocket.Message.Receive(ws, &data); err != nil {
			return err
		}
		if !reflect.DeepEqual(frames[i], data) {
			return fmt.Errorf("frame %d did not match expected: %v", data, err)
		}
	}
	var data []byte
	if err := websocket.Message.Receive(ws, &data); err != io.EOF {
		return fmt.Errorf("expected no more frames: %v (%v)", err, data)
	}
	return <-errCh
}
예제 #9
0
func (st *serverTester) websocket(rp requestParam) (*serverResponse, error) {
	urlstring := st.url + "/echo"

	config, err := websocket.NewConfig(urlstring, st.url)
	if err != nil {
		st.t.Fatalf("websocket.NewConfig(%q, %q) returned error: %v", urlstring, st.url, err)
	}

	config.Header.Add("Test-Case", rp.name)
	for _, h := range rp.header {
		config.Header.Add(h.Name, h.Value)
	}

	ws, err := websocket.NewClient(config, st.conn)
	if err != nil {
		st.t.Fatalf("Error creating websocket client: %v", err)
	}

	if _, err := ws.Write(rp.body); err != nil {
		st.t.Fatalf("ws.Write() returned error: %v", err)
	}

	msg := make([]byte, 1024)
	var n int
	if n, err = ws.Read(msg); err != nil {
		st.t.Fatalf("ws.Read() returned error: %v", err)
	}

	res := &serverResponse{
		body: msg[:n],
	}

	return res, nil
}
예제 #10
0
파일: shell_test.go 프로젝트: tsuru/tsuru
func (s *S) TestAppShellGenericError(c *check.C) {
	m := RunServer(true)
	server := httptest.NewServer(m)
	defer server.Close()
	testServerURL, err := url.Parse(server.URL)
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("ws://%s/apps/someapp/shell?width=140&height=38&term=xterm", testServerURL.Host)
	config, err := websocket.NewConfig(url, "ws://localhost/")
	c.Assert(err, check.IsNil)
	config.Header.Set("Authorization", "bearer "+s.token.GetValue())
	wsConn, err := websocket.DialConfig(config)
	c.Assert(err, check.IsNil)
	defer wsConn.Close()
	_, err = wsConn.Write([]byte("echo test"))
	c.Assert(err, check.IsNil)
	var result string
	err = tsurutest.WaitCondition(5*time.Second, func() bool {
		part, readErr := ioutil.ReadAll(wsConn)
		if readErr != nil {
			c.Log(readErr)
			return false
		}
		result += string(part)
		return result == "Error: App someapp not found.\n"
	})
	c.Assert(err, check.IsNil)
}
예제 #11
0
파일: main_test.go 프로젝트: uin57/frontd
func testWebSocketServer(hdrs map[string]string, expected string) {
	origin := "http://127.0.0.1/"
	url := "ws://" + string(_defaultFrontdAddr) + "/echo"
	cfg, err := websocket.NewConfig(url, origin)
	if err != nil {
		panic(err)
	}

	for k, v := range hdrs {
		cfg.Header.Set(k, v)
	}

	ws, err := websocket.DialConfig(cfg)
	if err != nil {
		panic(err)
	}
	if _, err := ws.Write([]byte(expected)); err != nil {
		panic(err)
	}
	var msg = make([]byte, len(expected))
	var n int
	if n, err = ws.Read(msg); err != nil {
		panic(err)
	}

	if expected != string(msg[:n]) {
		log.Println(string(msg[:n]))
		log.Println(expected)
		panic(fmt.Errorf("websocket reply not match: %s", string(msg[:n])))
	}

}
예제 #12
0
func cli(args CommandLineArguments, wg *sync.WaitGroup) {
	defer wg.Done()
	cfg, err := websocket.NewConfig(args.server, "wss://localhost")
	if err != nil {
		panic(err)
	}
	cert, err := tls.LoadX509KeyPair("server.pem", "server.key")
	if err != nil {
		panic(err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	config.InsecureSkipVerify = true
	cfg.TlsConfig = &config
	ws, err := websocket.DialConfig(cfg)
	if err != nil {
		panic(err)
	}
	if args.msg != "" {
		log.Println("Write data to websocket")
		_, err = ws.Write([]byte(args.msg))
		if err != nil {
			panic(err)
		}
	}
	if args.file != "" {
		go func() {
			f, err := os.Open(args.file)
			if err != nil {
				panic(err)
			}
			defer f.Close()
			s := bufio.NewScanner(f)
			for s.Scan() {
				time.Sleep(time.Duration(args.delay) * time.Second)
				_, err = ws.Write([]byte(s.Text()))
				if err != nil {
					panic(err)
				}
			}
		}()
	}
	ws.SetReadDeadline(time.Now().Add(time.Second * time.Duration(args.timeOut)))
	msgOut := make([]byte, 16384)
	for {
		n, err := ws.Read(msgOut)
		log.Println("Read bytes:", n)
		if err == io.EOF {
			log.Println("Reading finished")
			break
		}
		if err != nil {
			log.Println(err)
			break
		}
		log.Println(string(msgOut[:n]))
	}
	log.Println("Closing connection")
	ws.Close()
}
예제 #13
0
func (s *S) TestServeHTTPWebSocket(c *check.C) {
	var servers []*httptest.Server
	for i := 0; i < 2; i++ {
		msg := fmt.Sprintf("server-%d", i)
		srv := httptest.NewServer(websocket.Handler(func(conn *websocket.Conn) {
			conn.Write([]byte(msg + conn.Request().URL.Path))
			buf := make([]byte, 5)
			conn.Read(buf)
			conn.Write(buf)
		}))
		defer srv.Close()
		servers = append(servers, srv)
	}
	var err error
	_, err = s.redis.Do("RPUSH", "frontend:myfrontend.com", "myfrontend", servers[0].URL, servers[1].URL)
	c.Assert(err, check.IsNil)
	router := Router{}
	err = router.Init()
	c.Assert(err, check.IsNil)
	proxyServer := httptest.NewServer(&router)
	defer proxyServer.Close()
	dialWS := func() *websocket.Conn {
		config, err := websocket.NewConfig("ws://myfrontend.com", "ws://localhost/")
		c.Assert(err, check.IsNil)
		url, _ := url.Parse(proxyServer.URL)
		client, err := net.Dial("tcp", url.Host)
		c.Assert(err, check.IsNil)
		conn, err := websocket.NewClient(config, client)
		c.Assert(err, check.IsNil)
		return conn
	}
	msgBuf := make([]byte, 100)
	conn := dialWS()
	defer conn.Close()
	n, err := conn.Read(msgBuf)
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 9)
	c.Assert(string(msgBuf[:n]), check.Equals, "server-0/")
	n, err = conn.Write([]byte("12345"))
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 5)
	n, err = conn.Read(msgBuf)
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 5)
	c.Assert(string(msgBuf[:n]), check.Equals, "12345")
	conn = dialWS()
	defer conn.Close()
	n, err = conn.Read(msgBuf)
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 9)
	c.Assert(string(msgBuf[:n]), check.Equals, "server-1/")
	n, err = conn.Write([]byte("12345"))
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 5)
	n, err = conn.Read(msgBuf)
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 5)
	c.Assert(string(msgBuf[:n]), check.Equals, "12345")
}
예제 #14
0
func TestBase64Conn(t *testing.T) {
	conn := NewConn(NewDefaultChannelProtocols([]ChannelType{ReadWriteChannel, ReadWriteChannel}))
	s, addr := newServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		conn.Open(w, req)
	}))
	defer s.Close()

	config, err := websocket.NewConfig("ws://"+addr, "http://localhost/")
	if err != nil {
		t.Fatal(err)
	}
	config.Protocol = []string{"base64.channel.k8s.io"}
	client, err := websocket.DialConfig(config)
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	<-conn.ready
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		data, err := ioutil.ReadAll(conn.channels[0])
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(data, []byte("client")) {
			t.Errorf("unexpected server read: %s", string(data))
		}
	}()

	clientData := base64.StdEncoding.EncodeToString([]byte("client"))
	if n, err := client.Write(append([]byte{'0'}, clientData...)); err != nil || n != len(clientData)+1 {
		t.Fatalf("%d: %v", n, err)
	}

	wg.Add(1)
	go func() {
		defer wg.Done()
		if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 {
			t.Fatalf("%d: %v", n, err)
		}
	}()

	data := make([]byte, 1024)
	if n, err := io.ReadAtLeast(client, data, 9); n != 9 || err != nil {
		t.Fatalf("%d: %v", n, err)
	}
	expect := []byte(base64.StdEncoding.EncodeToString([]byte("server")))

	if !reflect.DeepEqual(data[:9], append([]byte{'1'}, expect...)) {
		t.Errorf("unexpected client read: %v", data[:9])
	}

	client.Close()
	wg.Wait()
}
예제 #15
0
파일: conn_test.go 프로젝트: CNDonny/scope
func TestBase64Conn(t *testing.T) {
	conn := NewConn(ReadWriteChannel, ReadWriteChannel)
	// TODO: Uncomment next two lines and remove third line when fix #19254
	// s, addr := newServer(conn.handle)
	// defer s.Close()
	_, addr := newServer(conn.handle)

	config, err := websocket.NewConfig("ws://"+addr, "http://localhost/")
	if err != nil {
		t.Fatal(err)
	}
	config.Protocol = []string{"base64.channel.k8s.io"}
	client, err := websocket.DialConfig(config)
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	<-conn.ready
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		data, err := ioutil.ReadAll(conn.channels[0])
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(data, []byte("client")) {
			t.Errorf("unexpected server read: %s", string(data))
		}
	}()

	clientData := base64.StdEncoding.EncodeToString([]byte("client"))
	if n, err := client.Write(append([]byte{'0'}, clientData...)); err != nil || n != len(clientData)+1 {
		t.Fatalf("%d: %v", n, err)
	}

	wg.Add(1)
	go func() {
		defer wg.Done()
		if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 {
			t.Fatalf("%d: %v", n, err)
		}
	}()

	data := make([]byte, 1024)
	if n, err := io.ReadAtLeast(client, data, 9); n != 9 || err != nil {
		t.Fatalf("%d: %v", n, err)
	}
	expect := []byte(base64.StdEncoding.EncodeToString([]byte("server")))

	if !reflect.DeepEqual(data[:9], append([]byte{'1'}, expect...)) {
		t.Errorf("unexpected client read: %v", data[:9])
	}

	client.Close()
	wg.Wait()
}
예제 #16
0
func (s *authHttpSuite) makeWebsocketConfigFromURL(c *gc.C, server string, header http.Header) *websocket.Config {
	config, err := websocket.NewConfig(server, "http://localhost/")
	c.Assert(err, jc.ErrorIsNil)
	config.Header = header
	caCerts := x509.NewCertPool()
	c.Assert(caCerts.AppendCertsFromPEM([]byte(testing.CACert)), jc.IsTrue)
	config.TlsConfig = &tls.Config{RootCAs: caCerts, ServerName: "anything"}
	return config
}
예제 #17
0
func newConfig(t *testing.T, path string) *websocket.Config {
	wsaddr := fmt.Sprintf("ws://%s%s", serverAddr, path)
	lh := "http://localhost"
	c, err := websocket.NewConfig(wsaddr, lh)
	if err != nil {
		t.Fatalf("NewConfig(%q, %q) got error: %s, want nil", wsaddr, lh, err.Error())
	}
	return c
}
예제 #18
0
// Register target type on vmt server and start to listen for server message
func (wsc *WebSocketCommunicator) RegisterAndListen(registrationMessage *MediationClientMessage) {
	// vmtServerUrl := "ws://10.10.173.154:8080/vmturbo/remoteMediation"
	vmtServerUrl := "ws://" + wsc.VmtServerAddress + "/vmturbo/remoteMediation"
	localAddr := wsc.LocalAddress

	glog.V(3).Infof("Dial Server: %s", vmtServerUrl)

	config, err := websocket.NewConfig(vmtServerUrl, localAddr)
	if err != nil {
		glog.Fatal(err)
	}
	usrpasswd := []byte(wsc.ServerUsername + ":" + wsc.ServerPassword)

	config.Header = http.Header{
		"Authorization": {"Basic " + base64.StdEncoding.EncodeToString(usrpasswd)},
	}
	webs, err := websocket.DialConfig(config)

	// webs, err := websocket.Dial(vmtServerUrl, "", localAddr)
	if err != nil {
		glog.Error(err)
		if webs == nil {
			glog.Error("The websocket is null, reset")
		}
		wsc.CloseAndRegisterAgain(registrationMessage)
	}
	wsc.ws = webs

	glog.V(3).Infof("Send registration info")
	wsc.SendClientMessage(registrationMessage)

	var msg = make([]byte, 1024)
	var n int

	// main loop for listening server message.
	for {
		if n, err = wsc.ws.Read(msg); err != nil {
			glog.Error(err)
			//glog.Fatal(err.Error())
			//re-establish connection when error
			glog.V(3).Infof("Error happened, re-establish websocket connection")
			break
		}
		serverMsg := &MediationServerMessage{}
		err = proto.Unmarshal(msg[:n], serverMsg)
		if err != nil {
			glog.Error("Received unmarshalable error, please make sure you are running the latest VMT server")
			glog.Fatal("unmarshaling error: ", err)
		}
		//Spawn a separate go routine to handle the server message
		go wsc.handleServerMessage(serverMsg, registrationMessage)
		glog.V(3).Infof("Continue listen from server...")
	}
	wsc.CloseAndRegisterAgain(registrationMessage)
}
예제 #19
0
func makeWebsocketConfigFromURL(c *gc.C, server string, header http.Header) *websocket.Config {
	config, err := websocket.NewConfig(server, "http://localhost/")
	c.Assert(err, jc.ErrorIsNil)
	config.Header = header
	caCerts := x509.NewCertPool()
	c.Assert(caCerts.AppendCertsFromPEM([]byte(testing.CACert)), jc.IsTrue)
	config.TlsConfig = utils.SecureTLSConfig()
	config.TlsConfig.RootCAs = caCerts
	config.TlsConfig.ServerName = "anything"
	return config
}
예제 #20
0
파일: server_test.go 프로젝트: imoapps/juju
func dialWebsocket(c *gc.C, addr, path string) (*websocket.Conn, error) {
	origin := "http://localhost/"
	url := fmt.Sprintf("wss://%s%s", addr, path)
	config, err := websocket.NewConfig(url, origin)
	c.Assert(err, jc.ErrorIsNil)
	pool := x509.NewCertPool()
	xcert, err := cert.ParseCert(coretesting.CACert)
	c.Assert(err, jc.ErrorIsNil)
	pool.AddCert(xcert)
	config.TlsConfig = &tls.Config{RootCAs: pool}
	return websocket.DialConfig(config)
}
예제 #21
0
파일: apiclient.go 프로젝트: bac/juju
// startDialWebsocket starts websocket connection to a single address
// on the given try instance.
func startDialWebsocket(try *parallel.Try, addr, path string, opts DialOpts, tlsConfig *tls.Config) error {
	// origin is required by the WebSocket API, used for "origin policy"
	// in websockets. We pass localhost to satisfy the API; it is
	// inconsequential to us.
	const origin = "http://localhost/"
	cfg, err := websocket.NewConfig("wss://"+addr+path, origin)
	if err != nil {
		return errors.Trace(err)
	}
	cfg.TlsConfig = tlsConfig
	return try.Start(newWebsocketDialer(cfg, opts))
}
예제 #22
0
파일: console.go 프로젝트: jkoelndorfer/cli
// Console opens a secure console to a code or database service. For code
// services, a command is required. This command is executed as root in the
// context of the application root directory. For database services, no command
// is needed - instead, the appropriate command for the database type is run.
// For example, for a postgres database, psql is run.
func Console(serviceLabel string, command string, settings *models.Settings) {
	helpers.SignIn(settings)
	service := helpers.RetrieveServiceByLabel(serviceLabel, settings)
	if service == nil {
		fmt.Printf("Could not find a service with the label \"%s\"\n", serviceLabel)
		os.Exit(1)
	}
	fmt.Printf("Opening console to %s (%s)\n", serviceLabel, service.ID)
	task := helpers.RequestConsole(command, service.ID, settings)
	fmt.Print("Waiting for the console to be ready. This might take a minute.")

	ch := make(chan string, 1)
	go helpers.PollConsoleJob(task.ID, service.ID, ch, settings)
	jobID := <-ch
	defer helpers.DestroyConsole(jobID, service.ID, settings)
	creds := helpers.RetrieveConsoleTokens(jobID, service.ID, settings)

	creds.URL = strings.Replace(creds.URL, "http", "ws", 1)
	fmt.Println("Connecting...")

	// BEGIN websocket impl
	config, _ := websocket.NewConfig(creds.URL, "ws://localhost:9443/")
	config.TlsConfig = &tls.Config{
		MinVersion: tls.VersionTLS12,
	}
	config.Header["X-Console-Token"] = []string{creds.Token}
	ws, err := websocket.DialConfig(config)
	if err != nil {
		panic(err)
	}
	defer ws.Close()
	fmt.Println("Connection opened")

	stdin, stdout, _ := term.StdStreams()
	fdIn, isTermIn := term.GetFdInfo(stdin)
	if !isTermIn {
		panic(errors.New("StdIn is not a terminal"))
	}
	oldState, err := term.SetRawTerminal(fdIn)
	if err != nil {
		panic(err)
	}

	done := make(chan bool)
	msgCh := make(chan []byte, 2)
	go webSocketDaemon(ws, &stdout, done, msgCh)

	signal.Notify(make(chan os.Signal, 1), os.Interrupt)

	defer term.RestoreTerminal(fdIn, oldState)
	go termDaemon(&stdin, ws)
	<-done
}
예제 #23
0
파일: baseBot.go 프로젝트: voldyman/baseBot
func irccConfig(sessionKey string) (config *websocket.Config, err error) {
	config, err = websocket.NewConfig("wss://api.irccloud.com/",
		"https://www.irccloud.com")
	if err != nil {
		return
	}

	config.Header.Add("Origin", "https://api.irccloud.com")
	config.Header.Add("Cookie", "session="+sessionKey)
	config.Header.Add("User-Agent", "ninja")
	return
}
예제 #24
0
파일: client.go 프로젝트: jbuck/rack
func (c *Client) Stream(path string, headers map[string]string, in io.Reader, out io.Writer) error {
	origin := fmt.Sprintf("https://%s", c.Host)
	url := fmt.Sprintf("wss://%s%s", c.Host, path)

	config, err := websocket.NewConfig(url, origin)

	if err != nil {
		return err
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	config.Header.Set("Version", c.Version)

	userpass := fmt.Sprintf("convox:%s", c.Password)
	userpass_encoded := base64.StdEncoding.EncodeToString([]byte(userpass))

	config.Header.Add("Authorization", fmt.Sprintf("Basic %s", userpass_encoded))

	for k, v := range headers {
		config.Header.Add(k, v)
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	ws, err := websocket.DialConfig(config)

	if err != nil {
		return err
	}

	defer ws.Close()

	var wg sync.WaitGroup

	if in != nil {
		go copyAsync(ws, in, nil)
	}

	if out != nil {
		wg.Add(1)
		go copyAsync(out, ws, &wg)
	}

	wg.Wait()

	return nil
}
예제 #25
0
파일: ws.go 프로젝트: Gaboose/manet-echo
func (w WS) Select(netcon net.Conn, url string) (*websocket.Conn, error) {
	conf, err := websocket.NewConfig(url, url)
	if err != nil {
		return nil, err
	}

	wcon, err := websocket.NewClient(conf, netcon)
	if err != nil {
		return nil, err
	}

	return wcon, nil
}
예제 #26
0
파일: main.go 프로젝트: pennello/go_gochat
func serveWebsocket() {
	serverUrl := getUrl("ws", websocketPort)
	originUrl := getUrl("http", httpPort)
	conf, err := websocket.NewConfig(serverUrl, originUrl)
	if err != nil {
		log.Fatal(err)
	}
	server := websocket.Server{
		Config:  *conf,
		Handler: websocketHandler,
	}
	serve(server, websocketPort)
}
예제 #27
0
파일: main.go 프로젝트: alexanderGugel/wsd
func dial(url, protocol, origin string) (ws *websocket.Conn, err error) {
	config, err := websocket.NewConfig(url, origin)
	if err != nil {
		return nil, err
	}
	if protocol != "" {
		config.Protocol = []string{protocol}
	}
	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: insecureSkipVerify,
	}
	return websocket.DialConfig(config)
}
예제 #28
0
func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat")

	rwc, err := sockConn(time.Duration(10*time.Second), "")
	c.Assert(err, checker.IsNil)

	cleanedContainerID := strings.TrimSpace(out)
	config, err := websocket.NewConfig(
		"/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1",
		"http://localhost",
	)
	c.Assert(err, checker.IsNil)

	ws, err := websocket.NewClient(config, rwc)
	c.Assert(err, checker.IsNil)
	defer ws.Close()

	expected := []byte("hello")
	actual := make([]byte, len(expected))

	outChan := make(chan error)
	go func() {
		_, err := io.ReadFull(ws, actual)
		outChan <- err
		close(outChan)
	}()

	inChan := make(chan error)
	go func() {
		_, err := ws.Write(expected)
		inChan <- err
		close(inChan)
	}()

	select {
	case err := <-inChan:
		c.Assert(err, checker.IsNil)
	case <-time.After(5 * time.Second):
		c.Fatal("Timeout writing to ws")
	}

	select {
	case err := <-outChan:
		c.Assert(err, checker.IsNil)
	case <-time.After(5 * time.Second):
		c.Fatal("Timeout reading from ws")
	}

	c.Assert(actual, checker.DeepEquals, expected, check.Commentf("Websocket didn't return the expected data"))
}
예제 #29
0
func (s *S) TestAppShellSpecifyUnit(c *check.C) {
	a := app.App{
		Name:     "someapp",
		Platform: "zend",
		Teams:    []string{s.team.Name},
	}
	err := s.conn.Apps().Insert(a)
	c.Assert(err, check.IsNil)
	defer s.conn.Apps().Remove(bson.M{"name": a.Name})
	defer s.logConn.Logs(a.Name).DropCollection()
	err = s.provisioner.Provision(&a)
	c.Assert(err, check.IsNil)
	defer s.provisioner.Destroy(&a)
	s.provisioner.AddUnits(&a, 5, "web", nil)
	units, err := s.provisioner.Units(&a)
	c.Assert(err, check.IsNil)
	unit := units[3]
	m := RunServer(true)
	server := httptest.NewServer(m)
	defer server.Close()
	testServerURL, err := url.Parse(server.URL)
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("ws://%s/apps/%s/shell?width=140&height=38&term=xterm&unit=%s", testServerURL.Host, a.Name, unit.ID)
	config, err := websocket.NewConfig(url, "ws://localhost/")
	c.Assert(err, check.IsNil)
	config.Header.Set("Authorization", "bearer "+s.token.GetValue())
	wsConn, err := websocket.DialConfig(config)
	c.Assert(err, check.IsNil)
	defer wsConn.Close()
	_, err = wsConn.Write([]byte("echo test"))
	c.Assert(err, check.IsNil)
	var shells []provision.ShellOptions
	err = tsurutest.WaitCondition(5*time.Second, func() bool {
		shells = s.provisioner.Shells(unit.ID)
		return len(shells) == 1
	})
	c.Assert(err, check.IsNil)
	c.Assert(shells, check.HasLen, 1)
	c.Assert(shells[0].App.GetName(), check.Equals, a.Name)
	c.Assert(shells[0].Width, check.Equals, 140)
	c.Assert(shells[0].Height, check.Equals, 38)
	c.Assert(shells[0].Term, check.Equals, "xterm")
	c.Assert(shells[0].Unit, check.Equals, unit.ID)
	units, err = s.provisioner.Units(&a)
	c.Assert(err, check.IsNil)
	for _, u := range units {
		if u.ID != unit.ID {
			c.Check(s.provisioner.Shells(u.ID), check.HasLen, 0)
		}
	}
}
예제 #30
0
파일: logstream_test.go 프로젝트: bac/juju
func newWebsocketServer(c *gc.C, h websocket.Handler) *websocket.Conn {
	cfg, err := websocket.NewConfig("ws://localhost:12345/", "http://localhost/")
	c.Assert(err, jc.ErrorIsNil)

	go func() {
		err = http.ListenAndServe(":12345", websocket.Server{
			Config:  *cfg,
			Handler: h,
		})
		c.Assert(err, jc.ErrorIsNil)
	}()

	return newWebsocketClient(c, cfg)
}