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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! STOMP protocol push parser, parses command and headers, not the body.
/// readonly bytes pushed in from the network.
/// Parser treats u8 as char as US-ASCII, we accept utf-8 but all protocol attributes are US-ASCII.
/// Also reads HTTP GET to support upgrading the stream from HTTP to WebSockets
use log::*;
use crate::message::stomp_message::*;
use crate::message::stomp_message::StompCommand;
/// State of the Struct
#[derive(Debug, PartialEq)]
pub enum ParserState {
/// finished reading the whole message
Done(usize),
/// read all the headers now comes the body (value is how much data was read)
Message(usize),
/// awaiting more input
Again,
/// Bombed parsing the command (first line)
InvalidCommand,
/// bombed parsing something else
InvalidMessage,
/// flupped a buffer
BodyFlup,
/// reached max headers
HdrFlup,
}
/// state of the loop
#[derive(Debug, PartialEq)]
enum State {
Start,
Command,
CommandLf,
HdrStart,
HdrName,
HdrValue,
AlmostDone,
MsgRead,
}
/// A push parser, externally a buffer is being filled with the STOMP message and headers as it arrive
/// we process the data as it comes off the stream and save state between chunks of data arriving.
#[derive(Debug)]
pub struct StompParser {
/// count of bytes read parsing the stream, can be > message len since optional whitespace is discarded.
bytes_read: usize,
state: State,
pub message: StompMessage,
cmd_start: usize,
request_line_start: usize,
hdr_name_start: usize,
hdr_name_end: usize,
hdr_value_start: usize,
hdr_value_end: usize,
}
impl StompParser {
pub fn new(session_id: usize) -> StompParser {
let mut m = StompMessage::new(Ownership::Parser);
m.session_id = Some(session_id);
StompParser {
bytes_read: 0,
state: State::Start,
message: m,
cmd_start: 0,
request_line_start: 0,
hdr_name_start: 0,
hdr_name_end: 0,
hdr_value_start: 0,
hdr_value_end: 0,
}
}
/// take ownership of the parsed message
pub fn take_message(&mut self, owner: Ownership) -> StompMessage {
self.bytes_read = 0;
self.state = State::Start;
self.cmd_start = 0;
self.request_line_start = 0;
self.hdr_name_start = 0;
self.hdr_name_end = 0;
self.hdr_value_start = 0;
self.hdr_value_end = 0;
self.message.take(owner)
}
/// reset wiping the message
pub fn reset(&mut self) {
self.bytes_read = 0;
self.state = State::Start;
self.cmd_start = 0;
self.request_line_start = 0;
self.hdr_name_start = 0;
self.hdr_name_end = 0;
self.hdr_value_start = 0;
self.hdr_value_end = 0;
let session_id = self.message.id;
self.message = StompMessage::new(Ownership::Parser);
self.message.session_id = Some(session_id);
}
pub fn bytes_read(&self) -> usize {
self.bytes_read
}
/// Required a complete rewrite from xtomp because rust does not have for loops or p++ and can not index arrays easily
///
/// `buffer` the full buffer we are loading
/// `pos` position in the outer buffer (not the chunk)
/// `chunk` slice of input buffer we are reading
pub fn push(&mut self, buffer: &[u8], mut pos: usize, chunk: &[u8]) -> Result<ParserState, ParserState> {
// debug!("READ chunk '{}'", String::from_utf8_lossy(chunk));
for c in chunk {
self.bytes_read += 1;
//println!("loop {}, {}", *c as char, String::from_utf8_lossy(buffer));
let ch: u8 = *c;
if ch == b'\0' && self.state != State::AlmostDone {
debug!("early frame termination");
return Err(ParserState::InvalidCommand);
}
match self.state {
State::Start => {
if ch == b'\n' || ch == b'\r' {
// TODO if all we got was a heart-beat we should reset buffer pos here
// continue
} else if ch < b'A' || ch > b'Z' {
return Err(ParserState::InvalidCommand);
} else {
self.cmd_start = pos;
self.state = State::Command;
self.message.command = StompCommand::Unknown;
}
}
State::Command => {
// TODO only allow non A-Z for HTTP GET
// if ch == b'\n' || ch == b'\r' {
//
// }
// else if ch < b'A' || ch > b'Z' {
// return Err(ParserState::InvalidCommand);
// }
let c = self.cmd_start;
// amount of command statement read
let cmd_read = pos - c;
let com = &buffer[c..c + cmd_read];
//println!("Reading Command {} cmd_start={} cmd_read={}", ch, self.cmd_start, cmd_read);
if cmd_read == 0 {
// continue
}
else if cmd_read == 1 {
// continue
}
else if cmd_read == 2 {
// continue
}
else if cmd_read == 3 { // ACK, GET
if com.eq(b"ACK") {
self.message.command = StompCommand::Ack;
}
}
else if cmd_read == 4 { // NACK, SEND
if com.eq(b"NACK") {
self.message.command = StompCommand::Nack;
}
if com.eq(b"SEND") {
self.message.command = StompCommand::Send;
}
if com.eq(b"GET ") {
self.message.command = StompCommand::Get;
self.message.message_type = MessageType::Http;
self.request_line_start = pos - 4;
}
}
else if cmd_read == 5 { // BEGIN, ABORT, ERROR, STOMP
if com.eq(b"BEGIN") {
self.message.command = StompCommand::Begin;
}
if com.eq(b"ABORT") {
self.message.command = StompCommand::Abort;
}
if com.eq(b"ERROR") {
self.message.command = StompCommand::Error;
}
if com.eq(b"STOMP") {
self.message.command = StompCommand::Stomp;
}
}
else if cmd_read == 6 { // COMMIT
if com.eq(b"COMMIT") {
self.message.command = StompCommand::Commit;
}
}
else if cmd_read == 7 { // CONNECT, MESSAGE, RECEIPT
if com.eq(b"CONNECT") {
self.message.command = StompCommand::Connect;
}
if com.eq(b"MESSAGE") {
self.message.command = StompCommand::Message;
}
if com.eq(b"RECEIPT") {
self.message.command = StompCommand::Receipt;
}
}
else if cmd_read == 8 { // none
// continue
}
else if cmd_read == 9 { // SUBSCRIBE, CONNECTED
if com.eq(b"SUBSCRIBE") {
self.message.command = StompCommand::Subscribe;
}
if com.eq(b"CONNECTED") {
self.message.command = StompCommand::Connected;
}
}
else if cmd_read == 10 { // DISCONNECT
if com.eq(b"DISCONNECT") {
self.message.command = StompCommand::Disconnect;
}
}
else if cmd_read == 11 { // UNSUBSCRIBE
if com.eq(b"UNSUBSCRIBE") {
self.message.command = StompCommand::Unsubscribe;
}
}
else if cmd_read == 12 {
if StompCommand::Get == self.message.command {
// HTTP GET can be long
} else {
return Err(ParserState::InvalidCommand);
}
} // end command types
match self.is_command_done(ch) {
Ok(state) => {
self.state = state;
self.hdr_name_start = pos;
if StompCommand::Get == self.message.command {
self.request_line_done(buffer, pos);
}
},
Err(ParserState::Again) => {
// continue
},
Err(e) => {
warn!("invalid command '{}'", String::from_utf8_lossy(com));
return Err(e);
}
}
}
State::CommandLf => {
if ch == b'\r' {
// continue;
} else if ch == b'\n' {
self.state = State::HdrStart;
self.hdr_name_start = pos;
// continue;
} else {
return Err(ParserState::InvalidCommand);
}
}
State::HdrStart => {
if ch == b' ' || ch == b'\t' || ch == b'\r' {
// continue (ignore leading whitespace)
} else if ch == b'\n' {
// two LF marks end of headers
match self.message.command {
StompCommand::Message | StompCommand::Send => {
// has a body, return without reading the trailing \0
self.state = State::MsgRead;
return Ok(ParserState::Message(pos + 1));
}
StompCommand::Get => {
// has no trailing \0
self.state = State::MsgRead;
return Ok(ParserState::Message(pos + 1));
}
_ => {
// wait for \0
self.state = State::AlmostDone;
}
}
} else {
self.hdr_name_start = pos;
self.state = State::HdrName;
}
}
State::HdrName => {
if ch == b':' {
self.hdr_name_end = pos;
self.hdr_value_start = pos + 1;
self.state = State::HdrValue;
} else if ch == b'\r' || ch == b'\n' {
return Err(ParserState::InvalidMessage);
}
}
// TODO ignore whitespace between name and value and :
State::HdrValue => {
if ch == b'\r' {
self.hdr_value_end = pos;
// continue
} else if ch == b'\n' {
if self.hdr_value_end == 0 {
self.hdr_value_end = pos;
};
self.header_done(buffer);
self.hdr_name_start = pos - 1;
self.state = State::HdrStart;
}
}
State::AlmostDone => {
if ch == b'\0' {
self.state = State::MsgRead;
debug!("DONE {} {}", pos, self.bytes_read);
return Ok(ParserState::Done(pos + 1));
} else {
return Err(ParserState::InvalidCommand);
}
}
State::MsgRead => {
panic!("unreachable in parser")
}
}
pos = pos + 1;
} // end for
Ok(ParserState::Again)
}
/// return Err(ParserState::Again) until a command is read, command is the first line of the message
fn is_command_done(&self, ch: u8) -> Result<State, ParserState> {
if ch == b'\r' || ch == b'\n' {
// println!("Read a command {:?}", self.message.command);
if StompCommand::Unknown == self.message.command {
return Err(ParserState::InvalidCommand);
}
if ch == b'\r' {
return Ok(State::CommandLf);
}
if ch == b'\n' {
return Ok(State::HdrStart);
}
}
Err(ParserState::Again)
}
/// parsed a header name:value
fn header_done(&mut self, buffer: &[u8]) {
self.message.add_header_clone(
&String::from_utf8_lossy(&buffer[self.hdr_name_start..self.hdr_name_end]),
&String::from_utf8_lossy(&buffer[self.hdr_value_start..self.hdr_value_end]));
self.hdr_name_start = 0;
self.hdr_name_end = 0;
self.hdr_value_start = 0;
self.hdr_value_end = 0;
}
fn request_line_done(&mut self, buffer: &[u8], pos: usize) {
//println!("read request line '{}'", String::from_utf8_lossy(&buffer[self.request_line_start..pos]) );
self.message.add_header_clone(
&String::from("request-line"),
&String::from_utf8_lossy(&buffer[self.request_line_start..pos]));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_happy() {
let mut p = StompParser::new(0);
let buffer = b"ACK\nhdr1:value1\nhdr2:value2\n\n\0";
let mut pos = 0;
let mut end = 10;
let mut chunk = &buffer[pos..end];
match p.push(buffer, pos, chunk) {
Ok(ParserState::Again) => {
if StompCommand::Ack == p.message.command {
println!("parsed ACK");
} else {
panic!("wrong command")
}
println!("p.message.command {:?}", p.message.command);
println!("chunk parsed");
}
Err(_) => {
println!("Parser error {:?}", p);
panic!("parser error");
}
_ => panic!("unexpected state")
};
let read = 10;
pos = end;
end += read;
chunk = &buffer[pos..end];
match p.push(buffer, pos, chunk) {
Ok(ParserState::Again) => println!("chunk parsed"),
Err(_) => panic!("parser error"),
_ => panic!("unexpected state")
};
pos = end;
end = buffer.len();
chunk = &buffer[pos..end];
match p.push(buffer, pos, chunk) {
Ok(ParserState::Done(_)) => println!("all parsed"),
Err(_) => panic!("parser error"),
_ => panic!("unexpected state")
};
println!("Parsed Message {:?}", p.message);
}
#[test]
fn test_happy_login() {
let mut p = StompParser::new(0);
let buffer = b"STOMP\nlogin:xtomp\npasscode:passcode\n\n\0";
match p.push(buffer, 0, buffer) {
Ok(ParserState::Done(38)) => {
if StompCommand::Stomp == p.message.command {}
else { panic!("wrong command"); }
match p.message.get_header("login") {
Some(value) => assert!( value.eq("xtomp")),
None => panic!("missing header")
}
match p.message.get_header("passcode") {
Some(value) => assert!( value.eq("passcode")),
None => panic!("missing header")
}
},
Ok(ParserState::Done(_)) => {
panic!("reporting wrong length")
}
Err(_) => {
println!("Parser error {:?}", p);
panic!("parser error")
},
_ => panic!("unexpected state")
};
}
#[test]
fn test_happy_body() {
let mut p = StompParser::new(0);
let buffer = b"SEND\ndestination:memtop-a\n\nsome text follows\0";
match p.push(buffer, 0, buffer) {
Ok(ParserState::Message(read)) => {
assert_eq!(27, read);
if StompCommand::Send == p.message.command {}
else { panic!("wrong command"); }
match p.message.get_header("destination") {
Some(value) => assert!( value.eq("memtop-a")),
None => panic!("missing header")
}
if State::MsgRead == p.state {}
else { panic!("wrong parser state"); }
}
Err(_) => {
println!("Parser error {:?}", p);
panic!("parser error")
},
_ => panic!("unexpected state")
};
}
#[test]
fn test_telnet_line_endings_login() {
let mut p = StompParser::new(0);
let buffer = b"STOMP\r\nlogin:xtomp\r\npasscode:passcode\r\n\r\n\0";
match p.push(buffer, 0, buffer) {
Ok(ParserState::Done(_)) => {
if StompCommand::Stomp == p.message.command {}
else { panic!("wrong command"); }
match p.message.get_header("login") {
Some(value) => assert!( value.eq("xtomp")),
None => panic!("missing header")
}
match p.message.get_header("passcode") {
Some(value) => assert!( value.eq("passcode")),
None => panic!("missing header")
}
}
Err(_) => {
println!("Parser error {:?}", p);
panic!("parser error")
},
_ => panic!("unexpected state")
};
}
#[test]
fn test_invalid_command() {
let buffer = b"WIBBLE\n\n\0";
if let Err(ParserState::InvalidCommand) = StompParser::new(0).push(buffer, 0, buffer) {
// expected
} else {
panic!("unexpected state")
}
}
#[test]
fn test_non_text_command() {
let buffer = b"*uck*you\n\n\0";
if let Err(ParserState::InvalidCommand) = StompParser::new(0).push(buffer, 0, buffer) {
// expected
} else {
panic!("unexpected state")
}
}
#[test]
fn test_wrong_case_command() {
let buffer = b"stomp\n\n\0";
if let Err(ParserState::InvalidCommand) = StompParser::new(0).push(buffer, 0, buffer) {
// expected
} else {
panic!("unexpected state")
}
}
#[test]
fn test_heart_beats() {
let mut p = StompParser::new(0);
// leading \n ignored
let buffer = b"\n\n\nSTOMP\n\n\0";
if let Ok(_) = p.push(buffer, 0, buffer) {
assert_eq!(StompCommand::Stomp, p.message.command);
} else {
panic!("unexpected state")
}
}
#[test]
fn test_early_zero_termination_in_cmd() {
let buffer = b"STOMP\0";
if let Err(ParserState::InvalidCommand) = StompParser::new(0).push(buffer, 0, buffer) {
// expected
} else {
panic!("unexpected state")
}
}
#[test]
fn test_early_zero_termination_in_hdr_val() {
let buffer = b"STOMP\n\nhdr:value\0";
if let Err(ParserState::InvalidCommand) = StompParser::new(0).push(buffer, 0, buffer) {
// expected
} else {
panic!("unexpected state")
}
}
#[test]
fn test_early_zero_termination_in_hdr_name() {
let buffer = b"STOMP\n\nhdr:value\n\0";
if let Err(ParserState::InvalidCommand) = StompParser::new(0).push(buffer, 0, buffer) {
// expected
} else {
panic!("unexpected state")
}
}
#[test]
fn test_http_get() {
let mut p = StompParser::new(0);
let buffer = b"GET /foo/baa HTTP/1.1\ndestination:memtop-a\n\n";
match p.push(buffer, 0, buffer) {
Ok(ParserState::Message(read)) => {
assert_eq!(44, read);
if StompCommand::Get == p.message.command {}
else { panic!("wrong command"); }
match p.message.get_header("destination") {
Some(value) => assert!( value.eq("memtop-a")),
None => panic!("missing header")
}
if State::MsgRead == p.state {}
else { panic!("wrong parser state"); }
}
Err(_) => {
println!("Parser error {:?}", p);
panic!("parser error")
},
_ => panic!("unexpected state")
};
}
}