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 }
// Registers the connection from to the intools engine func (appClient *AppClient) Register(conn *websocket.Conn) { // Add the client to the connected clients logs.Debug.Printf("Connection event from client") var client = &Client{ Socket: conn, GroupIds: []string{}, } logs.Debug.Printf("clients before %v", appClient.Clients) appClient.Clients[conn] = client // appClient.Clients = append(appClient.Clients, client) logs.Debug.Printf("clients %v", appClient.Clients) // Send ack message := Message{ Command: "connected", Data: nil, } conn.WriteJSON(message) // Handles events from client Events: for { var message Message err := conn.ReadJSON(&message) if err != nil { switch err.(type) { case *websocket.CloseError: logs.Debug.Printf("Websocket %p is deconnected. Removing from clients", conn) delete(appclient.Clients, conn) logs.Debug.Printf("Clients are now %v", appClient.Clients) break Events default: logs.Error.Printf("Error while reading json message : %s", err) continue Events } } logs.Debug.Printf("Message %v", message) switch message.Command { case "register-group": // Handles group registering for the client client.GroupIds = append(client.GroupIds, message.Data["groupId"].(string)) logs.Debug.Printf("Registered group %s for client %p", message.Data["groupId"], client) case "unregister-group": // Handles group unregistering for the client i := utils.IndexOf(client.GroupIds, message.Data["groupId"].(string)) if i != -1 { client.GroupIds = append(client.GroupIds[:i], client.GroupIds[i+1:]...) logs.Debug.Printf("Unregistered group %s for client %p", message.Data["groupId"], client) } } logs.Debug.Printf("Registered groups for client %p are now : %s", client, client.GroupIds) } }
func patchUserSource(t *testing.T, c *websocket.Conn, fileName, oldSource, newSource string) []interface{} { patchJson := createPatchJson(t, fileName, oldSource, newSource) err := c.WriteMessage(websocket.TextMessage, []byte(patchJson)) require.Nil(t, err) result := make(map[string]interface{}) err = c.ReadJSON(&result) require.Nil(t, err) return result["errors"].([]interface{}) }
func pingSocket(socket *websocket.Conn, err chan string) { var v interface{} for { errr := socket.ReadJSON(&v) if errr != nil { err <- errr.Error() } } }
func ReadJSON(conn *websocket.Conn) map[string]interface{} { reply := make(map[string]interface{}) err := conn.ReadJSON(&reply) if err != nil { logrus.Error(err.Error()) } return reply["data"].(map[string]interface{}) }
func EmitJSONWithReply(conn *websocket.Conn, req map[string]interface{}) (map[string]interface{}, error) { if err := conn.WriteJSON(req); err != nil { return nil, errors.New("Error while marshing request: " + err.Error()) } resp := make(map[string]interface{}) if err := conn.ReadJSON(&resp); err != nil { return nil, errors.New("Error while marshing response: " + err.Error()) } return resp["data"].(map[string]interface{}), nil }
func HandleLeafConn(conn *websocket.Conn) { log.Println("Leaf connected") for { var packet common.Packet if err := conn.ReadJSON(&packet); err != nil { log.Println("Error reading leaf json: ", err) return } HandlePacket(&packet, conn) } }
func HandleConn(conn *websocket.Conn) { log.Println("Client app connected") head.CurrentApp = conn for { var request Request if err := conn.ReadJSON(&request); err != nil { log.Println("Error reading app json: ", err) return } response := HandleRequest(&request) conn.WriteJSON(response) } }
func processMessage(conn *websocket.Conn) []byte { var tests []Test // _ = "breakpoint" err := conn.ReadJSON(&tests) if err != nil { return nil } tests[0].Number++ message, err := json.Marshal(&tests) if err != nil { return nil } return message }
func (chat *Chat) Join(client *websocket.Conn) { chat.clients = append(chat.clients, client) go func() { for { var message Message err := client.ReadJSON(&message) message.Time = time.Now() if err != nil { log.Println(err) break } chat.incoming <- &message log.Println("decoded message") } }() }
func handleConnect(conn *websocket.Conn) { player := httpPlayer{game.Black, conn} var c commandFromClient err := conn.ReadJSON(&c) if err != nil { log.Println("websocket error:", err) return } switch c.Command { case "new_game": var args newGameArgs if err := json.Unmarshal(c.Args, &args); err != nil { log.Printf("bad new_game args: %s (%s)", err, string(c.Args)) return } game, err := game.NewGame(game.Config{ Black: player, White: cpuPlayer, Width: args.Width, Height: args.Height, Logger: os.Stderr, }) if err != nil { log.Printf("error creating game: %s", err) return } result := game.Play() gameOver := commandToClient{ Command: "game_over", Args: map[string]string{ "message": fmt.Sprintf("%s (%s) is the winner!", result.Winner.Color(), result.Winner.Name()), }, } if err := conn.WriteJSON(gameOver); err != nil { log.Printf("error sending game_over: %s", err) return } default: log.Printf("unknown command from http player: %s", c.Command) } }
func readCommand(ws *websocket.Conn) interface{} { var command struct { Name string Command json.RawMessage } if err := ws.ReadJSON(&command); err != nil { return err } newFn := commands[command.Name] if newFn == nil { return errors.New("unknown command " + command.Name) } v := newFn() if err := json.Unmarshal([]byte(command.Command), v); err != nil { return err } return v }
func NewConnection(ws *websocket.Conn) (*connection, error) { var err error ret := &connection{ws: ws} err = ws.WriteJSON(&MyNode) if err == nil { err = ws.ReadJSON(&ret.node) } if err != nil { return nil, err } ret.name = fmt.Sprintf("%s -> %s (%s)", ws.LocalAddr(), ws.RemoteAddr(), ret.node) ret.sendChan = make(chan interface{}, 1) go ret.sendLoop() return ret, nil }
func messagesHandler(ws *websocket.Conn, ticker *time.Ticker, msg Event, c chan Event, e chan error) { ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(PONG_WAIT)) return nil }) for { err := ws.ReadJSON(&msg) if err != nil { log.Println("READ ERR") ticker.Stop() e <- err } if reflect.TypeOf(msg).String() == "tutum.Event" { c <- msg } } }
// Handle reading messages sent over websockets from the front-end func wsReader(ws *websocket.Conn, msgs chan wsMessage) { for { msg := wsMessage{} err := ws.ReadJSON(&msg) if err != nil { return // abort reader } switch msg.Action { case "export": go wsExportCommand(msgs) default: msgs <- msg } } }
func dispatchControl(sock *websocket.Conn) { var req controlRequest defer sock.Close() for { err := sock.ReadJSON(&req) if err != nil { log.Printf("Closing control socket. err=%v", err) return } log.Printf("Received control request %v\n", req) switch req.Typ { case "StatusRequest": go streamStatus(sock) default: log.Printf("UNKNOWN REQUEST TYPE %v", req.Typ) } } }
func reader(wsConn *websocket.Conn) { // connect to mongodb session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() for { m := make(map[string]interface{}) err := wsConn.ReadJSON(&m) if err != nil { log.Println("Error reading json.", err) } log.Println("Got message:") log.Println(m) // if its server_diff_response if m["action"] != nil { action := m["action"].(string) switch action { case "server_diff_response": log.Println("RECEIVED server_diff_response") processServerDiffResponse(wsConn, m, session) case "server_send_users": log.Println("RECEIVED server_send_users") processServerSendUsers(m, session) case "server_send_schemas": log.Println("RECEIVED server_send_schemas") } } } }
func wsRead(con *websocket.Conn, msgRead chan WSMsg, done chan int) { defer fmt.Println("wsRead: goroutine stopped") var nextMsg WSMsg for { //read the next message, put it on the channel err := con.ReadJSON(&nextMsg) if err != nil { fmt.Println("wsRead:", err) fmt.Println("wsRead: stopping") //we either need to send close, or we already sent close. //either way, close readdone close(done) // this signals to wssend to start close if needed close(msgRead) // this signals to process to stop //and exit return } //fmt.Println("Read from conn") //err = json.Unmarshal(msg, &nextMsg) fmt.Printf("wsRead: Read %T from conn\n", nextMsg.Data) nextMsg.time = time.Now() msgRead <- nextMsg } }
func (hub *Hub) listen(conn *websocket.Conn) { for { request := &ProtocolMessage{} err := conn.ReadJSON(request) if err != nil { conn.Close() log.Println(err) return } fn, exists := hub.processors[request.Type] var response *ProtocolMessage if exists { response, err = fn(hub, request) if err != nil { response = &ProtocolMessage{ Type: "error", Text: err.Error(), } } } else { response = &ProtocolMessage{ Type: "error", Text: "unknown method", } } err = conn.WriteJSON(response) if err != nil { conn.Close() log.Println(err) return } } conn.Close() }
func getMessage(ws *websocket.Conn) (m Message, err error) { //err = websocket.JSON.Receive(ws, &m) err = ws.ReadJSON(&m) return }
func (r *Handler) serveWS(conn *websocket.Conn) { handshake := struct { Protocol string ObjectVersions objectVersions }{} //first message is the rt handshake if err := conn.ReadJSON(&handshake); err != nil { conn.WriteMessage(websocket.TextMessage, []byte("Invalid rt handshake")) conn.Close() return } if handshake.Protocol != proto { conn.WriteMessage(websocket.TextMessage, []byte("Invalid rt protocol version")) conn.Close() return } //ready u := &User{ ID: conn.RemoteAddr().String(), Connected: true, uptime: time.Now(), conn: conn, versions: handshake.ObjectVersions, pending: []*update{}, } //add user and subscribe to each obj r.mut.Lock() for k := range u.versions { if _, ok := r.objs[k]; !ok { conn.WriteMessage(websocket.TextMessage, []byte("missing object: "+k)) r.mut.Unlock() return } } r.users[u.ID] = u if r.watchingUsers { r.userEvents <- u } for k := range u.versions { obj := r.objs[k] obj.subscribers[u.ID] = u //create initial update u.pending = append(u.pending, &update{ Key: k, Version: obj.version, Data: obj.bytes, }) obj.Update() } r.mut.Unlock() //loop here during connection for { //msgType, msgBytes, err _, _, err := conn.ReadMessage() if err != nil { break } //TODO(jpillora): allow changing of subscriptions } conn.Close() //ensure closed u.Connected = false //remove user and unsubscribe to each obj r.mut.Lock() delete(r.users, u.ID) if r.watchingUsers { r.userEvents <- u } for k := range u.versions { obj := r.objs[k] delete(obj.subscribers, u.ID) } r.mut.Unlock() //disconnected }
func (r *Receiver) receive(ws *websocket.Conn, v interface{}) bool { r.err = ws.ReadJSON(v) return r.err == nil }
func CmdLoop() { const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to resond to a ping event from peer pingWait = 55 * time.Second ) var ( // Connection object ws *websocket.Conn ) bigobjectURL := url.URL{ Scheme: "ws", Host: net.JoinHostPort(host, port), Path: "exec", } var err error dialer := websocket.DefaultDialer if ws, _, err = dialer.Dial(bigobjectURL.String(), nil); err != nil { if !quiet { log.Fatalln(err) } else { os.Exit(1) } } ws.SetPingHandler(nil) input, next := MakeReadline() ticker := time.Tick(pingWait) defer func() { if err := recover(); err != nil { ws.Close() if !quiet { log.Fatalln(err) } else { os.Exit(1) } } }() for { select { case stmt, ok := <-input: if !ok { return } now := time.Now() switch parseAction(stmt) { default: req := &api.RPCRequest{Stmt: stmt} if err := ws.WriteJSON(req); err != nil { if !quiet { fmt.Println(err) } } else { var resp interface{} if err := ws.ReadJSON(&resp); err != nil { panic(err) } text, _ := json.MarshalIndent(resp, "", " ") fmt.Println(string(text)) } break case GET_RESULT_NOW: req := &api.RPCRequest{Stmt: stmt, Opts: &api.RPCOpts{Handle: handle}} if err := ws.WriteJSON(req); err != nil { if !quiet { fmt.Println(err) } } else if !handle { var idx int64 = 1 for idx > 0 { var resp map[string]interface{} if err := ws.ReadJSON(&resp); err != nil { panic(err) } if thing, ok := resp["Content"]; ok && thing != nil { payload := thing.(map[string]interface{}) data := payload["content"].([]interface{}) idx = int64(payload["index"].(float64)) for _, thing := range data { text, _ := json.MarshalIndent(thing, "", " ") fmt.Println(string(text)) } } else { text, _ := json.MarshalIndent(resp, "", " ") fmt.Println(string(text)) break } } } else { var resp interface{} if err := ws.ReadJSON(&resp); err != nil { panic(err) } text, _ := json.MarshalIndent(resp, "", " ") fmt.Println(string(text)) } break case FETCH_DATA: req := &api.RPCRequest{Stmt: stmt} if err := ws.WriteJSON(req); err != nil { if !quiet { fmt.Println(err) } } else { var idx int64 = 1 for idx > 0 { var resp map[string]interface{} if err := ws.ReadJSON(&resp); err != nil { panic(err) } if thing, ok := resp["Content"]; ok && thing != nil { payload := thing.(map[string]interface{}) data := payload["content"].([]interface{}) idx = int64(payload["index"].(float64)) for _, thing := range data { text, _ := json.MarshalIndent(thing, "", " ") fmt.Println(string(text)) } } else { text, _ := json.MarshalIndent(resp, "", " ") fmt.Println(string(text)) break } } } } next <- time.Since(now) case <-ticker: ws.WriteControl( websocket.PongMessage, []byte{}, time.Now().Add(writeWait), ) } } }
func (s *Server) hijack(hLog lager.Logger, conn *websocket.Conn, request hijackRequest) { hLog = hLog.Session("hijack", lager.Data{ "handle": request.ContainerHandle, "process": request.Process, }) container, found, err := s.workerClient.LookupContainer(hLog, request.ContainerHandle) if err != nil { hLog.Error("failed-to-lookup-container", err) closeWithErr(hLog, conn, websocket.CloseInternalServerErr, "failed to lookup container") return } if !found { hLog.Info("could-not-find-container") closeWithErr(hLog, conn, websocket.CloseInternalServerErr, fmt.Sprintf("could not find container")) return } defer container.Release(nil) stdinR, stdinW := io.Pipe() inputs := make(chan atc.HijackInput) outputs := make(chan atc.HijackOutput) exited := make(chan int, 1) errs := make(chan error, 1) cleanup := make(chan struct{}) defer close(cleanup) outW := &stdoutWriter{ outputs: outputs, done: cleanup, } errW := &stderrWriter{ outputs: outputs, done: cleanup, } var tty *garden.TTYSpec if request.Process.TTY != nil { tty = &garden.TTYSpec{ WindowSize: &garden.WindowSize{ Columns: request.Process.TTY.WindowSize.Columns, Rows: request.Process.TTY.WindowSize.Rows, }, } } process, err := container.Run(garden.ProcessSpec{ Path: request.Process.Path, Args: request.Process.Args, Env: request.Process.Env, Dir: request.Process.Dir, User: request.Process.User, TTY: tty, }, garden.ProcessIO{ Stdin: stdinR, Stdout: outW, Stderr: errW, }) if err != nil { hLog.Error("failed-to-hijack", err) return } hLog.Info("hijacked") go func() { for { var input atc.HijackInput err := conn.ReadJSON(&input) if err != nil { break } select { case inputs <- input: case <-cleanup: return } } }() go func() { status, err := process.Wait() if err != nil { errs <- err } else { exited <- status } }() for { select { case input := <-inputs: if input.Closed { stdinW.Close() } else if input.TTYSpec != nil { err := process.SetTTY(garden.TTYSpec{ WindowSize: &garden.WindowSize{ Columns: input.TTYSpec.WindowSize.Columns, Rows: input.TTYSpec.WindowSize.Rows, }, }) if err != nil { conn.WriteJSON(atc.HijackOutput{ Error: err.Error(), }) } } else { stdinW.Write(input.Stdin) } case output := <-outputs: err := conn.WriteJSON(output) if err != nil { return } case status := <-exited: conn.WriteJSON(atc.HijackOutput{ ExitStatus: &status, }) return case err := <-errs: conn.WriteJSON(atc.HijackOutput{ Error: err.Error(), }) return } } }
func handleConnection(ctx context.Context, ws *websocket.Conn, in chan<- *transport.Message, out <-chan *transport.Message) { ch := make(chan error, 2) // start read loop go func(ch chan<- error) { var chErr error defer func() { if chErr != nil { ch <- chErr } }() for { select { case <-ctx.Done(): return default: } msg := &transport.Message{} if err := ws.ReadJSON(msg); err != nil { chErr = err return } select { case <-ctx.Done(): return case in <- msg: } } }(ch) // start write loop go func(ch chan<- error) { var chErr error defer func() { if chErr != nil { ch <- chErr } }() for { var msg *transport.Message select { case <-ctx.Done(): return case msg = <-out: } if err := ws.WriteJSON(msg); err != nil { chErr = err return } } }(ch) select { case <-ctx.Done(): if ctx.Err() != context.Canceled { logrus.Error(ctx.Err()) } case err := <-ch: logrus.Error(err) } }
}) }) Context("when the process prints to stdout", func() { JustBeforeEach(func() { Eventually(fakeContainer.RunCallCount).Should(Equal(1)) _, io := fakeContainer.RunArgsForCall(0) _, err := fmt.Fprintf(io.Stdout, "some stdout\n") Expect(err).NotTo(HaveOccurred()) }) It("forwards it to the response", func() { var hijackOutput atc.HijackOutput err := conn.ReadJSON(&hijackOutput) Expect(err).NotTo(HaveOccurred()) Expect(hijackOutput).To(Equal(atc.HijackOutput{ Stdout: []byte("some stdout\n"), })) }) }) Context("when the process prints to stderr", func() { JustBeforeEach(func() { Eventually(fakeContainer.RunCallCount).Should(Equal(1)) _, io := fakeContainer.RunArgsForCall(0) _, err := fmt.Fprintf(io.Stderr, "some stderr\n")
UUID: uuid, Sender: "sprinklers", } var buf bytes.Buffer enc := json.NewEncoder(&buf) enc.Encode(msg) req, err := http.NewRequest("POST", fmt.Sprintf(addr2, "internal/updates", "", ""), &buf) Expect(err).To(BeNil()) req.Header.Add("Authorization", token) r, err := http.DefaultClient.Do(req) Expect(err).To(BeNil()) Expect(r.StatusCode).To(Equal(http.StatusOK)) defer r.Body.Close() var msg2 gogadgets.Message err = ws.ReadJSON(&msg2) Expect(msg2.Value.Value).To(BeTrue()) Expect(msg2.Location).To(Equal("back yard")) Expect(msg2.UUID).To(Equal(uuid)) }) }) }) }) Describe("with cookies", func() { var ( getCookie cookieGetter ) BeforeEach(func() {
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() } } } }
func messagesHandler(ws *websocket.Conn, ticker *time.Ticker, msg Event, c chan Event, e chan error, e2 chan error) { ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(PONG_WAIT)) return nil }) for { err := ws.ReadJSON(&msg) if err != nil { e <- err e2 <- err time.Sleep(4 * time.Second) } else { if reflect.TypeOf(msg).String() == "tutum.Event" { c <- msg } } } }