func (dws DockerWebSockets) listen(ws *websocket.Conn) {
	//	defer ws.Close()
	defer printDebug(fmt.Sprintf("Closing Websocket to", ws.RemoteAddr()))

	var senderid string
	printDebug(fmt.Sprintf("starting listening to:", ws.RemoteAddr()))
	dec := json.NewDecoder(ws)
	for {
		//		msg, err :=rece?iveMsg(ws)

		var m websocketMsg
		//decoder := util.GetCodec("JSON")
		err := dec.Decode(&m)
		printDebug(m)
		//err = decoder.Decode(msg, &m)
		if err != nil {
			printDebug(err)
			dws.remove(senderid)
			return
		}
		senderid = m.Id

		if m.Type == messages.DOCK {
			conn := NewConnection(ws)
			dws.agent.InitDocking(m.Id, m.Codec, m.Msg, conn)
		} else {
			dws.agent.ProcessMsg(m.Id, m.Type, m.Codec, m.Msg)
		}
	}

}
Example #2
0
func (sinkServer *sinkServer) sinkRelayHandler(ws *websocket.Conn) {
	clientAddress := ws.RemoteAddr()

	appId := appid.FromUrl(ws.Request().URL)
	authToken := ws.Request().Header.Get("Authorization")

	if appId == "" {
		message := fmt.Sprintf("SinkServer: Did not accept sink connection with invalid app id: %s.", clientAddress)
		sinkServer.logger.Warn(message)
		ws.CloseWithStatus(4000)
		return
	}

	if authToken == "" {
		message := fmt.Sprintf("SinkServer: Did not accept sink connection from %s without authorization.", clientAddress)
		sinkServer.logger.Warnf(message)
		ws.CloseWithStatus(4001)
		return
	}

	if !sinkServer.authorize(authToken, appId, sinkServer.logger) {
		message := fmt.Sprintf("SinkServer: Auth token [%s] not authorized to access appId [%s].", authToken, appId)
		sinkServer.logger.Warn(message)
		ws.CloseWithStatus(4002)
		return
	}

	s := sinks.NewWebsocketSink(appId, sinkServer.logger, ws, clientAddress, sinkServer.keepAliveInterval)

	sinkServer.activeSinksChans.Register(s.Channel(), appId)
	s.Run(sinkServer.sinkCloseChan)
}
Example #3
0
func WebSocketServer(ws *websocket.Conn) {
	log.Printf("ws connect: %v\n", ws.RemoteAddr())
	var msg Message
	var in []byte
	CurrUser := users.Add(ws)
	defer users.Del(ws)
	defer func() { ws.Close(); log.Printf("ws disconnect: %v\n", ws.RemoteAddr()) }()

	for {
		err := websocket.Message.Receive(ws, &in)
		if err != nil { //пользователь ушел
			return
		}
		err = json.Unmarshal(in, &msg) //TO DO: обработка ошибок
		if err != nil {
			log.Println("json err:", err)
			return
		}
		log.Printf("%+v", msg)
		switch msg.Types {
		case "message":
			msg.User = CurrUser.Nickname
			broadcastMessage <- msg
		case "users":
			if msg.Action == "list" { //остальные типы action игнорятся
				go sendUserlist(ws)
			}
		}
	}
}
Example #4
0
func (s *server) Serve(ws *websocket.Conn) {
	defer log.Printf("Connection closed.")
	defer ws.Close()

	go downstream(ws, s.m.Sub())

	in := bufio.NewScanner(ws)
	var js jsonSplitter
	in.Split(js.Split)
	for in.Scan() {
		log.Printf("incoming json message: %s", in.Text())
		var req webRequest
		if err := json.Unmarshal(in.Bytes(), &req); err != nil {
			log.Printf("Failed to unmarshal incoming request: %v, err: %v", in.Bytes(), err)
			return
		}
		if req.Raw == "" {
			log.Printf("Only raw messages are currently supported")
			continue
		}
		s.m.Send(req.Raw)
	}
	if err := in.Err(); err != nil {
		log.Printf("Error while reading from connection with %v: %v", ws.RemoteAddr(), err)
	}
}
Example #5
0
func connect(conn *websocket.Conn) {
	logger.Printf("websocket from %s", conn.RemoteAddr())
	defer conn.Close()
	var form []byte
	var f Form
	if err := websocket.Message.Receive(conn, &form); err != nil {
		return
	}
	if err := json.Unmarshal(form, &f); err != nil {
		loggedmessage(conn, "invalid request: %s (%s)", form, err)
		return
	}
	loggedmessage(conn, "opening connection to %s for %s", f.Serv, f.Nick)
	client, err := NewClient(f.Serv, f.Nick)
	if err != nil {
		websocket.Message.Send(conn, "connection error: "+err.Error())
		return
	}
	defer func() {
		logger.Printf("closing connection to %s for %s", f.Serv, f.Nick)
		websocket.Message.Send(conn, "connection closed.")
		client.Cmd("QUIT :%s", "client left.")
		client.Close()
	}()
	logger.Printf("joining channel %s", f.Chan)
	client.Cmd("JOIN %s", f.Chan)
	for line := range client.lines {
		// send {"system": message} or {"line": message}
		websocket.JSON.Send(conn, line)
	}
}
// Creates and returns a new Connection object
// Finds token within request URI
func NewConnection(ws *websocket.Conn) (*Connection, error) {

	if origin := ws.RemoteAddr(); origin.String() != "http://lab.quantumtrip.org" && origin.String() != "localhost" {
		log.Println("Unkown origin: \n\tTo: %s\n\tFrom: %s", origin, ws.Request().RemoteAddr)
		//os.Exit(68)
		msg := "Please email [email protected] for access"
		b, err := json.Marshal(msg)
		if err != nil {
			log.Panic(err)
		}

		ws.Write(b)
	}

	query := ws.Request().URL.Query()
	token := GetToken(query)

	user, err := getUser(token)
	if err != nil {
		log.Println(err.Error())
		ws.Close()
		return nil, err
	}

	client := ClientInfo{token, ws.Request().RemoteAddr, user}
	log.Printf("Connection opened %+v", client)

	return &Connection{
		make(chan bool),
		make(chan interface{}),
		client,
		ws,
	}, nil
}
Example #7
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)

}
Example #8
0
func newClient(ws *websocket.Conn, h *hub, srv *wsServer) *wsClient {
	if ws == nil {
		log.Panicln("ws cannot be nil")
	}

	if srv == nil {
		log.Panicln("server cannot be nil")
	}

	maxID++

	return &wsClient{
		id:   maxID,
		ws:   ws,
		h:    h,
		srv:  srv,
		subs: make(map[string]string),

		inMsgChan:  make(chan *wsMessage),
		outMsgChan: make(chan *wsMessage),
		doneChan:   make(chan bool),

		socketID: sha1Sum(fmt.Sprintf("%s-%s-%d", ws.RemoteAddr().String(),
			ws.LocalAddr().String(), maxID)),
	}
}
Example #9
0
// producer handles incoming produce requests. Producers may send multiple
// produce requests on the same persistent connection. The function exits when
// an `io.EOF` is received on the connection.
func producer(conn *websocket.Conn) {

	defer conn.Close()

	for {

		var request protocol.ProduceRequest

		err := websocket.JSON.Receive(conn, &request)
		if err == io.EOF { // graceful shutdown
			break
		}

		if nil != err {
			log.Warn("Ignoring invalid message from %v.", conn.RemoteAddr())
			continue
		}

		ack := new(protocol.Ack)
		if err := broker.Publish(request.Topic, request.ID, &request.Message); nil != err {
			log.Error(err.Error())
			ack.Status = protocol.StatusFailure
		} else {
			ack.Status = protocol.StatusSuccess
		}
		// TODO: should redirect if this node is not the leader

		websocket.JSON.Send(conn, &ack)

	}

	log.Info("Closed producer connection from %v.", conn.RemoteAddr())

}
Example #10
0
func handle(conn *websocket.Conn) {
	logger.Printf("new websocket client: %s", conn.RemoteAddr())
	defer conn.Close()
	req := "1s"
	if err := websocket.Message.Receive(conn, &req); err != nil {
		logger.Printf("error request: %s", err)
		return
	}
	if freq, err := time.ParseDuration(req); err != nil {
		logger.Printf("invalid request: %s", req)
		websocket.Message.Send(conn, "invalid request")
		return
	} else {
		logger.Printf("new request for ticks from %s, period=%s", conn.RemoteAddr(), freq)
		T := time.NewTicker(freq)
		defer T.Stop()
		ticks := 0
		for t := range T.C {
			if ticks >= 16 {
				return
			}
			err := websocket.Message.Send(conn, t.String())
			if err != nil {
				logger.Printf("error sending: %s", err)
				return
			}
			ticks++
		}
	}
}
func wsHandler(ws *websocket.Conn) {
	fmt.Println("NEW WEBSOCKET!")
	fmt.Println(ws.Config())
	fmt.Println(ws.RemoteAddr())
	c := &connection{send: make(chan string, 256), ws: ws}
	go c.writer()
	c.reader()
}
Example #12
0
func wshandler(ws *websocket.Conn) {
	uid := get_uid(ws.RemoteAddr().String())

	// TODO: abstract to func NewConnection() which takes
	//			 interface io.ReadWriteCloser()
	c := &connection{send: make(chan json.RawMessage), ty: ws,
		uid: uid}

	handler(c)
}
Example #13
0
File: ws.go Project: alisle/elleLog
func wsHandler(wsock *websocket.Conn) {
	log.Print("Added WS: ", wsock.RemoteAddr())
	sock := Socket{wsock, make(chan Processors.Event)}
	ActiveSockets = append(ActiveSockets, sock)
	for event := range sock.queue {
		if err := sendPacket(wsock, event); err != nil {
			log.Print("Error: ", err)
			return
		}
	}
}
Example #14
0
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] closing websocket conn", w.RemoteAddr().String())
		ws.b.DelSubscriber(host)
		w.Close()
	}()

	log.Printf("[%s] accepting websocket conn", 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
			}
		}
	}
}
Example #15
0
File: web.go Project: edsu/ginger
func (cs *gingerServer) Add(ws *websocket.Conn) {
	for {

		var url string
		websocket.Message.Receive(ws, &url)

		message := "added:" + url

		if err := cs.g.Add(url, ws.RemoteAddr().String()); err != nil {
			message = fmt.Sprintf("error:", err)
		}

		websocket.Message.Send(ws, message)
	}
}
Example #16
0
func (p *WSPusher) Subscribe(conn *ws.Conn) chan (error) {
	exit := make(chan error)

	p.Lock()
	defer p.Unlock()

	addr := conn.RemoteAddr()
	if _, ok := p.conns[addr]; ok {
		go func() { exit <- fmt.Errorf("%s already connected", addr) }()
	} else {
		p.conns[addr] = conn
		log.Printf("Subscribed `%s` to WSPusher.", addr)
	}
	// TODO: Find a way to signal correct termination
	return exit
}
Example #17
0
func HandleWebSocket(ws *websocket.Conn) {
	var message string

	defer func() {
		log.Println("Closing connection with", ws.RemoteAddr())
		ws.Close()
	}()

	for {
		if websocket.Message.Receive(ws, &message) != nil {
			break
		} else {
			log.Println(message)
		}
	}
}
Example #18
0
func WebSocketServer(ws *websocket.Conn) {
	log.Printf("ws connect: %v\n", ws.RemoteAddr())
	clients = append(clients, ws)
	for {
		var in []byte
		err := websocket.Message.Receive(ws, &in)
		if err != nil {
			return
		}
		if string(in) == "OK" {
			log.Println("paging resfresh: ok")
		} else {
			log.Println("paging resfresh: FAIL")
		}
	}
}
func (websocketServer *websocketServer) recentLogs(ws *websocket.Conn) {
	clientAddress := ws.RemoteAddr()
	appId := appid.FromUrl(ws.Request().URL)

	if appId == "" {
		websocketServer.logInvalidApp(clientAddress)
		ws.CloseWithStatus(4000)
		return
	}

	logMessages := websocketServer.sinkManager.recentLogsFor(appId)

	sendMessagesToWebsocket(logMessages, ws, clientAddress, websocketServer.logger)

	ws.Close()
}
Example #20
0
func (httpServer *httpServer) websocketSinkHandler(ws *websocket.Conn) {
	clientAddress := ws.RemoteAddr()
	appId := appid.FromUrl(ws.Request().URL)

	if appId == "" {
		httpServer.logInvalidApp(clientAddress)
		ws.CloseWithStatus(4000)
		return
	}

	s := sinks.NewWebsocketSink(appId, httpServer.logger, ws, clientAddress, httpServer.messageRouter.sinkCloseChan, httpServer.keepAliveInterval, httpServer.wSMessageBufferSize)
	httpServer.logger.Debugf("HttpServer: Requesting a wss sink for app %s", s.AppId())
	httpServer.messageRouter.sinkOpenChan <- s

	s.Run()
}
Example #21
0
func (httpServer *httpServer) dumpSinkHandler(ws *websocket.Conn) {
	clientAddress := ws.RemoteAddr()
	appId := appid.FromUrl(ws.Request().URL)

	if appId == "" {
		httpServer.logInvalidApp(clientAddress)
		ws.CloseWithStatus(4000)
		return
	}

	dumpChan := httpServer.messageRouter.getDumpChanFor(appId)

	dumpMessagesFromChannelToWebsocket(dumpChan, ws, clientAddress, httpServer.logger)

	ws.Close()
}
Example #22
0
func (proxy *Proxy) proxyConnectionTo(server *websocket.Conn, client *websocket.Conn, doneChan chan bool) {
	proxy.logger.Debugf("Output Proxy: Starting to listen to server %v", server.RemoteAddr().String())

	var logMessage []byte
	defer server.Close()
	for {
		err := websocket.Message.Receive(server, &logMessage)
		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error reading from the server - %v - %v", err, server.RemoteAddr().String())
			doneChan <- true
			return
		}
		proxy.logger.Debugf("Output Proxy: Got message from server %v bytes", len(logMessage))
		websocket.Message.Send(client, logMessage)
	}
}
Example #23
0
// JSON Server
func jsonServer(ws *websocket.Conn) {
	fmt.Printf("websocket connection established, remote %s\n", ws.RemoteAddr())

	for {
		var msg message
		msg.ws = ws

		// Receive messages
		err := websocket.JSON.Receive(ws, &msg.Msg)
		if err != nil {
			fmt.Println("Error receiving json: ", err)
			err = nil
			os.Exit(1)
		}
		msg.parseCmd()
	}
	fmt.Printf("websocket client %v disconnected\n", ws.RemoteAddr())
}
Example #24
0
func WsBuildServer(ws *websocket.Conn) {
	defer ws.Close()
	var err error
	clientMsg := new(Message)
	if err = websocket.JSON.Receive(ws, &clientMsg); err != nil {
		Debugf("read json error: %v", err)
		return
	}
	addr := clientMsg.Data
	name := ws.RemoteAddr().String()
	log.Println("handle request project:", addr, name)

	proj := NewProject(addr, name)
	defer proj.Close()

	firstMsg := &Message{
		Data: proj.BufferStr,
	}
	err = websocket.JSON.Send(ws, firstMsg)
	if err != nil {
		Debugf("send first msg error: %v", err)
		return
	}

	// send the rest outputs
	buf := make([]byte, 100)
	msg := new(Message)
	for {
		n, err := proj.Reader.Read(buf)
		if n > 0 {
			msg.Data = string(buf[:n])
			deadline := time.Now().Add(time.Second * 1)
			ws.SetWriteDeadline(deadline)
			if er := websocket.JSON.Send(ws, msg); er != nil {
				log.Println("write failed timeout, user logout")
				return
			}
		}
		if err != nil {
			return
		}
	}
	log.Println(addr, "loop ends")
}
Example #25
0
func newWorker(ws *websocket.Conn) {
	atomic.AddInt32(&numWorkers, 1)
	log.Printf("Connected [%s] (active = %d)\n", ws.RemoteAddr(), numWorkers)
	for {
		select {
		case j := <-jobs:
			if err := handleJob(ws, j); err != nil {
				log.Printf("Error handling job: %s", err)
				// jobs <- j
			}
		case <-time.After(10 * time.Second):
			if err := isAlive(ws); err != nil {
				ws.Close()
				atomic.AddInt32(&numWorkers, -1)
				log.Printf("Worker died (active = %d)", numWorkers)
				return
			}
		}
	}
}
Example #26
0
func Echo(ws *websocket.Conn) {
	fmt.Println(ws)
	fmt.Println(ws.RemoteAddr())
	fmt.Println("Echoing")
	for n := 0; n < 10; n++ {
		msg := "Hello " + string(n+48)
		fmt.Println("Sending to client: " + msg)
		err := websocket.Message.Send(ws, msg)
		if err != nil {
			fmt.Println("Can't send")
			break
		}
		var reply string
		err = websocket.Message.Receive(ws, &reply)
		if err != nil {
			fmt.Println("Can't receive")
			break
		}
		fmt.Println("Received back from client: " + reply)
	}
}
Example #27
0
File: node.go Project: hycxa/kylin
func (n *node) handleConnect(conn *websocket.Conn) {
	info, err := readNodeInfo(conn)
	if err != nil {
		log.Printf("handle connect error:%v,%v \n", conn.RemoteAddr(), err)
		return
	}
	err = writeNodeInfo(n.Info(), conn)
	if err != nil {
		log.Printf("handle connect error:%v,%v \n", conn.RemoteAddr(), err)
		return
	}
	resultChan := make(chan NodeConnection, 1)
	nodeConnection := n.createNodeConnection(conn, info)
	command := func() {
		n.processNodeConnected(nodeConnection, resultChan)
	}
	n.commandChan <- command
	nodeConnection = <-resultChan
	if nodeConnection != nil {
		n.waitForClose(nodeConnection)
	}
}
Example #28
0
func websocketHander(ws *websocket.Conn) {
	log.App.Info("websocket:", ws.RemoteAddr())
	req := ws.Request()
	var routeMatched *RouteMatched
	if routeMatched = MatchWebSocketRoute([]byte(req.URL.Path)); routeMatched == nil {
		ws.Close()
		return
	}

	prt := reflect.New(routeMatched.ClassType)
	s := websock.GetServer(routeMatched.ClassType.String())
	if s == nil {
		ws.Close()
		return
	}

	prt.MethodByName("Prepare").Call([]reflect.Value{reflect.ValueOf(ws), prt, reflect.ValueOf(s)})
	if isDie(prt.MethodByName("Init").Call(nil)) {
		return
	}
	prt.MethodByName("Listen").Call(nil)
}
Example #29
0
func socketHandler(conn *websocket.Conn) {

	log.Println("socketHandler")
	gid++
	owner := "p" + strconv.Itoa(gid)
	if conns.Exists(owner) {
		conn.Write([]byte("duplicate id\n"))
		return
	}

	conns.Insert(owner, conn)
	msg := Msg{"system", []byte(owner + " login!\n")}
	read <- msg
	log.Println(conn.RemoteAddr(), "connected!")

	readMsg(conn, owner)

	log.Println(conn.RemoteAddr(), "disconnected!")
	conns.Delete(owner)
	conn.Close()
	msg = Msg{"system", []byte(owner + " logout!\n")}
	read <- msg
}
Example #30
0
func (httpServer *httpServer) dumpSinkHandler(ws *websocket.Conn) {
	clientAddress := ws.RemoteAddr()
	appId := appid.FromUrl(ws.Request().URL)

	if appId == "" {
		httpServer.logInvalidApp(clientAddress)
		ws.CloseWithStatus(4000)
		return
	}

	dumpChan := httpServer.messageRouter.registerDumpChan(appId)

	for message := range dumpChan {
		err := websocket.Message.Send(ws, message.GetRawMessage())
		if err != nil {
			httpServer.logger.Debugf("Dump Sink %s: Error when trying to send data to sink %s. Requesting close. Err: %v", clientAddress, err)
		} else {
			httpServer.logger.Debugf("Dump Sink %s: Successfully sent data", clientAddress)
		}
	}

	ws.Close()
}