Esempio n. 1
2
// getASocket calls MakeApiRequest() to get a websocket for the slack RTM
// interface.
func (b *Broker) getASocket() (*websocket.Conn, *ApiResponse, error) {
	var req = ApiRequest{
		URL:    `https://slack.com/api/rtm.start`,
		Values: make(url.Values),
		Broker: b,
	}
	authResp, err := MakeAPIReq(req)
	if err != nil {
		return nil, nil, err
	}

	if authResp.URL == "" {
		return nil, nil, fmt.Errorf("Auth failure")
	}
	wsURL := strings.Split(authResp.URL, "/")
	wsURL[2] = wsURL[2] + ":443"
	authResp.URL = strings.Join(wsURL, "/")
	Logger.Debug(`Team Wesocket URL: `, authResp.URL)

	var Dialer websocket.Dialer
	header := make(http.Header)
	header.Add("Origin", "http://localhost/")

	ws, _, err := Dialer.Dial(authResp.URL, header)
	if err != nil {
		return nil, nil, fmt.Errorf("no dice dialing that websocket: %v", err)
	}

	//yay we're websocketing
	return ws, authResp, nil
}
Esempio n. 2
0
func (wp websocketProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	logger.Debug("Upgrading websocket connection.")
	oconn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		logger.Error(err)
		return
	}
	defer oconn.Close()

	r.URL.Host = config.Destination
	r.URL.Scheme = "ws"
	dialer := websocket.Dialer{
		HandshakeTimeout: time.Second,
		ReadBufferSize:   1024,
		WriteBufferSize:  1024,
		Subprotocols:     websocket.Subprotocols(r),
	}
	logger.Debug("Dialing", r.URL.String(), "...")
	iconn, _, err := dialer.Dial(r.URL.String(), nil)
	if err != nil {
		logger.Error(err)
		return
	}
	defer iconn.Close()
	logger.Debug("Connected!")

	go wp.Copy(oconn, iconn)
	wp.Copy(iconn, oconn)

}
Esempio n. 3
0
func (h *Hijacker) Hijack(handle string, spec atc.HijackProcessSpec, pio ProcessIO) (int, error) {
	url, header, err := h.hijackRequestParts(handle)
	if err != nil {
		return -1, err
	}

	dialer := websocket.Dialer{
		TLSClientConfig: h.tlsConfig,
		Proxy:           http.ProxyFromEnvironment,
	}
	conn, _, err := dialer.Dial(url, header)
	if err != nil {
		return -1, err
	}

	defer conn.Close()

	err = conn.WriteJSON(spec)
	if err != nil {
		return -1, err
	}

	inputs := make(chan atc.HijackInput, 1)
	finished := make(chan struct{}, 1)

	go h.monitorTTYSize(inputs, finished)
	go io.Copy(&stdinWriter{inputs}, pio.In)
	go h.handleInput(conn, inputs, finished)

	exitStatus := h.handleOutput(conn, pio)

	close(finished)

	return exitStatus, nil
}
Esempio n. 4
0
func dial() (*websocket.Conn, error) {
	LoadAuth()

	if os.Getenv("TUTUM_STREAM_HOST") != "" {
		u, _ := url.Parse(os.Getenv("TUTUM_STREAM_HOST"))
		_, port, _ := net.SplitHostPort(u.Host)
		if port == "" {
			u.Host = u.Host + ":443"
		}
		StreamUrl = u.Scheme + "://" + u.Host + "/v1/"
	} else if os.Getenv("TUTUM_STREAM_URL") != "" {
		u, _ := url.Parse(os.Getenv("TUTUM_STREAM_URL"))
		_, port, _ := net.SplitHostPort(u.Host)
		if port == "" {
			u.Host = u.Host + ":443"
		}
		StreamUrl = u.Scheme + "://" + u.Host + "/v1/"
	}

	Url := StreamUrl + "events/"

	header := http.Header{}
	header.Add("Authorization", AuthHeader)
	header.Add("User-Agent", customUserAgent)

	var Dialer websocket.Dialer
	ws, _, err := Dialer.Dial(Url, header)
	if err != nil {
		return nil, err
	}

	return ws, nil
}
Esempio n. 5
0
func (self *Service) Logs(c chan Logs) {

	endpoint := ""
	if Namespace != "" {
		endpoint = "api/app/" + appSubsystemVersion + "/" + Namespace + "/service/" + self.Uuid + "/logs/"
	} else {
		endpoint = "api/app/" + appSubsystemVersion + "/service/" + self.Uuid + "/logs/"
	}

	url := StreamUrl + endpoint

	header := http.Header{}
	header.Add("Authorization", AuthHeader)
	header.Add("User-Agent", customUserAgent)

	var Dialer websocket.Dialer
	ws, _, err := Dialer.Dial(url, header)
	if err != nil {
		log.Println(err)
	}

	var msg Logs
	for {
		if err = ws.ReadJSON(&msg); err != nil {
			log.Println(err)
			break
		}
		c <- msg
	}
}
Esempio n. 6
0
func wsDial(src v2net.Address, dest v2net.Destination) (*wsconn, error) {
	commonDial := func(network, addr string) (net.Conn, error) {
		return internet.DialToDest(src, dest)
	}

	tlsconf := &tls.Config{ServerName: dest.Address().Domain(), InsecureSkipVerify: effectiveConfig.DeveloperInsecureSkipVerify}

	dialer := websocket.Dialer{NetDial: commonDial, ReadBufferSize: 65536, WriteBufferSize: 65536, TLSClientConfig: tlsconf}

	effpto := calcPto(dest)

	uri := func(dst v2net.Destination, pto string, path string) string {
		return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
	}(dest, effpto, effectiveConfig.Path)

	conn, resp, err := dialer.Dial(uri, nil)
	if err != nil {
		if resp != nil {
			reason, reasonerr := ioutil.ReadAll(resp.Body)
			log.Info(string(reason), reasonerr)
		}
		return nil, err
	}
	return func() internet.Connection {
		connv2ray := &wsconn{wsc: conn, connClosing: false}
		connv2ray.setup()
		return connv2ray
	}().(*wsconn), nil
}
Esempio n. 7
0
func ConnectToHead(url string, secret string) {
	var cstDialer = websocket.Dialer{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	conn, _, err := cstDialer.Dial(url, nil)
	if err != nil {
		fmt.Printf("Dial: %v", err)
	}

	log.Printf("ok")

	// Send a welcome packet for auth
	conn.WriteJSON(&common.Packet{
		Cmd:     "auth",
		Context: secret,
	})

	for {
		var p common.Packet

		if err := conn.ReadJSON(&p); err != nil {
			log.Println("Error reading head's json: ", err)
			return
		}

		response := HandlePacket(p)

		if response != nil {
			conn.WriteJSON(response)
		}
	}
}
Esempio n. 8
0
func startClient(url *url.URL, wg *sync.WaitGroup, chRequests chan stats.MessageRequest,
	chResponse chan *Response, id int) {

	dialer := websocket.Dialer{}

	conn, _, err := dialer.Dial(url.String(), nil)
	if err != nil {
		log.Fatal("Failed to establish connection with server: ", err)
	}

	defer conn.Close()
	start := time.Now()
	connected := true
	var clientWg sync.WaitGroup

	go func() {
		for connected {
			var mresp stats.MessageResponse

			if err := conn.ReadJSON(&mresp); err != nil {
				if connected {
					log.Error("Error reading json response: ", err)
					chResponse <- &Response{
						Success: false,
					}
					clientWg.Done()
					wg.Done()
				}
			} else {
				log.Debug("Received response Host:", mresp.Host)

				duration := time.Since(start)
				chResponse <- &Response{
					Success:  true,
					Duration: duration,
					Valid:    validateNodes(&mresp),
				}

				clientWg.Done()
				wg.Done()
			}
		}

	}()

	for mreq := range chRequests {
		clientWg.Add(1)

		if err := conn.WriteJSON(&mreq); err != nil {
			log.Error("Failed to send req: ", err)
			clientWg.Done()
		} else {
			start = time.Now()
			log.Debug("Sent req: ", mreq)
		}
	}

	clientWg.Wait()
	connected = false
}
Esempio n. 9
0
func (self *Container) Run(command string, c chan Exec) {

	endpoint := "container/" + self.Uuid + "/exec/?user="******"&token=" + ApiKey + "&command=" + url.QueryEscape(command)
	url := StreamUrl + endpoint

	header := http.Header{}
	header.Add("User-Agent", customUserAgent)

	var Dialer websocket.Dialer
	ws, _, err := Dialer.Dial(url, header)
	if err != nil {
		log.Println(err)
	}

	var msg Exec
	for {
		if err = ws.ReadJSON(&msg); err != nil {
			if err != nil && err.Error() != "EOF" {
				log.Println(err)
			} else {
				break
			}
		}
		c <- msg
	}
}
Esempio n. 10
0
func main() {
	//    logger.SetConsole(true)
	//    logger.SetRollingDaily(".", "test.log")
	//    logger.SetLevel(logger.ALL)

	flag.Parse()
	var addr = flag.String("addr", "localhost:8080", "http service address")
	var dialer = websocket.Dialer{}

	u := url.URL{Scheme: "ws", Host: *addr, Path: "/gows"}

	for {
		errCh := make(chan error)
		ws, _, err := dialer.Dial(u.String(), nil)
		defer ws.Close()
		if err == nil {
			fmt.Println("runing")
			go readMessages(ws, errCh)
			go writeMessages(ws)
			fmt.Println(<-errCh)
			close(errCh)
		}
		if ws != nil {
			ws.Close()
		}
		fmt.Println("reconning....")
		time.Sleep(5 * time.Second)
	}
}
Esempio n. 11
0
func newWebsocketPeer(url, protocol, origin string, serializer Serializer, payloadType int) (Peer, error) {
	dialer := websocket.Dialer{
		Subprotocols: []string{protocol},
	}
	conn, _, err := dialer.Dial(url, nil)
	if err != nil {
		return nil, err
	}
	ep := &websocketPeer{
		conn:        conn,
		messages:    make(chan Message, 10),
		serializer:  serializer,
		payloadType: payloadType,
	}
	go func() {
		for {
			// TODO: use conn.NextMessage() and stream
			// TODO: do something different based on binary/text frames
			if _, b, err := conn.ReadMessage(); err != nil {
				conn.Close()
				break
			} else {
				msg, err := serializer.Deserialize(b)
				if err != nil {
					// TODO: handle error
				} else {
					ep.messages <- msg
				}
			}
		}
	}()
	return ep, nil
}
Esempio n. 12
0
func (self *Container) Logs(c chan Logs) {

	endpoint := "container/" + self.Uuid + "/logs/?user="******"&token=" + ApiKey
	url := StreamUrl + endpoint

	header := http.Header{}
	header.Add("User-Agent", customUserAgent)

	var Dialer websocket.Dialer
	ws, _, err := Dialer.Dial(url, header)
	if err != nil {
		log.Println(err)
	}

	var msg Logs
	for {
		if err = ws.ReadJSON(&msg); err != nil {
			if err != nil && err.Error() != "EOF" {
				log.Println(err)
			} else {
				break
			}
		}
		c <- msg
	}
}
Esempio n. 13
0
func TestMainCLI(t *testing.T) {
	Convey("when I run the app", t, func() {
		port := 9003

		ctx, cancelFunc := context.WithCancel(context.Background())

		app := MakeCliApp(ctx)
		go app.Run([]string{"<executable path>", "--port", strconv.Itoa(port)})
		time.Sleep(time.Millisecond)

		url := fmt.Sprintf("ws://localhost:%v/", port)
		d := websocket.Dialer{}
		Convey("and connect", func() {
			conn, _, err := d.Dial(url, http.Header{})
			So(err, ShouldBeNil)
			conn.Close()
		})

		Reset(func() {
			cancelFunc()
			time.Sleep(5 * time.Millisecond)
			So("subicul", testutils.ShouldNotBeRunningGoroutines)
		})

	})

}
Esempio n. 14
0
// ConnectWebsocketSession dials the remote specified in the opts and
// creates new websocket session.
func ConnectWebsocketSession(opts *DialOptions) (*WebsocketSession, error) {
	dialURL, err := url.Parse(opts.BaseURL)
	if err != nil {
		return nil, err
	}

	// will be used to set the origin header
	originalScheme := dialURL.Scheme

	if err := replaceSchemeWithWS(dialURL); err != nil {
		return nil, err
	}

	if err := addMissingPortAndSlash(dialURL); err != nil {
		return nil, err
	}

	serverID := threeDigits()
	sessionID := utils.RandomString(20)

	// Add server_id and session_id to the path.
	dialURL.Path += serverID + "/" + sessionID + "/websocket"

	requestHeader := http.Header{}
	requestHeader.Add("Origin", originalScheme+"://"+dialURL.Host)

	ws := websocket.Dialer{
		ReadBufferSize:  opts.ReadBufferSize,
		WriteBufferSize: opts.WriteBufferSize,
	}

	// if the user passed a custom HTTP client and its transport
	// is of *http.Transport type - we're using its Dial field
	// for connecting to remote host
	if t, ok := opts.Client().Transport.(*http.Transport); ok {
		ws.NetDial = t.Dial
	}

	// if the user passed a timeout, use a dial with a timeout
	if opts.Timeout != 0 && ws.NetDial == nil {
		// If ws.NetDial is non-nil then gorilla does not
		// use ws.HandshakeTimeout for the deadlines.
		//
		// Instead we're going to set it ourselves.
		ws.NetDial = (&net.Dialer{
			Timeout:  opts.Timeout,
			Deadline: time.Now().Add(opts.Timeout),
		}).Dial
	}

	conn, _, err := ws.Dial(dialURL.String(), requestHeader)
	if err != nil {
		return nil, err
	}

	session := NewWebsocketSession(conn)
	session.id = sessionID
	return session, nil
}
Esempio n. 15
0
File: kdb.go Progetto: algos/kdb
func Connect(address, user, pass string) (*websocket.Conn, *http.Response, error) {
	authkey := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
	hdr := make(http.Header)
	hdr.Add("Authorization", "Basic "+authkey)
	var dialer websocket.Dialer
	conn, resp, err := dialer.Dial("ws://"+address, hdr)
	return conn, resp, err
}
Esempio n. 16
0
File: bot.go Progetto: ajm188/slack
func (bot *Bot) connect(websocketURL string) (bool, error) {
	dialer := websocket.Dialer{}
	conn, _, err := dialer.Dial(websocketURL, http.Header{})
	if err != nil {
		return false, err
	}
	return bot.loop(conn), nil
}
func (a *Alphapoint) WebsocketClient() {
	for a.ExchangeEnanbled && a.WebsocketEnabled {
		var Dialer websocket.Dialer
		var err error
		a.WebsocketConn, _, err = Dialer.Dial(a.WebsocketURL, http.Header{})

		if err != nil {
			log.Printf("%s Unable to connect to Websocket. Error: %s\n", a.ExchangeName, err)
			continue
		}

		if a.Verbose {
			log.Printf("%s Connected to Websocket.\n", a.ExchangeName)
		}

		err = a.WebsocketConn.WriteMessage(websocket.TextMessage, []byte(`{"messageType": "logon"}`))

		if err != nil {
			log.Println(err)
			return
		}

		for a.ExchangeEnanbled && a.WebsocketEnabled {
			msgType, resp, err := a.WebsocketConn.ReadMessage()
			if err != nil {
				log.Println(err)
				break
			}

			switch msgType {
			case websocket.TextMessage:
				type MsgType struct {
					MessageType string `json:"messageType"`
				}

				msgType := MsgType{}
				err := JSONDecode(resp, &msgType)
				if err != nil {
					log.Println(err)
					continue
				}

				switch msgType.MessageType {
				case "Ticker":
					ticker := AlphapointWebsocketTicker{}
					err = JSONDecode(resp, &ticker)
					if err != nil {
						log.Println(err)
						continue
					}
				}
			}
		}
		a.WebsocketConn.Close()
		log.Printf("%s Websocket client disconnected.", a.ExchangeName)
	}
}
Esempio n. 18
0
func wsDial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (*wsconn, error) {
	networkSettings, err := options.Stream.GetEffectiveNetworkSettings()
	if err != nil {
		return nil, err
	}
	wsSettings := networkSettings.(*Config)

	commonDial := func(network, addr string) (net.Conn, error) {
		return internet.DialToDest(src, dest)
	}

	dialer := websocket.Dialer{
		NetDial:         commonDial,
		ReadBufferSize:  65536,
		WriteBufferSize: 65536,
	}

	protocol := "ws"

	if options.Stream != nil && options.Stream.HasSecuritySettings() {
		protocol = "wss"
		securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
		if err != nil {
			log.Error("WebSocket: Failed to create security settings: ", err)
			return nil, err
		}
		tlsConfig, ok := securitySettings.(*v2tls.Config)
		if ok {
			dialer.TLSClientConfig = tlsConfig.GetTLSConfig()
			if dest.Address.Family().IsDomain() {
				dialer.TLSClientConfig.ServerName = dest.Address.Domain()
			}
		}
	}

	uri := func(dst v2net.Destination, pto string, path string) string {
		return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
	}(dest, protocol, wsSettings.Path)

	conn, resp, err := dialer.Dial(uri, nil)
	if err != nil {
		if resp != nil {
			reason, reasonerr := ioutil.ReadAll(resp.Body)
			log.Info(string(reason), reasonerr)
		}
		return nil, err
	}
	return func() internet.Connection {
		connv2ray := &wsconn{
			wsc:         conn,
			connClosing: false,
			config:      wsSettings,
		}
		connv2ray.setup()
		return connv2ray
	}().(*wsconn), nil
}
Esempio n. 19
0
func (start slackStart) openWebSocket() *websocket.Conn {
	var emptyHeader http.Header
	var defaultDialer *websocket.Dialer
	conn, _, err := defaultDialer.Dial(start.URL, emptyHeader)
	if err != nil {
		panic(err)
	}

	return conn
}
Esempio n. 20
0
func (b *Bitfinex) WebsocketClient() {
	msgCounter := 0
	for b.Enabled && b.Websocket {
		var Dialer websocket.Dialer
		var err error
		b.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{})

		if err != nil {
			log.Printf("%s Unable to connect to Websocket. Error: %s\n", b.GetName(), err)
			continue
		}

		if b.Verbose {
			log.Printf("%s Connected to Websocket.\n", b.GetName())
		}

		err = b.Subscribe(&msgCounter, BITFINEX_WEBSOCKET_ORDERBOOK, map[string]interface{}{"ExchangeID": "0", "ProductPairID": "1", "Depth": 25, "RoundToDecimals": 2})
		if err != nil {
			log.Println(err)
			continue
		}

		err = b.Subscribe(&msgCounter, BTIFINEX_WEBSOCKET_TRADES, map[string]interface{}{"ExchangeID": "0", "ProductPairID": "1", "IncludeLastCount": "100"})
		if err != nil {
			log.Println(err)
			continue
		}

		if b.Verbose {
			log.Printf("%s Subscribed to channels.\n", b.GetName())
		}

		for b.Enabled && b.Websocket {
			msgType, resp, err := b.WebsocketConn.ReadMessage()
			if err != nil {
				log.Println(err)
				break
			}

			switch msgType {
			case websocket.TextMessage:
				msg := BitfinexWebsocketResponse{}
				err := JSONDecode(resp, &msg)
				if err != nil {
					log.Println(err)
					continue
				}
				log.Println(string(resp))
				log.Println(msg)
			}
		}
		b.WebsocketConn.Close()
		log.Printf("%s Websocket client disconnected.\n", b.GetName())
	}
}
Esempio n. 21
0
/* The client dials a connection to wsUri. The client starts a reader, a writer, and a standardInput reader.
 * Standard in is sent to the writer that will send it on the connection. The readerResult is printed to standard out.
 */
func client(wsUri string) {

	tlsConfig := tls.Config{}
	tlsConfig.InsecureSkipVerify = true
	dialer := websocket.Dialer{TLSClientConfig: &tlsConfig}
	requestHeader := http.Header{}
	requestHeader.Set("origin", "http://localhost/")
	conn, _, err := dialer.Dial(wsUri, requestHeader)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("The gowebsock client is connected to %s\n", wsUri)

	readerResultChan := make(chan readerResult)
	go reader(conn, readerResultChan)

	writerCommandChan := make(chan writerCommand)
	go writer(conn, writerCommandChan)

	stdinReaderChan := make(chan string)
	go stdinReader(stdinReaderChan)

	for {
		select {
		case stdinMessage := <-stdinReaderChan:
			var messageType int
			data := ""
			switch stdinMessage {
			case "close":
				messageType = 8
			case "ping":
				messageType = 9
			case "pong":
				messageType = 10
			default:
				messageType = 1
				data = stdinMessage
			}
			writerCommandChan <- writerCommand{false, messageType, []byte(data)}
		case readerResult := <-readerResultChan:
			if readerResult.err == nil {
				output := "Server: type = " + messageTypeString(readerResult.messageType) + ", data = " + string(readerResult.data) + "\n"
				fmt.Printf(output)
			} else {
				fmt.Printf("%s\n", readerResult.err)
				os.Exit(0)
			}
		}
	}
}
Esempio n. 22
0
func wsDial(ctx context.Context, dest v2net.Destination) (*wsconn, error) {
	src := internet.DialerSourceFromContext(ctx)
	wsSettings := internet.TransportSettingsFromContext(ctx).(*Config)

	commonDial := func(network, addr string) (net.Conn, error) {
		return internet.DialSystem(src, dest)
	}

	dialer := websocket.Dialer{
		NetDial:         commonDial,
		ReadBufferSize:  32 * 1024,
		WriteBufferSize: 32 * 1024,
	}

	protocol := "ws"

	if securitySettings := internet.SecuritySettingsFromContext(ctx); securitySettings != nil {
		tlsConfig, ok := securitySettings.(*v2tls.Config)
		if ok {
			protocol = "wss"
			dialer.TLSClientConfig = tlsConfig.GetTLSConfig()
			if dest.Address.Family().IsDomain() {
				dialer.TLSClientConfig.ServerName = dest.Address.Domain()
			}
		}
	}

	host := dest.NetAddr()
	if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
		host = dest.Address.String()
	}
	uri := protocol + "://" + host + "/" + wsSettings.Path

	conn, resp, err := dialer.Dial(uri, nil)
	if err != nil {
		if resp != nil {
			reason, reasonerr := ioutil.ReadAll(resp.Body)
			log.Info(string(reason), reasonerr)
		}
		return nil, err
	}
	return func() internet.Connection {
		connv2ray := &wsconn{
			wsc:         conn,
			connClosing: false,
			config:      wsSettings,
		}
		connv2ray.setup()
		return connv2ray
	}().(*wsconn), nil
}
Esempio n. 23
0
File: client.go Progetto: djibi2/lxd
// WebsocketDial attempts to dial a websocket to a LXD instance, parsing
// LXD-style errors and returning them as go errors.
func WebsocketDial(dialer websocket.Dialer, url string) (*websocket.Conn, error) {
	conn, raw, err := dialer.Dial(url, http.Header{})
	if err != nil {
		_, err2 := HoistResponse(raw, Error)
		if err2 != nil {
			/* The response isn't one we understand, so return
			 * whatever the original error was. */
			return nil, err
		}

		return nil, err
	}
	return conn, err
}
Esempio n. 24
0
func main() {
	flag.Parse()

	log.SetLevel(log.InfoLevel)

	u := url.URL{Scheme: "ws", Host: *flAddress, Path: "/"}

	dialer := websocket.Dialer{}

	conn, _, err := dialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("Failed to establish connection with server: ", err)
	}

	defer conn.Close()

	now := time.Now()

	go func() {
		defer conn.Close()
		for {
			var mresp stats.MessageResponse

			if err := conn.ReadJSON(&mresp); err != nil {
				log.Error("Error reading json response: ", err)
				break
			} else {
				log.Info("Received response from node: ", mresp.Host)
				log.Info("Duration:", time.Since(now))
				PrintStats(&mresp)
			}
		}

	}()

	for {
		var mreq stats.MessageRequest
		mreq.StatType = stats.ALL
		mreq.Type = stats.STATALL

		if err := conn.WriteJSON(&mreq); err != nil {
			log.Error("Failed to send req: ", err)
		} else {
			now = time.Now()
			log.Debug("Sent req: ", mreq)
		}

		time.Sleep(time.Duration(*flDuration) * time.Second)
	}
}
Esempio n. 25
0
func ConnectWebsocketSession(opts *DialOptions) (*WebsocketSession, error) {
	dialURL, err := url.Parse(opts.BaseURL)
	if err != nil {
		return nil, err
	}

	// will be used to set the origin header
	originalScheme := dialURL.Scheme

	if err := replaceSchemeWithWS(dialURL); err != nil {
		return nil, err
	}

	if err := addMissingPortAndSlash(dialURL); err != nil {
		return nil, err
	}

	serverID := threeDigits()
	sessionID := randomStringLength(20)

	// Add server_id and session_id to the path.
	dialURL.Path += serverID + "/" + sessionID + "/websocket"

	requestHeader := http.Header{}
	requestHeader.Add("Origin", originalScheme+"://"+dialURL.Host)

	ws := websocket.Dialer{
		ReadBufferSize:  opts.ReadBufferSize,
		WriteBufferSize: opts.WriteBufferSize,
	}

	// if the user passed a timeout, us a dial with a timeout
	if opts.Timeout != 0 {
		ws.NetDial = func(network, addr string) (net.Conn, error) {
			return net.DialTimeout(network, addr, opts.Timeout)
		}
		// this is used as Deadline inside gorillas dialer method
		ws.HandshakeTimeout = opts.Timeout
	}

	conn, _, err := ws.Dial(dialURL.String(), requestHeader)
	if err != nil {
		return nil, err
	}

	session := NewWebsocketSession(conn)
	session.id = sessionID
	return session, nil
}
Esempio n. 26
0
func dial(url string) (*socketClient, *processor) {
	log.Printf("Dialing: %s", url)
	d := websocket.Dialer{}
	ws, _, err := d.Dial(url, nil)
	if err != nil {
		log.Panicf("An error occured while dialing: %s", err)
	}

	client := newClient(ws)
	processor := newProcessor(client)

	go processor.resultsTo(client)
	go client.read(processor)
	go client.write()
	return client, processor
}
Esempio n. 27
0
func (cnsmr *consumer) establishWebsocketConnection(path string, authToken string) (*websocket.Conn, error) {
	header := http.Header{"Origin": []string{"http://localhost"}, "Authorization": []string{authToken}}
	dialer := websocket.Dialer{NetDial: cnsmr.proxyDial, TLSClientConfig: cnsmr.tlsConfig}

	ws, resp, err := dialer.Dial(cnsmr.endpoint+path, header)

	if err == nil && cnsmr.callback != nil {
		cnsmr.callback()
	}
	if resp != nil && resp.StatusCode == http.StatusUnauthorized {
		bodyData, _ := ioutil.ReadAll(resp.Body)
		err = NewUnauthorizedError(string(bodyData))
	}

	return ws, err
}
Esempio n. 28
0
func (c *Client) Connect(i int, cb func(gogadgets.Message)) error {
	c.disconnect = make(chan bool)
	c.connectedTo = i
	g := c.Nodes[i]

	a := fmt.Sprintf(c.addr, fmt.Sprintf("gadgets/%s/websocket", g.Id))
	u, err := url.Parse(a)
	if err != nil {
		return err
	}

	if u.Scheme == "https" {
		a = strings.Replace(a, "https", "wss", -1)
	} else {
		a = strings.Replace(a, "http", "ws", -1)
	}

	h := http.Header{"Origin": {a}, "Authorization": {c.token}}
	dialer := websocket.Dialer{
		Subprotocols:    []string{"p1", "p2"},
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	c.ws, _, err = dialer.Dial(a, h)
	if err != nil {
		return err
	}
	c.Out = make(chan gogadgets.Message)
	ws := make(chan gogadgets.Message)
	go c.listen(ws)
	go func() {
		for {
			select {
			case msg := <-c.Out:
				d, _ := json.Marshal(msg)
				c.ws.WriteMessage(websocket.TextMessage, d)
			case msg := <-ws:
				cb(msg)
			case <-c.disconnect:
				c.ws.Close()
				return
			}
		}
	}()
	return nil
}
Esempio n. 29
0
func (self *jsonTestRunnerStruct) makeSureTheresAConnection() {
	if self.currentConnection == nil {
		log.Println("Connecting to server...")
		dialer := websocket.Dialer{
			HandshakeTimeout: 10 * time.Second,
		}
		header := make(http.Header)
		var err error
		self.currentConnection, _, err =
			dialer.Dial(fmt.Sprintf("%v%v", self.addr,
				self.url), header)
		log.Println("Connected to server.")
		if err != nil {
			panic(fmt.Sprintf("Error creating a connection: %v", err))
		}
	}
}
Esempio n. 30
0
func ProducerSetupFuction(producer *producers.GenericProducer, config map[string]interface{}) {

	dialer := websocket.Dialer{}

	wsConnection, _, err := dialer.Dial(wsURI+config["PushbulletApiToken"].(string), nil)
	if err != nil {
		log.Fatal("PushbulletProducer: Error opening websocket connection:" + err.Error())
	}

	producer.RuntimeObjects["PushbulletApiToken"] = config["PushbulletApiToken"].(string)
	producer.RuntimeObjects["connection"] = wsConnection
	producer.RuntimeObjects["wsMessageChannel"] = make(chan wsMessage)
	producer.RuntimeObjects["lastcheckTimestamp"] = float64(time.Now().Unix())

	go wsMessagePump(producer)

}