Unverified 提交 af15b524 authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi 提交者: GitHub

Worker communication optimization (aka removing netstring dependency) (#644)

上级 500f9178
......@@ -5,7 +5,7 @@ export declare class Channel extends EnhancedEventEmitter {
private readonly _consumerSocket;
private _nextId;
private readonly _sents;
private _recvBuffer?;
private _recvBuffer;
/**
* @private
*/
......
{"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,OAAQ,SAAQ,oBAAoB;IAGhD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAC,CAAS;IAE7B;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,GAAG,EACH,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;QACpB,GAAG,EAAE,MAAM,CAAC;KACZ;IAoIF;;OAEG;IACH,KAAK,IAAI,IAAI;IAmCb;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IA8D1E,OAAO,CAAC,eAAe;CA+DvB"}
\ No newline at end of file
{"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAqB9D,qBAAa,OAAQ,SAAQ,oBAAoB;IAGhD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAmB;IAEtC;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,GAAG,EACH,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;QACpB,GAAG,EAAE,MAAM,CAAC;KACZ;IAiIF;;OAEG;IACH,KAAK,IAAI,IAAI;IAmCb;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAgE1E,OAAO,CAAC,eAAe;CA+DvB"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// @ts-ignore
const netstring = require("netstring");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const errors_1 = require("./errors");
const os = require("os");
const littleEndian = os.endianness() == 'LE';
const logger = new Logger_1.Logger('Channel');
// netstring length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313;
const NS_PAYLOAD_MAX_LEN = 4194304;
// Binary length for a 4194304 bytes payload.
const MESSAGE_MAX_LEN = 4194308;
const PAYLOAD_MAX_LEN = 4194304;
class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
/**
* @private
......@@ -21,77 +21,76 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
this._nextId = 0;
// Map of pending sent requests.
this._sents = new Map();
// Buffer for reading messages from the worker.
this._recvBuffer = Buffer.alloc(0);
logger.debug('constructor()');
this._producerSocket = producerSocket;
this._consumerSocket = consumerSocket;
// Read Channel responses/notifications from the worker.
this._consumerSocket.on('data', (buffer) => {
if (!this._recvBuffer) {
if (!this._recvBuffer.length) {
this._recvBuffer = buffer;
}
else {
this._recvBuffer = Buffer.concat([this._recvBuffer, buffer], this._recvBuffer.length + buffer.length);
}
if (this._recvBuffer.length > NS_PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data into it');
if (this._recvBuffer.length > PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit.
this._recvBuffer = undefined;
this._recvBuffer = Buffer.alloc(0);
return;
}
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition
{
let nsPayload;
try {
nsPayload = netstring.nsPayload(this._recvBuffer);
const readLen = this._recvBuffer.length - msgStart;
if (readLen < 4) {
// Incomplete data.
break;
}
catch (error) {
logger.error('invalid netstring data received from the worker process: %s', String(error));
// Reset the buffer and exit.
this._recvBuffer = undefined;
return;
const dataView = new DataView(this._recvBuffer.buffer, this._recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
if (readLen < 4 + msgLen) {
// Incomplete data.
break;
}
// Incomplete netstring message.
if (nsPayload === -1)
return;
const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
msgStart += 4 + msgLen;
try {
// We can receive JSON messages (Channel messages) or log strings.
switch (nsPayload[0]) {
// 123 = '{' (a Channel JSON messsage).
switch (payload[0]) {
// 123 = '{' (a Channel JSON message).
case 123:
this._processMessage(JSON.parse(nsPayload.toString('utf8')));
this._processMessage(JSON.parse(payload.toString('utf8')));
break;
// 68 = 'D' (a debug log).
case 68:
logger.debug(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`);
logger.debug(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break;
// 87 = 'W' (a warn log).
case 87:
logger.warn(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`);
logger.warn(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break;
// 69 = 'E' (an error log).
case 69:
logger.error(`[pid:${pid} ${nsPayload.toString('utf8', 1)}`);
logger.error(`[pid:${pid} ${payload.toString('utf8', 1)}`);
break;
// 88 = 'X' (a dump log).
case 88:
// eslint-disable-next-line no-console
console.log(nsPayload.toString('utf8', 1));
console.log(payload.toString('utf8', 1));
break;
default:
// eslint-disable-next-line no-console
console.warn(`worker[pid:${pid}] unexpected data: %s`, nsPayload.toString('utf8', 1));
console.warn(`worker[pid:${pid}] unexpected data: %s`, payload.toString('utf8', 1));
}
}
catch (error) {
logger.error('received invalid message from the worker process: %s', String(error));
}
// Remove the read payload from the buffer.
this._recvBuffer =
this._recvBuffer.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length) {
this._recvBuffer = undefined;
return;
}
}
if (msgStart != 0) {
this._recvBuffer = this._recvBuffer.slice(msgStart);
}
});
this._consumerSocket.on('end', () => (logger.debug('Consumer Channel ended by the worker process')));
......@@ -141,11 +140,12 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
if (this._closed)
throw new errors_1.InvalidStateError('Channel closed');
const request = { id, method, internal, data };
const ns = netstring.nsWrite(JSON.stringify(request));
if (Buffer.byteLength(ns) > NS_MESSAGE_MAX_LEN)
const payload = JSON.stringify(request);
if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
// This may throw if closed or remote side ended.
this._producerSocket.write(ns);
this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) => {
const timeout = 1000 * (15 + (0.1 * this._sents.size));
const sent = {
......
......@@ -6,7 +6,7 @@ export declare class PayloadChannel extends EnhancedEventEmitter {
private readonly _consumerSocket;
private _nextId;
private readonly _sents;
private _recvBuffer?;
private _recvBuffer;
private _ongoingNotification?;
/**
* @private
......
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,cAAe,SAAQ,oBAAoB;IAGvD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAC,CAAS;IAG7B,OAAO,CAAC,oBAAoB,CAAC,CAAkD;IAE/E;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;KACpB;IAyFF;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Bb;;OAEG;IACH,MAAM,CACL,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,GAAG,SAAS,EACrB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IAyCP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAkExC,OAAO,CAAC,YAAY;CA8FpB"}
\ No newline at end of file
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAqB9D,qBAAa,cAAe,SAAQ,oBAAoB;IAGvD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAmB;IAGtC,OAAO,CAAC,oBAAoB,CAAC,CAAkD;IAE/E;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;KACpB;IAsFF;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Bb;;OAEG;IACH,MAAM,CACL,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,GAAG,SAAS,EACrB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IA2CP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAoExC,OAAO,CAAC,YAAY;CA8FpB"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// @ts-ignore
const netstring = require("netstring");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const errors_1 = require("./errors");
const os = require("os");
const littleEndian = os.endianness() == 'LE';
const logger = new Logger_1.Logger('PayloadChannel');
// netstring length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313;
const NS_PAYLOAD_MAX_LEN = 4194304;
// binary length for a 4194304 bytes payload.
const MESSAGE_MAX_LEN = 4194308;
const PAYLOAD_MAX_LEN = 4194304;
class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
/**
* @private
......@@ -21,46 +21,45 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
this._nextId = 0;
// Map of pending sent requests.
this._sents = new Map();
// Buffer for reading messages from the worker.
this._recvBuffer = Buffer.alloc(0);
logger.debug('constructor()');
this._producerSocket = producerSocket;
this._consumerSocket = consumerSocket;
// Read PayloadChannel notifications from the worker.
this._consumerSocket.on('data', (buffer) => {
if (!this._recvBuffer) {
if (!this._recvBuffer.length) {
this._recvBuffer = buffer;
}
else {
this._recvBuffer = Buffer.concat([this._recvBuffer, buffer], this._recvBuffer.length + buffer.length);
}
if (this._recvBuffer.length > NS_PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data into it');
if (this._recvBuffer.length > PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit.
this._recvBuffer = undefined;
this._recvBuffer = Buffer.alloc(0);
return;
}
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition
{
let nsPayload;
try {
nsPayload = netstring.nsPayload(this._recvBuffer);
const readLen = this._recvBuffer.length - msgStart;
if (readLen < 4) {
// Incomplete data.
break;
}
catch (error) {
logger.error('invalid netstring data received from the worker process: %s', String(error));
// Reset the buffer and exit.
this._recvBuffer = undefined;
return;
}
// Incomplete netstring message.
if (nsPayload === -1)
return;
this._processData(nsPayload);
// Remove the read payload from the buffer.
this._recvBuffer =
this._recvBuffer.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length) {
this._recvBuffer = undefined;
return;
const dataView = new DataView(this._recvBuffer.buffer, this._recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
if (readLen < 4 + msgLen) {
// Incomplete data.
break;
}
const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
msgStart += 4 + msgLen;
this._processData(payload);
}
if (msgStart != 0) {
this._recvBuffer = this._recvBuffer.slice(msgStart);
}
});
this._consumerSocket.on('end', () => (logger.debug('Consumer PayloadChannel ended by the worker process')));
......@@ -103,16 +102,15 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('notify() [event:%s]', event);
if (this._closed)
throw new errors_1.InvalidStateError('PayloadChannel closed');
const notification = { event, internal, data };
const ns1 = netstring.nsWrite(JSON.stringify(notification));
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
const notification = JSON.stringify({ event, internal, data });
if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN)
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
try {
// This may throw if closed or remote side ended.
this._producerSocket.write(ns1);
this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(notification)).buffer));
this._producerSocket.write(notification);
}
catch (error) {
logger.warn('notify() | sending notification failed: %s', String(error));
......@@ -120,7 +118,8 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
}
try {
// This may throw if closed or remote side ended.
this._producerSocket.write(ns2);
this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
}
catch (error) {
logger.warn('notify() | sending payload failed: %s', String(error));
......@@ -136,16 +135,16 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('request() [method:%s, id:%s]', method, id);
if (this._closed)
throw new errors_1.InvalidStateError('Channel closed');
const request = { id, method, internal, data };
const ns1 = netstring.nsWrite(JSON.stringify(request));
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
const request = JSON.stringify({ id, method, internal, data });
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN)
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended.
this._producerSocket.write(ns1);
this._producerSocket.write(ns2);
this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this._producerSocket.write(request);
this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) => {
const timeout = 1000 * (15 + (0.1 * this._sents.size));
const sent = {
......
......@@ -52,7 +52,6 @@
"awaitqueue": "^2.3.3",
"debug": "^4.3.2",
"h264-profile-level-id": "^1.0.1",
"netstring": "^0.3.0",
"random-number": "^0.0.9",
"supports-color": "^9.0.2",
"uuid": "^8.3.2"
......
# Changelog
# Unreleased
* Fix for receiving data over payload channel
# 0.8.5
* Fix types for `round_trip_time` and `bitrate_by_layer` fields `ProducerStat` and `ConsumerStat`
......
......@@ -69,3 +69,11 @@ actix = "0.12.0"
actix-web = "4.0.0-beta.8"
actix-web-actors = "4.0.0-beta.6"
env_logger = "0.9.0"
[dev-dependencies.criterion]
version = "0.3.5"
features = ["async_futures"]
[[bench]]
name = "direct_data"
harness = false
use bytes::Bytes;
use criterion::async_executor::FuturesExecutor;
use criterion::{criterion_group, criterion_main, Criterion};
use futures_lite::StreamExt;
use mediasoup::prelude::*;
async fn create_data_producer_consumer_pair(
) -> Result<(DataProducer, DataConsumer), Box<dyn std::error::Error>> {
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await?;
let router = worker.create_router(RouterOptions::default()).await?;
let direct_transport = router
.create_direct_transport(DirectTransportOptions::default())
.await?;
let data_producer = direct_transport
.produce_data(DataProducerOptions::new_direct())
.await?;
let data_consumer = direct_transport
.consume_data(DataConsumerOptions::new_direct(data_producer.id()))
.await?;
Ok((data_producer, data_consumer))
}
pub fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("direct_data");
let data = Bytes::from(
std::iter::repeat_with(|| fastrand::u8(..))
.take(512)
.collect::<Vec<u8>>(),
);
{
let (data_producer, _data_consumer) = futures_lite::future::block_on(async {
create_data_producer_consumer_pair().await.unwrap()
});
let direct_data_producer =
if let DataProducer::Direct(direct_data_producer) = data_producer.clone() {
direct_data_producer
} else {
unreachable!()
};
group.bench_with_input("send", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async {
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.await;
})
});
}
{
let (data_producer, data_consumer) = futures_lite::future::block_on(async {
create_data_producer_consumer_pair().await.unwrap()
});
let direct_data_producer =
if let DataProducer::Direct(direct_data_producer) = data_producer.clone() {
direct_data_producer
} else {
unreachable!()
};
group.bench_with_input("recv", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async {
let (sender, mut receiver) = async_channel::unbounded::<()>();
let _handler_id = data_consumer.on_message(move |_message| {
let _ = sender.try_send(());
});
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.await;
let _ = receiver.next().await;
})
});
}
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
......@@ -5,7 +5,7 @@ use async_executor::Executor;
use async_fs::File;
use bytes::{BufMut, Bytes, BytesMut};
use futures_lite::io::BufReader;
use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
use futures_lite::{future, AsyncReadExt, AsyncWriteExt};
use log::{debug, trace, warn};
use lru::LruCache;
use parking_lot::Mutex;
......@@ -14,7 +14,6 @@ use serde_json::Value;
use std::collections::HashMap;
use std::fmt::Debug;
use std::io;
use std::io::Write;
use std::sync::{Arc, Weak};
use std::time::Duration;
......@@ -148,7 +147,7 @@ impl Channel {
executor
.spawn(async move {
let mut len_bytes = Vec::new();
let mut len_bytes = [0u8; 4];
let mut bytes = Vec::new();
let mut reader = BufReader::new(reader);
// This this contain cache of targets that are known to not have buffering, so
......@@ -157,14 +156,8 @@ impl Channel {
LruCache::<SubscriptionTarget, ()>::new(1000);
loop {
let read_bytes = reader.read_until(b':', &mut len_bytes).await?;
if read_bytes == 0 {
// EOF
break;
}
let length = String::from_utf8_lossy(&len_bytes[..(read_bytes - 1)])
.parse::<usize>()
.unwrap();
reader.read_exact(&mut len_bytes).await?;
let length = u32::from_ne_bytes(len_bytes) as usize;
if length > NS_PAYLOAD_MAX_LEN {
warn!(
......@@ -173,13 +166,11 @@ impl Channel {
);
}
len_bytes.clear();
if bytes.len() < length + 1 {
if bytes.len() < length {
// Increase bytes size if/when needed
bytes.resize(length + 1, 0);
bytes.resize(length, 0);
}
// +1 because of netstring `,` at the very end
reader.read_exact(&mut bytes[..=length]).await?;
reader.read_exact(&mut bytes[..length]).await?;
trace!(
"received raw message: {}",
......@@ -273,13 +264,11 @@ impl Channel {
executor
.spawn(async move {
let mut len = Vec::new();
while let Ok(message) = receiver.recv().await {
len.clear();
write!(&mut len, "{}:", message.len()).unwrap();
writer.write_all(&len).await?;
writer
.write_all(&(message.len() as u32).to_ne_bytes())
.await?;
writer.write_all(&message).await?;
writer.write_all(&[b',']).await?;
}
io::Result::Ok(())
......
......@@ -5,7 +5,7 @@ use async_executor::Executor;
use async_fs::File;
use bytes::{BufMut, Bytes, BytesMut};
use futures_lite::io::BufReader;
use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
use futures_lite::{future, AsyncReadExt, AsyncWriteExt};
use log::{debug, error, trace, warn};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
......@@ -13,7 +13,6 @@ use serde_json::Value;
use std::collections::HashMap;
use std::fmt::Debug;
use std::io;
use std::io::Write;
use std::sync::{Arc, Weak};
use std::time::Duration;
use thiserror::Error;
......@@ -122,19 +121,13 @@ impl PayloadChannel {
executor
.spawn(async move {
let mut len_bytes = Vec::new();
let mut len_bytes = [0u8; 4];
let mut bytes = Vec::new();
let mut reader = BufReader::new(reader);
loop {
let read_bytes = reader.read_until(b':', &mut len_bytes).await?;
if read_bytes == 0 {
// EOF
break;
}
let length = String::from_utf8_lossy(&len_bytes[..(read_bytes - 1)])
.parse::<usize>()
.unwrap();
reader.read_exact(&mut len_bytes).await?;
let length = u32::from_ne_bytes(len_bytes) as usize;
if length > NS_PAYLOAD_MAX_LEN {
warn!(
......@@ -143,13 +136,11 @@ impl PayloadChannel {
);
}
len_bytes.clear();
if bytes.len() < length + 1 {
if bytes.len() < length {
// Increase bytes size if/when needed
bytes.resize(length + 1, 0);
bytes.resize(length, 0);
}
// +1 because of netstring `,` at the very end
reader.read_exact(&mut bytes[..=length]).await?;
reader.read_exact(&mut bytes[..length]).await?;
trace!(
"received raw message: {}",
......@@ -197,15 +188,8 @@ impl PayloadChannel {
})
});
let read_bytes = reader.read_until(b':', &mut len_bytes).await?;
if read_bytes == 0 {
// EOF
break;
}
let length =
String::from_utf8_lossy(&len_bytes[..(read_bytes - 1)])
.parse::<usize>()
.unwrap();
reader.read_exact(&mut len_bytes).await?;
let length = u32::from_ne_bytes(len_bytes) as usize;
if length > NS_PAYLOAD_MAX_LEN {
warn!(
......@@ -214,9 +198,11 @@ impl PayloadChannel {
);
}
len_bytes.clear();
// +1 because of netstring `,` at the very end
reader.read_exact(&mut bytes[..=length]).await?;
if bytes.len() < length {
// Increase bytes size if/when needed
bytes.resize(length, 0);
}
reader.read_exact(&mut bytes[..length]).await?;
trace!("received notification payload of {} bytes", length);
......@@ -259,19 +245,16 @@ impl PayloadChannel {
executor
.spawn(async move {
let mut len = Vec::new();
while let Ok(message) = receiver.recv().await {
len.clear();
write!(&mut len, "{}:", message.message.len()).unwrap();
writer.write_all(&len).await?;
writer
.write_all(&(message.message.len() as u32).to_ne_bytes())
.await?;
writer.write_all(&message.message).await?;
writer.write_all(&[b',']).await?;
len.clear();
write!(&mut len, "{}:", message.payload.len()).unwrap();
writer.write_all(&len).await?;
writer
.write_all(&(message.payload.len() as u32).to_ne_bytes())
.await?;
writer.write_all(&message.payload).await?;
writer.write_all(&[b',']).await?;
}
io::Result::Ok(())
......
import * as os from 'os';
import { Duplex } from 'stream';
// @ts-ignore
import * as netstring from 'netstring';
import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { InvalidStateError } from './errors';
const littleEndian = os.endianness() == 'LE';
const logger = new Logger('Channel');
type Sent =
......@@ -17,9 +17,9 @@ type Sent =
close: () => void;
}
// netstring length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313;
const NS_PAYLOAD_MAX_LEN = 4194304;
// Binary length for a 4194304 bytes payload.
const MESSAGE_MAX_LEN = 4194308;
const PAYLOAD_MAX_LEN = 4194304;
export class Channel extends EnhancedEventEmitter
{
......@@ -39,7 +39,7 @@ export class Channel extends EnhancedEventEmitter
private readonly _sents: Map<number, Sent> = new Map();
// Buffer for reading messages from the worker.
private _recvBuffer?: Buffer;
private _recvBuffer = Buffer.alloc(0);
/**
* @private
......@@ -66,7 +66,7 @@ export class Channel extends EnhancedEventEmitter
// Read Channel responses/notifications from the worker.
this._consumerSocket.on('data', (buffer: Buffer) =>
{
if (!this._recvBuffer)
if (!this._recvBuffer.length)
{
this._recvBuffer = buffer;
}
......@@ -77,76 +77,79 @@ export class Channel extends EnhancedEventEmitter
this._recvBuffer.length + buffer.length);
}
if (this._recvBuffer!.length > NS_PAYLOAD_MAX_LEN)
if (this._recvBuffer.length > PAYLOAD_MAX_LEN)
{
logger.error('receiving buffer is full, discarding all data into it');
logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit.
this._recvBuffer = undefined;
this._recvBuffer = Buffer.alloc(0);
return;
}
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition
{
let nsPayload;
const readLen = this._recvBuffer.length - msgStart;
try
if (readLen < 4)
{
nsPayload = netstring.nsPayload(this._recvBuffer);
// Incomplete data.
break;
}
catch (error)
{
logger.error(
'invalid netstring data received from the worker process: %s',
String(error));
// Reset the buffer and exit.
this._recvBuffer = undefined;
const dataView = new DataView(
this._recvBuffer.buffer,
this._recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
return;
if (readLen < 4 + msgLen)
{
// Incomplete data.
break;
}
// Incomplete netstring message.
if (nsPayload === -1)
return;
const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
msgStart += 4 + msgLen;
try
{
// We can receive JSON messages (Channel messages) or log strings.
switch (nsPayload[0])
switch (payload[0])
{
// 123 = '{' (a Channel JSON messsage).
// 123 = '{' (a Channel JSON message).
case 123:
this._processMessage(JSON.parse(nsPayload.toString('utf8')));
this._processMessage(JSON.parse(payload.toString('utf8')));
break;
// 68 = 'D' (a debug log).
case 68:
logger.debug(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`);
logger.debug(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break;
// 87 = 'W' (a warn log).
case 87:
logger.warn(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`);
logger.warn(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break;
// 69 = 'E' (an error log).
case 69:
logger.error(`[pid:${pid} ${nsPayload.toString('utf8', 1)}`);
logger.error(`[pid:${pid} ${payload.toString('utf8', 1)}`);
break;
// 88 = 'X' (a dump log).
case 88:
// eslint-disable-next-line no-console
console.log(nsPayload.toString('utf8', 1));
console.log(payload.toString('utf8', 1));
break;
default:
// eslint-disable-next-line no-console
console.warn(
`worker[pid:${pid}] unexpected data: %s`,
nsPayload.toString('utf8', 1));
payload.toString('utf8', 1));
}
}
catch (error)
......@@ -155,17 +158,11 @@ export class Channel extends EnhancedEventEmitter
'received invalid message from the worker process: %s',
String(error));
}
}
// Remove the read payload from the buffer.
this._recvBuffer =
this._recvBuffer!.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length)
{
this._recvBuffer = undefined;
return;
}
if (msgStart != 0)
{
this._recvBuffer = this._recvBuffer.slice(msgStart);
}
});
......@@ -239,13 +236,15 @@ export class Channel extends EnhancedEventEmitter
throw new InvalidStateError('Channel closed');
const request = { id, method, internal, data };
const ns = netstring.nsWrite(JSON.stringify(request));
const payload = JSON.stringify(request);
if (Buffer.byteLength(ns) > NS_MESSAGE_MAX_LEN)
if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
// This may throw if closed or remote side ended.
this._producerSocket.write(ns);
this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) =>
{
......
import * as os from 'os';
import { Duplex } from 'stream';
// @ts-ignore
import * as netstring from 'netstring';
import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { InvalidStateError } from './errors';
const littleEndian = os.endianness() == 'LE';
const logger = new Logger('PayloadChannel');
type Sent =
......@@ -17,9 +17,9 @@ type Sent =
close: () => void;
}
// netstring length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313;
const NS_PAYLOAD_MAX_LEN = 4194304;
// Binary length for a 4194304 bytes payload.
const MESSAGE_MAX_LEN = 4194308;
const PAYLOAD_MAX_LEN = 4194304;
export class PayloadChannel extends EnhancedEventEmitter
{
......@@ -39,7 +39,7 @@ export class PayloadChannel extends EnhancedEventEmitter
private readonly _sents: Map<number, Sent> = new Map();
// Buffer for reading messages from the worker.
private _recvBuffer?: Buffer;
private _recvBuffer = Buffer.alloc(0);
// Ongoing notification (waiting for its payload).
private _ongoingNotification?: { targetId: string; event: string; data?: any };
......@@ -67,7 +67,7 @@ export class PayloadChannel extends EnhancedEventEmitter
// Read PayloadChannel notifications from the worker.
this._consumerSocket.on('data', (buffer: Buffer) =>
{
if (!this._recvBuffer)
if (!this._recvBuffer.length)
{
this._recvBuffer = buffer;
}
......@@ -78,52 +78,49 @@ export class PayloadChannel extends EnhancedEventEmitter
this._recvBuffer.length + buffer.length);
}
if (this._recvBuffer!.length > NS_PAYLOAD_MAX_LEN)
if (this._recvBuffer.length > PAYLOAD_MAX_LEN)
{
logger.error('receiving buffer is full, discarding all data into it');
logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit.
this._recvBuffer = undefined;
this._recvBuffer = Buffer.alloc(0);
return;
}
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition
{
let nsPayload;
const readLen = this._recvBuffer.length - msgStart;
try
if (readLen < 4)
{
nsPayload = netstring.nsPayload(this._recvBuffer);
// Incomplete data.
break;
}
catch (error)
{
logger.error(
'invalid netstring data received from the worker process: %s',
String(error));
// Reset the buffer and exit.
this._recvBuffer = undefined;
const dataView = new DataView(
this._recvBuffer.buffer,
this._recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
return;
if (readLen < 4 + msgLen)
{
// Incomplete data.
break;
}
// Incomplete netstring message.
if (nsPayload === -1)
return;
this._processData(nsPayload);
const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
// Remove the read payload from the buffer.
this._recvBuffer =
this._recvBuffer!.slice(netstring.nsLength(this._recvBuffer));
msgStart += 4 + msgLen;
if (!this._recvBuffer.length)
{
this._recvBuffer = undefined;
this._processData(payload);
}
return;
}
if (msgStart != 0)
{
this._recvBuffer = this._recvBuffer.slice(msgStart);
}
});
......@@ -191,19 +188,19 @@ export class PayloadChannel extends EnhancedEventEmitter
if (this._closed)
throw new InvalidStateError('PayloadChannel closed');
const notification = { event, internal, data };
const ns1 = netstring.nsWrite(JSON.stringify(notification));
const ns2 = netstring.nsWrite(payload);
const notification = JSON.stringify({ event, internal, data });
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN)
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
try
{
// This may throw if closed or remote side ended.
this._producerSocket.write(ns1);
this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(notification)).buffer));
this._producerSocket.write(notification);
}
catch (error)
{
......@@ -215,7 +212,9 @@ export class PayloadChannel extends EnhancedEventEmitter
try
{
// This may throw if closed or remote side ended.
this._producerSocket.write(ns2);
this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
}
catch (error)
{
......@@ -243,18 +242,20 @@ export class PayloadChannel extends EnhancedEventEmitter
if (this._closed)
throw new InvalidStateError('Channel closed');
const request = { id, method, internal, data };
const ns1 = netstring.nsWrite(JSON.stringify(request));
const ns2 = netstring.nsWrite(payload);
const request = JSON.stringify({ id, method, internal, data });
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN)
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended.
this._producerSocket.write(ns1);
this._producerSocket.write(ns2);
this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this._producerSocket.write(request);
this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) =>
{
......
......@@ -54,7 +54,7 @@ IncludeCategories:
Priority: 3
- Regex: '"*"'
Priority: 2
- Regex: '^<(json|netstring|uv|openssl|srtp|usrsctp|libwebrtc)(.|/)'
- Regex: '^<(json|uv|openssl|srtp|usrsctp|libwebrtc)(.|/)'
Priority: 4
- Regex: '<*>'
Priority: 5
......
......@@ -19,7 +19,6 @@ include = [
"/deps/libuv",
"!/deps/libuv/libuv/{docs,img,m4,test,ChangeLog}",
"/deps/libwebrtc",
"/deps/netstring",
"/deps/openssl",
"!/deps/openssl/openssl/{apps,demos,docs,fuzz,test,tools,CHANGES}",
"/deps/usrsctp",
......
......@@ -95,7 +95,6 @@ fn main() {
}
for file in &[
"libnetstring.a",
"libuv.a",
"libopenssl.a",
"libsrtp.a",
......@@ -133,7 +132,6 @@ fn main() {
}
}
println!("cargo:rustc-link-lib=static=netstring");
println!("cargo:rustc-link-lib=static=uv");
println!("cargo:rustc-link-lib=static=openssl");
println!("cargo:rustc-link-lib=static=srtp");
......
Netstring parsing
=================
A [netstring](http://en.wikipedia.org/wiki/Netstring) is a way of encoding a sequence of bytes for transmission over a network, or for serialization. They're very easy to work with. They encode the data's length, and can be concatenated trivially. The format was [defined by D. J. Bernstein](http://cr.yp.to/proto/netstrings.txt) and is used in various software. Examples of netstrings:
"12:hello, world!,"
"3:foo,"
"0:,"
To specify a list of strings, just concatenate the netstrings. The list ["hey", "everyone"] can be encoded as
"3:hey,8:everyone,"
This is some code in C for netstring serialization and deserialization. It checks netstrings for validity when parsing them, and guards against malicious input. It's also fast.
Basic API
---------
All the code is in `netstring.c` and `netstring.h`, and these have no external dependencies. To use them, just include them in your application. Include `netstring.h` and link with the C code.
**Parsing netstrings**
To parse a netstring, use `netstring_read()`.
int netstring_read(char *buffer, size_t buffer_length,
char **netstring_start, size_t *netstring_length);
Reads a netstring from a `buffer` of length `buffer_length`. Writes to
`netstring_start` a pointer to the beginning of the string in the
buffer, and to `netstring_length` the length of the string. Does not
allocate any memory. If it reads successfully, then it returns 0. If
there is an error, then the return value will be negative. The error
values are:
NETSTRING_ERROR_TOO_LONG More than 999999999 bytes in a field
NETSTRING_ERROR_NO_COLON No colon was found after the number
NETSTRING_ERROR_TOO_SHORT Number of bytes greater than buffer length
NETSTRING_ERROR_NO_COMMA No comma was found at the end
NETSTRING_ERROR_LEADING_ZERO Leading zeros are not allowed
NETSTRING_ERROR_NO_LENGTH Length not given at start of netstring
If you're sending messages with more than 999999999 bytes -- about 2
GB -- then you probably should not be doing so in the form of a single
netstring. This restriction is in place partially to protect from
malicious or erroneous input, and partly to be compatible with
D. J. Bernstein's reference implementation.
**Creating netstrings**
To create a netstring, there are a few ways to do it. You could do something really simple like this example from [the spec](http://cr.yp.to/proto/netstrings.txt):
if (printf("%lu:", len) < 0) barf();
if (fwrite(buf, 1, len, stdout) < len) barf();
if (putchar(',') < 0) barf();
This code provides a convenience function for creating a new netstring:
size_t netstring_encode_new(char **netstring, char *data, size_t len);
This allocates and creates a netstring containing the first `len` bytes of `data`. This must be manually freed by the client. If `len` is 0 then no data will be read from `data`, and it may be null.
Contributing
------------
All this code is Public Domain. If you want to contribute, you can send bug reports, or fork the project on GitHub. Contributions are welcomed with open arms.
\ No newline at end of file
CFLAGS = -O2 -Wall
LDFLAGS= -lm
.PHONY: test clean
all: testsuite
testsuite: testsuite.c netstring.o
test: testsuite
./testsuite
clean:
rm -f *.o testsuite
/* Streaming API for netstrings. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include "netstring.h"
/* Reads a netstring from a `buffer` of length `buffer_length`. Writes
to `netstring_start` a pointer to the beginning of the string in
the buffer, and to `netstring_length` the length of the
string. Does not allocate any memory. If it reads successfully,
then it returns 0. If there is an error, then the return value will
be negative. The error values are:
NETSTRING_ERROR_TOO_LONG More than 999999999 bytes in a field
NETSTRING_ERROR_NO_COLON No colon was found after the number
NETSTRING_ERROR_TOO_SHORT Number of bytes greater than buffer length
NETSTRING_ERROR_NO_COMMA No comma was found at the end
NETSTRING_ERROR_LEADING_ZERO Leading zeros are not allowed
NETSTRING_ERROR_NO_LENGTH Length not given at start of netstring
If you're sending messages with more than 999999999 bytes -- about
2 GB -- then you probably should not be doing so in the form of a
single netstring. This restriction is in place partially to protect
from malicious or erroneous input, and partly to be compatible with
D. J. Bernstein's reference implementation.
Example:
if (netstring_read("3:foo,", 6, &str, &len) < 0) explode_and_die();
*/
int netstring_read(char *buffer, size_t buffer_length,
char **netstring_start, size_t *netstring_length) {
int i;
size_t len = 0;
/* Write default values for outputs */
*netstring_start = NULL; *netstring_length = 0;
/* Make sure buffer is big enough. Minimum size is 3. */
if (buffer_length < 3) return NETSTRING_ERROR_TOO_SHORT;
/* No leading zeros allowed! */
if (buffer[0] == '0' && isdigit(buffer[1]))
return NETSTRING_ERROR_LEADING_ZERO;
/* The netstring must start with a number */
if (!isdigit(buffer[0])) return NETSTRING_ERROR_NO_LENGTH;
/* Read the number of bytes */
for (i = 0; i < buffer_length && isdigit(buffer[i]); i++) {
/* Error if more than 9 digits */
if (i >= 9) return NETSTRING_ERROR_TOO_LONG;
/* Accumulate each digit, assuming ASCII. */
len = len*10 + (buffer[i] - '0');
}
/* Check buffer length once and for all. Specifically, we make sure
that the buffer is longer than the number we've read, the length
of the string itself, and the colon and comma. */
if (i + len + 1 >= buffer_length) return NETSTRING_ERROR_TOO_SHORT;
/* Read the colon */
if (buffer[i++] != ':') return NETSTRING_ERROR_NO_COLON;
/* Test for the trailing comma, and set the return values */
if (buffer[i + len] != ',') return NETSTRING_ERROR_NO_COMMA;
*netstring_start = &buffer[i]; *netstring_length = len;
return 0;
}
/* Return the length, in ASCII characters, of a netstring containing
`data_length` bytes. */
size_t netstring_buffer_size(size_t data_length) {
if (data_length == 0) return 3;
return (size_t)ceil(log10((double)data_length + 1)) + data_length + 2;
}
/* Allocate and create a netstring containing the first `len` bytes of
`data`. This must be manually freed by the client. If `len` is 0
then no data will be read from `data`, and it may be NULL. */
size_t netstring_encode_new(char **netstring, char *data, size_t len) {
char *ns;
size_t num_len = 1;
if (len == 0) {
ns = malloc(3);
ns[0] = '0';
ns[1] = ':';
ns[2] = ',';
} else {
num_len = (size_t)ceil(log10((double)len + 1));
ns = malloc(num_len + len + 2);
sprintf(ns, "%lu:", (unsigned long)len);
memcpy(ns + num_len + 1, data, len);
ns[num_len + len + 1] = ',';
}
*netstring = ns;
return num_len + len + 2;
}
#ifndef __NETSTRING_STREAM_H
#define __NETSTRING_STREAM_H
#include <string.h>
int netstring_read(char *buffer, size_t buffer_length,
char **netstring_start, size_t *netstring_length);
size_t netstring_buffer_size(size_t data_length);
size_t netstring_encode_new(char **netstring, char *data, size_t len);
/* Errors that can occur during netstring parsing */
#define NETSTRING_ERROR_TOO_LONG -1
#define NETSTRING_ERROR_NO_COLON -2
#define NETSTRING_ERROR_TOO_SHORT -3
#define NETSTRING_ERROR_NO_COMMA -4
#define NETSTRING_ERROR_LEADING_ZERO -5
#define NETSTRING_ERROR_NO_LENGTH -6
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "netstring.h"
/* Good examples */
char ex1[] = "12:hello world!,";
char ex2[] = "3:foo,0:,3:bar,";
/* Bad examples */
char ex3[] = "12:hello world! "; /* No comma */
char ex4[] = "15:hello world!,"; /* Too short */
char ex5[] = "03:foo,"; /* Leading zeros are forbidden */
char ex6[] = "999999999999999:haha lol,"; /* Too long */
char ex7[] = "3fool,"; /* No colon */
char ex8[] = "what's up"; /* No number or colon */
char ex9[] = ":what's up"; /* No number */
void test_netstring_read(void) {
char *netstring;
size_t netstring_len;
int retval;
/* ex1: hello world */
retval = netstring_read(ex1, strlen(ex1), &netstring, &netstring_len);
assert(netstring_len == 12); assert(strncmp(netstring, "hello world!", 12) == 0);
assert(retval == 0);
/* ex2: three netstrings, concatenated. */
retval = netstring_read(ex2, strlen(ex2), &netstring, &netstring_len);
assert(netstring_len == 3); assert(strncmp(netstring, "foo", 3) == 0);
assert(retval == 0);
retval = netstring_read(netstring+netstring_len+1, 9, &netstring, &netstring_len);
assert(netstring_len == 0); assert(retval == 0);
retval = netstring_read(netstring+netstring_len+1, 6, &netstring, &netstring_len);
assert(netstring_len == 3); assert(strncmp(netstring, "bar", 3) == 0);
assert(retval == 0);
/* ex3: no comma */
retval = netstring_read(ex3, strlen(ex3), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_COMMA);
/* ex4: too short */
retval = netstring_read(ex4, strlen(ex4), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_TOO_SHORT);
/* ex5: leading zero */
retval = netstring_read(ex5, strlen(ex5), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_LEADING_ZERO);
/* ex6: too long */
retval = netstring_read(ex6, strlen(ex6), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_TOO_LONG);
/* ex7: no colon */
retval = netstring_read(ex7, strlen(ex7), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_COLON);
/* ex8: no number or colon */
retval = netstring_read(ex8, strlen(ex8), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_LENGTH);
/* ex9: no number */
retval = netstring_read(ex9, strlen(ex9), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_LENGTH);
}
void test_netstring_buffer_size(void) {
assert(netstring_buffer_size(0) == 3);
assert(netstring_buffer_size(1) == 4);
assert(netstring_buffer_size(2) == 5);
assert(netstring_buffer_size(9) == 12);
assert(netstring_buffer_size(10) == 14);
assert(netstring_buffer_size(12345) == 12345 + 5 + 2);
}
void test_netstring_encode_new(void) {
char *ns; size_t bytes;
bytes = netstring_encode_new(&ns, "foo", 3);
assert(ns != NULL); assert(strncmp(ns, "3:foo,", 6) == 0); assert(bytes == 6);
free(ns);
bytes = netstring_encode_new(&ns, NULL, 0);
assert(ns != NULL); assert(strncmp(ns, "0:,", 3) == 0); assert(bytes == 3);
free(ns);
bytes = netstring_encode_new(&ns, "hello world!", 12); assert(bytes == 16);
assert(ns != NULL); assert(strncmp(ns, "12:hello world!,", 16) == 0);
free(ns);
}
int main(void) {
printf("Running test suite...\n");
test_netstring_read();
test_netstring_buffer_size();
test_netstring_encode_new();
printf("All tests passed!\n");
return 0;
}
{
'targets':
[
{
'target_name': 'netstring',
'type': 'static_library',
'sources':
[
'netstring-c/netstring.c',
'netstring-c/netstring.h'
],
'direct_dependent_settings':
{
'include_dirs':
[
'netstring-c'
]
},
'conditions':
[
[ 'OS != "win"', {
'cflags': [ '-Wall', '-Wno-sign-compare' ]
}],
[ 'OS == "mac"', {
'xcode_settings':
{
'WARNING_CFLAGS': [ '-Wall', '-Wno-sign-compare' ]
}
}]
]
}
]
}
......@@ -31,8 +31,6 @@ namespace Channel
private:
// Passed by argument.
Listener* listener{ nullptr };
// Others.
size_t msgStart{ 0u }; // Where the latest message starts.
};
class ProducerSocket : public ::UnixStreamSocket
......@@ -72,10 +70,10 @@ namespace Channel
void Close();
void SetListener(Listener* listener);
void Send(json& jsonMessage);
void SendLog(char* message, size_t messageLen);
void SendLog(char* message, uint32_t messageLen);
private:
void SendImpl(const void* nsPayload, size_t nsPayloadLen);
void SendImpl(const void* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */
public:
......
......@@ -160,7 +160,7 @@ public:
if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG) \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D(trace) " _MS_LOG_STR, _MS_LOG_ARG); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
} \
while (false)
......@@ -192,7 +192,7 @@ public:
if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG && _MS_TAG_ENABLED(tag)) \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
} \
while (false)
......@@ -214,7 +214,7 @@ public:
if (Settings::configuration.logLevel >= LogLevel::LOG_WARN && _MS_TAG_ENABLED(tag)) \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
} \
while (false)
......@@ -236,7 +236,7 @@ public:
if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG && _MS_TAG_ENABLED_2(tag1, tag2)) \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
} \
while (false)
......@@ -258,7 +258,7 @@ public:
if (Settings::configuration.logLevel >= LogLevel::LOG_WARN && _MS_TAG_ENABLED_2(tag1, tag2)) \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
} \
while (false)
......@@ -279,7 +279,7 @@ public:
do \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
while (false)
......@@ -301,7 +301,7 @@ public:
do \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
while (false)
......@@ -321,7 +321,7 @@ public:
do \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
while (false)
......@@ -337,7 +337,7 @@ public:
do \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X(data) " _MS_LOG_STR, _MS_LOG_ARG); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
size_t bufferDataLen{ 0 }; \
for (size_t i{0}; i < len; ++i) \
{ \
......@@ -345,7 +345,7 @@ public:
{ \
if (bufferDataLen != 0) \
{ \
Logger::channel->SendLog(Logger::buffer, bufferDataLen); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(bufferDataLen)); \
bufferDataLen = 0; \
} \
int loggerWritten = std::snprintf(Logger::buffer + bufferDataLen, Logger::bufferSize, "X%06X ", static_cast<unsigned int>(i)); \
......@@ -355,7 +355,7 @@ public:
bufferDataLen += loggerWritten; \
} \
if (bufferDataLen != 0) \
Logger::channel->SendLog(Logger::buffer, bufferDataLen); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(bufferDataLen)); \
} \
while (false)
......@@ -395,7 +395,7 @@ public:
if (Settings::configuration.logLevel >= LogLevel::LOG_ERROR || MS_LOG_DEV_LEVEL >= 1) \
{ \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "E" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \
Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \
} \
while (false)
......
......@@ -34,10 +34,6 @@ namespace PayloadChannel
private:
// Passed by argument.
Listener* listener{ nullptr };
// Allocated by this.
uint8_t* readBuffer{ nullptr };
// Others.
size_t msgStart{ 0u }; // Where the latest message starts.
};
class ProducerSocket : public ::UnixStreamSocket
......@@ -84,7 +80,7 @@ namespace PayloadChannel
void Send(json& jsonMessage);
private:
void SendImpl(const void* nsPayload, size_t nsPayloadLen);
void SendImpl(const void* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */
public:
......
......@@ -3,7 +3,6 @@
'type': 'executable',
'dependencies':
[
'deps/netstring/netstring.gyp:netstring',
'deps/libuv/uv.gyp:libuv',
'deps/openssl/openssl.gyp:openssl',
'deps/libsrtp/libsrtp.gyp:libsrtp',
......
......@@ -68,15 +68,6 @@ function get_json()
${DEST}/third_party/
}
function get_netstring()
{
GIT_REPO="https://github.com/PeterScott/netstring-c.git"
GIT_TAG="master"
DEST="deps/netstring/netstring-c"
get_dep "${GIT_REPO}" "${GIT_TAG}" "${DEST}"
}
function get_libuv()
{
GIT_REPO="https://github.com/libuv/libuv.git"
......@@ -183,7 +174,7 @@ function get_win_getopt()
case "${DEP}" in
'-h')
echo "Usage:"
echo " ./scripts/$(basename $0) [gyp|json|netstring|libuv|openssl|libsrtp|usrsctp|abseil-cpp|catch|lcov|clang-fuzzer|fuzzer-corpora|win-getopt]"
echo " ./scripts/$(basename $0) [gyp|json|libuv|openssl|libsrtp|usrsctp|abseil-cpp|catch|lcov|clang-fuzzer|fuzzer-corpora|win-getopt]"
echo
;;
gyp)
......@@ -192,9 +183,6 @@ case "${DEP}" in
json)
get_json
;;
netstring)
get_netstring
;;
libuv)
get_libuv
;;
......
......@@ -7,26 +7,22 @@
#include <cmath> // std::ceil()
#include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove()
extern "C"
{
#include <netstring.h>
}
namespace Channel
{
/* Static. */
// netstring length for a 4194304 bytes payload.
static constexpr size_t NsMessageMaxLen{ 4194313 };
static constexpr size_t NsPayloadMaxLen{ 4194304 };
// Binary length for a 4194304 bytes payload.
static constexpr size_t MessageMaxLen{ 4194308 };
static constexpr size_t PayloadMaxLen{ 4194304 };
/* Instance methods. */
ChannelSocket::ChannelSocket(int consumerFd, int producerFd)
: consumerSocket(consumerFd, NsMessageMaxLen, this), producerSocket(producerFd, NsMessageMaxLen)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen)
{
MS_TRACE_STD();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(NsMessageMaxLen));
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
}
ChannelSocket::~ChannelSocket()
......@@ -68,26 +64,26 @@ namespace Channel
std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen)
if (message.length() > PayloadMaxLen)
{
MS_ERROR_STD("mesage too big");
MS_ERROR_STD("message too big");
return;
}
SendImpl(message.c_str(), message.length());
SendImpl(message.c_str(), static_cast<uint32_t>(message.length()));
}
void ChannelSocket::SendLog(char* message, size_t messageLen)
void ChannelSocket::SendLog(char* message, uint32_t messageLen)
{
MS_TRACE_STD();
if (this->closed)
return;
if (messageLen > NsPayloadMaxLen)
if (messageLen > PayloadMaxLen)
{
MS_ERROR_STD("mesage too big");
MS_ERROR_STD("message too big");
return;
}
......@@ -95,30 +91,20 @@ namespace Channel
SendImpl(message, messageLen);
}
inline void ChannelSocket::SendImpl(const void* nsPayload, size_t nsPayloadLen)
inline void ChannelSocket::SendImpl(const void* payload, uint32_t payloadLen)
{
MS_TRACE_STD();
size_t nsNumLen;
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (nsPayloadLen == 0)
{
nsNumLen = 1;
this->writeBuffer[0] = '0';
this->writeBuffer[1] = ':';
this->writeBuffer[2] = ',';
}
else
if (payloadLen != 0)
{
nsNumLen = static_cast<size_t>(std::ceil(std::log10(static_cast<double>(nsPayloadLen) + 1)));
std::sprintf(reinterpret_cast<char*>(this->writeBuffer), "%zu:", nsPayloadLen);
std::memcpy(this->writeBuffer + nsNumLen + 1, nsPayload, nsPayloadLen);
this->writeBuffer[nsNumLen + nsPayloadLen + 1] = ',';
std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen);
}
size_t nsLen = nsNumLen + nsPayloadLen + 2;
size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket.Write(this->writeBuffer, nsLen);
this->producerSocket.Write(this->writeBuffer, len);
}
void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
......@@ -174,124 +160,48 @@ namespace Channel
{
MS_TRACE_STD();
size_t msgStart{ 0 };
// Be ready to parse more than a single message in a single chunk.
while (true)
{
if (IsClosed())
return;
size_t readLen = this->bufferDataLen - this->msgStart;
char* msgStart = nullptr;
size_t msgLen;
int nsRet = netstring_read(
reinterpret_cast<char*>(this->buffer + this->msgStart), readLen, &msgStart, &msgLen);
size_t readLen = this->bufferDataLen - msgStart;
if (nsRet != 0)
if (readLen < sizeof(uint32_t))
{
switch (nsRet)
{
case NETSTRING_ERROR_TOO_SHORT:
{
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize)
{
// First case: the incomplete message does not begin at position 0 of
// the buffer, so move the incomplete message to the position 0.
if (this->msgStart != 0)
{
std::memmove(this->buffer, this->buffer + this->msgStart, readLen);
this->msgStart = 0;
this->bufferDataLen = readLen;
}
// Second case: the incomplete message begins at position 0 of the buffer.
// The message is too big, so discard it.
else
{
MS_ERROR_STD(
"no more space in the buffer for the unfinished message being parsed, "
"discarding it");
this->msgStart = 0;
this->bufferDataLen = 0;
}
}
// Otherwise the buffer is not full, just wait.
return;
}
case NETSTRING_ERROR_TOO_LONG:
{
MS_ERROR_STD("NETSTRING_ERROR_TOO_LONG");
break;
}
case NETSTRING_ERROR_NO_COLON:
{
MS_ERROR_STD("NETSTRING_ERROR_NO_COLON");
break;
}
case NETSTRING_ERROR_NO_COMMA:
{
MS_ERROR_STD("NETSTRING_ERROR_NO_COMMA");
break;
}
case NETSTRING_ERROR_LEADING_ZERO:
{
MS_ERROR_STD("NETSTRING_ERROR_LEADING_ZERO");
break;
}
case NETSTRING_ERROR_NO_LENGTH:
{
MS_ERROR_STD("NETSTRING_ERROR_NO_LENGTH");
break;
}
}
// Error, so reset and exit the parsing loop.
this->msgStart = 0;
this->bufferDataLen = 0;
return;
// Incomplete data.
break;
}
// If here it means that msgStart points to the beginning of a message
// with msgLen bytes length, so recalculate readLen.
readLen =
reinterpret_cast<const uint8_t*>(msgStart) - (this->buffer + this->msgStart) + msgLen + 1;
uint32_t msgLen;
// Read message length.
std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
this->listener->OnConsumerSocketMessage(this, msgStart, msgLen);
// If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + readLen) == this->bufferSize)
if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
{
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else
{
this->msgStart += readLen;
// Incomplete data.
break;
}
// If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart)
this->listener->OnConsumerSocketMessage(
this,
reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
}
if (msgStart != 0)
{
this->bufferDataLen = this->bufferDataLen - msgStart;
if (this->bufferDataLen != 0)
{
continue;
std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
}
break;
}
}
......
......@@ -8,26 +8,22 @@
#include <cmath> // std::ceil()
#include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove()
extern "C"
{
#include <netstring.h>
}
namespace PayloadChannel
{
/* Static. */
// netstring length for a 4194304 bytes payload.
static constexpr size_t NsMessageMaxLen{ 4194313 };
static constexpr size_t NsPayloadMaxLen{ 4194304 };
// Binary length for a 4194304 bytes payload.
static constexpr size_t MessageMaxLen{ 4194308 };
static constexpr size_t PayloadMaxLen{ 4194304 };
/* Instance methods. */
PayloadChannelSocket::PayloadChannelSocket(int consumerFd, int producerFd)
: consumerSocket(consumerFd, NsMessageMaxLen, this), producerSocket(producerFd, NsMessageMaxLen)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen)
{
MS_TRACE();
this->writeBuffer = (uint8_t*)std::malloc(NsMessageMaxLen);
this->writeBuffer = (uint8_t*)std::malloc(MessageMaxLen);
}
PayloadChannelSocket::~PayloadChannelSocket()
......@@ -70,21 +66,21 @@ namespace PayloadChannel
std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen)
if (message.length() > PayloadMaxLen)
{
MS_ERROR("mesage too big");
MS_ERROR("message too big");
return;
}
else if (payloadLen > NsPayloadMaxLen)
else if (payloadLen > PayloadMaxLen)
{
MS_ERROR("payload too big");
return;
}
SendImpl(message.c_str(), message.length());
SendImpl(payload, payloadLen);
SendImpl(message.c_str(), static_cast<uint32_t>(message.length()));
SendImpl(payload, static_cast<uint32_t>(payloadLen));
}
void PayloadChannelSocket::Send(json& jsonMessage)
......@@ -96,40 +92,30 @@ namespace PayloadChannel
std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen)
if (message.length() > PayloadMaxLen)
{
MS_ERROR_STD("mesage too big");
MS_ERROR_STD("message too big");
return;
}
SendImpl(message.c_str(), message.length());
SendImpl(message.c_str(), static_cast<uint32_t>(message.length()));
}
inline void PayloadChannelSocket::SendImpl(const void* nsPayload, size_t nsPayloadLen)
inline void PayloadChannelSocket::SendImpl(const void* payload, uint32_t payloadLen)
{
MS_TRACE();
size_t nsNumLen;
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (nsPayloadLen == 0)
{
nsNumLen = 1;
this->writeBuffer[0] = '0';
this->writeBuffer[1] = ':';
this->writeBuffer[2] = ',';
}
else
if (payloadLen != 0)
{
nsNumLen = static_cast<size_t>(std::ceil(std::log10(static_cast<double>(nsPayloadLen) + 1)));
std::sprintf(reinterpret_cast<char*>(this->writeBuffer), "%zu:", nsPayloadLen);
std::memcpy(this->writeBuffer + nsNumLen + 1, nsPayload, nsPayloadLen);
this->writeBuffer[nsNumLen + nsPayloadLen + 1] = ',';
std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen);
}
size_t nsLen = nsNumLen + nsPayloadLen + 2;
size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket.Write(this->writeBuffer, nsLen);
this->producerSocket.Write(this->writeBuffer, len);
}
void PayloadChannelSocket::OnConsumerSocketMessage(
......@@ -232,140 +218,59 @@ namespace PayloadChannel
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener)
{
MS_TRACE();
this->readBuffer = static_cast<uint8_t*>(std::malloc(NsMessageMaxLen));
}
ConsumerSocket::~ConsumerSocket()
{
MS_TRACE();
std::free(this->readBuffer);
}
void ConsumerSocket::UserOnUnixStreamRead()
{
MS_TRACE();
size_t msgStart{ 0 };
// Be ready to parse more than a single message in a single chunk.
while (true)
{
if (IsClosed())
return;
size_t readLen = this->bufferDataLen - this->msgStart;
char* msgStart = nullptr;
size_t msgLen;
int nsRet = netstring_read(
reinterpret_cast<char*>(this->buffer + this->msgStart), readLen, &msgStart, &msgLen);
size_t readLen = this->bufferDataLen - msgStart;
if (nsRet != 0)
if (readLen < sizeof(uint32_t))
{
switch (nsRet)
{
case NETSTRING_ERROR_TOO_SHORT:
{
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize)
{
// First case: the incomplete message does not begin at position 0 of
// the buffer, so move the incomplete message to the position 0.
if (this->msgStart != 0)
{
std::memmove(this->buffer, this->buffer + this->msgStart, readLen);
this->msgStart = 0;
this->bufferDataLen = readLen;
}
// Second case: the incomplete message begins at position 0 of the buffer.
// The message is too big, so discard it.
else
{
MS_ERROR(
"no more space in the buffer for the unfinished message being parsed, "
"discarding it");
this->msgStart = 0;
this->bufferDataLen = 0;
}
}
// Otherwise the buffer is not full, just wait.
return;
}
case NETSTRING_ERROR_TOO_LONG:
{
MS_ERROR("NETSTRING_ERROR_TOO_LONG");
break;
}
case NETSTRING_ERROR_NO_COLON:
{
MS_ERROR("NETSTRING_ERROR_NO_COLON");
break;
}
case NETSTRING_ERROR_NO_COMMA:
{
MS_ERROR("NETSTRING_ERROR_NO_COMMA");
break;
}
case NETSTRING_ERROR_LEADING_ZERO:
{
MS_ERROR("NETSTRING_ERROR_LEADING_ZERO");
break;
}
case NETSTRING_ERROR_NO_LENGTH:
{
MS_ERROR("NETSTRING_ERROR_NO_LENGTH");
break;
}
}
// Incomplete data.
break;
}
// Error, so reset and exit the parsing loop.
this->msgStart = 0;
this->bufferDataLen = 0;
uint32_t msgLen;
// Read message length.
std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
return;
if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
{
// Incomplete data.
break;
}
// If here it means that msgStart points to the beginning of a message
// with msgLen bytes length, so recalculate readLen.
readLen =
reinterpret_cast<const uint8_t*>(msgStart) - (this->buffer + this->msgStart) + msgLen + 1;
this->listener->OnConsumerSocketMessage(
this,
reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
std::memcpy(this->readBuffer, msgStart, msgLen);
this->listener->OnConsumerSocketMessage(this, reinterpret_cast<char*>(this->readBuffer), msgLen);
msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
}
// If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + readLen) == this->bufferSize)
{
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else
{
this->msgStart += readLen;
}
if (msgStart != 0)
{
this->bufferDataLen = this->bufferDataLen - msgStart;
// If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart)
if (this->bufferDataLen != 0)
{
continue;
std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
}
break;
}
}
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论