Пример #1
0
func (c *WebsocketClient) ConnectOnce() error {
	c.logger.Debug("ConnectOnce:call")
	defer c.logger.Debug("ConnectOnce:return")

	// Make websocket connection.  If this fails, either API is down or the ws
	// address is wrong.
	link := c.api.AgentLink(c.link)
	c.logger.Debug("ConnectOnce:link:" + link)
	config, err := websocket.NewConfig(link, c.api.Origin())
	if err != nil {
		return err
	}
	config.Header.Add("X-Percona-API-Key", c.api.ApiKey())

	c.logger.Debug("ConnectOnce:websocket.DialConfig")
	c.status.Update(c.name, "Connecting "+link)
	conn, err := websocket.DialConfig(config)
	if err != nil {
		return err
	}

	c.mux.Lock()
	defer c.mux.Unlock()
	c.connected = true
	c.conn = conn
	c.status.Update(c.name, "Connected "+link)

	return nil
}
Пример #2
0
// newWebsocketDialer returns a function that
// can be passed to utils/parallel.Try.Start.
func newWebsocketDialer(cfg *websocket.Config, opts DialOpts) func(<-chan struct{}) (io.Closer, error) {
	openAttempt := utils.AttemptStrategy{
		Total: opts.Timeout,
		Delay: opts.RetryDelay,
	}
	return func(stop <-chan struct{}) (io.Closer, error) {
		for a := openAttempt.Start(); a.Next(); {
			select {
			case <-stop:
				return nil, parallel.ErrStopped
			default:
			}
			logger.Infof("dialing %q", cfg.Location)
			conn, err := websocket.DialConfig(cfg)
			if err == nil {
				return conn, nil
			}
			if a.HasNext() {
				logger.Debugf("error dialing %q, will retry: %v", cfg.Location, err)
			} else {
				logger.Infof("error dialing %q: %v", cfg.Location, err)
				return nil, fmt.Errorf("unable to connect to %q", cfg.Location)
			}
		}
		panic("unreachable")
	}
}
Пример #3
0
func (proxy *Proxy) HandleWebSocket(clientWS *websocket.Conn) {
	req := clientWS.Request()
	req.ParseForm()
	req.Form.Get("app")
	clientAddress := clientWS.RemoteAddr()

	appId := req.Form.Get("app")

	extractAuthTokenFromUrl := func(u *url.URL) string {
		authorization := ""
		queryValues := u.Query()
		if len(queryValues["authorization"]) == 1 {
			authorization = queryValues["authorization"][0]
		}
		return authorization
	}

	authToken := clientWS.Request().Header.Get("Authorization")
	if authToken == "" {
		authToken = extractAuthTokenFromUrl(req.URL)
	}

	if authorized, errorMessage := proxy.isAuthorized(appId, authToken, clientAddress); !authorized {
		data, err := proto.Marshal(errorMessage)
		if err != nil {
			proxy.logger.Errorf("Error marshalling log message: %s", err)
		}
		websocket.Message.Send(clientWS, data)
		clientWS.Close()
		return
	}

	defer clientWS.Close()

	proxy.logger.Debugf("Output Proxy: Request for app: %v", req.Form.Get("app"))
	serverWSs := make([]*websocket.Conn, len(proxy.hashers))
	for index, hasher := range proxy.hashers {
		proxy.logger.Debugf("Output Proxy: Servers in group [%v]: %v", index, hasher.LoggregatorServers())

		server := hasher.GetLoggregatorServerForAppId(appId)
		proxy.logger.Debugf("Output Proxy: AppId is %v. Using server: %v", appId, server)

		config, err := websocket.NewConfig("ws://"+server+req.URL.RequestURI(), "http://localhost")

		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error creating config for websocket - %v", err)
		}

		serverWS, err := websocket.DialConfig(config)
		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error connecting to loggregator server - %v", err)
		}

		if serverWS != nil {
			serverWSs[index] = serverWS
		}
	}
	proxy.forwardIO(serverWSs, clientWS)

}
Пример #4
0
func (repo LoggregatorLogsRepository) connectToWebsocket(location string, app cf.Application, onConnect func(), outputChan chan *logmessage.Message, stopLoggingChan chan bool, printTimeBuffer time.Duration) (err error) {

	trace.Logger.Printf("\n%s %s\n", terminal.HeaderColor("CONNECTING TO WEBSOCKET:"), location)

	config, err := websocket.NewConfig(location, "http://localhost")
	if err != nil {
		return
	}

	config.Header.Add("Authorization", repo.config.AccessToken)
	config.TlsConfig = &tls.Config{InsecureSkipVerify: true}

	ws, err := websocket.DialConfig(config)
	if err != nil {
		return
	}

	onConnect()

	inputChan := make(chan *logmessage.Message, 1000)

	go repo.sendKeepAlive(ws)
	go repo.listenForMessages(ws, inputChan, stopLoggingChan)
	go makeAndStartMessageSorter(inputChan, outputChan, stopLoggingChan, printTimeBuffer)

	return
}
Пример #5
0
func (repo LoggregatorLogsRepository) connectToWebsocket(location string, onConnect func(), outputChan chan *logmessage.Message, stopLoggingChan chan bool, printTimeBuffer time.Duration) (err error) {
	trace.Logger.Printf("\n%s %s\n", terminal.HeaderColor("CONNECTING TO WEBSOCKET:"), location)

	config, err := websocket.NewConfig(location, "http://localhost")
	if err != nil {
		return
	}

	config.Header.Add("Authorization", repo.config.AccessToken)
	config.TlsConfig = &tls.Config{InsecureSkipVerify: true}

	ws, err := websocket.DialConfig(config)
	if err != nil {
		return
	}
	defer ws.Close()

	onConnect()

	go repo.sendKeepAlive(ws)

	inputChan := make(chan *logmessage.Message, LogBufferSize)
	stopInputChan := make(chan bool, 1)
	go func() {
		defer close(stopInputChan)
		defer close(inputChan)
		repo.listenForMessages(ws, inputChan, stopInputChan)
	}()

	messageQueue := &SortedMessageQueue{printTimeBuffer: printTimeBuffer}

	repo.processMessages(messageQueue, inputChan, outputChan, stopLoggingChan, stopInputChan)

	return
}
Пример #6
0
func New(key, secret string, currencies ...string) (*StreamingApi, error) {
	url := fmt.Sprintf("%s%s?Currency=%s", api_host, api_path, strings.Join(currencies, ","))
	config, _ := websocket.NewConfig(url, origin_url)
	ws, err := websocket.DialConfig(config)

	if err != nil {
		return nil, err
	}

	api := &StreamingApi{
		ws:     ws,
		Ticker: make(chan Ticker),
		Info:   make(chan Info),
		Depth:  make(chan Depth),
		Trade:  make(chan Trade),
		Orders: make(chan []Order),
	}

	api.key, err = hex.DecodeString(strings.Replace(key, "-", "", -1))
	if err != nil {
		return nil, err
	}

	api.secret, err = base64.StdEncoding.DecodeString(secret)
	if err != nil {
		return nil, err
	}

	return api, err
}
Пример #7
0
func New(cfg *websocket.Config) (*JsonWebsocket, error) {
	ws, err := websocket.DialConfig(cfg)
	if err != nil {
		return nil, err
	}

	return &JsonWebsocket{ws: ws}, nil
}
Пример #8
0
func KeepAliveClient(t *testing.T, port string, path string) {
	config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
	config.Header.Add("Authorization", testhelpers.VALID_AUTHENTICATION_TOKEN)
	assert.NoError(t, err)
	ws, err := websocket.DialConfig(config)
	assert.NoError(t, err)

	websocket.Message.Send(ws, []byte("keep alive"))
}
Пример #9
0
func (s *debugLogSuite) dialWebsocketFromURL(c *gc.C, server string, header http.Header) (*websocket.Conn, error) {
	c.Logf("dialing %v", server)
	config, err := websocket.NewConfig(server, "http://localhost/")
	c.Assert(err, gc.IsNil)
	config.Header = header
	caCerts := x509.NewCertPool()
	c.Assert(caCerts.AppendCertsFromPEM([]byte(testing.CACert)), jc.IsTrue)
	config.TlsConfig = &tls.Config{RootCAs: caCerts, ServerName: "anything"}
	return websocket.DialConfig(config)
}
Пример #10
0
// Create a New SocketCluster Client
func NewClient(auth AuthDetails, dbpath string) (*Client, error) {
	Info = log.New(os.Stdout, "SOCKETCLUSTER: ", log.Ltime|log.Lshortfile)

	origin := "http://localhost"
	prefix := "ws"
	if auth.SecureWS {
		prefix = "wss"
	}

	url := fmt.Sprintf("%s://%s/socketcluster/", prefix, auth.Host)

	config, _ := websocket.NewConfig(url, origin)
	config.Header.Add("User-Agent", auth.UserAgent)

	Info.Println("Connecting: " + url)
	ws, err := websocket.DialConfig(config)
	if err != nil {
		Info.Println(err)
		return nil, err
	}

	c := &Client{
		ws:       ws,
		id:       0,
		mutex:    &sync.Mutex{},
		quitChan: make(chan int),
	}

	c.setupDB(dbpath)

	// Connection succeded. Send a handshake event.
	c.emit(c.NewEvent("#handshake", makeHandshakeData()))

	rEvent, err := c.recieve()

	if err != nil {
		Info.Println(err)
		return nil, errors.New("#handshake recieve error")
	}

	// Start listening to events
	go c.listen()

	if rEvent.Rid == 1 {
		if !isAuthenticated(rEvent) {
			c.emit(c.NewEvent("clearoldsessions", makeClearOldSessionsData(auth)))

			c.loginEvent = c.NewEvent("login", makeLoginData(auth))
			c.emit(c.loginEvent)
		}
	}

	return c, nil
}
Пример #11
0
func RunClient(url string, id string, userKey string) {
	rootPath, _ = filepath.Abs(rootPath)
	ListenForSignals()
	socketUrl := fmt.Sprintf("%s/clientsocket", url)
	var ws *websocket.Conn
	var timeout time.Duration = 1e8
	config, err := websocket.NewConfig(socketUrl, socketUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	config.TlsConfig = new(tls.Config)
	// Disable this when getting a proper certificate
	config.TlsConfig.InsecureSkipVerify = true
	for {
		time.Sleep(timeout)
		var err error
		ws, err = websocket.DialConfig(config)
		timeout *= 2
		if err != nil {
			fmt.Println("Could not yet connect:", err.Error(), ", trying again in", timeout)
		} else {
			break
		}
	}

	buffer, _ := json.Marshal(HelloMessage{"0.1", id, userKey})

	if _, err := ws.Write(buffer); err != nil {
		log.Fatal(err)
		return
	}
	connectUrl := strings.Replace(url, "ws://", "http://", 1)
	connectUrl = strings.Replace(connectUrl, "wss://", "https://", 1)
	multiplexer := NewRPCMultiplexer(ws, handleRequest)

	if userKey == "" {
		fmt.Print("In the Zed application copy and paste following URL to edit:\n\n")
		fmt.Printf("  %s/fs/%s\n\n", connectUrl, id)
	} else {
		fmt.Println("A Zed window should now open. If not, make sure Zed is running and configured with the correct userKey.")
	}
	fmt.Println("Press Ctrl-c to quit.")
	err = multiplexer.Multiplex()
	if err != nil {
		// TODO do this in a cleaner way (reconnect, that is)
		if err.Error() == "no-client" {
			fmt.Printf("ERROR: Your Zed editor is not currently connected to zedrem server %s.\nBe sure Zed is running and the project picker is open.\n", url)
		} else {
			RunClient(url, id, userKey)
		}
	}
}
Пример #12
0
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, gc.IsNil)
	pool := x509.NewCertPool()
	xcert, err := cert.ParseCert(coretesting.CACert)
	c.Assert(err, gc.IsNil)
	pool.AddCert(xcert)
	config.TlsConfig = &tls.Config{RootCAs: pool}
	return websocket.DialConfig(config)
}
Пример #13
0
func AssertConnectionFails(t *testing.T, port string, path string, expectedErrorCode uint16) {
	config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
	assert.NoError(t, err)

	ws, err := websocket.DialConfig(config)
	assert.NoError(t, err)
	data := make([]byte, 2)
	_, err = ws.Read(data)
	errorCode := binary.BigEndian.Uint16(data)
	assert.Equal(t, expectedErrorCode, errorCode)
	assert.Equal(t, "EOF", err.Error())
}
Пример #14
0
func Open(info *Info, opts DialOpts) (*State, error) {
	// TODO Select a random address from info.Addrs
	// and only fail when we've tried all the addresses.
	// TODO what does "origin" really mean, and is localhost always ok?
	cfg, err := websocket.NewConfig("wss://"+info.Addrs[0]+"/", "http://localhost/")
	if err != nil {
		return nil, err
	}
	pool := x509.NewCertPool()
	xcert, err := cert.ParseCert(info.CACert)
	if err != nil {
		return nil, err
	}
	pool.AddCert(xcert)
	cfg.TlsConfig = &tls.Config{
		RootCAs:    pool,
		ServerName: "anything",
	}
	var conn *websocket.Conn
	openAttempt := utils.AttemptStrategy{
		Total: opts.Timeout,
		Delay: opts.RetryDelay,
	}
	for a := openAttempt.Start(); a.Next(); {
		log.Infof("state/api: dialing %q", cfg.Location)
		conn, err = websocket.DialConfig(cfg)
		if err == nil {
			break
		}
		log.Errorf("state/api: %v", err)
	}
	if err != nil {
		return nil, err
	}
	log.Infof("state/api: connection established")

	client := rpc.NewConn(jsoncodec.NewWebsocket(conn))
	client.Start()
	st := &State{
		client: client,
		conn:   conn,
	}
	if info.Tag != "" || info.Password != "" {
		if err := st.Login(info.Tag, info.Password, info.Nonce); err != nil {
			conn.Close()
			return nil, err
		}
	}
	st.broken = make(chan struct{})
	go st.heartbeatMonitor()
	return st, nil
}
Пример #15
0
func WaitForServerStart(port string, path string) {
	serverStarted := func() bool {
		config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
		_, err = websocket.DialConfig(config)
		if err != nil {
			return false
		}
		return true
	}
	for !serverStarted() {
		time.Sleep(1 * time.Microsecond)
	}
}
Пример #16
0
func (c *Conn) connect() error {
	connectionString := c.creds.addrString + authutil.SignRequest("/eventhub", c.creds.apiKey, c.creds.secret)
	config, err := websocket.NewConfig(connectionString, "http://localhost")
	if err != nil {
		return err
	}
	// Ignore certs for now
	config.TlsConfig = &tls.Config{InsecureSkipVerify: true}
	ws, err := websocket.DialConfig(config)
	if err != nil {
		return err
	}
	c.ws = ws
	return nil
}
Пример #17
0
func main() {

	var server string

	var (
		ctx    context.Context
		cancel context.CancelFunc
	)

	ctx, cancel = context.WithCancel(context.Background())

	runtime.GOMAXPROCS(1)

	server = os.Args[1]
	id := os.Args[2]

	LogConditional(printLog, fmt.Printf, "Client Id %s\n", id)
	//fmt.Printf("Client Id %s\n", id)

	var headers http.Header = make(http.Header)
	headers.Add("X-Client-ID", id)

	var srvurl = "ws://173.39.210.210:8080/echo/"

	origin = fmt.Sprintf("http://%s/", server)
	srvurl = fmt.Sprintf("ws://%s:8080/echo/?id=%s", server, id)

	u, err := url.Parse(srvurl)
	o, err := url.Parse(origin)
	ws, err := websocket.DialConfig(&websocket.Config{Location: u, Header: headers, Origin: o, Version: 13})

	if err != nil {
		log.Fatal(err)
	}

	c := make(chan []byte)

	go collectdTcp(cancel, c)
	go collectSyslog(c)
	go writer(ws, id, c)
	//go reader(ws, id)

	select {
	case <-ctx.Done():
	}

}
Пример #18
0
func main() {

	var server string

	runtime.GOMAXPROCS(1)
	R = *new(responses)
	R.waiting = make(map[int64]response)
	rand.Seed(time.Now().UnixNano())
	var (
		ctx context.Context
	)

	ctx, _ = context.WithCancel(context.Background())

	server = os.Args[1]
	id := os.Args[2]
	printLog = (os.Args[3] == "1")
	fmt.Sscanf(os.Args[4], "%d", &loopCount)

	LogConditional(printLog, fmt.Printf, "Client Id %s\n", id)
	//fmt.Printf("Client Id %s\n", id)

	var headers http.Header = make(http.Header)
	headers.Add("X-Client-ID", id)

	var srvurl = "ws://173.39.210.210:8080/echo/"

	origin = fmt.Sprintf("http://%s/", server)
	srvurl = fmt.Sprintf("ws://%s:8080/echo/?id=%s", server, id)

	u, err := url.Parse(srvurl)
	o, err := url.Parse(origin)
	ws, err := websocket.DialConfig(&websocket.Config{Location: u, Header: headers, Origin: o, Version: 13})

	if err != nil {
		log.Fatal(err)
	}

	go writer(ws, id)
	go reader(ws, id)

	select {
	case <-ctx.Done():
	}

}
Пример #19
0
func RunClient(url string, id string) {
	rootPath, _ = filepath.Abs(rootPath)

	socketUrl := fmt.Sprintf("%s/clientsocket", url)
	var ws *websocket.Conn
	var timeout time.Duration = 1e8
	config, err := websocket.NewConfig(socketUrl, socketUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	config.TlsConfig = new(tls.Config)
	// Disable this when getting a proper certificate
	config.TlsConfig.InsecureSkipVerify = true
	for {
		time.Sleep(timeout)
		var err error
		ws, err = websocket.DialConfig(config)
		timeout *= 2
		if err != nil {
			fmt.Println("Could not yet connect:", err.Error(), ", trying again in", timeout)
		} else {
			break
		}
	}

	buffer, _ := json.Marshal(HelloMessage{"0.1", id})

	if _, err := ws.Write(buffer); err != nil {
		log.Fatal(err)
		return
	}
	connectUrl := strings.Replace(url, "ws://", "http://", 1)
	connectUrl = strings.Replace(connectUrl, "wss://", "https://", 1)
	multiplexer := NewRPCMultiplexer(ws, handleRequest)

	fmt.Print("In the Zed Chrome application copy and paste following URL to edit:\n\n")
	fmt.Printf("  %s/fs/%s\n\n", connectUrl, id)
	fmt.Println("Press Ctrl-c to quit.")
	err = multiplexer.Multiplex()
	if err != nil {
		// TODO do this in a cleaner way (reconnect, that is)
		RunClient(url, id)
	}
}
Пример #20
0
// BtcdWS opens a websocket connection to a btcd instance.
func BtcdWS(certificates []byte) (*websocket.Conn, error) {
	url := fmt.Sprintf("wss://%s/ws", cfg.RPCConnect)
	config, err := websocket.NewConfig(url, "https://localhost/")
	if err != nil {
		return nil, err
	}

	// btcd uses a self-signed TLS certifiate which is used as the CA.
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(certificates)
	config.TlsConfig = &tls.Config{
		RootCAs:    pool,
		MinVersion: tls.VersionTLS12,
	}

	// btcd requires basic authorization, so set the Authorization header.
	login := cfg.Username + ":" + cfg.Password
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
	config.Header.Add("Authorization", auth)

	// Dial connection.
	var ws *websocket.Conn
	var cerr error
	if cfg.Proxy != "" {
		proxy := &socks.Proxy{
			Addr:     cfg.Proxy,
			Username: cfg.ProxyUser,
			Password: cfg.ProxyPass,
		}
		conn, err := proxy.Dial("tcp", cfg.RPCConnect)
		if err != nil {
			return nil, err
		}

		tlsConn := tls.Client(conn, config.TlsConfig)
		ws, cerr = websocket.NewClient(config, tlsConn)
	} else {
		ws, cerr = websocket.DialConfig(config)
	}
	if cerr != nil {
		return nil, cerr
	}
	return ws, nil
}
Пример #21
0
func ClientWithAuth(t *testing.T, port string, path string, config *websocket.Config) chan []byte {
	receivedChan := make(chan []byte)
	ws, err := websocket.DialConfig(config)
	assert.NoError(t, err)

	go func() {
		for {
			var data []byte
			err := websocket.Message.Receive(ws, &data)
			if err != nil {
				close(receivedChan)
				ws.Close()
				return
			}
			receivedChan <- data
		}

	}()
	return receivedChan
}
Пример #22
0
func openConnection(uri *url.URL, tlsc *tls.Config) (net.Conn, error) {
	switch uri.Scheme {
	case "ws":
		conn, err := websocket.Dial(uri.String(), "mqtt", "ws://localhost")
		if err != nil {
			return nil, err
		}
		conn.PayloadType = websocket.BinaryFrame
		return conn, err
	case "wss":
		config, _ := websocket.NewConfig(uri.String(), "ws://localhost")
		config.Protocol = []string{"mqtt"}
		config.TlsConfig = tlsc
		conn, err := websocket.DialConfig(config)
		if err != nil {
			return nil, err
		}
		conn.PayloadType = websocket.BinaryFrame
		return conn, err
	case "tcp":
		conn, err := net.Dial("tcp", uri.Host)
		if err != nil {
			return nil, err
		}
		return conn, nil
	case "ssl":
		fallthrough
	case "tls":
		fallthrough
	case "tcps":
		conn, err := tls.Dial("tcp", uri.Host, tlsc)
		if err != nil {
			return nil, err
		}
		return conn, nil
	}
	return nil, errors.New("Unknown protocol")
}
Пример #23
0
func AddWSSink(t *testing.T, receivedChan chan []byte, port string, path string, authToken string) (*websocket.Conn, chan bool, <-chan bool) {
	dontKeepAliveChan := make(chan bool)
	connectionDroppedChannel := make(chan bool)

	config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
	assert.NoError(t, err)
	config.Header.Add("Authorization", authToken)
	ws, err := websocket.DialConfig(config)
	assert.NoError(t, err)

	go func() {
		for {
			var data []byte
			err := websocket.Message.Receive(ws, &data)
			if err != nil {
				connectionDroppedChannel <- true
				return
			}
			receivedChan <- data
		}

	}()
	go func() {
		for {
			err := websocket.Message.Send(ws, []byte{42})
			if err != nil {
				break
			}
			select {
			case <-dontKeepAliveChan:
				return
			case <-time.After(44 * time.Millisecond):
				// keep-alive
			}
		}
	}()
	return ws, dontKeepAliveChan, connectionDroppedChannel
}
Пример #24
0
func (repo LoggregatorLogsRepository) connectToWebsocket(location string, onConnect func(), outputChan chan *logmessage.Message, stopLoggingChan chan bool, printTimeBuffer time.Duration) (err error) {
	trace.Logger.Printf("\n%s %s\n", terminal.HeaderColor("CONNECTING TO WEBSOCKET:"), location)

	inputChan := make(chan *logmessage.Message, LogBufferSize)
	messageQueue := NewSortedMessageQueue(printTimeBuffer, time.Now)

	wsConfig, err := websocket.NewConfig(location, "http://localhost")
	if err != nil {
		return
	}

	wsConfig.Header.Add("Authorization", repo.config.AccessToken())
	wsConfig.TlsConfig = net.NewTLSConfig(repo.TrustedCerts, repo.config.IsSSLDisabled())

	ws, err := websocket.DialConfig(wsConfig)
	if err != nil {
		err = net.WrapSSLErrors(location, err)
		return
	}

	defer func() {
		ws.Close()
		repo.drainRemainingMessages(messageQueue, inputChan, outputChan)
	}()

	onConnect()

	go repo.sendKeepAlive(ws)

	go func() {
		defer close(inputChan)
		repo.listenForMessages(ws, inputChan)
	}()

	repo.processMessages(messageQueue, inputChan, outputChan, stopLoggingChan)

	return
}
Пример #25
0
func ClientWithAuth(t *testing.T, port string, path string, authToken string) chan []byte {
	receivedChan := make(chan []byte)
	config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
	config.Header.Add("Authorization", authToken)
	assert.NoError(t, err)
	ws, err := websocket.DialConfig(config)
	assert.NoError(t, err)

	go func() {
		for {
			var data []byte
			err := websocket.Message.Receive(ws, &data)
			if err != nil {
				close(receivedChan)
				ws.Close()
				return
			}
			receivedChan <- data
		}

	}()
	return receivedChan
}
Пример #26
0
func Open(info *Info) (*State, error) {
	// TODO what does "origin" really mean, and is localhost always ok?
	cfg, err := websocket.NewConfig("wss://"+info.Addr+"/", "http://localhost/")
	if err != nil {
		return nil, err
	}
	pool := x509.NewCertPool()
	xcert, err := cert.ParseCert(info.CACert)
	if err != nil {
		return nil, err
	}
	pool.AddCert(xcert)
	cfg.TlsConfig = &tls.Config{
		RootCAs:    pool,
		ServerName: "anything",
	}
	conn, err := websocket.DialConfig(cfg)
	if err != nil {
		return nil, err
	}
	return &State{
		conn: conn,
	}, nil
}
Пример #27
0
// ListenAndUpdate opens a websocket connection to a btcwallet
// instance and initiates requests to fill the GUI with relevant
// information.
func ListenAndUpdate(certificates []byte, c chan error) {
	// Start each updater func in a goroutine.  Use a sync.Once to
	// ensure there are no duplicate updater functions running.
	updateOnce.Do(func() {
		for _, f := range updateFuncs {
			go f()
		}
	})

	// Connect to websocket.
	url := fmt.Sprintf("wss://%s/frontend", cfg.Connect)
	config, err := websocket.NewConfig(url, "https://localhost/")
	if err != nil {
		log.Printf("[ERR] cannot create websocket config: %v", err)
		c <- ErrConnectionRefused
		return
	}

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(certificates)
	config.TlsConfig = &tls.Config{
		RootCAs:    pool,
		MinVersion: tls.VersionTLS12,
	}

	// btcwallet requires basic authorization, so we use a custom config
	// with the Authorization header set.
	login := cfg.Username + ":" + cfg.Password
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
	config.Header.Add("Authorization", auth)

	// Attempt to connect to running btcwallet instance. Bail if it fails.
	var ws *websocket.Conn
	var cerr error
	if cfg.Proxy != "" {
		proxy := &socks.Proxy{
			Addr:     cfg.Proxy,
			Username: cfg.ProxyUser,
			Password: cfg.ProxyPass,
		}
		conn, err := proxy.Dial("tcp", cfg.Connect)
		if err != nil {
			log.Printf("Error connecting to proxy: %v", err)
			c <- ErrConnectionRefused
			return
		}

		tlsConn := tls.Client(conn, config.TlsConfig)
		ws, cerr = websocket.NewClient(config, tlsConn)
	} else {
		ws, cerr = websocket.DialConfig(config)
	}
	if cerr != nil {
		log.Printf("[ERR] Cannot create websocket client: %v", cerr)
		c <- ErrConnectionRefused
		return
	}
	c <- nil

	// Buffered channel for replies and notifications from btcwallet.
	replies := make(chan []byte, 100)

	go func() {
		for {
			// Receive message from wallet
			var msg []byte
			err := websocket.Message.Receive(ws, &msg)
			if err != nil {
				close(replies)
				return
			}
			replies <- msg
		}
	}()

	for _, f := range walletReqFuncs {
		go f(ws)
	}

	for {
		select {
		case r, ok := <-replies:
			if !ok {
				// btcwallet connection lost.
				c <- ErrConnectionLost
				return
			}

			// Handle message here.
			go ProcessBtcwalletMessage(r)

		case <-triggers.newAddr:
			go cmdGetNewAddress(ws)

		case params := <-triggers.newWallet:
			go cmdCreateEncryptedWallet(ws, params)

		case <-triggers.lockWallet:
			go cmdWalletLock(ws)

		case params := <-triggers.unlockWallet:
			go cmdWalletPassphrase(ws, params)

		case pairs := <-triggers.sendTx:
			go cmdSendMany(ws, pairs)

		case fee := <-triggers.setTxFee:
			go cmdSetTxFee(ws, fee)
		}
	}
}
package sinkserver

import (
	"code.google.com/p/go.net/websocket"
	"encoding/binary"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("WebsocketServer", func() {
	assertConnectionFails := func(port string, path string, expectedErrorCode uint16) {
		config, err := websocket.NewConfig("ws://localhost:"+port+path, "http://localhost")
		Expect(err).ToNot(HaveOccurred())

		ws, err := websocket.DialConfig(config)
		Expect(err).ToNot(HaveOccurred())

		data := make([]byte, 2)
		_, err = ws.Read(data)
		errorCode := binary.BigEndian.Uint16(data)
		Expect(err).To(HaveOccurred())
		Expect(errorCode).To(Equal(expectedErrorCode))
		Expect(err.Error()).To(Equal("EOF"))
	}

	Describe("Start", func() {
		Context("given an unknown path", func() {
			It("returns an HTTP 400", func() {
				assertConnectionFails(SERVER_PORT, "/INVALID_PATH", 400)
			})
		})
Пример #29
0
Файл: logs.go Проект: jbayer/cli
func (repo LoggregatorLogsRepository) TailLogsFor(app cf.Application, onConnect func(), onMessage func(*logmessage.LogMessage)) (err error) {
	const REDIRECT_ERROR = "REDIRECTED"

	tlsConfig := &tls.Config{InsecureSkipVerify: true}

	tr := &http.Transport{TLSClientConfig: tlsConfig, Proxy: http.ProxyFromEnvironment}

	client := http.Client{
		Transport: tr,
		CheckRedirect: func(*http.Request, []*http.Request) error {
			return errors.New(REDIRECT_ERROR)
		},
	}

	host := repo.loggregatorHostResolver(repo.config.Target) + ":" + LOGGREGATOR_REDIRECTOR_PORT
	request, apiErr := repo.gateway.NewRequest("GET", fmt.Sprintf("%s/tail/?app=%s", host, app.Guid), repo.config.AccessToken, nil)
	if apiErr != nil {
		err = errors.New(apiErr.Error())
		return
	}

	resp, err := client.Do(request.Request)

	if err != nil && !strings.Contains(err.Error(), REDIRECT_ERROR) {
		return
	}

	location := resp.Header.Get("Location")
	config, err := websocket.NewConfig(location, "http://localhost")
	if err != nil {
		return
	}

	config.Header.Add("Authorization", repo.config.AccessToken)
	config.TlsConfig = tlsConfig

	ws, err := websocket.DialConfig(config)
	if err != nil {
		return
	}

	onConnect()
	go func() {
		for {
			websocket.Message.Send(ws, "I'm alive!")
			time.Sleep(25 * time.Second)
		}
	}()

	for {
		var data []byte
		err = websocket.Message.Receive(ws, &data)
		if err != nil {
			return
		}

		logMessage := new(logmessage.LogMessage)
		msgErr := proto.Unmarshal(data, logMessage)
		if msgErr != nil {
			continue
		}
		onMessage(logMessage)
	}

	return
}
Пример #30
0
	return result.Result, nil
}

// AgentVersion reports the version number of the api server.
func (c *Client) AgentVersion() (version.Number, error) {
	var result params.AgentVersionResult
	if err := c.facade.FacadeCall("AgentVersion", nil, &result); err != nil {
		return version.Number{}, err
	}
	return result.Version, nil
}

// websocketDialConfig is called instead of websocket.DialConfig so we can
// override it in tests.
var websocketDialConfig = func(config *websocket.Config) (io.ReadCloser, error) {
	return websocket.DialConfig(config)
}

// DebugLogParams holds parameters for WatchDebugLog that control the
// filtering of the log messages. If the structure is zero initialized, the
// entire log file is sent back starting from the end, and until the user
// closes the connection.
type DebugLogParams struct {
	// IncludeEntity lists entity tags to include in the response. Tags may
	// finish with a '*' to match a prefix e.g.: unit-mysql-*, machine-2. If
	// none are set, then all lines are considered included.
	IncludeEntity []string
	// IncludeModule lists logging modules to include in the response. If none
	// are set all modules are considered included.  If a module is specified,
	// all the submodules also match.
	IncludeModule []string