-
Notifications
You must be signed in to change notification settings - Fork 12
/
WebSocket.cpp
417 lines (360 loc) · 10.5 KB
/
WebSocket.cpp
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*
* WebSocket.cpp - Websocket Implementation - works on most browsers and Mobile Phones (but notably Not on IE8)
*
* Created: 3/30/2014 9:57:39 PM
*
* Aritech Alarm Panel Arduino Internet Enabled Keypad - CS350 - CD34 - CD72 - CD91 and more
*
* For Arduino (UNO or Leonardo) with added Ethernet Shield
*
* See Circuit Diagram for wiring instructions
*
* Author: Ozmo
*
* See: http://www.boards.ie/vbulletin/showthread.php?p=88215184
*
*/
#include "sha1.h"
#include "RKP.h" //for nKeyToSend
#include "LOG.h"
#include "websocket.h"
#ifdef AtmelStudio
//Other modules
#include <SPI.cpp>
#include <Ethernet.cpp>
#include <EthernetClient.cpp>
#include <EthernetServer.cpp>
#include <utility\socket.cpp>
#include <utility\w5100.cpp>
#else
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
//#include <util.h>
#endif
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
//--Sockets
//use this as password - pick random port - set code tamper on alarm also.
EthernetServer ethServer = EthernetServer(IP_P);
EthernetClient ethClient;
//Symbols as displayed on the HTML page
#define KEY_STAR "▲" //unicode arrow up "*"
#define KEY_POUND "▼" //unicode arrow down "#"
const char htmlSite[] PROGMEM=
"<!DOCTYPE html>"
"<html><head><title>Castle</title>"
"<meta name='viewport' content='width=320, initial-scale=1.8, user-scalable=no'>" //"no" as screen unzooms when press button
"<style>.long{height: 64px;} button{height: 35px;width: 35px;}</style>"
"</head><body>"
"<div style='border: 5px solid black; width: 180px;'> <div id=msg1 style='float:left'> </div><div id=msg2 style='float:right'> </div></div>"
"<table id='table'>"
"<tr><td><button>1</button></td><td><button>2</button></td><td><button>3</button></td><td rowspan=2><button class=long>Y</button></td></tr>"
"<tr><td><button>4</button></td><td><button>5</button></td><td><button>6</button></td></tr>"
"<tr><td><button>7</button></td><td><button>8</button></td><td><button>9</button></td><td rowspan=2><button class=long>N</button></td></tr>"
"<tr><td><button value='*'>" KEY_STAR "</button></td><td><button>0</button></td><td><button value='#'>" KEY_POUND "</button></td></tr>"
"</table>"
"<script defer>var ws;"
"function ge(x){return document.getElementById(x);}\n"
"function st(x,y){ge('msg1').innerText=x;ge('msg2').innerText=y?y:' ';}\n"
"try{"
"ws = new WebSocket('ws://'+location.hostname+':" STR(IP_P) "/sock/');"
"ws.onmessage = function(evt){var d=evt.data.split('|');st(d[0],d[1]);}\n"
"ws.onerror = function(evt){st('ERR:' + evt.data,'');}\n"
"ws.onclose = function(evt){st('Connection Closed','');}\n"
//"ws.onopen = function(){ws.send('r');}\n"
//pc keyboard support
"document.body.onkeydown = function(e){ws.send(String.fromCharCode(e.keyCode));}\n"
//buttons on html
"ge('table').onclick = function(e){ws.send(e.target.value || e.target.innerText);}\n"
"} catch(ex) {alert(ex.message);}\n"
"</script></body></html>";
void WebSocket::EtherPoll()
{
// Should be called for each loop.
EthernetClient cli=ethServer.available();
if (cli)
{
if (ethClient != cli)
{//New connection
LogLn(F("new"));
//Secrisk
ethClient = cli;
WebSocket_doHandshake();
}
else
{//Existing connection
//LogLn(F("existing"));
if (WebSocket_getFrame() == false)
{//Request to end comms (rarely happens)
//Got bad frame, disconnect
Log(F("Disconnect{"));
while(ethClient.available()>0)
ethClient.read();
ethClient.flush();
ethClient.stop();
}
}
}
//static int n=0;
//if (n++ % 1000 == 0)
// LogLn(Ethernet.localIP());
}
void WebSocket::SendHTMLSite(/*EthernetClient& cli*/)
{
//Log(F("ConnectWWW{"));
// while(ethClient.available()>0)
// Log((char)cli.read());
//LogLn(F("}"));
ethClient.println(F("HTTP/1.0 200 OK")); //
ethClient.println(F("Content-Type: text/html"));
ethClient.println(F("Connnection: close"));
ethClient.println();
const char* p = &htmlSite[0];
for(int n=0;n<2000;n++)
{
char c = pgm_read_byte(p++);
if (c==0) break;
//Can use tokens to compress the HTML a bit
//if (c=='*')
// ethClient.print(F("button"));
//else
ethClient.print(c);
}
// close the connection so browser gets data
ethClient.flush();
//delay(1);
ethClient.stop();
LogLn("Sent Page");
}
// Create a Websocket server
void WebSocket::WebSocket_EtherInit()
{
IPAddress ip( IP_A, IP_B, IP_C, IP_D); //Give the device a unique IP
IPAddress gateway( IP_A, IP_B, IP_C, 1 ); //Gateway (youre Router)
IPAddress subnet( 255, 255, 255, 0 ); //typically dont need change
// this sequence must be unique on your lan
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x59, 0x67 }; //typically dont need change
//Start Ethernet
Ethernet.begin(mac, ip/*, gateway, subnet*/);
ethServer.begin();
delay(1000); // Settle time
Log(F("server is at ")); LogLn(Ethernet.localIP());
}
//Send something to connected browser
bool WebSocket::WebSocket_send(char* data, byte length)
{
// LogLn("Sending Screen");LogHex((byte*)data,length);
if (!ethClient.connected())
{
//LogLn(F("No Client."));
return false;
}
//int length = strlen(data);
ethClient.write(0x81);// string type
if (length > 125) {
ethClient.write(126);
ethClient.write((uint8_t) (length >> 8));
ethClient.write((uint8_t) (length && 0xFF));
}
else
ethClient.write((uint8_t) length);
for (int i=0; i<length; ++i)
ethClient.write(data[i]);
//LogLn(F("Sent OK."));
return true;
}
//used by base64
inline void WebSocket::a3_to_a4(unsigned char * a4, unsigned char * a3) {
a4[0] = (a3[0] & 0xfc) >> 2;
a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4);
a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6);
a4[3] = (a3[2] & 0x3f);
}
int WebSocket::base64_encode(char *output, char *input, int inputLen)
{
int i = 0, j = 0;
int encLen = 0;
unsigned char a3[3];
unsigned char a4[4];
static char b64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
while(inputLen--) {
a3[i++] = *(input++);
if(i == 3) {
a3_to_a4(a4, a3);
for(i = 0; i < 4; i++) {
output[encLen++] = b64_alphabet[a4[i]];
}
i = 0;
}
}
if(i) {
for(j = i; j < 3; j++) {
a3[j] = '\0';
}
a3_to_a4(a4, a3);
for(j = 0; j < i + 1; j++) {
output[encLen++] = b64_alphabet[a4[j]];
}
while((i++ < 3)) {
output[encLen++] = '=';
}
}
output[encLen] = '\0';
return encLen;
}
char WebSocket::htmlline[128]; //There are 3 buffers needed - htmlline, key and sha - sha and htmlline share the same temp buffer
char WebSocket::key[80]; //this cannot use htmlline also
void WebSocket::WebSocket_doHandshake()
{
LogLn("HS");
bool hasKey = false;
bool bReqWebPage = false;
byte counter = 0;
while(ethClient.available()>0)
{//Read each line
//ignore any lines not starting with Sec-WebSocket-Key: if (counter.length==18){}
byte bite = ethClient.read();
//Log((char)bite); LogLn("");
htmlline[counter++] = bite;
if (counter > (127))
{
Log(F("Line too long{"));
htmlline[counter - 1] = 0; // Terminate string before CRLF
Log("Ignoring> ");LogLn(htmlline);
LogLn(F("}"));
counter=0;
continue;
}
if (bite == '\n')
{ // Parse the line
htmlline[counter - 2] = 0; // Terminate string before CRLF
//Log("req> "); LogLn(htmlline);
//request for websocket handover
bool bFound = (strstr_P(htmlline, PSTR("Sec-WebSocket-Key:")) != NULL);
if (bFound)
{
//Log("Found>");LogLn(htmlline);
hasKey = true;
strtok(htmlline, " ");
strcpy(key, strtok(NULL, " ")); //TODO: should specify max 80 limit
Log("Found> ");LogLn(key);
}
//request for HTTP page
if (strstr_P(htmlline, PSTR("GET / HTTP")) != NULL)
{
LogLn(F("Page Req"));
bReqWebPage=true;
}
counter = 0; // Start saving new header string
}
}
//Log("Got header: ");LogHex((byte*)htmlline,counter);
if (hasKey)
{
LogLn(F("WS Req"));
strcat_P(key, PSTR("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); // Magic Number GUID
Sha1.init();
Sha1.print(key);
uint8_t* hash = Sha1.result();
base64_encode(htmlline, (char*)hash, 20); //reuse htmlline buffer
ethClient.print(F("HTTP/1.1 101 Switching Protocols\r\n"));
ethClient.print(F("Upgrade: websocket\r\n"));
ethClient.print(F("Connection: Upgrade\r\n"));
ethClient.print(F("Sec-WebSocket-Accept: "));
ethClient.print(htmlline); //eg. VoNhf1LMVVTziHWxjiajVem5DB4=
ethClient.print(F("\r\n\r\n"));
//LogLn(F("Connected"));
//Send any display we might have
RKPClass::bScreenHasUpdated = true; //RKPClass::SendDisplayToBrowser();
}
else if (bReqWebPage)
{// Nope, Not a websocket request - send the main webpage
//LogLn(F("WebPageReq"));
SendHTMLSite();
}
else
{
ethClient.println(F("HTTP/1.0 404 File Not Found")); //
ethClient.println(F("Content-Type: text/html"));
ethClient.println(F("Connnection: close"));
ethClient.println();
//delay(1);
ethClient.stop();
}
return;
}
struct Frame {
bool isMasked;
bool isFinal;
byte opcode;
byte mask[4];
byte length;
char data[64+1];
} frame;
byte WebSocket::ReadNext()
{
byte bite = ethClient.read();
//LogHex(bite);
return bite;
}
bool WebSocket::WebSocket_getFrame()
{
// Get opcode
byte bite = ReadNext(); if (bite==0xFF) return false;
frame.opcode = bite & 0xf; // Opcode
frame.isFinal = bite & 0x80; // Final frame?
// Determine length (only accept <= 64 for now)
bite = ReadNext(); if (bite==0xFF) return false;
frame.length = bite & 0x7f; // Length of payload
if (frame.length >= 64)
{//Unlikely to happen
Log(F("Frame Too Big")); LogLn(bite);
return false;
}
// Client should always send mask, but check just to be sure
frame.isMasked = bite & 0x80;
if (frame.isMasked) {
frame.mask[0] = ReadNext();
frame.mask[1] = ReadNext();
frame.mask[2] = ReadNext();
frame.mask[3] = ReadNext();
}
// Get message bytes and unmask them if necessary
int i = 0;
for (; i < frame.length; i++)
{
bite = ReadNext();
if (frame.isMasked)
frame.data[i] = bite ^ frame.mask[i % 4];
else
frame.data[i] = bite;
}
frame.data[i]=0;
// Frame complete!
if (!frame.isFinal)
{ // We don't handle fragments! Close and disconnect.
LogLn(F("Unsurp"));
return false;
}
if (frame.opcode== 0x01)
{// Txt frame
Log(F("Data: ")); //Got Data
LogLn(frame.data);
RKPClass::PushKey(frame.data[0]);
return true;
}
if (frame.opcode== 0x08)
{
// Close frame. Answer with close and terminate tcp connection
LogLn(F("Close")); //Close frame
ethClient.write((uint8_t) 0x08);
return false;
}
// Unexpected. Ignore?
LogLn(F("Ex.")); //Unhandled frame ignored
return false;
}