Unverified 提交 34b647b3 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo 提交者: GitHub

Add DataChannel support (#323)

上级 31909cfc
...@@ -3,9 +3,9 @@ const Logger = require('./Logger'); ...@@ -3,9 +3,9 @@ const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter'); const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const { InvalidStateError } = require('./errors'); const { InvalidStateError } = require('./errors');
// netstring length for a 65536 bytes payload. // netstring length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 65543; const NS_MESSAGE_MAX_LEN = 4194313;
const NS_PAYLOAD_MAX_LEN = 65536; const NS_PAYLOAD_MAX_LEN = 4194304;
class Channel extends EnhancedEventEmitter class Channel extends EnhancedEventEmitter
{ {
...@@ -56,16 +56,16 @@ class Channel extends EnhancedEventEmitter ...@@ -56,16 +56,16 @@ class Channel extends EnhancedEventEmitter
this._recvBuffer = Buffer.concat( this._recvBuffer = Buffer.concat(
[ this._recvBuffer, buffer ], [ this._recvBuffer, buffer ],
this._recvBuffer.length + buffer.length); this._recvBuffer.length + buffer.length);
}
if (this._recvBuffer.length > NS_PAYLOAD_MAX_LEN) if (this._recvBuffer.length > NS_PAYLOAD_MAX_LEN)
{ {
this._logger.error('receiving buffer is full, discarding all data into it'); this._logger.error('receiving buffer is full, discarding all data into it');
// Reset the buffer and exit. // Reset the buffer and exit.
this._recvBuffer = null; this._recvBuffer = null;
return; return;
}
} }
while (true) // eslint-disable-line no-constant-condition while (true) // eslint-disable-line no-constant-condition
...@@ -79,7 +79,7 @@ class Channel extends EnhancedEventEmitter ...@@ -79,7 +79,7 @@ class Channel extends EnhancedEventEmitter
catch (error) catch (error)
{ {
this._logger.error( this._logger.error(
'invalid data received from the worker process: %s', String(error)); 'invalid netstring data received from the worker process: %s', String(error));
// Reset the buffer and exit. // Reset the buffer and exit.
this._recvBuffer = null; this._recvBuffer = null;
......
...@@ -243,11 +243,11 @@ class Consumer extends EnhancedEventEmitter ...@@ -243,11 +243,11 @@ class Consumer extends EnhancedEventEmitter
logger.debug('transportClosed()'); logger.debug('transportClosed()');
this._closed = true;
// Remove notification subscriptions. // Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.consumerId); this._channel.removeAllListeners(this._internal.consumerId);
this._closed = true;
this.safeEmit('transportclose'); this.safeEmit('transportclose');
// Emit observer event. // Emit observer event.
...@@ -347,6 +347,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -347,6 +347,9 @@ class Consumer extends EnhancedEventEmitter
await this._channel.request('consumer.requestKeyFrame', this._internal); await this._channel.request('consumer.requestKeyFrame', this._internal);
} }
/**
* @private
*/
_handleWorkerNotifications() _handleWorkerNotifications()
{ {
this._channel.on(this._internal.consumerId, (event, data) => this._channel.on(this._internal.consumerId, (event, data) =>
......
const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const logger = new Logger('DataConsumer');
class DataConsumer extends EnhancedEventEmitter
{
/**
* @private
*
* @emits transportclose
* @emits dataproducerclose
* @emits @close
* @emits @dataproducerclose
*/
constructor({ internal, data, channel, appData })
{
super(logger);
logger.debug('constructor()');
// Internal data.
// @type {Object}
// - .routerId
// - .transportId
// - .dataConsumerId
// - .dataProducerId
this._internal = internal;
// DataConsumer data.
// @type {RTCSctpStreamParameters}
// - .sctpStreamParameters
// - .label
// - .protocol
this._data = data;
// Channel instance.
// @type {Channel}
this._channel = channel;
// Closed flag.
// @type {Boolean}
this._closed = false;
// App data.
// @type {Object}
this._appData = appData;
// Observer.
// @type {EventEmitter}
this._observer = new EnhancedEventEmitter();
this._handleWorkerNotifications();
}
/**
* DataConsumer id.
*
* @type {String}
*/
get id()
{
return this._internal.dataConsumerId;
}
/**
* Associated DataProducer id.
*
* @type {String}
*/
get dataProducerId()
{
return this._internal.dataProducerId;
}
/**
* Whether the DataConsumer is closed.
*
* @type {Boolean}
*/
get closed()
{
return this._closed;
}
/**
* SCTP stream parameters.
*
* @type {RTCSctpStreamParameters}
*/
get sctpStreamParameters()
{
return this._data.sctpStreamParameters;
}
/**
* DataChannel label.
*
* @returns {String}
*/
get label()
{
return this._data.label;
}
/**
* DataChannel protocol.
*
* @returns {String}
*/
get protocol()
{
return this._data.protocol;
}
/**
* App custom data.
*
* @type {Object}
*/
get appData()
{
return this._appData;
}
/**
* Invalid setter.
*/
set appData(appData) // eslint-disable-line no-unused-vars
{
throw new Error('cannot override appData object');
}
/**
* Observer.
*
* @type {EventEmitter}
*
* @emits close
*/
get observer()
{
return this._observer;
}
/**
* Close the DataConsumer.
*/
close()
{
if (this._closed)
return;
logger.debug('close()');
this._closed = true;
// Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.dataConsumerId);
this._channel.request('dataConsumer.close', this._internal)
.catch(() => {});
this.emit('@close');
// Emit observer event.
this._observer.safeEmit('close');
}
/**
* Transport was closed.
*
* @private
*/
transportClosed()
{
if (this._closed)
return;
logger.debug('transportClosed()');
this._closed = true;
// Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.dataConsumerId);
this.safeEmit('transportclose');
// Emit observer event.
this._observer.safeEmit('close');
}
/**
* Dump DataConsumer.
*
* @async
* @returns {Object}
*/
async dump()
{
logger.debug('dump()');
return this._channel.request('dataConsumer.dump', this._internal);
}
/**
* Get DataConsumer stats.
*
* @async
* @returns {Array<Object>}
*/
async getStats()
{
logger.debug('getStats()');
return this._channel.request('dataConsumer.getStats', this._internal);
}
/**
* @private
*/
_handleWorkerNotifications()
{
this._channel.on(this._internal.dataConsumerId, (event) =>
{
switch (event)
{
case 'dataproducerclose':
{
if (this._closed)
break;
this._closed = true;
// Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.dataConsumerId);
this.emit('@dataproducerclose');
this.safeEmit('dataproducerclose');
// Emit observer event.
this._observer.safeEmit('close');
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
module.exports = DataConsumer;
const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const logger = new Logger('DataProducer');
class DataProducer extends EnhancedEventEmitter
{
/**
* @private
*
* @emits transportclose
* @emits @close
*/
constructor({ internal, data, channel, appData })
{
super(logger);
logger.debug('constructor()');
// Internal data.
// @type {Object}
// - .routerId
// - .transportId
// - .dataProducerId
this._internal = internal;
// DataProducer data.
// @type {RTCSctpStreamParameters}
// - .sctpStreamParameters
// - .label
// - .protocol
this._data = data;
// Channel instance.
// @type {Channel}
this._channel = channel;
// Closed flag.
// @type {Boolean}
this._closed = false;
// App data.
// @type {Object}
this._appData = appData;
// Observer.
// @type {EventEmitter}
this._observer = new EnhancedEventEmitter();
this._handleWorkerNotifications();
}
/**
* DataProducer id.
*
* @type {String}
*/
get id()
{
return this._internal.dataProducerId;
}
/**
* Whether the DataProducer is closed.
*
* @type {Boolean}
*/
get closed()
{
return this._closed;
}
/**
* SCTP stream parameters.
*
* @type {RTCSctpStreamParameters}
*/
get sctpStreamParameters()
{
return this._data.sctpStreamParameters;
}
/**
* DataChannel label.
*
* @returns {String}
*/
get label()
{
return this._data.label;
}
/**
* DataChannel protocol.
*
* @returns {String}
*/
get protocol()
{
return this._data.protocol;
}
/**
* App custom data.
*
* @type {Object}
*/
get appData()
{
return this._appData;
}
/**
* Invalid setter.
*/
set appData(appData) // eslint-disable-line no-unused-vars
{
throw new Error('cannot override appData object');
}
/**
* Observer.
*
* @type {EventEmitter}
*
* @emits close
*/
get observer()
{
return this._observer;
}
/**
* Close the DataProducer.
*/
close()
{
if (this._closed)
return;
logger.debug('close()');
this._closed = true;
// Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.dataProducerId);
this._channel.request('dataProducer.close', this._internal)
.catch(() => {});
this.emit('@close');
// Emit observer event.
this._observer.safeEmit('close');
}
/**
* Transport was closed.
*
* @private
*/
transportClosed()
{
if (this._closed)
return;
logger.debug('transportClosed()');
this._closed = true;
this.safeEmit('transportclose');
// Emit observer event.
this._observer.safeEmit('close');
}
/**
* Dump DataProducer.
*
* @async
* @returns {Object}
*/
async dump()
{
logger.debug('dump()');
return this._channel.request('dataProducer.dump', this._internal);
}
/**
* Get DataProducer stats.
*
* @async
* @returns {Array<Object>}
*/
async getStats()
{
logger.debug('getStats()');
return this._channel.request('dataProducer.getStats', this._internal);
}
/**
* @private
*/
_handleWorkerNotifications()
{
// No need to subscribe to any event.
}
}
module.exports = DataProducer;
...@@ -11,12 +11,14 @@ class PipeTransport extends Transport ...@@ -11,12 +11,14 @@ class PipeTransport extends Transport
/** /**
* @private * @private
*/ */
constructor({ data, ...params }) constructor(params)
{ {
super(params); super(params);
logger.debug('constructor()'); logger.debug('constructor()');
const { data } = params;
// PipeTransport data. // PipeTransport data.
// @type {Object} // @type {Object}
// - .tuple // - .tuple
...@@ -25,9 +27,17 @@ class PipeTransport extends Transport ...@@ -25,9 +27,17 @@ class PipeTransport extends Transport
// - .remoteIp // - .remoteIp
// - .remotePort // - .remotePort
// - .protocol // - .protocol
// - .sctpParameters
// - .port
// - .OS
// - .MIS
// - .maxMessageSize
// - .sctpState
this._data = this._data =
{ {
tuple : data.tuple tuple : data.tuple,
sctpParameters : data.sctpParameters,
sctpState : data.sctpState
}; };
} }
...@@ -39,6 +49,73 @@ class PipeTransport extends Transport ...@@ -39,6 +49,73 @@ class PipeTransport extends Transport
return this._data.tuple; return this._data.tuple;
} }
/**
* @type {Object}
*/
get sctpParameters()
{
return this._data.sctpParameters;
}
/**
* @type {String}
*/
get sctpState()
{
return this._data.sctpState;
}
/**
* Observer.
*
* @override
* @type {EventEmitter}
*
* @emits close
* @emits {producer: Producer} newproducer
* @emits {consumer: Consumer} newconsumer
* @emits {producer: DataProducer} newdataproducer
* @emits {consumer: DataConsumer} newdataconsumer
* @emits {sctpState: String} sctpstatechange
*/
get observer()
{
return this._observer;
}
/**
* Close the PlainRtpTransport.
*
* @override
*/
close()
{
if (this._closed)
return;
if (this._data.sctpState)
this._data.sctpState = 'closed';
super.close();
}
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed()
{
if (this._closed)
return;
if (this._data.sctpState)
this._data.sctpState = 'closed';
super.routerClosed();
}
/** /**
* Provide the PipeTransport remote parameters. * Provide the PipeTransport remote parameters.
* *
...@@ -67,8 +144,8 @@ class PipeTransport extends Transport ...@@ -67,8 +144,8 @@ class PipeTransport extends Transport
* @param {String} producerId * @param {String} producerId
* @param {Object} [appData={}] - Custom app data. * @param {Object} [appData={}] - Custom app data.
* *
* @override
* @async * @async
* @override
* @returns {Consumer} * @returns {Consumer}
*/ */
async consume({ producerId, appData = {} } = {}) async consume({ producerId, appData = {} } = {})
...@@ -129,7 +206,30 @@ class PipeTransport extends Transport ...@@ -129,7 +206,30 @@ class PipeTransport extends Transport
*/ */
_handleWorkerNotifications() _handleWorkerNotifications()
{ {
// No need to subscribe to any event. this._channel.on(this._internal.transportId, (event, data) =>
{
switch (event)
{
case 'sctpstatechange':
{
const { sctpState } = data;
this._data.sctpState = sctpState;
this.safeEmit('sctpstatechange', sctpState);
// Emit observer event.
this._observer.safeEmit('sctpstatechange', sctpState);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
} }
} }
......
...@@ -7,13 +7,17 @@ class PlainRtpTransport extends Transport ...@@ -7,13 +7,17 @@ class PlainRtpTransport extends Transport
{ {
/** /**
* @private * @private
*
* @emits {sctpState: String} sctpstatechange
*/ */
constructor({ data, ...params }) constructor(params)
{ {
super(params); super(params);
logger.debug('constructor()'); logger.debug('constructor()');
const { data } = params;
// PlainRtpTransport data. // PlainRtpTransport data.
// @type {Object} // @type {Object}
// - .rtcpMux // - .rtcpMux
...@@ -31,10 +35,18 @@ class PlainRtpTransport extends Transport ...@@ -31,10 +35,18 @@ class PlainRtpTransport extends Transport
// - .remoteIp // - .remoteIp
// - .remotePort // - .remotePort
// - .protocol // - .protocol
// - .sctpParameters
// - .port
// - .OS
// - .MIS
// - .maxMessageSize
// - .sctpState
this._data = this._data =
{ {
tuple : data.tuple, tuple : data.tuple,
rtcpTuple : data.rtcpTuple rtcpTuple : data.rtcpTuple,
sctpParameters : data.sctpParameters,
sctpState : data.sctpState
}; };
} }
...@@ -54,6 +66,73 @@ class PlainRtpTransport extends Transport ...@@ -54,6 +66,73 @@ class PlainRtpTransport extends Transport
return this._data.rtcpTuple; return this._data.rtcpTuple;
} }
/**
* @type {Object}
*/
get sctpParameters()
{
return this._data.sctpParameters;
}
/**
* @type {String}
*/
get sctpState()
{
return this._data.sctpState;
}
/**
* Observer.
*
* @override
* @type {EventEmitter}
*
* @emits close
* @emits {producer: Producer} newproducer
* @emits {consumer: Consumer} newconsumer
* @emits {producer: DataProducer} newdataproducer
* @emits {consumer: DataConsumer} newdataconsumer
* @emits {sctpState: String} sctpstatechange
*/
get observer()
{
return this._observer;
}
/**
* Close the PlainRtpTransport.
*
* @override
*/
close()
{
if (this._closed)
return;
if (this._data.sctpState)
this._data.sctpState = 'closed';
super.close();
}
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed()
{
if (this._closed)
return;
if (this._data.sctpState)
this._data.sctpState = 'closed';
super.routerClosed();
}
/** /**
* Provide the PlainRtpTransport remote parameters. * Provide the PlainRtpTransport remote parameters.
* *
...@@ -99,7 +178,30 @@ class PlainRtpTransport extends Transport ...@@ -99,7 +178,30 @@ class PlainRtpTransport extends Transport
*/ */
_handleWorkerNotifications() _handleWorkerNotifications()
{ {
// No need to subscribe to any event. this._channel.on(this._internal.transportId, (event, data) =>
{
switch (event)
{
case 'sctpstatechange':
{
const { sctpState } = data;
this._data.sctpState = sctpState;
this.safeEmit('sctpstatechange', sctpState);
// Emit observer event.
this._observer.safeEmit('sctpstatechange', sctpState);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
} }
} }
......
...@@ -214,6 +214,9 @@ class Producer extends EnhancedEventEmitter ...@@ -214,6 +214,9 @@ class Producer extends EnhancedEventEmitter
this._closed = true; this._closed = true;
// Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.producerId);
this.safeEmit('transportclose'); this.safeEmit('transportclose');
// Emit observer event. // Emit observer event.
...@@ -286,6 +289,9 @@ class Producer extends EnhancedEventEmitter ...@@ -286,6 +289,9 @@ class Producer extends EnhancedEventEmitter
this._observer.safeEmit('resume'); this._observer.safeEmit('resume');
} }
/**
* @private
*/
_handleWorkerNotifications() _handleWorkerNotifications()
{ {
this._channel.on(this._internal.producerId, (event, data) => this._channel.on(this._internal.producerId, (event, data) =>
......
差异被折叠。
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
const Logger = require('./Logger'); const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter'); const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const utils = require('./utils');
const ortc = require('./ortc'); const ortc = require('./ortc');
const Producer = require('./Producer'); const Producer = require('./Producer');
const Consumer = require('./Consumer'); const Consumer = require('./Consumer');
const DataProducer = require('./DataProducer');
const DataConsumer = require('./DataConsumer');
const logger = new Logger('Transport'); const logger = new Logger('Transport');
...@@ -17,14 +20,18 @@ class Transport extends EnhancedEventEmitter ...@@ -17,14 +20,18 @@ class Transport extends EnhancedEventEmitter
* @emits @close * @emits @close
* @emits @newproducer * @emits @newproducer
* @emits @producerclose * @emits @producerclose
* @emits @newdataproducer
* @emits @dataproducerclose
*/ */
constructor( constructor(
{ {
internal, internal,
data,
channel, channel,
appData, appData,
getRouterRtpCapabilities, getRouterRtpCapabilities,
getProducerById getProducerById,
getDataProducerById
}) })
{ {
super(logger); super(logger);
...@@ -37,6 +44,10 @@ class Transport extends EnhancedEventEmitter ...@@ -37,6 +44,10 @@ class Transport extends EnhancedEventEmitter
// - .transportId // - .transportId
this._internal = internal; this._internal = internal;
// Transport specific data.
// @type {Object}
this._data = data;
// Channel instance. // Channel instance.
// @type {Channel} // @type {Channel}
this._channel = channel; this._channel = channel;
...@@ -57,6 +68,10 @@ class Transport extends EnhancedEventEmitter ...@@ -57,6 +68,10 @@ class Transport extends EnhancedEventEmitter
// @type {Function: Producer} // @type {Function: Producer}
this._getProducerById = getProducerById; this._getProducerById = getProducerById;
// Function that gets any DataProducer in the Router.
// @type {Function: DataProducer}
this._getDataProducerById = getDataProducerById;
// Map of Producers indexed by id. // Map of Producers indexed by id.
// @type {Map<String, Producer>} // @type {Map<String, Producer>}
this._producers = new Map(); this._producers = new Map();
...@@ -65,11 +80,27 @@ class Transport extends EnhancedEventEmitter ...@@ -65,11 +80,27 @@ class Transport extends EnhancedEventEmitter
// @type {Map<String, Consumer>} // @type {Map<String, Consumer>}
this._consumers = new Map(); this._consumers = new Map();
// Map of DataProducers indexed by id.
// @type {Map<String, DataProducer>}
this._dataProducers = new Map();
// Map of DataConsumers indexed by id.
// @type {Map<String, DataConsumer>}
this._dataConsumers = new Map();
// CNAME of Producers in this Transport. This is for the scenario in which // CNAME of Producers in this Transport. This is for the scenario in which
// a Producer does not signal any CNAME in its RTP parameters. // a Producer does not signal any CNAME in its RTP parameters.
// @type {String} // @type {String}
this._cnameForProducers = null; this._cnameForProducers = null;
// Array for holding used and unused SCTP stream ids.
// @type {Buffer}
this._sctpStreamIds = null;
// SCTP stream id value counter.
// @type {Number}
this._nextSctpStreamId = 0;
// Observer. // Observer.
// @type {EventEmitter} // @type {EventEmitter}
this._observer = new EnhancedEventEmitter(); this._observer = new EnhancedEventEmitter();
...@@ -124,6 +155,8 @@ class Transport extends EnhancedEventEmitter ...@@ -124,6 +155,8 @@ class Transport extends EnhancedEventEmitter
* @emits close * @emits close
* @emits {producer: Producer} newproducer * @emits {producer: Producer} newproducer
* @emits {consumer: Consumer} newconsumer * @emits {consumer: Consumer} newconsumer
* @emits {producer: DataProducer} newdataproducer
* @emits {consumer: DataConsumer} newdataconsumer
*/ */
get observer() get observer()
{ {
...@@ -167,6 +200,23 @@ class Transport extends EnhancedEventEmitter ...@@ -167,6 +200,23 @@ class Transport extends EnhancedEventEmitter
} }
this._consumers.clear(); this._consumers.clear();
// Close every DataProducer.
for (const dataProducer of this._dataProducers.values())
{
dataProducer.transportClosed();
// Must tell the Router.
this.emit('@dataproducerclose', dataProducer);
}
this._dataProducers.clear();
// Close every DataConsumer.
for (const dataConsumer of this._dataConsumers.values())
{
dataConsumer.transportClosed();
}
this._dataConsumers.clear();
this.emit('@close'); this.emit('@close');
// Emit observer event. // Emit observer event.
...@@ -208,6 +258,23 @@ class Transport extends EnhancedEventEmitter ...@@ -208,6 +258,23 @@ class Transport extends EnhancedEventEmitter
} }
this._consumers.clear(); this._consumers.clear();
// Close every DataProducer.
for (const dataProducer of this._dataProducers.values())
{
dataProducer.transportClosed();
// NOTE: No need to tell the Router since it already knows (it has
// been closed in fact).
}
this._dataProducers.clear();
// Close every DataConsumer.
for (const dataConsumer of this._dataConsumers.values())
{
dataConsumer.transportClosed();
}
this._dataConsumers.clear();
this.safeEmit('routerclose'); this.safeEmit('routerclose');
// Emit observer event. // Emit observer event.
...@@ -437,6 +504,139 @@ class Transport extends EnhancedEventEmitter ...@@ -437,6 +504,139 @@ class Transport extends EnhancedEventEmitter
return consumer; return consumer;
} }
/**
* Create a DataProducer.
*
* @param {String} [id] - DataProducer id (just for PipeTransports).
* @param {RTCSctpStreamParameters} sctpStreamParameters - Remote SCTP stream
* parameters.
* @param {String} [label='']
* @param {String} [protocol='']
* @param {Object} [appData={}] - Custom app data.
*
* @async
* @returns {DataProducer}
*/
async produceData(
{
id = undefined,
sctpStreamParameters,
label = '',
protocol = '',
appData = {}
} = {}
)
{
logger.debug('produceData()');
if (id && this._dataProducers.has(id))
throw new TypeError(`a DataProducer with same id "${id}" already exists`);
else if (typeof sctpStreamParameters !== 'object')
throw new TypeError('missing sctpStreamParameters');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const internal = { ...this._internal, dataProducerId: id || uuidv4() };
const reqData = { sctpStreamParameters, label, protocol };
const data =
await this._channel.request('transport.produceData', internal, reqData);
const dataProducer = new DataProducer(
{
internal,
data,
channel : this._channel,
appData
});
this._dataProducers.set(dataProducer.id, dataProducer);
dataProducer.on('@close', () =>
{
this._dataProducers.delete(dataProducer.id);
this.emit('@dataproducerclose', dataProducer);
});
this.emit('@newdataproducer', dataProducer);
// Emit observer event.
this._observer.safeEmit('newdataproducer', dataProducer);
return dataProducer;
}
/**
* Create a DataConsumer.
*
* @param {String} dataProducerId
* @param {Object} [appData={}] - Custom app data.
*
* @async
* @virtual
* @returns {DataConsumer}
*/
async consumeData(
{
dataProducerId,
appData = {}
} = {}
)
{
logger.debug('consumeData()');
if (!dataProducerId || typeof dataProducerId !== 'string')
throw new TypeError('missing dataProducerId');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const dataProducer = this._getDataProducerById(dataProducerId);
if (!dataProducer)
throw Error(`DataProducer with id "${dataProducerId}" not found`);
const sctpStreamParameters = utils.clone(dataProducer.sctpStreamParameters);
const { label, protocol } = dataProducer;
// This may throw.
const sctpStreamId = this._getNextSctpStreamId();
this._sctpStreamIds[sctpStreamId] = true;
sctpStreamParameters.streamId = sctpStreamId;
const internal = { ...this._internal, dataConsumerId: uuidv4(), dataProducerId };
const reqData = { sctpStreamParameters, label, protocol };
const data =
await this._channel.request('transport.consumeData', internal, reqData);
const dataConsumer = new DataConsumer(
{
internal,
data,
channel : this._channel,
appData
});
this._dataConsumers.set(dataConsumer.id, dataConsumer);
dataConsumer.on('@close', () =>
{
this._dataConsumers.delete(dataConsumer.id);
this._sctpStreamIds[sctpStreamId] = false;
});
dataConsumer.on('@dataproducerclose', () =>
{
this._dataConsumers.delete(dataConsumer.id);
this._sctpStreamIds[sctpStreamId] = false;
});
// Emit observer event.
this._observer.safeEmit('newdataconsumer', dataConsumer);
return dataConsumer;
}
/** /**
* @private * @private
* @abstract * @abstract
...@@ -446,6 +646,38 @@ class Transport extends EnhancedEventEmitter ...@@ -446,6 +646,38 @@ class Transport extends EnhancedEventEmitter
// Should not happen. // Should not happen.
throw new Error('method not implemented in the subclass'); throw new Error('method not implemented in the subclass');
} }
_getNextSctpStreamId()
{
if (
!this._data.sctpParameters ||
typeof this._data.sctpParameters.MIS !== 'number'
)
{
throw new TypeError('missing data.sctpParameters.MIS');
}
const numStreams = this._data.sctpParameters.MIS;
if (!this._sctpStreamIds)
this._sctpStreamIds = Buffer.alloc(numStreams, false);
let sctpStreamId;
for (let idx = 0; idx < this._sctpStreamIds.length; ++idx)
{
sctpStreamId = (this._nextSctpStreamId + idx) % this._sctpStreamIds.length;
if (!this._sctpStreamIds[sctpStreamId])
{
this._nextSctpStreamId = sctpStreamId + 1;
return sctpStreamId;
}
}
throw new Error('no sctpStreamId available');
}
} }
module.exports = Transport; module.exports = Transport;
...@@ -11,13 +11,16 @@ class WebRtcTransport extends Transport ...@@ -11,13 +11,16 @@ class WebRtcTransport extends Transport
* @emits {iceState: String} icestatechange * @emits {iceState: String} icestatechange
* @emits {iceSelectedTuple: Object} iceselectedtuplechange * @emits {iceSelectedTuple: Object} iceselectedtuplechange
* @emits {dtlsState: String} dtlsstatechange * @emits {dtlsState: String} dtlsstatechange
* @emits {sctpState: String} sctpstatechange
*/ */
constructor({ data, ...params }) constructor(params)
{ {
super(params); super(params);
logger.debug('constructor()'); logger.debug('constructor()');
const { data } = params;
// WebRtcTransport data. // WebRtcTransport data.
// @type {Object} // @type {Object}
// - .iceRole // - .iceRole
...@@ -50,6 +53,12 @@ class WebRtcTransport extends Transport ...@@ -50,6 +53,12 @@ class WebRtcTransport extends Transport
// - .sha-512 // - .sha-512
// - .dtlsState // - .dtlsState
// - .dtlsRemoteCert // - .dtlsRemoteCert
// - .sctpParameters
// - .port
// - .OS
// - .MIS
// - .maxMessageSize
// - .sctpState
this._data = this._data =
{ {
iceRole : data.iceRole, iceRole : data.iceRole,
...@@ -59,7 +68,9 @@ class WebRtcTransport extends Transport ...@@ -59,7 +68,9 @@ class WebRtcTransport extends Transport
iceSelectedTuple : data.iceSelectedTuple, iceSelectedTuple : data.iceSelectedTuple,
dtlsParameters : data.dtlsParameters, dtlsParameters : data.dtlsParameters,
dtlsState : data.dtlsState, dtlsState : data.dtlsState,
dtlsRemoteCert : data.dtlsRemoteCert dtlsRemoteCert : data.dtlsRemoteCert,
sctpParameters : data.sctpParameters,
sctpState : data.sctpState
}; };
} }
...@@ -127,6 +138,22 @@ class WebRtcTransport extends Transport ...@@ -127,6 +138,22 @@ class WebRtcTransport extends Transport
return this._data.dtlsRemoteCert; return this._data.dtlsRemoteCert;
} }
/**
* @type {Object}
*/
get sctpParameters()
{
return this._data.sctpParameters;
}
/**
* @type {String}
*/
get sctpState()
{
return this._data.sctpState;
}
/** /**
* Observer. * Observer.
* *
...@@ -136,9 +163,12 @@ class WebRtcTransport extends Transport ...@@ -136,9 +163,12 @@ class WebRtcTransport extends Transport
* @emits close * @emits close
* @emits {producer: Producer} newproducer * @emits {producer: Producer} newproducer
* @emits {consumer: Consumer} newconsumer * @emits {consumer: Consumer} newconsumer
* @emits {producer: DataProducer} newdataproducer
* @emits {consumer: DataConsumer} newdataconsumer
* @emits {iceState: String} icestatechange * @emits {iceState: String} icestatechange
* @emits {iceSelectedTuple: Object} iceselectedtuplechange * @emits {iceSelectedTuple: Object} iceselectedtuplechange
* @emits {dtlsState: String} dtlsstatechange * @emits {dtlsState: String} dtlsstatechange
* @emits {sctpState: String} sctpstatechange
*/ */
get observer() get observer()
{ {
...@@ -159,6 +189,9 @@ class WebRtcTransport extends Transport ...@@ -159,6 +189,9 @@ class WebRtcTransport extends Transport
this._data.iceSelectedTuple = undefined; this._data.iceSelectedTuple = undefined;
this._data.dtlsState = 'closed'; this._data.dtlsState = 'closed';
if (this._data.sctpState)
this._data.sctpState = 'closed';
super.close(); super.close();
} }
...@@ -177,6 +210,9 @@ class WebRtcTransport extends Transport ...@@ -177,6 +210,9 @@ class WebRtcTransport extends Transport
this._data.iceSelectedTuple = undefined; this._data.iceSelectedTuple = undefined;
this._data.dtlsState = 'closed'; this._data.dtlsState = 'closed';
if (this._data.sctpState)
this._data.sctpState = 'closed';
super.routerClosed(); super.routerClosed();
} }
...@@ -293,6 +329,20 @@ class WebRtcTransport extends Transport ...@@ -293,6 +329,20 @@ class WebRtcTransport extends Transport
break; break;
} }
case 'sctpstatechange':
{
const { sctpState } = data;
this._data.sctpState = sctpState;
this.safeEmit('sctpstatechange', sctpState);
// Emit observer event.
this._observer.safeEmit('sctpstatechange', sctpState);
break;
}
default: default:
{ {
logger.error('ignoring unknown event "%s"', event); logger.error('ignoring unknown event "%s"', event);
......
...@@ -15,18 +15,16 @@ const DynamicPayloadTypes = ...@@ -15,18 +15,16 @@ const DynamicPayloadTypes =
* Generate RTP capabilities for the Router based on the given media codecs and * Generate RTP capabilities for the Router based on the given media codecs and
* mediasoup supported RTP capabilities. * mediasoup supported RTP capabilities.
* *
* @param {array<RTCRtpCodecCapability>} mediaCodecs * @param {array<RTCRtpCodecCapability>} [mediaCodecs]
* *
* @returns {RTCRtpCapabilities} * @returns {RTCRtpCapabilities}
* @throws {UnsupportedError} if codec not supported. * @throws {UnsupportedError} if codec not supported.
* @throws {Error} * @throws {Error}
*/ */
exports.generateRouterRtpCapabilities = function(mediaCodecs) exports.generateRouterRtpCapabilities = function(mediaCodecs = [])
{ {
if (!Array.isArray(mediaCodecs)) if (!Array.isArray(mediaCodecs))
throw new TypeError('mediaCodecs must be an Array'); throw new TypeError('mediaCodecs must be an Array');
else if (mediaCodecs.length === 0)
throw new TypeError('mediaCodecs cannot be empty');
const dynamicPayloadTypes = utils.clone(DynamicPayloadTypes); const dynamicPayloadTypes = utils.clone(DynamicPayloadTypes);
const supportedCodecs = supportedRtpCapabilities.codecs; const supportedCodecs = supportedRtpCapabilities.codecs;
......
...@@ -109,8 +109,7 @@ const supportedRtpCapabilities = ...@@ -109,8 +109,7 @@ const supportedRtpCapabilities =
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
] ]
}, },
{ {
...@@ -122,8 +121,7 @@ const supportedRtpCapabilities = ...@@ -122,8 +121,7 @@ const supportedRtpCapabilities =
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
] ]
}, },
{ {
...@@ -140,8 +138,7 @@ const supportedRtpCapabilities = ...@@ -140,8 +138,7 @@ const supportedRtpCapabilities =
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
] ]
}, },
{ {
...@@ -158,8 +155,7 @@ const supportedRtpCapabilities = ...@@ -158,8 +155,7 @@ const supportedRtpCapabilities =
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
] ]
}, },
{ {
...@@ -176,8 +172,7 @@ const supportedRtpCapabilities = ...@@ -176,8 +172,7 @@ const supportedRtpCapabilities =
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
] ]
}, },
{ {
...@@ -194,8 +189,7 @@ const supportedRtpCapabilities = ...@@ -194,8 +189,7 @@ const supportedRtpCapabilities =
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
] ]
} }
], ],
......
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
}, },
"devDependencies": { "devDependencies": {
"eslint": "^6.0.1", "eslint": "^6.0.1",
"eslint-plugin-jest": "^22.7.1", "eslint-plugin-jest": "^22.7.2",
"gulp": "^4.0.2", "gulp": "^4.0.2",
"gulp-clang-format": "^1.0.27", "gulp-clang-format": "^1.0.27",
"jest": "^24.8.0", "jest": "^24.8.0",
......
const { toBeType } = require('jest-tobetype');
const mediasoup = require('../');
const { createWorker } = mediasoup;
expect.extend({ toBeType });
let worker;
let router;
let transport1;
let transport2;
let dataProducer;
let dataConsumer;
const dataProducerParameters =
{
sctpStreamParameters :
{
streamId : 12345,
ordered : false,
maxPacketLifeTime : 5000
},
label : 'foo',
protocol : 'bar'
};
beforeAll(async () =>
{
worker = await createWorker();
router = await worker.createRouter();
transport1 = await router.createWebRtcTransport(
{
listenIps : [ '127.0.0.1' ],
enableSctp : true
});
transport2 = await router.createPlainRtpTransport(
{
listenIp : '127.0.0.1',
enableSctp : true
});
dataProducer = await transport1.produceData(dataProducerParameters);
});
afterAll(() => worker.close());
test('transport.consumeData() succeeds', async () =>
{
const onObserverNewDataConsumer = jest.fn();
transport2.observer.once('newdataconsumer', onObserverNewDataConsumer);
dataConsumer = await transport2.consumeData(
{
dataProducerId : dataProducer.id,
appData : { baz: 'LOL' }
});
expect(onObserverNewDataConsumer).toHaveBeenCalledTimes(1);
expect(onObserverNewDataConsumer).toHaveBeenCalledWith(dataConsumer);
expect(dataConsumer.id).toBeType('string');
expect(dataConsumer.dataProducerId).toBe(dataProducer.id);
expect(dataConsumer.closed).toBe(false);
expect(dataConsumer.sctpStreamParameters).toBeType('object');
expect(dataConsumer.sctpStreamParameters.streamId).toBeType('number');
expect(dataConsumer.sctpStreamParameters.ordered).toBe(false);
expect(dataConsumer.sctpStreamParameters.maxPacketLifeTime).toBe(5000);
expect(dataConsumer.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(dataConsumer.label).toBe('foo');
expect(dataConsumer.protocol).toBe('bar');
expect(dataConsumer.appData).toEqual({ baz: 'LOL' });
await expect(router.dump())
.resolves
.toMatchObject(
{
mapDataProducerIdDataConsumerIds : { [dataProducer.id]: [ dataConsumer.id ] },
mapDataConsumerIdDataProducerId : { [dataConsumer.id]: dataProducer.id }
});
await expect(transport2.dump())
.resolves
.toMatchObject(
{
id : transport2.id,
dataProducerIds : [],
dataConsumerIds : [ dataConsumer.id ]
});
}, 2000);
test('dataConsumer.dump() succeeds', async () =>
{
const data = await dataConsumer.dump();
expect(data.id).toBe(dataConsumer.id);
expect(data.sctpStreamParameters).toBeType('object');
expect(data.sctpStreamParameters.streamId)
.toBe(dataConsumer.sctpStreamParameters.streamId);
expect(data.sctpStreamParameters.ordered).toBe(false);
expect(data.sctpStreamParameters.maxPacketLifeTime).toBe(5000);
expect(data.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(data.label).toBe('foo');
expect(data.protocol).toBe('bar');
}, 2000);
test('dataConsumer.getStats() succeeds', async () =>
{
await expect(dataConsumer.getStats())
.resolves
.toStrictEqual(
[
{
type : 'data-consumer',
label : dataConsumer.label,
protocol : dataConsumer.protocol,
messagesSent : 0,
bytesSent : 0
}
]);
}, 2000);
test('dataConsumer.close() succeeds', async () =>
{
const onObserverClose = jest.fn();
dataConsumer.observer.once('close', onObserverClose);
dataConsumer.close();
expect(onObserverClose).toHaveBeenCalledTimes(1);
expect(dataConsumer.closed).toBe(true);
await expect(router.dump())
.resolves
.toMatchObject(
{
mapDataProducerIdDataConsumerIds : { [dataProducer.id]: [] },
mapDataConsumerIdDataProducerId : {}
});
await expect(transport2.dump())
.resolves
.toMatchObject(
{
id : transport2.id,
dataProducerIds : [],
dataConsumerIds : []
});
}, 2000);
test('Consumer methods reject if closed', async () =>
{
await expect(dataConsumer.dump())
.rejects
.toThrow(Error);
await expect(dataConsumer.getStats())
.rejects
.toThrow(Error);
}, 2000);
test('DataConsumer emits "dataproducerclose" if DataProducer is closed', async () =>
{
dataConsumer = await transport2.consumeData(
{
dataProducerId : dataProducer.id
});
const onObserverClose = jest.fn();
dataConsumer.observer.once('close', onObserverClose);
await new Promise((resolve) =>
{
dataConsumer.on('dataproducerclose', resolve);
dataProducer.close();
});
expect(onObserverClose).toHaveBeenCalledTimes(1);
expect(dataConsumer.closed).toBe(true);
}, 2000);
test('Consumer emits "transportclose" if Transport is closed', async () =>
{
dataProducer = await transport1.produceData(dataProducerParameters);
dataConsumer = await transport2.consumeData(
{
dataProducerId : dataProducer.id
});
const onObserverClose = jest.fn();
dataConsumer.observer.once('close', onObserverClose);
await new Promise((resolve) =>
{
dataConsumer.on('transportclose', resolve);
transport2.close();
});
expect(onObserverClose).toHaveBeenCalledTimes(1);
expect(dataConsumer.closed).toBe(true);
await expect(router.dump())
.resolves
.toMatchObject(
{
mapDataProducerIdDataConsumerIds : {},
mapDataConsumerIdDataProducerId : {}
});
}, 2000);
const { toBeType } = require('jest-tobetype');
const mediasoup = require('../');
const { createWorker } = mediasoup;
expect.extend({ toBeType });
let worker;
let router;
let transport1;
let transport2;
let dataProducer1;
let dataProducer2;
beforeAll(async () =>
{
worker = await createWorker();
router = await worker.createRouter();
transport1 = await router.createWebRtcTransport(
{
listenIps : [ '127.0.0.1' ],
enableSctp : true
});
transport2 = await router.createPlainRtpTransport(
{
listenIp : '127.0.0.1',
enableSctp : true
});
});
afterAll(() => worker.close());
test('transport1.produceData() succeeds', async () =>
{
const onObserverNewDataProducer = jest.fn();
transport1.observer.once('newdataproducer', onObserverNewDataProducer);
dataProducer1 = await transport1.produceData(
{
sctpStreamParameters :
{
streamId : 666
},
label : 'foo',
protocol : 'bar',
appData : { foo: 1, bar: '2' }
});
expect(onObserverNewDataProducer).toHaveBeenCalledTimes(1);
expect(onObserverNewDataProducer).toHaveBeenCalledWith(dataProducer1);
expect(dataProducer1.id).toBeType('string');
expect(dataProducer1.closed).toBe(false);
expect(dataProducer1.sctpStreamParameters).toBeType('object');
expect(dataProducer1.sctpStreamParameters.streamId).toBe(666);
expect(dataProducer1.sctpStreamParameters.ordered).toBe(true);
expect(dataProducer1.sctpStreamParameters.maxPacketLifeTime).toBe(undefined);
expect(dataProducer1.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(dataProducer1.label).toBe('foo');
expect(dataProducer1.protocol).toBe('bar');
expect(dataProducer1.appData).toEqual({ foo: 1, bar: '2' });
await expect(router.dump())
.resolves
.toMatchObject(
{
mapDataProducerIdDataConsumerIds : { [dataProducer1.id]: [] },
mapDataConsumerIdDataProducerId : {}
});
await expect(transport1.dump())
.resolves
.toMatchObject(
{
id : transport1.id,
dataProducerIds : [ dataProducer1.id ],
dataConsumerIds : []
});
}, 2000);
test('transport2.produceData() succeeds', async () =>
{
const onObserverNewDataProducer = jest.fn();
transport2.observer.once('newdataproducer', onObserverNewDataProducer);
dataProducer2 = await transport2.produceData(
{
sctpStreamParameters :
{
streamId : 777,
maxRetransmits : 3
},
label : 'foo',
protocol : 'bar',
appData : { foo: 1, bar: '2' }
});
expect(onObserverNewDataProducer).toHaveBeenCalledTimes(1);
expect(onObserverNewDataProducer).toHaveBeenCalledWith(dataProducer2);
expect(dataProducer2.id).toBeType('string');
expect(dataProducer2.closed).toBe(false);
expect(dataProducer2.sctpStreamParameters).toBeType('object');
expect(dataProducer2.sctpStreamParameters.streamId).toBe(777);
expect(dataProducer2.sctpStreamParameters.ordered).toBe(false);
expect(dataProducer2.sctpStreamParameters.maxPacketLifeTime).toBe(undefined);
expect(dataProducer2.sctpStreamParameters.maxRetransmits).toBe(3);
expect(dataProducer2.label).toBe('foo');
expect(dataProducer2.protocol).toBe('bar');
expect(dataProducer2.appData).toEqual({ foo: 1, bar: '2' });
await expect(router.dump())
.resolves
.toMatchObject(
{
mapDataProducerIdDataConsumerIds : { [dataProducer2.id]: [] },
mapDataConsumerIdDataProducerId : {}
});
await expect(transport2.dump())
.resolves
.toMatchObject(
{
id : transport2.id,
dataProducerIds : [ dataProducer2.id ],
dataConsumerIds : []
});
}, 2000);
test('transport1.produceData() with wrong arguments rejects with TypeError', async () =>
{
await expect(transport1.produceData({}))
.rejects
.toThrow(TypeError);
// Missing or empty sctpStreamParameters.streamId.
await expect(transport1.produceData(
{
sctpStreamParameters : { foo: 'foo' }
}))
.rejects
.toThrow(TypeError);
}, 2000);
test('transport.produceData() with already used streamId rejects with Error', async () =>
{
await expect(transport1.produceData(
{
sctpStreamParameters :
{
streamId : 666
}
}))
.rejects
.toThrow(Error);
}, 2000);
test('transport.produceData() with ordered and maxPacketLifeTime rejects with TypeError', async () =>
{
await expect(transport1.produceData(
{
sctpStreamParameters :
{
streamId : 999,
ordered : true,
maxPacketLifeTime : 4000
}
}))
.rejects
.toThrow(TypeError);
}, 2000);
test('dataProducer.dump() succeeds', async () =>
{
let data;
data = await dataProducer1.dump();
expect(data.id).toBe(dataProducer1.id);
expect(data.sctpStreamParameters).toBeType('object');
expect(data.sctpStreamParameters.streamId).toBe(666);
expect(data.sctpStreamParameters.ordered).toBe(true);
expect(data.sctpStreamParameters.maxPacketLifeTime).toBe(undefined);
expect(data.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(data.label).toBe('foo');
expect(data.protocol).toBe('bar');
data = await dataProducer2.dump();
expect(data.id).toBe(dataProducer2.id);
expect(data.sctpStreamParameters).toBeType('object');
expect(data.sctpStreamParameters.streamId).toBe(777);
expect(data.sctpStreamParameters.ordered).toBe(false);
expect(data.sctpStreamParameters.maxPacketLifeTime).toBe(undefined);
expect(data.sctpStreamParameters.maxRetransmits).toBe(3);
expect(data.label).toBe('foo');
expect(data.protocol).toBe('bar');
}, 2000);
test('dataProducer.getStats() succeeds', async () =>
{
await expect(dataProducer1.getStats())
.resolves
.toStrictEqual(
[
{
type : 'data-producer',
label : dataProducer1.label,
protocol : dataProducer1.protocol,
messagesReceived : 0,
bytesReceived : 0
}
]);
await expect(dataProducer2.getStats())
.resolves
.toStrictEqual(
[
{
type : 'data-producer',
label : dataProducer2.label,
protocol : dataProducer2.protocol,
messagesReceived : 0,
bytesReceived : 0
}
]);
}, 2000);
test('dataProducer.close() succeeds', async () =>
{
const onObserverClose = jest.fn();
dataProducer1.observer.once('close', onObserverClose);
dataProducer1.close();
expect(onObserverClose).toHaveBeenCalledTimes(1);
expect(dataProducer1.closed).toBe(true);
await expect(router.dump())
.resolves
.toMatchObject(
{
mapDataProducerIdDataConsumerIds : {},
mapDataConsumerIdDataProducerId : {}
});
await expect(transport1.dump())
.resolves
.toMatchObject(
{
id : transport1.id,
dataProducerIds : [],
dataConsumerIds : []
});
}, 2000);
test('DataProducer methods reject if closed', async () =>
{
await expect(dataProducer1.dump())
.rejects
.toThrow(Error);
await expect(dataProducer1.getStats())
.rejects
.toThrow(Error);
}, 2000);
test('DataProducer emits "transportclose" if Transport is closed', async () =>
{
const onObserverClose = jest.fn();
dataProducer2.observer.once('close', onObserverClose);
await new Promise((resolve) =>
{
dataProducer2.on('transportclose', resolve);
transport2.close();
});
expect(onObserverClose).toHaveBeenCalledTimes(1);
expect(dataProducer2.closed).toBe(true);
}, 2000);
...@@ -12,6 +12,8 @@ let audioProducer; ...@@ -12,6 +12,8 @@ let audioProducer;
let videoProducer; let videoProducer;
let transport2; let transport2;
let videoConsumer; let videoConsumer;
let dataProducer;
let dataConsumer;
const mediaCodecs = const mediaCodecs =
[ [
...@@ -119,6 +121,18 @@ const videoProducerParameters = ...@@ -119,6 +121,18 @@ const videoProducerParameters =
appData : { foo: 'bar2' } appData : { foo: 'bar2' }
}; };
const dataProducerParameters =
{
sctpStreamParameters :
{
streamId : 666,
ordered : false,
maxPacketLifeTime : 5000
},
label : 'foo',
protocol : 'bar'
};
const consumerDeviceCapabilities = const consumerDeviceCapabilities =
{ {
codecs : codecs :
...@@ -176,7 +190,11 @@ const consumerDeviceCapabilities = ...@@ -176,7 +190,11 @@ const consumerDeviceCapabilities =
preferredId : 10, preferredId : 10,
preferredEncrypt : false preferredEncrypt : false
} }
] ],
sctpCapabilities :
{
numSctpStreams : 2048
}
}; };
beforeAll(async () => beforeAll(async () =>
...@@ -186,14 +204,17 @@ beforeAll(async () => ...@@ -186,14 +204,17 @@ beforeAll(async () =>
router2 = await worker.createRouter({ mediaCodecs }); router2 = await worker.createRouter({ mediaCodecs });
transport1 = await router1.createWebRtcTransport( transport1 = await router1.createWebRtcTransport(
{ {
listenIps : [ '127.0.0.1' ] listenIps : [ '127.0.0.1' ],
enableSctp : true
}); });
transport2 = await router2.createWebRtcTransport( transport2 = await router2.createWebRtcTransport(
{ {
listenIps : [ '127.0.0.1' ] listenIps : [ '127.0.0.1' ],
enableSctp : true
}); });
audioProducer = await transport1.produce(audioProducerParameters); audioProducer = await transport1.produce(audioProducerParameters);
videoProducer = await transport1.produce(videoProducerParameters); videoProducer = await transport1.produce(videoProducerParameters);
dataProducer = await transport1.produceData(dataProducerParameters);
// Pause the videoProducer. // Pause the videoProducer.
await videoProducer.pause(); await videoProducer.pause();
...@@ -213,14 +234,14 @@ test('router.pipeToRouter() succeeds with audio', async () => ...@@ -213,14 +234,14 @@ test('router.pipeToRouter() succeeds with audio', async () =>
dump = await router1.dump(); dump = await router1.dump();
// There shoud should be two Transports in router1: // There shoud be two Transports in router1:
// - WebRtcTransport for audioProducer and videoProducer. // - WebRtcTransport for audioProducer and videoProducer.
// - PipeTransport between router1 and router2. // - PipeTransport between router1 and router2.
expect(dump.transportIds.length).toBe(2); expect(dump.transportIds.length).toBe(2);
dump = await router2.dump(); dump = await router2.dump();
// There shoud should be two Transports in router2: // There shoud be two Transports in router2:
// - WebRtcTransport for audioConsumer and videoConsumer. // - WebRtcTransport for audioConsumer and videoConsumer.
// - pipeTransport between router2 and router1. // - pipeTransport between router2 and router1.
expect(dump.transportIds.length).toBe(2); expect(dump.transportIds.length).toBe(2);
...@@ -498,3 +519,78 @@ test('producer.close() is transmitted to pipe Consumer', async () => ...@@ -498,3 +519,78 @@ test('producer.close() is transmitted to pipe Consumer', async () =>
expect(videoConsumer.closed).toBe(true); expect(videoConsumer.closed).toBe(true);
}, 2000); }, 2000);
test('router.pipeToRouter() succeeds with data', async () =>
{
let dump;
const { pipeDataConsumer, pipeDataProducer } = await router1.pipeToRouter(
{
dataProducerId : dataProducer.id,
router : router2
});
dump = await router1.dump();
// There shoud be two Transports in router1:
// - WebRtcTransport for audioProducer, videoProducer and dataProducer.
// - PipeTransport between router1 and router2.
expect(dump.transportIds.length).toBe(2);
dump = await router2.dump();
// There shoud be two Transports in router2:
// - WebRtcTransport for audioConsumer, videoConsumer and dataConsumer.
// - pipeTransport between router2 and router1.
expect(dump.transportIds.length).toBe(2);
expect(pipeDataConsumer.id).toBeType('string');
expect(pipeDataConsumer.closed).toBe(false);
expect(pipeDataConsumer.sctpStreamParameters).toBeType('object');
expect(pipeDataConsumer.sctpStreamParameters.streamId).toBeType('number');
expect(pipeDataConsumer.sctpStreamParameters.ordered).toBe(false);
expect(pipeDataConsumer.sctpStreamParameters.maxPacketLifeTime).toBe(5000);
expect(pipeDataConsumer.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(pipeDataConsumer.label).toBe('foo');
expect(pipeDataConsumer.protocol).toBe('bar');
expect(pipeDataProducer.id).toBe(dataProducer.id);
expect(pipeDataProducer.closed).toBe(false);
expect(pipeDataProducer.sctpStreamParameters).toBeType('object');
expect(pipeDataProducer.sctpStreamParameters.streamId).toBeType('number');
expect(pipeDataProducer.sctpStreamParameters.ordered).toBe(false);
expect(pipeDataProducer.sctpStreamParameters.maxPacketLifeTime).toBe(5000);
expect(pipeDataProducer.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(pipeDataProducer.label).toBe('foo');
expect(pipeDataProducer.protocol).toBe('bar');
}, 2000);
test('transport.dataConsume() for a pipe DataProducer succeeds', async () =>
{
dataConsumer = await transport2.consumeData(
{
dataProducerId : dataProducer.id
});
expect(dataConsumer.id).toBeType('string');
expect(dataConsumer.closed).toBe(false);
expect(dataConsumer.sctpStreamParameters).toBeType('object');
expect(dataConsumer.sctpStreamParameters.streamId).toBeType('number');
expect(dataConsumer.sctpStreamParameters.ordered).toBe(false);
expect(dataConsumer.sctpStreamParameters.maxPacketLifeTime).toBe(5000);
expect(dataConsumer.sctpStreamParameters.maxRetransmits).toBe(undefined);
expect(dataConsumer.label).toBe('foo');
expect(dataConsumer.protocol).toBe('bar');
}, 2000);
test('dataProducer.close() is transmitted to pipe DataConsumer', async () =>
{
await dataProducer.close();
expect(dataProducer.closed).toBe(true);
if (!dataConsumer.closed)
await new Promise((resolve) => dataConsumer.once('dataproducerclose', resolve));
expect(dataConsumer.closed).toBe(true);
}, 2000);
...@@ -73,9 +73,10 @@ test('router.createPlainRtpTransport() succeeds', async () => ...@@ -73,9 +73,10 @@ test('router.createPlainRtpTransport() succeeds', async () =>
// Create a separate transport here. // Create a separate transport here.
const transport1 = await router.createPlainRtpTransport( const transport1 = await router.createPlainRtpTransport(
{ {
listenIp : { ip: '127.0.0.1', announcedIp: '9.9.9.1' }, listenIp : { ip: '127.0.0.1', announcedIp: '9.9.9.1' },
rtcpMux : true, rtcpMux : true,
appData : { foo: 'bar' } enableSctp : true,
appData : { foo: 'bar' }
}); });
expect(onObserverNewTransport).toHaveBeenCalledTimes(1); expect(onObserverNewTransport).toHaveBeenCalledTimes(1);
...@@ -88,6 +89,15 @@ test('router.createPlainRtpTransport() succeeds', async () => ...@@ -88,6 +89,15 @@ test('router.createPlainRtpTransport() succeeds', async () =>
expect(transport1.tuple.localPort).toBeType('number'); expect(transport1.tuple.localPort).toBeType('number');
expect(transport1.tuple.protocol).toBe('udp'); expect(transport1.tuple.protocol).toBe('udp');
expect(transport1.rtcpTuple).toBe(undefined); expect(transport1.rtcpTuple).toBe(undefined);
expect(transport1.sctpParameters).toStrictEqual(
{
port : 5000,
OS : 1024,
MIS : 1024,
maxMessageSize : 262144,
isDataChannel : false
});
expect(transport1.sctpState).toBe('new');
const data1 = await transport1.dump(); const data1 = await transport1.dump();
...@@ -96,6 +106,8 @@ test('router.createPlainRtpTransport() succeeds', async () => ...@@ -96,6 +106,8 @@ test('router.createPlainRtpTransport() succeeds', async () =>
expect(data1.consumerIds).toEqual([]); expect(data1.consumerIds).toEqual([]);
expect(data1.tuple).toEqual(transport1.tuple); expect(data1.tuple).toEqual(transport1.tuple);
expect(data1.rtcpTuple).toEqual(transport1.rtcpTuple); expect(data1.rtcpTuple).toEqual(transport1.rtcpTuple);
expect(data1.sctpParameters).toEqual(transport1.sctpParameters);
expect(data1.sctpState).toBe('new');
expect(data1.rtpHeaderExtensions).toBeType('object'); expect(data1.rtpHeaderExtensions).toBeType('object');
expect(data1.rtpListener).toBeType('object'); expect(data1.rtpListener).toBeType('object');
...@@ -123,12 +135,15 @@ test('router.createPlainRtpTransport() succeeds', async () => ...@@ -123,12 +135,15 @@ test('router.createPlainRtpTransport() succeeds', async () =>
expect(transport2.rtcpTuple.localIp).toBe('127.0.0.1'); expect(transport2.rtcpTuple.localIp).toBe('127.0.0.1');
expect(transport2.rtcpTuple.localPort).toBeType('number'); expect(transport2.rtcpTuple.localPort).toBeType('number');
expect(transport2.rtcpTuple.protocol).toBe('udp'); expect(transport2.rtcpTuple.protocol).toBe('udp');
expect(transport2.sctpParameters).toBe(undefined);
expect(transport2.sctpState).toBe(undefined);
const data2 = await transport2.dump(); const data2 = await transport2.dump();
expect(data2.id).toBe(transport2.id); expect(data2.id).toBe(transport2.id);
expect(data2.tuple).toEqual(transport2.tuple); expect(data2.tuple).toEqual(transport2.tuple);
expect(data2.rtcpTuple).toEqual(transport2.rtcpTuple); expect(data2.rtcpTuple).toEqual(transport2.rtcpTuple);
expect(data2.sctpState).toBe(undefined);
}, 2000); }, 2000);
test('router.createPlainRtpTransport() with wrong arguments rejects with TypeError', async () => test('router.createPlainRtpTransport() with wrong arguments rejects with TypeError', async () =>
......
...@@ -7,8 +7,8 @@ expect.extend({ toBeType }); ...@@ -7,8 +7,8 @@ expect.extend({ toBeType });
let worker; let worker;
let router; let router;
let webRtcTransport; let transport1;
let plainRtpTransport; let transport2;
let audioProducer; let audioProducer;
let videoProducer; let videoProducer;
...@@ -48,11 +48,11 @@ beforeAll(async () => ...@@ -48,11 +48,11 @@ beforeAll(async () =>
{ {
worker = await createWorker(); worker = await createWorker();
router = await worker.createRouter({ mediaCodecs }); router = await worker.createRouter({ mediaCodecs });
webRtcTransport = await router.createWebRtcTransport( transport1 = await router.createWebRtcTransport(
{ {
listenIps : [ '127.0.0.1' ] listenIps : [ '127.0.0.1' ]
}); });
plainRtpTransport = await router.createPlainRtpTransport( transport2 = await router.createPlainRtpTransport(
{ {
listenIp : '127.0.0.1' listenIp : '127.0.0.1'
}); });
...@@ -60,13 +60,13 @@ beforeAll(async () => ...@@ -60,13 +60,13 @@ beforeAll(async () =>
afterAll(() => worker.close()); afterAll(() => worker.close());
test('webRtcTransport.produce() succeeds', async () => test('transport1.produce() succeeds', async () =>
{ {
const onObserverNewProducer = jest.fn(); const onObserverNewProducer = jest.fn();
webRtcTransport.observer.once('newproducer', onObserverNewProducer); transport1.observer.once('newproducer', onObserverNewProducer);
audioProducer = await webRtcTransport.produce( audioProducer = await transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : rtpParameters :
...@@ -129,23 +129,23 @@ test('webRtcTransport.produce() succeeds', async () => ...@@ -129,23 +129,23 @@ test('webRtcTransport.produce() succeeds', async () =>
mapConsumerIdProducerId : {} mapConsumerIdProducerId : {}
}); });
await expect(webRtcTransport.dump()) await expect(transport1.dump())
.resolves .resolves
.toMatchObject( .toMatchObject(
{ {
id : webRtcTransport.id, id : transport1.id,
producerIds : [ audioProducer.id ], producerIds : [ audioProducer.id ],
consumerIds : [] consumerIds : []
}); });
}, 2000); }, 2000);
test('plainRtpTransport.produce() succeeds', async () => test('transport2.produce() succeeds', async () =>
{ {
const onObserverNewProducer = jest.fn(); const onObserverNewProducer = jest.fn();
plainRtpTransport.observer.once('newproducer', onObserverNewProducer); transport2.observer.once('newproducer', onObserverNewProducer);
videoProducer = await plainRtpTransport.produce( videoProducer = await transport2.produce(
{ {
kind : 'video', kind : 'video',
rtpParameters : rtpParameters :
...@@ -223,19 +223,19 @@ test('plainRtpTransport.produce() succeeds', async () => ...@@ -223,19 +223,19 @@ test('plainRtpTransport.produce() succeeds', async () =>
mapConsumerIdProducerId : {} mapConsumerIdProducerId : {}
}); });
await expect(plainRtpTransport.dump()) await expect(transport2.dump())
.resolves .resolves
.toMatchObject( .toMatchObject(
{ {
id : plainRtpTransport.id, id : transport2.id,
producerIds : [ videoProducer.id ], producerIds : [ videoProducer.id ],
consumerIds : [] consumerIds : []
}); });
}, 2000); }, 2000);
test('webRtcTransport.produce() with wrong arguments rejects with TypeError', async () => test('transport1.produce() with wrong arguments rejects with TypeError', async () =>
{ {
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'chicken', kind : 'chicken',
rtpParameters : {} rtpParameters : {}
...@@ -243,7 +243,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as ...@@ -243,7 +243,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as
.rejects .rejects
.toThrow(TypeError); .toThrow(TypeError);
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : {} rtpParameters : {}
...@@ -252,7 +252,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as ...@@ -252,7 +252,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as
.toThrow(TypeError); .toThrow(TypeError);
// Missing or empty rtpParameters.codecs. // Missing or empty rtpParameters.codecs.
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : rtpParameters :
...@@ -267,7 +267,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as ...@@ -267,7 +267,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as
.toThrow(TypeError); .toThrow(TypeError);
// Missing or empty rtpParameters.encodings. // Missing or empty rtpParameters.encodings.
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'video', kind : 'video',
rtpParameters : rtpParameters :
...@@ -300,7 +300,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as ...@@ -300,7 +300,7 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as
.toThrow(TypeError); .toThrow(TypeError);
// Wrong apt in RTX codec. // Wrong apt in RTX codec.
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : rtpParameters :
...@@ -339,9 +339,9 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as ...@@ -339,9 +339,9 @@ test('webRtcTransport.produce() with wrong arguments rejects with TypeError', as
.toThrow(TypeError); .toThrow(TypeError);
}, 2000); }, 2000);
test('webRtcTransport.produce() with unsupported codecs rejects with UnsupportedError', async () => test('transport1.produce() with unsupported codecs rejects with UnsupportedError', async () =>
{ {
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : rtpParameters :
...@@ -363,7 +363,7 @@ test('webRtcTransport.produce() with unsupported codecs rejects with Unsupported ...@@ -363,7 +363,7 @@ test('webRtcTransport.produce() with unsupported codecs rejects with Unsupported
.toThrow(UnsupportedError); .toThrow(UnsupportedError);
// Invalid H264 profile-level-id. // Invalid H264 profile-level-id.
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'video', kind : 'video',
rtpParameters : rtpParameters :
...@@ -400,7 +400,7 @@ test('webRtcTransport.produce() with unsupported codecs rejects with Unsupported ...@@ -400,7 +400,7 @@ test('webRtcTransport.produce() with unsupported codecs rejects with Unsupported
test('transport.produce() with already used MID or SSRC rejects with Error', async () => test('transport.produce() with already used MID or SSRC rejects with Error', async () =>
{ {
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : rtpParameters :
...@@ -426,7 +426,7 @@ test('transport.produce() with already used MID or SSRC rejects with Error', asy ...@@ -426,7 +426,7 @@ test('transport.produce() with already used MID or SSRC rejects with Error', asy
.rejects .rejects
.toThrow(Error); .toThrow(Error);
await expect(plainRtpTransport.produce( await expect(transport2.produce(
{ {
kind : 'video', kind : 'video',
rtpParameters : rtpParameters :
...@@ -468,7 +468,7 @@ test('transport.produce() with already used MID or SSRC rejects with Error', asy ...@@ -468,7 +468,7 @@ test('transport.produce() with already used MID or SSRC rejects with Error', asy
test('transport.produce() with no MID and with single encoding without RID or SSRC rejects with Error', async () => test('transport.produce() with no MID and with single encoding without RID or SSRC rejects with Error', async () =>
{ {
await expect(webRtcTransport.produce( await expect(transport1.produce(
{ {
kind : 'audio', kind : 'audio',
rtpParameters : rtpParameters :
...@@ -671,11 +671,11 @@ test('producer.close() succeeds', async () => ...@@ -671,11 +671,11 @@ test('producer.close() succeeds', async () =>
mapConsumerIdProducerId : {} mapConsumerIdProducerId : {}
}); });
await expect(webRtcTransport.dump()) await expect(transport1.dump())
.resolves .resolves
.toMatchObject( .toMatchObject(
{ {
id : webRtcTransport.id, id : transport1.id,
producerIds : [], producerIds : [],
consumerIds : [] consumerIds : []
}); });
...@@ -709,7 +709,7 @@ test('Producer emits "transportclose" if Transport is closed', async () => ...@@ -709,7 +709,7 @@ test('Producer emits "transportclose" if Transport is closed', async () =>
await new Promise((resolve) => await new Promise((resolve) =>
{ {
videoProducer.on('transportclose', resolve); videoProducer.on('transportclose', resolve);
plainRtpTransport.close(); transport2.close();
}); });
expect(onObserverClose).toHaveBeenCalledTimes(1); expect(onObserverClose).toHaveBeenCalledTimes(1);
......
...@@ -69,12 +69,14 @@ test('worker.createRouter() succeeds', async () => ...@@ -69,12 +69,14 @@ test('worker.createRouter() succeeds', async () =>
.resolves .resolves
.toMatchObject( .toMatchObject(
{ {
id : router.id, id : router.id,
transportIds : [], transportIds : [],
rtpObserverIds : [], rtpObserverIds : [],
mapProducerIdConsumerIds : {}, mapProducerIdConsumerIds : {},
mapConsumerIdProducerId : {}, mapConsumerIdProducerId : {},
mapProducerIdObserverIds : {} mapProducerIdObserverIds : {},
mapDataProducerIdDataConsumerIds : {},
mapDataConsumerIdDataProducerId : {}
}); });
// Private API. // Private API.
...@@ -88,11 +90,11 @@ test('worker.createRouter() succeeds', async () => ...@@ -88,11 +90,11 @@ test('worker.createRouter() succeeds', async () =>
expect(worker._routers.size).toBe(0); expect(worker._routers.size).toBe(0);
}, 2000); }, 2000);
test('worker.createRouter() without mediaCodecs rejects with TypeError', async () => test('worker.createRouter() with wrong mediaCodecs rejects with TypeError', async () =>
{ {
worker = await createWorker(); worker = await createWorker();
await expect(worker.createRouter()) await expect(worker.createRouter({ mediaCodecs: {} }))
.rejects .rejects
.toThrow(TypeError); .toThrow(TypeError);
......
...@@ -78,9 +78,12 @@ test('router.createWebRtcTransport() succeeds', async () => ...@@ -78,9 +78,12 @@ test('router.createWebRtcTransport() succeeds', async () =>
{ ip: '0.0.0.0', announcedIp: '9.9.9.2' }, { ip: '0.0.0.0', announcedIp: '9.9.9.2' },
{ ip: '127.0.0.1', announcedIp: null } { ip: '127.0.0.1', announcedIp: null }
], ],
enableTcp : true, enableTcp : true,
preferUdp : true, preferUdp : true,
appData : { foo: 'bar' } enableSctp : true,
numSctpStreams : { OS: 2048, MIS: 2048 },
maxSctpMessageSize : 1000000,
appData : { foo: 'bar' }
}); });
expect(onObserverNewTransport).toHaveBeenCalledTimes(1); expect(onObserverNewTransport).toHaveBeenCalledTimes(1);
...@@ -93,6 +96,14 @@ test('router.createWebRtcTransport() succeeds', async () => ...@@ -93,6 +96,14 @@ test('router.createWebRtcTransport() succeeds', async () =>
expect(transport1.iceParameters.iceLite).toBe(true); expect(transport1.iceParameters.iceLite).toBe(true);
expect(transport1.iceParameters.usernameFragment).toBeType('string'); expect(transport1.iceParameters.usernameFragment).toBeType('string');
expect(transport1.iceParameters.password).toBeType('string'); expect(transport1.iceParameters.password).toBeType('string');
expect(transport1.sctpParameters).toStrictEqual(
{
port : 5000,
OS : 2048,
MIS : 2048,
maxMessageSize : 1000000,
isDataChannel : true
});
expect(transport1.iceCandidates).toBeType('array'); expect(transport1.iceCandidates).toBeType('array');
expect(transport1.iceCandidates.length).toBe(6); expect(transport1.iceCandidates.length).toBe(6);
...@@ -127,6 +138,7 @@ test('router.createWebRtcTransport() succeeds', async () => ...@@ -127,6 +138,7 @@ test('router.createWebRtcTransport() succeeds', async () =>
expect(iceCandidates[2].priority).toBeGreaterThan(iceCandidates[3].priority); expect(iceCandidates[2].priority).toBeGreaterThan(iceCandidates[3].priority);
expect(iceCandidates[4].priority).toBeGreaterThan(iceCandidates[3].priority); expect(iceCandidates[4].priority).toBeGreaterThan(iceCandidates[3].priority);
expect(iceCandidates[4].priority).toBeGreaterThan(iceCandidates[5].priority); expect(iceCandidates[4].priority).toBeGreaterThan(iceCandidates[5].priority);
expect(transport1.iceState).toBe('new'); expect(transport1.iceState).toBe('new');
expect(transport1.iceSelectedTuple).toBe(undefined); expect(transport1.iceSelectedTuple).toBe(undefined);
expect(transport1.dtlsParameters).toBeType('object'); expect(transport1.dtlsParameters).toBeType('object');
...@@ -134,6 +146,7 @@ test('router.createWebRtcTransport() succeeds', async () => ...@@ -134,6 +146,7 @@ test('router.createWebRtcTransport() succeeds', async () =>
expect(transport1.dtlsParameters.role).toBe('auto'); expect(transport1.dtlsParameters.role).toBe('auto');
expect(transport1.dtlsState).toBe('new'); expect(transport1.dtlsState).toBe('new');
expect(transport1.dtlsRemoteCert).toBe(undefined); expect(transport1.dtlsRemoteCert).toBe(undefined);
expect(transport1.sctpState).toBe('new');
const data1 = await transport1.dump(); const data1 = await transport1.dump();
...@@ -147,6 +160,8 @@ test('router.createWebRtcTransport() succeeds', async () => ...@@ -147,6 +160,8 @@ test('router.createWebRtcTransport() succeeds', async () =>
expect(data1.iceSelectedTuple).toEqual(transport1.iceSelectedTuple); expect(data1.iceSelectedTuple).toEqual(transport1.iceSelectedTuple);
expect(data1.dtlsParameters).toEqual(transport1.dtlsParameters); expect(data1.dtlsParameters).toEqual(transport1.dtlsParameters);
expect(data1.dtlsState).toBe(transport1.dtlsState); expect(data1.dtlsState).toBe(transport1.dtlsState);
expect(data1.sctpParameters).toEqual(transport1.sctpParameters);
expect(data1.sctpState).toBe(transport1.sctpState);
expect(data1.rtpHeaderExtensions).toBeType('object'); expect(data1.rtpHeaderExtensions).toBeType('object');
expect(data1.rtpListener).toBeType('object'); expect(data1.rtpListener).toBeType('object');
...@@ -183,6 +198,15 @@ test('router.createWebRtcTransport() with wrong arguments rejects with TypeError ...@@ -183,6 +198,15 @@ test('router.createWebRtcTransport() with wrong arguments rejects with TypeError
})) }))
.rejects .rejects
.toThrow(TypeError); .toThrow(TypeError);
await expect(router.createWebRtcTransport(
{
listenIps : [ '127.0.0.1' ],
enableSctp : true,
numSctpStreams : 'foo'
}))
.rejects
.toThrow(TypeError);
}, 2000); }, 2000);
test('router.createWebRtcTransport() with non bindable IP rejects with Error', async () => test('router.createWebRtcTransport() with non bindable IP rejects with Error', async () =>
...@@ -204,6 +228,7 @@ test('webRtcTransport.getStats() succeeds', async () => ...@@ -204,6 +228,7 @@ test('webRtcTransport.getStats() succeeds', async () =>
expect(data[0].iceRole).toBe('controlled'); expect(data[0].iceRole).toBe('controlled');
expect(data[0].iceState).toBe('new'); expect(data[0].iceState).toBe('new');
expect(data[0].dtlsState).toBe('new'); expect(data[0].dtlsState).toBe('new');
expect(data[0].sctpState).toBe(undefined);
expect(data[0].bytesReceived).toBe(0); expect(data[0].bytesReceived).toBe(0);
expect(data[0].bytesSent).toBe(0); expect(data[0].bytesSent).toBe(0);
expect(data[0].iceSelectedTuple).toBe(undefined); expect(data[0].iceSelectedTuple).toBe(undefined);
...@@ -374,6 +399,7 @@ test('WebRtcTransport methods reject if closed', async () => ...@@ -374,6 +399,7 @@ test('WebRtcTransport methods reject if closed', async () =>
expect(transport.iceState).toBe('closed'); expect(transport.iceState).toBe('closed');
expect(transport.iceSelectedTuple).toBe(undefined); expect(transport.iceSelectedTuple).toBe(undefined);
expect(transport.dtlsState).toBe('closed'); expect(transport.dtlsState).toBe('closed');
expect(transport.sctpState).toBe(undefined);
await expect(transport.dump()) await expect(transport.dump())
.rejects .rejects
...@@ -400,8 +426,11 @@ test('WebRtcTransport emits "routerclose" if Router is closed', async () => ...@@ -400,8 +426,11 @@ test('WebRtcTransport emits "routerclose" if Router is closed', async () =>
{ {
// We need different Router and WebRtcTransport instances here. // We need different Router and WebRtcTransport instances here.
const router2 = await worker.createRouter({ mediaCodecs }); const router2 = await worker.createRouter({ mediaCodecs });
const transport2 = const transport2 = await router2.createWebRtcTransport(
await router2.createWebRtcTransport({ listenIps: [ '127.0.0.1' ] }); {
listenIps : [ '127.0.0.1' ],
enableSctp : true
});
const onObserverClose = jest.fn(); const onObserverClose = jest.fn();
transport2.observer.once('close', onObserverClose); transport2.observer.once('close', onObserverClose);
...@@ -417,6 +446,7 @@ test('WebRtcTransport emits "routerclose" if Router is closed', async () => ...@@ -417,6 +446,7 @@ test('WebRtcTransport emits "routerclose" if Router is closed', async () =>
expect(transport2.iceState).toBe('closed'); expect(transport2.iceState).toBe('closed');
expect(transport2.iceSelectedTuple).toBe(undefined); expect(transport2.iceSelectedTuple).toBe(undefined);
expect(transport2.dtlsState).toBe('closed'); expect(transport2.dtlsState).toBe('closed');
expect(transport2.sctpState).toBe('closed');
}, 2000); }, 2000);
test('WebRtcTransport emits "routerclose" if Worker is closed', async () => test('WebRtcTransport emits "routerclose" if Worker is closed', async () =>
...@@ -436,4 +466,5 @@ test('WebRtcTransport emits "routerclose" if Worker is closed', async () => ...@@ -436,4 +466,5 @@ test('WebRtcTransport emits "routerclose" if Worker is closed', async () =>
expect(transport.iceState).toBe('closed'); expect(transport.iceState).toBe('closed');
expect(transport.iceSelectedTuple).toBe(undefined); expect(transport.iceSelectedTuple).toBe(undefined);
expect(transport.dtlsState).toBe('closed'); expect(transport.dtlsState).toBe('closed');
expect(transport.sctpState).toBe(undefined);
}, 2000); }, 2000);
...@@ -71,8 +71,7 @@ test('generateRouterRtpCapabilities() succeeds', () => ...@@ -71,8 +71,7 @@ test('generateRouterRtpCapabilities() succeeds', () =>
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
], ],
parameters : {} parameters : {}
}); });
...@@ -103,8 +102,7 @@ test('generateRouterRtpCapabilities() succeeds', () => ...@@ -103,8 +102,7 @@ test('generateRouterRtpCapabilities() succeeds', () =>
{ type: 'nack' }, { type: 'nack' },
{ type: 'nack', parameter: 'pli' }, { type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' }, { type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' }, { type: 'goog-remb' }
{ type: 'transport-cc' }
], ],
parameters : parameters :
{ {
......
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
'openssl_fips%': '', 'openssl_fips%': '',
'openssl_no_asm%': 1, # Must be defined in OpenSSL >= 1.1.0g. 'openssl_no_asm%': 1, # Must be defined in OpenSSL >= 1.1.0g.
'libopenssl': '<(PRODUCT_DIR)/libopenssl.a', 'libopenssl': '<(PRODUCT_DIR)/libopenssl.a',
# usrsctp variables.
'sctp_debug%': 'false',
# Others. # Others.
'clang%': 0, 'clang%': 0,
'mediasoup_asan%': 'false' 'mediasoup_asan%': 'false'
......
This source diff could not be displayed because it is too large. You can view the blob instead.
test/fixtures/lorem_ipsum.txt text eol=lf
...@@ -382,3 +382,10 @@ George Zhao <zhaozg@gmail.com> ...@@ -382,3 +382,10 @@ George Zhao <zhaozg@gmail.com>
Kyle Edwards <kyle.edwards@kitware.com> Kyle Edwards <kyle.edwards@kitware.com>
ken-cunningham-webuse <ken.cunningham.webuse@gmail.com> ken-cunningham-webuse <ken.cunningham.webuse@gmail.com>
Kelvin Jin <kelvinjin@google.com> Kelvin Jin <kelvinjin@google.com>
Leorize <leorize+oss@disroot.org>
Vlad A <vladmore@gmail.com>
Niels Lohmann <mail@nlohmann.me>
Jenil Christo <jenilchristo5@gmail.com>
Evgeny Ermakov <evgeny.v.ermakov@gmail.com>
gengjiawen <technicalcute@gmail.com>
Leo Chung <gewalalb@gmail.com>
# TODO: determine CMAKE_SYSTEM_NAME on OS/390. Currently assumes "OS/390". # TODO: determine CMAKE_SYSTEM_NAME on OS/390. Currently assumes "OS/390".
cmake_minimum_required(VERSION 3.0) cmake_minimum_required(VERSION 3.0)
project(libuv) project(libuv)
enable_testing()
if(MSVC) if(MSVC)
list(APPEND uv_cflags /W4) list(APPEND uv_cflags /W4)
...@@ -137,6 +136,7 @@ set(uv_test_sources ...@@ -137,6 +136,7 @@ set(uv_test_sources
test/test-tcp-read-stop.c test/test-tcp-read-stop.c
test/test-tcp-shutdown-after-write.c test/test-tcp-shutdown-after-write.c
test/test-tcp-try-write.c test/test-tcp-try-write.c
test/test-tcp-try-write-error.c
test/test-tcp-unexpected-read.c test/test-tcp-unexpected-read.c
test/test-tcp-write-after-connect.c test/test-tcp-write-after-connect.c
test/test-tcp-write-fail.c test/test-tcp-write-fail.c
...@@ -260,8 +260,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Android") ...@@ -260,8 +260,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Android")
src/unix/linux-syscalls.c src/unix/linux-syscalls.c
src/unix/procfs-exepath.c src/unix/procfs-exepath.c
src/unix/pthread-fixes.c src/unix/pthread-fixes.c
src/unix/sysinfo-loadavg.c src/unix/sysinfo-loadavg.c)
src/unix/sysinfo-memory.c)
endif() endif()
if(APPLE OR CMAKE_SYSTEM_NAME MATCHES "Android|Linux|OS/390") if(APPLE OR CMAKE_SYSTEM_NAME MATCHES "Android|Linux|OS/390")
...@@ -350,8 +349,11 @@ target_compile_options(uv_a PRIVATE ${uv_cflags}) ...@@ -350,8 +349,11 @@ target_compile_options(uv_a PRIVATE ${uv_cflags})
target_include_directories(uv_a PRIVATE include src) target_include_directories(uv_a PRIVATE include src)
target_link_libraries(uv_a ${uv_libraries}) target_link_libraries(uv_a ${uv_libraries})
if(BUILD_TESTING) option(libuv_buildtests "Build the unit tests when BUILD_TESTING is enabled." ON)
include(CTest)
include(CTest)
if(BUILD_TESTING AND libuv_buildtests)
enable_testing()
add_executable(uv_run_tests ${uv_test_sources}) add_executable(uv_run_tests ${uv_test_sources})
target_compile_definitions(uv_run_tests target_compile_definitions(uv_run_tests
PRIVATE ${uv_defines} USING_UV_SHARED=1) PRIVATE ${uv_defines} USING_UV_SHARED=1)
......
2019.05.22, Version 1.29.1 (Stable) 2019.07.03, Version 1.30.1 (Stable)
Changes since version 1.30.0:
* doc: fix incorrect versionchanged (cjihrig)
* test: allow UV_ECONNRESET in tcp_try_write_error (cjihrig)
* unix: add uv_get_constrained_memory() cygwin stub (cjihrig)
* build: fix android cmake build (Ben Noordhuis)
* unix: squelch -Wcast-function-type warning (Ben Noordhuis)
* build: fix compile error with uClibc (zlargon)
2019.06.28, Version 1.30.0 (Stable), 365b6f2a0eacda1ff52be8e57ab9381cfddc5dbb
Changes since version 1.29.1:
* darwin: fall back to F_BARRIERFSYNC (Ben Noordhuis)
* darwin: add 32 bit close$NOCANCEL implementation (ken-cunningham-webuse)
* build, core, unix: add support for Haiku (Leorize)
* darwin,linux: more conservative minimum stack size (Ben Noordhuis)
* threadpool: increase UV_THREADPOOL_SIZE limit (Vlad A)
* unix: return actual error from `uv_try_write()` (Anna Henningsen)
* darwin: fix build error with macos 10.10 (Ben Noordhuis)
* unix: make uv_cwd() report UV_ENOBUFS (Ben Noordhuis)
* unix: make uv_fs_read() fill all buffers (Ben Noordhuis)
* test: give hrtime test a custom 10s timeout (Ben Noordhuis)
* fs: fix uv_fs_copyfile if same src and dst (Santiago Gimeno)
* build: add cmake option to skip building tests (Niels Lohmann)
* doc: add link to nodejs.org (Jenil Christo)
* unix: fix a comment typo in signal.c (Evgeny Ermakov)
* unix: remove redundant cast in process.c (gengjiawen)
* doc: fix wrong mutex function prototypes (Leo Chung)
2019.05.22, Version 1.29.1 (Stable), d16e6094e1eb3b0b5981ef1dd7e03ec4d466944d
Changes since version 1.29.0: Changes since version 1.29.0:
......
...@@ -117,6 +117,7 @@ endif # WINNT ...@@ -117,6 +117,7 @@ endif # WINNT
EXTRA_DIST = test/fixtures/empty_file \ EXTRA_DIST = test/fixtures/empty_file \
test/fixtures/load_error.node \ test/fixtures/load_error.node \
test/fixtures/lorem_ipsum.txt \
include \ include \
docs \ docs \
img \ img \
...@@ -272,6 +273,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \ ...@@ -272,6 +273,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \
test/test-tcp-writealot.c \ test/test-tcp-writealot.c \
test/test-tcp-write-fail.c \ test/test-tcp-write-fail.c \
test/test-tcp-try-write.c \ test/test-tcp-try-write.c \
test/test-tcp-try-write-error.c \
test/test-tcp-write-queue-order.c \ test/test-tcp-write-queue-order.c \
test/test-thread-equal.c \ test/test-thread-equal.c \
test/test-thread.c \ test/test-thread.c \
...@@ -320,6 +322,10 @@ test_run_tests_CFLAGS += -D_ALL_SOURCE \ ...@@ -320,6 +322,10 @@ test_run_tests_CFLAGS += -D_ALL_SOURCE \
-D_LINUX_SOURCE_COMPAT -D_LINUX_SOURCE_COMPAT
endif endif
if HAIKU
test_run_tests_CFLAGS += -D_BSD_SOURCE
endif
if LINUX if LINUX
test_run_tests_CFLAGS += -D_GNU_SOURCE test_run_tests_CFLAGS += -D_GNU_SOURCE
endif endif
...@@ -409,6 +415,17 @@ libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \ ...@@ -409,6 +415,17 @@ libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
test_run_tests_LDFLAGS += -lutil test_run_tests_LDFLAGS += -lutil
endif endif
if HAIKU
uvinclude_HEADERS += include/uv/posix.h
libuv_la_CFLAGS += -D_BSD_SOURCE
libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
src/unix/haiku.c \
src/unix/no-fsevents.c \
src/unix/no-proctitle.c \
src/unix/posix-hrtime.c \
src/unix/posix-poll.c
endif
if HURD if HURD
uvinclude_HEADERS += include/uv/posix.h uvinclude_HEADERS += include/uv/posix.h
libuv_la_SOURCES += src/unix/no-fsevents.c \ libuv_la_SOURCES += src/unix/no-fsevents.c \
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
AC_PREREQ(2.57) AC_PREREQ(2.57)
AC_INIT([libuv], [1.29.1], [https://github.com/libuv/libuv/issues]) AC_INIT([libuv], [1.30.1], [https://github.com/libuv/libuv/issues])
AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_MACRO_DIR([m4])
m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/libuv-extra-automake-flags.m4])
m4_include([m4/as_case.m4]) m4_include([m4/as_case.m4])
...@@ -56,6 +56,7 @@ AM_CONDITIONAL([CYGWIN], [AS_CASE([$host_os],[cygwin*], [true], [false]) ...@@ -56,6 +56,7 @@ AM_CONDITIONAL([CYGWIN], [AS_CASE([$host_os],[cygwin*], [true], [false])
AM_CONDITIONAL([DARWIN], [AS_CASE([$host_os],[darwin*], [true], [false])]) AM_CONDITIONAL([DARWIN], [AS_CASE([$host_os],[darwin*], [true], [false])])
AM_CONDITIONAL([DRAGONFLY],[AS_CASE([$host_os],[dragonfly*], [true], [false])]) AM_CONDITIONAL([DRAGONFLY],[AS_CASE([$host_os],[dragonfly*], [true], [false])])
AM_CONDITIONAL([FREEBSD], [AS_CASE([$host_os],[*freebsd*], [true], [false])]) AM_CONDITIONAL([FREEBSD], [AS_CASE([$host_os],[*freebsd*], [true], [false])])
AM_CONDITIONAL([HAIKU], [AS_CASE([$host_os],[haiku], [true], [false])])
AM_CONDITIONAL([HURD], [AS_CASE([$host_os],[gnu*], [true], [false])]) AM_CONDITIONAL([HURD], [AS_CASE([$host_os],[gnu*], [true], [false])])
AM_CONDITIONAL([LINUX], [AS_CASE([$host_os],[linux*], [true], [false])]) AM_CONDITIONAL([LINUX], [AS_CASE([$host_os],[linux*], [true], [false])])
AM_CONDITIONAL([MSYS], [AS_CASE([$host_os],[msys*], [true], [false])]) AM_CONDITIONAL([MSYS], [AS_CASE([$host_os],[msys*], [true], [false])])
...@@ -71,6 +72,9 @@ AS_CASE([$host_os], [netbsd*], [AC_CHECK_LIB([kvm], [kvm_open])]) ...@@ -71,6 +72,9 @@ AS_CASE([$host_os], [netbsd*], [AC_CHECK_LIB([kvm], [kvm_open])])
AS_CASE([$host_os], [kfreebsd*], [ AS_CASE([$host_os], [kfreebsd*], [
LIBS="$LIBS -lfreebsd-glue" LIBS="$LIBS -lfreebsd-glue"
]) ])
AS_CASE([$host_os], [haiku], [
LIBS="$LIBS -lnetwork"
])
AC_CHECK_HEADERS([sys/ahafs_evProds.h]) AC_CHECK_HEADERS([sys/ahafs_evProds.h])
AC_CONFIG_FILES([Makefile libuv.pc]) AC_CONFIG_FILES([Makefile libuv.pc])
AC_CONFIG_LINKS([test/fixtures/empty_file:test/fixtures/empty_file]) AC_CONFIG_LINKS([test/fixtures/empty_file:test/fixtures/empty_file])
......
...@@ -4,9 +4,11 @@ ...@@ -4,9 +4,11 @@
Design overview Design overview
=============== ===============
libuv is cross-platform support library which was originally written for NodeJS. It's designed libuv is cross-platform support library which was originally written for `Node.js`_. It's designed
around the event-driven asynchronous I/O model. around the event-driven asynchronous I/O model.
.. _Node.js: https://nodejs.org
The library provides much more than a simple abstraction over different I/O polling mechanisms: The library provides much more than a simple abstraction over different I/O polling mechanisms:
'handles' and 'streams' provide a high level abstraction for sockets and other entities; 'handles' and 'streams' provide a high level abstraction for sockets and other entities;
cross-platform file I/O and threading functionality is also provided, amongst other things. cross-platform file I/O and threading functionality is also provided, amongst other things.
......
...@@ -77,7 +77,7 @@ The mutex functions are a **direct** map to the pthread equivalents. ...@@ -77,7 +77,7 @@ The mutex functions are a **direct** map to the pthread equivalents.
.. rubric:: libuv mutex functions .. rubric:: libuv mutex functions
.. literalinclude:: ../../../include/uv.h .. literalinclude:: ../../../include/uv.h
:lines: 1355-1360 :lines: 1575-1580
The ``uv_mutex_init()``, ``uv_mutex_init_recursive()`` and ``uv_mutex_trylock()`` The ``uv_mutex_init()``, ``uv_mutex_init_recursive()`` and ``uv_mutex_trylock()``
functions will return 0 on success, and an error code otherwise. functions will return 0 on success, and an error code otherwise.
......
...@@ -10,7 +10,9 @@ operations, as well as getaddrinfo and getnameinfo requests. ...@@ -10,7 +10,9 @@ operations, as well as getaddrinfo and getnameinfo requests.
Its default size is 4, but it can be changed at startup time by setting the Its default size is 4, but it can be changed at startup time by setting the
``UV_THREADPOOL_SIZE`` environment variable to any value (the absolute maximum ``UV_THREADPOOL_SIZE`` environment variable to any value (the absolute maximum
is 128). is 1024).
.. versionchanged:: 1.30.0 the maximum UV_THREADPOOL_SIZE allowed was increased from 128 to 1024.
The threadpool is global and shared across all event loops. When a particular The threadpool is global and shared across all event loops. When a particular
function makes use of the threadpool (i.e. when using :c:func:`uv_queue_work`) function makes use of the threadpool (i.e. when using :c:func:`uv_queue_work`)
......
...@@ -66,6 +66,8 @@ ...@@ -66,6 +66,8 @@
defined(__MSYS__) || \ defined(__MSYS__) || \
defined(__GNU__) defined(__GNU__)
# include "uv/posix.h" # include "uv/posix.h"
#elif defined(__HAIKU__)
# include "uv/posix.h"
#endif #endif
#ifndef NI_MAXHOST #ifndef NI_MAXHOST
......
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
*/ */
#define UV_VERSION_MAJOR 1 #define UV_VERSION_MAJOR 1
#define UV_VERSION_MINOR 29 #define UV_VERSION_MINOR 30
#define UV_VERSION_PATCH 1 #define UV_VERSION_PATCH 1
#define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_IS_RELEASE 1
#define UV_VERSION_SUFFIX "" #define UV_VERSION_SUFFIX ""
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
#include <stdlib.h> #include <stdlib.h>
#define MAX_THREADPOOL_SIZE 128 #define MAX_THREADPOOL_SIZE 1024
static uv_once_t once = UV_ONCE_INIT; static uv_once_t once = UV_ONCE_INIT;
static uv_cond_t cond; static uv_cond_t cond;
......
...@@ -31,6 +31,10 @@ ...@@ -31,6 +31,10 @@
#include <net/if_dl.h> #include <net/if_dl.h>
#endif #endif
#if defined(__HAIKU__)
#define IFF_RUNNING IFF_LINK
#endif
static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) { static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) {
if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING))) if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
return 1; return 1;
...@@ -45,7 +49,8 @@ static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) { ...@@ -45,7 +49,8 @@ static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) {
if (exclude_type == UV__EXCLUDE_IFPHYS) if (exclude_type == UV__EXCLUDE_IFPHYS)
return (ent->ifa_addr->sa_family != AF_LINK); return (ent->ifa_addr->sa_family != AF_LINK);
#endif #endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) || \
defined(__HAIKU__)
/* /*
* On BSD getifaddrs returns information related to the raw underlying * On BSD getifaddrs returns information related to the raw underlying
* devices. We're not interested in this information. * devices. We're not interested in this information.
......
...@@ -526,8 +526,13 @@ int uv__close_nocancel(int fd) { ...@@ -526,8 +526,13 @@ int uv__close_nocancel(int fd) {
#if defined(__APPLE__) #if defined(__APPLE__)
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension" #pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension"
#if defined(__LP64__)
extern int close$NOCANCEL(int); extern int close$NOCANCEL(int);
return close$NOCANCEL(fd); return close$NOCANCEL(fd);
#else
extern int close$NOCANCEL$UNIX2003(int);
return close$NOCANCEL$UNIX2003(fd);
#endif
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#elif defined(__linux__) #elif defined(__linux__)
return syscall(SYS_close, fd); return syscall(SYS_close, fd);
...@@ -579,7 +584,7 @@ int uv__nonblock_ioctl(int fd, int set) { ...@@ -579,7 +584,7 @@ int uv__nonblock_ioctl(int fd, int set) {
} }
#if !defined(__CYGWIN__) && !defined(__MSYS__) #if !defined(__CYGWIN__) && !defined(__MSYS__) && !defined(__HAIKU__)
int uv__cloexec_ioctl(int fd, int set) { int uv__cloexec_ioctl(int fd, int set) {
int r; int r;
...@@ -696,16 +701,38 @@ ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) { ...@@ -696,16 +701,38 @@ ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
int uv_cwd(char* buffer, size_t* size) { int uv_cwd(char* buffer, size_t* size) {
char scratch[1 + UV__PATH_MAX];
if (buffer == NULL || size == NULL) if (buffer == NULL || size == NULL)
return UV_EINVAL; return UV_EINVAL;
if (getcwd(buffer, *size) == NULL) /* Try to read directly into the user's buffer first... */
if (getcwd(buffer, *size) != NULL)
goto fixup;
if (errno != ERANGE)
return UV__ERR(errno);
/* ...or into scratch space if the user's buffer is too small
* so we can report how much space to provide on the next try.
*/
if (getcwd(scratch, sizeof(scratch)) == NULL)
return UV__ERR(errno); return UV__ERR(errno);
buffer = scratch;
fixup:
*size = strlen(buffer); *size = strlen(buffer);
if (*size > 1 && buffer[*size - 1] == '/') { if (*size > 1 && buffer[*size - 1] == '/') {
buffer[*size-1] = '\0'; *size -= 1;
(*size)--; buffer[*size] = '\0';
}
if (buffer == scratch) {
*size += 1;
return UV_ENOBUFS;
} }
return 0; return 0;
...@@ -947,7 +974,7 @@ int uv_getrusage(uv_rusage_t* rusage) { ...@@ -947,7 +974,7 @@ int uv_getrusage(uv_rusage_t* rusage) {
rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec; rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec; rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
#if !defined(__MVS__) #if !defined(__MVS__) && !defined(__HAIKU__)
rusage->ru_maxrss = usage.ru_maxrss; rusage->ru_maxrss = usage.ru_maxrss;
rusage->ru_ixrss = usage.ru_ixrss; rusage->ru_ixrss = usage.ru_ixrss;
rusage->ru_idrss = usage.ru_idrss; rusage->ru_idrss = usage.ru_idrss;
......
...@@ -52,3 +52,7 @@ void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) { ...@@ -52,3 +52,7 @@ void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
(void)cpu_infos; (void)cpu_infos;
(void)count; (void)count;
} }
uint64_t uv_get_constrained_memory(void) {
return 0; /* Memory constraints are unknown. */
}
...@@ -160,12 +160,15 @@ static ssize_t uv__fs_fsync(uv_fs_t* req) { ...@@ -160,12 +160,15 @@ static ssize_t uv__fs_fsync(uv_fs_t* req) {
* to the drive platters. This is in contrast to Linux's fdatasync and fsync * to the drive platters. This is in contrast to Linux's fdatasync and fsync
* which do, according to recent man pages. F_FULLFSYNC is Apple's equivalent * which do, according to recent man pages. F_FULLFSYNC is Apple's equivalent
* for flushing buffered data to permanent storage. If F_FULLFSYNC is not * for flushing buffered data to permanent storage. If F_FULLFSYNC is not
* supported by the file system we should fall back to fsync(). This is the * supported by the file system we fall back to F_BARRIERFSYNC or fsync().
* same approach taken by sqlite. * This is the same approach taken by sqlite, except sqlite does not issue
* an F_BARRIERFSYNC call.
*/ */
int r; int r;
r = fcntl(req->file, F_FULLFSYNC); r = fcntl(req->file, F_FULLFSYNC);
if (r != 0)
r = fcntl(req->file, 85 /* F_BARRIERFSYNC */); /* fsync + barrier */
if (r != 0) if (r != 0)
r = fsync(req->file); r = fsync(req->file);
return r; return r;
...@@ -189,7 +192,8 @@ static ssize_t uv__fs_fdatasync(uv_fs_t* req) { ...@@ -189,7 +192,8 @@ static ssize_t uv__fs_fdatasync(uv_fs_t* req) {
static ssize_t uv__fs_futime(uv_fs_t* req) { static ssize_t uv__fs_futime(uv_fs_t* req) {
#if defined(__linux__) \ #if defined(__linux__) \
|| defined(_AIX71) || defined(_AIX71) \
|| defined(__HAIKU__)
/* utimesat() has nanosecond resolution but we stick to microseconds /* utimesat() has nanosecond resolution but we stick to microseconds
* for the sake of consistency with other platforms. * for the sake of consistency with other platforms.
*/ */
...@@ -274,6 +278,54 @@ static ssize_t uv__fs_open(uv_fs_t* req) { ...@@ -274,6 +278,54 @@ static ssize_t uv__fs_open(uv_fs_t* req) {
} }
static ssize_t uv__fs_preadv(uv_file fd,
uv_buf_t* bufs,
unsigned int nbufs,
off_t off) {
uv_buf_t* buf;
uv_buf_t* end;
ssize_t result;
ssize_t rc;
size_t pos;
assert(nbufs > 0);
result = 0;
pos = 0;
buf = bufs + 0;
end = bufs + nbufs;
for (;;) {
do
rc = pread(fd, buf->base + pos, buf->len - pos, off + result);
while (rc == -1 && errno == EINTR);
if (rc == 0)
break;
if (rc == -1 && result == 0)
return UV__ERR(errno);
if (rc == -1)
break; /* We read some data so return that, ignore the error. */
pos += rc;
result += rc;
if (pos < buf->len)
continue;
pos = 0;
buf += 1;
if (buf == end)
break;
}
return result;
}
static ssize_t uv__fs_read(uv_fs_t* req) { static ssize_t uv__fs_read(uv_fs_t* req) {
#if defined(__linux__) #if defined(__linux__)
static int no_preadv; static int no_preadv;
...@@ -303,7 +355,7 @@ static ssize_t uv__fs_read(uv_fs_t* req) { ...@@ -303,7 +355,7 @@ static ssize_t uv__fs_read(uv_fs_t* req) {
if (no_preadv) retry: if (no_preadv) retry:
# endif # endif
{ {
result = pread(req->file, req->bufs[0].base, req->bufs[0].len, req->off); result = uv__fs_preadv(req->file, req->bufs, req->nbufs, req->off);
} }
# if defined(__linux__) # if defined(__linux__)
else { else {
...@@ -467,22 +519,13 @@ static int uv__fs_closedir(uv_fs_t* req) { ...@@ -467,22 +519,13 @@ static int uv__fs_closedir(uv_fs_t* req) {
return 0; return 0;
} }
#if defined(_POSIX_PATH_MAX)
# define UV__FS_PATH_MAX _POSIX_PATH_MAX
#elif defined(PATH_MAX)
# define UV__FS_PATH_MAX PATH_MAX
#else
# define UV__FS_PATH_MAX_FALLBACK 8192
# define UV__FS_PATH_MAX UV__FS_PATH_MAX_FALLBACK
#endif
static ssize_t uv__fs_pathmax_size(const char* path) { static ssize_t uv__fs_pathmax_size(const char* path) {
ssize_t pathmax; ssize_t pathmax;
pathmax = pathconf(path, _PC_PATH_MAX); pathmax = pathconf(path, _PC_PATH_MAX);
if (pathmax == -1) if (pathmax == -1)
pathmax = UV__FS_PATH_MAX; pathmax = UV__PATH_MAX;
return pathmax; return pathmax;
} }
...@@ -493,7 +536,9 @@ static ssize_t uv__fs_readlink(uv_fs_t* req) { ...@@ -493,7 +536,9 @@ static ssize_t uv__fs_readlink(uv_fs_t* req) {
char* buf; char* buf;
char* newbuf; char* newbuf;
#if defined(UV__FS_PATH_MAX_FALLBACK) #if defined(_POSIX_PATH_MAX) || defined(PATH_MAX)
maxlen = uv__fs_pathmax_size(req->path);
#else
/* We may not have a real PATH_MAX. Read size of link. */ /* We may not have a real PATH_MAX. Read size of link. */
struct stat st; struct stat st;
int ret; int ret;
...@@ -511,8 +556,6 @@ static ssize_t uv__fs_readlink(uv_fs_t* req) { ...@@ -511,8 +556,6 @@ static ssize_t uv__fs_readlink(uv_fs_t* req) {
for some symlinks, such as those in /proc or /sys. */ for some symlinks, such as those in /proc or /sys. */
if (maxlen == 0) if (maxlen == 0)
maxlen = uv__fs_pathmax_size(req->path); maxlen = uv__fs_pathmax_size(req->path);
#else
maxlen = uv__fs_pathmax_size(req->path);
#endif #endif
buf = uv__malloc(maxlen); buf = uv__malloc(maxlen);
...@@ -796,7 +839,8 @@ static ssize_t uv__fs_sendfile(uv_fs_t* req) { ...@@ -796,7 +839,8 @@ static ssize_t uv__fs_sendfile(uv_fs_t* req) {
static ssize_t uv__fs_utime(uv_fs_t* req) { static ssize_t uv__fs_utime(uv_fs_t* req) {
#if defined(__linux__) \ #if defined(__linux__) \
|| defined(_AIX71) \ || defined(_AIX71) \
|| defined(__sun) || defined(__sun) \
|| defined(__HAIKU__)
/* utimesat() has nanosecond resolution but we stick to microseconds /* utimesat() has nanosecond resolution but we stick to microseconds
* for the sake of consistency with other platforms. * for the sake of consistency with other platforms.
*/ */
...@@ -903,7 +947,8 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) { ...@@ -903,7 +947,8 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) {
uv_fs_t fs_req; uv_fs_t fs_req;
uv_file srcfd; uv_file srcfd;
uv_file dstfd; uv_file dstfd;
struct stat statsbuf; struct stat src_statsbuf;
struct stat dst_statsbuf;
int dst_flags; int dst_flags;
int result; int result;
int err; int err;
...@@ -921,7 +966,7 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) { ...@@ -921,7 +966,7 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) {
return srcfd; return srcfd;
/* Get the source file's mode. */ /* Get the source file's mode. */
if (fstat(srcfd, &statsbuf)) { if (fstat(srcfd, &src_statsbuf)) {
err = UV__ERR(errno); err = UV__ERR(errno);
goto out; goto out;
} }
...@@ -936,7 +981,7 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) { ...@@ -936,7 +981,7 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) {
&fs_req, &fs_req,
req->new_path, req->new_path,
dst_flags, dst_flags,
statsbuf.st_mode, src_statsbuf.st_mode,
NULL); NULL);
uv_fs_req_cleanup(&fs_req); uv_fs_req_cleanup(&fs_req);
...@@ -945,7 +990,19 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) { ...@@ -945,7 +990,19 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) {
goto out; goto out;
} }
if (fchmod(dstfd, statsbuf.st_mode) == -1) { /* Get the destination file's mode. */
if (fstat(dstfd, &dst_statsbuf)) {
err = UV__ERR(errno);
goto out;
}
/* Check if srcfd and dstfd refer to the same file */
if (src_statsbuf.st_dev == dst_statsbuf.st_dev &&
src_statsbuf.st_ino == dst_statsbuf.st_ino) {
goto out;
}
if (fchmod(dstfd, src_statsbuf.st_mode) == -1) {
err = UV__ERR(errno); err = UV__ERR(errno);
goto out; goto out;
} }
...@@ -975,7 +1032,7 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) { ...@@ -975,7 +1032,7 @@ static ssize_t uv__fs_copyfile(uv_fs_t* req) {
} }
#endif #endif
bytes_to_send = statsbuf.st_size; bytes_to_send = src_statsbuf.st_size;
in_offset = 0; in_offset = 0;
while (bytes_to_send != 0) { while (bytes_to_send != 0) {
err = uv_fs_sendfile(NULL, err = uv_fs_sendfile(NULL,
......
/* Copyright libuv project contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "uv.h"
#include "internal.h"
#include <FindDirectory.h> /* find_path() */
#include <OS.h>
void uv_loadavg(double avg[3]) {
avg[0] = 0;
avg[1] = 0;
avg[2] = 0;
}
int uv_exepath(char* buffer, size_t* size) {
char abspath[B_PATH_NAME_LENGTH];
status_t status;
ssize_t abspath_len;
if (buffer == NULL || size == NULL || *size == 0)
return UV_EINVAL;
status = find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, abspath,
sizeof(abspath));
if (status != B_OK)
return UV__ERR(status);
abspath_len = uv__strscpy(buffer, abspath, *size);
*size -= 1;
if (abspath_len >= 0 && *size > (size_t)abspath_len)
*size = (size_t)abspath_len;
return 0;
}
uint64_t uv_get_free_memory(void) {
status_t status;
system_info sinfo;
status = get_system_info(&sinfo);
if (status != B_OK)
return 0;
return (sinfo.max_pages - sinfo.used_pages) * B_PAGE_SIZE;
}
uint64_t uv_get_total_memory(void) {
status_t status;
system_info sinfo;
status = get_system_info(&sinfo);
if (status != B_OK)
return 0;
return sinfo.max_pages * B_PAGE_SIZE;
}
uint64_t uv_get_constrained_memory(void) {
return 0; /* Memory constraints are unknown. */
}
int uv_resident_set_memory(size_t* rss) {
area_info area;
ssize_t cookie;
status_t status;
thread_info thread;
status = get_thread_info(find_thread(NULL), &thread);
if (status != B_OK)
return UV__ERR(status);
cookie = 0;
*rss = 0;
while (get_next_area_info(thread.team, &cookie, &area) == B_OK)
*rss += area.ram_size;
return 0;
}
int uv_uptime(double* uptime) {
/* system_time() returns time since booting in microseconds */
*uptime = (double)system_time() / 1000000;
return 0;
}
int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
cpu_topology_node_info* topology_infos;
int i;
status_t status;
system_info system;
uint32_t topology_count;
uint64_t cpuspeed;
uv_cpu_info_t* cpu_info;
if (cpu_infos == NULL || count == NULL)
return UV_EINVAL;
status = get_cpu_topology_info(NULL, &topology_count);
if (status != B_OK)
return UV__ERR(status);
topology_infos = uv__malloc(topology_count * sizeof(*topology_infos));
if (topology_infos == NULL)
return UV_ENOMEM;
status = get_cpu_topology_info(topology_infos, &topology_count);
if (status != B_OK) {
uv__free(topology_infos);
return UV__ERR(status);
}
cpuspeed = 0;
for (i = 0; i < (int)topology_count; i++) {
if (topology_infos[i].type == B_TOPOLOGY_CORE) {
cpuspeed = topology_infos[i].data.core.default_frequency;
break;
}
}
uv__free(topology_infos);
status = get_system_info(&system);
if (status != B_OK)
return UV__ERR(status);
*cpu_infos = uv__calloc(system.cpu_count, sizeof(**cpu_infos));
if (*cpu_infos == NULL)
return UV_ENOMEM;
/* CPU time and model are not exposed by Haiku. */
cpu_info = *cpu_infos;
for (i = 0; i < (int)system.cpu_count; i++) {
cpu_info->model = uv__strdup("unknown");
cpu_info->speed = (int)(cpuspeed / 1000000);
cpu_info++;
}
*count = system.cpu_count;
return 0;
}
void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
int i;
for (i = 0; i < count; i++)
uv__free(cpu_infos[i].model);
uv__free(cpu_infos);
}
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
#include "uv-common.h" #include "uv-common.h"
#include <assert.h> #include <assert.h>
#include <limits.h> /* _POSIX_PATH_MAX, PATH_MAX */
#include <stdlib.h> /* abort */ #include <stdlib.h> /* abort */
#include <string.h> /* strrchr */ #include <string.h> /* strrchr */
#include <fcntl.h> /* O_CLOEXEC, may be */ #include <fcntl.h> /* O_CLOEXEC, may be */
...@@ -60,6 +61,14 @@ ...@@ -60,6 +61,14 @@
# include <AvailabilityMacros.h> # include <AvailabilityMacros.h>
#endif #endif
#if defined(_POSIX_PATH_MAX)
# define UV__PATH_MAX _POSIX_PATH_MAX
#elif defined(PATH_MAX)
# define UV__PATH_MAX PATH_MAX
#else
# define UV__PATH_MAX 8192
#endif
#if defined(__ANDROID__) #if defined(__ANDROID__)
int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset); int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset);
# ifdef pthread_sigmask # ifdef pthread_sigmask
......
...@@ -249,7 +249,7 @@ static int uv__process_open_stream(uv_stdio_container_t* container, ...@@ -249,7 +249,7 @@ static int uv__process_open_stream(uv_stdio_container_t* container,
static void uv__process_close_stream(uv_stdio_container_t* container) { static void uv__process_close_stream(uv_stdio_container_t* container) {
if (!(container->flags & UV_CREATE_PIPE)) return; if (!(container->flags & UV_CREATE_PIPE)) return;
uv__stream_close((uv_stream_t*)container->data.stream); uv__stream_close(container->data.stream);
} }
...@@ -385,6 +385,11 @@ static void uv__process_child_init(const uv_process_options_t* options, ...@@ -385,6 +385,11 @@ static void uv__process_child_init(const uv_process_options_t* options,
if (n == SIGKILL || n == SIGSTOP) if (n == SIGKILL || n == SIGSTOP)
continue; /* Can't be changed. */ continue; /* Can't be changed. */
#if defined(__HAIKU__)
if (n == SIGKILLTHR)
continue; /* Can't be changed. */
#endif
if (SIG_ERR != signal(n, SIG_DFL)) if (SIG_ERR != signal(n, SIG_DFL))
continue; continue;
......
...@@ -375,7 +375,7 @@ static int uv__signal_start(uv_signal_t* handle, ...@@ -375,7 +375,7 @@ static int uv__signal_start(uv_signal_t* handle,
/* Short circuit: if the signal watcher is already watching {signum} don't /* Short circuit: if the signal watcher is already watching {signum} don't
* go through the process of deregistering and registering the handler. * go through the process of deregistering and registering the handler.
* Additionally, this avoids pending signals getting lost in the small time * Additionally, this avoids pending signals getting lost in the small
* time frame that handle->signum == 0. * time frame that handle->signum == 0.
*/ */
if (signum == handle->signum) { if (signum == handle->signum) {
......
...@@ -1541,7 +1541,7 @@ int uv_try_write(uv_stream_t* stream, ...@@ -1541,7 +1541,7 @@ int uv_try_write(uv_stream_t* stream,
} }
if (written == 0 && req_size != 0) if (written == 0 && req_size != 0)
return UV_EAGAIN; return req.error < 0 ? req.error : UV_EAGAIN;
else else
return written; return written;
} }
......
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
#include <sys/sem.h> #include <sys/sem.h>
#endif #endif
#ifdef __GLIBC__ #if defined(__GLIBC__) && !defined(__UCLIBC__)
#include <gnu/libc-version.h> /* gnu_get_libc_version() */ #include <gnu/libc-version.h> /* gnu_get_libc_version() */
#endif #endif
...@@ -178,8 +178,21 @@ static size_t thread_stack_size(void) { ...@@ -178,8 +178,21 @@ static size_t thread_stack_size(void) {
if (lim.rlim_cur != RLIM_INFINITY) { if (lim.rlim_cur != RLIM_INFINITY) {
/* pthread_attr_setstacksize() expects page-aligned values. */ /* pthread_attr_setstacksize() expects page-aligned values. */
lim.rlim_cur -= lim.rlim_cur % (rlim_t) getpagesize(); lim.rlim_cur -= lim.rlim_cur % (rlim_t) getpagesize();
if (lim.rlim_cur >= PTHREAD_STACK_MIN)
return lim.rlim_cur; /* Musl's PTHREAD_STACK_MIN is 2 KB on all architectures, which is
* too small to safely receive signals on.
*
* Musl's PTHREAD_STACK_MIN + MINSIGSTKSZ == 8192 on arm64 (which has
* the largest MINSIGSTKSZ of the architectures that musl supports) so
* let's use that as a lower bound.
*
* We use a hardcoded value because PTHREAD_STACK_MIN + MINSIGSTKSZ
* is between 28 and 133 KB when compiling against glibc, depending
* on the architecture.
*/
if (lim.rlim_cur >= 8192)
if (lim.rlim_cur >= PTHREAD_STACK_MIN)
return lim.rlim_cur;
} }
#endif #endif
...@@ -209,6 +222,12 @@ int uv_thread_create_ex(uv_thread_t* tid, ...@@ -209,6 +222,12 @@ int uv_thread_create_ex(uv_thread_t* tid,
size_t pagesize; size_t pagesize;
size_t stack_size; size_t stack_size;
/* Used to squelch a -Wcast-function-type warning. */
union {
void (*in)(void*);
void* (*out)(void*);
} f;
stack_size = stack_size =
params->flags & UV_THREAD_HAS_STACK_SIZE ? params->stack_size : 0; params->flags & UV_THREAD_HAS_STACK_SIZE ? params->stack_size : 0;
...@@ -235,7 +254,8 @@ int uv_thread_create_ex(uv_thread_t* tid, ...@@ -235,7 +254,8 @@ int uv_thread_create_ex(uv_thread_t* tid,
abort(); abort();
} }
err = pthread_create(tid, attr, (void*(*)(void*)) entry, arg); f.in = entry;
err = pthread_create(tid, attr, f.out, arg);
if (attr != NULL) if (attr != NULL)
pthread_attr_destroy(attr); pthread_attr_destroy(attr);
...@@ -461,7 +481,7 @@ int uv_sem_trywait(uv_sem_t* sem) { ...@@ -461,7 +481,7 @@ int uv_sem_trywait(uv_sem_t* sem) {
#else /* !(defined(__APPLE__) && defined(__MACH__)) */ #else /* !(defined(__APPLE__) && defined(__MACH__)) */
#ifdef __GLIBC__ #if defined(__GLIBC__) && !defined(__UCLIBC__)
/* Hack around https://sourceware.org/bugzilla/show_bug.cgi?id=12674 /* Hack around https://sourceware.org/bugzilla/show_bug.cgi?id=12674
* by providing a custom implementation for glibc < 2.21 in terms of other * by providing a custom implementation for glibc < 2.21 in terms of other
...@@ -497,7 +517,8 @@ typedef struct uv_semaphore_s { ...@@ -497,7 +517,8 @@ typedef struct uv_semaphore_s {
unsigned int value; unsigned int value;
} uv_semaphore_t; } uv_semaphore_t;
#if defined(__GLIBC__) || platform_needs_custom_semaphore #if (defined(__GLIBC__) && !defined(__UCLIBC__)) || \
platform_needs_custom_semaphore
STATIC_ASSERT(sizeof(uv_sem_t) >= sizeof(uv_semaphore_t*)); STATIC_ASSERT(sizeof(uv_sem_t) >= sizeof(uv_semaphore_t*));
#endif #endif
...@@ -626,7 +647,7 @@ static int uv__sem_trywait(uv_sem_t* sem) { ...@@ -626,7 +647,7 @@ static int uv__sem_trywait(uv_sem_t* sem) {
} }
int uv_sem_init(uv_sem_t* sem, unsigned int value) { int uv_sem_init(uv_sem_t* sem, unsigned int value) {
#ifdef __GLIBC__ #if defined(__GLIBC__) && !defined(__UCLIBC__)
uv_once(&glibc_version_check_once, glibc_version_check); uv_once(&glibc_version_check_once, glibc_version_check);
#endif #endif
......
...@@ -1409,47 +1409,57 @@ INLINE static void fs__stat_prepare_path(WCHAR* pathw) { ...@@ -1409,47 +1409,57 @@ INLINE static void fs__stat_prepare_path(WCHAR* pathw) {
} }
INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) { INLINE static DWORD fs__stat_impl_from_path(WCHAR* path,
int do_lstat,
uv_stat_t* statbuf) {
HANDLE handle; HANDLE handle;
DWORD flags; DWORD flags;
DWORD ret;
flags = FILE_FLAG_BACKUP_SEMANTICS; flags = FILE_FLAG_BACKUP_SEMANTICS;
if (do_lstat) { if (do_lstat)
flags |= FILE_FLAG_OPEN_REPARSE_POINT; flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
handle = CreateFileW(req->file.pathw, handle = CreateFileW(path,
FILE_READ_ATTRIBUTES, FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, NULL,
OPEN_EXISTING, OPEN_EXISTING,
flags, flags,
NULL); NULL);
if (handle == INVALID_HANDLE_VALUE) {
SET_REQ_WIN32_ERROR(req, GetLastError());
return;
}
if (fs__stat_handle(handle, &req->statbuf, do_lstat) != 0) { if (handle == INVALID_HANDLE_VALUE)
DWORD error = GetLastError(); ret = GetLastError();
else if (fs__stat_handle(handle, statbuf, do_lstat) != 0)
ret = GetLastError();
else
ret = 0;
CloseHandle(handle);
return ret;
}
INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) {
DWORD error;
error = fs__stat_impl_from_path(req->file.pathw, do_lstat, &req->statbuf);
if (error != 0) {
if (do_lstat && if (do_lstat &&
(error == ERROR_SYMLINK_NOT_SUPPORTED || (error == ERROR_SYMLINK_NOT_SUPPORTED ||
error == ERROR_NOT_A_REPARSE_POINT)) { error == ERROR_NOT_A_REPARSE_POINT)) {
/* We opened a reparse point but it was not a symlink. Try again. */ /* We opened a reparse point but it was not a symlink. Try again. */
fs__stat_impl(req, 0); fs__stat_impl(req, 0);
} else { } else {
/* Stat failed. */ /* Stat failed. */
SET_REQ_WIN32_ERROR(req, GetLastError()); SET_REQ_WIN32_ERROR(req, error);
} }
CloseHandle(handle);
return; return;
} }
req->ptr = &req->statbuf; req->ptr = &req->statbuf;
req->result = 0; req->result = 0;
CloseHandle(handle);
} }
...@@ -1553,6 +1563,9 @@ static void fs__ftruncate(uv_fs_t* req) { ...@@ -1553,6 +1563,9 @@ static void fs__ftruncate(uv_fs_t* req) {
static void fs__copyfile(uv_fs_t* req) { static void fs__copyfile(uv_fs_t* req) {
int flags; int flags;
int overwrite; int overwrite;
DWORD error;
uv_stat_t statbuf;
uv_stat_t new_statbuf;
flags = req->fs.info.file_flags; flags = req->fs.info.file_flags;
...@@ -1563,12 +1576,25 @@ static void fs__copyfile(uv_fs_t* req) { ...@@ -1563,12 +1576,25 @@ static void fs__copyfile(uv_fs_t* req) {
overwrite = flags & UV_FS_COPYFILE_EXCL; overwrite = flags & UV_FS_COPYFILE_EXCL;
if (CopyFileW(req->file.pathw, req->fs.info.new_pathw, overwrite) == 0) { if (CopyFileW(req->file.pathw, req->fs.info.new_pathw, overwrite) != 0) {
SET_REQ_WIN32_ERROR(req, GetLastError()); SET_REQ_RESULT(req, 0);
return; return;
} }
SET_REQ_RESULT(req, 0); SET_REQ_WIN32_ERROR(req, GetLastError());
if (req->result != UV_EBUSY)
return;
/* if error UV_EBUSY check if src and dst file are the same */
if (fs__stat_impl_from_path(req->file.pathw, 0, &statbuf) != 0 ||
fs__stat_impl_from_path(req->fs.info.new_pathw, 0, &new_statbuf) != 0) {
return;
}
if (statbuf.st_dev == new_statbuf.st_dev &&
statbuf.st_ino == new_statbuf.st_ino) {
SET_REQ_RESULT(req, 0);
}
} }
......
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
...@@ -33,9 +33,16 @@ TEST_IMPL(cwd_and_chdir) { ...@@ -33,9 +33,16 @@ TEST_IMPL(cwd_and_chdir) {
size_t size2; size_t size2;
int err; int err;
size1 = 1;
err = uv_cwd(buffer_orig, &size1);
ASSERT(err == UV_ENOBUFS);
ASSERT(size1 > 1);
size1 = sizeof buffer_orig; size1 = sizeof buffer_orig;
err = uv_cwd(buffer_orig, &size1); err = uv_cwd(buffer_orig, &size1);
ASSERT(err == 0); ASSERT(err == 0);
ASSERT(size1 > 0);
ASSERT(buffer_orig[size1] != '/');
err = uv_chdir(buffer_orig); err = uv_chdir(buffer_orig);
ASSERT(err == 0); ASSERT(err == 0);
......
...@@ -24,7 +24,8 @@ ...@@ -24,7 +24,8 @@
#if defined(__unix__) || defined(__POSIX__) || \ #if defined(__unix__) || defined(__POSIX__) || \
defined(__APPLE__) || defined(__sun) || \ defined(__APPLE__) || defined(__sun) || \
defined(_AIX) || defined(__MVS__) defined(_AIX) || defined(__MVS__) || \
defined(__HAIKU__)
#include <unistd.h> /* unlink, etc. */ #include <unistd.h> /* unlink, etc. */
#else #else
# include <direct.h> # include <direct.h>
...@@ -119,6 +120,13 @@ TEST_IMPL(fs_copyfile) { ...@@ -119,6 +120,13 @@ TEST_IMPL(fs_copyfile) {
ASSERT(r != 0); ASSERT(r != 0);
uv_fs_req_cleanup(&req); uv_fs_req_cleanup(&req);
/* Succeeds if src and dst files are identical. */
touch_file(src, 12);
r = uv_fs_copyfile(NULL, &req, src, src, 0, NULL);
ASSERT(r == 0);
uv_fs_req_cleanup(&req);
unlink(src);
/* Copies file synchronously. Creates new file. */ /* Copies file synchronously. Creates new file. */
unlink(dst); unlink(dst);
r = uv_fs_copyfile(NULL, &req, fixture, dst, 0, NULL); r = uv_fs_copyfile(NULL, &req, fixture, dst, 0, NULL);
......
...@@ -31,7 +31,8 @@ ...@@ -31,7 +31,8 @@
/* FIXME we shouldn't need to branch in this file */ /* FIXME we shouldn't need to branch in this file */
#if defined(__unix__) || defined(__POSIX__) || \ #if defined(__unix__) || defined(__POSIX__) || \
defined(__APPLE__) || defined(__sun) || \ defined(__APPLE__) || defined(__sun) || \
defined(_AIX) || defined(__MVS__) defined(_AIX) || defined(__MVS__) || \
defined(__HAIKU__)
#include <unistd.h> /* unlink, rmdir, etc. */ #include <unistd.h> /* unlink, rmdir, etc. */
#else #else
# include <winioctl.h> # include <winioctl.h>
...@@ -1653,6 +1654,8 @@ TEST_IMPL(fs_chown) { ...@@ -1653,6 +1654,8 @@ TEST_IMPL(fs_chown) {
uv_run(loop, UV_RUN_DEFAULT); uv_run(loop, UV_RUN_DEFAULT);
ASSERT(fchown_cb_count == 1); ASSERT(fchown_cb_count == 1);
#ifndef __HAIKU__
/* Haiku doesn't support hardlink */
/* sync link */ /* sync link */
r = uv_fs_link(NULL, &req, "test_file", "test_file_link", NULL); r = uv_fs_link(NULL, &req, "test_file", "test_file_link", NULL);
ASSERT(r == 0); ASSERT(r == 0);
...@@ -1670,6 +1673,7 @@ TEST_IMPL(fs_chown) { ...@@ -1670,6 +1673,7 @@ TEST_IMPL(fs_chown) {
ASSERT(r == 0); ASSERT(r == 0);
uv_run(loop, UV_RUN_DEFAULT); uv_run(loop, UV_RUN_DEFAULT);
ASSERT(lchown_cb_count == 1); ASSERT(lchown_cb_count == 1);
#endif
/* Close file */ /* Close file */
r = uv_fs_close(NULL, &req, file, NULL); r = uv_fs_close(NULL, &req, file, NULL);
...@@ -2717,6 +2721,60 @@ TEST_IMPL(fs_rename_to_existing_file) { ...@@ -2717,6 +2721,60 @@ TEST_IMPL(fs_rename_to_existing_file) {
} }
TEST_IMPL(fs_read_bufs) {
char scratch[768];
uv_buf_t bufs[4];
ASSERT(0 <= uv_fs_open(NULL, &open_req1,
"test/fixtures/lorem_ipsum.txt",
O_RDONLY, 0, NULL));
ASSERT(open_req1.result >= 0);
uv_fs_req_cleanup(&open_req1);
ASSERT(UV_EINVAL == uv_fs_read(NULL, &read_req, open_req1.result,
NULL, 0, 0, NULL));
ASSERT(UV_EINVAL == uv_fs_read(NULL, &read_req, open_req1.result,
NULL, 1, 0, NULL));
ASSERT(UV_EINVAL == uv_fs_read(NULL, &read_req, open_req1.result,
bufs, 0, 0, NULL));
bufs[0] = uv_buf_init(scratch + 0, 256);
bufs[1] = uv_buf_init(scratch + 256, 256);
bufs[2] = uv_buf_init(scratch + 512, 128);
bufs[3] = uv_buf_init(scratch + 640, 128);
ASSERT(446 == uv_fs_read(NULL,
&read_req,
open_req1.result,
bufs + 0,
2, /* 2x 256 bytes. */
0, /* Positional read. */
NULL));
ASSERT(read_req.result == 446);
uv_fs_req_cleanup(&read_req);
ASSERT(190 == uv_fs_read(NULL,
&read_req,
open_req1.result,
bufs + 2,
2, /* 2x 128 bytes. */
256, /* Positional read. */
NULL));
ASSERT(read_req.result == /* 446 - 256 */ 190);
uv_fs_req_cleanup(&read_req);
ASSERT(0 == memcmp(bufs[1].base + 0, bufs[2].base, 128));
ASSERT(0 == memcmp(bufs[1].base + 128, bufs[3].base, 190 - 128));
ASSERT(0 == uv_fs_close(NULL, &close_req, open_req1.result, NULL));
ASSERT(close_req.result == 0);
uv_fs_req_cleanup(&close_req);
MAKE_VALGRIND_HAPPY();
return 0;
}
TEST_IMPL(fs_read_file_eof) { TEST_IMPL(fs_read_file_eof) {
#if defined(__CYGWIN__) || defined(__MSYS__) #if defined(__CYGWIN__) || defined(__MSYS__)
RETURN_SKIP("Cygwin pread at EOF may (incorrectly) return data!"); RETURN_SKIP("Cygwin pread at EOF may (incorrectly) return data!");
......
...@@ -91,6 +91,7 @@ TEST_DECLARE (tcp_write_after_connect) ...@@ -91,6 +91,7 @@ TEST_DECLARE (tcp_write_after_connect)
TEST_DECLARE (tcp_writealot) TEST_DECLARE (tcp_writealot)
TEST_DECLARE (tcp_write_fail) TEST_DECLARE (tcp_write_fail)
TEST_DECLARE (tcp_try_write) TEST_DECLARE (tcp_try_write)
TEST_DECLARE (tcp_try_write_error)
TEST_DECLARE (tcp_write_queue_order) TEST_DECLARE (tcp_write_queue_order)
TEST_DECLARE (tcp_open) TEST_DECLARE (tcp_open)
TEST_DECLARE (tcp_open_twice) TEST_DECLARE (tcp_open_twice)
...@@ -325,6 +326,7 @@ TEST_DECLARE (fs_utime) ...@@ -325,6 +326,7 @@ TEST_DECLARE (fs_utime)
TEST_DECLARE (fs_futime) TEST_DECLARE (fs_futime)
TEST_DECLARE (fs_file_open_append) TEST_DECLARE (fs_file_open_append)
TEST_DECLARE (fs_stat_missing_path) TEST_DECLARE (fs_stat_missing_path)
TEST_DECLARE (fs_read_bufs)
TEST_DECLARE (fs_read_file_eof) TEST_DECLARE (fs_read_file_eof)
TEST_DECLARE (fs_event_watch_dir) TEST_DECLARE (fs_event_watch_dir)
TEST_DECLARE (fs_event_watch_dir_recursive) TEST_DECLARE (fs_event_watch_dir_recursive)
...@@ -582,6 +584,7 @@ TASK_LIST_START ...@@ -582,6 +584,7 @@ TASK_LIST_START
TEST_HELPER (tcp_write_fail, tcp4_echo_server) TEST_HELPER (tcp_write_fail, tcp4_echo_server)
TEST_ENTRY (tcp_try_write) TEST_ENTRY (tcp_try_write)
TEST_ENTRY (tcp_try_write_error)
TEST_ENTRY (tcp_write_queue_order) TEST_ENTRY (tcp_write_queue_order)
...@@ -776,7 +779,7 @@ TASK_LIST_START ...@@ -776,7 +779,7 @@ TASK_LIST_START
TEST_ENTRY (tmpdir) TEST_ENTRY (tmpdir)
TEST_ENTRY (hrtime) TEST_ENTRY_CUSTOM (hrtime, 0, 0, 10000)
TEST_ENTRY_CUSTOM (getaddrinfo_fail, 0, 0, 10000) TEST_ENTRY_CUSTOM (getaddrinfo_fail, 0, 0, 10000)
TEST_ENTRY_CUSTOM (getaddrinfo_fail_sync, 0, 0, 10000) TEST_ENTRY_CUSTOM (getaddrinfo_fail_sync, 0, 0, 10000)
...@@ -911,6 +914,7 @@ TASK_LIST_START ...@@ -911,6 +914,7 @@ TASK_LIST_START
TEST_ENTRY (fs_non_symlink_reparse_point) TEST_ENTRY (fs_non_symlink_reparse_point)
#endif #endif
TEST_ENTRY (fs_stat_missing_path) TEST_ENTRY (fs_stat_missing_path)
TEST_ENTRY (fs_read_bufs)
TEST_ENTRY (fs_read_file_eof) TEST_ENTRY (fs_read_file_eof)
TEST_ENTRY (fs_file_open_append) TEST_ENTRY (fs_file_open_append)
TEST_ENTRY (fs_event_watch_dir) TEST_ENTRY (fs_event_watch_dir)
......
/* Copyright libuv contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "uv.h"
#include "task.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static uv_tcp_t server;
static uv_tcp_t client;
static uv_tcp_t incoming;
static int connect_cb_called;
static int close_cb_called;
static int connection_cb_called;
static void close_cb(uv_handle_t* handle) {
close_cb_called++;
}
static void incoming_close_cb(uv_handle_t* handle) {
uv_buf_t buf;
int r = 1;
close_cb_called++;
buf = uv_buf_init("meow", 4);
while (r > 0)
r = uv_try_write((uv_stream_t*) &client, &buf, 1);
fprintf(stderr, "uv_try_write error: %d %s\n", r, uv_strerror(r));
ASSERT(r == UV_EPIPE || r == UV_ECONNABORTED || r == UV_ECONNRESET);
ASSERT(client.write_queue_size == 0);
}
static void connect_cb(uv_connect_t* req, int status) {
ASSERT(status == 0);
connect_cb_called++;
}
static void connection_cb(uv_stream_t* tcp, int status) {
ASSERT(status == 0);
ASSERT(0 == uv_tcp_init(tcp->loop, &incoming));
ASSERT(0 == uv_accept(tcp, (uv_stream_t*) &incoming));
connection_cb_called++;
uv_close((uv_handle_t*) &incoming, incoming_close_cb);
uv_close((uv_handle_t*) tcp, close_cb);
}
static void start_server(void) {
struct sockaddr_in addr;
ASSERT(0 == uv_ip4_addr("0.0.0.0", TEST_PORT, &addr));
ASSERT(0 == uv_tcp_init(uv_default_loop(), &server));
ASSERT(0 == uv_tcp_bind(&server, (struct sockaddr*) &addr, 0));
ASSERT(0 == uv_listen((uv_stream_t*) &server, 128, connection_cb));
}
TEST_IMPL(tcp_try_write_error) {
uv_connect_t connect_req;
struct sockaddr_in addr;
start_server();
ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr));
ASSERT(0 == uv_tcp_init(uv_default_loop(), &client));
ASSERT(0 == uv_tcp_connect(&connect_req,
&client,
(struct sockaddr*) &addr,
connect_cb));
ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT));
uv_close((uv_handle_t*) &client, close_cb);
ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT));
ASSERT(connect_cb_called == 1);
ASSERT(close_cb_called == 3);
ASSERT(connection_cb_called == 1);
MAKE_VALGRIND_HAPPY();
return 0;
}
...@@ -120,6 +120,7 @@ ...@@ -120,6 +120,7 @@
'test-tcp-writealot.c', 'test-tcp-writealot.c',
'test-tcp-write-fail.c', 'test-tcp-write-fail.c',
'test-tcp-try-write.c', 'test-tcp-try-write.c',
'test-tcp-try-write-error.c',
'test-tcp-unexpected-read.c', 'test-tcp-unexpected-read.c',
'test-tcp-oob.c', 'test-tcp-oob.c',
'test-tcp-read-stop.c', 'test-tcp-read-stop.c',
......
# NOTE: Inspired by
# https://chromium.googlesource.com/chromium/src/+/master/third_party/usrsctp/BUILD.gn
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'target_defaults': {
'dependencies': [
# We need our own openssl dependency (required if SCTP_USE_OPENSSL_SHA1
# is defined).
'../openssl/openssl.gyp:openssl',
],
'defines': [
'SCTP_PROCESS_LEVEL_LOCKS',
'SCTP_SIMPLE_ALLOCATOR',
'SCTP_USE_OPENSSL_SHA1',
'__Userspace__',
# 'SCTP_DEBUG', # Uncomment for SCTP debugging.
],
'direct_dependent_settings': {
'include_dirs': [
'usrsctp/usrsctplib',
'usrsctp/usrsctplib/netinet',
],
},
'include_dirs': [
'usrsctp/usrsctplib',
# 'usrsctp/usrsctplib/netinet', # Not needed (it seems).
],
'cflags': [
'-UINET',
'-UINET6',
],
'xcode_settings': {
'OTHER_CFLAGS': [
'-UINET',
'-UINET6',
],
},
'conditions': [
['OS in "linux android"', {
'defines': [
'__Userspace_os_Linux',
'_GNU_SOURCE',
],
}],
['OS in "mac ios"', {
'defines': [
'HAVE_SA_LEN',
'HAVE_SCONN_LEN',
'__APPLE_USE_RFC_2292',
'__Userspace_os_Darwin',
],
'xcode_settings': {
'WARNING_CFLAGS': [
'-Wall',
'-Wextra',
'-Wno-unused-parameter',
'-Wstrict-prototypes',
],
'OTHER_CFLAGS': [
'-U__APPLE__',
'-Wno-deprecated-declarations',
# atomic_init in user_atomic.h is a static function in a header.
'-Wno-unused-function',
],
}
}],
['OS=="win"', {
'defines': [
'__Userspace_os_Windows'
],
}],
['OS!="win"', {
'defines': [
'NON_WINDOWS_DEFINE'
],
}],
[ 'sctp_debug == "true"', {
'defines': [ 'SCTP_DEBUG' ]
}]
],
},
'targets': [
{
'target_name': 'usrsctp',
'type': 'static_library',
'sources': [
'usrsctp/usrsctplib/netinet/sctp.h',
'usrsctp/usrsctplib/netinet/sctp_asconf.c',
'usrsctp/usrsctplib/netinet/sctp_asconf.h',
'usrsctp/usrsctplib/netinet/sctp_auth.c',
'usrsctp/usrsctplib/netinet/sctp_auth.h',
'usrsctp/usrsctplib/netinet/sctp_bsd_addr.c',
'usrsctp/usrsctplib/netinet/sctp_bsd_addr.h',
'usrsctp/usrsctplib/netinet/sctp_callout.c',
'usrsctp/usrsctplib/netinet/sctp_callout.h',
'usrsctp/usrsctplib/netinet/sctp_cc_functions.c',
'usrsctp/usrsctplib/netinet/sctp_constants.h',
'usrsctp/usrsctplib/netinet/sctp_crc32.c',
'usrsctp/usrsctplib/netinet/sctp_crc32.h',
'usrsctp/usrsctplib/netinet/sctp_header.h',
'usrsctp/usrsctplib/netinet/sctp_indata.c',
'usrsctp/usrsctplib/netinet/sctp_indata.h',
'usrsctp/usrsctplib/netinet/sctp_input.c',
'usrsctp/usrsctplib/netinet/sctp_input.h',
'usrsctp/usrsctplib/netinet/sctp_lock_userspace.h',
'usrsctp/usrsctplib/netinet/sctp_os.h',
'usrsctp/usrsctplib/netinet/sctp_os_userspace.h',
'usrsctp/usrsctplib/netinet/sctp_output.c',
'usrsctp/usrsctplib/netinet/sctp_output.h',
'usrsctp/usrsctplib/netinet/sctp_pcb.c',
'usrsctp/usrsctplib/netinet/sctp_pcb.h',
'usrsctp/usrsctplib/netinet/sctp_peeloff.c',
'usrsctp/usrsctplib/netinet/sctp_peeloff.h',
'usrsctp/usrsctplib/netinet/sctp_process_lock.h',
'usrsctp/usrsctplib/netinet/sctp_sha1.c',
'usrsctp/usrsctplib/netinet/sctp_sha1.h',
'usrsctp/usrsctplib/netinet/sctp_ss_functions.c',
'usrsctp/usrsctplib/netinet/sctp_structs.h',
'usrsctp/usrsctplib/netinet/sctp_sysctl.c',
'usrsctp/usrsctplib/netinet/sctp_sysctl.h',
'usrsctp/usrsctplib/netinet/sctp_timer.c',
'usrsctp/usrsctplib/netinet/sctp_timer.h',
'usrsctp/usrsctplib/netinet/sctp_uio.h',
'usrsctp/usrsctplib/netinet/sctp_userspace.c',
'usrsctp/usrsctplib/netinet/sctp_usrreq.c',
'usrsctp/usrsctplib/netinet/sctp_var.h',
'usrsctp/usrsctplib/netinet/sctputil.c',
'usrsctp/usrsctplib/netinet/sctputil.h',
'usrsctp/usrsctplib/netinet6/sctp6_usrreq.c',
'usrsctp/usrsctplib/netinet6/sctp6_var.h',
'usrsctp/usrsctplib/user_atomic.h',
'usrsctp/usrsctplib/user_environment.c',
'usrsctp/usrsctplib/user_environment.h',
'usrsctp/usrsctplib/user_inpcb.h',
'usrsctp/usrsctplib/user_ip6_var.h',
'usrsctp/usrsctplib/user_ip_icmp.h',
'usrsctp/usrsctplib/user_malloc.h',
'usrsctp/usrsctplib/user_mbuf.c',
'usrsctp/usrsctplib/user_mbuf.h',
'usrsctp/usrsctplib/user_queue.h',
'usrsctp/usrsctplib/user_recv_thread.c',
'usrsctp/usrsctplib/user_recv_thread.h',
'usrsctp/usrsctplib/user_route.h',
'usrsctp/usrsctplib/user_socket.c',
'usrsctp/usrsctplib/user_socketvar.h',
'usrsctp/usrsctplib/user_uma.h',
'usrsctp/usrsctplib/usrsctp.h',
],
},
], # targets
}
# Object files
*.o
*.ko
*.obj
*.elf
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM
# Automake and make releated stuff
Makefile
Makefile.in
.deps
.libs
/autom4te.cache
/aclocal.m4
/compile
/configure
/depcomp
/install-sh
/missing
/stamp-h1
/config.guess
/config.log
/config.status
/config.sub
/libtool
/ltmain.sh
/m4
/usrsctp.pc
.dirstamp
# binaries
programs/client
programs/client_upcall
programs/daytime_server
programs/daytime_server_upcall
programs/discard_server
programs/discard_server_upcall
programs/echo_server
programs/echo_server_upcall
programs/ekr_client
programs/ekr_loop
programs/ekr_loop_offload
programs/ekr_loop_upcall
programs/ekr_peer
programs/ekr_server
programs/http_client
programs/http_client_upcall
programs/rtcweb
programs/tsctp
programs/test_libmgmt
programs/test_timer
# callgrind
callgrind.out*
# cmake build
/build
#
# Copyright (C) 2015-2015 Oleg Alexeenkov
# Copyright (C) 2015-2018 Felix Weinrank
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
project(usrsctplib)
cmake_minimum_required(VERSION 3.0)
# Debug build type as default
if (NOT CMAKE_BUILD_TYPE)
message(STATUS "No build type selected, using DEBUG")
set(CMAKE_BUILD_TYPE "DEBUG")
endif ()
include(CheckStructHasMember)
include(CheckIncludeFile)
include(CheckIncludeFiles)
include(CheckCCompilerFlag)
#################################################
# CHECK OPTIONS
#################################################
option(sctp_invariants "Add runtime checks" 0)
if (sctp_invariants)
add_definitions(-DINVARIANTS)
endif ()
option(sctp_debug "Provide debug information" 1)
if (sctp_debug)
add_definitions(-DSCTP_DEBUG)
endif ()
option(sctp_inet "Support IPv4" 1)
if (sctp_inet)
add_definitions(-DINET)
endif ()
option(sctp_inet6 "Support IPv6" 1)
if (sctp_inet6)
add_definitions(-DINET6)
endif ()
option(sctp_werror "Treat warning as error" 1)
option(sctp_link_programs_static "Link example programs static" 0)
option(sctp_build_programs "Build example programs" 1)
option(sctp_sanitizer_address "Compile with address sanitizer" 0)
option(sctp_sanitizer_memory "Compile with memory sanitizer" 0)
if (sctp_sanitizer_address AND sctp_sanitizer_memory)
message(FATAL_ERROR "Can not compile with both sanitizer options")
endif ()
if (sctp_link_programs_static OR WIN32)
set(programs_link_library "usrsctp-static")
else ()
set(programs_link_library "usrsctp")
endif ()
#################################################
# CHECK FOR TYPES AND FUNCTIONS
#################################################
check_include_files("sys/queue.h" have_sys_queue_h)
if (have_sys_queue_h)
add_definitions(-DHAVE_SYS_QUEUE_H)
endif ()
check_include_files("sys/socket.h;linux/if_addr.h" have_linux_if_addr_h)
if (have_linux_if_addr_h)
add_definitions(-DHAVE_LINUX_IF_ADDR_H)
endif ()
check_include_files("sys/socket.h;linux/rtnetlink.h" have_linux_rtnetlink_h)
if (have_linux_rtnetlink_h)
add_definitions(-DHAVE_LINUX_RTNETLINK_H)
endif ()
check_include_files("sys/types.h;netinet/in.h;netinet/ip.h;netinet/ip_icmp.h" have_netinet_ip_icmp_h)
if (have_netinet_ip_icmp_h)
add_definitions(-DHAVE_NETINET_IP_ICMP_H)
endif ()
check_include_files("stdatomic.h" have_stdatomic_h)
if (have_stdatomic_h)
add_definitions(-DHAVE_STDATOMIC_H)
endif ()
#################################################
# CHECK STRUCT MEMBERS
#################################################
set(CMAKE_REQUIRED_INCLUDES "${CMAKE_SOURCE_DIR}/usrsctplib")
check_include_file(usrsctp.h have_usrsctp_h)
if (NOT have_usrsctp_h)
message(FATAL_ERROR "usrsctp.h not found")
endif ()
check_struct_has_member("struct sockaddr" "sa_len" "sys/types.h;sys/socket.h" have_sa_len)
if (have_sa_len)
message(STATUS "have_sa_len")
add_definitions(-DHAVE_SA_LEN)
endif ()
check_struct_has_member("struct sockaddr_in" "sin_len" "sys/types.h;netinet/in.h" have_sin_len)
if (have_sin_len)
message(STATUS "have_sin_len")
add_definitions(-DHAVE_SIN_LEN)
endif ()
check_struct_has_member("struct sockaddr_in6" "sin6_len" "sys/types.h;netinet/in.h" have_sin6_len)
if (have_sin6_len)
message(STATUS "have_sin6_len")
add_definitions(-DHAVE_SIN6_LEN)
endif ()
check_struct_has_member("struct sockaddr_conn" "sconn_len" "usrsctp.h" have_sconn_len)
if (have_sconn_len)
message(STATUS "HAVE_SCONN_LEN")
add_definitions(-DHAVE_SCONN_LEN)
endif ()
#################################################
# COMPILER SETTINGS
#################################################
# SETTINGS FOR UNIX COMPILER
if (CMAKE_C_COMPILER_ID MATCHES "Clang" OR CMAKE_C_COMPILER_ID MATCHES "AppleClang" OR CMAKE_C_COMPILER_ID MATCHES "GNU")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic -Wall -Wextra")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c99 -pedantic -Wall -Wextra")
check_c_compiler_flag(-Wfloat-equal has_wfloat_equal)
if (has_wfloat_equal)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wfloat-equal")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wfloat-equal")
endif ()
check_c_compiler_flag(-Wshadow has_wshadow)
if (has_wshadow)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wshadow")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wshadow")
endif ()
check_c_compiler_flag(-Wpointer-arith has_wpointer_aritih)
if (has_wpointer_aritih)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wpointer-arith")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wpointer-arith")
endif ()
check_c_compiler_flag(-Wunreachable-code has_wunreachable_code)
if (has_wunreachable_code)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wunreachable-code")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wunreachable-code")
endif ()
check_c_compiler_flag(-Winit-self has_winit_self)
if (has_winit_self)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Winit-self")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Winit-self")
endif ()
check_c_compiler_flag(-Wno-unused-function has_wno_unused_function)
if (has_wno_unused_function)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-function")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-function")
endif ()
check_c_compiler_flag(-Wno-unused-parameter has_wno_unused_parameter)
if (has_wno_unused_parameter)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-parameter")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
endif ()
check_c_compiler_flag(-Wno-unreachable-code has_wno_unreachable_code)
if (has_wno_unreachable_code)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unreachable-code")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unreachable-code")
endif ()
check_c_compiler_flag(-Wstrict-prototypes has_wstrict_prototypes)
if (has_wstrict_prototypes)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstrict-prototypes")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wstrict-prototypes")
endif ()
if (sctp_werror)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
endif ()
if (sctp_sanitizer_address)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fno-omit-frame-pointer -g")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fno-omit-frame-pointer -g")
endif ()
if (sctp_sanitizer_memory)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=memory -fno-omit-frame-pointer -g -fsanitize-memory-track-origins")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=memory -fno-omit-frame-pointer -g -fsanitize-memory-track-origins")
endif ()
endif ()
# SETTINGS FOR VISUAL STUDIO COMPILER
if (CMAKE_C_COMPILER_ID MATCHES "MSVC")
if (CMAKE_C_FLAGS MATCHES "/W[0-4]")
string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
else ()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4")
endif ()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4100") # 'identifier' : unreferenced formal parameter
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4127") # conditional expression is constant
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4200") # nonstandard extension used : zero-sized array in struct/union
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4214") # bit field types other than int
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4706") # assignment within conditional expression
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4245") # 'conversion' : conversion from 'type1' to 'type2', signed/unsigned mismatch
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4389") # 'operator' : signed/unsigned mismatch
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4702") # unreachable code
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4701") # Potentially uninitialized local variable 'name' used
# ToDo
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4244") # 'conversion' conversion from 'type1' to 'type2', possible loss of data
if (sctp_werror)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX")
endif ()
endif ()
message(STATUS "Compiler flags (CMAKE_C_FLAGS): ${CMAKE_C_FLAGS}")
#################################################
# INCLUDE SUBDIRS
#################################################
add_subdirectory(usrsctplib)
if (sctp_build_programs)
add_subdirectory(programs)
endif ()
Copyright (c) 2015, Randall Stewart and Michael Tuexen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of usrsctp nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Copyright (C) 2011-2012 Michael Tuexen
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
if COND_PROGRAMS
MAYBEPROGRAMS = programs
endif
SUBDIRS = usrsctplib $(MAYBEPROGRAMS)
EXTRA_DIST = bootstrap Makefile.nmake
ACLOCAL_AMFLAGS = -I m4
# pkgconfig_DATA = usrsctp.pc
#
# Copyright (C) 2011-2012 Michael Tuexen
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
all:
cd usrsctplib
nmake -f Makefile.nmake
cd ..
cd programs
nmake all -f Makefile.nmake
cd ..
clean:
cd usrsctplib
nmake clean -f Makefile.nmake
cd ..
cd programs
nmake clean -f Makefile.nmake
cd ..
差异被折叠。
差异被折叠。
# usrsctp
[![Coverity Scan Build Status](https://scan.coverity.com/projects/13430/badge.svg)](https://scan.coverity.com/projects/usrsctp)
This is a userland SCTP stack supporting FreeBSD, Linux, Mac OS X and Windows.
See [manual](Manual.md) for more information.
The status of continuous integration testing is available from our [Buildbot](http://buildbot.nplab.de:18010/#/console).
#! /bin/sh
#
# Copyright (C) 2011-2012 Michael Tuexen
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#bail out on error
set -e
#detect (g)libtoolize
if which libtoolize >/dev/null
then
_LIBTOOLIZE=`which libtoolize`
elif which glibtoolize >/dev/null
then
_LIBTOOLIZE=`which glibtoolize`
else
echo "ERROR: I cannot find libtoolize or glibtoolize!"
exit 1
fi
#execute (g)libtoolize
${_LIBTOOLIZE}
#execute aclocal
if [ -e /usr/local/share/aclocal ]
then
aclocal -I /usr/local/share/aclocal
elif [ -e /usr/share/aclocal ]
then
aclocal -I /usr/share/aclocal
else
aclocal
fi
#execute autoconf
autoconf
#generate the ./configure
automake --foreign --add-missing --copy
dnl
dnl Copyright (C) 2011-2012 Michael Tuexen
dnl
dnl All rights reserved.
dnl
dnl Redistribution and use in source and binary forms, with or without
dnl modification, are permitted provided that the following conditions
dnl are met:
dnl 1. Redistributions of source code must retain the above copyright
dnl notice, this list of conditions and the following disclaimer.
dnl 2. Redistributions in binary form must reproduce the above copyright
dnl notice, this list of conditions and the following disclaimer in the
dnl documentation and/or other materials provided with the distribution.
dnl 3. Neither the name of the project nor the names of its contributors
dnl may be used to endorse or promote products derived from this software
dnl without specific prior written permission.
dnl
dnl THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
dnl ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
dnl IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
dnl ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
dnl FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
dnl DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
dnl OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
dnl HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
dnl LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
dnl OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
dnl SUCH DAMAGE.
dnl
AC_INIT([libusrsctp], [0.9.3.0])
AM_INIT_AUTOMAKE([foreign])
AC_PROG_CC
AC_PROG_LIBTOOL
AC_CANONICAL_HOST
AC_CONFIG_MACRO_DIR([m4])
dnl Disable pkg_config support for now
dnl PKG_PROG_PKG_CONFIG
dnl PKG_INSTALLDIR
LIBCFLAGS="-DSCTP_PROCESS_LEVEL_LOCKS -DSCTP_SIMPLE_ALLOCATOR -D__Userspace__"
APPCFLAGS=""
case $host_os in
darwin*)
CFLAGS="$CFLAGS -std=c99 -Wno-deprecated-declarations -D__APPLE_USE_RFC_2292"
LIBCFLAGS="$LIBCFLAGS -U__APPLE__ -D__Userspace_os_Darwin"
;;
dragonfly*)
CFLAGS="$CFLAGS -std=c99 -pthread"
LIBCFLAGS="$LIBCFLAGS -U__DragonFly__ -D__Userspace_os_DragonFly"
;;
freebsd*)
CFLAGS="$CFLAGS -std=c99 -pthread"
if $CC --version | grep -q clang; then
CFLAGS="$CFLAGS -Wno-unknown-warning-option"
LDFLAGS="$LDFLAGS -Qunused-arguments"
fi
LIBCFLAGS="$LIBCFLAGS -U__FreeBSD__ -D__Userspace_os_FreeBSD"
;;
linux*)
CFLAGS="$CFLAGS -std=c99 -pthread -D_GNU_SOURCE"
LIBCFLAGS="$LIBCFLAGS -D__Userspace_os_Linux"
;;
netbsd*)
CFLAGS="$CFLAGS -std=c99 -pthread"
LIBCFLAGS="$LIBCFLAGS -U__NetBSD__ -D__Userspace_os_NetBSD"
;;
openbsd*)
CFLAGS="$CFLAGS -std=c99 -pthread"
LIBCFLAGS="$LIBCFLAGS -U__OpenBSD__ -D__Userspace_os_OpenBSD"
;;
solaris*)
CFLAGS="$CFLAGS -D_XPG4_2"
;;
esac
if test "x$GCC" = "xyes" -o "x$CC" = "xclang" ; then
ac_supports_gcc_flags=yes
fi
if test "x$ac_supports_gcc_flags" = "xyes" ; then
CFLAGS="$CFLAGS -pedantic -Wall"
fi
AC_MSG_CHECKING(whether we should treat compiler warnings as errors)
AC_ARG_ENABLE(warnings-as-errors,
AC_HELP_STRING( [--enable-warnings-as-errors],
[treat warnings as errors (only for GCC or clang) @<:@default=yes@:>@]),
enable_warnings_as_errors=$enableval,enable_warnings_as_errors=yes)
if test "x$ac_supports_gcc_flags" = "xyes" -a x$enable_warnings_as_errors = xyes; then
AC_MSG_RESULT(yes)
CFLAGS="$CFLAGS -Werror"
else
AC_MSG_RESULT(no)
fi
AC_ARG_ENABLE(invariants,
AC_HELP_STRING( [--enable-invariants],
[add additional runtime checks @<:@default=no@:>@]),
enable_invariants=$enableval,enable_invariants=no)
if test x$enable_invariants = xyes; then
AC_DEFINE(INVARIANTS, 1, [Add additional runtime checks])
fi
AC_ARG_ENABLE(debug,
AC_HELP_STRING( [--enable-debug],
[provide debug information @<:@default=yes@:>@]),
enable_debug=$enableval,enable_debug=yes)
if test x$enable_debug = xyes; then
AC_DEFINE(SCTP_DEBUG, 1, [Provide debug information])
CFLAGS="$CFLAGS -g -O0"
fi
AC_ARG_ENABLE(inet,
AC_HELP_STRING( [--enable-inet],
[Support IPv4 @<:@default=yes@:>@]),
enable_inet=$enableval,enable_inet=yes)
if test x$enable_inet = xyes; then
APPCFLAGS="$APPCFLAGS -DINET"
AC_DEFINE(INET, 1, [Support IPv4])
fi
AC_ARG_ENABLE(inet6,
AC_HELP_STRING( [--enable-inet6],
[Support IPv6 @<:@default=yes@:>@]),
enable_inet6=$enableval,enable_inet6=yes)
if test x$enable_inet6 = xyes; then
APPCFLAGS="$APPCFLAGS -DINET6"
AC_DEFINE(INET6, 1, [Support IPv6])
fi
AC_ARG_ENABLE(programs,
AC_HELP_STRING( [--enable-programs],
[build example programs @<:@default=yes@:>@]),
enable_programs=$enableval,enable_programs=yes)
AM_CONDITIONAL([COND_PROGRAMS], [test "$enable_programs" = yes])
AC_CHECK_TYPE(size_t)
AC_CHECK_TYPE(ssize_t)
AC_CHECK_FUNCS(socket, , AC_CHECK_LIB(socket, socket))
AC_CHECK_FUNCS(inet_addr, , AC_CHECK_LIB(nsl, inet_addr))
AC_CHECK_HEADERS(stdatomic.h)
AC_CHECK_HEADERS(sys/queue.h)
AC_CHECK_HEADERS(linux/if_addr.h, [], [], [#include <sys/socket.h>])
AC_CHECK_HEADERS(linux/rtnetlink.h, [], [], [#include <sys/socket.h>])
AC_CHECK_HEADERS(netinet/ip_icmp.h, [], [], [#include <netinet/ip.h>])
AC_CHECK_MEMBER(struct sockaddr.sa_len,
AC_DEFINE(HAVE_SA_LEN, 1, [Define this if your stack has sa_len in sockaddr struct.]),,
[#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <sys/socket.h>])
AC_CHECK_MEMBER(struct sockaddr_in.sin_len,
AC_DEFINE(HAVE_SIN_LEN, 1, [Define this if your IPv4 has sin_len in sockaddr_in struct.]),,
[#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <netinet/in.h>])
AC_CHECK_MEMBER(struct sockaddr_in6.sin6_len,
AC_DEFINE(HAVE_SIN6_LEN, 1, [Define this if your IPv6 has sin6_len in sockaddr_in6 struct.]),,
[#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <netinet/in.h>])
AC_CHECK_MEMBER(struct sockaddr_conn.sconn_len,
AC_DEFINE(HAVE_SCONN_LEN, 1, [Define this if your userland stack has sconn_len in sockaddr_conn struct.]),,
[#include "usrsctplib/usrsctp.h"])
AC_MSG_CHECKING(for socklen_t)
AC_TRY_COMPILE([#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <sys/socket.h>],
[socklen_t x; x = 1; return ((int)x);],
[AC_MSG_RESULT(yes)],
[AC_MSG_RESULT(int)
AC_DEFINE(socklen_t, int, [Define a type for socklen_t.])])
AC_C_BIGENDIAN
AC_SUBST([LIBCFLAGS])
AC_SUBST([APPCFLAGS])
dnl AC_CONFIG_FILES([usrsctp.pc])
AC_CONFIG_FILES(usrsctplib/Makefile programs/Makefile Makefile)
AC_OUTPUT
差异被折叠。
/*-
* Copyright (c) 2019 Felix Weinrank
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef __PROGRAMS_HELPER_H__
#define __PROGRAMS_HELPER_H__
void debug_printf(const char *format, ...);
void handle_notification(union sctp_notification *notif, size_t n);
#ifndef timersub
#define timersub(tvp, uvp, vvp) \
do { \
(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
if ((vvp)->tv_usec < 0) { \
(vvp)->tv_sec--; \
(vvp)->tv_usec += 1000000; \
} \
} while (0)
#endif
#endif /* __PROGRAMS_HELPER_H__ */
差异被折叠。
/*
* Copyright (C) 2016 Michael Tuexen
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _WIN32
#include <unistd.h>
#endif
#include "usrsctp.h"
int
main(void)
{
int i;
for (i = 0; i < 10000; i++) {
usrsctp_init(0, NULL, NULL);
while (usrsctp_finish() != 0) {
#ifdef _WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
}
return (0);
}
差异被折叠。
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: usrsctp
Description: SCTP implementation
URL: https://github.com/sctplab/usrsctp
Version: @VERSION@
Requires:
Libs: -L${libdir} -lusrsctp
Cflags: -I${includedir} @APPCFLAGS@
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论