Esempio n. 1
1
func connectToAgent(timeout int, onReady func(*websocket.Conn)) (*websocket.Conn, error) {
	var ws *websocket.Conn
	var err error

	t := 0
	for {
		if t > timeout {
			return nil, errors.New("Connection to Agent : timeout reached")
		}

		ws, err = newClient()
		if err == nil {
			break
		}
		time.Sleep(1 * time.Second)
		t++
	}

	ready := false
	h := func(message string) error {
		err := ws.WriteControl(websocket.PongMessage, []byte(message), time.Now().Add(time.Second))
		if err != nil {
			return err
		}
		if !ready {
			ready = true
			onReady(ws)
		}
		return nil
	}
	ws.SetPingHandler(h)

	return ws, nil
}
Esempio n. 2
1
func (w *WebsocketController) listenForIncomingData(connection *websocket.Conn, client *WebsocketClient, disconnect chan bool) {
	for {
		mt, message, err := connection.ReadMessage()

		if mt == websocket.CloseMessage {
			disconnect <- true
		}
		if _, ok := err.(*websocket.CloseError); ok {
			disconnect <- true
		}

		if err != nil {
			w.logger.Println("warning: read message error:", err)
			continue
		}
		if mt != websocket.TextMessage && mt != websocket.CloseMessage {
			w.logger.Println("warning: recieved unsupported message: ", mt, message)
			continue
		}

		if mt == websocket.TextMessage {
			w.Received() <- ReceivedData{client, message}
		}
	}
}
Esempio n. 3
0
func streamStatus(sock *websocket.Conn) {
	installed := installedPacks()
	filteredInstalled := []shared.Pack{}
	available := availablePacks()

loopinstalled:
	for _, ip := range installed {
		for ai, ap := range available {
			if ip.Installing && ip.File == ap.File {
				available[ai].Installing = true
				continue loopinstalled
			}
		}
		filteredInstalled = append(filteredInstalled, ip)
	}

	info := StatusInfo{
		Packs: PackInfo{
			Installed: filteredInstalled,
			Available: available,
		},
		Version: global.buildVersion,
	}

	err := sock.WriteJSON(controlResponse{Typ: "StatusResponse", Data: info})
	if err != nil {
		log.Printf("Error while writing status info: %v\n", err)
		return
	}
}
Esempio n. 4
0
func (wss *WSTraffickers) SaveConnection(accessToken string, conn *websocket.Conn) (*WSTrafficker, error) {
	_, payloadJson, err := conn.ReadMessage()
	if err != nil {
		return nil, err
	}

	var payload map[string]interface{}

	err = json.Unmarshal(payloadJson, &payload)
	if err != nil {
		return nil, err
	}

	hostnameInterface, hostnameExists := payload["Hostname"]
	if !hostnameExists {
		return nil, errors.New("Unable to establish websocket connection without Hostname payload")
	}

	wsTrafficker := NewWSTrafficker(conn)
	wsTrafficker.Hostname = hostnameInterface.(string)

	wss.ByAccessTokenHostname[accessToken+"-"+wsTrafficker.Hostname] = NewWSTrafficker(conn)

	logrus.WithFields(logrus.Fields{
		"AccessToken": accessToken,
		"Hostname":    wsTrafficker.Hostname,
	}).Info("Saved websocket connection in memory")

	return wsTrafficker, nil
}
Esempio n. 5
0
func WebsocketSendStream(conn *websocket.Conn, r io.Reader) chan bool {
	ch := make(chan bool)

	go func(conn *websocket.Conn, r io.Reader) {
		in := ReaderToChannel(r)
		for {
			buf, ok := <-in
			if !ok {
				break
			}

			w, err := conn.NextWriter(websocket.BinaryMessage)
			if err != nil {
				Debugf("got error getting next writer %s", err)
				break
			}

			_, err = w.Write(buf)
			w.Close()
			if err != nil {
				Debugf("got err writing %s", err)
				break
			}
		}
		closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
		conn.WriteMessage(websocket.CloseMessage, closeMsg)
		ch <- true
	}(conn, r)

	return ch
}
Esempio n. 6
0
func write(ws *websocket.Conn, mt int, payload []byte) error {
	if ws == nil {
		return errors.New("no web socket connection: ws")
	}
	ws.SetWriteDeadline(time.Now().Add(writeWait))
	return ws.WriteMessage(mt, payload)
}
Esempio n. 7
0
// NOTE :: When a guild voice server changes how do we shut this down
// properly, so a new connection can be setup without fuss?
//
// wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
// is still connected.  If you do not send these heartbeats Discord will
// disconnect the websocket connection after a few seconds.
func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {

	if close == nil || wsConn == nil {
		return
	}

	var err error
	ticker := time.NewTicker(i * time.Millisecond)
	for {
		v.log(LogDebug, "sending heartbeat packet")
		v.wsMutex.Lock()
		err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
		v.wsMutex.Unlock()
		if err != nil {
			v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
			return
		}

		select {
		case <-ticker.C:
			// continue loop and send heartbeat
		case <-close:
			return
		}
	}
}
func createPlayer(conn *websocket.Conn) {
	message, _ := json.Marshal(&Message{Title: "createPlayer", Data: connections.m[conn]})

	if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
		closeConnection(conn)
	}
}
Esempio n. 9
0
func handleWs(s Service, ws *websocket.Conn, subs map[uint32]*wsSub, slock *sync.Mutex) error {
	ch := make(chan []byte)
	defer close(ch)

	go func() {
		for {
			v, ok := <-ch
			if !ok {
				break
			}

			if err := ws.WriteMessage(websocket.BinaryMessage, v); err != nil {
				fmt.Printf("ws.WriteMessage: %#v\n", err)
				break
			}
		}
	}()

	for {
		mt, msg, err := ws.ReadMessage()
		if err != nil {
			fmt.Printf("ws.ReadMessage: %#v\n", err)
			break
		}

		if mt != websocket.BinaryMessage {
			continue
		}

		if err := iter(ch, msg, s, subs, slock); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 10
0
func (w *WebsocketServer) streamWebsocket(websocketSink *websocket.WebsocketSink, websocketConnection *gorilla.Conn, register func(sinks.Sink) bool, unregister func(sinks.Sink)) {
	register(websocketSink)
	defer unregister(websocketSink)

	go websocketConnection.ReadMessage()
	server.NewKeepAlive(websocketConnection, w.keepAliveInterval).Run()
}
Esempio n. 11
0
// writer runs in a goroutine for each connected WS client. It emits all message returned by the observer.
func writer(ws *websocket.Conn, a *ApiHandlers) {
	pingTicker := time.NewTicker(pingPeriod)
	s := a.getDBSubscriber()
	jww.INFO.Println("Opened WebSocket connection.")
	defer func(is *subscriber) {
		jww.INFO.Println("Closing WebSocket connection.")
		is.quitChan <- true
		pingTicker.Stop()
		ws.Close()
	}(s)

	for {
		select {
		case msg := <-s.bufChan:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteJSON(msg); err != nil {
				return
			}
		case <-pingTicker.C:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
Esempio n. 12
0
func (app *App) registerSocket(ws *websocket.Conn, hub *Hub, toHub *Hub) {
	defer hub.RemoveMember(ws)
	hub.AddMember(ws)

	app.KeepAlive()

	from := toHub.FromLabel
	to := toHub.ToLabel
	appname := app.Name

	for {
		mtype, p, err := ws.ReadMessage()
		if err != nil {
			log.Printf("%s: Connection (%s): %s", app.Name, from, err)
			break
		}

		msg := &AppMessage{Data: p,
			Mtype: mtype,
			Id:    int(atomic.AddInt32(&msgcnt, 1)),
			To:    toHub}
		log.Printf("%s: QUEUE [%d] %s -> %s (of %d) [%s]", appname, msg.Id, from, to, len(hub.Members), string(msg.Data))
		app.Channel <- msg
	}
}
Esempio n. 13
0
func PushMsg(ws *websocket.Conn, WSWriter chan []uint8) {

	defer ws.Close()

	for {
		msg := <-WSWriter

		if msg == nil {
			continue
		}

		// write message to client
		if err := ws.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
			log.Println("[ErrorInfo]", err.Error())
			break
		}

		if string(msg) == "bye" {
			break
		}
	}

	endChan <- true

}
Esempio n. 14
0
func streamResults(sock *websocket.Conn, params searchParams, limit int) {
	start := time.Now()
	count := 0
	results := make(chan searchResult)
	control := make(chan struct{}, 1)

	go find(results, control, params)
	for {
		res, ok := <-results
		if !ok {
			log.Printf("Finished request in %v\n", time.Since(start))
			return
		}

		count++
		log.Printf("Found result #%v after %v\n", count, time.Since(start))

		err := sock.WriteJSON(res)
		if err != nil {
			log.Printf("Error while writing result: %v\n", err)
			control <- struct{}{}
			return
		}

		if count >= limit {
			log.Printf("Finished request after hitting limit in %v\n", time.Since(start))
			control <- struct{}{}
			return
		}
	}
}
Esempio n. 15
0
func wsSend(con *websocket.Conn, msgSend chan WSMsg, done, readDone, stopWS chan int) {
	defer fmt.Println("wsSend: goroutine stopped")
	seq := 1
	for {
		select {
		case <-stopWS:
			stopSend(con, done)
			return
		case <-readDone:
			stopSend(con, done)
			return
		case nextMsg, ok := <-msgSend:
			if ok {
				//send the message on the channel to the connection
				nextMsg.Seq = seq
				seq++
				fmt.Println("wsSend: sending msg", nextMsg.Type)
				j, _ := json.Marshal(nextMsg)
				fmt.Printf("wsSend: msg sent: `%s`\n", j)
				if err := con.WriteJSON(&nextMsg); err != nil {
					fmt.Println("wsSend:", err)
				}
			}
		}
	}
}
Esempio n. 16
0
// Handle open Subscriber.
func onOpen(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, sessionID string, app *app) websocketError {
	params := r.URL.Query()
	p := params.Get("protocol")

	protocol, err := strconv.Atoi(p)

	if err != nil {
		return newInvalidVersionStringFormatError()
	}

	switch {
	case strings.TrimSpace(p) == "":
		return newNoProtocolVersionSuppliedError()
	case protocol != SUPPORTED_PROTOCOL_VERSION:
		return newUnsupportedProtocolVersionError()
	case app.ApplicationDisabled:
		return newApplicationDisabledError()
	case r.TLS != nil:
		if app.OnlySSL {
			return newApplicationOnlyAccepsSSLError()
		}
	}

	// Create the new Subscriber
	connection := newConnection(sessionID, conn)
	app.Connect(connection)

	// Everything went fine. Huhu.
	if err := conn.WriteJSON(newConnectionEstablishedEvent(connection.SocketID)); err != nil {
		return newGenericReconnectImmediatelyError()
	}

	return nil
}
Esempio n. 17
0
func (c Discord) WSInit(con *websocket.Conn, msgChan chan WSMsg) {
	//send init on wire
	p := Properties{
		OS:              "DiscordBot",
		Browser:         "discord.go",
		Device:          "console",
		Referrer:        "",
		ReferringDomain: "",
	}
	msgData := INIT{
		Token:      c.Token,
		Version:    3, // hard-coded so changes will only happen when coded in
		Properties: &p,
	}
	msg := WSMsg{
		Op:   2,
		Data: msgData,
	}
	j, _ := json.Marshal(msg)
	fmt.Printf("msgSentInit: `%s`\n", j)
	/* if err := con.WriteMessage(1, j); err != nil {
		fmt.Println("wsInit:",err)
	} */
	err := con.WriteJSON(msg)
	if err != nil {
		fmt.Println("wsInit:", err)
	}
}
Esempio n. 18
0
func pipe_to_net(netConn net.Conn, wsConn *websocket.Conn, protocolType int, stopChan chan int) {
	for {
		select {
		case <-stopChan:
			return
		default:
			{
				_, p, err := wsConn.ReadMessage()
				if err != nil {
					stopChan <- 1
					return
				}
				if protocolType == websocket.BinaryMessage {
					_, err = netConn.Write(p)
					if err != nil {
						stopChan <- 1
						return
					}
				} else if protocolType == websocket.TextMessage {
					data := make([]byte, base64.StdEncoding.DecodedLen(len(p)))
					n, err := base64.StdEncoding.Decode(data, p)
					if err != nil {
						stopChan <- 1
						return
					}
					_, err = netConn.Write(data[:n])
					if err != nil {
						stopChan <- 1
						return
					}
				}
			}
		}
	}
}
Esempio n. 19
0
func WebsocketSendStream(conn *websocket.Conn, r io.Reader) chan bool {
	ch := make(chan bool)

	if r == nil {
		close(ch)
		return ch
	}

	go func(conn *websocket.Conn, r io.Reader) {
		in := ReaderToChannel(r)
		for {
			buf, ok := <-in
			if !ok {
				break
			}

			w, err := conn.NextWriter(websocket.BinaryMessage)
			if err != nil {
				Debugf("Got error getting next writer %s", err)
				break
			}

			_, err = w.Write(buf)
			w.Close()
			if err != nil {
				Debugf("Got err writing %s", err)
				break
			}
		}
		conn.WriteMessage(websocket.TextMessage, []byte{})
		ch <- true
	}(conn, r)

	return ch
}
Esempio n. 20
0
func pipe_to_ws(netConn net.Conn, wsConn *websocket.Conn, protocolType int, stopChan chan int) {
	for {
		select {
		case <-stopChan:
			return
		default:
			{
				data := make([]byte, BUFFER_SIZE)
				n, err := netConn.Read(data)
				if err != nil {
					stopChan <- 1
					return
				}

				if protocolType == websocket.BinaryMessage {
					err = wsConn.WriteMessage(protocolType, data[:n])
					if err != nil {
						stopChan <- 1
						return
					}
				} else if protocolType == websocket.TextMessage {
					encodedData := []byte(base64.StdEncoding.EncodeToString(data[:n]))
					err = wsConn.WriteMessage(protocolType, encodedData)
					if err != nil {
						stopChan <- 1
						return
					}
				}
			}
		}
	}
}
Esempio n. 21
0
func (r *RancherService) pipeLogs(container *rancherClient.Container, conn *websocket.Conn) {
	defer conn.Close()

	log_name := strings.TrimPrefix(container.Name, r.context.ProjectName+"_")
	logger := r.context.LoggerFactory.Create(log_name)

	for {
		messageType, bytes, err := conn.ReadMessage()
		if messageType != websocket.TextMessage {
			continue
		}

		if err == io.EOF {
			return
		} else if err != nil {
			logrus.Errorf("Failed to read log: %v", err)
			return
		}

		if len(bytes) <= 3 {
			continue
		}

		if bytes[len(bytes)-1] != '\n' {
			bytes = append(bytes, '\n')
		}
		message := bytes[3:]

		if "01" == string(bytes[:2]) {
			logger.Out(message)
		} else {
			logger.Err(message)
		}
	}
}
Esempio n. 22
0
func (self *remoteService) run(ws *websocket.Conn) error {
	for {
		mt, msg, err := ws.ReadMessage()
		if err != nil {
			fmt.Printf("remoteService.run: %#v\n", err)
			break
		}

		if mt != websocket.BinaryMessage {
			continue
		}

		cmd := cmdResult{}
		if err := json.NewDecoder(bytes.NewReader(msg)).Decode(&cmd); err != nil {
			return err
		}

		if cmd.Id == nil {
			if err := self.handleEvent(cmd.Back, cmd.Sid, stream.Event([]byte(cmd.Data))); err != nil {
				return err
			}
		} else {
			if err := self.handleCmdRes(*cmd.Id, cmd.Data); err != nil {
				return err
			}
		}
	}
	return nil
}
Esempio n. 23
0
func subChannelEvent(c *websocket.Conn, channel string) {
	subChan := subChannel{Event: "addChannel", Channel: channel}
	err := c.WriteJSON(subChan)
	if err != nil {
		log.Printf("sub channel %s err :%s", channel, err)
	}
}
Esempio n. 24
0
func jionToChatRoom(uname string, ws *websocket.Conn) {

	// Join chat room.
	Join(uname, ws)
	defer Leave(uname)

	// Message receive loop.
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		//=======deal with chat====
		// js, err := simplejson.NewJson(p)
		// if err != nil {
		// 	panic(err.Error())
		// }
		chat := new(models.ChatBean)
		json.Unmarshal(p, chat)

		//=====================
		if chat.Type == 1 || len(chat.To) > 0 {
			publish <- newEvent(models.EVENT_CHAT, uname, string(p))
		} else {
			publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
		}

	}
}
Esempio n. 25
0
func (h *Hijacker) handleOutput(conn *websocket.Conn, pio ProcessIO) int {
	var exitStatus int
	for {
		var output atc.HijackOutput
		err := conn.ReadJSON(&output)
		if err != nil {
			if !websocket.IsCloseError(err) && !websocket.IsUnexpectedCloseError(err) {
				fmt.Println(err)
			}
			break
		}

		if output.ExitStatus != nil {
			exitStatus = *output.ExitStatus
		} else if len(output.Error) > 0 {
			fmt.Fprintf(os.Stderr, "%s\n", ansi.Color(output.Error, "red+b"))
			exitStatus = 255
		} else if len(output.Stdout) > 0 {
			pio.Out.Write(output.Stdout)
		} else if len(output.Stderr) > 0 {
			pio.Err.Write(output.Stderr)
		}
	}

	return exitStatus
}
Esempio n. 26
0
func ptySetupWs(ws *websocket.Conn, sizeFlag string) {
	ptym, cmd := start()
	setPtySize(ptym, sizeFlag)

	go func() {
		handleOutputWs(ptym, ws)
	}()

	go func() {
		handleInputWs(ptym, ws)
	}()

	// Listen for a new winsize on stdin.
	for {
		var newSize string
		_, scanErr := fmt.Scanln(&newSize)
		if scanErr != nil {
			fmt.Println("scan failed: ", scanErr)
		}

		setPtySize(ptym, newSize)
		fmt.Println("new size: ", newSize)
	}

	stop(ptym, cmd)
	ws.Close()
}
func loadLatestSales(websocketConnection *websocket.Conn) {
	results, err := r.Table("analytics").Filter(M{
		"type": "sale",
	}).OrderBy(
		r.Desc(r.Row.Field("data").Field("date")),
	).Limit(10).Map(func(row r.Term) interface{} {
		return row.Field("data")
	}).Run(rethinkSession)
	if err != nil {
		log.Printf("error loadLatestSales: %q", err)
	}
	defer results.Close()

	var latestSales []interface{}
	err = results.All(&latestSales)
	if err != nil {
		log.Println(err)
		return
	}

	log.Printf("sending latest %d sales\n", len(latestSales))

	socketOutgoingMessage := &SocketOutgoingMessage{
		Function: "loadLatestSales",
		Data: M{
			"type": "sale",
			"data": latestSales,
		},
	}

	err = websocketConnection.WriteJSON(socketOutgoingMessage)
	if err != nil {
		log.Println(err)
	}
}
Esempio n. 28
0
File: exec.go Progetto: rockstar/lxd
func sendTermSize(control *websocket.Conn) error {
	width, height, err := terminal.GetSize(int(syscall.Stdout))
	if err != nil {
		return err
	}

	shared.Debugf("Window size is now: %dx%d", width, height)

	w, err := control.NextWriter(websocket.TextMessage)
	if err != nil {
		return err
	}

	msg := shared.ContainerExecControl{}
	msg.Command = "window-resize"
	msg.Args = make(map[string]string)
	msg.Args["width"] = strconv.Itoa(width)
	msg.Args["height"] = strconv.Itoa(height)

	buf, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	_, err = w.Write(buf)

	w.Close()
	return err
}
Esempio n. 29
0
func newWSConn(conn *websocket.Conn, pendingWriteNum int) *WSConn {
	wsConn := new(WSConn)
	wsConn.conn = conn
	wsConn.writeChan = make(chan []byte, pendingWriteNum)

	go func() {
		for b := range wsConn.writeChan {
			if b == nil {
				break
			}

			err := conn.WriteMessage(websocket.BinaryMessage, b)
			if err != nil {
				break
			}
		}

		conn.Close()
		wsConn.Lock()
		wsConn.closeFlag = true
		wsConn.Unlock()
	}()

	return wsConn
}
Esempio n. 30
-1
func listener(conn *websocket.Conn, ID int, field *models.Field) {
	tick := time.NewTicker(5 * time.Millisecond)
	for {
		select {
		case <-tick.C:
			var req struct {
				Request string `json:"request"`
				Param   string `json:"param"`
			}

			err := conn.ReadJSON(&req)
			if err != nil {
				//field.Remove <- ID
				return
			}

			switch req.Request {
			case "move":
				dir, ok := dirMap[req.Param]
				if !ok {
					continue
				}

				wait := new(sync.WaitGroup)
				wait.Add(1)
				field.Change <- models.ChangeDirection{
					Index:     ID,
					Direction: dir,
					Wait:      wait,
				}
				wait.Wait()
			}
		}
	}
}