Added remote folder

This commit is contained in:
Kasper Rynning-Tønnesen
2015-11-29 13:30:54 +01:00
parent 97e7dfd7c4
commit 95bb0c3919
3521 changed files with 331825 additions and 0 deletions

43
server/node_modules/mongodb/bug.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
"use strict"
const mongodb = require('./');
const connString = "mongodb://localhost:31000,localhost:31001,localhost:31002/test?readPreference=secondary";
// mongodb.Logger.setLevel('info')
function getStream(db) {
return db.collection('t').find({}).batchSize(2).stream();
}
mongodb.MongoClient.connect(connString, { replSet: { replicaSet: "rs", socketOptions: {
// socketTimeoutMS: 5000
} } })
.then((db) => {
// setTimeout(function() {
// console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ CLOSE")
// db.close();
// }, 10000)
db.serverConfig.on('left', function(t, s, s1) {
console.log("--------------------- left " + t + " = " + s.name)
})
db.serverConfig.on('joined', function(t, s, s1) {
console.log("--------------------- joined " + t + " = " + s1.name)
})
const stream = getStream(db);
stream.on('data', (doc) => {
// console.log(Date.now());
});
stream.on('error', (chunk) => {
console.error('Got an error from cursor');
});
stream.on('end', () => {
console.log('Got everything')
db.close();
});
})
.then(null, console.error);

608
server/node_modules/mongodb/lib/apm.js generated vendored Normal file
View File

@@ -0,0 +1,608 @@
var EventEmitter = require('events').EventEmitter,
inherits = require('util').inherits;
// Get prototypes
var AggregationCursor = require('./aggregation_cursor'),
CommandCursor = require('./command_cursor'),
OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation,
UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation,
GridStore = require('./gridfs/grid_store'),
Server = require('./server'),
ReplSet = require('./replset'),
Mongos = require('./mongos'),
Cursor = require('./cursor'),
Collection = require('./collection'),
Db = require('./db'),
Admin = require('./admin');
var basicOperationIdGenerator = {
operationId: 1,
next: function() {
return this.operationId++;
}
}
var basicTimestampGenerator = {
current: function() {
return new Date().getTime();
},
duration: function(start, end) {
return end - start;
}
}
var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce',
'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb'];
var Instrumentation = function(core, options, callback) {
options = options || {};
// Optional id generators
var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator;
// Optional timestamp generator
var timestampGenerator = options.timestampGenerator || basicTimestampGenerator;
// Extend with event emitter functionality
EventEmitter.call(this);
// Contains all the instrumentation overloads
this.overloads = [];
// ---------------------------------------------------------
//
// Instrument prototype
//
// ---------------------------------------------------------
var instrumentPrototype = function(callback) {
var instrumentations = []
// Classes to support
var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation,
CommandCursor, AggregationCursor, Cursor, Collection, Db];
// Add instrumentations to the available list
for(var i = 0; i < classes.length; i++) {
if(classes[i].define) {
instrumentations.push(classes[i].define.generate());
}
}
// Return the list of instrumentation points
callback(null, instrumentations);
}
// Did the user want to instrument the prototype
if(typeof callback == 'function') {
instrumentPrototype(callback);
}
// ---------------------------------------------------------
//
// Server
//
// ---------------------------------------------------------
// Reference
var self = this;
// Names of methods we need to wrap
var methods = ['command', 'insert', 'update', 'remove'];
// Prototype
var proto = core.Server.prototype;
// Core server method we are going to wrap
methods.forEach(function(x) {
var func = proto[x];
// Add to overloaded methods
self.overloads.push({proto: proto, name:x, func:func});
// The actual prototype
proto[x] = function() {
var requestId = core.Query.nextRequestId();
// Get the aruments
var args = Array.prototype.slice.call(arguments, 0);
var ns = args[0];
var commandObj = args[1];
var options = args[2] || {};
var keys = Object.keys(commandObj);
var commandName = keys[0];
var db = ns.split('.')[0];
// Do we have a legacy insert/update/remove command
if(x == 'insert' && !this.lastIsMaster().maxWireVersion) {
commandName = 'insert';
// Get the collection
var col = ns.split('.');
col.shift();
col = col.join('.');
// Re-write the command
commandObj = {
insert: col, documents: commandObj
}
if(options.writeConcern && Object.keys(options.writeConcern).length > 0) {
commandObj.writeConcern = options.writeConcern;
}
commandObj.ordered = options.ordered != undefined ? options.ordered : true;
} else if(x == 'update' && !this.lastIsMaster().maxWireVersion) {
commandName = 'update';
// Get the collection
var col = ns.split('.');
col.shift();
col = col.join('.');
// Re-write the command
commandObj = {
update: col, updates: commandObj
}
if(options.writeConcern && Object.keys(options.writeConcern).length > 0) {
commandObj.writeConcern = options.writeConcern;
}
commandObj.ordered = options.ordered != undefined ? options.ordered : true;
} else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) {
commandName = 'delete';
// Get the collection
var col = ns.split('.');
col.shift();
col = col.join('.');
// Re-write the command
commandObj = {
delete: col, deletes: commandObj
}
if(options.writeConcern && Object.keys(options.writeConcern).length > 0) {
commandObj.writeConcern = options.writeConcern;
}
commandObj.ordered = options.ordered != undefined ? options.ordered : true;
} else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) {
// Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher
return func.apply(this, args);
}
// Get the callback
var callback = args.pop();
// Set current callback operation id from the current context or create
// a new one
var ourOpId = callback.operationId || operationIdGenerator.next();
// Get a connection reference for this server instance
var connection = this.s.pool.get()
// Emit the start event for the command
var command = {
// Returns the command.
command: commandObj,
// Returns the database name.
databaseName: db,
// Returns the command name.
commandName: commandName,
// Returns the driver generated request id.
requestId: requestId,
// Returns the driver generated operation id.
// This is used to link events together such as bulk write operations. OPTIONAL.
operationId: ourOpId,
// Returns the connection id for the command. For languages that do not have this,
// this MUST return the driver equivalent which MUST include the server address and port.
// The name of this field is flexible to match the object that is returned from the driver.
connectionId: connection
};
// Filter out any sensitive commands
if(senstiveCommands.indexOf(commandName.toLowerCase())) {
command.commandObj = {};
command.commandObj[commandName] = true;
}
// Emit the started event
self.emit('started', command)
// Start time
var startTime = timestampGenerator.current();
// Push our handler callback
args.push(function(err, r) {
var endTime = timestampGenerator.current();
var command = {
duration: timestampGenerator.duration(startTime, endTime),
commandName: commandName,
requestId: requestId,
operationId: ourOpId,
connectionId: connection
};
// If we have an error
if(err || (r && r.result && r.result.ok == 0)) {
command.failure = err || r.result.writeErrors || r.result;
// Filter out any sensitive commands
if(senstiveCommands.indexOf(commandName.toLowerCase())) {
command.failure = {};
}
self.emit('failed', command);
} else if(commandObj && commandObj.writeConcern
&& commandObj.writeConcern.w == 0) {
// If we have write concern 0
command.reply = {ok:1};
self.emit('succeeded', command);
} else {
command.reply = r && r.result ? r.result : r;
// Filter out any sensitive commands
if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) {
command.reply = {};
}
self.emit('succeeded', command);
}
// Return to caller
callback(err, r);
});
// Apply the call
func.apply(this, args);
}
});
// ---------------------------------------------------------
//
// Bulk Operations
//
// ---------------------------------------------------------
// Inject ourselves into the Bulk methods
var methods = ['execute'];
var prototypes = [
require('./bulk/ordered').Bulk.prototype,
require('./bulk/unordered').Bulk.prototype
]
prototypes.forEach(function(proto) {
// Core server method we are going to wrap
methods.forEach(function(x) {
var func = proto[x];
// Add to overloaded methods
self.overloads.push({proto: proto, name:x, func:func});
// The actual prototype
proto[x] = function() {
var bulk = this;
// Get the aruments
var args = Array.prototype.slice.call(arguments, 0);
// Set an operation Id on the bulk object
this.operationId = operationIdGenerator.next();
// Get the callback
var callback = args.pop();
// If we have a callback use this
if(typeof callback == 'function') {
args.push(function(err, r) {
// Return to caller
callback(err, r);
});
// Apply the call
func.apply(this, args);
} else {
return func.apply(this, args);
}
}
});
});
// ---------------------------------------------------------
//
// Cursor
//
// ---------------------------------------------------------
// Inject ourselves into the Cursor methods
var methods = ['_find', '_getmore', '_killcursor'];
var prototypes = [
require('./cursor').prototype,
require('./command_cursor').prototype,
require('./aggregation_cursor').prototype
]
// Command name translation
var commandTranslation = {
'_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain'
}
prototypes.forEach(function(proto) {
// Core server method we are going to wrap
methods.forEach(function(x) {
var func = proto[x];
// Add to overloaded methods
self.overloads.push({proto: proto, name:x, func:func});
// The actual prototype
proto[x] = function() {
var cursor = this;
var requestId = core.Query.nextRequestId();
var ourOpId = operationIdGenerator.next();
var parts = this.ns.split('.');
var db = parts[0];
// Get the collection
parts.shift();
var collection = parts.join('.');
// Set the command
var command = this.query;
var cmd = this.s.cmd;
// If we have a find method, set the operationId on the cursor
if(x == '_find') {
cursor.operationId = ourOpId;
}
// Do we have a find command rewrite it
if(x == '_getmore') {
command = {
getMore: this.cursorState.cursorId,
collection: collection,
batchSize: cmd.batchSize
}
if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS;
} else if(x == '_killcursors') {
command = {
killCursors: collection,
cursors: [this.cursorState.cursorId]
}
} else if(cmd.find) {
command = {
find: collection, filter: cmd.query
}
if(cmd.sort) command.sort = cmd.sort;
if(cmd.fields) command.projection = cmd.fields;
if(cmd.limit && cmd.limit < 0) {
command.limit = Math.abs(cmd.limit);
command.singleBatch = true;
} else if(cmd.limit) {
command.limit = Math.abs(cmd.limit);
}
// Options
if(cmd.skip) command.skip = cmd.skip;
if(cmd.hint) command.hint = cmd.hint;
if(cmd.batchSize) command.batchSize = cmd.batchSize;
if(typeof cmd.returnKey == 'boolean') command.returnKey = cmd.returnKey;
if(cmd.comment) command.comment = cmd.comment;
if(cmd.min) command.min = cmd.min;
if(cmd.max) command.max = cmd.max;
if(cmd.maxScan) command.maxScan = cmd.maxScan;
if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS;
// Flags
if(typeof cmd.awaitData == 'boolean') command.awaitData = cmd.awaitData;
if(typeof cmd.snapshot == 'boolean') command.snapshot = cmd.snapshot;
if(typeof cmd.tailable == 'boolean') command.tailable = cmd.tailable;
if(typeof cmd.oplogReplay == 'boolean') command.oplogReplay = cmd.oplogReplay;
if(typeof cmd.noCursorTimeout == 'boolean') command.noCursorTimeout = cmd.noCursorTimeout;
if(typeof cmd.partial == 'boolean') command.partial = cmd.partial;
if(typeof cmd.showDiskLoc == 'boolean') command.showRecordId = cmd.showDiskLoc;
// Read Concern
if(cmd.readConcern) command.readConcern = cmd.readConcern;
// Override method
if(cmd.explain) command.explain = cmd.explain;
if(cmd.exhaust) command.exhaust = cmd.exhaust;
// If we have a explain flag
if(cmd.explain) {
// Create fake explain command
command = {
explain: command,
verbosity: 'allPlansExecution'
}
// Set readConcern on the command if available
if(cmd.readConcern) command.readConcern = cmd.readConcern
// Set up the _explain name for the command
x = '_explain';
}
} else {
command = cmd;
}
// Set up the connection
var connectionId = null;
// Set local connection
if(this.connection) connectionId = this.connection;
if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection();
// Get the command Name
var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x];
// Emit the start event for the command
var command = {
// Returns the command.
command: command,
// Returns the database name.
databaseName: db,
// Returns the command name.
commandName: commandName,
// Returns the driver generated request id.
requestId: requestId,
// Returns the driver generated operation id.
// This is used to link events together such as bulk write operations. OPTIONAL.
operationId: this.operationId,
// Returns the connection id for the command. For languages that do not have this,
// this MUST return the driver equivalent which MUST include the server address and port.
// The name of this field is flexible to match the object that is returned from the driver.
connectionId: connectionId
};
// Get the aruments
var args = Array.prototype.slice.call(arguments, 0);
// Get the callback
var callback = args.pop();
// We do not have a callback but a Promise
if(typeof callback == 'function' || command.commandName == 'killCursors') {
var startTime = timestampGenerator.current();
// Emit the started event
self.emit('started', command)
// Emit succeeded event with killcursor if we have a legacy protocol
if(command.commandName == 'killCursors'
&& this.server.lastIsMaster()
&& this.server.lastIsMaster().maxWireVersion < 4) {
// Emit the succeeded command
var command = {
duration: timestampGenerator.duration(startTime, timestampGenerator.current()),
commandName: commandName,
requestId: requestId,
operationId: cursor.operationId,
connectionId: cursor.server.getConnection(),
reply: [{ok:1}]
};
// Emit the command
return self.emit('succeeded', command)
}
// Add our callback handler
args.push(function(err, r) {
if(err) {
// Command
var command = {
duration: timestampGenerator.duration(startTime, timestampGenerator.current()),
commandName: commandName,
requestId: requestId,
operationId: ourOpId,
connectionId: cursor.server.getConnection(),
failure: err };
// Emit the command
self.emit('failed', command)
} else {
// Do we have a getMore
if(commandName.toLowerCase() == 'getmore' && r == null) {
r = {
cursor: {
id: cursor.cursorState.cursorId,
ns: cursor.ns,
nextBatch: cursor.cursorState.documents
}, ok:1
}
} else if(commandName.toLowerCase() == 'find' && r == null) {
r = {
cursor: {
id: cursor.cursorState.cursorId,
ns: cursor.ns,
firstBatch: cursor.cursorState.documents
}, ok:1
}
} else if(commandName.toLowerCase() == 'killcursors' && r == null) {
r = {
cursorsUnknown:[cursor.cursorState.lastCursorId],
ok:1
}
}
// cursor id is zero, we can issue success command
var command = {
duration: timestampGenerator.duration(startTime, timestampGenerator.current()),
commandName: commandName,
requestId: requestId,
operationId: cursor.operationId,
connectionId: cursor.server.getConnection(),
reply: r && r.result ? r.result : r
};
// Emit the command
self.emit('succeeded', command)
}
// Return
if(!callback) return;
// Return to caller
callback(err, r);
});
// Apply the call
func.apply(this, args);
} else {
// Assume promise, push back the missing value
args.push(callback);
// Get the promise
var promise = func.apply(this, args);
// Return a new promise
return new cursor.s.promiseLibrary(function(resolve, reject) {
var startTime = timestampGenerator.current();
// Emit the started event
self.emit('started', command)
// Execute the function
promise.then(function(r) {
// cursor id is zero, we can issue success command
var command = {
duration: timestampGenerator.duration(startTime, timestampGenerator.current()),
commandName: commandName,
requestId: requestId,
operationId: cursor.operationId,
connectionId: cursor.server.getConnection(),
reply: cursor.cursorState.documents
};
// Emit the command
self.emit('succeeded', command)
}).catch(function(err) {
// Command
var command = {
duration: timestampGenerator.duration(startTime, timestampGenerator.current()),
commandName: commandName,
requestId: requestId,
operationId: ourOpId,
connectionId: cursor.server.getConnection(),
failure: err };
// Emit the command
self.emit('failed', command)
// reject the promise
reject(err);
});
});
}
}
});
});
}
inherits(Instrumentation, EventEmitter);
Instrumentation.prototype.uninstrument = function() {
for(var i = 0; i < this.overloads.length; i++) {
var obj = this.overloads[i];
obj.proto[obj.name] = obj.func;
}
// Remove all listeners
this.removeAllListeners('started');
this.removeAllListeners('succeeded');
this.removeAllListeners('failed');
}
module.exports = Instrumentation;

View File

@@ -0,0 +1,310 @@
var shallowClone = require('../utils').shallowClone;
var stream = require('stream');
var util = require('util');
module.exports = GridFSBucketReadStream;
/**
* A readable stream that enables you to read buffers from GridFS.
*
* Do not instantiate this class directly. Use `openDownloadStream()` instead.
*
* @class
* @param {Collection} chunks Handle for chunks collection
* @param {Collection} files Handle for files collection
* @param {Object} readPreference The read preference to use
* @param {Object} filter The query to use to find the file document
* @param {Object} [options=null] Optional settings.
* @param {Number} [options.sort=null] Optional sort for the file find query
* @param {Number} [options.skip=null] Optional skip for the file find query
* @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from
* @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before
* @fires GridFSBucketReadStream#error
* @fires GridFSBucketReadStream#file
* @return {GridFSBucketReadStream} a GridFSBucketReadStream instance.
*/
function GridFSBucketReadStream(chunks, files, readPreference, filter, options) {
var _this = this;
this.s = {
bytesRead: 0,
chunks: chunks,
cursor: null,
expected: 0,
files: files,
filter: filter,
init: false,
expectedEnd: 0,
file: null,
options: options,
readPreference: readPreference
};
stream.Readable.call(this);
}
util.inherits(GridFSBucketReadStream, stream.Readable);
/**
* An error occurred
*
* @event GridFSBucketReadStream#error
* @type {Error}
*/
/**
* Fires when the stream loaded the file document corresponding to the
* provided id.
*
* @event GridFSBucketReadStream#file
* @type {object}
*/
/**
* Reads from the cursor and pushes to the stream.
* @method
*/
GridFSBucketReadStream.prototype._read = function() {
var _this = this;
waitForFile(_this, function() {
doRead(_this);
});
};
/**
* Sets the 0-based offset in bytes to start streaming from. Throws
* an error if this stream has entered flowing mode
* (e.g. if you've already called `on('data')`)
* @method
* @param {Number} start Offset in bytes to start reading at
* @return {GridFSBucketReadStream}
*/
GridFSBucketReadStream.prototype.start = function(start) {
throwIfInitialized(this);
this.s.options.start = start;
return this;
};
/**
* Sets the 0-based offset in bytes to start streaming from. Throws
* an error if this stream has entered flowing mode
* (e.g. if you've already called `on('data')`)
* @method
* @param {Number} end Offset in bytes to stop reading at
* @return {GridFSBucketReadStream}
*/
GridFSBucketReadStream.prototype.end = function(end) {
throwIfInitialized(this);
this.s.options.end = end;
return this;
};
/**
* @ignore
*/
function throwIfInitialized(self) {
if (self.s.init) {
throw new Error('You cannot change options after the stream has entered' +
'flowing mode!');
}
}
/**
* @ignore
*/
function doRead(_this) {
_this.s.cursor.next(function(error, doc) {
if (error) {
return __handleError(_this, error);
}
if (!doc) {
return _this.push(null);
}
var bytesRemaining = _this.s.file.length - _this.s.bytesRead;
var expectedN = _this.s.expected++;
var expectedLength = Math.min(_this.s.file.chunkSize,
bytesRemaining);
if (doc.n > expectedN) {
var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n +
', expected: ' + expectedN;
return __handleError(_this, new Error(errmsg));
}
if (doc.n < expectedN) {
var errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n +
', expected: ' + expectedN;
return __handleError(_this, new Error(errmsg));
}
if (doc.data.length() !== expectedLength) {
if (bytesRemaining <= 0) {
var errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n;
return __handleError(_this, new Error(errmsg));
}
var errmsg = 'ChunkIsWrongSize: Got unexpected length: ' +
doc.data.length() + ', expected: ' + expectedLength;
return __handleError(_this, new Error(errmsg));
}
_this.s.bytesRead += doc.data.length();
if (doc.data.buffer.length === 0) {
return _this.push(null);
}
var sliceStart = null;
var sliceEnd = null;
var buf = doc.data.buffer;
if (_this.s.bytesToSkip != null) {
sliceStart = _this.s.bytesToSkip;
_this.s.bytesToSkip = 0;
}
if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) {
sliceEnd = _this.s.bytesToTrim;
}
if (sliceStart != null || sliceEnd != null) {
buf = buf.slice(sliceStart || 0, sliceEnd || buf.length);
}
_this.push(buf);
});
};
/**
* @ignore
*/
function init(self) {
var findOneOptions = {};
if (self.s.readPreference) {
findOneOptions.readPreference = self.s.readPreference;
}
if (self.s.options && self.s.options.sort) {
findOneOptions.sort = self.s.options.sort;
}
if (self.s.options && self.s.options.skip) {
findOneOptions.skip = self.s.options.skip;
}
self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) {
if (error) {
return __handleError(self, error);
}
if (!doc) {
var identifier = self.s.filter._id ?
self.s.filter._id.toString() : self.s.filter.filename;
var errmsg = 'FileNotFound: file ' + identifier + ' was not found';
return __handleError(self, new Error(errmsg));
}
// If document is empty, kill the stream immediately and don't
// execute any reads
if (doc.length <= 0) {
self.push(null);
return;
}
self.s.cursor = self.s.chunks.find({ files_id: doc._id }).sort({ n: 1 });
if (self.s.readPreference) {
self.s.cursor.setReadPreference(self.s.readPreference);
}
self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);
self.s.file = doc;
self.s.bytesToSkip = handleStartOption(self, doc, self.s.cursor,
self.s.options);
self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor,
self.s.options);
self.emit('file', doc);
});
}
/**
* @ignore
*/
function waitForFile(_this, callback) {
if (_this.s.file) {
return callback();
}
if (!_this.s.init) {
init(_this);
_this.s.init = true;
}
_this.once('file', function() {
callback();
});
};
/**
* @ignore
*/
function handleStartOption(stream, doc, cursor, options) {
if (options && options.start != null) {
if (options.start > doc.length) {
throw new Error('Stream start (' + options.start + ') must not be ' +
'more than the length of the file (' + doc.length +')')
}
if (options.start < 0) {
throw new Error('Stream start (' + options.start + ') must not be ' +
'negative');
}
if (options.end != null && options.end < options.start) {
throw new Error('Stream start (' + options.start + ') must not be ' +
'greater than stream end (' + options.end + ')');
}
cursor.skip(Math.floor(options.start / doc.chunkSize));
stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) *
doc.chunkSize;
stream.s.expected = Math.floor(options.start / doc.chunkSize);
return options.start - stream.s.bytesRead;
}
}
/**
* @ignore
*/
function handleEndOption(stream, doc, cursor, options) {
if (options && options.end != null) {
if (options.end > doc.length) {
throw new Error('Stream end (' + options.end + ') must not be ' +
'more than the length of the file (' + doc.length +')')
}
if (options.start < 0) {
throw new Error('Stream end (' + options.end + ') must not be ' +
'negative');
}
var start = options.start != null ?
Math.floor(options.start / doc.chunkSize) :
0;
cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);
stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);
return (Math.ceil(options.end / doc.chunkSize) * doc.chunkSize) -
options.end;
}
}
/**
* @ignore
*/
function __handleError(_this, error) {
_this.emit('error', error);
}

335
server/node_modules/mongodb/lib/gridfs-stream/index.js generated vendored Normal file
View File

@@ -0,0 +1,335 @@
var Emitter = require('events').EventEmitter;
var GridFSBucketReadStream = require('./download');
var GridFSBucketWriteStream = require('./upload');
var shallowClone = require('../utils').shallowClone;
var toError = require('../utils').toError;
var util = require('util');
var DEFAULT_GRIDFS_BUCKET_OPTIONS = {
bucketName: 'fs',
chunkSizeBytes: 255 * 1024
};
module.exports = GridFSBucket;
/**
* Constructor for a streaming GridFS interface
* @class
* @param {Db} db A db handle
* @param {object} [options=null] Optional settings.
* @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot.
* @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB
* @param {object} [options.writeConcern=null] Optional write concern to be passed to write operations, for instance `{ w: 1 }`
* @param {object} [options.readPreference=null] Optional read preference to be passed to read operations
* @fires GridFSBucketWriteStream#index
* @return {GridFSBucket}
*/
function GridFSBucket(db, options) {
Emitter.apply(this);
this.setMaxListeners(0);
if (options && typeof options === 'object') {
options = shallowClone(options);
var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS);
for (var i = 0; i < keys.length; ++i) {
if (!options[keys[i]]) {
options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]];
}
}
} else {
options = DEFAULT_GRIDFS_BUCKET_OPTIONS;
}
this.s = {
db: db,
options: options,
_chunksCollection: db.collection(options.bucketName + '.chunks'),
_filesCollection: db.collection(options.bucketName + '.files'),
checkedIndexes: false,
calledOpenUploadStream: false,
promiseLibrary: db.s.promiseLibrary ||
(typeof global.Promise == 'function' ? global.Promise : require('es6-promise').Promise)
};
};
util.inherits(GridFSBucket, Emitter);
/**
* When the first call to openUploadStream is made, the upload stream will
* check to see if it needs to create the proper indexes on the chunks and
* files collections. This event is fired either when 1) it determines that
* no index creation is necessary, 2) when it successfully creates the
* necessary indexes.
*
* @event GridFSBucket#index
* @type {Error}
*/
/**
* Returns a writable stream (GridFSBucketWriteStream) for writing
* buffers to GridFS. The stream's 'id' property contains the resulting
* file's id.
* @method
* @param {string} filename The value of the 'filename' key in the files doc
* @param {object} [options=null] Optional settings.
* @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file
* @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field
* @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field
* @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field
* @return {GridFSBucketWriteStream}
*/
GridFSBucket.prototype.openUploadStream = function(filename, options) {
if (options) {
options = shallowClone(options);
} else {
options = {};
}
if (!options.chunkSizeBytes) {
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
}
return new GridFSBucketWriteStream(this, filename, options);
};
/**
* Returns a readable stream (GridFSBucketReadStream) for streaming file
* data from GridFS.
* @method
* @param {ObjectId} id The id of the file doc
* @param {Object} [options=null] Optional settings.
* @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from
* @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before
* @return {GridFSBucketReadStream}
*/
GridFSBucket.prototype.openDownloadStream = function(id, options) {
var filter = { _id: id };
var options = {
start: options && options.start,
end: options && options.end
};
return new GridFSBucketReadStream(this.s._chunksCollection,
this.s._filesCollection, this.s.options.readPreference, filter, options);
};
/**
* Deletes a file with the given id
* @method
* @param {ObjectId} id The id of the file doc
* @param {Function} callback
*/
GridFSBucket.prototype.delete = function(id, callback) {
if (typeof callback === 'function') {
return _delete(this, id, callback);
}
var _this = this;
return new this.s.promiseLibrary(function(resolve, reject) {
_delete(_this, id, function(error, res) {
if (error) {
reject(error);
} else {
resolve(res);
}
});
});
};
/**
* @ignore
*/
function _delete(_this, id, callback) {
_this.s._filesCollection.deleteOne({ _id: id }, function(error, res) {
if (error) {
return callback(error);
}
_this.s._chunksCollection.deleteMany({ files_id: id }, function(error) {
if (error) {
return callback(error);
}
// Delete orphaned chunks before returning FileNotFound
if (!res.result.n) {
var errmsg = 'FileNotFound: no file with id ' + id + ' found';
return callback(new Error(errmsg));
}
callback();
});
});
}
/**
* Convenience wrapper around find on the files collection
* @method
* @param {Object} filter
* @param {Object} [options=null] Optional settings for cursor
* @param {number} [options.batchSize=null] Optional batch size for cursor
* @param {number} [options.limit=null] Optional limit for cursor
* @param {number} [options.maxTimeMS=null] Optional maxTimeMS for cursor
* @param {boolean} [options.noCursorTimeout=null] Optionally set cursor's `noCursorTimeout` flag
* @param {number} [options.skip=null] Optional skip for cursor
* @param {object} [options.sort=null] Optional sort for cursor
* @return {Cursor}
*/
GridFSBucket.prototype.find = function(filter, options) {
filter = filter || {};
options = options || {};
var cursor = this.s._filesCollection.find(filter);
if (options.batchSize != null) {
cursor.batchSize(options.batchSize);
}
if (options.limit != null) {
cursor.limit(options.limit);
}
if (options.maxTimeMS != null) {
cursor.maxTimeMS(options.maxTimeMS);
}
if (options.noCursorTimeout != null) {
cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout);
}
if (options.skip != null) {
cursor.skip(options.skip);
}
if (options.sort != null) {
cursor.sort(options.sort);
}
return cursor;
};
/**
* Returns a readable stream (GridFSBucketReadStream) for streaming the
* file with the given name from GridFS. If there are multiple files with
* the same name, this will stream the most recent file with the given name
* (as determined by the `uploadedDate` field). You can set the `revision`
* option to change this behavior.
* @method
* @param {String} filename The name of the file to stream
* @param {Object} [options=null] Optional settings
* @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest.
* @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from
* @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before
* @return {GridFSBucketReadStream}
*/
GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) {
var sort = { uploadedDate: -1 };
var skip = null;
if (options && options.revision != null) {
if (options.revision >= 0) {
sort = { uploadedDate: 1 };
skip = options.revision;
} else {
skip = -options.revision - 1;
}
}
var filter = { filename: filename };
var options = {
sort: sort,
skip: skip,
start: options && options.start,
end: options && options.end
};
return new GridFSBucketReadStream(this.s._chunksCollection,
this.s._filesCollection, this.s.options.readPreference, filter, options);
};
/**
* Renames the file with the given _id to the given string
* @method
* @param {ObjectId} id the id of the file to rename
* @param {String} filename new name for the file
* @param {GridFSBucket~errorCallback} [callback]
*/
GridFSBucket.prototype.rename = function(id, filename, callback) {
if (typeof callback === 'function') {
return _rename(this, id, filename, callback);
}
var _this = this;
return new this.s.promiseLibrary(function(resolve, reject) {
_rename(_this, id, filename, function(error, res) {
if (error) {
reject(error);
} else {
resolve(res);
}
});
});
};
/**
* @ignore
*/
function _rename(_this, id, filename, callback) {
var filter = { _id: id };
var update = { $set: { filename: filename } };
_this.s._filesCollection.updateOne(filter, update, function(error, res) {
if (error) {
return callback(error);
}
if (!res.result.n) {
return callback(toError('File with id ' + id + ' not found'));
}
callback();
});
}
/**
* Removes this bucket's files collection, followed by its chunks collection.
* @method
* @param {GridFSBucket~errorCallback} [callback]
*/
GridFSBucket.prototype.drop = function(callback) {
if (typeof callback === 'function') {
return _drop(this, callback);
}
var _this = this;
return new this.s.promiseLibrary(function(resolve, reject) {
_drop(_this, function(error, res) {
if (error) {
reject(error);
} else {
resolve(res);
}
});
});
};
/**
* @ignore
*/
function _drop(_this, callback) {
_this.s._filesCollection.drop(function(error) {
if (error) {
return callback(error);
}
_this.s._chunksCollection.drop(function(error) {
if (error) {
return callback(error);
}
return callback();
});
});
}
/**
* Callback format for all GridFSBucket methods that can accept a callback.
* @callback GridFSBucket~errorCallback
* @param {MongoError} error An error instance representing any errors that occurred
*/

450
server/node_modules/mongodb/lib/gridfs-stream/upload.js generated vendored Normal file
View File

@@ -0,0 +1,450 @@
var core = require('mongodb-core');
var crypto = require('crypto');
var shallowClone = require('../utils').shallowClone;
var stream = require('stream');
var util = require('util');
var ERROR_NAMESPACE_NOT_FOUND = 26;
module.exports = GridFSBucketWriteStream;
/**
* A writable stream that enables you to write buffers to GridFS.
*
* Do not instantiate this class directly. Use `openUploadStream()` instead.
*
* @class
* @param {GridFSBucket} bucket Handle for this stream's corresponding bucket
* @param {string} filename The value of the 'filename' key in the files doc
* @param {object} [options=null] Optional settings.
* @param {number} [options.chunkSizeBytes=null] The chunk size to use, in bytes
* @param {number} [options.w=null] The write concern
* @param {number} [options.wtimeout=null] The write concern timeout
* @param {number} [options.j=null] The journal write concern
* @fires GridFSBucketWriteStream#error
* @fires GridFSBucketWriteStream#finish
* @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance.
*/
function GridFSBucketWriteStream(bucket, filename, options) {
this.bucket = bucket;
this.chunks = bucket.s._chunksCollection;
this.filename = filename;
this.files = bucket.s._filesCollection;
this.options = options;
this.id = core.BSON.ObjectId();
this.chunkSizeBytes = this.options.chunkSizeBytes;
this.bufToStore = new Buffer(this.chunkSizeBytes);
this.length = 0;
this.md5 = crypto.createHash('md5');
this.n = 0;
this.pos = 0;
this.state = {
streamEnd: false,
outstandingRequests: 0,
errored: false
};
if (!this.bucket.s.calledOpenUploadStream) {
this.bucket.s.calledOpenUploadStream = true;
var _this = this;
checkIndexes(this, function() {
_this.bucket.s.checkedIndexes = true;
_this.bucket.emit('index');
});
}
}
util.inherits(GridFSBucketWriteStream, stream.Writable);
/**
* An error occurred
*
* @event GridFSBucketWriteStream#error
* @type {Error}
*/
/**
* end() was called and the write stream successfully wrote all chunks to
* MongoDB.
*
* @event GridFSBucketWriteStream#finish
* @type {object}
*/
/**
* Write a buffer to the stream.
*
* @method
* @param {Buffer} chunk Buffer to write
* @param {String} encoding Optional encoding for the buffer
* @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
* @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise.
*/
GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) {
var _this = this;
return waitForIndexes(this, function() {
return doWrite(_this, chunk, encoding, callback);
});
};
/**
* Tells the stream that no more data will be coming in. The stream will
* persist the remaining data to MongoDB, write the files document, and
* then emit a 'finish' event.
*
* @method
* @param {Buffer} chunk Buffer to write
* @param {String} encoding Optional encoding for the buffer
* @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB
*/
GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) {
var _this = this;
this.state.streamEnd = true;
if (callback) {
this.once('finish', callback);
}
if (!chunk) {
waitForIndexes(this, function() {
writeRemnant(_this);
});
return;
}
var _this = this;
var inputBuf = (Buffer.isBuffer(chunk)) ?
chunk : new Buffer(chunk, encoding);
this.write(chunk, encoding, function() {
writeRemnant(_this);
});
};
/**
* @ignore
*/
function __handleError(_this, error, callback) {
if (_this.state.errored) {
return;
}
_this.state.errored = true;
if (callback) {
return callback(error);
}
_this.emit('error', error);
}
/**
* @ignore
*/
function createChunkDoc(filesId, n, data) {
return {
_id: core.BSON.ObjectId(),
files_id: filesId,
n: n,
data: data
};
}
/**
* @ignore
*/
function checkChunksIndex(_this, callback) {
_this.chunks.listIndexes().toArray(function(error, indexes) {
if (error) {
// Collection doesn't exist so create index
if (error.code === ERROR_NAMESPACE_NOT_FOUND) {
var index = { files_id: 1, n: 1 };
_this.chunks.createIndex(index, { background: false }, function(error) {
if (error) {
return callback(error);
}
callback();
});
return;
}
return callback(error);
}
var hasChunksIndex = false;
indexes.forEach(function(index) {
if (index.key) {
var keys = Object.keys(index.key);
if (keys.length === 2 && index.key.files_id === 1 &&
index.key.n === 1) {
hasChunksIndex = true;
}
}
});
if (hasChunksIndex) {
callback();
} else {
var index = { files_id: 1, n: 1 };
var indexOptions = getWriteOptions(_this);
indexOptions.background = false;
indexOptions.unique = true;
_this.chunks.createIndex(index, indexOptions, function(error) {
if (error) {
return callback(error);
}
callback();
});
}
});
}
/**
* @ignore
*/
function checkDone(_this, callback) {
if (_this.state.streamEnd &&
_this.state.outstandingRequests === 0 &&
!_this.state.errored) {
var filesDoc = createFilesDoc(_this.id, _this.length, _this.chunkSizeBytes,
_this.md5.digest('hex'), _this.filename, _this.options.contentType,
_this.options.aliases, _this.options.metadata);
_this.files.insert(filesDoc, getWriteOptions(_this), function(error) {
if (error) {
return __handleError(_this, error, callback);
}
_this.emit('finish', filesDoc);
});
return true;
}
return false;
}
/**
* @ignore
*/
function checkIndexes(_this, callback) {
_this.files.findOne({}, { _id: 1 }, function(error, doc) {
if (error) {
return callback(error);
}
if (doc) {
return callback();
}
_this.files.listIndexes().toArray(function(error, indexes) {
if (error) {
// Collection doesn't exist so create index
if (error.code === ERROR_NAMESPACE_NOT_FOUND) {
var index = { filename: 1, uploadDate: 1 };
_this.files.createIndex(index, { background: false }, function(error) {
if (error) {
return callback(error);
}
checkChunksIndex(_this, callback);
});
return;
}
return callback(error);
}
var hasFileIndex = false;
indexes.forEach(function(index) {
var keys = Object.keys(index.key);
if (keys.length === 2 && index.key.filename === 1 &&
index.key.uploadDate === 1) {
hasFileIndex = true;
}
});
if (hasFileIndex) {
checkChunksIndex(_this, callback);
} else {
var index = { filename: 1, uploadDate: 1 };
var indexOptions = getWriteOptions(_this);
indexOptions.background = false;
_this.files.createIndex(index, indexOptions, function(error) {
if (error) {
return callback(error);
}
checkChunksIndex(_this, callback);
});
}
});
});
}
/**
* @ignore
*/
function createFilesDoc(_id, length, chunkSize, md5, filename, contentType,
aliases, metadata) {
var ret = {
_id: _id,
length: length,
chunkSize: chunkSize,
uploadDate: new Date(),
md5: md5,
filename: filename
};
if (contentType) {
ret.contentType = contentType;
}
if (aliases) {
ret.aliases = aliases;
}
if (metadata) {
ret.metadata = metadata;
}
return ret;
}
/**
* @ignore
*/
function doWrite(_this, chunk, encoding, callback) {
var inputBuf = (Buffer.isBuffer(chunk)) ?
chunk : new Buffer(chunk, encoding);
_this.length += inputBuf.length;
// Input is small enough to fit in our buffer
if (_this.pos + inputBuf.length < _this.chunkSizeBytes) {
inputBuf.copy(_this.bufToStore, _this.pos);
_this.pos += inputBuf.length;
callback && callback();
// Note that we reverse the typical semantics of write's return value
// to be compatible with node's `.pipe()` function.
// True means client can keep writing.
return true;
}
// Otherwise, buffer is too big for current chunk, so we need to flush
// to MongoDB.
var inputBufRemaining = inputBuf.length;
var spaceRemaining = _this.chunkSizeBytes - _this.pos;
var numToCopy = Math.min(spaceRemaining, inputBuf.length);
var outstandingRequests = 0;
while (inputBufRemaining > 0) {
var inputBufPos = inputBuf.length - inputBufRemaining;
inputBuf.copy(_this.bufToStore, _this.pos,
inputBufPos, inputBufPos + numToCopy);
_this.pos += numToCopy;
spaceRemaining -= numToCopy;
if (spaceRemaining === 0) {
_this.md5.update(_this.bufToStore);
var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore);
++_this.state.outstandingRequests;
++outstandingRequests;
_this.chunks.insert(doc, getWriteOptions(_this), function(error) {
if (error) {
return __handleError(_this, error);
}
--_this.state.outstandingRequests;
--outstandingRequests;
if (!outstandingRequests) {
_this.emit('drain', doc);
callback && callback();
checkDone(_this);
}
});
spaceRemaining = _this.chunkSizeBytes;
_this.pos = 0;
++_this.n;
}
inputBufRemaining -= numToCopy;
numToCopy = Math.min(spaceRemaining, inputBufRemaining);
}
// Note that we reverse the typical semantics of write's return value
// to be compatible with node's `.pipe()` function.
// False means the client should wait for the 'drain' event.
return false;
}
/**
* @ignore
*/
function getWriteOptions(_this) {
var obj = {};
if (_this.options.writeConcern) {
obj.w = concern.w;
obj.wtimeout = concern.wtimeout;
obj.j = concern.j;
}
return obj;
}
/**
* @ignore
*/
function waitForIndexes(_this, callback) {
if (_this.bucket.s.checkedIndexes) {
callback(false);
}
_this.bucket.once('index', function() {
callback(true);
});
return true;
}
/**
* @ignore
*/
function writeRemnant(_this, callback) {
// Buffer is empty, so don't bother to insert
if (_this.pos === 0) {
return checkDone(_this, callback);
}
++_this.state.outstandingRequests;
// Create a new buffer to make sure the buffer isn't bigger than it needs
// to be.
var remnant = new Buffer(_this.pos);
_this.bufToStore.copy(remnant, 0, 0, _this.pos);
_this.md5.update(remnant);
var doc = createChunkDoc(_this.id, _this.n, remnant);
_this.chunks.insert(doc, getWriteOptions(_this), function(error) {
if (error) {
return __handleError(_this, error);
}
--_this.state.outstandingRequests;
checkDone(_this);
});
}

64
server/node_modules/mongodb/lib/metadata.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
var f = require('util').format;
var Define = function(name, object, stream) {
this.name = name;
this.object = object;
this.stream = typeof stream == 'boolean' ? stream : false;
this.instrumentations = {};
}
Define.prototype.classMethod = function(name, options) {
var keys = Object.keys(options).sort();
var key = generateKey(keys, options);
// Add a list of instrumentations
if(this.instrumentations[key] == null) {
this.instrumentations[key] = {
methods: [], options: options
}
}
// Push to list of method for this instrumentation
this.instrumentations[key].methods.push(name);
}
var generateKey = function(keys, options) {
var parts = [];
for(var i = 0; i < keys.length; i++) {
parts.push(f('%s=%s', keys[i], options[keys[i]]));
}
return parts.join();
}
Define.prototype.staticMethod = function(name, options) {
options.static = true;
var keys = Object.keys(options).sort();
var key = generateKey(keys, options);
// Add a list of instrumentations
if(this.instrumentations[key] == null) {
this.instrumentations[key] = {
methods: [], options: options
}
}
// Push to list of method for this instrumentation
this.instrumentations[key].methods.push(name);
}
Define.prototype.generate = function(keys, options) {
// Generate the return object
var object = {
name: this.name, obj: this.object, stream: this.stream,
instrumentations: []
}
for(var name in this.instrumentations) {
object.instrumentations.push(this.instrumentations[name]);
}
return object;
}
module.exports = Define;

32
server/node_modules/mongodb/load.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
var MongoClient = require('./').MongoClient;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
var col = db.collection('test');
col.ensureIndex({dt:-1}, function() {
var docs = [];
for(var i = 0; i < 100; i++) {
docs.push({a:i, dt:i, ot:i});
}
console.log("------------------------------- 0")
col.insertMany(docs, function() {
// Start firing finds
for(var i = 0; i < 100; i++) {
setInterval(function() {
col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) {
console.log("-------------------------------- 1")
});
}, 10)
}
// while(true) {
//
// // console.log("------------------------------- 1")
// col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) {
// console.log("-------------------------------- 1")
// });
// }
});
});
});

View File

@@ -0,0 +1,29 @@
# Master
# 3.0.2
* correctly bump both bower and package.json versions
# 3.0.1
* no longer include dist/test in npm releases
# 3.0.0
* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of
nodes are not affected as they were already using nextTick(). Note that using nextTick() might
trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410.
The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask
instead of a microtask and might result in a different scheduling.
If needed you can revert to the former behavior as follow:
var Promise = require('es6-promise').Promise;
Promise._setScheduler(setImmediate);
# 2.0.0
* re-sync with RSVP. Many large performance improvements and bugfixes.
# 1.0.0
* first subset of RSVP

View File

@@ -0,0 +1,19 @@
Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors
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.

View File

@@ -0,0 +1,61 @@
# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js))
This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js).
For API details and how to use promises, see the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises HTML5Rocks article</a>.
## Downloads
* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js)
* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.min.js)
## Node.js
To install:
```sh
npm install es6-promise
```
To use:
```js
var Promise = require('es6-promise').Promise;
```
## Usage in IE<9
`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example.
However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production:
```js
promise['catch'](function(err) {
// ...
});
```
Or use `.then` instead:
```js
promise.then(undefined, function(err) {
// ...
});
```
## Auto-polyfill
To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet:
```js
require('es6-promise').polyfill();
```
Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called.
## Building & Testing
* `npm run build` to build
* `npm test` to run tests
* `npm start` to run a build watcher, and webserver to test
* `npm run test:server` for a testem test runner and watching builder

View File

@@ -0,0 +1,967 @@
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 3.0.2
*/
(function() {
"use strict";
function lib$es6$promise$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function lib$es6$promise$utils$$isFunction(x) {
return typeof x === 'function';
}
function lib$es6$promise$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var lib$es6$promise$utils$$_isArray;
if (!Array.isArray) {
lib$es6$promise$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
lib$es6$promise$utils$$_isArray = Array.isArray;
}
var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
var lib$es6$promise$asap$$len = 0;
var lib$es6$promise$asap$$toString = {}.toString;
var lib$es6$promise$asap$$vertxNext;
var lib$es6$promise$asap$$customSchedulerFn;
var lib$es6$promise$asap$$asap = function asap(callback, arg) {
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
lib$es6$promise$asap$$len += 2;
if (lib$es6$promise$asap$$len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (lib$es6$promise$asap$$customSchedulerFn) {
lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
} else {
lib$es6$promise$asap$$scheduleFlush();
}
}
}
function lib$es6$promise$asap$$setScheduler(scheduleFn) {
lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
}
function lib$es6$promise$asap$$setAsap(asapFn) {
lib$es6$promise$asap$$asap = asapFn;
}
var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function lib$es6$promise$asap$$useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function() {
process.nextTick(lib$es6$promise$asap$$flush);
};
}
// vertx
function lib$es6$promise$asap$$useVertxTimer() {
return function() {
lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
};
}
function lib$es6$promise$asap$$useMutationObserver() {
var iterations = 0;
var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function lib$es6$promise$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = lib$es6$promise$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function lib$es6$promise$asap$$useSetTimeout() {
return function() {
setTimeout(lib$es6$promise$asap$$flush, 1);
};
}
var lib$es6$promise$asap$$queue = new Array(1000);
function lib$es6$promise$asap$$flush() {
for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
var callback = lib$es6$promise$asap$$queue[i];
var arg = lib$es6$promise$asap$$queue[i+1];
callback(arg);
lib$es6$promise$asap$$queue[i] = undefined;
lib$es6$promise$asap$$queue[i+1] = undefined;
}
lib$es6$promise$asap$$len = 0;
}
function lib$es6$promise$asap$$attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
return lib$es6$promise$asap$$useVertxTimer();
} catch(e) {
return lib$es6$promise$asap$$useSetTimeout();
}
}
var lib$es6$promise$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (lib$es6$promise$asap$$isNode) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
} else if (lib$es6$promise$asap$$BrowserMutationObserver) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
} else if (lib$es6$promise$asap$$isWorker) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
} else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
} else {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
}
function lib$es6$promise$$internal$$noop() {}
var lib$es6$promise$$internal$$PENDING = void 0;
var lib$es6$promise$$internal$$FULFILLED = 1;
var lib$es6$promise$$internal$$REJECTED = 2;
var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function lib$es6$promise$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function lib$es6$promise$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
return lib$es6$promise$$internal$$GET_THEN_ERROR;
}
}
function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
lib$es6$promise$asap$$asap(function(promise) {
var sealed = false;
var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
lib$es6$promise$$internal$$resolve(promise, value);
} else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
lib$es6$promise$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
lib$es6$promise$$internal$$reject(promise, error);
}
}, promise);
}
function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, thenable._result);
} else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, thenable._result);
} else {
lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
lib$es6$promise$$internal$$resolve(promise, value);
}, function(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
}
}
function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
var then = lib$es6$promise$$internal$$getThen(maybeThenable);
if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
} else if (lib$es6$promise$utils$$isFunction(then)) {
lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
}
}
}
function lib$es6$promise$$internal$$resolve(promise, value) {
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
} else if (lib$es6$promise$utils$$objectOrFunction(value)) {
lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
} else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}
function lib$es6$promise$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
lib$es6$promise$$internal$$publish(promise);
}
function lib$es6$promise$$internal$$fulfill(promise, value) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
promise._result = value;
promise._state = lib$es6$promise$$internal$$FULFILLED;
if (promise._subscribers.length !== 0) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
}
}
function lib$es6$promise$$internal$$reject(promise, reason) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
promise._state = lib$es6$promise$$internal$$REJECTED;
promise._result = reason;
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
}
function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
}
}
function lib$es6$promise$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function lib$es6$promise$$internal$$ErrorObject() {
this.error = null;
}
var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
}
}
function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = lib$es6$promise$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = lib$es6$promise$$internal$$tryCatch(callback, detail);
if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== lib$es6$promise$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
lib$es6$promise$$internal$$resolve(promise, value);
} else if (failed) {
lib$es6$promise$$internal$$reject(promise, error);
} else if (settled === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, value);
} else if (settled === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
}
}
function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
lib$es6$promise$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
} catch(e) {
lib$es6$promise$$internal$$reject(promise, e);
}
}
function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
var enumerator = this;
enumerator._instanceConstructor = Constructor;
enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
if (enumerator._validateInput(input)) {
enumerator._input = input;
enumerator.length = input.length;
enumerator._remaining = input.length;
enumerator._init();
if (enumerator.length === 0) {
lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
} else {
enumerator.length = enumerator.length || 0;
enumerator._enumerate();
if (enumerator._remaining === 0) {
lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
}
}
} else {
lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
}
}
lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
return lib$es6$promise$utils$$isArray(input);
};
lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
return new Error('Array Methods must be provided an Array');
};
lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
this._result = new Array(this.length);
};
var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
var enumerator = this;
var length = enumerator.length;
var promise = enumerator.promise;
var input = enumerator._input;
for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
enumerator._eachEntry(input[i], i);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var enumerator = this;
var c = enumerator._instanceConstructor;
if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
entry._onerror = null;
enumerator._settledAt(entry._state, i, entry._result);
} else {
enumerator._willSettleAt(c.resolve(entry), i);
}
} else {
enumerator._remaining--;
enumerator._result[i] = entry;
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var enumerator = this;
var promise = enumerator.promise;
if (promise._state === lib$es6$promise$$internal$$PENDING) {
enumerator._remaining--;
if (state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
} else {
enumerator._result[i] = value;
}
}
if (enumerator._remaining === 0) {
lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
});
};
function lib$es6$promise$promise$all$$all(entries) {
return new lib$es6$promise$enumerator$$default(this, entries).promise;
}
var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
function lib$es6$promise$promise$race$$race(entries) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(lib$es6$promise$$internal$$noop);
if (!lib$es6$promise$utils$$isArray(entries)) {
lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
lib$es6$promise$$internal$$resolve(promise, value);
}
function onRejection(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
}
for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
}
var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
function lib$es6$promise$promise$resolve$$resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$resolve(promise, object);
return promise;
}
var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
function lib$es6$promise$promise$reject$$reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$reject(promise, reason);
return promise;
}
var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
var lib$es6$promise$promise$$counter = 0;
function lib$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function lib$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function lib$es6$promise$promise$$Promise(resolver) {
this._id = lib$es6$promise$promise$$counter++;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if (lib$es6$promise$$internal$$noop !== resolver) {
if (!lib$es6$promise$utils$$isFunction(resolver)) {
lib$es6$promise$promise$$needsResolver();
}
if (!(this instanceof lib$es6$promise$promise$$Promise)) {
lib$es6$promise$promise$$needsNew();
}
lib$es6$promise$$internal$$initializePromise(this, resolver);
}
}
lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
lib$es6$promise$promise$$Promise.prototype = {
constructor: lib$es6$promise$promise$$Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: function(onFulfillment, onRejection) {
var parent = this;
var state = parent._state;
if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
return this;
}
var child = new this.constructor(lib$es6$promise$$internal$$noop);
var result = parent._result;
if (state) {
var callback = arguments[state - 1];
lib$es6$promise$asap$$asap(function(){
lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
});
} else {
lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
function lib$es6$promise$polyfill$$polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
return;
}
local.Promise = lib$es6$promise$promise$$default;
}
var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
var lib$es6$promise$umd$$ES6Promise = {
'Promise': lib$es6$promise$promise$$default,
'polyfill': lib$es6$promise$polyfill$$default
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return lib$es6$promise$umd$$ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = lib$es6$promise$umd$$ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
}
lib$es6$promise$polyfill$$default();
}).call(this);

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import Promise from './es6-promise/promise';
import polyfill from './es6-promise/polyfill';
var ES6Promise = {
'Promise': Promise,
'polyfill': polyfill
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = ES6Promise;
}
polyfill();

View File

@@ -0,0 +1,252 @@
import {
objectOrFunction,
isFunction
} from './utils';
import {
asap
} from './asap';
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch(error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function(promise) {
var sealed = false;
var error = tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function(value) {
resolve(promise, value);
}, function(reason) {
reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
handleOwnThenable(promise, maybeThenable);
} else {
var then = getThen(maybeThenable);
if (then === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
} else if (then === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then)) {
handleForeignThenable(promise, maybeThenable, then);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value);
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch(e) {
reject(promise, e);
}
}
export {
noop,
resolve,
reject,
fulfill,
subscribe,
publish,
publishRejection,
initializePromise,
invokeCallback,
FULFILLED,
REJECTED,
PENDING
};

View File

@@ -0,0 +1,120 @@
var len = 0;
var toString = {}.toString;
var vertxNext;
var customSchedulerFn;
export var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
}
export function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
export function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = (typeof window !== 'undefined') ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function() {
process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
return function() {
vertxNext(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i+=2) {
var callback = queue[i];
var arg = queue[i+1];
callback(arg);
queue[i] = undefined;
queue[i+1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch(e) {
return useSetTimeout();
}
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}

View File

@@ -0,0 +1,113 @@
import {
isArray,
isMaybeThenable
} from './utils';
import {
noop,
reject,
fulfill,
subscribe,
FULFILLED,
REJECTED,
PENDING
} from './-internal';
function Enumerator(Constructor, input) {
var enumerator = this;
enumerator._instanceConstructor = Constructor;
enumerator.promise = new Constructor(noop);
if (enumerator._validateInput(input)) {
enumerator._input = input;
enumerator.length = input.length;
enumerator._remaining = input.length;
enumerator._init();
if (enumerator.length === 0) {
fulfill(enumerator.promise, enumerator._result);
} else {
enumerator.length = enumerator.length || 0;
enumerator._enumerate();
if (enumerator._remaining === 0) {
fulfill(enumerator.promise, enumerator._result);
}
}
} else {
reject(enumerator.promise, enumerator._validationError());
}
}
Enumerator.prototype._validateInput = function(input) {
return isArray(input);
};
Enumerator.prototype._validationError = function() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._init = function() {
this._result = new Array(this.length);
};
export default Enumerator;
Enumerator.prototype._enumerate = function() {
var enumerator = this;
var length = enumerator.length;
var promise = enumerator.promise;
var input = enumerator._input;
for (var i = 0; promise._state === PENDING && i < length; i++) {
enumerator._eachEntry(input[i], i);
}
};
Enumerator.prototype._eachEntry = function(entry, i) {
var enumerator = this;
var c = enumerator._instanceConstructor;
if (isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== PENDING) {
entry._onerror = null;
enumerator._settledAt(entry._state, i, entry._result);
} else {
enumerator._willSettleAt(c.resolve(entry), i);
}
} else {
enumerator._remaining--;
enumerator._result[i] = entry;
}
};
Enumerator.prototype._settledAt = function(state, i, value) {
var enumerator = this;
var promise = enumerator.promise;
if (promise._state === PENDING) {
enumerator._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
enumerator._result[i] = value;
}
}
if (enumerator._remaining === 0) {
fulfill(promise, enumerator._result);
}
};
Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
subscribe(promise, undefined, function(value) {
enumerator._settledAt(FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt(REJECTED, i, reason);
});
};

View File

@@ -0,0 +1,26 @@
/*global self*/
import Promise from './promise';
export default function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
return;
}
local.Promise = Promise;
}

View File

@@ -0,0 +1,415 @@
import {
isFunction
} from './utils';
import {
noop,
subscribe,
initializePromise,
invokeCallback,
FULFILLED,
REJECTED
} from './-internal';
import {
asap,
setAsap,
setScheduler
} from './asap';
import all from './promise/all';
import race from './promise/race';
import Resolve from './promise/resolve';
import Reject from './promise/reject';
var counter = 0;
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
export default Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this._id = counter++;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if (noop !== resolver) {
if (!isFunction(resolver)) {
needsResolver();
}
if (!(this instanceof Promise)) {
needsNew();
}
initializePromise(this, resolver);
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = Resolve;
Promise.reject = Reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: function(onFulfillment, onRejection) {
var parent = this;
var state = parent._state;
if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
return this;
}
var child = new this.constructor(noop);
var result = parent._result;
if (state) {
var callback = arguments[state - 1];
asap(function(){
invokeCallback(state, child, callback, result);
});
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};

View File

@@ -0,0 +1,52 @@
import Enumerator from '../enumerator';
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
var promise1 = resolve(1);
var promise2 = resolve(2);
var promise3 = resolve(3);
var promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = resolve(1);
var promise2 = reject(new Error("2"));
var promise3 = reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
export default function all(entries) {
return new Enumerator(this, entries).promise;
}

View File

@@ -0,0 +1,104 @@
import {
isArray
} from "../utils";
import {
noop,
resolve,
reject,
subscribe,
PENDING
} from '../-internal';
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
var promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
var promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
var promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
var promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
export default function race(entries) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
if (!isArray(entries)) {
reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
resolve(promise, value);
}
function onRejection(reason) {
reject(promise, reason);
}
for (var i = 0; promise._state === PENDING && i < length; i++) {
subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
}

View File

@@ -0,0 +1,46 @@
import {
noop,
reject as _reject
} from '../-internal';
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
var promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
export default function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}

View File

@@ -0,0 +1,48 @@
import {
noop,
resolve as _resolve
} from '../-internal';
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
var promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
export default function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}

View File

@@ -0,0 +1,22 @@
export function objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
export function isFunction(x) {
return typeof x === 'function';
}
export function isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var _isArray;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
export var isArray = _isArray;

View File

@@ -0,0 +1,93 @@
{
"name": "es6-promise",
"namespace": "es6-promise",
"version": "3.0.2",
"description": "A lightweight library that provides tools for organizing asynchronous code",
"main": "dist/es6-promise.js",
"directories": {
"lib": "lib"
},
"files": [
"dist",
"lib",
"!dist/test"
],
"devDependencies": {
"bower": "^1.3.9",
"brfs": "0.0.8",
"broccoli-es3-safe-recast": "0.0.8",
"broccoli-es6-module-transpiler": "^0.5.0",
"broccoli-jshint": "^0.5.1",
"broccoli-merge-trees": "^0.1.4",
"broccoli-replace": "^0.2.0",
"broccoli-stew": "0.0.6",
"broccoli-uglify-js": "^0.1.3",
"broccoli-watchify": "^0.2.0",
"ember-cli": "0.2.3",
"ember-publisher": "0.0.7",
"git-repo-version": "0.0.2",
"json3": "^3.3.2",
"minimatch": "^2.0.1",
"mocha": "^1.20.1",
"promises-aplus-tests-phantom": "^2.1.0-revise",
"release-it": "0.0.10"
},
"scripts": {
"build": "ember build",
"start": "ember s",
"test": "ember test",
"test:server": "ember test --server",
"test:node": "ember build && mocha ./dist/test/browserify",
"lint": "jshint lib",
"prepublish": "ember build --environment production",
"dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive"
},
"repository": {
"type": "git",
"url": "git://github.com/jakearchibald/ES6-Promises.git"
},
"bugs": {
"url": "https://github.com/jakearchibald/ES6-Promises/issues"
},
"browser": {
"vertx": false
},
"keywords": [
"promises",
"futures"
],
"author": {
"name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors",
"url": "Conversion to ES6 API by Jake Archibald"
},
"license": "MIT",
"spm": {
"main": "dist/es6-promise.js"
},
"gitHead": "6c49ef79609737bac2b496d508806a3d5e37303e",
"homepage": "https://github.com/jakearchibald/ES6-Promises#readme",
"_id": "es6-promise@3.0.2",
"_shasum": "010d5858423a5f118979665f46486a95c6ee2bb6",
"_from": "es6-promise@3.0.2",
"_npmVersion": "2.13.4",
"_nodeVersion": "2.2.1",
"_npmUser": {
"name": "stefanpenner",
"email": "stefan.penner@gmail.com"
},
"maintainers": [
{
"name": "jaffathecake",
"email": "jaffathecake@gmail.com"
},
{
"name": "stefanpenner",
"email": "stefan.penner@gmail.com"
}
],
"dist": {
"shasum": "010d5858423a5f118979665f46486a95c6ee2bb6",
"tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz"
},
"_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz"
}

View File

@@ -0,0 +1,20 @@
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "iojs-v1.8.4"
- "iojs-v2.5.0"
- "iojs-v3.3.0"
- "4"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.8
before_install:
- '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@1.4.28'
- if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi
- $CXX --version
- npm explore npm -g -- npm install node-gyp@latest

View File

@@ -0,0 +1,7 @@
0.0.17 10-30-2015
-----------------
- Reverted changes in package.json from 0.0.16.
0.0.16 10-26-2015
-----------------
- Removed (exit 0) on build to let correct failure happen.

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,70 @@
Kerberos
========
The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build node.js itself to be able to compile and install the `kerberos` module. Furthermore the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager what libraries to install.
{{% note class="important" %}}
Windows already contains the SSPI API used for Kerberos authentication. However you will need to install a full compiler tool chain using visual studio C++ to correctly install the kerberos extension.
{{% /note %}}
### Diagnosing on UNIX
If you dont have the build essentials it wont build. In the case of linux you will need gcc and g++, node.js with all the headers and python. The easiest way to figure out whats missing is by trying to build the kerberos project. You can do this by performing the following steps.
```
git clone https://github.com/christkv/kerberos.git
cd kerberos
npm install
```
If all the steps complete you have the right toolchain installed. If you get node-gyp not found you need to install it globally by doing.
```
npm install -g node-gyp
```
If correctly compiles and runs the tests you are golden. We can now try to install the kerberos module by performing the following command.
```
cd yourproject
npm install kerberos --save
```
If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
```
npm --loglevel verbose install kerberos
```
This will print out all the steps npm is performing while trying to install the module.
### Diagnosing on Windows
A known compiler tool chain known to work for compiling `kerberos` on windows is the following.
* Visual Studio c++ 2010 (do not use higher versions)
* Windows 7 64bit SDK
* Python 2.7 or higher
Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp.
```
npm install -g node-gyp
```
Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo.
```
git clone https://github.com/christkv/kerberos.git
cd kerberos
npm install
node-gyp rebuild
```
This should rebuild the driver successfully if you have everything set up correctly.
### Other possible issues
Your python installation might be hosed making gyp break. I always recommend that you test your deployment environment first by trying to build node itself on the server in question as this should unearth any issues with broken packages (and there are a lot of broken packages out there).
Another thing is to ensure your user has write permission to wherever the node modules are being installed.

View File

@@ -0,0 +1,46 @@
{
'targets': [
{
'target_name': 'kerberos',
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'include_dirs': [ '<!(node -e "require(\'nan\')")', '/usr/include/mit-krb5' ],
'conditions': [
['OS=="mac"', {
'sources': [ 'lib/kerberos.cc', 'lib/worker.cc', 'lib/kerberosgss.c', 'lib/base64.c', 'lib/kerberos_context.cc' ],
'defines': [
'__MACOSX_CORE__'
],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
},
"link_settings": {
"libraries": [
"-lkrb5"
]
}
}],
['OS=="linux"', {
'sources': [ 'lib/kerberos.cc', 'lib/worker.cc', 'lib/kerberosgss.c', 'lib/base64.c', 'lib/kerberos_context.cc' ],
'libraries': ['-lkrb5', '-lgssapi_krb5']
}],
['OS=="win"', {
'sources': [
'lib/win32/kerberos.cc',
'lib/win32/base64.c',
'lib/win32/worker.cc',
'lib/win32/kerberos_sspi.c',
'lib/win32/wrappers/security_buffer.cc',
'lib/win32/wrappers/security_buffer_descriptor.cc',
'lib/win32/wrappers/security_context.cc',
'lib/win32/wrappers/security_credentials.cc'
],
"link_settings": {
"libraries": [
]
}
}]
]
}
]
}

View File

@@ -0,0 +1,332 @@
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS) $(CPPFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
#
# Note: flock is used to seralize linking. Linking is a memory-intensive
# process so running parallel links can often lead to thrashing. To disable
# the serialization, override LINK via an envrionment variable as follows:
#
# export LINK=g++
#
# This will allow make to invoke N linker processes as specified in -jN.
LINK ?= flock $(builddir)/linker.lock $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,kerberos.target.mk)))),)
include kerberos.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/share/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/var/www/server/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/share/node-gyp/addon.gypi -I/usr/include/nodejs/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/usr/include/nodejs" "-Dmodule_root_dir=/var/www/server/node_modules/mongodb/node_modules/kerberos" binding.gyp
Makefile: $(srcdir)/../../../../../../../usr/share/node-gyp/addon.gypi $(srcdir)/../../../../../../../usr/include/nodejs/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif

View File

@@ -0,0 +1,6 @@
# This file is generated by gyp; do not edit.
export builddir_name ?= build/./.
.PHONY: all
all:
$(MAKE) kerberos

View File

@@ -0,0 +1,122 @@
# Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"clang": 0,
"gcc_version": 48,
"host_arch": "x64",
"node_byteorder": "little",
"node_install_npm": "false",
"node_prefix": "/usr",
"node_shared_cares": "true",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_openssl": "true",
"node_shared_v8": "true",
"node_shared_zlib": "true",
"node_tag": "",
"node_unsafe_optimizations": 0,
"node_use_dtrace": "false",
"node_use_etw": "false",
"node_use_openssl": "true",
"node_use_perfctr": "false",
"node_use_systemtap": "false",
"python": "/usr/bin/python",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_no_strict_aliasing": 1,
"v8_use_snapshot": "false",
"nodedir": "/usr/include/nodejs",
"copy_dev_lib": "true",
"standalone_static_library": 1,
"cache_lock_stale": "60000",
"sign_git_tag": "",
"user_agent": "npm/1.4.21 node/v0.10.25 linux x64",
"always_auth": "",
"bin_links": "true",
"key": "",
"description": "true",
"fetch_retries": "2",
"heading": "npm",
"user": "1000",
"force": "",
"cache_min": "10",
"init_license": "ISC",
"editor": "vi",
"rollback": "true",
"cache_max": "Infinity",
"userconfig": "/home/kasper/.npmrc",
"engine_strict": "",
"init_author_name": "",
"init_author_url": "",
"tmp": "/tmp",
"depth": "Infinity",
"save_dev": "",
"usage": "",
"cafile": "",
"https_proxy": "",
"onload_script": "",
"rebuild_bundle": "true",
"save_bundle": "",
"shell": "/bin/zsh",
"prefix": "/usr/local",
"registry": "https://registry.npmjs.org/",
"__DO_NOT_MODIFY_THIS_FILE___use__etc_npmrc_instead_": "true",
"browser": "",
"cache_lock_wait": "10000",
"save_optional": "",
"searchopts": "",
"versions": "",
"cache": "/home/kasper/.npm",
"ignore_scripts": "",
"searchsort": "name",
"version": "",
"local_address": "",
"viewer": "man",
"color": "true",
"fetch_retry_mintimeout": "10000",
"umask": "18",
"fetch_retry_maxtimeout": "60000",
"message": "%s",
"ca": "",
"cert": "",
"global": "",
"link": "",
"save": "",
"unicode": "true",
"long": "",
"production": "",
"unsafe_perm": "",
"node_version": "0.10.25",
"tag": "latest",
"git_tag_version": "true",
"shrinkwrap": "true",
"fetch_retry_factor": "10",
"npat": "",
"proprietary_attribs": "true",
"save_exact": "",
"strict_ssl": "true",
"username": "",
"globalconfig": "/etc/npmrc",
"dev": "",
"init_module": "/home/kasper/.npm-init.js",
"parseable": "",
"globalignorefile": "/etc/npmignore",
"cache_lock_retries": "10",
"save_prefix": "^",
"group": "1000",
"init_author_email": "",
"searchexclude": "",
"git": "git",
"optional": "true",
"email": "",
"json": "",
"spin": "true"
}
}

View File

@@ -0,0 +1,147 @@
# This file is generated by gyp; do not edit.
TOOLSET := target
TARGET := kerberos
DEFS_Debug := \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION' \
'-DDEBUG' \
'-D_DEBUG'
# Flags passed to all source files.
CFLAGS_Debug := \
-fPIC \
-Wall \
-Wextra \
-Wno-unused-parameter \
-pthread \
-m64 \
-g \
-O0
# Flags passed to only C files.
CFLAGS_C_Debug :=
# Flags passed to only C++ files.
CFLAGS_CC_Debug := \
-fno-rtti
INCS_Debug := \
-I/usr/include/nodejs/src \
-I/usr/include/nodejs/deps/uv/include \
-I/usr/include/nodejs/deps/v8/include \
-I$(srcdir)/node_modules/nan \
-I/usr/include/mit-krb5
DEFS_Release := \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION'
# Flags passed to all source files.
CFLAGS_Release := \
-fPIC \
-Wall \
-Wextra \
-Wno-unused-parameter \
-pthread \
-m64 \
-O2 \
-fno-strict-aliasing \
-fno-tree-vrp \
-fno-omit-frame-pointer
# Flags passed to only C files.
CFLAGS_C_Release :=
# Flags passed to only C++ files.
CFLAGS_CC_Release := \
-fno-rtti
INCS_Release := \
-I/usr/include/nodejs/src \
-I/usr/include/nodejs/deps/uv/include \
-I/usr/include/nodejs/deps/v8/include \
-I$(srcdir)/node_modules/nan \
-I/usr/include/mit-krb5
OBJS := \
$(obj).target/$(TARGET)/lib/kerberos.o \
$(obj).target/$(TARGET)/lib/worker.o \
$(obj).target/$(TARGET)/lib/kerberosgss.o \
$(obj).target/$(TARGET)/lib/base64.o \
$(obj).target/$(TARGET)/lib/kerberos_context.o
# Add to the list of files we specially track dependencies for.
all_deps += $(OBJS)
# CFLAGS et al overrides must be target-local.
# See "Target-specific Variable Values" in the GNU Make manual.
$(OBJS): TOOLSET := $(TOOLSET)
$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
# End of this set of suffix rules
### Rules for final target.
LDFLAGS_Debug := \
-pthread \
-rdynamic \
-m64
LDFLAGS_Release := \
-pthread \
-rdynamic \
-m64
LIBS := \
-lkrb5 \
-lgssapi_krb5
$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
$(obj).target/kerberos.node: LIBS := $(LIBS)
$(obj).target/kerberos.node: TOOLSET := $(TOOLSET)
$(obj).target/kerberos.node: $(OBJS) FORCE_DO_CMD
$(call do_cmd,solink_module)
all_deps += $(obj).target/kerberos.node
# Add target alias
.PHONY: kerberos
kerberos: $(builddir)/kerberos.node
# Copy this to the executable output path.
$(builddir)/kerberos.node: TOOLSET := $(TOOLSET)
$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD
$(call do_cmd,copy)
all_deps += $(builddir)/kerberos.node
# Short alias for building this executable.
.PHONY: kerberos.node
kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node
# Add executable to "all" target.
.PHONY: all
all: $(builddir)/kerberos.node

View File

@@ -0,0 +1,25 @@
../lib/kerberos.cc:848:43: error: no viable conversion from 'Handle<v8::Value>' to 'Local<v8::Value>'
Local<Value> info[2] = { Nan::Null(), result};
^~~~~~
/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:269:26: note: candidate constructor (the implicit copy constructor) not viable: cannot bind base class object of type 'Handle<v8::Value>' to derived class reference 'const v8::Local<v8::Value> &' for 1st argument
template <class T> class Local : public Handle<T> {
^
/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:272:29: note: candidate template ignored: could not match 'Local' against 'Handle'
template <class S> inline Local(Local<S> that)
^
/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:281:29: note: candidate template ignored: could not match 'S *' against 'Handle<v8::Value>'
template <class S> inline Local(S* that) : Handle<T>(that) { }
^
1 error generated.
make: *** [Release/obj.target/kerberos/lib/kerberos.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack at ChildProcess.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12)
gyp ERR! System Darwin 14.3.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/christkv/coding/projects/kerberos
gyp ERR! node -v v0.10.35
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok

View File

@@ -0,0 +1,6 @@
// Get the Kerberos library
module.exports = require('./lib/kerberos');
// Set up the auth processes
module.exports['processes'] = {
MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess
}

View File

@@ -0,0 +1,281 @@
var format = require('util').format;
var MongoAuthProcess = function(host, port, service_name) {
// Check what system we are on
if(process.platform == 'win32') {
this._processor = new Win32MongoProcessor(host, port, service_name);
} else {
this._processor = new UnixMongoProcessor(host, port, service_name);
}
}
MongoAuthProcess.prototype.init = function(username, password, callback) {
this._processor.init(username, password, callback);
}
MongoAuthProcess.prototype.transition = function(payload, callback) {
this._processor.transition(payload, callback);
}
/*******************************************************************
*
* Win32 SSIP Processor for MongoDB
*
*******************************************************************/
var Win32MongoProcessor = function(host, port, service_name) {
this.host = host;
this.port = port
// SSIP classes
this.ssip = require("../kerberos").SSIP;
// Set up first transition
this._transition = Win32MongoProcessor.first_transition(this);
// Set up service name
service_name = service_name || "mongodb";
// Set up target
this.target = format("%s/%s", service_name, host);
// Number of retries
this.retries = 10;
}
Win32MongoProcessor.prototype.init = function(username, password, callback) {
var self = this;
// Save the values used later
this.username = username;
this.password = password;
// Aquire credentials
this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) {
if(err) return callback(err);
// Save credentials
self.security_credentials = security_credentials;
// Callback with success
callback(null);
});
}
Win32MongoProcessor.prototype.transition = function(payload, callback) {
if(this._transition == null) return callback(new Error("Transition finished"));
this._transition(payload, callback);
}
Win32MongoProcessor.first_transition = function(self) {
return function(payload, callback) {
self.ssip.SecurityContext.initialize(
self.security_credentials,
self.target,
payload, function(err, security_context) {
if(err) return callback(err);
// If no context try again until we have no more retries
if(!security_context.hasContext) {
if(self.retries == 0) return callback(new Error("Failed to initialize security context"));
// Update the number of retries
self.retries = self.retries - 1;
// Set next transition
return self.transition(payload, callback);
}
// Set next transition
self._transition = Win32MongoProcessor.second_transition(self);
self.security_context = security_context;
// Return the payload
callback(null, security_context.payload);
});
}
}
Win32MongoProcessor.second_transition = function(self) {
return function(payload, callback) {
// Perform a step
self.security_context.initialize(self.target, payload, function(err, security_context) {
if(err) return callback(err);
// If no context try again until we have no more retries
if(!security_context.hasContext) {
if(self.retries == 0) return callback(new Error("Failed to initialize security context"));
// Update the number of retries
self.retries = self.retries - 1;
// Set next transition
self._transition = Win32MongoProcessor.first_transition(self);
// Retry
return self.transition(payload, callback);
}
// Set next transition
self._transition = Win32MongoProcessor.third_transition(self);
// Return the payload
callback(null, security_context.payload);
});
}
}
Win32MongoProcessor.third_transition = function(self) {
return function(payload, callback) {
var messageLength = 0;
// Get the raw bytes
var encryptedBytes = new Buffer(payload, 'base64');
var encryptedMessage = new Buffer(messageLength);
// Copy first byte
encryptedBytes.copy(encryptedMessage, 0, 0, messageLength);
// Set up trailer
var securityTrailerLength = encryptedBytes.length - messageLength;
var securityTrailer = new Buffer(securityTrailerLength);
// Copy the bytes
encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength);
// Types used
var SecurityBuffer = self.ssip.SecurityBuffer;
var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor;
// Set up security buffers
var buffers = [
new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes)
, new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer)
];
// Set up the descriptor
var descriptor = new SecurityBufferDescriptor(buffers);
// Decrypt the data
self.security_context.decryptMessage(descriptor, function(err, security_context) {
if(err) return callback(err);
var length = 4;
if(self.username != null) {
length += self.username.length;
}
var bytesReceivedFromServer = new Buffer(length);
bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION
bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION
bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION
bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION
if(self.username != null) {
var authorization_id_bytes = new Buffer(self.username, 'utf8');
authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0);
}
self.security_context.queryContextAttributes(0x00, function(err, sizes) {
if(err) return callback(err);
var buffers = [
new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer))
, new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer)
, new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize))
]
var descriptor = new SecurityBufferDescriptor(buffers);
self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) {
if(err) return callback(err);
callback(null, security_context.payload);
});
});
});
}
}
/*******************************************************************
*
* UNIX MIT Kerberos processor
*
*******************************************************************/
var UnixMongoProcessor = function(host, port, service_name) {
this.host = host;
this.port = port
// SSIP classes
this.Kerberos = require("../kerberos").Kerberos;
this.kerberos = new this.Kerberos();
service_name = service_name || "mongodb";
// Set up first transition
this._transition = UnixMongoProcessor.first_transition(this);
// Set up target
this.target = format("%s@%s", service_name, host);
// Number of retries
this.retries = 10;
}
UnixMongoProcessor.prototype.init = function(username, password, callback) {
var self = this;
this.username = username;
this.password = password;
// Call client initiate
this.kerberos.authGSSClientInit(
self.target
, this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) {
self.context = context;
// Return the context
callback(null, context);
});
}
UnixMongoProcessor.prototype.transition = function(payload, callback) {
if(this._transition == null) return callback(new Error("Transition finished"));
this._transition(payload, callback);
}
UnixMongoProcessor.first_transition = function(self) {
return function(payload, callback) {
self.kerberos.authGSSClientStep(self.context, '', function(err, result) {
if(err) return callback(err);
// Set up the next step
self._transition = UnixMongoProcessor.second_transition(self);
// Return the payload
callback(null, self.context.response);
})
}
}
UnixMongoProcessor.second_transition = function(self) {
return function(payload, callback) {
self.kerberos.authGSSClientStep(self.context, payload, function(err, result) {
if(err && self.retries == 0) return callback(err);
// Attempt to re-establish a context
if(err) {
// Adjust the number of retries
self.retries = self.retries - 1;
// Call same step again
return self.transition(payload, callback);
}
// Set up the next step
self._transition = UnixMongoProcessor.third_transition(self);
// Return the payload
callback(null, self.context.response || '');
});
}
}
UnixMongoProcessor.third_transition = function(self) {
return function(payload, callback) {
// GSS Client Unwrap
self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) {
if(err) return callback(err, false);
// Wrap the response
self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) {
if(err) return callback(err, false);
// Set up the next step
self._transition = UnixMongoProcessor.fourth_transition(self);
// Return the payload
callback(null, self.context.response);
});
});
}
}
UnixMongoProcessor.fourth_transition = function(self) {
return function(payload, callback) {
// Clean up context
self.kerberos.authGSSClientClean(self.context, function(err, result) {
if(err) return callback(err, false);
// Set the transition to null
self._transition = null;
// Callback with valid authentication
callback(null, true);
});
}
}
// Set the process
exports.MongoAuthProcess = MongoAuthProcess;

View File

@@ -0,0 +1,134 @@
/**
* Copyright (c) 2006-2008 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#include "base64.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
void die2(const char *message) {
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
// base64 tables
static char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static signed char index_64[128] =
{
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
};
#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)])
// base64_encode : base64 encode
//
// value : data to encode
// vlen : length of data
// (result) : new char[] - c-str of result
char *base64_encode(const unsigned char *value, int vlen)
{
char *result = (char *)malloc((vlen * 4) / 3 + 5);
if(result == NULL) die2("Memory allocation failed");
char *out = result;
while (vlen >= 3)
{
*out++ = basis_64[value[0] >> 2];
*out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)];
*out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)];
*out++ = basis_64[value[2] & 0x3F];
value += 3;
vlen -= 3;
}
if (vlen > 0)
{
*out++ = basis_64[value[0] >> 2];
unsigned char oval = (value[0] << 4) & 0x30;
if (vlen > 1) oval |= value[1] >> 4;
*out++ = basis_64[oval];
*out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C];
*out++ = '=';
}
*out = '\0';
return result;
}
// base64_decode : base64 decode
//
// value : c-str to decode
// rlen : length of decoded result
// (result) : new unsigned char[] - decoded result
unsigned char *base64_decode(const char *value, int *rlen)
{
*rlen = 0;
int c1, c2, c3, c4;
int vlen = strlen(value);
unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1);
if(result == NULL) die2("Memory allocation failed");
unsigned char *out = result;
while (1)
{
if (value[0]==0)
return result;
c1 = value[0];
if (CHAR64(c1) == -1)
goto base64_decode_error;;
c2 = value[1];
if (CHAR64(c2) == -1)
goto base64_decode_error;;
c3 = value[2];
if ((c3 != '=') && (CHAR64(c3) == -1))
goto base64_decode_error;;
c4 = value[3];
if ((c4 != '=') && (CHAR64(c4) == -1))
goto base64_decode_error;;
value += 4;
*out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4);
*rlen += 1;
if (c3 != '=')
{
*out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2);
*rlen += 1;
if (c4 != '=')
{
*out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4);
*rlen += 1;
}
}
}
base64_decode_error:
*result = 0;
*rlen = 0;
return result;
}

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) 2006-2008 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#ifndef BASE64_H
#define BASE64_H
char *base64_encode(const unsigned char *value, int vlen);
unsigned char *base64_decode(const char *value, int *rlen);
#endif

View File

@@ -0,0 +1,893 @@
#include "kerberos.h"
#include <stdlib.h>
#include <errno.h>
#include "worker.h"
#include "kerberos_context.h"
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
#endif
void die(const char *message) {
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
// Call structs
typedef struct AuthGSSClientCall {
uint32_t flags;
char *uri;
} AuthGSSClientCall;
typedef struct AuthGSSClientStepCall {
KerberosContext *context;
char *challenge;
} AuthGSSClientStepCall;
typedef struct AuthGSSClientUnwrapCall {
KerberosContext *context;
char *challenge;
} AuthGSSClientUnwrapCall;
typedef struct AuthGSSClientWrapCall {
KerberosContext *context;
char *challenge;
char *user_name;
} AuthGSSClientWrapCall;
typedef struct AuthGSSClientCleanCall {
KerberosContext *context;
} AuthGSSClientCleanCall;
typedef struct AuthGSSServerInitCall {
char *service;
bool constrained_delegation;
char *username;
} AuthGSSServerInitCall;
typedef struct AuthGSSServerCleanCall {
KerberosContext *context;
} AuthGSSServerCleanCall;
typedef struct AuthGSSServerStepCall {
KerberosContext *context;
char *auth_data;
} AuthGSSServerStepCall;
Kerberos::Kerberos() : Nan::ObjectWrap() {
}
Nan::Persistent<FunctionTemplate> Kerberos::constructor_template;
void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("Kerberos").ToLocalChecked());
// Set up method for the Kerberos instance
Nan::SetPrototypeMethod(t, "authGSSClientInit", AuthGSSClientInit);
Nan::SetPrototypeMethod(t, "authGSSClientStep", AuthGSSClientStep);
Nan::SetPrototypeMethod(t, "authGSSClientUnwrap", AuthGSSClientUnwrap);
Nan::SetPrototypeMethod(t, "authGSSClientWrap", AuthGSSClientWrap);
Nan::SetPrototypeMethod(t, "authGSSClientClean", AuthGSSClientClean);
Nan::SetPrototypeMethod(t, "authGSSServerInit", AuthGSSServerInit);
Nan::SetPrototypeMethod(t, "authGSSServerClean", AuthGSSServerClean);
Nan::SetPrototypeMethod(t, "authGSSServerStep", AuthGSSServerStep);
constructor_template.Reset(t);
// Set the symbol
target->ForceSet(Nan::New<String>("Kerberos").ToLocalChecked(), t->GetFunction());
}
NAN_METHOD(Kerberos::New) {
// Create a Kerberos instance
Kerberos *kerberos = new Kerberos();
// Return the kerberos object
kerberos->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSClientInit
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSClientInit(Worker *worker) {
gss_client_state *state;
gss_client_response *response;
// Allocate state
state = (gss_client_state *)malloc(sizeof(gss_client_state));
if(state == NULL) die("Memory allocation failed");
// Unpack the parameter data struct
AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters;
// Start the kerberos client
response = authenticate_gss_client_init(call->uri, call->flags, state);
// Release the parameter struct memory
free(call->uri);
free(call);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
free(state);
} else {
worker->return_value = state;
}
// Free structure
free(response);
}
static Local<Value> _map_authGSSClientInit(Worker *worker) {
KerberosContext *context = KerberosContext::New();
context->state = (gss_client_state *)worker->return_value;
return context->handle();
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSClientInit) {
// Ensure valid call
if(info.Length() != 3) return Nan::ThrowError("Requires a service string uri, integer flags and a callback function");
if(info.Length() == 3 && (!info[0]->IsString() || !info[1]->IsInt32() || !info[2]->IsFunction()))
return Nan::ThrowError("Requires a service string uri, integer flags and a callback function");
Local<String> service = info[0]->ToString();
// Convert uri string to c-string
char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char));
if(service_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
service->WriteUtf8(service_str);
// Allocate a structure
AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall));
if(call == NULL) die("Memory allocation failed");
call->flags =info[1]->ToInt32()->Uint32Value();
call->uri = service_str;
// Unpack the callback
Local<Function> callbackHandle = Local<Function>::Cast(info[2]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSClientInit;
worker->mapper = _map_authGSSClientInit;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSClientStep
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSClientStep(Worker *worker) {
gss_client_state *state;
gss_client_response *response;
char *challenge;
// Unpack the parameter data struct
AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters;
// Get the state
state = call->context->state;
challenge = call->challenge;
// Check what kind of challenge we have
if(call->challenge == NULL) {
challenge = (char *)"";
}
// Perform authentication step
response = authenticate_gss_client_step(state, challenge);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
} else {
worker->return_code = response->return_code;
}
// Free up structure
if(call->challenge != NULL) free(call->challenge);
free(call);
free(response);
}
static Local<Value> _map_authGSSClientStep(Worker *worker) {
Nan::HandleScope scope;
// Return the return code
return Nan::New<Int32>(worker->return_code);
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSClientStep) {
// Ensure valid call
if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function");
if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function");
if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function");
// Challenge string
char *challenge_str = NULL;
// Let's unpack the parameters
Local<Object> object = info[0]->ToObject();
KerberosContext *kerberos_context = KerberosContext::Unwrap<KerberosContext>(object);
if (!kerberos_context->IsClientInstance()) {
return Nan::ThrowError("GSS context is not a client instance");
}
int callbackArg = 1;
// If we have a challenge string
if(info.Length() == 3) {
// Unpack the challenge string
Local<String> challenge = info[1]->ToString();
// Convert uri string to c-string
challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char));
if(challenge_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
challenge->WriteUtf8(challenge_str);
callbackArg = 2;
}
// Allocate a structure
AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientStepCall));
if(call == NULL) die("Memory allocation failed");
call->context = kerberos_context;
call->challenge = challenge_str;
// Unpack the callback
Local<Function> callbackHandle = Local<Function>::Cast(info[callbackArg]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSClientStep;
worker->mapper = _map_authGSSClientStep;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSClientUnwrap
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSClientUnwrap(Worker *worker) {
gss_client_response *response;
char *challenge;
// Unpack the parameter data struct
AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters;
challenge = call->challenge;
// Check what kind of challenge we have
if(call->challenge == NULL) {
challenge = (char *)"";
}
// Perform authentication step
response = authenticate_gss_client_unwrap(call->context->state, challenge);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
} else {
worker->return_code = response->return_code;
}
// Free up structure
if(call->challenge != NULL) free(call->challenge);
free(call);
free(response);
}
static Local<Value> _map_authGSSClientUnwrap(Worker *worker) {
Nan::HandleScope scope;
// Return the return code
return Nan::New<Int32>(worker->return_code);
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSClientUnwrap) {
// Ensure valid call
if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function");
if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function");
if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function");
// Challenge string
char *challenge_str = NULL;
// Let's unpack the parameters
Local<Object> object = info[0]->ToObject();
KerberosContext *kerberos_context = KerberosContext::Unwrap<KerberosContext>(object);
if (!kerberos_context->IsClientInstance()) {
return Nan::ThrowError("GSS context is not a client instance");
}
// If we have a challenge string
if(info.Length() == 3) {
// Unpack the challenge string
Local<String> challenge = info[1]->ToString();
// Convert uri string to c-string
challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char));
if(challenge_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
challenge->WriteUtf8(challenge_str);
}
// Allocate a structure
AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall));
if(call == NULL) die("Memory allocation failed");
call->context = kerberos_context;
call->challenge = challenge_str;
// Unpack the callback
Local<Function> callbackHandle = info.Length() == 3 ? Local<Function>::Cast(info[2]) : Local<Function>::Cast(info[1]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSClientUnwrap;
worker->mapper = _map_authGSSClientUnwrap;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSClientWrap
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSClientWrap(Worker *worker) {
gss_client_response *response;
char *user_name = NULL;
// Unpack the parameter data struct
AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters;
user_name = call->user_name;
// Check what kind of challenge we have
if(call->user_name == NULL) {
user_name = (char *)"";
}
// Perform authentication step
response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
} else {
worker->return_code = response->return_code;
}
// Free up structure
if(call->challenge != NULL) free(call->challenge);
if(call->user_name != NULL) free(call->user_name);
free(call);
free(response);
}
static Local<Value> _map_authGSSClientWrap(Worker *worker) {
Nan::HandleScope scope;
// Return the return code
return Nan::New<Int32>(worker->return_code);
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSClientWrap) {
// Ensure valid call
if(info.Length() != 3 && info.Length() != 4) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function");
if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function");
if(info.Length() == 4 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsString() || !info[3]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function");
// Challenge string
char *challenge_str = NULL;
char *user_name_str = NULL;
// Let's unpack the kerberos context
Local<Object> object = info[0]->ToObject();
KerberosContext *kerberos_context = KerberosContext::Unwrap<KerberosContext>(object);
if (!kerberos_context->IsClientInstance()) {
return Nan::ThrowError("GSS context is not a client instance");
}
// Unpack the challenge string
Local<String> challenge = info[1]->ToString();
// Convert uri string to c-string
challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char));
if(challenge_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
challenge->WriteUtf8(challenge_str);
// If we have a user string
if(info.Length() == 4) {
// Unpack user name
Local<String> user_name = info[2]->ToString();
// Convert uri string to c-string
user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char));
if(user_name_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
user_name->WriteUtf8(user_name_str);
}
// Allocate a structure
AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall));
if(call == NULL) die("Memory allocation failed");
call->context = kerberos_context;
call->challenge = challenge_str;
call->user_name = user_name_str;
// Unpack the callback
Local<Function> callbackHandle = info.Length() == 4 ? Local<Function>::Cast(info[3]) : Local<Function>::Cast(info[2]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSClientWrap;
worker->mapper = _map_authGSSClientWrap;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSClientClean
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSClientClean(Worker *worker) {
gss_client_response *response;
// Unpack the parameter data struct
AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters;
// Perform authentication step
response = authenticate_gss_client_clean(call->context->state);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
} else {
worker->return_code = response->return_code;
}
// Free up structure
free(call);
free(response);
}
static Local<Value> _map_authGSSClientClean(Worker *worker) {
Nan::HandleScope scope;
// Return the return code
return Nan::New<Int32>(worker->return_code);
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSClientClean) {
// Ensure valid call
if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function");
if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function");
// Let's unpack the kerberos context
Local<Object> object = info[0]->ToObject();
KerberosContext *kerberos_context = KerberosContext::Unwrap<KerberosContext>(object);
if (!kerberos_context->IsClientInstance()) {
return Nan::ThrowError("GSS context is not a client instance");
}
// Allocate a structure
AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall));
if(call == NULL) die("Memory allocation failed");
call->context = kerberos_context;
// Unpack the callback
Local<Function> callbackHandle = Local<Function>::Cast(info[1]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSClientClean;
worker->mapper = _map_authGSSClientClean;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSServerInit
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSServerInit(Worker *worker) {
gss_server_state *state;
gss_client_response *response;
// Allocate state
state = (gss_server_state *)malloc(sizeof(gss_server_state));
if(state == NULL) die("Memory allocation failed");
// Unpack the parameter data struct
AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)worker->parameters;
// Start the kerberos service
response = authenticate_gss_server_init(call->service, call->constrained_delegation, call->username, state);
// Release the parameter struct memory
free(call->service);
free(call->username);
free(call);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
free(state);
} else {
worker->return_value = state;
}
// Free structure
free(response);
}
static Local<Value> _map_authGSSServerInit(Worker *worker) {
KerberosContext *context = KerberosContext::New();
context->server_state = (gss_server_state *)worker->return_value;
return context->handle();
}
// Server Initialize method
NAN_METHOD(Kerberos::AuthGSSServerInit) {
// Ensure valid call
if(info.Length() != 4) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function");
if(!info[0]->IsString() ||
!info[1]->IsBoolean() ||
!(info[2]->IsString() || info[2]->IsNull()) ||
!info[3]->IsFunction()
) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function");
if (!info[1]->BooleanValue() && !info[2]->IsNull()) return Nan::ThrowError("S4U2Self only possible when constrained delegation is enabled");
// Allocate a structure
AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)calloc(1, sizeof(AuthGSSServerInitCall));
if(call == NULL) die("Memory allocation failed");
Local<String> service = info[0]->ToString();
// Convert service string to c-string
char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char));
if(service_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
service->WriteUtf8(service_str);
call->service = service_str;
call->constrained_delegation = info[1]->BooleanValue();
if (info[2]->IsNull())
{
call->username = NULL;
}
else
{
Local<String> tmpString = info[2]->ToString();
char *tmpCstr = (char *)calloc(tmpString->Utf8Length() + 1, sizeof(char));
if(tmpCstr == NULL) die("Memory allocation failed");
tmpString->WriteUtf8(tmpCstr);
call->username = tmpCstr;
}
// Unpack the callback
Local<Function> callbackHandle = Local<Function>::Cast(info[3]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSServerInit;
worker->mapper = _map_authGSSServerInit;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSServerClean
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSServerClean(Worker *worker) {
gss_client_response *response;
// Unpack the parameter data struct
AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)worker->parameters;
// Perform authentication step
response = authenticate_gss_server_clean(call->context->server_state);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
} else {
worker->return_code = response->return_code;
}
// Free up structure
free(call);
free(response);
}
static Local<Value> _map_authGSSServerClean(Worker *worker) {
Nan::HandleScope scope;
// Return the return code
return Nan::New<Int32>(worker->return_code);
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSServerClean) {
// // Ensure valid call
if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function");
if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function");
// Let's unpack the kerberos context
Local<Object> object = info[0]->ToObject();
KerberosContext *kerberos_context = KerberosContext::Unwrap<KerberosContext>(object);
if (!kerberos_context->IsServerInstance()) {
return Nan::ThrowError("GSS context is not a server instance");
}
// Allocate a structure
AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)calloc(1, sizeof(AuthGSSServerCleanCall));
if(call == NULL) die("Memory allocation failed");
call->context = kerberos_context;
// Unpack the callback
Local<Function> callbackHandle = Local<Function>::Cast(info[1]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSServerClean;
worker->mapper = _map_authGSSServerClean;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSServerStep
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authGSSServerStep(Worker *worker) {
gss_server_state *state;
gss_client_response *response;
char *auth_data;
// Unpack the parameter data struct
AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)worker->parameters;
// Get the state
state = call->context->server_state;
auth_data = call->auth_data;
// Check if we got auth_data or not
if(call->auth_data == NULL) {
auth_data = (char *)"";
}
// Perform authentication step
response = authenticate_gss_server_step(state, auth_data);
// If we have an error mark worker as having had an error
if(response->return_code == AUTH_GSS_ERROR) {
worker->error = TRUE;
worker->error_code = response->return_code;
worker->error_message = response->message;
} else {
worker->return_code = response->return_code;
}
// Free up structure
if(call->auth_data != NULL) free(call->auth_data);
free(call);
free(response);
}
static Local<Value> _map_authGSSServerStep(Worker *worker) {
Nan::HandleScope scope;
// Return the return code
return Nan::New<Int32>(worker->return_code);
}
// Initialize method
NAN_METHOD(Kerberos::AuthGSSServerStep) {
// Ensure valid call
if(info.Length() != 3) return Nan::ThrowError("Requires a GSS context, auth-data string and callback function");
if(!KerberosContext::HasInstance(info[0])) return Nan::ThrowError("1st arg must be a GSS context");
if (!info[1]->IsString()) return Nan::ThrowError("2nd arg must be auth-data string");
if (!info[2]->IsFunction()) return Nan::ThrowError("3rd arg must be a callback function");
// Auth-data string
char *auth_data_str = NULL;
// Let's unpack the parameters
Local<Object> object = info[0]->ToObject();
KerberosContext *kerberos_context = KerberosContext::Unwrap<KerberosContext>(object);
if (!kerberos_context->IsServerInstance()) {
return Nan::ThrowError("GSS context is not a server instance");
}
// Unpack the auth_data string
Local<String> auth_data = info[1]->ToString();
// Convert uri string to c-string
auth_data_str = (char *)calloc(auth_data->Utf8Length() + 1, sizeof(char));
if(auth_data_str == NULL) die("Memory allocation failed");
// Write v8 string to c-string
auth_data->WriteUtf8(auth_data_str);
// Allocate a structure
AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)calloc(1, sizeof(AuthGSSServerStepCall));
if(call == NULL) die("Memory allocation failed");
call->context = kerberos_context;
call->auth_data = auth_data_str;
// Unpack the callback
Local<Function> callbackHandle = Local<Function>::Cast(info[2]);
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authGSSServerStep;
worker->mapper = _map_authGSSServerStep;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// UV Lib callbacks
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void Kerberos::Process(uv_work_t* work_req) {
// Grab the worker
Worker *worker = static_cast<Worker*>(work_req->data);
// Execute the worker code
worker->execute(worker);
}
void Kerberos::After(uv_work_t* work_req) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Get the worker reference
Worker *worker = static_cast<Worker*>(work_req->data);
// If we have an error
if(worker->error) {
Local<Value> err = v8::Exception::Error(Nan::New<String>(worker->error_message).ToLocalChecked());
Local<Object> obj = err->ToObject();
obj->Set(Nan::New<String>("code").ToLocalChecked(), Nan::New<Int32>(worker->error_code));
Local<Value> info[2] = { err, Nan::Null() };
// Execute the error
Nan::TryCatch try_catch;
// Call the callback
worker->callback->Call(ARRAY_SIZE(info), info);
// If we have an exception handle it as a fatalexception
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
} else {
// // Map the data
Local<Value> result = worker->mapper(worker);
// Set up the callback with a null first
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Local<Value> info[2] = { Nan::Null(), result};
#else
Local<Value> info[2] = { Nan::Null(), Nan::New<v8::Value>(result)};
#endif
// Wrap the callback function call in a TryCatch so that we can call
// node's FatalException afterwards. This makes it possible to catch
// the exception from JavaScript land using the
// process.on('uncaughtException') event.
Nan::TryCatch try_catch;
// Call the callback
worker->callback->Call(ARRAY_SIZE(info), info);
// If we have an exception handle it as a fatalexception
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
}
// Clean up the memory
delete worker->callback;
delete worker;
}
// Exporting function
NAN_MODULE_INIT(init) {
Kerberos::Initialize(target);
KerberosContext::Initialize(target);
}
NODE_MODULE(kerberos, init);

View File

@@ -0,0 +1,50 @@
#ifndef KERBEROS_H
#define KERBEROS_H
#include <node.h>
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_generic.h>
#include <gssapi/gssapi_krb5.h>
#include "nan.h"
#include <node_object_wrap.h>
#include <v8.h>
extern "C" {
#include "kerberosgss.h"
}
using namespace v8;
using namespace node;
class Kerberos : public Nan::ObjectWrap {
public:
Kerberos();
~Kerberos() {};
// Constructor used for creating new Kerberos objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
// Initialize function for the object
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
// Method available
static NAN_METHOD(AuthGSSClientInit);
static NAN_METHOD(AuthGSSClientStep);
static NAN_METHOD(AuthGSSClientUnwrap);
static NAN_METHOD(AuthGSSClientWrap);
static NAN_METHOD(AuthGSSClientClean);
static NAN_METHOD(AuthGSSServerInit);
static NAN_METHOD(AuthGSSServerClean);
static NAN_METHOD(AuthGSSServerStep);
private:
static NAN_METHOD(New);
// Handles the uv calls
static void Process(uv_work_t* work_req);
// Called after work is done
static void After(uv_work_t* work_req);
};
#endif

View File

@@ -0,0 +1,164 @@
var kerberos = require('../build/Release/kerberos')
, KerberosNative = kerberos.Kerberos;
var Kerberos = function() {
this._native_kerberos = new KerberosNative();
}
// callback takes two arguments, an error string if defined and a new context
// uri should be given as service@host. Services are not always defined
// in a straightforward way. Use 'HTTP' for SPNEGO / Negotiate authentication.
Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) {
return this._native_kerberos.authGSSClientInit(uri, flags, callback);
}
// This will obtain credentials using a credentials cache. To override the default
// location (posible /tmp/krb5cc_nnnnnn, where nnnn is your numeric uid) use
// the environment variable KRB5CNAME.
// The credentials (suitable for using in an 'Authenticate: ' header, when prefixed
// with 'Negotiate ') will be available as context.response inside the callback
// if no error is indicated.
// callback takes one argument, an error string if defined
Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) {
if(typeof challenge == 'function') {
callback = challenge;
challenge = '';
}
return this._native_kerberos.authGSSClientStep(context, challenge, callback);
}
Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) {
if(typeof challenge == 'function') {
callback = challenge;
challenge = '';
}
return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback);
}
Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) {
if(typeof user_name == 'function') {
callback = user_name;
user_name = '';
}
return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback);
}
// free memory used by a context created using authGSSClientInit.
// callback takes one argument, an error string if defined.
Kerberos.prototype.authGSSClientClean = function(context, callback) {
return this._native_kerberos.authGSSClientClean(context, callback);
}
// The server will obtain credentials using a keytab. To override the
// default location (probably /etc/krb5.keytab) set the KRB5_KTNAME
// environment variable.
// The service name should be in the form service, or service@host.name
// e.g. for HTTP, use "HTTP" or "HTTP@my.host.name". See gss_import_name
// for GSS_C_NT_HOSTBASED_SERVICE.
//
// a boolean turns on "constrained_delegation". this enables acquisition of S4U2Proxy
// credentials which will be stored in a credentials cache during the authGSSServerStep
// method. this parameter is optional.
//
// when "constrained_delegation" is enabled, a username can (optionally) be provided and
// S4U2Self protocol transition will be initiated. In this case, we will not
// require any "auth" data during the authGSSServerStep. This parameter is optional
// but constrained_delegation MUST be enabled for this to work. When S4U2Self is
// used, the username will be assumed to have been already authenticated, and no
// actual authentication will be performed. This is basically a way to "bootstrap"
// kerberos credentials (which can then be delegated with S4U2Proxy) for a user
// authenticated externally.
//
// callback takes two arguments, an error string if defined and a new context
//
Kerberos.prototype.authGSSServerInit = function(service, constrained_delegation, username, callback) {
if(typeof(constrained_delegation) === 'function') {
callback = constrained_delegation;
constrained_delegation = false;
username = null;
}
if (typeof(constrained_delegation) === 'string') {
throw new Error("S4U2Self protocol transation is not possible without enabling constrained delegation");
}
if (typeof(username) === 'function') {
callback = username;
username = null;
}
constrained_delegation = !!constrained_delegation;
return this._native_kerberos.authGSSServerInit(service, constrained_delegation, username, callback);
};
//callback takes one argument, an error string if defined.
Kerberos.prototype.authGSSServerClean = function(context, callback) {
return this._native_kerberos.authGSSServerClean(context, callback);
};
// authData should be the base64 encoded authentication data obtained
// from client, e.g., in the Authorization header (without the leading
// "Negotiate " string) during SPNEGO authentication. The authenticated user
// is available in context.username after successful authentication.
// callback takes one argument, an error string if defined.
//
// Note: when S4U2Self protocol transition was requested in the authGSSServerInit
// no actual authentication will be performed and authData will be ignored.
//
Kerberos.prototype.authGSSServerStep = function(context, authData, callback) {
return this._native_kerberos.authGSSServerStep(context, authData, callback);
};
Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) {
return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain);
}
Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) {
return this._native_kerberos.prepareOutboundPackage(principal, inputdata);
}
Kerberos.prototype.decryptMessage = function(challenge) {
return this._native_kerberos.decryptMessage(challenge);
}
Kerberos.prototype.encryptMessage = function(challenge) {
return this._native_kerberos.encryptMessage(challenge);
}
Kerberos.prototype.queryContextAttribute = function(attribute) {
if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported");
return this._native_kerberos.queryContextAttribute(attribute);
}
// Some useful result codes
Kerberos.AUTH_GSS_CONTINUE = 0;
Kerberos.AUTH_GSS_COMPLETE = 1;
// Some useful gss flags
Kerberos.GSS_C_DELEG_FLAG = 1;
Kerberos.GSS_C_MUTUAL_FLAG = 2;
Kerberos.GSS_C_REPLAY_FLAG = 4;
Kerberos.GSS_C_SEQUENCE_FLAG = 8;
Kerberos.GSS_C_CONF_FLAG = 16;
Kerberos.GSS_C_INTEG_FLAG = 32;
Kerberos.GSS_C_ANON_FLAG = 64;
Kerberos.GSS_C_PROT_READY_FLAG = 128;
Kerberos.GSS_C_TRANS_FLAG = 256;
// Export Kerberos class
exports.Kerberos = Kerberos;
// If we have SSPI (windows)
if(kerberos.SecurityCredentials) {
// Put all SSPI classes in it's own namespace
exports.SSIP = {
SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials
, SecurityContext: require('./win32/wrappers/security_context').SecurityContext
, SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer
, SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor
}
}

View File

@@ -0,0 +1,134 @@
#include "kerberos_context.h"
Nan::Persistent<FunctionTemplate> KerberosContext::constructor_template;
KerberosContext::KerberosContext() : Nan::ObjectWrap() {
state = NULL;
server_state = NULL;
}
KerberosContext::~KerberosContext() {
}
KerberosContext* KerberosContext::New() {
Nan::HandleScope scope;
Local<Object> obj = Nan::New(constructor_template)->GetFunction()->NewInstance();
KerberosContext *kerberos_context = Nan::ObjectWrap::Unwrap<KerberosContext>(obj);
return kerberos_context;
}
NAN_METHOD(KerberosContext::New) {
// Create code object
KerberosContext *kerberos_context = new KerberosContext();
// Wrap it
kerberos_context->Wrap(info.This());
// Return the object
info.GetReturnValue().Set(info.This());
}
void KerberosContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(static_cast<NAN_METHOD((*))>(New));
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("KerberosContext").ToLocalChecked());
// Get prototype
Local<ObjectTemplate> proto = t->PrototypeTemplate();
// Getter for the response
Nan::SetAccessor(proto, Nan::New<String>("response").ToLocalChecked(), KerberosContext::ResponseGetter);
// Getter for the username
Nan::SetAccessor(proto, Nan::New<String>("username").ToLocalChecked(), KerberosContext::UsernameGetter);
// Getter for the targetname - server side only
Nan::SetAccessor(proto, Nan::New<String>("targetname").ToLocalChecked(), KerberosContext::TargetnameGetter);
Nan::SetAccessor(proto, Nan::New<String>("delegatedCredentialsCache").ToLocalChecked(), KerberosContext::DelegatedCredentialsCacheGetter);
// Set persistent
constructor_template.Reset(t);
// NanAssignPersistent(constructor_template, t);
// Set the symbol
target->ForceSet(Nan::New<String>("KerberosContext").ToLocalChecked(), t->GetFunction());
}
// Response Setter / Getter
NAN_GETTER(KerberosContext::ResponseGetter) {
gss_client_state *client_state;
gss_server_state *server_state;
// Unpack the object
KerberosContext *context = Nan::ObjectWrap::Unwrap<KerberosContext>(info.This());
// Response could come from client or server state...
client_state = context->state;
server_state = context->server_state;
// If client state is in use, take response from there, otherwise from server
char *response = client_state != NULL ? client_state->response :
server_state != NULL ? server_state->response : NULL;
if(response == NULL) {
info.GetReturnValue().Set(Nan::Null());
} else {
// Return the response
info.GetReturnValue().Set(Nan::New<String>(response).ToLocalChecked());
}
}
// username Getter
NAN_GETTER(KerberosContext::UsernameGetter) {
// Unpack the object
KerberosContext *context = Nan::ObjectWrap::Unwrap<KerberosContext>(info.This());
gss_client_state *client_state = context->state;
gss_server_state *server_state = context->server_state;
// If client state is in use, take response from there, otherwise from server
char *username = client_state != NULL ? client_state->username :
server_state != NULL ? server_state->username : NULL;
if(username == NULL) {
info.GetReturnValue().Set(Nan::Null());
} else {
info.GetReturnValue().Set(Nan::New<String>(username).ToLocalChecked());
}
}
// targetname Getter - server side only
NAN_GETTER(KerberosContext::TargetnameGetter) {
// Unpack the object
KerberosContext *context = Nan::ObjectWrap::Unwrap<KerberosContext>(info.This());
gss_server_state *server_state = context->server_state;
char *targetname = server_state != NULL ? server_state->targetname : NULL;
if(targetname == NULL) {
info.GetReturnValue().Set(Nan::Null());
} else {
info.GetReturnValue().Set(Nan::New<String>(targetname).ToLocalChecked());
}
}
// targetname Getter - server side only
NAN_GETTER(KerberosContext::DelegatedCredentialsCacheGetter) {
// Unpack the object
KerberosContext *context = Nan::ObjectWrap::Unwrap<KerberosContext>(info.This());
gss_server_state *server_state = context->server_state;
char *delegated_credentials_cache = server_state != NULL ? server_state->delegated_credentials_cache : NULL;
if(delegated_credentials_cache == NULL) {
info.GetReturnValue().Set(Nan::Null());
} else {
info.GetReturnValue().Set(Nan::New<String>(delegated_credentials_cache).ToLocalChecked());
}
}

View File

@@ -0,0 +1,64 @@
#ifndef KERBEROS_CONTEXT_H
#define KERBEROS_CONTEXT_H
#include <node.h>
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_generic.h>
#include <gssapi/gssapi_krb5.h>
#include "nan.h"
#include <node_object_wrap.h>
#include <v8.h>
extern "C" {
#include "kerberosgss.h"
}
using namespace v8;
using namespace node;
class KerberosContext : public Nan::ObjectWrap {
public:
KerberosContext();
~KerberosContext();
static inline bool HasInstance(Local<Value> val) {
if (!val->IsObject()) return false;
Local<Object> obj = val->ToObject();
return Nan::New(constructor_template)->HasInstance(obj);
};
inline bool IsClientInstance() {
return state != NULL;
}
inline bool IsServerInstance() {
return server_state != NULL;
}
// Constructor used for creating new Kerberos objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
// Initialize function for the object
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
// Public constructor
static KerberosContext* New();
// Handle to the kerberos client context
gss_client_state *state;
// Handle to the kerberos server context
gss_server_state *server_state;
private:
static NAN_METHOD(New);
// In either client state or server state
static NAN_GETTER(ResponseGetter);
static NAN_GETTER(UsernameGetter);
// Only in the "server_state"
static NAN_GETTER(TargetnameGetter);
static NAN_GETTER(DelegatedCredentialsCacheGetter);
};
#endif

View File

@@ -0,0 +1,931 @@
/**
* Copyright (c) 2006-2010 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**/
/*
* S4U2Proxy implementation
* Copyright (C) 2015 David Mansfield
* Code inspired by mod_auth_kerb.
*/
#include "kerberosgss.h"
#include "base64.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdarg.h>
#include <unistd.h>
#include <krb5.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
void die1(const char *message) {
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
static gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min);
static gss_client_response *other_error(const char *fmt, ...);
static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem);
static gss_client_response *store_gss_creds(gss_server_state *state);
static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context context, krb5_principal princ, krb5_ccache *ccache);
/*
char* server_principal_details(const char* service, const char* hostname)
{
char match[1024];
int match_len = 0;
char* result = NULL;
int code;
krb5_context kcontext;
krb5_keytab kt = NULL;
krb5_kt_cursor cursor = NULL;
krb5_keytab_entry entry;
char* pname = NULL;
// Generate the principal prefix we want to match
snprintf(match, 1024, "%s/%s@", service, hostname);
match_len = strlen(match);
code = krb5_init_context(&kcontext);
if (code)
{
PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))",
"Cannot initialize Kerberos5 context", code));
return NULL;
}
if ((code = krb5_kt_default(kcontext, &kt)))
{
PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))",
"Cannot get default keytab", code));
goto end;
}
if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor)))
{
PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))",
"Cannot get sequence cursor from keytab", code));
goto end;
}
while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0)
{
if ((code = krb5_unparse_name(kcontext, entry.principal, &pname)))
{
PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))",
"Cannot parse principal name from keytab", code));
goto end;
}
if (strncmp(pname, match, match_len) == 0)
{
result = malloc(strlen(pname) + 1);
strcpy(result, pname);
krb5_free_unparsed_name(kcontext, pname);
krb5_free_keytab_entry_contents(kcontext, &entry);
break;
}
krb5_free_unparsed_name(kcontext, pname);
krb5_free_keytab_entry_contents(kcontext, &entry);
}
if (result == NULL)
{
PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))",
"Principal not found in keytab", -1));
}
end:
if (cursor)
krb5_kt_end_seq_get(kcontext, kt, &cursor);
if (kt)
krb5_kt_close(kcontext, kt);
krb5_free_context(kcontext);
return result;
}
*/
gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) {
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER;
gss_client_response *response = NULL;
int ret = AUTH_GSS_COMPLETE;
state->server_name = GSS_C_NO_NAME;
state->context = GSS_C_NO_CONTEXT;
state->gss_flags = gss_flags;
state->username = NULL;
state->response = NULL;
// Import server name first
name_token.length = strlen(service);
name_token.value = (char *)service;
maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name);
if (GSS_ERROR(maj_stat)) {
response = gss_error(__func__, "gss_import_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
end:
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
return response;
}
gss_client_response *authenticate_gss_client_clean(gss_client_state *state) {
OM_uint32 min_stat;
int ret = AUTH_GSS_COMPLETE;
gss_client_response *response = NULL;
if(state->context != GSS_C_NO_CONTEXT)
gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER);
if(state->server_name != GSS_C_NO_NAME)
gss_release_name(&min_stat, &state->server_name);
if(state->username != NULL) {
free(state->username);
state->username = NULL;
}
if (state->response != NULL) {
free(state->response);
state->response = NULL;
}
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
return response;
}
gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) {
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
int ret = AUTH_GSS_CONTINUE;
gss_client_response *response = NULL;
// Always clear out the old response
if (state->response != NULL) {
free(state->response);
state->response = NULL;
}
// If there is a challenge (data from the server) we need to give it to GSS
if (challenge && *challenge) {
int len;
input_token.value = base64_decode(challenge, &len);
input_token.length = len;
}
// Do GSSAPI step
maj_stat = gss_init_sec_context(&min_stat,
GSS_C_NO_CREDENTIAL,
&state->context,
state->server_name,
GSS_C_NO_OID,
(OM_uint32)state->gss_flags,
0,
GSS_C_NO_CHANNEL_BINDINGS,
&input_token,
NULL,
&output_token,
NULL,
NULL);
if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) {
response = gss_error(__func__, "gss_init_sec_context", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE;
// Grab the client response to send back to the server
if(output_token.length) {
state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);
maj_stat = gss_release_buffer(&min_stat, &output_token);
}
// Try to get the user name if we have completed all GSS operations
if (ret == AUTH_GSS_COMPLETE) {
gss_name_t gssuser = GSS_C_NO_NAME;
maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL);
if(GSS_ERROR(maj_stat)) {
response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
gss_buffer_desc name_token;
name_token.length = 0;
maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL);
if(GSS_ERROR(maj_stat)) {
if(name_token.value)
gss_release_buffer(&min_stat, &name_token);
gss_release_name(&min_stat, &gssuser);
response = gss_error(__func__, "gss_display_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
} else {
state->username = (char *)malloc(name_token.length + 1);
if(state->username == NULL) die1("Memory allocation failed");
strncpy(state->username, (char*) name_token.value, name_token.length);
state->username[name_token.length] = 0;
gss_release_buffer(&min_stat, &name_token);
gss_release_name(&min_stat, &gssuser);
}
}
end:
if(output_token.value)
gss_release_buffer(&min_stat, &output_token);
if(input_token.value)
free(input_token.value);
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
// Return the response
return response;
}
gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) {
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
gss_client_response *response = NULL;
int ret = AUTH_GSS_CONTINUE;
// Always clear out the old response
if(state->response != NULL) {
free(state->response);
state->response = NULL;
}
// If there is a challenge (data from the server) we need to give it to GSS
if(challenge && *challenge) {
int len;
input_token.value = base64_decode(challenge, &len);
input_token.length = len;
}
// Do GSSAPI step
maj_stat = gss_unwrap(&min_stat,
state->context,
&input_token,
&output_token,
NULL,
NULL);
if(maj_stat != GSS_S_COMPLETE) {
response = gss_error(__func__, "gss_unwrap", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
} else {
ret = AUTH_GSS_COMPLETE;
}
// Grab the client response
if(output_token.length) {
state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);
gss_release_buffer(&min_stat, &output_token);
}
end:
if(output_token.value)
gss_release_buffer(&min_stat, &output_token);
if(input_token.value)
free(input_token.value);
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
// Return the response
return response;
}
gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) {
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
int ret = AUTH_GSS_CONTINUE;
gss_client_response *response = NULL;
char buf[4096], server_conf_flags;
unsigned long buf_size;
// Always clear out the old response
if(state->response != NULL) {
free(state->response);
state->response = NULL;
}
if(challenge && *challenge) {
int len;
input_token.value = base64_decode(challenge, &len);
input_token.length = len;
}
if(user) {
// get bufsize
server_conf_flags = ((char*) input_token.value)[0];
((char*) input_token.value)[0] = 0;
buf_size = ntohl(*((long *) input_token.value));
free(input_token.value);
#ifdef PRINTFS
printf("User: %s, %c%c%c\n", user,
server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-',
server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-',
server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-');
printf("Maximum GSS token size is %ld\n", buf_size);
#endif
// agree to terms (hack!)
buf_size = htonl(buf_size); // not relevant without integrity/privacy
memcpy(buf, &buf_size, 4);
buf[0] = GSS_AUTH_P_NONE;
// server decides if principal can log in as user
strncpy(buf + 4, user, sizeof(buf) - 4);
input_token.value = buf;
input_token.length = 4 + strlen(user);
}
// Do GSSAPI wrap
maj_stat = gss_wrap(&min_stat,
state->context,
0,
GSS_C_QOP_DEFAULT,
&input_token,
NULL,
&output_token);
if (maj_stat != GSS_S_COMPLETE) {
response = gss_error(__func__, "gss_wrap", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
} else
ret = AUTH_GSS_COMPLETE;
// Grab the client response to send back to the server
if (output_token.length) {
state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);;
gss_release_buffer(&min_stat, &output_token);
}
end:
if (output_token.value)
gss_release_buffer(&min_stat, &output_token);
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
// Return the response
return response;
}
gss_client_response *authenticate_gss_server_init(const char *service, bool constrained_delegation, const char *username, gss_server_state *state)
{
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER;
int ret = AUTH_GSS_COMPLETE;
gss_client_response *response = NULL;
gss_cred_usage_t usage = GSS_C_ACCEPT;
state->context = GSS_C_NO_CONTEXT;
state->server_name = GSS_C_NO_NAME;
state->client_name = GSS_C_NO_NAME;
state->server_creds = GSS_C_NO_CREDENTIAL;
state->client_creds = GSS_C_NO_CREDENTIAL;
state->username = NULL;
state->targetname = NULL;
state->response = NULL;
state->constrained_delegation = constrained_delegation;
state->delegated_credentials_cache = NULL;
// Server name may be empty which means we aren't going to create our own creds
size_t service_len = strlen(service);
if (service_len != 0)
{
// Import server name first
name_token.length = strlen(service);
name_token.value = (char *)service;
maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_import_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
if (state->constrained_delegation)
{
usage = GSS_C_BOTH;
}
// Get credentials
maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE,
GSS_C_NO_OID_SET, usage, &state->server_creds, NULL, NULL);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_acquire_cred", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
}
// If a username was passed, perform the S4U2Self protocol transition to acquire
// a credentials from that user as if we had done gss_accept_sec_context.
// In this scenario, the passed username is assumed to be already authenticated
// by some external mechanism, and we are here to "bootstrap" some gss credentials.
// In authenticate_gss_server_step we will bypass the actual authentication step.
if (username != NULL)
{
gss_name_t gss_username;
name_token.length = strlen(username);
name_token.value = (char *)username;
maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_USER_NAME, &gss_username);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_import_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
maj_stat = gss_acquire_cred_impersonate_name(&min_stat,
state->server_creds,
gss_username,
GSS_C_INDEFINITE,
GSS_C_NO_OID_SET,
GSS_C_INITIATE,
&state->client_creds,
NULL,
NULL);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_acquire_cred_impersonate_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
}
gss_release_name(&min_stat, &gss_username);
if (response != NULL)
{
goto end;
}
// because the username MAY be a "local" username,
// we want get the canonical name from the acquired creds.
maj_stat = gss_inquire_cred(&min_stat, state->client_creds, &state->client_name, NULL, NULL, NULL);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_inquire_cred", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
}
end:
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
// Return the response
return response;
}
gss_client_response *authenticate_gss_server_clean(gss_server_state *state)
{
OM_uint32 min_stat;
int ret = AUTH_GSS_COMPLETE;
gss_client_response *response = NULL;
if (state->context != GSS_C_NO_CONTEXT)
gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER);
if (state->server_name != GSS_C_NO_NAME)
gss_release_name(&min_stat, &state->server_name);
if (state->client_name != GSS_C_NO_NAME)
gss_release_name(&min_stat, &state->client_name);
if (state->server_creds != GSS_C_NO_CREDENTIAL)
gss_release_cred(&min_stat, &state->server_creds);
if (state->client_creds != GSS_C_NO_CREDENTIAL)
gss_release_cred(&min_stat, &state->client_creds);
if (state->username != NULL)
{
free(state->username);
state->username = NULL;
}
if (state->targetname != NULL)
{
free(state->targetname);
state->targetname = NULL;
}
if (state->response != NULL)
{
free(state->response);
state->response = NULL;
}
if (state->delegated_credentials_cache)
{
// TODO: what about actually destroying the cache? It can't be done now as
// the whole point is having it around for the lifetime of the "session"
free(state->delegated_credentials_cache);
}
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
// Return the response
return response;
}
gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *auth_data)
{
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
int ret = AUTH_GSS_CONTINUE;
gss_client_response *response = NULL;
// Always clear out the old response
if (state->response != NULL)
{
free(state->response);
state->response = NULL;
}
// we don't need to check the authentication token if S4U2Self protocol
// transition was done, because we already have the client credentials.
if (state->client_creds == GSS_C_NO_CREDENTIAL)
{
if (auth_data && *auth_data)
{
int len;
input_token.value = base64_decode(auth_data, &len);
input_token.length = len;
}
else
{
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->message = strdup("No auth_data value in request from client");
response->return_code = AUTH_GSS_ERROR;
goto end;
}
maj_stat = gss_accept_sec_context(&min_stat,
&state->context,
state->server_creds,
&input_token,
GSS_C_NO_CHANNEL_BINDINGS,
&state->client_name,
NULL,
&output_token,
NULL,
NULL,
&state->client_creds);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_accept_sec_context", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
// Grab the server response to send back to the client
if (output_token.length)
{
state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);
maj_stat = gss_release_buffer(&min_stat, &output_token);
}
}
// Get the user name
maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_display_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
state->username = (char *)malloc(output_token.length + 1);
strncpy(state->username, (char*) output_token.value, output_token.length);
state->username[output_token.length] = 0;
// Get the target name if no server creds were supplied
if (state->server_creds == GSS_C_NO_CREDENTIAL)
{
gss_name_t target_name = GSS_C_NO_NAME;
maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL);
if (GSS_ERROR(maj_stat))
{
response = gss_error(__func__, "gss_display_name", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
state->targetname = (char *)malloc(output_token.length + 1);
strncpy(state->targetname, (char*) output_token.value, output_token.length);
state->targetname[output_token.length] = 0;
}
if (state->constrained_delegation && state->client_creds != GSS_C_NO_CREDENTIAL)
{
if ((response = store_gss_creds(state)) != NULL)
{
goto end;
}
}
ret = AUTH_GSS_COMPLETE;
end:
if (output_token.length)
gss_release_buffer(&min_stat, &output_token);
if (input_token.value)
free(input_token.value);
if(response == NULL) {
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->return_code = ret;
}
// Return the response
return response;
}
static gss_client_response *store_gss_creds(gss_server_state *state)
{
OM_uint32 maj_stat, min_stat;
krb5_principal princ = NULL;
krb5_ccache ccache = NULL;
krb5_error_code problem;
krb5_context context;
gss_client_response *response = NULL;
problem = krb5_init_context(&context);
if (problem) {
response = other_error("No auth_data value in request from client");
return response;
}
problem = krb5_parse_name(context, state->username, &princ);
if (problem) {
response = krb5_ctx_error(context, problem);
goto end;
}
if ((response = create_krb5_ccache(state, context, princ, &ccache)))
{
goto end;
}
maj_stat = gss_krb5_copy_ccache(&min_stat, state->client_creds, ccache);
if (GSS_ERROR(maj_stat)) {
response = gss_error(__func__, "gss_krb5_copy_ccache", maj_stat, min_stat);
response->return_code = AUTH_GSS_ERROR;
goto end;
}
krb5_cc_close(context, ccache);
ccache = NULL;
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
// TODO: something other than AUTH_GSS_COMPLETE?
response->return_code = AUTH_GSS_COMPLETE;
end:
if (princ)
krb5_free_principal(context, princ);
if (ccache)
krb5_cc_destroy(context, ccache);
krb5_free_context(context);
return response;
}
static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context kcontext, krb5_principal princ, krb5_ccache *ccache)
{
char *ccname = NULL;
int fd;
krb5_error_code problem;
krb5_ccache tmp_ccache = NULL;
gss_client_response *error = NULL;
// TODO: mod_auth_kerb used a temp file under /run/httpd/krbcache. what can we do?
ccname = strdup("FILE:/tmp/krb5cc_nodekerberos_XXXXXX");
if (!ccname) die1("Memory allocation failed");
fd = mkstemp(ccname + strlen("FILE:"));
if (fd < 0) {
error = other_error("mkstemp() failed: %s", strerror(errno));
goto end;
}
close(fd);
problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache);
if (problem) {
error = krb5_ctx_error(kcontext, problem);
goto end;
}
problem = krb5_cc_initialize(kcontext, tmp_ccache, princ);
if (problem) {
error = krb5_ctx_error(kcontext, problem);
goto end;
}
state->delegated_credentials_cache = strdup(ccname);
// TODO: how/when to cleanup the creds cache file?
// TODO: how to expose the credentials expiration time?
*ccache = tmp_ccache;
tmp_ccache = NULL;
end:
if (tmp_ccache)
krb5_cc_destroy(kcontext, tmp_ccache);
if (ccname && error)
unlink(ccname);
if (ccname)
free(ccname);
return error;
}
gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min) {
OM_uint32 maj_stat, min_stat;
OM_uint32 msg_ctx = 0;
gss_buffer_desc status_string;
gss_client_response *response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
char *message = NULL;
message = calloc(1024, 1);
if(message == NULL) die1("Memory allocation failed");
response->message = message;
int nleft = 1024;
int n;
n = snprintf(message, nleft, "%s(%s)", func, op);
message += n;
nleft -= n;
do {
maj_stat = gss_display_status (&min_stat,
err_maj,
GSS_C_GSS_CODE,
GSS_C_NO_OID,
&msg_ctx,
&status_string);
if(GSS_ERROR(maj_stat))
break;
n = snprintf(message, nleft, ": %.*s",
(int)status_string.length, (char*)status_string.value);
message += n;
nleft -= n;
gss_release_buffer(&min_stat, &status_string);
maj_stat = gss_display_status (&min_stat,
err_min,
GSS_C_MECH_CODE,
GSS_C_NULL_OID,
&msg_ctx,
&status_string);
if(!GSS_ERROR(maj_stat)) {
n = snprintf(message, nleft, ": %.*s",
(int)status_string.length, (char*)status_string.value);
message += n;
nleft -= n;
gss_release_buffer(&min_stat, &status_string);
}
} while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
return response;
}
static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem)
{
gss_client_response *response = NULL;
const char *error_text = krb5_get_error_message(context, problem);
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->message = strdup(error_text);
// TODO: something other than AUTH_GSS_ERROR? AUTH_KRB5_ERROR ?
response->return_code = AUTH_GSS_ERROR;
krb5_free_error_message(context, error_text);
return response;
}
static gss_client_response *other_error(const char *fmt, ...)
{
size_t needed;
char *msg;
gss_client_response *response = NULL;
va_list ap, aps;
va_start(ap, fmt);
va_copy(aps, ap);
needed = snprintf(NULL, 0, fmt, aps);
va_end(aps);
msg = malloc(needed);
if (!msg) die1("Memory allocation failed");
vsnprintf(msg, needed, fmt, ap);
va_end(ap);
response = calloc(1, sizeof(gss_client_response));
if(response == NULL) die1("Memory allocation failed");
response->message = msg;
// TODO: something other than AUTH_GSS_ERROR?
response->return_code = AUTH_GSS_ERROR;
return response;
}
#pragma clang diagnostic pop

View File

@@ -0,0 +1,73 @@
/**
* Copyright (c) 2006-2009 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#ifndef KERBEROS_GSS_H
#define KERBEROS_GSS_H
#include <stdbool.h>
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_generic.h>
#include <gssapi/gssapi_krb5.h>
#define krb5_get_err_text(context,code) error_message(code)
#define AUTH_GSS_ERROR -1
#define AUTH_GSS_COMPLETE 1
#define AUTH_GSS_CONTINUE 0
#define GSS_AUTH_P_NONE 1
#define GSS_AUTH_P_INTEGRITY 2
#define GSS_AUTH_P_PRIVACY 4
typedef struct {
int return_code;
char *message;
} gss_client_response;
typedef struct {
gss_ctx_id_t context;
gss_name_t server_name;
long int gss_flags;
char* username;
char* response;
} gss_client_state;
typedef struct {
gss_ctx_id_t context;
gss_name_t server_name;
gss_name_t client_name;
gss_cred_id_t server_creds;
gss_cred_id_t client_creds;
char* username;
char* targetname;
char* response;
bool constrained_delegation;
char* delegated_credentials_cache;
} gss_server_state;
// char* server_principal_details(const char* service, const char* hostname);
gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state);
gss_client_response *authenticate_gss_client_clean(gss_client_state *state);
gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge);
gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge);
gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user);
gss_client_response *authenticate_gss_server_init(const char* service, bool constrained_delegation, const char *username, gss_server_state* state);
gss_client_response *authenticate_gss_server_clean(gss_server_state *state);
gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *challenge);
#endif

View File

@@ -0,0 +1,15 @@
// Load the native SSPI classes
var kerberos = require('../build/Release/kerberos')
, Kerberos = kerberos.Kerberos
, SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer
, SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor
, SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials
, SecurityContext = require('./win32/wrappers/security_context').SecurityContext;
var SSPI = function() {
}
exports.SSPI = SSPI;
exports.SecurityBuffer = SecurityBuffer;
exports.SecurityBufferDescriptor = SecurityBufferDescriptor;
exports.SecurityCredentials = SecurityCredentials;
exports.SecurityContext = SecurityContext;

View File

@@ -0,0 +1,121 @@
/**
* Copyright (c) 2006-2008 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#include "base64.h"
#include <stdlib.h>
#include <string.h>
// base64 tables
static char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static signed char index_64[128] =
{
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
};
#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)])
// base64_encode : base64 encode
//
// value : data to encode
// vlen : length of data
// (result) : new char[] - c-str of result
char *base64_encode(const unsigned char *value, int vlen)
{
char *result = (char *)malloc((vlen * 4) / 3 + 5);
char *out = result;
unsigned char oval;
while (vlen >= 3)
{
*out++ = basis_64[value[0] >> 2];
*out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)];
*out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)];
*out++ = basis_64[value[2] & 0x3F];
value += 3;
vlen -= 3;
}
if (vlen > 0)
{
*out++ = basis_64[value[0] >> 2];
oval = (value[0] << 4) & 0x30;
if (vlen > 1) oval |= value[1] >> 4;
*out++ = basis_64[oval];
*out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C];
*out++ = '=';
}
*out = '\0';
return result;
}
// base64_decode : base64 decode
//
// value : c-str to decode
// rlen : length of decoded result
// (result) : new unsigned char[] - decoded result
unsigned char *base64_decode(const char *value, int *rlen)
{
int c1, c2, c3, c4;
int vlen = (int)strlen(value);
unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1);
unsigned char *out = result;
*rlen = 0;
while (1)
{
if (value[0]==0)
return result;
c1 = value[0];
if (CHAR64(c1) == -1)
goto base64_decode_error;;
c2 = value[1];
if (CHAR64(c2) == -1)
goto base64_decode_error;;
c3 = value[2];
if ((c3 != '=') && (CHAR64(c3) == -1))
goto base64_decode_error;;
c4 = value[3];
if ((c4 != '=') && (CHAR64(c4) == -1))
goto base64_decode_error;;
value += 4;
*out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4);
*rlen += 1;
if (c3 != '=')
{
*out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2);
*rlen += 1;
if (c4 != '=')
{
*out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4);
*rlen += 1;
}
}
}
base64_decode_error:
*result = 0;
*rlen = 0;
return result;
}

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) 2006-2008 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
char *base64_encode(const unsigned char *value, int vlen);
unsigned char *base64_decode(const char *value, int *rlen);

View File

@@ -0,0 +1,51 @@
#include "kerberos.h"
#include <stdlib.h>
#include <tchar.h>
#include "base64.h"
#include "wrappers/security_buffer.h"
#include "wrappers/security_buffer_descriptor.h"
#include "wrappers/security_context.h"
#include "wrappers/security_credentials.h"
Nan::Persistent<FunctionTemplate> Kerberos::constructor_template;
Kerberos::Kerberos() : Nan::ObjectWrap() {
}
void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("Kerberos").ToLocalChecked());
// Set persistent
constructor_template.Reset(t);
// Set the symbol
Nan::Set(target, Nan::New<String>("Kerberos").ToLocalChecked(), t->GetFunction());
}
NAN_METHOD(Kerberos::New) {
// Load the security.dll library
load_library();
// Create a Kerberos instance
Kerberos *kerberos = new Kerberos();
// Return the kerberos object
kerberos->Wrap(info.This());
// Return the object
info.GetReturnValue().Set(info.This());
}
// Exporting function
NAN_MODULE_INIT(init) {
Kerberos::Initialize(target);
SecurityContext::Initialize(target);
SecurityBuffer::Initialize(target);
SecurityBufferDescriptor::Initialize(target);
SecurityCredentials::Initialize(target);
}
NODE_MODULE(kerberos, init);

View File

@@ -0,0 +1,60 @@
#ifndef KERBEROS_H
#define KERBEROS_H
#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#include "nan.h"
extern "C" {
#include "kerberos_sspi.h"
#include "base64.h"
}
using namespace v8;
using namespace node;
class Kerberos : public Nan::ObjectWrap {
public:
Kerberos();
~Kerberos() {};
// Constructor used for creating new Kerberos objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
// Initialize function for the object
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
// Method available
static NAN_METHOD(AcquireAlternateCredentials);
static NAN_METHOD(PrepareOutboundPackage);
static NAN_METHOD(DecryptMessage);
static NAN_METHOD(EncryptMessage);
static NAN_METHOD(QueryContextAttributes);
private:
static NAN_METHOD(New);
// Pointer to context object
SEC_WINNT_AUTH_IDENTITY m_Identity;
// credentials
CredHandle m_Credentials;
// Expiry time for ticket
TimeStamp Expiration;
// package info
SecPkgInfo m_PkgInfo;
// context
CtxtHandle m_Context;
// Do we have a context
bool m_HaveContext;
// Attributes
DWORD CtxtAttr;
// Handles the uv calls
static void Process(uv_work_t* work_req);
// Called after work is done
static void After(uv_work_t* work_req);
};
#endif

View File

@@ -0,0 +1,244 @@
#include "kerberos_sspi.h"
#include <stdlib.h>
#include <stdio.h>
static HINSTANCE _sspi_security_dll = NULL;
static HINSTANCE _sspi_secur32_dll = NULL;
/**
* Encrypt A Message
*/
SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) {
// Create function pointer instance
encryptMessage_fn pfn_encryptMessage = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function to library method
pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage");
// Check if the we managed to map function pointer
if(!pfn_encryptMessage) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo);
}
/**
* Acquire Credentials
*/
SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle(
LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse,
void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument,
PCredHandle phCredential, PTimeStamp ptsExpiry
) {
SECURITY_STATUS status;
// Create function pointer instance
acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
#ifdef _UNICODE
pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW");
#else
pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA");
#endif
// Check if the we managed to map function pointer
if(!pfn_acquireCredentialsHandle) {
printf("GetProcAddress failed.\n");
return -2;
}
// Status
status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse,
pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry
);
// Call the function
return status;
}
/**
* Delete Security Context
*/
SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) {
// Create function pointer instance
deleteSecurityContext_fn pfn_deleteSecurityContext = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext");
// Check if the we managed to map function pointer
if(!pfn_deleteSecurityContext) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_deleteSecurityContext)(phContext);
}
/**
* Decrypt Message
*/
SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) {
// Create function pointer instance
decryptMessage_fn pfn_decryptMessage = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage");
// Check if the we managed to map function pointer
if(!pfn_decryptMessage) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP);
}
/**
* Initialize Security Context
*/
SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext(
PCredHandle phCredential, PCtxtHandle phContext,
LPSTR pszTargetName, unsigned long fContextReq,
unsigned long Reserved1, unsigned long TargetDataRep,
PSecBufferDesc pInput, unsigned long Reserved2,
PCtxtHandle phNewContext, PSecBufferDesc pOutput,
unsigned long * pfContextAttr, PTimeStamp ptsExpiry
) {
SECURITY_STATUS status;
// Create function pointer instance
initializeSecurityContext_fn pfn_initializeSecurityContext = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
// Map function
#ifdef _UNICODE
pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW");
#else
pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA");
#endif
// Check if the we managed to map function pointer
if(!pfn_initializeSecurityContext) {
printf("GetProcAddress failed.\n");
return -2;
}
// Execute intialize context
status = (*pfn_initializeSecurityContext)(
phCredential, phContext, pszTargetName, fContextReq,
Reserved1, TargetDataRep, pInput, Reserved2,
phNewContext, pOutput, pfContextAttr, ptsExpiry
);
// Call the function
return status;
}
/**
* Query Context Attributes
*/
SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes(
PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer
) {
// Create function pointer instance
queryContextAttributes_fn pfn_queryContextAttributes = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return -1;
#ifdef _UNICODE
pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW");
#else
pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA");
#endif
// Check if the we managed to map function pointer
if(!pfn_queryContextAttributes) {
printf("GetProcAddress failed.\n");
return -2;
}
// Call the function
return (*pfn_queryContextAttributes)(
phContext, ulAttribute, pBuffer
);
}
/**
* InitSecurityInterface
*/
PSecurityFunctionTable _ssip_InitSecurityInterface() {
INIT_SECURITY_INTERFACE InitSecurityInterface;
PSecurityFunctionTable pSecurityInterface = NULL;
// Return error if library not loaded
if(_sspi_security_dll == NULL) return NULL;
#ifdef _UNICODE
// Get the address of the InitSecurityInterface function.
InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress (
_sspi_secur32_dll,
TEXT("InitSecurityInterfaceW"));
#else
// Get the address of the InitSecurityInterface function.
InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress (
_sspi_secur32_dll,
TEXT("InitSecurityInterfaceA"));
#endif
if(!InitSecurityInterface) {
printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ());
return NULL;
}
// Use InitSecurityInterface to get the function table.
pSecurityInterface = (*InitSecurityInterface)();
if(!pSecurityInterface) {
printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ());
return NULL;
}
return pSecurityInterface;
}
/**
* Load security.dll dynamically
*/
int load_library() {
DWORD err;
// Load the library
_sspi_security_dll = LoadLibrary("security.dll");
// Check if the library loaded
if(_sspi_security_dll == NULL) {
err = GetLastError();
return err;
}
// Load the library
_sspi_secur32_dll = LoadLibrary("secur32.dll");
// Check if the library loaded
if(_sspi_secur32_dll == NULL) {
err = GetLastError();
return err;
}
return 0;
}

View File

@@ -0,0 +1,106 @@
#ifndef SSPI_C_H
#define SSPI_C_H
#define SECURITY_WIN32 1
#include <windows.h>
#include <sspi.h>
/**
* Encrypt A Message
*/
SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo);
typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo);
/**
* Acquire Credentials
*/
SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle(
LPSTR pszPrincipal, // Name of principal
LPSTR pszPackage, // Name of package
unsigned long fCredentialUse, // Flags indicating use
void * pvLogonId, // Pointer to logon ID
void * pAuthData, // Package specific data
SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func
void * pvGetKeyArgument, // Value to pass to GetKey()
PCredHandle phCredential, // (out) Cred Handle
PTimeStamp ptsExpiry // (out) Lifetime (optional)
);
typedef DWORD (WINAPI *acquireCredentialsHandle_fn)(
LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse,
void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument,
PCredHandle phCredential, PTimeStamp ptsExpiry
);
/**
* Delete Security Context
*/
SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(
PCtxtHandle phContext // Context to delete
);
typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext);
/**
* Decrypt Message
*/
SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(
PCtxtHandle phContext,
PSecBufferDesc pMessage,
unsigned long MessageSeqNo,
unsigned long pfQOP
);
typedef DWORD (WINAPI *decryptMessage_fn)(
PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP);
/**
* Initialize Security Context
*/
SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext(
PCredHandle phCredential, // Cred to base context
PCtxtHandle phContext, // Existing context (OPT)
LPSTR pszTargetName, // Name of target
unsigned long fContextReq, // Context Requirements
unsigned long Reserved1, // Reserved, MBZ
unsigned long TargetDataRep, // Data rep of target
PSecBufferDesc pInput, // Input Buffers
unsigned long Reserved2, // Reserved, MBZ
PCtxtHandle phNewContext, // (out) New Context handle
PSecBufferDesc pOutput, // (inout) Output Buffers
unsigned long * pfContextAttr, // (out) Context attrs
PTimeStamp ptsExpiry // (out) Life span (OPT)
);
typedef DWORD (WINAPI *initializeSecurityContext_fn)(
PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq,
unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2,
PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry);
/**
* Query Context Attributes
*/
SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes(
PCtxtHandle phContext, // Context to query
unsigned long ulAttribute, // Attribute to query
void * pBuffer // Buffer for attributes
);
typedef DWORD (WINAPI *queryContextAttributes_fn)(
PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer);
/**
* InitSecurityInterface
*/
PSecurityFunctionTable _ssip_InitSecurityInterface();
typedef DWORD (WINAPI *initSecurityInterface_fn) ();
/**
* Load security.dll dynamically
*/
int load_library();
#endif

View File

@@ -0,0 +1,7 @@
#include "worker.h"
Worker::Worker() {
}
Worker::~Worker() {
}

View File

@@ -0,0 +1,38 @@
#ifndef WORKER_H_
#define WORKER_H_
#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#include <nan.h>
using namespace node;
using namespace v8;
class Worker {
public:
Worker();
virtual ~Worker();
// libuv's request struct.
uv_work_t request;
// Callback
Nan::Callback *callback;
// Parameters
void *parameters;
// Results
void *return_value;
// Did we raise an error
bool error;
// The error message
char *error_message;
// Error code if not message
int error_code;
// Any return code
int return_code;
// Method we are going to fire
void (*execute)(Worker *worker);
Local<Value> (*mapper)(Worker *worker);
};
#endif // WORKER_H_

View File

@@ -0,0 +1,101 @@
#include <node.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <v8.h>
#include <node_buffer.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include "security_buffer.h"
using namespace node;
Nan::Persistent<FunctionTemplate> SecurityBuffer::constructor_template;
SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : Nan::ObjectWrap() {
this->size = size;
this->data = calloc(size, sizeof(char));
this->security_type = security_type;
// Set up the data in the sec_buffer
this->sec_buffer.BufferType = security_type;
this->sec_buffer.cbBuffer = (unsigned long)size;
this->sec_buffer.pvBuffer = this->data;
}
SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : Nan::ObjectWrap() {
this->size = size;
this->data = data;
this->security_type = security_type;
// Set up the data in the sec_buffer
this->sec_buffer.BufferType = security_type;
this->sec_buffer.cbBuffer = (unsigned long)size;
this->sec_buffer.pvBuffer = this->data;
}
SecurityBuffer::~SecurityBuffer() {
free(this->data);
}
NAN_METHOD(SecurityBuffer::New) {
SecurityBuffer *security_obj;
if(info.Length() != 2)
return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required");
if(!info[0]->IsInt32())
return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required");
if(!info[1]->IsInt32() && !Buffer::HasInstance(info[1]))
return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required");
// Unpack buffer type
uint32_t buffer_type = info[0]->ToUint32()->Value();
// If we have an integer
if(info[1]->IsInt32()) {
security_obj = new SecurityBuffer(buffer_type, info[1]->ToUint32()->Value());
} else {
// Get the length of the Buffer
size_t length = Buffer::Length(info[1]->ToObject());
// Allocate space for the internal void data pointer
void *data = calloc(length, sizeof(char));
// Write the data to out of V8 heap space
memcpy(data, Buffer::Data(info[1]->ToObject()), length);
// Create new SecurityBuffer
security_obj = new SecurityBuffer(buffer_type, length, data);
}
// Wrap it
security_obj->Wrap(info.This());
// Return the object
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(SecurityBuffer::ToBuffer) {
// Unpack the Security Buffer object
SecurityBuffer *security_obj = Nan::ObjectWrap::Unwrap<SecurityBuffer>(info.This());
// Create a Buffer
Local<Object> buffer = Nan::CopyBuffer((char *)security_obj->data, (uint32_t)security_obj->size).ToLocalChecked();
// Return the buffer
info.GetReturnValue().Set(buffer);
}
void SecurityBuffer::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Define a new function template
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("SecurityBuffer").ToLocalChecked());
// Class methods
Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer);
// Set persistent
constructor_template.Reset(t);
// Set the symbol
target->ForceSet(Nan::New<String>("SecurityBuffer").ToLocalChecked(), t->GetFunction());
}

View File

@@ -0,0 +1,48 @@
#ifndef SECURITY_BUFFER_H
#define SECURITY_BUFFER_H
#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#define SECURITY_WIN32 1
#include <winsock2.h>
#include <windows.h>
#include <sspi.h>
#include <nan.h>
using namespace v8;
using namespace node;
class SecurityBuffer : public Nan::ObjectWrap {
public:
SecurityBuffer(uint32_t security_type, size_t size);
SecurityBuffer(uint32_t security_type, size_t size, void *data);
~SecurityBuffer();
// Internal values
void *data;
size_t size;
uint32_t security_type;
SecBuffer sec_buffer;
// Has instance check
static inline bool HasInstance(Local<Value> val) {
if (!val->IsObject()) return false;
Local<Object> obj = val->ToObject();
return Nan::New(constructor_template)->HasInstance(obj);
};
// Functions available from V8
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(ToBuffer);
// Constructor used for creating new Long objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
private:
static NAN_METHOD(New);
};
#endif

View File

@@ -0,0 +1,12 @@
var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer;
// Add some attributes
SecurityBufferNative.VERSION = 0;
SecurityBufferNative.EMPTY = 0;
SecurityBufferNative.DATA = 1;
SecurityBufferNative.TOKEN = 2;
SecurityBufferNative.PADDING = 9;
SecurityBufferNative.STREAM = 10;
// Export the modified class
exports.SecurityBuffer = SecurityBufferNative;

View File

@@ -0,0 +1,182 @@
#include <node.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <v8.h>
#include <node_buffer.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#define SECURITY_WIN32 1
#include "security_buffer_descriptor.h"
#include "security_buffer.h"
Nan::Persistent<FunctionTemplate> SecurityBufferDescriptor::constructor_template;
SecurityBufferDescriptor::SecurityBufferDescriptor() : Nan::ObjectWrap() {
}
SecurityBufferDescriptor::SecurityBufferDescriptor(const Nan::Persistent<Array>& arrayObjectPersistent) : Nan::ObjectWrap() {
SecurityBuffer *security_obj = NULL;
// Get the Local value
Local<Array> arrayObject = Nan::New(arrayObjectPersistent);
// Safe reference to array
this->arrayObject = arrayObject;
// Unpack the array and ensure we have a valid descriptor
this->secBufferDesc.cBuffers = arrayObject->Length();
this->secBufferDesc.ulVersion = SECBUFFER_VERSION;
if(arrayObject->Length() == 1) {
// Unwrap the buffer
security_obj = Nan::ObjectWrap::Unwrap<SecurityBuffer>(arrayObject->Get(0)->ToObject());
// Assign the buffer
this->secBufferDesc.pBuffers = &security_obj->sec_buffer;
} else {
this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()];
this->secBufferDesc.cBuffers = arrayObject->Length();
// Assign the buffers
for(uint32_t i = 0; i < arrayObject->Length(); i++) {
security_obj = Nan::ObjectWrap::Unwrap<SecurityBuffer>(arrayObject->Get(i)->ToObject());
this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType;
this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer;
this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer;
}
}
}
SecurityBufferDescriptor::~SecurityBufferDescriptor() {
}
size_t SecurityBufferDescriptor::bufferSize() {
SecurityBuffer *security_obj = NULL;
if(this->secBufferDesc.cBuffers == 1) {
security_obj = Nan::ObjectWrap::Unwrap<SecurityBuffer>(arrayObject->Get(0)->ToObject());
return security_obj->size;
} else {
int bytesToAllocate = 0;
for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) {
bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer;
}
// Return total size
return bytesToAllocate;
}
}
char *SecurityBufferDescriptor::toBuffer() {
SecurityBuffer *security_obj = NULL;
char *data = NULL;
if(this->secBufferDesc.cBuffers == 1) {
security_obj = Nan::ObjectWrap::Unwrap<SecurityBuffer>(arrayObject->Get(0)->ToObject());
data = (char *)malloc(security_obj->size * sizeof(char));
memcpy(data, security_obj->data, security_obj->size);
} else {
size_t bytesToAllocate = this->bufferSize();
char *data = (char *)calloc(bytesToAllocate, sizeof(char));
int offset = 0;
for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) {
memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer);
offset +=this->secBufferDesc.pBuffers[i].cbBuffer;
}
// Return the data
return data;
}
return data;
}
NAN_METHOD(SecurityBufferDescriptor::New) {
SecurityBufferDescriptor *security_obj;
Nan::Persistent<Array> arrayObject;
if(info.Length() != 1)
return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]");
if(!info[0]->IsInt32() && !info[0]->IsArray())
return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]");
if(info[0]->IsArray()) {
Local<Array> array = Local<Array>::Cast(info[0]);
// Iterate over all items and ensure we the right type
for(uint32_t i = 0; i < array->Length(); i++) {
if(!SecurityBuffer::HasInstance(array->Get(i))) {
return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]");
}
}
}
// We have a single integer
if(info[0]->IsInt32()) {
// Create new SecurityBuffer instance
Local<Value> argv[] = {Nan::New<Int32>(0x02), info[0]};
Local<Value> security_buffer = Nan::New(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv);
// Create a new array
Local<Array> array = Nan::New<Array>(1);
// Set the first value
array->Set(0, security_buffer);
// Create persistent handle
Nan::Persistent<Array> persistenHandler;
persistenHandler.Reset(array);
// Create descriptor
security_obj = new SecurityBufferDescriptor(persistenHandler);
} else {
// Create a persistent handler
Nan::Persistent<Array> persistenHandler;
persistenHandler.Reset(Local<Array>::Cast(info[0]));
// Create a descriptor
security_obj = new SecurityBufferDescriptor(persistenHandler);
}
// Wrap it
security_obj->Wrap(info.This());
// Return the object
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(SecurityBufferDescriptor::ToBuffer) {
// Unpack the Security Buffer object
SecurityBufferDescriptor *security_obj = Nan::ObjectWrap::Unwrap<SecurityBufferDescriptor>(info.This());
// Get the buffer
char *buffer_data = security_obj->toBuffer();
size_t buffer_size = security_obj->bufferSize();
// Create a Buffer
Local<Object> buffer = Nan::CopyBuffer(buffer_data, (uint32_t)buffer_size).ToLocalChecked();
// Return the buffer
info.GetReturnValue().Set(buffer);
}
void SecurityBufferDescriptor::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("SecurityBufferDescriptor").ToLocalChecked());
// Class methods
Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer);
// Set persistent
constructor_template.Reset(t);
// Set the symbol
target->ForceSet(Nan::New<String>("SecurityBufferDescriptor").ToLocalChecked(), t->GetFunction());
}

View File

@@ -0,0 +1,46 @@
#ifndef SECURITY_BUFFER_DESCRIPTOR_H
#define SECURITY_BUFFER_DESCRIPTOR_H
#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#include <WinSock2.h>
#include <windows.h>
#include <sspi.h>
#include <nan.h>
using namespace v8;
using namespace node;
class SecurityBufferDescriptor : public Nan::ObjectWrap {
public:
Local<Array> arrayObject;
SecBufferDesc secBufferDesc;
SecurityBufferDescriptor();
SecurityBufferDescriptor(const Nan::Persistent<Array>& arrayObjectPersistent);
~SecurityBufferDescriptor();
// Has instance check
static inline bool HasInstance(Local<Value> val) {
if (!val->IsObject()) return false;
Local<Object> obj = val->ToObject();
return Nan::New(constructor_template)->HasInstance(obj);
};
char *toBuffer();
size_t bufferSize();
// Functions available from V8
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(ToBuffer);
// Constructor used for creating new Long objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
private:
static NAN_METHOD(New);
};
#endif

View File

@@ -0,0 +1,3 @@
var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor;
// Export the modified class
exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative;

View File

@@ -0,0 +1,856 @@
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <node.h>
#include <v8.h>
#include <node_buffer.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include "security_context.h"
#include "security_buffer_descriptor.h"
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
#endif
static LPSTR DisplaySECError(DWORD ErrCode);
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// UV Lib callbacks
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void Process(uv_work_t* work_req) {
// Grab the worker
Worker *worker = static_cast<Worker*>(work_req->data);
// Execute the worker code
worker->execute(worker);
}
static void After(uv_work_t* work_req) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Get the worker reference
Worker *worker = static_cast<Worker*>(work_req->data);
// If we have an error
if(worker->error) {
Local<Value> err = v8::Exception::Error(Nan::New<String>(worker->error_message).ToLocalChecked());
Local<Object> obj = err->ToObject();
obj->Set(Nan::New<String>("code").ToLocalChecked(), Nan::New<Int32>(worker->error_code));
Local<Value> info[2] = { err, Nan::Null() };
// Execute the error
Nan::TryCatch try_catch;
// Call the callback
worker->callback->Call(ARRAY_SIZE(info), info);
// If we have an exception handle it as a fatalexception
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
} else {
// // Map the data
Local<Value> result = worker->mapper(worker);
// Set up the callback with a null first
Local<Value> info[2] = { Nan::Null(), result};
// Wrap the callback function call in a TryCatch so that we can call
// node's FatalException afterwards. This makes it possible to catch
// the exception from JavaScript land using the
// process.on('uncaughtException') event.
Nan::TryCatch try_catch;
// Call the callback
worker->callback->Call(ARRAY_SIZE(info), info);
// If we have an exception handle it as a fatalexception
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
}
// Clean up the memory
delete worker->callback;
delete worker;
}
Nan::Persistent<FunctionTemplate> SecurityContext::constructor_template;
SecurityContext::SecurityContext() : Nan::ObjectWrap() {
}
SecurityContext::~SecurityContext() {
if(this->hasContext) {
_sspi_DeleteSecurityContext(&this->m_Context);
}
}
NAN_METHOD(SecurityContext::New) {
PSecurityFunctionTable pSecurityInterface = NULL;
DWORD dwNumOfPkgs;
SECURITY_STATUS status;
// Create code object
SecurityContext *security_obj = new SecurityContext();
// Get security table interface
pSecurityInterface = _ssip_InitSecurityInterface();
// Call the security interface
status = (*pSecurityInterface->EnumerateSecurityPackages)(
&dwNumOfPkgs,
&security_obj->m_PkgInfo);
if(status != SEC_E_OK) {
printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError());
return Nan::ThrowError("Failed in retrieving security packages");
}
// Wrap it
security_obj->Wrap(info.This());
// Return the object
info.GetReturnValue().Set(info.This());
}
//
// Async InitializeContext
//
typedef struct SecurityContextStaticInitializeCall {
char *service_principal_name_str;
char *decoded_input_str;
int decoded_input_str_length;
SecurityContext *context;
} SecurityContextStaticInitializeCall;
static void _initializeContext(Worker *worker) {
// Status of operation
SECURITY_STATUS status;
BYTE *out_bound_data_str = NULL;
SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters;
// Structures used for c calls
SecBufferDesc ibd, obd;
SecBuffer ib, ob;
//
// Prepare data structure for returned data from SSPI
ob.BufferType = SECBUFFER_TOKEN;
ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken;
// Allocate space for return data
out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)];
ob.pvBuffer = out_bound_data_str;
// prepare buffer description
obd.cBuffers = 1;
obd.ulVersion = SECBUFFER_VERSION;
obd.pBuffers = &ob;
//
// Prepare the data we are passing to the SSPI method
if(call->decoded_input_str_length > 0) {
ib.BufferType = SECBUFFER_TOKEN;
ib.cbBuffer = call->decoded_input_str_length;
ib.pvBuffer = call->decoded_input_str;
// prepare buffer description
ibd.cBuffers = 1;
ibd.ulVersion = SECBUFFER_VERSION;
ibd.pBuffers = &ib;
}
// Perform initialization step
status = _sspi_initializeSecurityContext(
&call->context->security_credentials->m_Credentials
, NULL
, const_cast<TCHAR*>(call->service_principal_name_str)
, 0x02 // MUTUAL
, 0
, 0 // Network
, call->decoded_input_str_length > 0 ? &ibd : NULL
, 0
, &call->context->m_Context
, &obd
, &call->context->CtxtAttr
, &call->context->Expiration
);
// If we have a ok or continue let's prepare the result
if(status == SEC_E_OK
|| status == SEC_I_COMPLETE_NEEDED
|| status == SEC_I_CONTINUE_NEEDED
|| status == SEC_I_COMPLETE_AND_CONTINUE
) {
call->context->hasContext = true;
call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer);
// Set the context
worker->return_code = status;
worker->return_value = call->context;
} else if(status == SEC_E_INSUFFICIENT_MEMORY) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action.";
} else if(status == SEC_E_INTERNAL_ERROR) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code.";
} else if(status == SEC_E_INVALID_HANDLE) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid.";
} else if(status == SEC_E_INVALID_TOKEN) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package.";
} else if(status == SEC_E_LOGON_DENIED) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_LOGON_DENIED The logon failed.";
} else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure.";
} else if(status == SEC_E_NO_CREDENTIALS) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package.";
} else if(status == SEC_E_TARGET_UNKNOWN) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized.";
} else if(status == SEC_E_UNSUPPORTED_FUNCTION) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter.";
} else if(status == SEC_E_WRONG_PRINCIPAL) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication.";
} else {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = DisplaySECError(status);
}
// Clean up data
if(call->decoded_input_str != NULL) free(call->decoded_input_str);
if(call->service_principal_name_str != NULL) free(call->service_principal_name_str);
}
static Local<Value> _map_initializeContext(Worker *worker) {
// Unwrap the security context
SecurityContext *context = (SecurityContext *)worker->return_value;
// Return the value
return context->handle();
}
NAN_METHOD(SecurityContext::InitializeContext) {
char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL;
int decoded_input_str_length = NULL;
// Store reference to security credentials
SecurityCredentials *security_credentials = NULL;
// We need 3 parameters
if(info.Length() != 4)
return Nan::ThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]");
// First parameter must be an instance of SecurityCredentials
if(!SecurityCredentials::HasInstance(info[0]))
return Nan::ThrowError("First parameter for Initialize must be an instance of SecurityCredentials");
// Second parameter must be a string
if(!info[1]->IsString())
return Nan::ThrowError("Second parameter for Initialize must be a string");
// Third parameter must be a base64 encoded string
if(!info[2]->IsString())
return Nan::ThrowError("Second parameter for Initialize must be a string");
// Third parameter must be a callback
if(!info[3]->IsFunction())
return Nan::ThrowError("Third parameter for Initialize must be a callback function");
// Let's unpack the values
Local<String> service_principal_name = info[1]->ToString();
service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char));
service_principal_name->WriteUtf8(service_principal_name_str);
// Unpack the user name
Local<String> input = info[2]->ToString();
if(input->Utf8Length() > 0) {
input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char));
input->WriteUtf8(input_str);
// Now let's get the base64 decoded string
decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length);
// Free original allocation
free(input_str);
}
// Unpack the Security credentials
security_credentials = Nan::ObjectWrap::Unwrap<SecurityCredentials>(info[0]->ToObject());
// Create Security context instance
Local<Object> security_context_value = Nan::New(constructor_template)->GetFunction()->NewInstance();
// Unwrap the security context
SecurityContext *security_context = Nan::ObjectWrap::Unwrap<SecurityContext>(security_context_value);
// Add a reference to the security_credentials
security_context->security_credentials = security_credentials;
// Build the call function
SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall));
call->context = security_context;
call->decoded_input_str = decoded_input_str;
call->decoded_input_str_length = decoded_input_str_length;
call->service_principal_name_str = service_principal_name_str;
// Callback
Local<Function> callback = Local<Function>::Cast(info[3]);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = new Nan::Callback(callback);
worker->parameters = call;
worker->execute = _initializeContext;
worker->mapper = _map_initializeContext;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_GETTER(SecurityContext::PayloadGetter) {
// Unpack the context object
SecurityContext *context = Nan::ObjectWrap::Unwrap<SecurityContext>(info.This());
// Return the low bits
info.GetReturnValue().Set(Nan::New<String>(context->payload).ToLocalChecked());
}
NAN_GETTER(SecurityContext::HasContextGetter) {
// Unpack the context object
SecurityContext *context = Nan::ObjectWrap::Unwrap<SecurityContext>(info.This());
// Return the low bits
info.GetReturnValue().Set(Nan::New<Boolean>(context->hasContext));
}
//
// Async InitializeContextStep
//
typedef struct SecurityContextStepStaticInitializeCall {
char *service_principal_name_str;
char *decoded_input_str;
int decoded_input_str_length;
SecurityContext *context;
} SecurityContextStepStaticInitializeCall;
static void _initializeContextStep(Worker *worker) {
// Outbound data array
BYTE *out_bound_data_str = NULL;
// Status of operation
SECURITY_STATUS status;
// Unpack data
SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters;
SecurityContext *context = call->context;
// Structures used for c calls
SecBufferDesc ibd, obd;
SecBuffer ib, ob;
//
// Prepare data structure for returned data from SSPI
ob.BufferType = SECBUFFER_TOKEN;
ob.cbBuffer = context->m_PkgInfo->cbMaxToken;
// Allocate space for return data
out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)];
ob.pvBuffer = out_bound_data_str;
// prepare buffer description
obd.cBuffers = 1;
obd.ulVersion = SECBUFFER_VERSION;
obd.pBuffers = &ob;
//
// Prepare the data we are passing to the SSPI method
if(call->decoded_input_str_length > 0) {
ib.BufferType = SECBUFFER_TOKEN;
ib.cbBuffer = call->decoded_input_str_length;
ib.pvBuffer = call->decoded_input_str;
// prepare buffer description
ibd.cBuffers = 1;
ibd.ulVersion = SECBUFFER_VERSION;
ibd.pBuffers = &ib;
}
// Perform initialization step
status = _sspi_initializeSecurityContext(
&context->security_credentials->m_Credentials
, context->hasContext == true ? &context->m_Context : NULL
, const_cast<TCHAR*>(call->service_principal_name_str)
, 0x02 // MUTUAL
, 0
, 0 // Network
, call->decoded_input_str_length ? &ibd : NULL
, 0
, &context->m_Context
, &obd
, &context->CtxtAttr
, &context->Expiration
);
// If we have a ok or continue let's prepare the result
if(status == SEC_E_OK
|| status == SEC_I_COMPLETE_NEEDED
|| status == SEC_I_CONTINUE_NEEDED
|| status == SEC_I_COMPLETE_AND_CONTINUE
) {
// Set the new payload
if(context->payload != NULL) free(context->payload);
context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer);
worker->return_code = status;
worker->return_value = context;
} else {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = DisplaySECError(status);
}
// Clean up data
if(call->decoded_input_str != NULL) free(call->decoded_input_str);
if(call->service_principal_name_str != NULL) free(call->service_principal_name_str);
}
static Local<Value> _map_initializeContextStep(Worker *worker) {
// Unwrap the security context
SecurityContext *context = (SecurityContext *)worker->return_value;
// Return the value
return context->handle();
}
NAN_METHOD(SecurityContext::InitalizeStep) {
char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL;
int decoded_input_str_length = NULL;
// We need 3 parameters
if(info.Length() != 3)
return Nan::ThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]");
// Second parameter must be a string
if(!info[0]->IsString())
return Nan::ThrowError("First parameter for Initialize must be a string");
// Third parameter must be a base64 encoded string
if(!info[1]->IsString())
return Nan::ThrowError("Second parameter for Initialize must be a string");
// Third parameter must be a base64 encoded string
if(!info[2]->IsFunction())
return Nan::ThrowError("Third parameter for Initialize must be a callback function");
// Let's unpack the values
Local<String> service_principal_name = info[0]->ToString();
service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char));
service_principal_name->WriteUtf8(service_principal_name_str);
// Unpack the user name
Local<String> input = info[1]->ToString();
if(input->Utf8Length() > 0) {
input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char));
input->WriteUtf8(input_str);
// Now let's get the base64 decoded string
decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length);
// Free input string
free(input_str);
}
// Unwrap the security context
SecurityContext *security_context = Nan::ObjectWrap::Unwrap<SecurityContext>(info.This());
// Create call structure
SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall));
call->context = security_context;
call->decoded_input_str = decoded_input_str;
call->decoded_input_str_length = decoded_input_str_length;
call->service_principal_name_str = service_principal_name_str;
// Callback
Local<Function> callback = Local<Function>::Cast(info[2]);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = new Nan::Callback(callback);
worker->parameters = call;
worker->execute = _initializeContextStep;
worker->mapper = _map_initializeContextStep;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
//
// Async EncryptMessage
//
typedef struct SecurityContextEncryptMessageCall {
SecurityContext *context;
SecurityBufferDescriptor *descriptor;
unsigned long flags;
} SecurityContextEncryptMessageCall;
static void _encryptMessage(Worker *worker) {
SECURITY_STATUS status;
// Unpack call
SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters;
// Unpack the security context
SecurityContext *context = call->context;
SecurityBufferDescriptor *descriptor = call->descriptor;
// Let's execute encryption
status = _sspi_EncryptMessage(
&context->m_Context
, call->flags
, &descriptor->secBufferDesc
, 0
);
// We've got ok
if(status == SEC_E_OK) {
int bytesToAllocate = (int)descriptor->bufferSize();
// Free up existing payload
if(context->payload != NULL) free(context->payload);
// Save the payload
context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate);
// Set result
worker->return_code = status;
worker->return_value = context;
} else {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = DisplaySECError(status);
}
}
static Local<Value> _map_encryptMessage(Worker *worker) {
// Unwrap the security context
SecurityContext *context = (SecurityContext *)worker->return_value;
// Return the value
return context->handle();
}
NAN_METHOD(SecurityContext::EncryptMessage) {
if(info.Length() != 3)
return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function");
if(!SecurityBufferDescriptor::HasInstance(info[0]))
return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function");
if(!info[1]->IsUint32())
return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function");
if(!info[2]->IsFunction())
return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function");
// Unpack the security context
SecurityContext *security_context = Nan::ObjectWrap::Unwrap<SecurityContext>(info.This());
// Unpack the descriptor
SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap<SecurityBufferDescriptor>(info[0]->ToObject());
// Create call structure
SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall));
call->context = security_context;
call->descriptor = descriptor;
call->flags = (unsigned long)info[1]->ToInteger()->Value();
// Callback
Local<Function> callback = Local<Function>::Cast(info[2]);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = new Nan::Callback(callback);
worker->parameters = call;
worker->execute = _encryptMessage;
worker->mapper = _map_encryptMessage;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
//
// Async DecryptMessage
//
typedef struct SecurityContextDecryptMessageCall {
SecurityContext *context;
SecurityBufferDescriptor *descriptor;
} SecurityContextDecryptMessageCall;
static void _decryptMessage(Worker *worker) {
unsigned long quality = 0;
SECURITY_STATUS status;
// Unpack parameters
SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters;
SecurityContext *context = call->context;
SecurityBufferDescriptor *descriptor = call->descriptor;
// Let's execute encryption
status = _sspi_DecryptMessage(
&context->m_Context
, &descriptor->secBufferDesc
, 0
, (unsigned long)&quality
);
// We've got ok
if(status == SEC_E_OK) {
int bytesToAllocate = (int)descriptor->bufferSize();
// Free up existing payload
if(context->payload != NULL) free(context->payload);
// Save the payload
context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate);
// Set return values
worker->return_code = status;
worker->return_value = context;
} else {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = DisplaySECError(status);
}
}
static Local<Value> _map_decryptMessage(Worker *worker) {
// Unwrap the security context
SecurityContext *context = (SecurityContext *)worker->return_value;
// Return the value
return context->handle();
}
NAN_METHOD(SecurityContext::DecryptMessage) {
if(info.Length() != 2)
return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function");
if(!SecurityBufferDescriptor::HasInstance(info[0]))
return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function");
if(!info[1]->IsFunction())
return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function");
// Unpack the security context
SecurityContext *security_context = Nan::ObjectWrap::Unwrap<SecurityContext>(info.This());
// Unpack the descriptor
SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap<SecurityBufferDescriptor>(info[0]->ToObject());
// Create call structure
SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall));
call->context = security_context;
call->descriptor = descriptor;
// Callback
Local<Function> callback = Local<Function>::Cast(info[1]);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = new Nan::Callback(callback);
worker->parameters = call;
worker->execute = _decryptMessage;
worker->mapper = _map_decryptMessage;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
//
// Async QueryContextAttributes
//
typedef struct SecurityContextQueryContextAttributesCall {
SecurityContext *context;
uint32_t attribute;
} SecurityContextQueryContextAttributesCall;
static void _queryContextAttributes(Worker *worker) {
SECURITY_STATUS status;
// Cast to data structure
SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters;
// Allocate some space
SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes));
// Let's grab the query context attribute
status = _sspi_QueryContextAttributes(
&call->context->m_Context,
call->attribute,
sizes
);
if(status == SEC_E_OK) {
worker->return_code = status;
worker->return_value = sizes;
} else {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = DisplaySECError(status);
}
}
static Local<Value> _map_queryContextAttributes(Worker *worker) {
// Cast to data structure
SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters;
// Unpack the attribute
uint32_t attribute = call->attribute;
// Convert data
if(attribute == SECPKG_ATTR_SIZES) {
SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value;
// Create object
Local<Object> value = Nan::New<Object>();
value->Set(Nan::New<String>("maxToken").ToLocalChecked(), Nan::New<Integer>(uint32_t(sizes->cbMaxToken)));
value->Set(Nan::New<String>("maxSignature").ToLocalChecked(), Nan::New<Integer>(uint32_t(sizes->cbMaxSignature)));
value->Set(Nan::New<String>("blockSize").ToLocalChecked(), Nan::New<Integer>(uint32_t(sizes->cbBlockSize)));
value->Set(Nan::New<String>("securityTrailer").ToLocalChecked(), Nan::New<Integer>(uint32_t(sizes->cbSecurityTrailer)));
return value;
}
// Return the value
return Nan::Null();
}
NAN_METHOD(SecurityContext::QueryContextAttributes) {
if(info.Length() != 2)
return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function");
if(!info[0]->IsInt32())
return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function");
if(!info[1]->IsFunction())
return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function");
// Unpack the security context
SecurityContext *security_context = Nan::ObjectWrap::Unwrap<SecurityContext>(info.This());
// Unpack the int value
uint32_t attribute = info[0]->ToInt32()->Value();
// Check that we have a supported attribute
if(attribute != SECPKG_ATTR_SIZES)
return Nan::ThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute");
// Create call structure
SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall));
call->attribute = attribute;
call->context = security_context;
// Callback
Local<Function> callback = Local<Function>::Cast(info[1]);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = new Nan::Callback(callback);
worker->parameters = call;
worker->execute = _queryContextAttributes;
worker->mapper = _map_queryContextAttributes;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
void SecurityContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(static_cast<NAN_METHOD((*))>(SecurityContext::New));
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("SecurityContext").ToLocalChecked());
// Class methods
Nan::SetMethod(t, "initialize", SecurityContext::InitializeContext);
// Set up method for the instance
Nan::SetPrototypeMethod(t, "initialize", SecurityContext::InitalizeStep);
Nan::SetPrototypeMethod(t, "decryptMessage", SecurityContext::DecryptMessage);
Nan::SetPrototypeMethod(t, "queryContextAttributes", SecurityContext::QueryContextAttributes);
Nan::SetPrototypeMethod(t, "encryptMessage", SecurityContext::EncryptMessage);
// Get prototype
Local<ObjectTemplate> proto = t->PrototypeTemplate();
// Getter for the response
Nan::SetAccessor(proto, Nan::New<String>("payload").ToLocalChecked(), SecurityContext::PayloadGetter);
Nan::SetAccessor(proto, Nan::New<String>("hasContext").ToLocalChecked(), SecurityContext::HasContextGetter);
// Set persistent
SecurityContext::constructor_template.Reset(t);
// Set the symbol
target->ForceSet(Nan::New<String>("SecurityContext").ToLocalChecked(), t->GetFunction());
}
static LPSTR DisplaySECError(DWORD ErrCode) {
LPSTR pszName = NULL; // WinError.h
switch(ErrCode) {
case SEC_E_BUFFER_TOO_SMALL:
pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP.";
break;
case SEC_E_CRYPTO_SYSTEM_INVALID:
pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP.";
break;
case SEC_E_INCOMPLETE_MESSAGE:
pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again.";
break;
case SEC_E_INVALID_HANDLE:
pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs.";
break;
case SEC_E_INVALID_TOKEN:
pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP.";
break;
case SEC_E_MESSAGE_ALTERED:
pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs.";
break;
case SEC_E_OUT_OF_SEQUENCE:
pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence.";
break;
case SEC_E_QOP_NOT_SUPPORTED:
pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP.";
break;
case SEC_I_CONTEXT_EXPIRED:
pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown.";
break;
case SEC_I_RENEGOTIATE:
pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown.";
break;
case SEC_E_ENCRYPT_FAILURE:
pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted.";
break;
case SEC_E_DECRYPT_FAILURE:
pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted.";
break;
case -1:
pszName = "Failed to load security.dll library";
break;
}
return pszName;
}

View File

@@ -0,0 +1,74 @@
#ifndef SECURITY_CONTEXT_H
#define SECURITY_CONTEXT_H
#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#define SECURITY_WIN32 1
#include <winsock2.h>
#include <windows.h>
#include <sspi.h>
#include <tchar.h>
#include "security_credentials.h"
#include "../worker.h"
#include <nan.h>
extern "C" {
#include "../kerberos_sspi.h"
#include "../base64.h"
}
using namespace v8;
using namespace node;
class SecurityContext : public Nan::ObjectWrap {
public:
SecurityContext();
~SecurityContext();
// Security info package
PSecPkgInfo m_PkgInfo;
// Do we have a context
bool hasContext;
// Reference to security credentials
SecurityCredentials *security_credentials;
// Security context
CtxtHandle m_Context;
// Attributes
DWORD CtxtAttr;
// Expiry time for ticket
TimeStamp Expiration;
// Payload
char *payload;
// Has instance check
static inline bool HasInstance(Local<Value> val) {
if (!val->IsObject()) return false;
Local<Object> obj = val->ToObject();
return Nan::New(constructor_template)->HasInstance(obj);
};
// Functions available from V8
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(InitializeContext);
static NAN_METHOD(InitalizeStep);
static NAN_METHOD(DecryptMessage);
static NAN_METHOD(QueryContextAttributes);
static NAN_METHOD(EncryptMessage);
// Payload getter
static NAN_GETTER(PayloadGetter);
// hasContext getter
static NAN_GETTER(HasContextGetter);
// Constructor used for creating new Long objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
// private:
// Create a new instance
static NAN_METHOD(New);
};
#endif

View File

@@ -0,0 +1,3 @@
var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext;
// Export the modified class
exports.SecurityContext = SecurityContextNative;

View File

@@ -0,0 +1,348 @@
#include <node.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <v8.h>
#include <node_buffer.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include "security_credentials.h"
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
#endif
static LPSTR DisplaySECError(DWORD ErrCode);
Nan::Persistent<FunctionTemplate> SecurityCredentials::constructor_template;
SecurityCredentials::SecurityCredentials() : Nan::ObjectWrap() {
}
SecurityCredentials::~SecurityCredentials() {
}
NAN_METHOD(SecurityCredentials::New) {
// Create security credentials instance
SecurityCredentials *security_credentials = new SecurityCredentials();
// Wrap it
security_credentials->Wrap(info.This());
// Return the object
info.GetReturnValue().Set(info.This());
}
// Call structs
typedef struct SecurityCredentialCall {
char *package_str;
char *username_str;
char *password_str;
char *domain_str;
SecurityCredentials *credentials;
} SecurityCredentialCall;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// authGSSClientInit
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
static void _authSSPIAquire(Worker *worker) {
// Status of operation
SECURITY_STATUS status;
// Unpack data
SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters;
// // Unwrap the credentials
// SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials;
SecurityCredentials *security_credentials = new SecurityCredentials();
// If we have domain string
if(call->domain_str != NULL) {
security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str));
security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str);
} else {
security_credentials->m_Identity.Domain = NULL;
security_credentials->m_Identity.DomainLength = 0;
}
// Set up the user
security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str));
security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str);
// If we have a password string
if(call->password_str != NULL) {
// Set up the password
security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str));
security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str);
}
#ifdef _UNICODE
security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
#else
security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
#endif
// Attempt to acquire credentials
status = _sspi_AcquireCredentialsHandle(
NULL,
call->package_str,
SECPKG_CRED_OUTBOUND,
NULL,
call->password_str != NULL ? &security_credentials->m_Identity : NULL,
NULL, NULL,
&security_credentials->m_Credentials,
&security_credentials->Expiration
);
// We have an error
if(status != SEC_E_OK) {
worker->error = TRUE;
worker->error_code = status;
worker->error_message = DisplaySECError(status);
} else {
worker->return_code = status;
worker->return_value = security_credentials;
}
// Free up parameter structure
if(call->package_str != NULL) free(call->package_str);
if(call->domain_str != NULL) free(call->domain_str);
if(call->password_str != NULL) free(call->password_str);
if(call->username_str != NULL) free(call->username_str);
free(call);
}
static Local<Value> _map_authSSPIAquire(Worker *worker) {
return Nan::Null();
}
NAN_METHOD(SecurityCredentials::Aquire) {
char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL;
// Unpack the variables
if(info.Length() != 2 && info.Length() != 3 && info.Length() != 4 && info.Length() != 5)
return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]");
if(!info[0]->IsString())
return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]");
if(!info[1]->IsString())
return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]");
if(info.Length() == 3 && (!info[2]->IsString() && !info[2]->IsFunction()))
return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]");
if(info.Length() == 4 && (!info[3]->IsString() && !info[3]->IsUndefined() && !info[3]->IsNull()) && !info[3]->IsFunction())
return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]");
if(info.Length() == 5 && !info[4]->IsFunction())
return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]");
Local<Function> callbackHandle;
// Figure out which parameter is the callback
if(info.Length() == 5) {
callbackHandle = Local<Function>::Cast(info[4]);
} else if(info.Length() == 4) {
callbackHandle = Local<Function>::Cast(info[3]);
} else if(info.Length() == 3) {
callbackHandle = Local<Function>::Cast(info[2]);
}
// Unpack the package
Local<String> package = info[0]->ToString();
package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char));
package->WriteUtf8(package_str);
// Unpack the user name
Local<String> username = info[1]->ToString();
username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char));
username->WriteUtf8(username_str);
// If we have a password
if(info.Length() == 3 || info.Length() == 4 || info.Length() == 5) {
Local<String> password = info[2]->ToString();
password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char));
password->WriteUtf8(password_str);
}
// If we have a domain
if((info.Length() == 4 || info.Length() == 5) && info[3]->IsString()) {
Local<String> domain = info[3]->ToString();
domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char));
domain->WriteUtf8(domain_str);
}
// Allocate call structure
SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall));
call->domain_str = domain_str;
call->package_str = package_str;
call->password_str = password_str;
call->username_str = username_str;
// Unpack the callback
Nan::Callback *callback = new Nan::Callback(callbackHandle);
// Let's allocate some space
Worker *worker = new Worker();
worker->error = false;
worker->request.data = worker;
worker->callback = callback;
worker->parameters = call;
worker->execute = _authSSPIAquire;
worker->mapper = _map_authSSPIAquire;
// Schedule the worker with lib_uv
uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After);
// Return no value as it's callback based
info.GetReturnValue().Set(Nan::Undefined());
}
void SecurityCredentials::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New<String>("SecurityCredentials").ToLocalChecked());
// Class methods
Nan::SetMethod(t, "aquire", Aquire);
// Set persistent
constructor_template.Reset(t);
// Set the symbol
target->ForceSet(Nan::New<String>("SecurityCredentials").ToLocalChecked(), t->GetFunction());
// Attempt to load the security.dll library
load_library();
}
static LPSTR DisplaySECError(DWORD ErrCode) {
LPSTR pszName = NULL; // WinError.h
switch(ErrCode) {
case SEC_E_BUFFER_TOO_SMALL:
pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP.";
break;
case SEC_E_CRYPTO_SYSTEM_INVALID:
pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP.";
break;
case SEC_E_INCOMPLETE_MESSAGE:
pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again.";
break;
case SEC_E_INVALID_HANDLE:
pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs.";
break;
case SEC_E_INVALID_TOKEN:
pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP.";
break;
case SEC_E_MESSAGE_ALTERED:
pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs.";
break;
case SEC_E_OUT_OF_SEQUENCE:
pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence.";
break;
case SEC_E_QOP_NOT_SUPPORTED:
pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP.";
break;
case SEC_I_CONTEXT_EXPIRED:
pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown.";
break;
case SEC_I_RENEGOTIATE:
pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown.";
break;
case SEC_E_ENCRYPT_FAILURE:
pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted.";
break;
case SEC_E_DECRYPT_FAILURE:
pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted.";
break;
case -1:
pszName = "Failed to load security.dll library";
break;
}
return pszName;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// UV Lib callbacks
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void SecurityCredentials::Process(uv_work_t* work_req) {
// Grab the worker
Worker *worker = static_cast<Worker*>(work_req->data);
// Execute the worker code
worker->execute(worker);
}
void SecurityCredentials::After(uv_work_t* work_req) {
// Grab the scope of the call from Node
Nan::HandleScope scope;
// Get the worker reference
Worker *worker = static_cast<Worker*>(work_req->data);
// If we have an error
if(worker->error) {
Local<Value> err = v8::Exception::Error(Nan::New<String>(worker->error_message).ToLocalChecked());
Local<Object> obj = err->ToObject();
obj->Set(Nan::New<String>("code").ToLocalChecked(), Nan::New<Int32>(worker->error_code));
Local<Value> info[2] = { err, Nan::Null() };
// Execute the error
Nan::TryCatch try_catch;
// Call the callback
worker->callback->Call(ARRAY_SIZE(info), info);
// If we have an exception handle it as a fatalexception
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
} else {
SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value;
// Create a new instance
Local<Object> result = Nan::New(constructor_template)->GetFunction()->NewInstance();
// Unwrap the credentials
SecurityCredentials *security_credentials = Nan::ObjectWrap::Unwrap<SecurityCredentials>(result);
// Set the values
security_credentials->m_Identity = return_value->m_Identity;
security_credentials->m_Credentials = return_value->m_Credentials;
security_credentials->Expiration = return_value->Expiration;
// Set up the callback with a null first
Local<Value> info[2] = { Nan::Null(), result};
// Wrap the callback function call in a TryCatch so that we can call
// node's FatalException afterwards. This makes it possible to catch
// the exception from JavaScript land using the
// process.on('uncaughtException') event.
Nan::TryCatch try_catch;
// Call the callback
worker->callback->Call(ARRAY_SIZE(info), info);
// If we have an exception handle it as a fatalexception
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
}
// Clean up the memory
delete worker->callback;
delete worker;
}

View File

@@ -0,0 +1,68 @@
#ifndef SECURITY_CREDENTIALS_H
#define SECURITY_CREDENTIALS_H
#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#define SECURITY_WIN32 1
#include <WinSock2.h>
#include <windows.h>
#include <sspi.h>
#include <tchar.h>
#include <nan.h>
#include "../worker.h"
#include <uv.h>
extern "C" {
#include "../kerberos_sspi.h"
}
// SEC_WINNT_AUTH_IDENTITY makes it unusually hard
// to compile for both Unicode and ansi, so I use this macro:
#ifdef _UNICODE
#define USTR(str) (str)
#else
#define USTR(str) ((unsigned char*)(str))
#endif
using namespace v8;
using namespace node;
class SecurityCredentials : public Nan::ObjectWrap {
public:
SecurityCredentials();
~SecurityCredentials();
// Pointer to context object
SEC_WINNT_AUTH_IDENTITY m_Identity;
// credentials
CredHandle m_Credentials;
// Expiry time for ticket
TimeStamp Expiration;
// Has instance check
static inline bool HasInstance(Local<Value> val) {
if (!val->IsObject()) return false;
Local<Object> obj = val->ToObject();
return Nan::New(constructor_template)->HasInstance(obj);
};
// Functions available from V8
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(Aquire);
// Constructor used for creating new Long objects from C++
static Nan::Persistent<FunctionTemplate> constructor_template;
private:
// Create a new instance
static NAN_METHOD(New);
// Handles the uv calls
static void Process(uv_work_t* work_req);
// Called after work is done
static void After(uv_work_t* work_req);
};
#endif

View File

@@ -0,0 +1,22 @@
var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials;
// Add simple kebros helper
SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) {
if(typeof password == 'function') {
callback = password;
password = null;
} else if(typeof domain == 'function') {
callback = domain;
domain = null;
}
// We are going to use the async version
if(typeof callback == 'function') {
return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback);
} else {
return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain);
}
}
// Export the modified class
exports.SecurityCredentials = SecurityCredentialsNative;

View File

@@ -0,0 +1,7 @@
#include "worker.h"
Worker::Worker() {
}
Worker::~Worker() {
}

View File

@@ -0,0 +1,38 @@
#ifndef WORKER_H_
#define WORKER_H_
#include <node.h>
#include <node_object_wrap.h>
#include <nan.h>
#include <v8.h>
using namespace node;
using namespace v8;
class Worker {
public:
Worker();
virtual ~Worker();
// libuv's request struct.
uv_work_t request;
// Callback
Nan::Callback *callback;
// Parameters
void *parameters;
// Results
void *return_value;
// Did we raise an error
bool error;
// The error message
char *error_message;
// Error code if not message
int error_code;
// Any return code
int return_code;
// Method we are going to fire
void (*execute)(Worker *worker);
Local<Value> (*mapper)(Worker *worker);
};
#endif // WORKER_H_

View File

@@ -0,0 +1,30 @@
## DNT config file
## see https://github.com/rvagg/dnt
NODE_VERSIONS="\
master \
v0.11.13 \
v0.10.30 \
v0.10.29 \
v0.10.28 \
v0.10.26 \
v0.10.25 \
v0.10.24 \
v0.10.23 \
v0.10.22 \
v0.10.21 \
v0.10.20 \
v0.10.19 \
v0.8.28 \
v0.8.27 \
v0.8.26 \
v0.8.24 \
"
OUTPUT_PREFIX="nan-"
TEST_CMD=" \
cd /dnt/ && \
npm install && \
node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \
node_modules/.bin/tap --gc test/js/*-test.js \
"

View File

@@ -0,0 +1,374 @@
# NAN ChangeLog
**Version 2.0.9: current Node 4.0.0, Node 12: 0.12.7, Node 10: 0.10.40, iojs: 3.2.0**
### 2.0.9 Sep 8 2015
- Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7
### 2.0.8 Aug 28 2015
- Work around duplicate linking bug in clang 11902da
### 2.0.7 Aug 26 2015
- Build: Repackage
### 2.0.6 Aug 26 2015
- Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1
- Bugfix: Remove unused static std::map instances 525bddc
- Bugfix: Make better use of maybe versions of APIs bfba85b
- Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d
### 2.0.5 Aug 10 2015
- Bugfix: Reimplement weak callback in ObjectWrap 98d38c1
- Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d
### 2.0.4 Aug 6 2015
- Build: Repackage
### 2.0.3 Aug 6 2015
- Bugfix: Don't use clang++ / g++ syntax extension. 231450e
### 2.0.2 Aug 6 2015
- Build: Repackage
### 2.0.1 Aug 6 2015
- Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687
- Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601
- Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f
- Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed
### 2.0.0 Jul 31 2015
- Change: Renamed identifiers with leading underscores b5932b4
- Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1
- Change: Replace NanScope and NanEscpableScope macros with classes 47751c4
- Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99
- Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5
- Change: Rename NanNewBuffer to NanCopyBuffer d6af78d
- Change: Remove Nan prefix from all names 72d1f67
- Change: Update Buffer API for new upstream changes d5d3291
- Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a
- Change: Get rid of Handles e6c0daf
- Feature: Support io.js 3 with V8 4.4
- Feature: Introduce NanPersistent 7fed696
- Feature: Introduce NanGlobal 4408da1
- Feature: Added NanTryCatch 10f1ca4
- Feature: Update for V8 v4.3 4b6404a
- Feature: Introduce NanNewOneByteString c543d32
- Feature: Introduce namespace Nan 67ed1b1
- Removal: Remove NanLocker and NanUnlocker dd6e401
- Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9
- Removal: Remove NanReturn* macros d90a25c
- Removal: Remove HasInstance e8f84fe
### 1.9.0 Jul 31 2015
- Feature: Added `NanFatalException` 81d4a2c
- Feature: Added more error types 4265f06
- Feature: Added dereference and function call operators to NanCallback c4b2ed0
- Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c
- Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6
- Feature: Added NanErrnoException dd87d9e
- Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130
- Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c
- Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b
### 1.8.4 Apr 26 2015
- Build: Repackage
### 1.8.3 Apr 26 2015
- Bugfix: Include missing header 1af8648
### 1.8.2 Apr 23 2015
- Build: Repackage
### 1.8.1 Apr 23 2015
- Bugfix: NanObjectWrapHandle should take a pointer 155f1d3
### 1.8.0 Apr 23 2015
- Feature: Allow primitives with NanReturnValue 2e4475e
- Feature: Added comparison operators to NanCallback 55b075e
- Feature: Backport thread local storage 15bb7fa
- Removal: Remove support for signatures with arguments 8a2069d
- Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59
### 1.7.0 Feb 28 2015
- Feature: Made NanCallback::Call accept optional target 8d54da7
- Feature: Support atom-shell 0.21 0b7f1bb
### 1.6.2 Feb 6 2015
- Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639
### 1.6.1 Jan 23 2015
- Build: version bump
### 1.5.3 Jan 23 2015
- Build: repackage
### 1.6.0 Jan 23 2015
- Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af
- Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179
- Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9
### 1.5.2 Jan 23 2015
- Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4
- Bugfix: Readded missing String constructors 18d828f
- Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b
- Bugfix: Fix uv_work_cb versioning 997e4ae
- Bugfix: Add function factory and test 4eca89c
- Bugfix: Add object template factory and test cdcb951
- Correctness: Lifted an io.js related typedef c9490be
- Correctness: Make explicit downcasts of String lengths 00074e6
- Windows: Limit the scope of disabled warning C4530 83d7deb
### 1.5.1 Jan 15 2015
- Build: version bump
### 1.4.3 Jan 15 2015
- Build: version bump
### 1.4.2 Jan 15 2015
- Feature: Support io.js 0dbc5e8
### 1.5.0 Jan 14 2015
- Feature: Support io.js b003843
- Correctness: Improved NanNew internals 9cd4f6a
- Feature: Implement progress to NanAsyncWorker 8d6a160
### 1.4.1 Nov 8 2014
- Bugfix: Handle DEBUG definition correctly
- Bugfix: Accept int as Boolean
### 1.4.0 Nov 1 2014
- Feature: Added NAN_GC_CALLBACK 6a5c245
- Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8
- Correctness: Added constness to references in NanHasInstance 02c61cd
- Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6
- Windoze: Shut Visual Studio up when compiling 8d558c1
- License: Switch to plain MIT from custom hacked MIT license 11de983
- Build: Added test target to Makefile e232e46
- Performance: Removed superfluous scope in NanAsyncWorker f4b7821
- Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208
- Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450
### 1.3.0 Aug 2 2014
- Added NanNew<v8::String, std::string>(std::string)
- Added NanNew<v8::String, std::string&>(std::string&)
- Added NanAsciiString helper class
- Added NanUtf8String helper class
- Added NanUcs2String helper class
- Deprecated NanRawString()
- Deprecated NanCString()
- Added NanGetIsolateData(v8::Isolate *isolate)
- Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv)
- Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv)
- Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv)
- Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
- Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
- Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value)
- Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
### 1.2.0 Jun 5 2014
- Add NanSetPrototypeTemplate
- Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class,
introduced _NanWeakCallbackDispatcher
- Removed -Wno-unused-local-typedefs from test builds
- Made test builds Windows compatible ('Sleep()')
### 1.1.2 May 28 2014
- Release to fix more stuff-ups in 1.1.1
### 1.1.1 May 28 2014
- Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0
### 1.1.0 May 25 2014
- Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead
- Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]),
(uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*,
v8::String::ExternalAsciiStringResource*
- Deprecate NanSymbol()
- Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker
### 1.0.0 May 4 2014
- Heavy API changes for V8 3.25 / Node 0.11.13
- Use cpplint.py
- Removed NanInitPersistent
- Removed NanPersistentToLocal
- Removed NanFromV8String
- Removed NanMakeWeak
- Removed NanNewLocal
- Removed NAN_WEAK_CALLBACK_OBJECT
- Removed NAN_WEAK_CALLBACK_DATA
- Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions
- Introduce NanUndefined, NanNull, NanTrue and NanFalse
- Introduce NanEscapableScope and NanEscapeScope
- Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node)
- Introduce NanMakeCallback for node::MakeCallback
- Introduce NanSetTemplate
- Introduce NanGetCurrentContext
- Introduce NanCompileScript and NanRunScript
- Introduce NanAdjustExternalMemory
- Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback
- Introduce NanGetHeapStatistics
- Rename NanAsyncWorker#SavePersistent() to SaveToPersistent()
### 0.8.0 Jan 9 2014
- NanDispose -> NanDisposePersistent, deprecate NanDispose
- Extract _NAN_*_RETURN_TYPE, pull up NAN_*()
### 0.7.1 Jan 9 2014
- Fixes to work against debug builds of Node
- Safer NanPersistentToLocal (avoid reinterpret_cast)
- Speed up common NanRawString case by only extracting flattened string when necessary
### 0.7.0 Dec 17 2013
- New no-arg form of NanCallback() constructor.
- NanCallback#Call takes Handle rather than Local
- Removed deprecated NanCallback#Run method, use NanCallback#Call instead
- Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS
- Restore (unofficial) Node 0.6 compatibility at NanCallback#Call()
- Introduce NanRawString() for char* (or appropriate void*) from v8::String
(replacement for NanFromV8String)
- Introduce NanCString() for null-terminated char* from v8::String
### 0.6.0 Nov 21 2013
- Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of
v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9
### 0.5.2 Nov 16 2013
- Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public
### 0.5.1 Nov 12 2013
- Use node::MakeCallback() instead of direct v8::Function::Call()
### 0.5.0 Nov 11 2013
- Added @TooTallNate as collaborator
- New, much simpler, "include_dirs" for binding.gyp
- Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros
### 0.4.4 Nov 2 2013
- Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+
### 0.4.3 Nov 2 2013
- Include node_object_wrap.h, removed from node.h for Node 0.11.8.
### 0.4.2 Nov 2 2013
- Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for
Node 0.11.8 release.
### 0.4.1 Sep 16 2013
- Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8
### 0.4.0 Sep 2 2013
- Added NAN_INLINE and NAN_DEPRECATED and made use of them
- Added NanError, NanTypeError and NanRangeError
- Cleaned up code
### 0.3.2 Aug 30 2013
- Fix missing scope declaration in GetFromPersistent() and SaveToPersistent
in NanAsyncWorker
### 0.3.1 Aug 20 2013
- fix "not all control paths return a value" compile warning on some platforms
### 0.3.0 Aug 19 2013
- Made NAN work with NPM
- Lots of fixes to NanFromV8String, pulling in features from new Node core
- Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API
- Added optional error number argument for NanThrowError()
- Added NanInitPersistent()
- Added NanReturnNull() and NanReturnEmptyString()
- Added NanLocker and NanUnlocker
- Added missing scopes
- Made sure to clear disposed Persistent handles
- Changed NanAsyncWorker to allocate error messages on the heap
- Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>)
- Fixed leak in NanAsyncWorker when errmsg is used
### 0.2.2 Aug 5 2013
- Fixed usage of undefined variable with node::BASE64 in NanFromV8String()
### 0.2.1 Aug 5 2013
- Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for
NanFromV8String()
### 0.2.0 Aug 5 2013
- Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR,
NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY
- Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS,
_NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS,
_NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS,
_NAN_PROPERTY_QUERY_ARGS
- Added NanGetInternalFieldPointer, NanSetInternalFieldPointer
- Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT,
NAN_WEAK_CALLBACK_DATA, NanMakeWeak
- Renamed THROW_ERROR to _NAN_THROW_ERROR
- Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*)
- Added NanBufferUse(char*, uint32_t)
- Added NanNewContextHandle(v8::ExtensionConfiguration*,
v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>)
- Fixed broken NanCallback#GetFunction()
- Added optional encoding and size arguments to NanFromV8String()
- Added NanGetPointerSafe() and NanSetPointerSafe()
- Added initial test suite (to be expanded)
- Allow NanUInt32OptionValue to convert any Number object
### 0.1.0 Jul 21 2013
- Added `NAN_GETTER`, `NAN_SETTER`
- Added `NanThrowError` with single Local<Value> argument
- Added `NanNewBufferHandle` with single uint32_t argument
- Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)`
- Added `Local<Function> NanCallback#GetFunction()`
- Added `NanCallback#Call(int, Local<Value>[])`
- Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call

View File

@@ -0,0 +1,13 @@
The MIT License (MIT)
=====================
Copyright (c) 2015 NAN contributors
-----------------------------------
*NAN contributors listed at <https://github.com/nodejs/nan#contributors>*
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.

View File

@@ -0,0 +1,367 @@
Native Abstractions for Node.js
===============================
**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.**
***Current version: 2.0.9***
*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/)
[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan)
[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan)
Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
This project also contains some helper utilities that make addon development a bit more pleasant.
* **[News & Updates](#news)**
* **[Usage](#usage)**
* **[Example](#example)**
* **[API](#api)**
* **[Tests](#tests)**
* **[Governance & Contributing](#governance)**
<a name="news"></a>
## News & Updates
<a name="usage"></a>
## Usage
Simply add **NAN** as a dependency in the *package.json* of your Node addon:
``` bash
$ npm install --save nan
```
Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
``` python
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
```
This works like a `-I<path-to-NAN>` when compiling your addon.
<a name="example"></a>
## Example
Just getting started with Nan? Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
<a name="api"></a>
## API
Additional to the NAN documentation below, please consult:
* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started)
* [The V8 Embedders Guide](https://developers.google.com/v8/embed)
* [V8 API Documentation](http://v8docs.nodesource.com/)
<!-- START API -->
### JavaScript-accessible methods
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information.
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
* **Method argument types**
- <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
* **Method declarations**
- <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
- <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
- <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
- <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
* Method and template helpers
- <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
### Scopes
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
- <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
- <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
### Persistent references
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
- <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
- <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
- <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
### New
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
- <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
- <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
- <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
- <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
- <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
- <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
### Converters
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
- <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
### Maybe Types
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
* **Maybe Types**
- <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
- <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
- <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
- <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
* **Maybe Helpers**
- <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_force_set"><b><code>Nan::ForceSet()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
### Script
NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
- <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
- <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
### Errors
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
Note that an Error object is simply a specialized form of `v8::Value`.
Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
- <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
- <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
- <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
- <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
### Buffers
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
- <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
### Nan::Callback
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
- <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
### Asynchronous work helpers
`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier.
- <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
### Strings & Bytes
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
- <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
- <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
### V8 internals
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
- <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
### Miscellaneous V8 Helpers
- <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
### Miscellaneous Node Helpers
- <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
- <a href="doc/node_misc.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
- <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
- <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
<!-- END API -->
<a name="tests"></a>
### Tests
To run the NAN tests do:
``` sh
npm install
npm run-script rebuild-tests
npm test
```
Or just:
``` sh
npm install
make test
```
<a name="governance"></a>
## Governance & Contributing
NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group
### Addon API Working Group (WG)
The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects.
The WG has final authority over this project including:
* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Maintaining the list of additional Collaborators
For the current list of WG members, see the project [README.md](./README.md#collaborators).
Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
### Consensus Seeking Process
The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
### Developer's Certificate of Origin 1.0
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.
<a name="collaborators"></a>
### WG Members / Collaborators
<table><tbody>
<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td>-</td></tr>
</tbody></table>
## Licence &amp; copyright
Copyright (c) 2015 NAN WG Members / Collaborators (listed above).
Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.

View File

@@ -0,0 +1,38 @@
# http://www.appveyor.com/docs/appveyor-yml
# Test against these versions of Io.js and Node.js.
environment:
matrix:
# node.js
- nodejs_version: "0.8"
- nodejs_version: "0.10"
- nodejs_version: "0.12"
# io.js
- nodejs_version: "1"
- nodejs_version: "2"
- nodejs_version: "3"
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node 0.STABLE.latest
- ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version}
- ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)}
- IF %nodejs_version% LSS 1 npm -g install npm
- IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH%
# Typical npm stuff.
- npm install
- IF %nodejs_version% EQU 0.8 (node node_modules\node-gyp\bin\node-gyp.js rebuild --msvs_version=2013 --directory test) ELSE (npm run rebuild-tests)
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- IF %nodejs_version% LSS 1 (npm test) ELSE (iojs node_modules\tap\bin\tap.js --gc test/js/*-test.js)
# Don't actually build.
build: off
# Set build version format here instead of in the admin panel.
version: "{build}"

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env bash
files=" \
methods.md \
scopes.md \
persistent.md \
new.md \
converters.md \
maybe_types.md \
script.md \
errors.md \
buffers.md \
callback.md \
asyncworker.md \
string_bytes.md \
v8_internals.md \
v8_misc.md \
node_misc.md \
"
__dirname=$(dirname "${BASH_SOURCE[0]}")
head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/<!-- START/){$en=1} };' $__dirname/../README.md)
tail=$(perl -e 'while (<>) { if ($_=~/<!-- END/){$st=1} if ($st){print;} };' $__dirname/../README.md)
apidocs=$(for f in $files; do
perl -pe '
last if /^<a name/;
$_ =~ s/^## /### /;
$_ =~ s/<a href="#/<a href="doc\/'$f'#/;
' $__dirname/$f;
done)
cat > $__dirname/../README.md << EOF
$head
$apidocs
$tail
EOF

View File

@@ -0,0 +1,97 @@
## Asynchronous work helpers
`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier.
- <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
- <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorker</code></b></a>
- <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
<a name="api_nan_async_worker"></a>
### Nan::AsyncWorker
`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress.
Definition:
```c++
class AsyncWorker {
public:
explicit AsyncWorker(Callback *callback_);
virtual ~AsyncWorker();
virtual void WorkComplete();
void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value);
void SaveToPersistent(const v8::Local<v8::String> &key,
const v8::Local<v8::Value> &value);
void SaveToPersistent(uint32_t index,
const v8::Local<v8::Value> &value);
v8::Local<v8::Value> GetFromPersistent(const char *key) const;
v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const;
v8::Local<v8::Value> GetFromPersistent(uint32_t index) const;
virtual void Execute() = 0;
uv_work_t request;
virtual void Destroy();
protected:
Persistent<v8::Object> persistentHandle;
Callback *callback;
virtual void HandleOKCallback();
virtual void HandleErrorCallback();
void SetErrorMessage(const char *msg);
const char* ErrorMessage();
};
```
<a name="api_nan_async_progress_worker"></a>
### Nan::AsyncProgressWorker
`Nan::AsyncProgressWorker` is an _abstract_ class that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
Definition:
```c++
class AsyncProgressWorker : public AsyncWorker {
public:
explicit AsyncProgressWorker(Callback *callback_);
virtual ~AsyncProgressWorker();
void WorkProgress();
class ExecutionProgress {
public:
void Send(const char* data, size_t size) const;
};
virtual void Execute(const ExecutionProgress& progress) = 0;
virtual void HandleProgressCallback(const char *data, size_t size) = 0;
virtual void Destroy();
```
<a name="api_nan_async_queue_worker"></a>
### Nan::AsyncQueueWorker
`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`.
Definition:
```c++
void AsyncQueueWorker(AsyncWorker *);
```

View File

@@ -0,0 +1,54 @@
## Buffers
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
- <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
- <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
- <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
<a name="api_nan_new_buffer"></a>
### Nan::NewBuffer()
Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`.
Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management.
When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`.
You _must not_ free the memory space manually once you have created a `Buffer` in this way.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size)
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size)
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data,
size_t length,
Nan::FreeCallback callback,
void *hint)
```
<a name="api_nan_copy_buffer"></a>
### Nan::CopyBuffer()
Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`.
Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size)
```
<a name="api_nan_free_callback"></a>
### Nan::FreeCallback()
A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer).
The supplied callback will be invoked when the `Buffer` undergoes garbage collection.
Signature:
```c++
typedef void (*FreeCallback)(char *data, void *hint);
```

View File

@@ -0,0 +1,52 @@
## Nan::Callback
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
- <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a>
<a name="api_nan_callback"></a>
### Nan::Callback
```c++
class Callback {
public:
Callback();
explicit Callback(const v8::Local<v8::Function> &fn);
~Callback();
bool operator==(const Callback &other) const;
bool operator!=(const Callback &other) const;
v8::Local<v8::Function> operator*() const;
v8::Local<v8::Value> operator()(v8::Local<v8::Object> target,
int argc = 0,
v8::Local<v8::Value> argv[] = 0) const;
v8::Local<v8::Value> operator()(int argc = 0,
v8::Local<v8::Value> argv[] = 0) const;
void SetFunction(const v8::Local<v8::Function> &fn);
v8::Local<v8::Function> GetFunction() const;
bool IsEmpty() const;
v8::Local<v8::Value> Call(v8::Local<v8::Object> target,
int argc,
v8::Local<v8::Value> argv[]) const;
v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const;
};
```
Example usage:
```c++
v8::Local<v8::Function> function;
Nan::Callback callback(function);
callback->Call(0, 0);
```

View File

@@ -0,0 +1,41 @@
## Converters
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
- <a href="#api_nan_to"><b><code>Nan::To()</code></b></a>
<a name="api_nan_to"></a>
### Nan::To()
Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly.
See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types.
Signatures:
```c++
// V8 types
Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val);
// Native types
Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val);
Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val);
Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val);
Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val);
Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val);
```
### Example
```c++
v8::Local<v8::Value> val;
Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val);
Nan::Maybe<double> d = Nan::To<double>(val);
```

View File

@@ -0,0 +1,226 @@
## Errors
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
Note that an Error object is simply a specialized form of `v8::Value`.
Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
- <a href="#api_nan_error"><b><code>Nan::Error()</code></b></a>
- <a href="#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
- <a href="#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
- <a href="#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
- <a href="#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
- <a href="#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
- <a href="#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
- <a href="#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
- <a href="#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
- <a href="#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
- <a href="#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
- <a href="#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
- <a href="#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
<a name="api_nan_error"></a>
### Nan::Error()
Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.0/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an Error object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::Error(const char *msg);
v8::Local<v8::Value> Nan::Error(v8::Local<v8::String> msg);
```
<a name="api_nan_range_error"></a>
### Nan::RangeError()
Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.0/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an RangeError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::RangeError(const char *msg);
v8::Local<v8::Value> Nan::RangeError(v8::Local<v8::String> msg);
```
<a name="api_nan_reference_error"></a>
### Nan::ReferenceError()
Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.0/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an ReferenceError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::ReferenceError(const char *msg);
v8::Local<v8::Value> Nan::ReferenceError(v8::Local<v8::String> msg);
```
<a name="api_nan_syntax_error"></a>
### Nan::SyntaxError()
Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.0/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an SyntaxError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::SyntaxError(const char *msg);
v8::Local<v8::Value> Nan::SyntaxError(v8::Local<v8::String> msg);
```
<a name="api_nan_type_error"></a>
### Nan::TypeError()
Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.0/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an TypeError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::TypeError(const char *msg);
v8::Local<v8::Value> Nan::TypeError(v8::Local<v8::String> msg);
```
<a name="api_nan_throw_error"></a>
### Nan::ThrowError()
Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created.
Signature:
```c++
void Nan::ThrowError(const char *msg);
void Nan::ThrowError(v8::Local<v8::String> msg);
void Nan::ThrowError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_range_error"></a>
### Nan::ThrowRangeError()
Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created.
Signature:
```c++
void Nan::ThrowRangeError(const char *msg);
void Nan::ThrowRangeError(v8::Local<v8::String> msg);
void Nan::ThrowRangeError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_reference_error"></a>
### Nan::ThrowReferenceError()
Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created.
Signature:
```c++
void Nan::ThrowReferenceError(const char *msg);
void Nan::ThrowReferenceError(v8::Local<v8::String> msg);
void Nan::ThrowReferenceError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_syntax_error"></a>
### Nan::ThrowSyntaxError()
Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created.
Signature:
```c++
void Nan::ThrowSyntaxError(const char *msg);
void Nan::ThrowSyntaxError(v8::Local<v8::String> msg);
void Nan::ThrowSyntaxError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_type_error"></a>
### Nan::ThrowTypeError()
Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created.
Signature:
```c++
void Nan::ThrowTypeError(const char *msg);
void Nan::ThrowTypeError(v8::Local<v8::String> msg);
void Nan::ThrowTypeError(v8::Local<v8::Value> error);
```
<a name="api_nan_fatal_exception"></a>
### Nan::FatalException()
Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch).
Signature:
```c++
void Nan::FatalException(const Nan::TryCatch& try_catch);
```
<a name="api_nan_errno_exception"></a>
### Nan::ErrnoException()
Replaces `node::ErrnoException()` which has a different API across supported versions of Node.
Signature:
```c++
v8::Local<v8::Value> Nan::ErrnoException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL);
```
<a name="api_nan_try_catch"></a>
### Nan::TryCatch
A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/io.js-3.0/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`.
Signature:
```c++
class Nan::TryCatch {
public:
Nan::TryCatch();
bool HasCaught() const;
bool CanContinue() const;
v8::Local<v8::Value> ReThrow();
v8::Local<v8::Value> Exception() const;
// Nan::MaybeLocal for older versions of V8
v8::MaybeLocal<v8::Value> StackTrace() const;
v8::Local<v8::Message> Message() const;
void Reset();
void SetVerbose(bool value);
void SetCaptureMessage(bool value);
};
```

View File

@@ -0,0 +1,480 @@
## Maybe Types
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
* **Maybe Types**
- <a href="#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
- <a href="#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
- <a href="#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
- <a href="#api_nan_just"><b><code>Nan::Just</code></b></a>
* **Maybe Helpers**
- <a href="#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
- <a href="#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
- <a href="#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
- <a href="#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
- <a href="#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
- <a href="#api_nan_set"><b><code>Nan::Set()</code></b></a>
- <a href="#api_nan_force_set"><b><code>Nan::ForceSet()</code></b></a>
- <a href="#api_nan_get"><b><code>Nan::Get()</code></b></a>
- <a href="#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
- <a href="#api_nan_has"><b><code>Nan::Has()</code></b></a>
- <a href="#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
- <a href="#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
- <a href="#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
- <a href="#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
- <a href="#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
- <a href="#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
- <a href="#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
- <a href="#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
- <a href="#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
- <a href="#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
- <a href="#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
- <a href="#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
- <a href="#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
- <a href="#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
- <a href="#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
- <a href="#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
- <a href="#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
- <a href="#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
<a name="api_nan_maybe_local"></a>
### Nan::MaybeLocal
A `Nan::MaybeLocal<T>` is a wrapper around [`v8::Local<T>`](https://v8docs.nodesource.com/io.js-3.0/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local<T>` is empty before it can be used.
If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned.
Definition:
```c++
template<typename T> class Nan::MaybeLocal {
public:
MaybeLocal();
template<typename S> MaybeLocal(v8::Local<S> that);
bool IsEmpty() const;
template<typename S> bool ToLocal(v8::Local<S> *out);
// Will crash if the MaybeLocal<> is empty.
v8::Local<T> ToLocalChecked();
template<typename S> v8::Local<S> FromMaybe(v8::Local<S> default_value) const;
};
```
See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/io.js-3.0/d8/d7d/classv8_1_1_maybe_local.html) for further details.
<a name="api_nan_maybe"></a>
### Nan::Maybe
A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned.
Definition:
```c++
template<typename T> class Nan::Maybe {
public:
bool IsNothing() const;
bool IsJust() const;
// Will crash if the Maybe<> is nothing.
T FromJust();
T FromMaybe(const T& default_value);
bool operator==(const Maybe &other);
bool operator!=(const Maybe &other);
};
```
See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/io.js-3.0/d9/d4b/classv8_1_1_maybe.html) for further details.
<a name="api_nan_nothing"></a>
### Nan::Nothing
Construct an empty `Nan::Maybe` type representing _nothing_.
```c++
template<typename T> Nan::Maybe<T> Nan::Nothing();
```
<a name="api_nan_just"></a>
### Nan::Just
Construct a `Nan::Maybe` type representing _just_ a value.
```c++
template<typename T> Nan::Maybe<T> Nan::Just(const T &t);
```
<a name="api_nan_to_detail_string"></a>
### Nan::ToDetailString()
A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/io.js-3.0/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::ToDetailString(v8::Local<v8::Value> val);
```
<a name="api_nan_to_array_index"></a>
### Nan::ToArrayIndex()
A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/io.js-3.0/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Uint32> Nan::ToArrayIndex(v8::Local<v8::Value> val);
```
<a name="api_nan_equals"></a>
### Nan::Equals()
A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/io.js-3.0/dc/d0a/classv8_1_1_value.html#a0d9616ab2de899d4e3047c30a10c9285) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b));
```
<a name="api_nan_new_instance"></a>
### Nan::NewInstance()
A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/io.js-3.0/d5/d54/classv8_1_1_function.html#a691b13f7a553069732cbacf5ac8c62ec) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/io.js-3.0/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h);
Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h, int argc, v8::Local<v8::Value> argv[]);
Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::ObjectTemplate> h);
```
<a name="api_nan_get_function"></a>
### Nan::GetFunction()
A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/io.js-3.0/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Function> Nan::GetFunction(v8::Local<v8::FunctionTemplate> t);
```
<a name="api_nan_set"></a>
### Nan::Set()
A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
v8::Local<v8::Value> key,
v8::Local<v8::Value> value)
Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
uint32_t index,
v8::Local<v8::Value> value);
```
<a name="api_nan_force_set"></a>
### Nan::ForceSet()
A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a796b7b682896fb64bf1872747734e836) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object> obj,
v8::Local<v8::Value> key,
v8::Local<v8::Value> value,
v8::PropertyAttribute attribs = v8::None);
```
<a name="api_nan_get"></a>
### Nan::Get()
A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj,
v8::Local<v8::Value> key);
Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, uint32_t index);
```
<a name="api_nan_get_property_attribute"></a>
### Nan::GetPropertyAttributes()
A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<v8::PropertyAttribute> Nan::GetPropertyAttributes(
v8::Local<v8::Object> obj,
v8::Local<v8::Value> key);
```
<a name="api_nan_has"></a>
### Nan::Has()
A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, v8::Local<v8::String> key);
Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, uint32_t index);
```
<a name="api_nan_delete"></a>
### Nan::Delete()
A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a2fa0f5a592582434ed1ceceff7d891ef) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, uint32_t index);
```
<a name="api_nan_get_property_names"></a>
### Nan::GetPropertyNames()
A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Array> Nan::GetPropertyNames(v8::Local<v8::Object> obj);
```
<a name="api_nan_get_own_property_names"></a>
### Nan::GetOwnPropertyNames()
A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Array> Nan::GetOwnPropertyNames(v8::Local<v8::Object> obj);
```
<a name="api_nan_set_prototype"></a>
### Nan::SetPrototype()
A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::SetPrototype(v8::Local<v8::Object> obj,
v8::Local<v8::Value> prototype);
```
<a name="api_nan_object_proto_to_string"></a>
### Nan::ObjectProtoToString()
A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::ObjectProtoToString(v8::Local<v8::Object> obj);
```
<a name="api_nan_has_own_property"></a>
### Nan::HasOwnProperty()
A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasOwnProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_has_real_named_property"></a>
### Nan::HasRealNamedProperty()
A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasRealNamedProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_has_real_indexed_property"></a>
### Nan::HasRealIndexedProperty()
A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasRealIndexedProperty(v8::Local<v8::Object> obj,
uint32_t index);
```
<a name="api_nan_has_real_named_callback_property"></a>
### Nan::HasRealNamedCallbackProperty()
A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasRealNamedCallbackProperty(
v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_get_real_named_property_in_prototype_chain"></a>
### Nan::GetRealNamedPropertyInPrototypeChain()
A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::GetRealNamedPropertyInPrototypeChain(
v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_get_real_named_property"></a>
### Nan::GetRealNamedProperty()
A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::GetRealNamedProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_call_as_function"></a>
### Nan::CallAsFunction()
A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a9ef18be634e79b4f0cdffa1667a29f58) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::CallAsFunction(v8::Local<v8::Object> obj,
v8::Local<v8::Object> recv,
int argc,
v8::Local<v8::Value> argv[]);
```
<a name="api_nan_call_as_constructor"></a>
### Nan::CallAsConstructor()
A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::CallAsConstructor(v8::Local<v8::Object> obj,
int argc,
v8::Local<v8::Value> argv[]);
```
<a name="api_nan_get_source_line"></a>
### Nan::GetSourceLine()
A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/io.js-3.0/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::GetSourceLine(v8::Local<v8::Message> msg);
```
<a name="api_nan_get_line_number"></a>
### Nan::GetLineNumber()
A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/io.js-3.0/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<int> Nan::GetLineNumber(v8::Local<v8::Message> msg);
```
<a name="api_nan_get_start_column"></a>
### Nan::GetStartColumn()
A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/io.js-3.0/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<int> Nan::GetStartColumn(v8::Local<v8::Message> msg);
```
<a name="api_nan_get_end_column"></a>
### Nan::GetEndColumn()
A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/io.js-3.0/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<int> Nan::GetEndColumn(v8::Local<v8::Message> msg);
```
<a name="api_nan_clone_element_at"></a>
### Nan::CloneElementAt()
A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/io.js-3.0/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array> array, uint32_t index);
```

View File

@@ -0,0 +1,624 @@
## JavaScript-accessible methods
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information.
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
* **Method argument types**
- <a href="#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
- <a href="#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
- <a href="#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
* **Method declarations**
- <a href="#api_nan_method"><b>Method declaration</b></a>
- <a href="#api_nan_getter"><b>Getter declaration</b></a>
- <a href="#api_nan_setter"><b>Setter declaration</b></a>
- <a href="#api_nan_property_getter"><b>Property getter declaration</b></a>
- <a href="#api_nan_property_setter"><b>Property setter declaration</b></a>
- <a href="#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
- <a href="#api_nan_property_deleter"><b>Property deleter declaration</b></a>
- <a href="#api_nan_property_query"><b>Property query declaration</b></a>
- <a href="#api_nan_index_getter"><b>Index getter declaration</b></a>
- <a href="#api_nan_index_setter"><b>Index setter declaration</b></a>
- <a href="#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
- <a href="#api_nan_index_deleter"><b>Index deleter declaration</b></a>
- <a href="#api_nan_index_query"><b>Index query declaration</b></a>
* Method and template helpers
- <a href="#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
- <a href="#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
- <a href="#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
- <a href="#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
- <a href="#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
- <a href="#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
- <a href="#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
<a name="api_nan_function_callback_info"></a>
### Nan::FunctionCallbackInfo
`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/io.js-3.0/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist.
Definition:
```c++
template<typename T> class FunctionCallbackInfo {
public:
ReturnValue<T> GetReturnValue() const;
v8::Local<v8::Function> Callee();
v8::Local<v8::Value> Data();
v8::Local<v8::Object> Holder();
bool IsConstructCall();
int Length() const;
v8::Local<v8::Value> operator[](int i) const;
v8::Local<v8::Object> This() const;
v8::Isolate *GetIsolate() const;
};
```
See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/io.js-3.0/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods.
<a name="api_nan_property_callback_info"></a>
### Nan::PropertyCallbackInfo
`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/io.js-3.0/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist.
Definition:
```c++
template<typename T> class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
public:
ReturnValue<T> GetReturnValue() const;
v8::Isolate* GetIsolate() const;
v8::Local<v8::Value> Data() const;
v8::Local<v8::Object> This() const;
v8::Local<v8::Object> Holder() const;
};
```
See the [`v8::PropertyCallbackInfo](https://v8docs.nodesource.com/io.js-3.0/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods.
<a name="api_nan_return_value"></a>
### Nan::ReturnValue
`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/io.js-3.0/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`.
Example usage:
```c++
void EmptyArray(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(Nan::New<v8::Array>());
}
```
Definition:
```c++
template<typename T> class ReturnValue {
public:
// Handle setters
template <typename S> void Set(const v8::Local<S> &handle);
template <typename S> void Set(const Nan::Global<S> &handle);
// Fast primitive setters
void Set(bool value);
void Set(double i);
void Set(int32_t i);
void Set(uint32_t i);
// Fast JS primitive setters
void SetNull();
void SetUndefined();
void SetEmptyString();
// Convenience getter for isolate
v8::Isolate *GetIsolate() const;
};
```
See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/io.js-3.0/da/da7/classv8_1_1_return_value.html) for further information on this.
<a name="api_nan_method"></a>
### Method declaration
JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`:
```c++
typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
```
Example:
```c++
void MethodName(const Nan::FunctionCallbackInfo<v8::Value>& info) {
...
}
You do not need to declare a new `HandleScope` within a method as one is implicitly created for you.
**Example usage**
```c++
// .h:
class Foo : public Nan::ObjectWrap {
...
static void Bar(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void Baz(const Nan::FunctionCallbackInfo<v8::Value>& info);
}
// .cc:
void Foo::Bar(const Nan::FunctionCallbackInfo<v8::Value>& info) {
...
}
void Foo::Baz(const Nan::FunctionCallbackInfo<v8::Value>& info) {
...
}
```
A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations.
**Example usage with `NAN_METHOD(methodname)`**
```c++
// .h:
class Foo : public Nan::ObjectWrap {
...
static NAN_METHOD(Bar);
static NAN_METHOD(Baz);
}
// .cc:
NAN_METHOD(Foo::Bar) {
...
}
NAN_METHOD(Foo::Baz) {
...
}
```
Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object.
<a name="api_nan_getter"></a>
### Getter declaration
JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`:
```c++
typedef void(*GetterCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void GetterName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you.
A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
<a name="api_nan_setter"></a>
### Setter declaration
JavaScript-accessible setters should be declared with the following signature to form a <b><code>Nan::SetterCallback</code></b>:
```c++
typedef void(*SetterCallback)(v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<void>&);
```
Example:
```c++
void SetterName(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const Nan::PropertyCallbackInfo<v8::Value>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you.
A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
<a name="api_nan_property_getter"></a>
### Property getter declaration
JavaScript-accessible property getters should be declared with the following signature to form a <b><code>Nan::PropertyGetterCallback</code></b>:
```c++
typedef void(*PropertyGetterCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void PropertyGetterName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you.
A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_setter"></a>
### Property setter declaration
JavaScript-accessible property setters should be declared with the following signature to form a <b><code>Nan::PropertySetterCallback</code></b>:
```c++
typedef void(*PropertySetterCallback)(v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void PropertySetterName(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const Nan::PropertyCallbackInfo<v8::Value>& info);
```
You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you.
A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_enumerator"></a>
### Property enumerator declaration
JavaScript-accessible property enumerators should be declared with the following signature to form a <b><code>Nan::PropertyEnumeratorCallback</code></b>:
```c++
typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
```
Example:
```c++
void PropertyEnumeratorName(const Nan::PropertyCallbackInfo<v8::Array>& info);
```
You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you.
A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_deleter"></a>
### Property deleter declaration
JavaScript-accessible property deleters should be declared with the following signature to form a <b><code>Nan::PropertyDeleterCallback</code></b>:
```c++
typedef void(*PropertyDeleterCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Boolean>&);
```
Example:
```c++
void PropertyDeleterName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Boolean>& info);
```
You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you.
A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_query"></a>
### Property query declaration
JavaScript-accessible property query methods should be declared with the following signature to form a <b><code>Nan::PropertyQueryCallback</code></b>:
```c++
typedef void(*PropertyQueryCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Integer>&);
```
Example:
```c++
void PropertyQueryName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Integer>& info);
```
You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you.
A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_getter"></a>
### Index getter declaration
JavaScript-accessible index getter methods should be declared with the following signature to form a <b><code>Nan::IndexGetterCallback</code></b>:
```c++
typedef void(*IndexGetterCallback)(uint32_t,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void IndexGetterName(uint32_t index, const PropertyCallbackInfo<v8::Value>& info);
```
You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you.
A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_setter"></a>
### Index setter declaration
JavaScript-accessible index setter methods should be declared with the following signature to form a <b><code>Nan::IndexSetterCallback</code></b>:
```c++
typedef void(*IndexSetterCallback)(uint32_t,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void IndexSetterName(uint32_t index,
v8::Local<v8::Value> value,
const PropertyCallbackInfo<v8::Value>& info);
```
You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you.
A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_enumerator"></a>
### Index enumerator declaration
JavaScript-accessible index enumerator methods should be declared with the following signature to form a <b><code>Nan::IndexEnumeratorCallback</code></b>:
```c++
typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
```
Example:
```c++
void IndexEnumeratorName(const PropertyCallbackInfo<v8::Array>& info);
```
You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you.
A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_deleter"></a>
### Index deleter declaration
JavaScript-accessible index deleter methods should be declared with the following signature to form a <b><code>Nan::IndexDeleterCallback</code></b>:
```c++
typedef void(*IndexDeleterCallback)(uint32_t,
const PropertyCallbackInfo<v8::Boolean>&);
```
Example:
```c++
void IndexDeleterName(uint32_t index, const PropertyCallbackInfo<v8::Boolean>& info);
```
You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you.
A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_query"></a>
### Index query declaration
JavaScript-accessible index query methods should be declared with the following signature to form a <b><code>Nan::IndexQueryCallback</code></b>:
```c++
typedef void(*IndexQueryCallback)(uint32_t,
const PropertyCallbackInfo<v8::Integer>&);
```
Example:
```c++
void IndexQueryName(uint32_t index, const PropertyCallbackInfo<v8::Integer>& info);
```
You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you.
A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_set_method"></a>
### Nan::SetMethod()
Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
Signature:
```c++
template<typename T> void Nan::SetMethod(const T &recv,
const char *name,
Nan::FunctionCallback callback)
```
<a name="api_nan_set_prototype_method"></a>
### Nan::SetPrototypeMethod()
Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
Signature:
```c++
void Nan::SetPrototypeMethod(v8::Local<v8::FunctionTemplate> recv,
const char* name,
Nan::FunctionCallback callback)
```
<a name="api_nan_set_accessor"></a>
### Nan::SetAccessor()
Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see <a href="#api_nan_getter">Getter declaration</a>) and setters with the `Nan::SetterCallback` signature (see <a href="#api_nan_setter">Setter declaration</a>).
Signature:
```c++
void SetAccessor(v8::Local<v8::ObjectTemplate> tpl,
v8::Local<v8::String> name,
Nan::GetterCallback getter,
Nan::SetterCallback setter = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
v8::AccessControl settings = v8::DEFAULT,
v8::PropertyAttribute attribute = v8::None,
imp::Sig signature = imp::Sig())
bool SetAccessor(v8::Local<v8::Object> obj,
v8::Local<v8::String> name,
Nan::GetterCallback getter,
Nan::SetterCallback setter = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
v8::AccessControl settings = v8::DEFAULT,
v8::PropertyAttribute attribute = v8::None)
```
See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/io.js-3.0/db/d5f/classv8_1_1_object_template.html#aa90691622f01269c6a11391d372ca0c5) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#a3f9dee085f5ec346465f1dc924325043) for further information about how to use `Nan::SetAccessor()`.
<a name="api_nan_set_named_property_handler"></a>
### Nan::SetNamedPropertyHandler()
Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
* Property getters with the `Nan::PropertyGetterCallback` signature (see <a href="#api_nan_property_getter">Property getter declaration</a>)
* Property setters with the `Nan::PropertySetterCallback` signature (see <a href="#api_nan_property_setter">Property setter declaration</a>)
* Property query methods with the `Nan::PropertyQueryCallback` signature (see <a href="#api_nan_property_query">Property query declaration</a>)
* Property deleters with the `Nan::PropertyDeleterCallback` signature (see <a href="#api_nan_property_deleter">Property deleter declaration</a>)
* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see <a href="#api_nan_property_enumerator">Property enumerator declaration</a>)
Signature:
```c++
void SetNamedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
Nan::PropertyGetterCallback getter,
Nan::PropertySetterCallback setter = 0,
Nan::PropertyQueryCallback query = 0,
Nan::PropertyDeleterCallback deleter = 0,
Nan::PropertyEnumeratorCallback enumerator = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/io.js-3.0/db/d5f/classv8_1_1_object_template.html#a34d1cc45b642cd131706663801aadd76) for further information about how to use `Nan::SetNamedPropertyHandler()`.
<a name="api_nan_set_indexed_property_handler"></a>
### Nan::SetIndexedPropertyHandler()
Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
* Indexed property getters with the `Nan::IndexGetterCallback` signature (see <a href="#api_nan_index_getter">Index getter declaration</a>)
* Indexed property setters with the `Nan::IndexSetterCallback` signature (see <a href="#api_nan_index_setter">Index setter declaration</a>)
* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see <a href="#api_nan_index_query">Index query declaration</a>)
* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see <a href="#api_nan_index_deleter">Index deleter declaration</a>)
* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see <a href="#api_nan_index_enumerator">Index enumerator declaration</a>)
Signature:
```c++
void SetIndexedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
Nan::IndexGetterCallback getter,
Nan::IndexSetterCallback setter = 0,
Nan::IndexQueryCallback query = 0,
Nan::IndexDeleterCallback deleter = 0,
Nan::IndexEnumeratorCallback enumerator = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/io.js-3.0/db/d5f/classv8_1_1_object_template.html#ac0234cbede45d51778bb5f6a32a9e125) for further information about how to use `Nan::SetIndexedPropertyHandler()`.
<a name="api_nan_set_template"></a>
### Nan::SetTemplate()
Adds properties on an `Object`'s or `Function`'s template.
Signature:
```c++
void Nan::SetTemplate(v8::Local<v8::Template> templ,
const char *name,
v8::Local<v8::Data> value)
void Nan::SetTemplate(v8::Local<v8::Template> templ,
v8::Local<v8::String> name,
v8::Local<v8::Data> value,
v8::PropertyAttribute attributes)
```
Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/io.js-3.0/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
<a name="api_nan_set_prototype_template"></a>
### Nan::SetPrototypeTemplate()
Adds properties on an `Object`'s or `Function`'s prototype template.
Signature:
```c++
void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
const char *name,
v8::Local<v8::Data> value)
void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
v8::Local<v8::String> name,
v8::Local<v8::Data> value,
v8::PropertyAttribute attributes)
```
Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/io.js-3.0/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
<a name="api_nan_set_instance_template"></a>
### Nan::SetInstanceTemplate()
Use to add instance properties on `FunctionTemplate`'s.
Signature:
```c++
void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
const char *name,
v8::Local<v8::Data> value)
void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
v8::Local<v8::String> name,
v8::Local<v8::Data> value,
v8::PropertyAttribute attributes)
```
Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/io.js-3.0/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).

View File

@@ -0,0 +1,141 @@
## New
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
- <a href="#api_nan_new"><b><code>Nan::New()</code></b></a>
- <a href="#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
- <a href="#api_nan_null"><b><code>Nan::Null()</code></b></a>
- <a href="#api_nan_true"><b><code>Nan::True()</code></b></a>
- <a href="#api_nan_false"><b><code>Nan::False()</code></b></a>
- <a href="#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
<a name="api_nan_new"></a>
### Nan::New()
`Nan::New()` should be used to instantiate new JavaScript objects.
Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/io.js-3.0/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation.
Signatures:
Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local<T>`. The following types will be contained within a `Nan::MaybeLocal<T>`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`.
Empty objects:
```c++
Nan::New<T>();
```
Generic single and multiple-argument:
```c++
Nan::New<T>(A0 arg0);
Nan::New<T>(A0 arg0, A1 arg1);
Nan::New<T>(A0 arg0, A1 arg1, A2 arg2);
Nan::New<T>(A0 arg0, A1 arg1, A2 arg2, A3 arg3);
```
For creating `v8::FunctionTemplate` and `v8::Function` objects:
_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._
```c++
Nan::New<T>(Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
Nan::New<T>(Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
A2 a2 = A2());
```
Native types:
```c++
v8::Local<v8::Boolean> Nan::New<T>(bool value);
v8::Local<v8::Int32> Nan::New<T>(int32_t value);
v8::Local<v8::Uint32> Nan::New<T>(uint32_t value);
v8::Local<v8::Number> Nan::New<T>(double value);
v8::Local<v8::String> Nan::New<T>(std::string const& value);
v8::Local<v8::String> Nan::New<T>(const char * value, int length);
v8::Local<v8::String> Nan::New<T>(const char * value);
v8::Local<v8::String> Nan::New<T>(const uint16_t * value);
```
Specialized types:
```c++
v8::Local<v8::String> Nan::New<T>(v8::String::ExternalStringResource * value);
v8::Local<v8::String> Nan::New<T>(Nan::ExternalOneByteStringResource * value);
v8::Local<v8::RegExp> Nan::New<T>(v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
```
Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/io.js-3.0/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8.
<a name="api_nan_undefined"></a>
### Nan::Undefined()
A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Primitive> Nan::Undefined()
```
<a name="api_nan_null"></a>
### Nan::Null()
A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Primitive> Nan::Null()
```
<a name="api_nan_true"></a>
### Nan::True()
A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Boolean> Nan::True()
```
<a name="api_nan_false"></a>
### Nan::False()
A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Boolean> Nan::False()
```
<a name="api_nan_empty_string"></a>
### Nan::EmptyString()
Call [`v8::String::Empty`](https://v8docs.nodesource.com/io.js-3.0/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::String> Nan::EmptyString()
```
<a name="api_nan_new_one_byte_string"></a>
### Nan::NewOneByteString()
An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/io.js-3.0/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::NewOneByteString(const uint8_t * value,
int length = -1)
```

View File

@@ -0,0 +1,114 @@
## Miscellaneous Node Helpers
- <a href="#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
- <a href="#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
- <a href="#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
- <a href="#api_nan_export"><b><code>Nan::Export()</code></b></a>
<a name="api_nan_make_callback"></a>
### Nan::MakeCallback()
Wrappers around `node::MakeCallback()` providing a consistent API across all supported versions of Node.
Use `MakeCallback()` rather than using `v8::Function#Call()` directly in order to properly process internal Node functionality including domains, async hooks, the microtask queue, and other debugging functionality.
Signatures:
```c++
v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
v8::Local<v8::Function> func,
int argc,
v8::Local<v8::Value>* argv);
v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
v8::Local<v8::String> symbol,
int argc,
v8::Local<v8::Value>* argv);
v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
const char* method,
int argc,
v8::Local<v8::Value>* argv);
```
<a name="api_nan_object_wrap"></a>
### Nan::ObjectWrap()
A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency.
See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details.
Definition:
```c++
class ObjectWrap {
public:
ObjectWrap();
virtual ~ObjectWrap();
template <class T>
static inline T* Unwrap(v8::Local<v8::Object> handle);
inline v8::Local<v8::Object> handle();
inline Nan::Persistent<v8::Object>& persistent();
protected:
inline void Wrap(v8::Local<v8::Object> handle);
inline void MakeWeak();
/* Ref() marks the object as being attached to an event loop.
* Refed objects will not be garbage collected, even if
* all references are lost.
*/
virtual void Ref();
/* Unref() marks an object as detached from the event loop. This is its
* default state. When an object with a "weak" reference changes from
* attached to detached state it will be freed. Be careful not to access
* the object after making this call as it might be gone!
* (A "weak reference" means an object that only has a
* persistant handle.)
*
* DO NOT CALL THIS FROM DESTRUCTOR
*/
virtual void Unref();
int refs_; // ro
};
```
<a name="api_nan_module_init"></a>
### NAN_MODULE_INIT()
Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object.
See example below.
<a name="api_nan_export"></a>
### Nan::Export()
A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript.
Signature:
```c++
void Export(v8::Local<v8::Object> target, const char *name, Nan::FunctionCallback f)
```
Also available as the shortcut `NAN_EXPORT` macro.
Example:
```c++
NAN_METHOD(Foo) {
...
}
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, Foo);
}
```

View File

@@ -0,0 +1,292 @@
## Persistent references
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
- <a href="#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
- <a href="#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
- <a href="#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
- <a href="#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
- <a href="#api_nan_global"><b><code>Nan::Global</code></b></a>
- <a href="#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
- <a href="#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
<a name="api_nan_persistent_base"></a>
### Nan::PersistentBase & v8::PersistentBase
A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`.
Definition:
_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_
```c++
template<typename T> class PersistentBase {
public:
/**
* If non-empty, destroy the underlying storage cell
*/
void Reset();
/**
* If non-empty, destroy the underlying storage cell and create a new one with
* the contents of another if it is also non-empty
*/
template<typename S> void Reset(const v8::Local<S> &other);
/**
* If non-empty, destroy the underlying storage cell and create a new one with
* the contents of another if it is also non-empty
*/
template<typename S> void Reset(const PersistentBase<S> &other);
/**
* If non-empty, destroy the underlying storage cell
* IsEmpty() will return true after this call.
*/
bool IsEmpty();
void Empty();
template<typename S> bool operator==(const PersistentBase<S> &that);
template<typename S> bool operator==(const v8::Local<S> &that);
template<typename S> bool operator!=(const PersistentBase<S> &that);
template<typename S> bool operator!=(const v8::Local<S> &that);
/**
* Install a finalization callback on this object.
* NOTE: There is no guarantee as to *when* or even *if* the callback is
* invoked. The invocation is performed solely on a best effort basis.
* As always, GC-based finalization should *not* be relied upon for any
* critical form of resource management! At the moment you can either
* specify a parameter for the callback or the location of two internal
* fields in the dying object.
*/
template<typename P>
void SetWeak(P *parameter,
typename WeakCallbackInfo<P>::Callback callback,
WeakCallbackType type);
void ClearWeak();
/**
* Marks the reference to this object independent. Garbage collector is free
* to ignore any object groups containing this object. Weak callback for an
* independent handle should not assume that it will be preceded by a global
* GC prologue callback or followed by a global GC epilogue callback.
*/
void MarkIndependent() const;
bool IsIndependent() const;
/** Checks if the handle holds the only reference to an object. */
bool IsNearDeath() const;
/** Returns true if the handle's reference is weak. */
bool IsWeak() const
};
```
See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/io.js-3.0/d4/dca/classv8_1_1_persistent_base.html) for further information.
<a name="api_nan_non_copyable_persistent_traits"></a>
### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits
Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version.
Definition:
_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
```c++
template<typename T> class NonCopyablePersistentTraits {
public:
typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
static const bool kResetInDestructor = false;
template<typename S, typename M>
static void Copy(const Persistent<S, M> &source,
NonCopyablePersistent *dest);
template<typename O> static void Uncompilable();
};
```
See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/io.js-3.0/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information.
<a name="api_nan_copyable_persistent_traits"></a>
### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits
A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc..
Definition:
_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
```c++
template<typename T>
class CopyablePersistentTraits {
public:
typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
static const bool kResetInDestructor = true;
template<typename S, typename M>
static void Copy(const Persistent<S, M> &source,
CopyablePersistent *dest);
};
```
See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/io.js-3.0/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information.
<a name="api_nan_persistent"></a>
### Nan::Persistent
A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`.
Definition:
```c++
template<typename T, typename M = NonCopyablePersistentTraits<T> >
class Persistent;
template<typename T, typename M> class Persistent : public PersistentBase<T> {
public:
/**
* A Persistent with no storage cell.
*/
Persistent();
/**
* Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a
* new storage cell is created pointing to the same object, and no flags are
* set.
*/
template<typename S> Persistent(v8::Local<S> that);
/**
* Construct a Persistent from a Persistent. When the Persistent is non-empty,
* a new storage cell is created pointing to the same object, and no flags are
* set.
*/
Persistent(const Persistent &that);
/**
* The copy constructors and assignment operator create a Persistent exactly
* as the Persistent constructor, but the Copy function from the traits class
* is called, allowing the setting of flags based on the copied Persistent.
*/
Persistent &operator=(const Persistent &that);
template <typename S, typename M2>
Persistent &operator=(const Persistent<S, M2> &that);
/**
* The destructor will dispose the Persistent based on the kResetInDestructor
* flags in the traits class. Since not calling dispose can result in a
* memory leak, it is recommended to always set this flag.
*/
~Persistent();
};
```
See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/io.js-3.0/d2/d78/classv8_1_1_persistent.html) for further information.
<a name="api_nan_global"></a>
### Nan::Global
A type of `PersistentBase` which has move semantics.
```c++
template<typename T> class Global : public PersistentBase<T> {
public:
/**
* A Global with no storage cell.
*/
Global();
/**
* Construct a Global from a v8::Local. When the v8::Local is non-empty, a new
* storage cell is created pointing to the same object, and no flags are set.
*/
template<typename S> Global(v8::Local<S> that);
/**
* Construct a Global from a PersistentBase. When the Persistent is non-empty,
* a new storage cell is created pointing to the same object, and no flags are
* set.
*/
template<typename S> Global(const PersistentBase<S> &that);
/**
* Pass allows returning globals from functions, etc.
*/
Global Pass();
};
```
See the V8 documentation for [`Global`](https://v8docs.nodesource.com/io.js-3.0/d5/d40/classv8_1_1_global.html) for further information.
<a name="api_nan_weak_callback_type"></a>
### Nan::WeakCallbackType
<a name="api_nan_weak_callback_info"></a>
### Nan::WeakCallbackInfo
`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8.
Definition:
```c++
template<typename T> class WeakCallbackInfo {
public:
typedef void (*Callback)(const WeakCallbackInfo<T>& data);
v8::Isolate *GetIsolate() const;
/**
* Get the parameter that was associated with the weak handle.
*/
T *GetParameter() const;
/**
* Get pointer from internal field, index can be 0 or 1.
*/
void *GetInternalField(int index) const;
};
```
Example usage:
```c++
void weakCallback(const WeakCallbackInfo<int> &data) {
int *parameter = data.GetParameter();
delete parameter;
}
Persistent<v8::Object> obj;
int *data = new int(0);
obj.SetWeak(data, callback, WeakCallbackType::kParameter);
```
See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/io.js-3.0/d8/d06/classv8_1_1_weak_callback_info.html) for further information.
<a name="api_nan_weak_callback_type"></a>
### Nan::WeakCallbackType
Represents the type of a weak callback.
A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`.
A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase<v8::Object>` being made weak.
Note that only `v8::Object`s and derivatives can have internal fields.
Definition:
```c++
enum class WeakCallbackType { kParameter, kInternalFields };
```

View File

@@ -0,0 +1,73 @@
## Scopes
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
- <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
- <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
<a name="api_nan_handle_scope"></a>
### Nan::HandleScope
A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/io.js-3.0/d3/d95/classv8_1_1_handle_scope.html).
Definition:
```c++
class Nan::HandleScope {
public:
Nan::HandleScope();
static int NumberOfHandles();
};
```
Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself.
Example:
```c++
// new object is created, it needs a new scope:
void Pointless() {
Nan::HandleScope scope;
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
}
// JavaScript-accessible method already has a HandleScope
NAN_METHOD(Pointless2) {
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
}
```
<a name="api_nan_escapable_handle_scope"></a>
### Nan::EscapableHandleScope
Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it.
Definition:
```c++
class Nan::EscapableHandleScope {
public:
Nan::EscapableHandleScope();
static int NumberOfHandles();
template<typename T> v8::Local<T> Escape(v8::Local<T> value);
}
```
Use `Escape(value)` to return the object.
Example:
```c++
v8::Local<v8::Object> EmptyObj() {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
return scope.Escape(obj);
}
```

View File

@@ -0,0 +1,38 @@
## Script
NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
- <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
- <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
<a name="api_nan_compile_script"></a>
### Nan::CompileScript()
A wrapper around [`v8::Script::Compile()`](https://v8docs.nodesource.com/io.js-3.0/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b).
Note that `Nan::BoundScript` is an alias for `v8::Script`.
Signature:
```c++
Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(
v8::Local<v8::String> s,
const v8::ScriptOrigin& origin);
Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s);
```
<a name="api_nan_run_script"></a>
### Nan::RunScript()
Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`.
Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script)
Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script)
```

View File

@@ -0,0 +1,62 @@
## Strings & Bytes
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
- <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
- <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
- <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
- <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
<a name="api_nan_encoding"></a>
### Nan::Encoding
An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node.
Definition:
```c++
enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER }
```
<a name="api_nan_encode"></a>
### Nan::Encode()
A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node.
Signature:
```c++
v8::Local<v8::Value> Nan::Encode(const void *buf,
size_t len,
enum Nan::Encoding encoding = BINARY);
```
<a name="api_nan_decode_bytes"></a>
### Nan::DecodeBytes()
A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node.
Signature:
```c++
ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val,
enum Nan::Encoding encoding = BINARY);
```
<a name="api_nan_decode_write"></a>
### Nan::DecodeWrite()
A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node.
Signature:
```c++
ssize_t Nan::DecodeWrite(char *buf,
size_t len,
v8::Local<v8::Value> val,
enum Nan::Encoding encoding = BINARY);
```

View File

@@ -0,0 +1,199 @@
## V8 internals
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
- <a href="#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
- <a href="#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
- <a href="#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
- <a href="#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
- <a href="#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
- <a href="#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
- <a href="#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
- <a href="#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
- <a href="#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
- <a href="#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
- <a href="#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
- <a href="#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
- <a href="#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
- <a href="#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
- <a href="#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
<a name="api_nan_gc_callback"></a>
### NAN_GC_CALLBACK(callbackname)
Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`.
```c++
static Nan::Persistent<Function> callback;
NAN_GC_CALLBACK(gcPrologueCallback) {
v8::Local<Value> argv[] = { Nan::New("prologue").ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv);
}
NAN_METHOD(Hook) {
callback.Reset(args[0].As<Function>());
Nan::AddGCPrologueCallback(gcPrologueCallback);
info.GetReturnValue().Set(info.Holder());
}
```
<a name="api_nan_add_gc_epilogue_callback"></a>
### Nan::AddGCEpilogueCallback()
Signature:
```c++
void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll)
```
Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a90d1860babc76059c62514b422f56960).
<a name="api_nan_remove_gc_epilogue_callback"></a>
### Nan::RemoveGCEpilogueCallback()
Signature:
```c++
void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback)
```
Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a05c60859fd4b8e96bfcd451281ed6c7c).
<a name="api_nan_add_gc_prologue_callback"></a>
### Nan::AddGCPrologueCallback()
Signature:
```c++
void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback)
```
Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#ab4b87b8f9f8e5bf95eba4009357e001f).
<a name="api_nan_remove_gc_prologue_callback"></a>
### Nan::RemoveGCPrologueCallback()
Signature:
```c++
void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback)
```
Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a9f6c51932811593f81ff30b949124186).
<a name="api_nan_get_heap_statistics"></a>
### Nan::GetHeapStatistics()
Signature:
```c++
void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics)
```
Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34).
<a name="api_nan_set_counter_function"></a>
### Nan::SetCounterFunction()
Signature:
```c++
void Nan::SetCounterFunction(v8::CounterLookupCallback cb)
```
Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94).
<a name="api_nan_set_create_histogram_function"></a>
### Nan::SetCreateHistogramFunction()
Signature:
```c++
void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb)
```
Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732).
<a name="api_nan_set_add_histogram_sample_function"></a>
### Nan::SetAddHistogramSampleFunction()
Signature:
```c++
void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb)
```
Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea).
<a name="api_nan_idle_notification"></a>
### Nan::IdleNotification()
Signature:
```c++
void Nan::IdleNotification(v8::HeapStatistics *heap_statistics)
```
Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version.
<a name="api_nan_low_memory_notification"></a>
### Nan::LowMemoryNotification()
Signature:
```c++
void Nan::LowMemoryNotification()
```
Calls V8's [`IdleNotification()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f).
<a name="api_nan_context_disposed_notification"></a>
### Nan::ContextDisposedNotification()
Signature:
```c++
void Nan::ContextDisposedNotification()
```
Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b).
<a name="api_nan_get_internal_field_pointer"></a>
### Nan::GetInternalFieldPointer()
Gets a pointer to the internal field with at `index` from a V8 `Object` handle.
Signature:
```c++
void* Nan::GetInternalFieldPointer(v8::Local<v8::Object> object, int index)
```
Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/io.js-3.0/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8.
<a name="api_nan_set_internal_field_pointer"></a>
### Nan::SetInternalFieldPointer()
Sets the value of the internal field at `index` on a V8 `Object` handle.
Signature:
```c++
void Nan::SetInternalFieldPointer(v8::Local<v8::Object> object, int index, void* value)
```
Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b) depending on the version of V8.
<a name="api_nan_adjust_external_memory"></a>
### Nan::AdjustExternalMemory()
Signature:
```c++
int Nan::AdjustExternalMemory(int bytesChange)
```
Calls V8's [`AdjustAmountOfExternalAllocatedMemory()` or `AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e) depending on the version of V8.

View File

@@ -0,0 +1,63 @@
## Miscellaneous V8 Helpers
- <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
- <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
- <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
- <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
<a name="api_nan_utf8_string"></a>
### Nan::Utf8String
Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object.
An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/io.js-3.0/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8.
Definition:
```c++
class Nan::Utf8String {
public:
Nan::Utf8String(v8::Local<v8::Value> from);
int length() const;
char* operator*();
const char* operator*() const;
};
```
<a name="api_nan_get_current_context"></a>
### Nan::GetCurrentContext()
A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Context> Nan::GetCurrentContext()
```
<a name="api_nan_set_isolate_data"></a>
### Nan::SetIsolateData()
A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36).
Signature:
```c++
void Nan::SetIsolateData(v8::Isolate *isolate, T *data)
```
<a name="api_nan_get_isolate_data"></a>
### Nan::GetIsolateData()
A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/io.js-3.0/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257).
Signature:
```c++
T *Nan::GetIsolateData(v8::Isolate *isolate)
```

View File

@@ -0,0 +1 @@
console.log(require('path').relative('.', __dirname));

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_H_
#define NAN_CALLBACKS_H_
template<typename T> class FunctionCallbackInfo;
template<typename T> class PropertyCallbackInfo;
template<typename T> class Global;
typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
typedef void(*GetterCallback)
(v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&);
typedef void(*SetterCallback)(
v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<void>&);
typedef void(*PropertyGetterCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*PropertySetterCallback)(
v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*PropertyEnumeratorCallback)
(const PropertyCallbackInfo<v8::Array>&);
typedef void(*PropertyDeleterCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Boolean>&);
typedef void(*PropertyQueryCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Integer>&);
typedef void(*IndexGetterCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*IndexSetterCallback)(
uint32_t,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*IndexEnumeratorCallback)
(const PropertyCallbackInfo<v8::Array>&);
typedef void(*IndexDeleterCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Boolean>&);
typedef void(*IndexQueryCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Integer>&);
namespace imp {
typedef v8::Local<v8::AccessorSignature> Sig;
static const int kDataIndex = 0;
static const int kFunctionIndex = 1;
static const int kFunctionFieldCount = 2;
static const int kGetterIndex = 1;
static const int kSetterIndex = 2;
static const int kAccessorFieldCount = 3;
static const int kPropertyGetterIndex = 1;
static const int kPropertySetterIndex = 2;
static const int kPropertyEnumeratorIndex = 3;
static const int kPropertyDeleterIndex = 4;
static const int kPropertyQueryIndex = 5;
static const int kPropertyFieldCount = 6;
static const int kIndexPropertyGetterIndex = 1;
static const int kIndexPropertySetterIndex = 2;
static const int kIndexPropertyEnumeratorIndex = 3;
static const int kIndexPropertyDeleterIndex = 4;
static const int kIndexPropertyQueryIndex = 5;
static const int kIndexPropertyFieldCount = 6;
} // end of namespace imp
#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
# include "nan_callbacks_12_inl.h" // NOLINT(build/include)
#else
# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include)
#endif
#endif // NAN_CALLBACKS_H_

View File

@@ -0,0 +1,512 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_12_INL_H_
#define NAN_CALLBACKS_12_INL_H_
template<typename T>
class ReturnValue {
v8::ReturnValue<T> value_;
public:
template <class S>
explicit inline ReturnValue(const v8::ReturnValue<S> &value) :
value_(value) {}
template <class S>
explicit inline ReturnValue(const ReturnValue<S>& that)
: value_(that.value_) {
TYPE_CHECK(T, S);
}
// Handle setters
template <typename S> inline void Set(const v8::Local<S> &handle) {
TYPE_CHECK(T, S);
value_.Set(handle);
}
template <typename S> inline void Set(const Global<S> &handle) {
TYPE_CHECK(T, S);
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \
(V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \
defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8))))
value_.Set(handle);
#else
value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle));
const_cast<Global<S> &>(handle).Reset();
#endif
}
// Fast primitive setters
inline void Set(bool value) {
TYPE_CHECK(T, v8::Boolean);
value_.Set(value);
}
inline void Set(double i) {
TYPE_CHECK(T, v8::Number);
value_.Set(i);
}
inline void Set(int32_t i) {
TYPE_CHECK(T, v8::Integer);
value_.Set(i);
}
inline void Set(uint32_t i) {
TYPE_CHECK(T, v8::Integer);
value_.Set(i);
}
// Fast JS primitive setters
inline void SetNull() {
TYPE_CHECK(T, v8::Primitive);
value_.SetNull();
}
inline void SetUndefined() {
TYPE_CHECK(T, v8::Primitive);
value_.SetUndefined();
}
inline void SetEmptyString() {
TYPE_CHECK(T, v8::String);
value_.SetEmptyString();
}
// Convenience getter for isolate
inline v8::Isolate *GetIsolate() const {
return value_.GetIsolate();
}
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template<typename S>
inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
};
template<typename T>
class FunctionCallbackInfo {
const v8::FunctionCallbackInfo<T> &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline FunctionCallbackInfo(
const v8::FunctionCallbackInfo<T> &info
, v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(info_.GetReturnValue());
}
inline v8::Local<v8::Function> Callee() const { return info_.Callee(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
inline bool IsConstructCall() const { return info_.IsConstructCall(); }
inline int Length() const { return info_.Length(); }
inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kCalleeIndex = 5;
static const int kContextSaveIndex = 6;
static const int kArgsLength = 7;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
};
template<typename T>
class PropertyCallbackInfo {
const v8::PropertyCallbackInfo<T> &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline PropertyCallbackInfo(
const v8::PropertyCallbackInfo<T> &info
, const v8::Local<v8::Value> &data) :
info_(info)
, data_(data) {}
inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(info_.GetReturnValue());
}
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kThisIndex = 5;
static const int kArgsLength = 6;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo)
};
namespace imp {
static
void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
FunctionCallback callback = reinterpret_cast<FunctionCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
FunctionCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
callback(cbinfo);
}
typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &);
#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
static
void GetterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativeGetter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void SetterCallbackWrapper(
v8::Local<v8::Name> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<void> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property.As<v8::String>(), value, cbinfo);
}
typedef void (*NativeSetter)(
v8::Local<v8::Name>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<void> &);
#else
static
void GetterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativeGetter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void SetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<void> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativeSetter)(
v8::Local<v8::String>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<void> &);
#endif
#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
static
void PropertyGetterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativePropertyGetter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertySetterCallbackWrapper(
v8::Local<v8::Name> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), value, cbinfo);
}
typedef void (*NativePropertySetter)(
v8::Local<v8::Name>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertyEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativePropertyEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void PropertyDeleterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (NativePropertyDeleter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void PropertyQueryCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativePropertyQuery)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &);
#else
static
void PropertyGetterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativePropertyGetter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertySetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativePropertySetter)(
v8::Local<v8::String>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertyEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativePropertyEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void PropertyDeleterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (NativePropertyDeleter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void PropertyQueryCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativePropertyQuery)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &);
#endif
static
void IndexGetterCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexGetter)
(uint32_t, const v8::PropertyCallbackInfo<v8::Value> &);
static
void IndexSetterCallbackWrapper(
uint32_t index
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertySetterIndex)
.As<v8::External>()->Value()));
callback(index, value, cbinfo);
}
typedef void (*NativeIndexSetter)(
uint32_t
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void IndexEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(
kIndexPropertyEnumeratorIndex).As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativeIndexEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void IndexDeleterCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexDeleter)
(uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void IndexQueryCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexQuery)
(uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &);
} // end of namespace imp
#endif // NAN_CALLBACKS_12_INL_H_

View File

@@ -0,0 +1,506 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_PRE_12_INL_H_
#define NAN_CALLBACKS_PRE_12_INL_H_
namespace imp {
template<typename T> class ReturnValueImp;
} // end of namespace imp
template<typename T>
class ReturnValue {
v8::Isolate *isolate_;
v8::Persistent<T> *value_;
friend class imp::ReturnValueImp<T>;
public:
template <class S>
explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) :
isolate_(isolate), value_(p) {}
template <class S>
explicit inline ReturnValue(const ReturnValue<S>& that)
: isolate_(that.isolate_), value_(that.value_) {
TYPE_CHECK(T, S);
}
// Handle setters
template <typename S> inline void Set(const v8::Local<S> &handle) {
TYPE_CHECK(T, S);
value_->Dispose();
*value_ = v8::Persistent<T>::New(handle);
}
template <typename S> inline void Set(const Global<S> &handle) {
TYPE_CHECK(T, S);
value_->Dispose();
*value_ = v8::Persistent<T>::New(handle.persistent);
const_cast<Global<S> &>(handle).Reset();
}
// Fast primitive setters
inline void Set(bool value) {
TYPE_CHECK(T, v8::Boolean);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Boolean::New(value));
}
inline void Set(double i) {
TYPE_CHECK(T, v8::Number);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Number::New(i));
}
inline void Set(int32_t i) {
TYPE_CHECK(T, v8::Integer);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Int32::New(i));
}
inline void Set(uint32_t i) {
TYPE_CHECK(T, v8::Integer);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Uint32::New(i));
}
// Fast JS primitive setters
inline void SetNull() {
TYPE_CHECK(T, v8::Primitive);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Null());
}
inline void SetUndefined() {
TYPE_CHECK(T, v8::Primitive);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Undefined());
}
inline void SetEmptyString() {
TYPE_CHECK(T, v8::String);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::String::Empty());
}
// Convenience getter for isolate
inline v8::Isolate *GetIsolate() const {
return isolate_;
}
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template<typename S>
inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
};
template<typename T>
class FunctionCallbackInfo {
const v8::Arguments &args_;
v8::Local<v8::Value> data_;
ReturnValue<T> return_value_;
v8::Persistent<T> retval_;
public:
explicit inline FunctionCallbackInfo(
const v8::Arguments &args
, v8::Local<v8::Value> data) :
args_(args)
, data_(data)
, return_value_(args.GetIsolate(), &retval_)
, retval_(v8::Persistent<T>::New(v8::Undefined())) {}
inline ~FunctionCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(return_value_);
}
inline v8::Local<v8::Function> Callee() const { return args_.Callee(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> Holder() const { return args_.Holder(); }
inline bool IsConstructCall() const { return args_.IsConstructCall(); }
inline int Length() const { return args_.Length(); }
inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; }
inline v8::Local<v8::Object> This() const { return args_.This(); }
inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kCalleeIndex = 5;
static const int kContextSaveIndex = 6;
static const int kArgsLength = 7;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
};
template<typename T>
class PropertyCallbackInfoBase {
const v8::AccessorInfo &info_;
const v8::Local<v8::Value> &data_;
public:
explicit inline PropertyCallbackInfoBase(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> &data) :
info_(info)
, data_(data) {}
inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kThisIndex = 5;
static const int kArgsLength = 6;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase)
};
template<typename T>
class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
ReturnValue<T> return_value_;
v8::Persistent<T> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> &data) :
PropertyCallbackInfoBase<T>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<T>::New(v8::Undefined())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<T> GetReturnValue() const { return return_value_; }
};
template<>
class PropertyCallbackInfo<v8::Array> :
public PropertyCallbackInfoBase<v8::Array> {
ReturnValue<v8::Array> return_value_;
v8::Persistent<v8::Array> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> &data) :
PropertyCallbackInfoBase<v8::Array>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Array> GetReturnValue() const {
return return_value_;
}
};
template<>
class PropertyCallbackInfo<v8::Boolean> :
public PropertyCallbackInfoBase<v8::Boolean> {
ReturnValue<v8::Boolean> return_value_;
v8::Persistent<v8::Boolean> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> &data) :
PropertyCallbackInfoBase<v8::Boolean>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Boolean> GetReturnValue() const {
return return_value_;
}
};
template<>
class PropertyCallbackInfo<v8::Integer> :
public PropertyCallbackInfoBase<v8::Integer> {
ReturnValue<v8::Integer> return_value_;
v8::Persistent<v8::Integer> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> &data) :
PropertyCallbackInfoBase<v8::Integer>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Integer> GetReturnValue() const {
return return_value_;
}
};
namespace imp {
template<typename T>
class ReturnValueImp : public ReturnValue<T> {
public:
explicit ReturnValueImp(ReturnValue<T> that) :
ReturnValue<T>(that) {}
NAN_INLINE v8::Handle<T> Value() {
return *ReturnValue<T>::value_;
}
};
static
v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) {
v8::Local<v8::Object> obj = args.Data().As<v8::Object>();
FunctionCallback callback = reinterpret_cast<FunctionCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
FunctionCallbackInfo<v8::Value>
cbinfo(args, obj->GetInternalField(kDataIndex));
callback(cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &);
static
v8::Handle<v8::Value> GetterCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeGetter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
void SetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativeSetter)
(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> PropertyGetterCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativePropertyGetter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> PropertySetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property, value, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativePropertySetter)
(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper(
const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Array> (*NativePropertyEnumerator)
(const v8::AccessorInfo &);
static
v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper(
v8::Local<v8::String> property
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Boolean> (NativePropertyDeleter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Integer> PropertyQueryCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Integer> (*NativePropertyQuery)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> IndexGetterCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeIndexGetter)
(uint32_t, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> IndexSetterCallbackWrapper(
uint32_t index
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertySetterIndex)
.As<v8::External>()->Value()));
callback(index, value, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeIndexSetter)
(uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper(
const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Array> (*NativeIndexEnumerator)
(const v8::AccessorInfo &);
static
v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter)
(uint32_t, const v8::AccessorInfo &);
static
v8::Handle<v8::Integer> IndexQueryCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Integer> (*NativeIndexQuery)
(uint32_t, const v8::AccessorInfo &);
} // end of namespace imp
#endif // NAN_CALLBACKS_PRE_12_INL_H_

View File

@@ -0,0 +1,64 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_H_
#define NAN_CONVERTERS_H_
namespace imp {
template<typename T> struct ToFactoryBase {
typedef MaybeLocal<T> return_t;
};
template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; };
template<typename T> struct ToFactory;
#define X(TYPE) \
template<> \
struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> { \
static inline return_t convert(v8::Local<v8::Value> val); \
};
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE) \
template<> \
struct ToFactory<TYPE> : ValueFactoryBase<TYPE> { \
static inline return_t convert(v8::Local<v8::Value> val); \
};
X(bool)
X(double)
X(int64_t)
X(uint32_t)
X(int32_t)
#undef X
} // end of namespace imp
template<typename T>
NAN_INLINE
typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) {
return imp::ToFactory<T>::convert(val);
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
# include "nan_converters_43_inl.h"
#else
# include "nan_converters_pre_43_inl.h"
#endif
#endif // NAN_CONVERTERS_H_

View File

@@ -0,0 +1,42 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_43_INL_H_
#define NAN_CONVERTERS_43_INL_H_
#define X(TYPE) \
imp::ToFactory<v8::TYPE>::return_t \
imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \
return val->To ## TYPE(GetCurrentContext()); \
}
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE, NAME) \
imp::ToFactory<TYPE>::return_t \
imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \
return val->NAME ## Value(GetCurrentContext()); \
}
X(bool, Boolean)
X(double, Number)
X(int64_t, Integer)
X(uint32_t, Uint32)
X(int32_t, Int32)
#undef X
#endif // NAN_CONVERTERS_43_INL_H_

View File

@@ -0,0 +1,42 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_PRE_43_INL_H_
#define NAN_CONVERTERS_PRE_43_INL_H_
#define X(TYPE) \
imp::ToFactory<v8::TYPE>::return_t \
imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \
return MaybeLocal<v8::TYPE>(val->To ## TYPE()); \
}
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE, NAME) \
imp::ToFactory<TYPE>::return_t \
imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \
return Just<TYPE>(val->NAME ##Value()); \
}
X(bool, Boolean)
X(double, Number)
X(int64_t, Integer)
X(uint32_t, Uint32)
X(int32_t, Int32)
#undef X
#endif // NAN_CONVERTERS_PRE_43_INL_H_

View File

@@ -0,0 +1,399 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_12_INL_H_
#define NAN_IMPLEMENTATION_12_INL_H_
//==============================================================================
// node v0.11 implementation
//==============================================================================
namespace imp {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New(v8::Isolate::GetCurrent());
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(v8::Isolate::GetCurrent(), length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Local<v8::ObjectTemplate> tmpl
, v8::Local<v8::Value> obj) {
return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj);
}
//=== Date =====================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
v8::Local<v8::Date> ret;
if (v8::Date::New(GetCurrentContext(), value).
ToLocal(reinterpret_cast<v8::Local<v8::Value>*>(&ret))) {
return v8::MaybeLocal<v8::Date>(ret);
} else {
return v8::MaybeLocal<v8::Date>(ret);
}
}
#else
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return Factory<v8::Date>::return_t(
v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>());
}
#endif
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(v8::Isolate::GetCurrent(), value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( FunctionCallback callback
, v8::Local<v8::Value> data) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(isolate, reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
return scope.Escape(v8::Function::New( isolate
, imp::FunctionCallbackWrapper
, obj));
}
//=== Function Template ========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( FunctionCallback callback
, v8::Local<v8::Value> data
, v8::Local<v8::Signature> signature) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
if (callback) {
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(isolate, reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
return scope.Escape(v8::FunctionTemplate::New( isolate
, imp::FunctionCallbackWrapper
, obj
, signature));
} else {
return v8::FunctionTemplate::New(isolate, 0, data, signature);
}
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(v8::Isolate::GetCurrent(), value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New( v8::Isolate::GetCurrent()
, value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(v8::Isolate::GetCurrent(), value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New(v8::Isolate::GetCurrent());
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New(v8::Isolate::GetCurrent());
}
//=== RegExp ===================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return v8::RegExp::New(GetCurrentContext(), pattern, flags);
}
#else
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return Factory<v8::RegExp>::return_t(v8::RegExp::New(pattern, flags));
}
#endif
//=== Script ===================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::Compile(GetCurrentContext(), &src);
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::Compile(GetCurrentContext(), &src);
}
#else
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return Factory<v8::Script>::return_t(
v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src));
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return Factory<v8::Script>::return_t(
v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src));
}
#endif
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
return v8::Signature::New(v8::Isolate::GetCurrent(), receiver);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return Factory<v8::String>::return_t(
v8::String::Empty(v8::Isolate::GetCurrent()));
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return v8::String::NewFromUtf8(
v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(std::string const& value) {
assert(value.size() <= INT_MAX && "string too long");
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size()));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
v8::NewStringType::kNormal, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(ExternalOneByteStringResource * value) {
return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value);
}
#else
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return Factory<v8::String>::return_t(
v8::String::NewFromUtf8(
v8::Isolate::GetCurrent()
, value
, v8::String::kNormalString
, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(
std::string const& value) /* NOLINT(build/include_what_you_use) */ {
assert(value.size() <= INT_MAX && "string too long");
return Factory<v8::String>::return_t(
v8::String::NewFromUtf8(
v8::Isolate::GetCurrent()
, value.data()
, v8::String::kNormalString
, static_cast<int>(value.size())));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return Factory<v8::String>::return_t(
v8::String::NewFromTwoByte(
v8::Isolate::GetCurrent()
, value
, v8::String::kNormalString
, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return Factory<v8::String>::return_t(
v8::String::NewExternal(v8::Isolate::GetCurrent(), value));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(ExternalOneByteStringResource * value) {
return Factory<v8::String>::return_t(
v8::String::NewExternal(v8::Isolate::GetCurrent(), value));
}
#endif
//=== String Object ============================================================
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
return v8::StringObject::New(value).As<v8::StringObject>();
}
//=== Unbound Script ===========================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::CompileUnboundScript(
v8::Isolate::GetCurrent(), &src);
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::CompileUnboundScript(
v8::Isolate::GetCurrent(), &src);
}
#else
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return Factory<v8::UnboundScript>::return_t(
v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src));
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return Factory<v8::UnboundScript>::return_t(
v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src));
}
#endif
} // end of namespace imp
//=== Presistents and Handles ==================================================
#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
template <typename T>
inline v8::Local<T> New(v8::Handle<T> h) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), h);
}
#endif
template <typename T, typename M>
inline v8::Local<T> New(v8::Persistent<T, M> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
#endif // NAN_IMPLEMENTATION_12_INL_H_

View File

@@ -0,0 +1,259 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_
#define NAN_IMPLEMENTATION_PRE_12_INL_H_
//==============================================================================
// node v0.10 implementation
//==============================================================================
namespace imp {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New();
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(value)->ToBoolean();
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Local<v8::ObjectTemplate> tmpl
, v8::Local<v8::Value> obj) {
v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj);
v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx);
ctx.Dispose();
return lctx;
}
//=== Date =====================================================================
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return Factory<v8::Date>::return_t(v8::Date::New(value).As<v8::Date>());
}
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( FunctionCallback callback
, v8::Local<v8::Value> data) {
return Factory<v8::FunctionTemplate>::New( callback
, data
, v8::Local<v8::Signature>()
)->GetFunction();
}
//=== FunctionTemplate =========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( FunctionCallback callback
, v8::Local<v8::Value> data
, v8::Local<v8::Signature> signature) {
if (callback) {
v8::HandleScope scope;
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New();
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = tpl->NewInstance();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
// Note(agnat): Emulate length argument here. Unfortunately, I couldn't find
// a way. Have at it though...
return scope.Close(
v8::FunctionTemplate::New(imp::FunctionCallbackWrapper
, obj
, signature));
} else {
return v8::FunctionTemplate::New(0, data, signature);
}
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New(value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New();
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New();
}
//=== RegExp ===================================================================
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return Factory<v8::RegExp>::return_t(v8::RegExp::New(pattern, flags));
}
//=== Script ===================================================================
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
return Factory<v8::Script>::return_t(v8::Script::New(source));
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
return Factory<v8::Script>::return_t(
v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin)));
}
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
return v8::Signature::New(receiver);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return Factory<v8::String>::return_t(v8::String::Empty());
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return Factory<v8::String>::return_t(v8::String::New(value, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(
std::string const& value) /* NOLINT(build/include_what_you_use) */ {
assert(value.size() <= INT_MAX && "string too long");
return Factory<v8::String>::return_t(
v8::String::New( value.data(), static_cast<int>(value.size())));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return Factory<v8::String>::return_t(v8::String::New(value, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return Factory<v8::String>::return_t(v8::String::NewExternal(value));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) {
return Factory<v8::String>::return_t(v8::String::NewExternal(value));
}
//=== String Object ============================================================
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
return v8::StringObject::New(value).As<v8::StringObject>();
}
} // end of namespace imp
//=== Presistents and Handles ==================================================
template <typename T>
inline v8::Local<T> New(v8::Handle<T> h) {
return v8::Local<T>::New(h);
}
template <typename T>
inline v8::Local<T> New(v8::Persistent<T> const& p) {
return v8::Local<T>::New(p);
}
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p) {
return v8::Local<T>::New(p.persistent);
}
#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_

View File

@@ -0,0 +1,224 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_MAYBE_43_INL_H_
#define NAN_MAYBE_43_INL_H_
template<typename T>
using MaybeLocal = v8::MaybeLocal<T>;
template<typename T>
using Maybe = v8::Maybe<T>;
template<typename T>
NAN_INLINE Maybe<T> Nothing() {
return v8::Nothing<T>();
}
template<typename T>
NAN_INLINE Maybe<T> Just(const T& t) {
return v8::Just<T>(t);
}
v8::Local<v8::Context> GetCurrentContext();
NAN_INLINE
MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) {
return val->ToDetailString(GetCurrentContext());
}
NAN_INLINE
MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) {
return val->ToArrayIndex(GetCurrentContext());
}
NAN_INLINE
Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) {
return a->Equals(GetCurrentContext(), b);
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) {
return MaybeLocal<v8::Object>(h->NewInstance(GetCurrentContext()));
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(
v8::Local<v8::Function> h
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Object>(h->NewInstance(GetCurrentContext(),
argc, argv));
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) {
return MaybeLocal<v8::Object>(h->NewInstance(GetCurrentContext()));
}
NAN_INLINE MaybeLocal<v8::Function> GetFunction(
v8::Local<v8::FunctionTemplate> t) {
return t->GetFunction(GetCurrentContext());
}
NAN_INLINE Maybe<bool> Set(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key
, v8::Local<v8::Value> value) {
return obj->Set(GetCurrentContext(), key, value);
}
NAN_INLINE Maybe<bool> Set(
v8::Local<v8::Object> obj
, uint32_t index
, v8::Local<v8::Value> value) {
return obj->Set(GetCurrentContext(), index, value);
}
NAN_INLINE Maybe<bool> ForceSet(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key
, v8::Local<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
return obj->ForceSet(GetCurrentContext(), key, value, attribs);
}
NAN_INLINE MaybeLocal<v8::Value> Get(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key) {
return obj->Get(GetCurrentContext(), key);
}
NAN_INLINE
MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) {
return obj->Get(GetCurrentContext(), index);
}
NAN_INLINE v8::PropertyAttribute GetPropertyAttributes(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key) {
return obj->GetPropertyAttributes(GetCurrentContext(), key).FromJust();
}
NAN_INLINE Maybe<bool> Has(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->Has(GetCurrentContext(), key);
}
NAN_INLINE Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) {
return obj->Has(GetCurrentContext(), index);
}
NAN_INLINE Maybe<bool> Delete(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->Delete(GetCurrentContext(), key);
}
NAN_INLINE
Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) {
return obj->Delete(GetCurrentContext(), index);
}
NAN_INLINE
MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) {
return obj->GetPropertyNames(GetCurrentContext());
}
NAN_INLINE
MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) {
return obj->GetOwnPropertyNames(GetCurrentContext());
}
NAN_INLINE Maybe<bool> SetPrototype(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> prototype) {
return obj->SetPrototype(GetCurrentContext(), prototype);
}
NAN_INLINE MaybeLocal<v8::String> ObjectProtoToString(
v8::Local<v8::Object> obj) {
return obj->ObjectProtoToString(GetCurrentContext());
}
NAN_INLINE Maybe<bool> HasOwnProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->HasOwnProperty(GetCurrentContext(), key);
}
NAN_INLINE Maybe<bool> HasRealNamedProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->HasRealNamedProperty(GetCurrentContext(), key);
}
NAN_INLINE Maybe<bool> HasRealIndexedProperty(
v8::Local<v8::Object> obj
, uint32_t index) {
return obj->HasRealIndexedProperty(GetCurrentContext(), index);
}
NAN_INLINE Maybe<bool> HasRealNamedCallbackProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->HasRealNamedCallbackProperty(GetCurrentContext(), key);
}
NAN_INLINE MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->GetRealNamedPropertyInPrototypeChain(GetCurrentContext(), key);
}
NAN_INLINE MaybeLocal<v8::Value> GetRealNamedProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->GetRealNamedProperty(GetCurrentContext(), key);
}
NAN_INLINE MaybeLocal<v8::Value> CallAsFunction(
v8::Local<v8::Object> obj
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
return obj->CallAsFunction(GetCurrentContext(), recv, argc, argv);
}
NAN_INLINE MaybeLocal<v8::Value> CallAsConstructor(
v8::Local<v8::Object> obj
, int argc, v8::Local<v8::Value> argv[]) {
return obj->CallAsConstructor(GetCurrentContext(), argc, argv);
}
NAN_INLINE
MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) {
return msg->GetSourceLine(GetCurrentContext());
}
NAN_INLINE Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) {
return msg->GetLineNumber(GetCurrentContext());
}
NAN_INLINE Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) {
return msg->GetStartColumn(GetCurrentContext());
}
NAN_INLINE Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) {
return msg->GetEndColumn(GetCurrentContext());
}
NAN_INLINE MaybeLocal<v8::Object> CloneElementAt(
v8::Local<v8::Array> array
, uint32_t index) {
return array->CloneElementAt(GetCurrentContext(), index);
}
#endif // NAN_MAYBE_43_INL_H_

Some files were not shown because too many files have changed in this diff Show More