Skip to content

Commit

Permalink
infinite loop when content-type not provided (#6)
Browse files Browse the repository at this point in the history
Sometime device does not send content-type, it will cause the while loops forever. I've added a fix to handle it
  • Loading branch information
MartinPham authored Feb 20, 2020
1 parent 3289bb4 commit 0517d1a
Showing 1 changed file with 37 additions and 16 deletions.
53 changes: 37 additions & 16 deletions lib/transport/ip/http-event-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const State = {
HEADERS_COMPLETE: 2,
};

const HEADER_SUFFIX = '\r\n\r\n';

class HttpEventParser extends EventEmitter {
/**
* Initialize the HttpEventParser object.
Expand Down Expand Up @@ -52,7 +54,7 @@ class HttpEventParser extends EventEmitter {
break;
}
case State.REQUEST_LINE_COMPLETE: {
const end = this._pending.indexOf('\r\n\r\n');
const end = this._pending.indexOf(HEADER_SUFFIX);
if (end < 0) {
return;
}
Expand All @@ -79,21 +81,40 @@ class HttpEventParser extends EventEmitter {
break;
}
case State.HEADERS_COMPLETE: {
const contentLength = parseInt(this.headers['content-length'], 10);
const toCopy = Math.min(
contentLength - this.body.length,
this._pending.length
);

this.body = Buffer.concat([
this.body,
this._pending.slice(0, toCopy),
]);
this._pending = this._pending.slice(toCopy, this._pending.length);

if (this.body.length === contentLength && this.protocol === 'EVENT') {
this.emit('event', this.body);
this._reset();
if (typeof this.headers['content-length'] !== 'undefined') {
const contentLength = parseInt(this.headers['content-length'], 10);
const toCopy = Math.min(
contentLength - this.body.length,
this._pending.length
);
this.body = Buffer.concat([
this.body,
this._pending.slice(0, toCopy),
]);
this._pending = this._pending.slice(toCopy, this._pending.length);
if (this.body.length === contentLength &&
this.protocol === 'EVENT') {
this.emit('event', this.body);
this._reset();
}
} else if (typeof this.headers['content-type'] !== 'undefined') {
if (this._pending.indexOf(
HEADER_SUFFIX,
this._pending.length - HEADER_SUFFIX.length
) >= 0) {
this.body = this._pending.toString('utf8');
const firstPosition = this.body.indexOf('{');
const lastPosition = this.body.lastIndexOf('}');
this.body = this.body.substring(firstPosition, lastPosition + 1);
this._pending = this._pending.slice(
this.body.length,
this._pending.length
);
if (this.body.length > 0 && this.protocol === 'EVENT') {
this.emit('event', this.body);
this._reset();
}
}
}

break;
Expand Down

0 comments on commit 0517d1a

Please sign in to comment.