func WebsocketHandler(ws *websocket.Conn) { key := ws.Request().Header.Get("Sec-Websocket-Key") client := Client{ws, key} Srv.register(client) defer func() { Srv.unregister(client) }() for { msg := make([]byte, 512) n, err := ws.Read(msg) if err != nil { break } var cmd Command json.Unmarshal(msg[:n], &cmd) log.Println(cmd.Event) client.process(cmd) } }
func SockServer(ws *websocket.Conn) { var err error var clientMessage string // use []byte if websocket binary type is blob or arraybuffer // var clientMessage []byte defer func() { if err = ws.Close(); err != nil { log.Println("Websocket could not be closed", err.Error()) } }() client := ws.Request().RemoteAddr log.Println("Client connected:", client) sockCli := ClientConn{ws, client} ActiveClients[sockCli] = 0 log.Println("Number of clients connected ...", len(ActiveClients)) for { if err = Message.Receive(ws, &clientMessage); err != nil { log.Println("Websocket Disconnected waiting", err.Error()) delete(ActiveClients, sockCli) log.Println("Number of clients still connected ...", len(ActiveClients)) return } if len(clientMessage) > 0 { clientMessage = sockCli.clientIP + " Said: " + clientMessage for cs, _ := range ActiveClients { if err = Message.Send(cs.websocket, clientMessage); err != nil { log.Println("Could not send message to ", cs.clientIP, err.Error()) } } } } }
func BuildConnection(ws *websocket.Conn) { email := ws.Request().URL.Query().Get("email") if email == "" { return } onlineUser := &OnlineUser{ InRoom: runningActiveRoom, Connection: ws, Send: make(chan Message, 256), UserInfo: &User{ Email: email, Name: strings.Split(email, "@")[0], Gravatar: libs.UrlSize(email, 20), }, } runningActiveRoom.OnlineUsers[email] = onlineUser m := Message{ MType: STATUS_MTYPE, UserStatus: UserStatus{ Users: runningActiveRoom.GetOnlineUsers(), }, } runningActiveRoom.Broadcast <- m go onlineUser.PushToClient() onlineUser.PullFromClient() onlineUser.killUserResource() }
func websocketUploadServer(ws *websocket.Conn) { dlId := ws.Request().URL.Path[len("/api/upload_ws/"):] bf := GetBounceFile(dlId) if bf == nil { ws.Write([]byte("ERROR! Download with this ID does not exist.")) return } var dataBuffer [50000]byte // 50 KB arbitrary total := 0 for { numBytes, err := ws.Read(dataBuffer[:]) total += numBytes dataCopy := append([]byte{}, dataBuffer[:numBytes]...) bf.SendData(dataCopy) if err == io.EOF { break } if err != nil { // Oops! ws.Write([]byte("ERROR! " + err.Error())) break } ws.Write([]byte("OK")) } }
func handleWss(wsconn *websocket.Conn) { p := Responder{nil, wsconn.Request(), time.Now()} serverIP := wsconn.Request().Header.Get("X-Server-IP") conn, err := net.Dial("tcp", serverIP) if err != nil { p.errorLog(http.StatusInternalServerError, "Error connecting to '%s': %s", serverIP, err.Error()) wsconn.Close() return } defer conn.Close() defer wsconn.Close() wsconn.PayloadType = websocket.BinaryFrame t := ©Syncer{alive: true} go p.CopyR2W(t, conn, wsconn, serverIP+" ws2vnc") go p.CopyR2W(t, wsconn, conn, serverIP+" vnc2ws") p.errorLog(http.StatusOK, "websocket started: '%s'", serverIP) for t.IsAlive() { time.Sleep(100 * time.Millisecond) } p.errorLog(http.StatusOK, "websocket closed: '%s'", serverIP) }
func ServeWebSocket(ws *websocket.Conn) { segs := strings.Split(ws.Request().URL.Path, "/") if len(segs) < 2 { log.Println("No token in incoming request, dropped") websocket.JSON.Send(ws, "No token in incoming request, dropped") return } ak, err := LoadKey(segs[1]) if err != nil { log.Println(err.Error()) websocket.JSON.Send(ws, err.Error()) return } if ak.UsageIsLimited() { err = ak.ConsumeUsage() if err != nil { log.Println(err.Error()) websocket.JSON.Send(ws, err.Error()) return } } socket := NewSocket(ak, ws) go socket.ListenToRedis() go socket.ListenToSocket() socket.Wait() }
func (l *listener) handler(ws *websocket.Conn) { l.lock.Lock() if !l.running { ws.Close() l.lock.Unlock() return } w := &wsPipe{ws: ws, addr: l.addr, proto: l.proto, open: true} w.iswss = l.iswss req := ws.Request() w.props = make(map[string]interface{}) w.props[mangos.PropLocalAddr] = ws.LocalAddr() w.props[mangos.PropRemoteAddr], _ = net.ResolveTCPAddr("tcp", req.RemoteAddr) if l.iswss { w.props[mangos.PropTlsConnState] = *req.TLS } w.wg.Add(1) l.pending = append(l.pending, w) l.cv.Broadcast() l.lock.Unlock() // We must not return before the socket is closed, because // our caller will close the websocket on our return. w.wg.Wait() }
func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) { source := w.Request().FormValue("source") host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano()) defer func() { log.Printf("[%s - %s] closing websocket conn", ws.name, w.RemoteAddr().String()) ws.b.DelSubscriber(host) w.Close() }() log.Printf("[%s - %s] accepting websocket conn", ws.name, w.RemoteAddr().String()) r := make(chan *buffer.Event, recvBuffer) ws.b.AddSubscriber(host, r) for { select { case ev := <-r: if len(source) > 0 { if ev.Source != source { continue } } err := websocket.Message.Send(w, *ev.Text) if err != nil { log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error()) return } } } }
func BuildConnection(ws *websocket.Conn) { log.Info("BuildConnection()") token := ws.Request().URL.Query().Get("token") log.Debug(token) var uci userConnectionInfo err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci) if err != nil { log.WithFields(log.Fields{ "error": err, }).Error("validation error") // how should this reply to the client? return } onlineUser := &OnlineUser{ Connection: ws, Uci: uci, Send: make(chan envelope, 256), } runningRoom.Users[onlineUser] = true go onlineUser.PushToClient() onlineUser.PullFromClient() delete(runningRoom.Users, onlineUser) log.Info("tore down user connection") }
func addLogs(ws *websocket.Conn) { var err error defer func() { data := map[string]interface{}{} if err != nil { data["error"] = err.Error() log.Error(err.Error()) } else { data["error"] = nil } msg, _ := json.Marshal(data) ws.Write(msg) ws.Close() }() req := ws.Request() t := context.GetAuthToken(req) if t == nil { err = fmt.Errorf("wslogs: no token") return } if t.GetAppName() != app.InternalAppName { err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName()) return } err = scanLogs(ws) if err != nil { return } }
func AppLogs(ws *websocket.Conn) *httperr.Error { app := mux.Vars(ws.Request())["app"] header := ws.Request().Header var err error follow := true if header.Get("Follow") == "false" { follow = false } since := 2 * time.Minute if s := header.Get("Since"); s != "" { since, err = time.ParseDuration(s) if err != nil { return httperr.Errorf(403, "Invalid duration %s", s) } } err = models.Provider().LogStream(app, ws, structs.LogStreamOptions{ Filter: header.Get("Filter"), Follow: follow, Since: time.Now().Add(-1 * since), }) if err != nil { if strings.HasSuffix(err.Error(), "write: broken pipe") { return nil } return httperr.Server(err) } return nil }
func AppLogs(ws *websocket.Conn) error { defer ws.Close() app := mux.Vars(ws.Request())["app"] a, err := models.GetApp(app) if awsError(err) == "ValidationError" { return fmt.Errorf("no such app: %s", app) } if err != nil { return err } logs := make(chan []byte) done := make(chan bool) a.SubscribeLogs(logs, done) for data := range logs { ws.Write(data) } return nil }
func addLogs(ws *websocket.Conn) { var err error defer func() { msg := &errMsg{} if err != nil { msg.Error = err.Error() log.Errorf("failure in logs webservice: %s", err) } websocket.JSON.Send(ws, msg) ws.Close() }() req := ws.Request() t := context.GetAuthToken(req) if t == nil { err = errors.Errorf("wslogs: no token") return } if t.GetAppName() != app.InternalAppName { err = errors.Errorf("wslogs: invalid token app name: %q", t.GetAppName()) return } err = scanLogs(ws) if err != nil { return } }
func ircHandler(ws *websocket.Conn) { var err error var clientmessage string current := ClientConn{ws, ws.Request().RemoteAddr} clients[current] = 0 fmt.Println("number of clients connected ", len(clients)) for { if err = message.Receive(ws, &clientmessage); err != nil { delete(clients, current) fmt.Println("client disconnect,", len(clients), " clients remain") return } clientmessage = "<" + hash(current.ip) + "> " + clientmessage for cs, _ := range clients { if err = message.Send(cs.websocket, clientmessage); err != nil { fmt.Println("sending failed") } } } }
/** * Event -> On connection opened */ func (server *server) onConnectionOpened(conn *websocket.Conn) { defer server.Close(conn) log.Printf("Connection opened: %v", conn.Request().RemoteAddr) client := NewClient(conn, server) server.startClient(client) }
func (c *Client) Connect(s *websocket.Conn) { c.knownEnts = make(map[uint32]struct{}) c.c = s c.pinger = time.NewTicker(time.Second) c.latency = 5 c.ponged = true encoder := json.NewEncoder(s) c.encoder = encoder c.origin = s.Request().RemoteAddr log.Println("+", c.origin) ent := NewEntity() ent.x = 20 ent.y = 20 ent.z = 20 ent.owner = c c.owns = ent clientLock.Lock() client[c] = c clientLock.Unlock() c.Send("WORLD", level) go c.Pings() c.ReadForever() }
func socketHandler(ws *websocket.Conn) { fmt.Println("In socketHandler" + ws.Request().RequestURI) var msg DbgMessage err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println("socketHandler: got error", err) _ = websocket.Message.Send(ws, "FAIL:"+err.Error()) return } if msg.Command != "start" { fmt.Println("socketHandler: terminating, 'start' expected.") _ = websocket.Message.Send(ws, "FAIL: 'start' expected)") return } var startMsg StartMessage err = json.Unmarshal(msg.Payload, &startMsg) if err != nil { fmt.Println("socketHandler: wrong payload", err) _ = websocket.Message.Send(ws, "FAIL:"+err.Error()) return } fmt.Println("socketHandler: received start message, exec = " + startMsg.Exec) // Create communication channels. fromProcess := make(chan string) toProcess := make(chan string) fromSocket := make(chan DbgMessage) toSocket := make(chan string) // Start processing the messages. go process(fromProcess, toProcess, fromSocket, toSocket) // Start the child process go processHandler(fromProcess, toProcess) // Launch a goroutine for sending messages through the websocket. // TODO(jarin) Handle termination properly. go func() { for { select { case tosend := (<-toSocket): err := websocket.Message.Send(ws, tosend) if err != nil { fmt.Println("socketHandler sender error", err) return } } } }() // Process incoming messages from the socket and pass them to the channel. for { err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println("socketHandler receive error", err) return } fromSocket <- msg } }
func ProcessRunAttached(ws *websocket.Conn) *httperr.Error { vars := mux.Vars(ws.Request()) header := ws.Request().Header app := vars["app"] process := vars["process"] command := header.Get("Command") release := header.Get("Release") height, _ := strconv.Atoi(header.Get("Height")) width, _ := strconv.Atoi(header.Get("Width")) _, err := models.Provider().ProcessRun(app, process, structs.ProcessRunOptions{ Command: command, Height: height, Width: width, Release: release, Stream: ws, }) if provider.ErrorNotFound(err) { return httperr.New(404, err) } if err != nil { return httperr.Server(err) } return nil }
// SystemLogs returns the logs for the Rack func SystemLogs(ws *websocket.Conn) *httperr.Error { header := ws.Request().Header var err error follow := true if header.Get("Follow") == "false" { follow = false } since := 2 * time.Minute if s := header.Get("Since"); s != "" { since, err = time.ParseDuration(s) if err != nil { return httperr.Errorf(403, "Invalid duration %s", s) } } err = models.Provider().SystemLogs(ws, structs.LogStreamOptions{ Filter: header.Get("Filter"), Follow: follow, Since: time.Now().Add(-1 * since), }) if err != nil { return httperr.Server(err) } return nil }
func (self *Handler) PushSocketHandler(ws *websocket.Conn) { requestID := ws.Request().Header.Get(HeaderID) sock := PushWS{Uaid: "", Socket: ws, Store: self.store, Logger: self.logger, Born: time.Now()} if self.logger.ShouldLog(INFO) { self.logger.Info("handler", "websocket connection", LogFields{"rid": requestID}) } defer func() { now := time.Now() // Clean-up the resources self.app.Server().HandleCommand(PushCommand{DIE, nil}, &sock) self.metrics.Timer("socket.lifespan", now.Sub(sock.Born)) self.metrics.Increment("socket.disconnect") }() self.metrics.Increment("socket.connect") NewWorker(self.app, requestID).Run(&sock) if self.logger.ShouldLog(INFO) { self.logger.Info("main", "Server for client shut-down", LogFields{"rid": requestID}) } }
func echoHandler(ws *websocket.Conn) { var err error var message Message client := ClientConn{ws, ws.Request().RemoteAddr} log.Println("Client connected:", client.ip) for { // получили сообщенько if err = websocket.JSON.Receive(ws, &message); err != nil { log.Println("Disconnected waiting", err.Error()) return } // разбираем, назначаем мастером того, кто так представился if message.Data == "master" { master = &client log.Println("Master client:", master.ip) continue } // если не мастера, то некому слать if master == nil { continue } // шлем то, что пришло, мастеру if err = websocket.JSON.Send(master.ws, message); err != nil { log.Println("Could not send message to ", master.ip, err.Error()) } } }
func serveWebsocket(conn *websocket.Conn) { var ( // ip addr rAddr = conn.Request().RemoteAddr ) log.Debug("start serve \"%s\"", rAddr) DefaultServer.serve(conn, conn, nil, conn, rand.Int()) }
func (a *Api) execContainer(ws *websocket.Conn) { qry := ws.Request().URL.Query() containerId := qry.Get("id") command := qry.Get("cmd") ttyWidth := qry.Get("w") ttyHeight := qry.Get("h") token := qry.Get("token") cmd := strings.Split(command, ",") if !a.manager.ValidateConsoleSessionToken(containerId, token) { ws.Write([]byte("unauthorized")) ws.Close() return } log.Debugf("starting exec session: container=%s cmd=%s", containerId, command) clientUrl := a.manager.DockerClient().URL execConfig := &dockerclient.ExecConfig{ AttachStdin: true, AttachStdout: true, AttachStderr: true, Tty: true, Cmd: cmd, Container: containerId, Detach: true, } execId, err := a.manager.DockerClient().ExecCreate(execConfig) if err != nil { log.Errorf("error calling exec: %s", err) return } if err := a.hijack(clientUrl.Host, "POST", "/exec/"+execId+"/start", true, ws, ws, ws, nil, nil); err != nil { log.Errorf("error during hijack: %s", err) return } // resize w, err := strconv.Atoi(ttyWidth) if err != nil { log.Error(err) return } h, err := strconv.Atoi(ttyHeight) if err != nil { log.Error(err) return } if err := a.manager.DockerClient().ExecResize(execId, w, h); err != nil { log.Errorf("error resizing exec tty: %s", err) return } }
func addLogs(ws *websocket.Conn) { var err error defer func() { data := map[string]interface{}{} if err != nil { data["error"] = err.Error() log.Error(err.Error()) } else { data["error"] = nil } msg, _ := json.Marshal(data) ws.Write(msg) ws.Close() }() req := ws.Request() t := context.GetAuthToken(req) if t == nil { err = fmt.Errorf("wslogs: no token") return } if t.GetAppName() != app.InternalAppName { err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName()) return } dispatcher := app.NewlogDispatcher() scanner := bufio.NewScanner(ws) for scanner.Scan() { var entry app.Applog data := bytes.TrimSpace(scanner.Bytes()) if len(data) == 0 { continue } err = json.Unmarshal(data, &entry) if err != nil { dispatcher.Stop() err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err) return } err = dispatcher.Send(&entry) if err != nil { // Do not disconnect by returning here, dispatcher will already // retry db connection and we gain nothing by ending the WS // connection. log.Errorf("wslogs: error storing log: %s", err) } } err = dispatcher.Stop() if err != nil { err = fmt.Errorf("wslogs: error storing log: %s", err) return } err = scanner.Err() if err != nil { err = fmt.Errorf("wslogs: waiting for log data: %s", err) return } }
func addLogs(ws *websocket.Conn) { var err error defer func() { data := map[string]interface{}{} if err != nil { data["error"] = err.Error() log.Error(err.Error()) } else { data["error"] = nil } msg, _ := json.Marshal(data) ws.Write(msg) ws.Close() }() req := ws.Request() t := context.GetAuthToken(req) if t == nil { err = fmt.Errorf("wslogs: no token") return } if t.GetAppName() != app.InternalAppName { err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName()) return } logCh, errCh := app.LogReceiver() scanner := bufio.NewScanner(ws) for scanner.Scan() { var entry app.Applog data := bytes.TrimSpace(scanner.Bytes()) if len(data) == 0 { continue } err = json.Unmarshal(data, &entry) if err != nil { close(logCh) err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err) return } select { case logCh <- &entry: case err := <-errCh: close(logCh) err = fmt.Errorf("wslogs: storing log: %s", err) return } } close(logCh) err = scanner.Err() if err != nil { err = fmt.Errorf("wslogs: waiting for log data: %s", err) return } err = <-errCh if err != nil { err = fmt.Errorf("wslogs: storing log: %s", err) } }
func remoteShellHandler(ws *websocket.Conn) { var httpErr *errors.HTTP defer func() { defer ws.Close() if httpErr != nil { var msg string switch httpErr.Code { case http.StatusUnauthorized: msg = "no token provided or session expired, please login again\n" default: msg = httpErr.Message + "\n" } ws.Write([]byte("Error: " + msg)) } }() r := ws.Request() token := context.GetAuthToken(r) if token == nil { httpErr = &errors.HTTP{ Code: http.StatusUnauthorized, Message: "no token provided", } return } appName := r.URL.Query().Get(":appname") app, err := getAppFromContext(appName, r) if err != nil { if herr, ok := err.(*errors.HTTP); ok { httpErr = herr } else { httpErr = &errors.HTTP{ Code: http.StatusInternalServerError, Message: err.Error(), } } return } unitID := r.URL.Query().Get("unit") width, _ := strconv.Atoi(r.URL.Query().Get("width")) height, _ := strconv.Atoi(r.URL.Query().Get("height")) term := r.URL.Query().Get("term") opts := provision.ShellOptions{ Conn: ws, Width: width, Height: height, Unit: unitID, Term: term, } err = app.Shell(opts) if err != nil { httpErr = &errors.HTTP{ Code: http.StatusInternalServerError, Message: err.Error(), } } }
// EchoServer contains the main server loop func WsHandler(ws *websocket.Conn) { log.Printf("%v connected to server", ws.Request().RemoteAddr) addr := ws.Request().RemoteAddr // Cleanup defer func() { // TODO: remove conn from channel if err := ws.Close(); err != nil { log.Panicf("%v cleanup could not close connecteion: %v", addr, err.Error()) } }() var data Request for { err := websocket.JSON.Receive(ws, &data) switch { case err == io.EOF: log.Printf("%v disconnected", addr) return default: panic(err.Error()) case err == nil: } switch data.Command { case "": fmt.Printf("empty message\n") case "requestChannelId": log.Printf("%v requestChannelId", addr) channelId, err := generateChannelId() if err { log.Panicf("%v could not generate channel id", addr) return } connections[channelId] = []*websocket.Conn{} response := RequestChannelIdResponse{ ChannelId: channelId, } websocket.JSON.Send(ws, response) case "connectChannel": log.Printf("%v connectChannel", addr) // TODO: disconnect from previous channel connections[data.Channel] = append(connections[data.Channel], ws) case "send": log.Printf("%v send", addr) /* Iterate all connections */ for _, conn := range connections[data.Channel] { if conn != ws { websocket.JSON.Send(conn, data) } } default: log.Panicf("%v Unhandled message\n%v", addr, data) } } }
// socketHandler handles the websocket connection for a given present session. // It handles transcoding Messages to and from JSON format, and starting // and killing processes. func socketHandler(c *websocket.Conn) { in, out := make(chan *Message), make(chan *Message) errc := make(chan error, 1) // Decode messages from client and send to the in channel. go func() { dec := json.NewDecoder(c) for { var m Message if err := dec.Decode(&m); err != nil { errc <- err return } in <- &m } }() // Receive messages from the out channel and encode to the client. go func() { enc := json.NewEncoder(c) for m := range out { if err := enc.Encode(m); err != nil { errc <- err return } } }() defer close(out) // Start and kill processes and handle errors. proc := make(map[string]*process) for { select { case m := <-in: switch m.Kind { case "run": log.Println("running snippet from:", c.Request().RemoteAddr) proc[m.Id].Kill() proc[m.Id] = startProcess(m.Id, m.Body, out, m.Options) case "kill": proc[m.Id].Kill() } case err := <-errc: if err != io.EOF { // A encode or decode has failed; bail. log.Println(err) } // Shut down any running processes. for _, p := range proc { p.Kill() } return } } }
func echoServer(ws *websocket.Conn) { request := make([]byte, 10000) n, err := ws.Read(request) if err != nil { fmt.Println("Error", err.Error()) return } rStr := string(request[:n]) fmt.Println("Read:", n, "It was ", rStr, " type:", ws.Request().FormValue("l")) ws.Write([]byte(rStr)) }
func createserver(ws *websocket.Conn) { var c ClientConnection c.RemoteAddr = ws.Request().RemoteAddr fmt.Printf(c.RemoteAddr + "\r\n") c.Auth = false allClients[ws] = c fmt.Println("Client connected:") fmt.Println("Remote Address: ", c.RemoteAddr) fmt.Println("Authorized: ", c.Auth) Receive(ws) }