summaryrefslogtreecommitdiff
path: root/src/rhctl/web_socket.go
blob: df12bde0ca3c8117115da17cb16c9a3b57033b8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//
//  rhctl
//
//  Copyright (C) 2009-2016 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of rhctl.
//
//  rhctl is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  rhctl is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with rhctl. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/gorilla/websocket"
)

type webSocketRequestData struct {
	Command string   `json:"COMMAND"`
	Args    []string `json:"ARGS"`
}

type webSocketResponseBaseData struct {
	ResponseCode int    `json:"RESPONSE_CODE"`
	Type         string `json:"TYPE"`
	ErrorString  string `json:"ERROR_STRING"`
}

type webSocketResponseStateData struct {
	webSocketResponseBaseData
	State interface{} `json:"STATE"`
}

type webSocketResponseUpdateData struct {
	webSocketResponseBaseData
	Update interface{} `json:"UPDATE"`
}

func sendWebSocketResponse(ws *websocket.Conn, rd interface{}) {
	if err := ws.WriteJSON(rd); err != nil {
		rhdl.Println("Web(socket) client", ws.RemoteAddr(), "write error:", err)
	}
}

func sendWebSocketErrorResponse(ws *websocket.Conn, code int, errStr string) {
	rd := &webSocketResponseBaseData{}
	rd.ResponseCode = code
	rd.Type = "error"
	rd.ErrorString = errStr
	sendWebSocketResponse(ws, rd)
}

func sendWebSocketAckResponse(ws *websocket.Conn) {
	rd := &webSocketResponseBaseData{}
	rd.ResponseCode = http.StatusOK
	rd.Type = "ack"
	rd.ErrorString = "OK"
	sendWebSocketResponse(ws, rd)
}

func sendWebSocketStateResponse(ws *websocket.Conn, state State) {
	rd := &webSocketResponseStateData{}
	rd.ResponseCode = http.StatusOK
	rd.Type = "state"
	rd.ErrorString = "OK"
	rd.State = state
	sendWebSocketResponse(ws, rd)
}

func sendWebSocketServerStateResponse(ws *websocket.Conn, state ServerState) {
	rd := &webSocketResponseStateData{}
	rd.ResponseCode = http.StatusOK
	rd.Type = "server-state"
	rd.ErrorString = "OK"
	rd.State = state
	sendWebSocketResponse(ws, rd)
}

func sendWebSocketSwitchStateResponse(ws *websocket.Conn, state SwitchState) {
	rd := &webSocketResponseStateData{}
	rd.ResponseCode = http.StatusOK
	rd.Type = "switch-state"
	rd.ErrorString = "OK"
	rd.State = state
	sendWebSocketResponse(ws, rd)
}

func sendWebSocketSwitchUpdateResponse(ws *websocket.Conn, update SwitchUpdate) {
	rd := &webSocketResponseUpdateData{}
	rd.ResponseCode = http.StatusOK
	rd.Type = "switch-update"
	rd.ErrorString = "OK"
	rd.Update = update
	sendWebSocketResponse(ws, rd)
}

func sendWebSocketUpdateData(ws *websocket.Conn, data interface{}) {
	switch data.(type) {
	case State:
		sendWebSocketStateResponse(ws, data.(State))
	case ServerState:
		sendWebSocketServerStateResponse(ws, data.(ServerState))
	case SwitchState:
		sendWebSocketSwitchStateResponse(ws, data.(SwitchState))
	case SwitchUpdate:
		sendWebSocketSwitchUpdateResponse(ws, data.(SwitchUpdate))
	default:
		sendWebSocketErrorResponse(ws, http.StatusInternalServerError, "got invalid data update")
	}
}

func webSocketSessionHandler(reqchan <-chan webSocketRequestData, ws *websocket.Conn, ctrl *SwitchControl) {
	defer ws.Close()

	updateC := ctrl.Updates.Sub()
	defer ctrl.Updates.Unsub(updateC)

	for {
		select {
		case reqdata, ok := <-reqchan:
			if !ok {
				return
			}
			switch reqdata.Command {
			case "state":
				resp := make(chan interface{})
				ctrl.Commands <- &Command{Type: CmdState, Response: resp}
				result := <-resp
				switch result.(type) {
				case State:
					sendWebSocketStateResponse(ws, result.(State))
				case error:
					sendWebSocketErrorResponse(ws, http.StatusInternalServerError, result.(error).Error())
				default:
					sendWebSocketErrorResponse(ws, http.StatusInternalServerError, fmt.Sprintf("invalid response of type %T: %+v", result, result))
				}
			case "subscribe":
				if len(reqdata.Args) == 1 {
					switch strings.ToLower(reqdata.Args[0]) {
					case "state":
						ctrl.Updates.AddSub(updateC, "state")
						sendWebSocketAckResponse(ws)
					case "server":
						ctrl.Updates.AddSub(updateC, "server:state")
						sendWebSocketAckResponse(ws)
					case "switch":
						ctrl.Updates.AddSub(updateC, "switch:state")
						sendWebSocketAckResponse(ws)
					case "audio":
						fallthrough
					case "gpi":
						fallthrough
					case "oc":
						fallthrough
					case "relay":
						fallthrough
					case "silence":
						ctrl.Updates.AddSub(updateC, "switch:"+reqdata.Args[0])
						sendWebSocketAckResponse(ws)
					default:
						sendWebSocketErrorResponse(ws, http.StatusInternalServerError, fmt.Sprintf("unknown message type '%s'", reqdata.Args[0]))
					}
				} else {
					sendWebSocketErrorResponse(ws, http.StatusInternalServerError, "subscribe takes exactly one argument")
				}
			default:
				sendWebSocketErrorResponse(ws, http.StatusBadRequest, fmt.Sprintf("unknown command '%s'", reqdata.Command))
			}
		case update := <-updateC:
			sendWebSocketUpdateData(ws, update)
		}
	}
}

func webSocketHandler(ctrl *SwitchControl, w http.ResponseWriter, r *http.Request) {
	ws, err := websocket.Upgrade(w, r, nil, 64*1024, 64*1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		rhdl.Println("Web(socket) client", ws.RemoteAddr(), "error:", err)
		return
	}
	rhdl.Println("Web(socket) client", ws.RemoteAddr(), "connected")
	reqchan := make(chan webSocketRequestData)
	go webSocketSessionHandler(reqchan, ws, ctrl)
	defer close(reqchan)

	for {
		t, r, err := ws.NextReader()
		if err != nil {
			rhdl.Println("Web(socket) Client", ws.RemoteAddr(), "disconnected:", err)
			return
		}

		switch t {
		case websocket.TextMessage:
			var reqdata webSocketRequestData
			if err := json.NewDecoder(r).Decode(&reqdata); err != nil {
				if err == io.EOF {
					err = io.ErrUnexpectedEOF
				}
				rhdl.Println("Web(socket) client", ws.RemoteAddr(), "request error:", err)
				sendWebSocketErrorResponse(ws, http.StatusBadRequest, err.Error())
				return
			}
			// rhdl.Printf("Web(socket) client %s got: %+v", ws.RemoteAddr(), reqdata)
			reqchan <- reqdata
		case websocket.BinaryMessage:
			sendWebSocketErrorResponse(ws, http.StatusBadRequest, "binary messages are not allowed")
			io.Copy(ioutil.Discard, r) // consume all the data
		}
	}
}