diff --git a/.gitignore b/.gitignore index 646ac51..fd3aaa9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store node_modules/ +data/ \ No newline at end of file diff --git a/README.md b/README.md index 7c88c51..a86504f 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,14 @@ It requires [node.js](http://nodejs.org/download/) The server will run on port 3000. You can test it in the (Chrome) browser at localhost:3000. +## User Database + +Using a local MongoDB + +* mongod --dbpath ./data --port 1664 + +You can configure the url in /config/database.js + ## Author - Pierre Chabardes diff --git a/app.js b/app.js index dea82b2..c53f9ea 100644 --- a/app.js +++ b/app.js @@ -1,25 +1,43 @@ /** * Module dependencies. */ -var express = require('express') - , http = require('http') - , path = require('path') - , streams = require('./app/streams.js')(); - -var app = express() - , server = http.createServer(app) - , io = require('socket.io').listen(server); - -// all environments -app.set('port', 3000); -app.set('views', __dirname + '/views'); -app.set('view engine', 'ejs'); -app.use(express.favicon(__dirname + '/public/images/favicon.ico')); -app.use(express.logger('dev')); -app.use(express.bodyParser()); -app.use(express.methodOverride()); -app.use(app.router); -app.use(express.static(path.join(__dirname, 'public'))); +var express = require('express') + , http = require('http') + , path = require('path') + , mongoose = require('mongoose') + , passport = require('passport') + , flash = require('connect-flash') + , streams = require('./app/streams.js')(); + +var app = express() + , server = http.createServer(app) + , configDB = require('./config/database.js') + , io = require('socket.io').listen(server); + +mongoose.connect(configDB.url); +require('./config/passport')(passport); // pass passport for configuration + +app.configure(function() { + // all environments + app.set('port', 3000); + app.set('views', __dirname + '/views'); + app.set('view engine', 'ejs'); + app.use(express.favicon(__dirname + '/public/images/favicon.ico')); + app.use(express.logger('dev')); + app.use(express.cookieParser()); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + + // required for passport + app.use(express.session({ secret: 'ilovemaplesyruppancakes' })); // session secret + app.use(passport.initialize()); + app.use(passport.session()); // persistent login sessions + app.use(flash()); // use connect-flash for flash messages stored in session + + app.use(app.router); + app.use(express.static(path.join(__dirname, 'public'))); +}); + // development only if ('development' == app.get('env')) { @@ -27,7 +45,7 @@ if ('development' == app.get('env')) { } // routing -require('./app/routes.js')(app, streams); +require('./app/routes.js')(app, streams, passport); /** * Socket.io event handling diff --git a/app/models/user.js b/app/models/user.js new file mode 100644 index 0000000..42bddd8 --- /dev/null +++ b/app/models/user.js @@ -0,0 +1,25 @@ +var mongoose = require('mongoose'); +var bcrypt = require('bcrypt-nodejs'); + +// define the schema for our user model +var userSchema = mongoose.Schema({ + + local : { + username: String, + password: String, + } +}); + +// methods ====================== +// generating a hash +userSchema.methods.generateHash = function(password) { + return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); +}; + +// checking if password is valid +userSchema.methods.validPassword = function(password) { + return bcrypt.compareSync(password, this.local.password); +}; + +// create the model for users and expose it to our app +module.exports = mongoose.model('User', userSchema); \ No newline at end of file diff --git a/app/routes.js b/app/routes.js index f9a8e8b..cd5fc76 100644 --- a/app/routes.js +++ b/app/routes.js @@ -1,50 +1,82 @@ -module.exports = function(app, streams) { +module.exports = function(app, streams, passport) { - // GET home + // HOME PAGE (with login links) var index = function(req, res) { - res.render('index', { - title: 'Project RTC', - header: 'WebRTC live streaming', - footer: 'pierre@chabardes.net', - id: req.params.id + res.render('index', { + title: 'Project RTC' }); }; - // GET crowd - var crowd = function(req, res) { - res.render('crowd', { - title: 'Project RTC', - footer: '' + // LOGIN PAGE + var login = function(req, res) { + res.render('login', { + title: 'Project RTC', + message: req.flash('loginMessage') }); }; - // GET join - var join = function(req, res) { - res.render('join', { + // LOGOUT PAGE + var logout = function(req, res) { + req.logout(); + res.redirect('/'); + }; + + // SIGNUP PAGE + var signup = function(req, res) { + res.render('signup', { + title: 'Project RTC', + message: req.flash('signupMessage') + }); + }; + + // GET main + var main = function(req, res) { + res.render('main', { title: 'Project RTC', - footer: '' + header: 'WebRTC live streaming', + footer: 'pierre@chabardes.net', + id: req.params.id, + user: req.user.local.username }); }; // GET streams as JSON var displayStreams = function(req, res) { - var id = req.params.id; var streamList = streams.getStreams(); // JSON exploit to clone streamList.public - var data = (JSON.parse(JSON.stringify(streamList.public))); - - /* - * if a specific id is requested, always add the stream even if private - */ - if(!!id) { - data[id] = streamList.public[id] || streamList.private[id]; - } + var data = (JSON.parse(JSON.stringify(streamList))); res.json(200, data); }; + // route middleware to make sure a user is logged in + var isLoggedIn = function(req, res, next) { + + // if user is authenticated in the session, carry on + if (req.isAuthenticated()) + return next(); + + // if they aren't redirect them to the home page + res.redirect('/'); + } + app.get('/streams', displayStreams); - app.get('/streams/:id', displayStreams); + app.get('/main', isLoggedIn, main); + app.get('/login', login); + // process the login form + app.post('/login', passport.authenticate('local-login', { + successRedirect : '/main', // redirect to the secure profile section + failureRedirect : '/login', // redirect back to the signup page if there is an error + failureFlash : true // allow flash messages + })); + app.get('/logout', logout); + app.get('/signup', signup); + // process the signup form + app.post('/signup', passport.authenticate('local-signup', { + successRedirect : '/main', // redirect to the secure main section + failureRedirect : '/signup', // redirect back to the signup page if there is an error + failureFlash : true // allow flash messages + })); app.get('/', index); - app.get('/:id', index); + app.get('/:id', isLoggedIn, main); } \ No newline at end of file diff --git a/app/socketHandler.js b/app/socketHandler.js index 5851d87..a8926ac 100644 --- a/app/socketHandler.js +++ b/app/socketHandler.js @@ -18,7 +18,7 @@ module.exports = function(io, streams) { client.on('readyToStream', function(options) { console.log('-- ' + client.id + ' is ready to stream --'); - streams.addStream(client.id, options.name, options.privacy); + streams.addStream(client.id, options.name); }); client.on('rate', function(rating) { @@ -26,7 +26,7 @@ module.exports = function(io, streams) { }); client.on('update', function(options) { - streams.update(client.id, options.name, options.privacy); + streams.update(client.id, options.name); }); function leave() { diff --git a/app/streams.js b/app/streams.js index c4222c2..ae09b87 100644 --- a/app/streams.js +++ b/app/streams.js @@ -3,10 +3,7 @@ module.exports = function() { * available streams * the id key is considered unique (provided by socket.io) */ - var streamList = { - public: {}, - private: {} - }; + var streamList = {}; /** * Stream object @@ -21,19 +18,18 @@ module.exports = function() { } return { - addStream : function(id, name, isPrivate) { + addStream : function(id, name) { var stream = new Stream(name); - isPrivate ? streamList.private[id] = stream : streamList.public[id] = stream; + streamList[id] = stream; }, removeStream : function(id) { - delete streamList.public[id]; - delete streamList.private[id]; + delete streamList[id]; }, // rate function rate : function(id, rater, rating) { - var stream = (streamList.public[id] || streamList.private[id]); + var stream = streamList[id]; if(stream.raters[rater] || stream.raters[rater] === null) { stream.rating += rating - stream.raters[rater]; } else { @@ -44,12 +40,12 @@ module.exports = function() { }, // update function - update : function(id, name, isPrivate) { - var stream = streamList.public[id] || streamList.private[id]; + update : function(id, name) { + var stream = streamList[id]; stream.name = name; this.removeStream(id); - isPrivate ? streamList.private[id] = stream : streamList.public[id] = stream; + streamList[id] = stream; }, getStreams : function() { diff --git a/config/database.js b/config/database.js new file mode 100644 index 0000000..76695fd --- /dev/null +++ b/config/database.js @@ -0,0 +1,6 @@ +// config/database.js +module.exports = { + + 'url' : 'mongodb://localhost:1664' + +}; \ No newline at end of file diff --git a/config/passport.js b/config/passport.js new file mode 100644 index 0000000..947a41c --- /dev/null +++ b/config/passport.js @@ -0,0 +1,108 @@ +var LocalStrategy = require('passport-local').Strategy; + +// load up the user model +var User = require('../app/models/user.js'); + +// expose this function to our app using module.exports +module.exports = function(passport) { + + // ========================================================================= + // passport session setup ================================================== + // ========================================================================= + // required for persistent login sessions + // passport needs ability to serialize and unserialize users out of session + + // used to serialize the user for the session + passport.serializeUser(function(user, done) { + done(null, user.id); + }); + + // used to deserialize the user + passport.deserializeUser(function(id, done) { + User.findById(id, function(err, user) { + done(err, user); + }); + }); + + // ========================================================================= + // LOCAL SIGNUP ============================================================ + // ========================================================================= + // we are using named strategies since we have one for login and one for signup + // by default, if there was no name, it would just be called 'local' + + passport.use('local-signup', new LocalStrategy({ + passReqToCallback : true // allows us to pass back the entire request to the callback + }, + function(req, username, password, done) { + + // asynchronous + // User.findOne wont fire unless data is sent back + process.nextTick(function() { + + // find a user whose username is the same as the forms username + // we are checking to see if the user trying to login already exists + User.findOne({ 'local.username' : username }, function(err, user) { + // if there are any errors, return the error + if (err) + return done(err); + + // check to see if theres already a user with that username + if (user) { + return done(null, false, req.flash('signupMessage', 'That username is already taken.')); + } else { + + // if there is no user with that username + // create the user + var newUser = new User(); + + // set the user's local credentials + newUser.local.username = username; + newUser.local.password = newUser.generateHash(password); + + // save the user + newUser.save(function(err) { + if (err) + throw err; + return done(null, newUser); + }); + } + + }); + + }); + + })); + + // ========================================================================= + // LOCAL LOGIN ============================================================= + // ========================================================================= + // we are using named strategies since we have one for login and one for signup + // by default, if there was no name, it would just be called 'local' + + passport.use('local-login', new LocalStrategy({ + passReqToCallback : true // allows us to pass back the entire request to the callback + }, + function(req, username, password, done) { // callback with username and password from our form + + // find a user whose username is the same as the forms username + // we are checking to see if the user trying to login already exists + User.findOne({ 'local.username' : username }, function(err, user) { + // if there are any errors, return the error before anything else + if (err) + return done(err); + + // if no user is found, return the message + if (!user) + return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash + + // if the user is found but the password is wrong + if (!user.validPassword(password)) + return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata + + // all is well, return successful user + return done(null, user); + }); + + })); + +}; \ No newline at end of file diff --git a/package.json b/package.json index 6803720..d818b18 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "author": "Pierre Chabardes ", "description": "a webRTC live streaming server", "scripts": { + "local-db": "mongod --dbpath ./data --port 1664", "start": "forever start app.js", "stop": "forever stopall" }, @@ -15,6 +16,11 @@ "express": "3.2.5", "ejs": "*", "socket.io": "~0.9", - "forever": "0.10.8" + "forever": "0.10.8", + "mongoose" : "~3.8.1", + "passport" : "~0.1.17", + "passport-local" : "~0.1.6", + "connect-flash" : "~0.1.1", + "bcrypt-nodejs" : "latest" } } \ No newline at end of file diff --git a/public/javascripts/RTCViewModel.js b/public/javascripts/RTCViewModel.js index 0b6af7c..20a9a9d 100644 --- a/public/javascripts/RTCViewModel.js +++ b/public/javascripts/RTCViewModel.js @@ -28,8 +28,7 @@ var RTCViewModel = function(client, path) { }, availableStreams = ko.observable([]), isStreaming = ko.observable(false), - isPrivate = ko.observable(false), - name = ko.observable('Guest'), + name = ko.observable('newStream'), link = ko.observable(), localVideoEl = document.getElementById('localVideo'); @@ -37,8 +36,7 @@ var RTCViewModel = function(client, path) { ko.computed(function() { if(isStreaming()) { client.send('update', { - name: name(), - privacy: isPrivate() + name: name() }); } }).extend({throttle: 500}); @@ -47,8 +45,7 @@ var RTCViewModel = function(client, path) { attachMediaStream(localVideoEl, stream); client.setLocalStream(stream); client.send('readyToStream', { - name: name(), - privacy: isPrivate() + name: name() } ); link(window.location.host + "/" + client.getId()); @@ -86,7 +83,6 @@ var RTCViewModel = function(client, path) { return { streams: availableStreams, isStreaming: isStreaming, - isPrivate: isPrivate, name: name, link: link, localCamButtonText: ko.computed( @@ -119,8 +115,7 @@ var RTCViewModel = function(client, path) { stream.isPlaying(!stream.isPlaying()); }, - startPrivateCall: function(remoteId) { - isPrivate(true); + startDirectCall: function(remoteId) { getUserMedia( mediaConfig, function (stream) { diff --git a/public/javascripts/ndn.min.js b/public/javascripts/ndn.min.js new file mode 100644 index 0000000..f722417 --- /dev/null +++ b/public/javascripts/ndn.min.js @@ -0,0 +1,439 @@ +/* + MIT License + MIT License + MIT License + MIT License + MIT License +*/ +var ndn=ndn||{},exports=ndn,require=function(){return ndn},Buffer=function Buffer(b,c){var d;if("number"==typeof b)d=new Uint8Array(b);else if("string"==typeof b)if(null==c||"utf8"==c){var e=Buffer.str2rstr_utf8(b);d=new Uint8Array(e.length);for(var f=0;fthis[d]?"0":"")+this[d].toString(16);if("hex"==b)return c;if("base64"==b)return hex2b64(c);throw Error("Buffer.toString: unknown encoding format "+b);};d.__proto__.slice=function(b,c){return void 0!==c?new Buffer(this.subarray(b,c),!1):new Buffer(this.subarray(b),!1)};d.__proto__.copy=function(b,c){void 0!==c?b.set(this,c):b.set(this)}; +return d};Buffer.prototype=Uint8Array.prototype;Buffer.concat=function(a){for(var b=0,c=0;c=d&&56320<=e&&57343>=e)&&(d=65536+((d&1023)<<10)+(e&1023),c++),127>=d?b+=String.fromCharCode(d):2047>=d?b+=String.fromCharCode(192|d>>>6&31,128|d&63):65535>=d?b+=String.fromCharCode(224|d>>>12&15,128|d>>>6&63,128|d&63):2097151>=d&&(b+=String.fromCharCode(240|d>>>18&7,128|d>>>12&63,128|d>>>6&63,128|d&63));return b}; +exports.createHash=function(a){if("sha256"!=a)throw Error("createHash: unsupported algorithm.");a={};a.md=new KJUR.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"});a.update=function(a){this.md.updateHex(a.toString("hex"))};a.digest=function(){return new Buffer(this.md.digest(),"hex")};return a}; +exports.createSign=function(a){if("RSA-SHA256"!=a)throw Error("createSign: unsupported algorithm.");return{arr:[],update:function(a){this.arr.push(a)},sign:function(a){var c=new RSAKey;c.readPrivateKeyFromPEMString(a);a=new KJUR.crypto.Signature({alg:"SHA256withRSA",prov:"cryptojs/jsrsa"});a.initSign(c);for(c=0;c>>2]|=(c[e>>>2]>>>24-8*(e%4)&255)<<24-8*((d+e)%4);else if(65535>>2]=c[e>>>2];else b.push.apply(b,c);this.sigBytes+=a;return this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<< +32-8*(c%4);b.length=a.ceil(c/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(b){for(var c=[],d=0;d>>2]>>>24-8*(d%4)&255;c.push((e>>>4).toString(16));c.push((e&15).toString(16))}return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d>>3]|=parseInt(a.substr(d, +2),16)<<24-4*(d%8);return new g.init(c,b/2)}},k=h.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var c=[],d=0;d>>2]>>>24-8*(d%4)&255));return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return new g.init(c,b)}},m=h.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}}, +n=d.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new g.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=m.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,f=this.blockSize,h=e/(4*f),h=b?a.ceil(h):a.max((h|0)-this._minBufferSize,0);b=h*f;e=a.min(4*b,e);if(b){for(var j=0;jk;){var m;a:{m=j;for(var n=a.sqrt(m),p=2;p<=n;p++)if(!(m%p)){m=!1;break a}m=!0}m&&(8>k&&(f[k]=h(a.pow(j,0.5))),g[k]=h(a.pow(j,1/3)),k++);j++}var l=[],c=c.SHA256=e.extend({_doReset:function(){this._hash=new d.init(f.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],j=c[4],k=c[5],m=c[6],n=c[7],p=0;64>p;p++){if(16>p)l[p]= +a[b+p]|0;else{var q=l[p-15],r=l[p-2];l[p]=((q<<25|q>>>7)^(q<<14|q>>>18)^q>>>3)+l[p-7]+((r<<15|r>>>17)^(r<<13|r>>>19)^r>>>10)+l[p-16]}q=n+((j<<26|j>>>6)^(j<<21|j>>>11)^(j<<7|j>>>25))+(j&k^~j&m)+g[p]+l[p];r=((d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22))+(d&e^d&f^e&f);n=m;m=k;k=j;j=h+q|0;h=f;f=e;e=d;d=q+r|0}c[0]=c[0]+d|0;c[1]=c[1]+e|0;c[2]=c[2]+f|0;c[3]=c[3]+h|0;c[4]=c[4]+j|0;c[5]=c[5]+k|0;c[6]=c[6]+m|0;c[7]=c[7]+n|0},_doFinalize:function(){var b=this._data,c=b.words,d=8*this._nDataBytes,e=8*b.sigBytes; +c[e>>>5]|=128<<24-e%32;c[(e+64>>>9<<4)+14]=a.floor(d/4294967296);c[(e+64>>>9<<4)+15]=d;b.sigBytes=4*c.length;this._process();return this._hash},clone:function(){var a=e.clone.call(this);a._hash=this._hash.clone();return a}});b.SHA256=e._createHelper(c);b.HmacSHA256=e._createHmacHelper(c)})(Math);var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="="; +function hex2b64(a){var b,c,d="";for(b=0;b+3<=a.length;b+=3)c=parseInt(a.substring(b,b+3),16),d+=b64map.charAt(c>>6)+b64map.charAt(c&63);b+1==a.length?(c=parseInt(a.substring(b,b+1),16),d+=b64map.charAt(c<<2)):b+2==a.length&&(c=parseInt(a.substring(b,b+2),16),d+=b64map.charAt(c>>2)+b64map.charAt((c&3)<<4));if(b64pad)for(;0<(d.length&3);)d+=b64pad;return d} +function b64tohex(a){var b="",c,d=0,e;for(c=0;cv||(0==d?(b+=int2char(v>>2),e=v&3,d=1):1==d?(b+=int2char(e<<2|v>>4),e=v&15,d=2):2==d?(b+=int2char(e),b+=int2char(v>>2),e=v&3,d=3):(b+=int2char(e<<2|v>>4),b+=int2char(v&15),d=0));1==d&&(b+=int2char(e<<2));return b}function b64toBA(a){a=b64tohex(a);var b,c=[];for(b=0;2*ba?"0"+a.toString(16):a.toString(16)} +function pkcs1pad2(a,b){if(be?c[--b]=e:127e?(c[--b]=e&63|128,c[--b]=e>>6|192):(c[--b]=e&63|128,c[--b]=e>>6&63|128,c[--b]=e>>12|224)}c[--b]=0;d=new SecureRandom;for(e=[];2>24,(e&16711680)>>16,(e&65280)>>8,e&255]))),e+=1;return d}var SHA1_SIZE=20; +function oaep_pad(a,b,c){if(a.length+2*SHA1_SIZE+2>b)throw"Message too long for RSA";var d="",e;for(e=0;e>3);if(null==a)return null;a=this.doPublic(a);if(null==a)return null;a=a.toString(16);return 0==(a.length&1)?a:"0"+a}function RSAEncryptOAEP(a,b){var c=oaep_pad(a,this.n.bitLength()+7>>3,b);if(null==c)return null;c=this.doPublic(c);if(null==c)return null;c=c.toString(16);return 0==(c.length&1)?c:"0"+c}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt; +RSAKey.prototype.encryptOAEP=RSAEncryptOAEP;function pkcs1unpad2(a,b){for(var c=a.toByteArray(),d=0;d=c.length)return null;for(var e="";++df?e+=String.fromCharCode(f):191f?(e+=String.fromCharCode((f&31)<<6|c[d+1]&63),++d):(e+=String.fromCharCode((f&15)<<12|(c[d+1]&63)<<6|c[d+2]&63),d+=2)}return e} +function oaep_mgf1_str(a,b,c){for(var d="",e=0;d.length>24,(e&16711680)>>16,(e&65280)>>8,e&255])),e+=1;return d}SHA1_SIZE=20; +function oaep_unpad(a,b,c){a=a.toByteArray();var d;for(d=0;d>1;this.e=parseInt(b,16);for(var e=new BigInteger(b,16);;){for(;!(this.p=new BigInteger(a-d,1,c),0==this.p.subtract(BigInteger.ONE).gcd(e).compareTo(BigInteger.ONE)&&this.p.isProbablePrime(10)););for(;!(this.q=new BigInteger(d,1,c),0==this.q.subtract(BigInteger.ONE).gcd(e).compareTo(BigInteger.ONE)&&this.q.isProbablePrime(10)););if(0>=this.p.compareTo(this.q)){var f=this.p;this.p=this.q;this.q=f}var f=this.p.subtract(BigInteger.ONE),g=this.q.subtract(BigInteger.ONE), +h=f.multiply(g);if(0==h.gcd(e).compareTo(BigInteger.ONE)){this.n=this.p.multiply(this.q);this.d=e.modInverse(h);this.dmp1=this.d.mod(f);this.dmq1=this.d.mod(g);this.coeff=this.q.modInverse(this.p);break}}}function RSADoPrivate(a){if(null==this.p||null==this.q)return a.modPow(this.d,this.n);var b=a.mod(this.p).modPow(this.dmp1,this.p);for(a=a.mod(this.q).modPow(this.dmq1,this.q);0>b.compareTo(a);)b=b.add(this.p);return b.subtract(a).multiply(this.coeff).mod(this.p).multiply(this.q).add(a)} +function RSADecrypt(a){a=parseBigInt(a,16);a=this.doPrivate(a);return null==a?null:pkcs1unpad2(a,this.n.bitLength()+7>>3)}function RSADecryptOAEP(a,b){var c=parseBigInt(a,16),c=this.doPrivate(c);return null==c?null:oaep_unpad(c,this.n.bitLength()+7>>3,b)}RSAKey.prototype.doPrivate=RSADoPrivate;RSAKey.prototype.setPrivate=RSASetPrivate;RSAKey.prototype.setPrivateEx=RSASetPrivateEx;RSAKey.prototype.generate=RSAGenerate;RSAKey.prototype.decrypt=RSADecrypt;RSAKey.prototype.decryptOAEP=RSADecryptOAEP; +if("undefined"==typeof KJUR||!KJUR)KJUR={};if("undefined"==typeof KJUR.crypto||!KJUR.crypto)KJUR.crypto={}; +KJUR.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"};this.getDigestInfoHex=function(a,b){if("undefined"==typeof this.DIGESTINFOHEAD[b])throw"alg not supported in Util.DIGESTINFOHEAD: "+ +b;return this.DIGESTINFOHEAD[b]+a};this.getPaddedDigestInfoHex=function(a,b,c){var d=this.getDigestInfoHex(a,b);a=c/4;if(d.length+22>a)throw"key is too short for SigAlg: keylen="+c+","+b;b="00"+d;c="";a=a-4-b.length;for(d=0;d>24,(e&16711680)>>16,(e&65280)>>8,e&255])),e+=1;return d} +function _rsasign_signStringPSS(a,b,c){var d=_RSASIGN_HASHRAWFUNC[b],e=d(a);a=e.length;b=this.n.bitLength()-1;var f=Math.ceil(b/8);if(-1===c)c=a;else if(-2===c||void 0===c)c=f-a-2;else if(-2>c)throw"invalid salt length";if(f>8*f-b&255);for(e=0;ed)throw"invalid salt length";if(g>8*g-f&255;if(0!==(j.charCodeAt(0)&k))throw"bits beyond keysize not zero";var m=pss_mgf1_str(h,j.length,c),f=[];for(b=0;bc?c+1:-2}function _asnhex_getHexOfL_AtObj(a,b){var c=_asnhex_getByteLengthOfL_AtObj(a,b);return 1>c?"":a.substring(b+2,b+2+2*c)}function _asnhex_getIntOfL_AtObj(a,b){var c=_asnhex_getHexOfL_AtObj(a,b);return""==c?-1:(8>parseInt(c.substring(0,1))?parseBigInt(c,16):parseBigInt(c.substring(2),16)).intValue()} +function _asnhex_getStartPosOfV_AtObj(a,b){var c=_asnhex_getByteLengthOfL_AtObj(a,b);return 0>c?c:b+2*(c+1)}function _asnhex_getHexOfV_AtObj(a,b){var c=_asnhex_getStartPosOfV_AtObj(a,b),d=_asnhex_getIntOfL_AtObj(a,b);return a.substring(c,c+2*d)}function _asnhex_getHexOfTLV_AtObj(a,b){var c=a.substr(b,2),d=_asnhex_getHexOfL_AtObj(a,b),e=_asnhex_getHexOfV_AtObj(a,b);return c+d+e} +function _asnhex_getPosOfNextSibling_AtObj(a,b){var c=_asnhex_getStartPosOfV_AtObj(a,b),d=_asnhex_getIntOfL_AtObj(a,b);return c+2*d}function _asnhex_getPosArrayOfChildren_AtObj(a,b){var c=[],d=_asnhex_getStartPosOfV_AtObj(a,b);c.push(d);for(var e=_asnhex_getIntOfL_AtObj(a,b),f=d,g=0;;){f=_asnhex_getPosOfNextSibling_AtObj(a,f);if(null==f||f-d>=2*e)break;if(200<=g)break;c.push(f);g++}return c}function _asnhex_getNthChildIndex_AtObj(a,b,c){return _asnhex_getPosArrayOfChildren_AtObj(a,b)[c]} +function _asnhex_getDecendantIndexByNthList(a,b,c){if(0==c.length)return b;var d=c.shift();b=_asnhex_getPosArrayOfChildren_AtObj(a,b);return _asnhex_getDecendantIndexByNthList(a,b[d],c)}function _asnhex_getDecendantHexTLVByNthList(a,b,c){b=_asnhex_getDecendantIndexByNthList(a,b,c);return _asnhex_getHexOfTLV_AtObj(a,b)}function _asnhex_getDecendantHexVByNthList(a,b,c){b=_asnhex_getDecendantIndexByNthList(a,b,c);return _asnhex_getHexOfV_AtObj(a,b)}function ASN1HEX(){return ASN1HEX} +ASN1HEX.getByteLengthOfL_AtObj=_asnhex_getByteLengthOfL_AtObj;ASN1HEX.getHexOfL_AtObj=_asnhex_getHexOfL_AtObj;ASN1HEX.getIntOfL_AtObj=_asnhex_getIntOfL_AtObj;ASN1HEX.getStartPosOfV_AtObj=_asnhex_getStartPosOfV_AtObj;ASN1HEX.getHexOfV_AtObj=_asnhex_getHexOfV_AtObj;ASN1HEX.getHexOfTLV_AtObj=_asnhex_getHexOfTLV_AtObj;ASN1HEX.getPosOfNextSibling_AtObj=_asnhex_getPosOfNextSibling_AtObj;ASN1HEX.getPosArrayOfChildren_AtObj=_asnhex_getPosArrayOfChildren_AtObj;ASN1HEX.getNthChildIndex_AtObj=_asnhex_getNthChildIndex_AtObj; +ASN1HEX.getDecendantIndexByNthList=_asnhex_getDecendantIndexByNthList;ASN1HEX.getDecendantHexVByNthList=_asnhex_getDecendantHexVByNthList;ASN1HEX.getDecendantHexTLVByNthList=_asnhex_getDecendantHexTLVByNthList;function _x509_pemToBase64(a){a=a.replace("-----BEGIN CERTIFICATE-----","");a=a.replace("-----END CERTIFICATE-----","");return a=a.replace(/[ \n]+/g,"")}function _x509_pemToHex(a){a=_x509_pemToBase64(a);return b64tohex(a)} +function _x509_getHexTbsCertificateFromCert(a){return ASN1HEX.getStartPosOfV_AtObj(a,0)}function _x509_getSubjectPublicKeyInfoPosFromCertHex(a){var b=ASN1HEX.getStartPosOfV_AtObj(a,0),b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);return 1>b.length?-1:"a003020102"==a.substring(b[0],b[0]+10)?6>b.length?-1:b[6]:5>b.length?-1:b[5]} +function _x509_getSubjectPublicKeyPosFromCertHex(a){var b=_x509_getSubjectPublicKeyInfoPosFromCertHex(a);if(-1==b)return-1;b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);if(2!=b.length)return-1;b=b[1];if("03"!=a.substring(b,b+2))return-1;b=ASN1HEX.getStartPosOfV_AtObj(a,b);return"00"!=a.substring(b,b+2)?-1:b+2} +function _x509_getPublicKeyHexArrayFromCertHex(a){var b=_x509_getSubjectPublicKeyPosFromCertHex(a),c=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);if(2!=c.length)return[];b=ASN1HEX.getHexOfV_AtObj(a,c[0]);a=ASN1HEX.getHexOfV_AtObj(a,c[1]);return null!=b&&null!=a?[b,a]:[]}function _x509_getPublicKeyHexArrayFromCertPEM(a){a=_x509_pemToHex(a);return _x509_getPublicKeyHexArrayFromCertHex(a)}function _x509_getSerialNumberHex(){return ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,1])} +function _x509_getIssuerHex(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3])}function _x509_getIssuerString(){return _x509_hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3]))}function _x509_getSubjectHex(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5])}function _x509_getSubjectString(){return _x509_hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5]))} +function _x509_getNotBefore(){var a=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,0]),a=a.replace(/(..)/g,"%$1");return a=decodeURIComponent(a)}function _x509_getNotAfter(){var a=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,1]),a=a.replace(/(..)/g,"%$1");return a=decodeURIComponent(a)}_x509_DN_ATTRHEX={"0603550406":"C","060355040a":"O","060355040b":"OU","0603550403":"CN","0603550405":"SN","0603550408":"ST","0603550407":"L"}; +function _x509_hex2dn(a){for(var b="",c=ASN1HEX.getPosArrayOfChildren_AtObj(a,0),d=0;d>=15;0<=--f;){var h=this[a]&32767,j=this[a++]>>15,k=b*h+j*g,h=g*h+((k&32767)<<15)+c[d]+(e&1073741823);e=(h>>>30)+(k>>>15)+b*j+(e>>>30);c[d++]=h&1073741823}return e}function am3(a,b,c,d,e,f){var g=b&16383;for(b>>=14;0<=--f;){var h=this[a]&16383,j=this[a++]>>14,k=b*h+j*g,h=g*h+((k&16383)<<14)+c[d]+e;e=(h>>28)+(k>>14)+b*j;c[d++]=h&268435455}return e} +j_lm&&"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=am2,dbits=30):j_lm&&"Netscape"!=navigator.appName?(BigInteger.prototype.am=am1,dbits=26):(BigInteger.prototype.am=am3,dbits=28);BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<=vv;++vv)BI_RC[rr++]=vv;rr=97;for(vv=10;36>vv;++vv)BI_RC[rr++]=vv;rr=65;for(vv=10;36>vv;++vv)BI_RC[rr++]=vv;function int2char(a){return BI_RM.charAt(a)}function intAt(a,b){var c=BI_RC[a.charCodeAt(b)];return null==c?-1:c}function bnpCopyTo(a){for(var b=this.t-1;0<=b;--b)a[b]=this[b];a.t=this.t;a.s=this.s}function bnpFromInt(a){this.t=1;this.s=0>a?-1:0;0a?this[0]=a+DV:this.t=0}function nbv(a){var b=nbi();b.fromInt(a);return b} +function bnpFromString(a,b){var c;if(16==b)c=4;else if(8==b)c=3;else if(256==b)c=8;else if(2==b)c=1;else if(32==b)c=5;else if(4==b)c=2;else{this.fromRadix(a,b);return}this.s=this.t=0;for(var d=a.length,e=!1,f=0;0<=--d;){var g=8==c?a[d]&255:intAt(a,d);0>g?"-"==a.charAt(d)&&(e=!0):(e=!1,0==f?this[this.t++]=g:f+c>this.DB?(this[this.t-1]|=(g&(1<>this.DB-f):this[this.t-1]|=g<=this.DB&&(f-=this.DB))}8==c&&0!=(a[0]&128)&&(this.s=-1,0this.s)return"-"+this.negate().toString(a);if(16==a)a=4;else if(8==a)a=3;else if(2==a)a=1;else if(32==a)a=5;else if(4==a)a=2;else return this.toRadix(a);var b=(1<>g))d=!0,e=int2char(c);for(;0<=f;)g>(g+=this.DB-a)):(c=this[f]>>(g-=a)&b,0>=g&&(g+=this.DB,--f)),0this.s?this.negate():this}function bnCompareTo(a){var b=this.s-a.s;if(0!=b)return b;var c=this.t,b=c-a.t;if(0!=b)return 0>this.s?-b:b;for(;0<=--c;)if(0!=(b=this[c]-a[c]))return b;return 0}function nbits(a){var b=1,c;if(0!=(c=a>>>16))a=c,b+=16;if(0!=(c=a>>8))a=c,b+=8;if(0!=(c=a>>4))a=c,b+=4;if(0!=(c=a>>2))a=c,b+=2;0!=a>>1&&(b+=1);return b} +function bnBitLength(){return 0>=this.t?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(a,b){var c;for(c=this.t-1;0<=c;--c)b[c+a]=this[c];for(c=a-1;0<=c;--c)b[c]=0;b.t=this.t+a;b.s=this.s}function bnpDRShiftTo(a,b){for(var c=a;c>d|g,g=(this[h]&e)<=this.t)b.t=0;else{var d=a%this.DB,e=this.DB-d,f=(1<>d;for(var g=c+1;g>d;0>=this.DB;if(a.t>=this.DB;d+=this.s}else{for(d+=this.s;c>=this.DB;d-=a.s}b.s=0>d?-1:0;-1>d?b[c++]=this.DV+d:0=b.DV)a[c+b.t]-=b.DV,a[c+b.t+1]=1}0=d.t)){var e=this.abs();if(e.t>this.F2:0),k=this.FV/j,j=(1<g&&BigInteger.ZERO.subTo(c,c)}}}}function bnMod(a){var b=nbi();this.abs().divRemTo(a,null,b);0>this.s&&0a.s||0<=a.compareTo(this.m)?a.mod(this.m):a}function cRevert(a){return a}function cReduce(a){a.divRemTo(this.m,null,a)}function cMulTo(a,b,c){a.multiplyTo(b,c);this.reduce(c)}function cSqrTo(a,b){a.squareTo(b);this.reduce(b)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo; +function bnpInvDigit(){if(1>this.t)return 0;var a=this[0];if(0==(a&1))return 0;var b=a&3,b=b*(2-(a&15)*b)&15,b=b*(2-(a&255)*b)&255,b=b*(2-((a&65535)*b&65535))&65535,b=b*(2-a*b%this.DV)%this.DV;return 0>15;this.um=(1<a.s&&0>15)*this.mpl&this.um)<<15)&a.DM,c=b+this.m.t;for(a[c]+=this.m.am(0,d,a,b,0,this.m.t);a[c]>=a.DV;)a[c]-=a.DV,a[++c]++}a.clamp();a.drShiftTo(this.m.t,a);0<=a.compareTo(this.m)&&a.subTo(this.m,a)}function montSqrTo(a,b){a.squareTo(b);this.reduce(b)}function montMulTo(a,b,c){a.multiplyTo(b,c);this.reduce(c)}Montgomery.prototype.convert=montConvert; +Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return 0==(0a)return BigInteger.ONE;var c=nbi(),d=nbi(),e=b.convert(this),f=nbits(a)-1;for(e.copyTo(c);0<=--f;)if(b.sqrTo(c,d),0<(a&1<a||b.isEven()?new Classic(b):new Montgomery(b);return this.exp(a,c)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo; +BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt; +BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var a=nbi();this.copyTo(a);return a}function bnIntValue(){if(0>this.s){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return 0==this.t?this.s:this[0]<<16>>16}function bnpChunkSize(a){return Math.floor(Math.LN2*this.DB/Math.log(a))} +function bnSigNum(){return 0>this.s?-1:0>=this.t||1==this.t&&0>=this[0]?0:1}function bnpToRadix(a){null==a&&(a=10);if(0==this.signum()||2>a||36j?"-"==a.charAt(h)&&0==this.signum()&&(e=!0):(g=b*g+j,++f>=c&&(this.dMultiply(d),this.dAddOffset(g,0),g=f=0))}0a)this.fromInt(1);else{this.fromNumber(a,c);this.testBit(a-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);for(this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(b);)this.dAddOffset(2,0),this.bitLength()>a&&this.subTo(BigInteger.ONE.shiftLeft(a-1),this)}else{c=[];var d=a&7;c.length=(a>>3)+1;b.nextBytes(c);c[0]=0>c)!=(this.s&this.DM)>>c)b[e++]=d|this.s<c?(d=(this[a]&(1<>(c+=this.DB-8)):(d=this[a]>>(c-=8)&255,0>=c&&(c+=this.DB,--a)),0!=(d&128)&&(d|=-256),0==e&&(this.s&128)!=(d&128)&&++e,0this.compareTo(a)?this:a} +function bnMax(a){return 0a?this.rShiftTo(-a,b):this.lShiftTo(a,b);return b} +function bnShiftRight(a){var b=nbi();0>a?this.lShiftTo(-a,b):this.rShiftTo(a,b);return b}function lbit(a){if(0==a)return-1;var b=0;0==(a&65535)&&(a>>=16,b+=16);0==(a&255)&&(a>>=8,b+=8);0==(a&15)&&(a>>=4,b+=4);0==(a&3)&&(a>>=2,b+=2);0==(a&1)&&++b;return b}function bnGetLowestSetBit(){for(var a=0;athis.s?this.t*this.DB:-1}function cbit(a){for(var b=0;0!=a;)a&=a-1,++b;return b} +function bnBitCount(){for(var a=0,b=this.s&this.DM,c=0;c=this.t?0!=this.s:0!=(this[b]&1<>=this.DB;if(a.t>=this.DB;d+=this.s}else{for(d+=this.s;c>=this.DB;d+=a.s}b.s=0>d?-1:0;0d&&(b[c++]=this.DV+d);b.t=c;b.clamp()}function bnAdd(a){var b=nbi();this.addTo(a,b);return b}function bnSubtract(a){var b=nbi();this.subTo(a,b);return b} +function bnMultiply(a){var b=nbi();this.multiplyTo(a,b);return b}function bnSquare(){var a=nbi();this.squareTo(a);return a}function bnDivide(a){var b=nbi();this.divRemTo(a,b,null);return b}function bnRemainder(a){var b=nbi();this.divRemTo(a,null,b);return b}function bnDivideAndRemainder(a){var b=nbi(),c=nbi();this.divRemTo(a,b,c);return[b,c]}function bnpDMultiply(a){this[this.t]=this.am(0,a-1,this,0,0,this.t);++this.t;this.clamp()} +function bnpDAddOffset(a,b){if(0!=a){for(;this.t<=b;)this[this.t++]=0;for(this[b]+=a;this[b]>=this.DV;)this[b]-=this.DV,++b>=this.t&&(this[this.t++]=0),++this[b]}}function NullExp(){}function nNop(a){return a}function nMulTo(a,b,c){a.multiplyTo(b,c)}function nSqrTo(a,b){a.squareTo(b)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(a){return this.exp(a,new NullExp)} +function bnpMultiplyLowerTo(a,b,c){var d=Math.min(this.t+a.t,b);c.s=0;for(c.t=d;0a.s||a.t>2*this.m.t)return a.mod(this.m);if(0>a.compareTo(this.m))return a;var b=nbi();a.copyTo(b);this.reduce(b);return b}function barrettRevert(a){return a} +function barrettReduce(a){a.drShiftTo(this.m.t-1,this.r2);a.t>this.m.t+1&&(a.t=this.m.t+1,a.clamp());this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);for(this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);0>a.compareTo(this.r2);)a.dAddOffset(1,this.m.t+1);for(a.subTo(this.r2,a);0<=a.compareTo(this.m);)a.subTo(this.m,a)}function barrettSqrTo(a,b){a.squareTo(b);this.reduce(b)}function barrettMulTo(a,b,c){a.multiplyTo(b,c);this.reduce(c)}Barrett.prototype.convert=barrettConvert; +Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo; +function bnModPow(a,b){var c=a.bitLength(),d,e=nbv(1),f;if(0>=c)return e;d=18>c?1:48>c?3:144>c?4:768>c?5:6;f=8>c?new Classic(b):b.isEven()?new Barrett(b):new Montgomery(b);var g=[],h=3,j=d-1,k=(1<=j?n=a[m]>>c-j&k:(n=(a[m]&(1<>this.DB+c-j));for(h=d;0==(n&1);)n>>=1,--h;if(0>(c-=h))c+=this.DB,--m;if(p)g[n].copyTo(e), +p=!1;else{for(;1--c&&(c=this.DB-1,--m)}return f.revert(e)} +function bnGCD(a){var b=0>this.s?this.negate():this.clone();a=0>a.s?a.negate():a.clone();if(0>b.compareTo(a)){var c=b,b=a;a=c}var c=b.getLowestSetBit(),d=a.getLowestSetBit();if(0>d)return b;c=a)return 0;var b=this.DV%a,c=0>this.s?a-1:0;if(0h.signum())h.addTo(a,h);else return h;return 0>h.signum()?h.add(a):h} +var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727, +733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=67108864/lowprimes[lowprimes.length-1]; +function bnIsProbablePrime(a){var b,c=this.abs();if(1==c.t&&c[0]<=lowprimes[lowprimes.length-1]){for(b=0;b=c)return!1;var d=b.shiftRight(c);a=a+1>>1;a>lowprimes.length&&(a=lowprimes.length);for(var e=nbi(),f=0;fthis.maxInterestLifetime)return this.callerClosure.upcall(Closure.UPCALL_INTEREST_TIMED_OUT,b);var d=b.interest.clone();d.interestLifetime=c;b.face.expressInterest(d.name,this,d);return Closure.RESULT_OK}return this.callerClosure.upcall(a,b)}catch(e){return console.log("ExponentialReExpressClosure.upcall exception: "+ +e),Closure.RESULT_ERR}};var Blob=function Blob(b,c){null==c&&(c=!0);this.buffer=null==b?null:"object"===typeof b&&b instanceof Blob?b.buffer:"string"===typeof b?new Buffer(b,"utf8"):c?new Buffer(b):"object"===typeof b&&b instanceof Buffer?b:new Buffer(b)};exports.Blob=Blob;Blob.prototype.size=function(){return null!=this.buffer?this.buffer.length:0};Blob.prototype.buf=function(){return this.buffer};Blob.prototype.isNull=function(){return null==this.buffer}; +Blob.prototype.toHex=function(){return null==this.buffer?"":this.buffer.toString("hex")}; +var Blob=require("./blob.js").Blob,SignedBlob=function SignedBlob(b,c,d){Blob.call(this,b);null==this.buffer?this.signedPortionEndOffset=this.signedPortionBeginOffset=0:"object"===typeof b&&b instanceof SignedBlob?(this.signedPortionBeginOffset=null==c?b.signedPortionBeginOffset:c,this.signedPortionEndOffset=null==d?b.signedPortionEndOffset:d):(this.signedPortionBeginOffset=c||0,this.signedPortionEndOffset=d||0);this.signedBuffer=null==this.buffer?null:this.buffer.slice(this.signedPortionBeginOffset, +this.signedPortionEndOffset)};SignedBlob.prototype=new Blob;SignedBlob.prototype.name="SignedBlob";exports.SignedBlob=SignedBlob;SignedBlob.prototype.signedSize=function(){return null!=this.signedBuffer?this.signedBuffer.length:0};SignedBlob.prototype.signedBuf=function(){return null!=this.signedBuffer?this.signedBuffer:null};SignedBlob.prototype.getSignedPortionBeginOffset=function(){return this.signedPortionBeginOffset};SignedBlob.prototype.getSignedPortionEndOffset=function(){return this.signedPortionEndOffset}; +var DynamicBuffer=function(a){a||(a=16);this.array=new Buffer(a)};exports.DynamicBuffer=DynamicBuffer;DynamicBuffer.prototype.ensureLength=function(a){if(!(this.array.length>=a)){var b=2*this.array.length;a>b&&(b=a);a=new Buffer(b);this.array.copy(a);this.array=a}};DynamicBuffer.prototype.copy=function(a,b){this.ensureLength(a.length+b);"object"==typeof a&&a instanceof Buffer?a.copy(this.array,b):(new Buffer(a)).copy(this.array,b)}; +DynamicBuffer.prototype.ensureLengthFromBack=function(a){if(!(this.array.length>=a)){var b=2*this.array.length;a>b&&(b=a);a=new Buffer(b);this.array.copy(a,a.length-this.array.length);this.array=a}};DynamicBuffer.prototype.copyFromBack=function(a,b){this.ensureLengthFromBack(b);"object"==typeof a&&a instanceof Buffer?a.copy(this.array,this.array.length-b):(new Buffer(a)).copy(this.array,this.array.length-b)};DynamicBuffer.prototype.slice=function(a,b){return this.array.slice(a,b)};var DataUtils=function(){}; +exports.DataUtils=DataUtils;DataUtils.keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";DataUtils.stringtoBase64=function(a){var b="",c,d,e="",f,g,h="",j=0;do c=a.charCodeAt(j++),d=a.charCodeAt(j++),e=a.charCodeAt(j++),f=c>>2,c=(c&3)<<4|d>>4,g=(d&15)<<2|e>>6,h=e&63,isNaN(d)?g=h=64:isNaN(e)&&(h=64),b=b+DataUtils.keyStr.charAt(f)+DataUtils.keyStr.charAt(c)+DataUtils.keyStr.charAt(g)+DataUtils.keyStr.charAt(h);while(jl?"a":"p",tt:12>l?"am":"pm",T:12>l?"A":"P",TT:12>l?"AM":"PM",Z:g?"UTC":(String(e).match(b)||[""]).pop().replace(c,""),o:(0XML_UDATA||0>a||0>b)throw Error("Tag and value must be positive, and tag valid.");var c=this.numEncodingBytes(b);this.ostream.ensureLength(this.offset+c);this.ostream.array[this.offset+c-1]=BYTE_MASK&(XML_TT_MASK&a|(XML_TT_VAL_MASK&b)<>>=XML_TT_VAL_BITS;for(var d=this.offset+c-2;0!=b&&d>=this.offset;)this.ostream.array[d]= +BYTE_MASK&b&XML_REG_VAL_MASK,b>>>=XML_REG_VAL_BITS,--d;if(0!=b)throw Error("This should not happen: miscalculated encoding");this.offset+=c;return c}; +BinaryXMLEncoder.prototype.encodeUString=function(a,b){if(null!=a&&!(b==XML_TAG||b==XML_ATTR&&0==a.length)){3>>=XML_TT_VAL_BITS;0!=a;)b++,a>>>=XML_REG_VAL_BITS;return b};BinaryXMLEncoder.prototype.writeDateTimeDTagElement=function(a,b){var c=Math.round(4096*(b.msec/1E3)).toString(16);1==c.length%2&&(c="0"+c);this.writeDTagElement(a,DataUtils.toNumbers(c))}; +BinaryXMLEncoder.prototype.writeDateTime=function(a,b){var c=Math.round(4096*(b.msec/1E3)).toString(16);1==c.length%2&&(c="0"+c);this.writeElement(a,DataUtils.toNumbers(c))}; +BinaryXMLEncoder.prototype.writeString=function(a){if("string"===typeof a){4DEBUG_MAX_LEN)throw new DecodingException(Error("Decoding error: length "+c.val()+1+" longer than expected maximum length!"));var d;d="string"==typeof c.val()?parseInt(c.val())+1:c.val()+1;var e=this.decodeUString(d),a=stringToTag(e)}else c.type()==XML_DTAG&&(a=c.val())}catch(f){}finally{try{this.offset=b}catch(g){throw Log.logStackTrace(Log.FAC_ENCODING, +Level.WARNING,g),Error("Cannot reset stream! "+g.getMessage(),g);}}return a};BinaryXMLDecoder.prototype.readBinaryDTagElement=function(a,b){this.readElementStartDTag(a);return this.readBlob(b)};BinaryXMLDecoder.prototype.readBinaryElement=function(a,b,c){this.readStartElement(a,b);return this.readBlob(c)};BinaryXMLDecoder.prototype.readElementClose=function(){var a=this.input[this.offset++];if(a!=XML_CLOSE)throw new DecodingException(Error("Expected end element, got: "+a));}; +BinaryXMLDecoder.prototype.readEndElement=function(){4d||0==d&&0==b)return null;(c=0==(d&XML_TT_NO_MORE))?(b<<=XML_REG_VAL_BITS,b|=d&XML_REG_VAL_MASK):(a=d&XML_TT_MASK,b<<=XML_TT_VAL_BITS,b|=d>>>XML_TT_BITS&XML_TT_VAL_MASK);this.offset++}while(c);4=a.length)return!1;switch(this.state){case BinaryXMLStructureDecoder.READ_HEADER_OR_CLOSE:if(0==this.headerLength&&a[this.offset]==XML_CLOSE){++this.offset;--this.level;if(0==this.level)return this.gotElementEnd=!0;if(0>this.level)throw Error("BinaryXMLStructureDecoder: Unexpected close tag at offset "+(this.offset-1));this.startHeader();break}for(var c= +this.headerLength;;){if(this.offset>=a.length){this.useHeaderBuffer=!0;var d=this.headerLength-c;this.headerBuffer.copy(a.slice(this.offset-d,d),c);return!1}d=a[this.offset++];++this.headerLength;if(d&XML_TT_NO_MORE)break}this.useHeaderBuffer?(d=this.headerLength-c,this.headerBuffer.copy(a.slice(this.offset-d,d),c),c=(new BinaryXMLDecoder(this.headerBuffer.array)).decodeTypeAndVal()):(b.seek(this.offset-this.headerLength),c=b.decodeTypeAndVal());if(null==c)throw Error("BinaryXMLStructureDecoder: Can't read header starting at offset "+ +(this.offset-this.headerLength));d=c.t;if(d==XML_DATTR)this.startHeader();else if(d==XML_DTAG||d==XML_EXT)++this.level,this.startHeader();else if(d==XML_TAG||d==XML_ATTR)d==XML_TAG&&++this.level,this.nBytesToRead=c.v+1,this.state=BinaryXMLStructureDecoder.READ_BYTES;else if(d==XML_BLOB||d==XML_UDATA)this.nBytesToRead=c.v,this.state=BinaryXMLStructureDecoder.READ_BYTES;else throw Error("BinaryXMLStructureDecoder: Unrecognized header type "+d);break;case BinaryXMLStructureDecoder.READ_BYTES:c=a.length- +this.offset;if(ca)this.length+=1,this.output.ensureLengthFromBack(this.length),this.output.array[this.output.array.length-this.length]=a&255;else if(65535>=a){this.length+=3;this.output.ensureLengthFromBack(this.length);var b=this.output.array.length-this.length;this.output.array[b]=253;this.output.array[b+1]=a>>8&255;this.output.array[b+2]=a&255}else 4294967295>=a?(this.length+=5,this.output.ensureLengthFromBack(this.length),b=this.output.array.length-this.length, +this.output.array[b]=254,this.output.array[b+1]=a>>24&255,this.output.array[b+2]=a>>16&255,this.output.array[b+3]=a>>8&255,this.output.array[b+4]=a&255):(this.length+=9,this.output.ensureLengthFromBack(this.length),b=this.output.array.length-this.length,this.output.array[b]=255,this.output.array[b+1]=a>>56&255,this.output.array[b+2]=a>>48&255,this.output.array[b+3]=a>>40&255,this.output.array[b+4]=a>>32&255,this.output.array[b+5]=a>>24&255,this.output.array[b+6]=a>>16&255,this.output.array[b+7]=a>> +8&255,this.output.array[b+8]=a&255)};TlvEncoder.prototype.writeTypeAndLength=function(a,b){this.writeVarNumber(b);this.writeVarNumber(a)}; +TlvEncoder.prototype.writeNonNegativeIntegerTlv=function(a,b){if(0>b)throw Error("TLV integer value may not be negative");b=Math.round(b);var c=this.length;if(253>b)this.length+=1,this.output.ensureLengthFromBack(this.length),this.output.array[this.output.array.length-this.length]=b&255;else if(65535>=b){this.length+=2;this.output.ensureLengthFromBack(this.length);var d=this.output.array.length-this.length;this.output.array[d]=b>>8&255;this.output.array[d+1]=b&255}else 4294967295>=b?(this.length+= +4,this.output.ensureLengthFromBack(this.length),d=this.output.array.length-this.length,this.output.array[d]=b>>24&255,this.output.array[d+1]=b>>16&255,this.output.array[d+2]=b>>8&255,this.output.array[d+3]=b&255):(this.length+=8,this.output.ensureLengthFromBack(this.length),d=this.output.array.length-this.length,this.output.array[d]=b>>56&255,this.output.array[d+1]=b>>48&255,this.output.array[d+2]=b>>40&255,this.output.array[d+3]=b>>32&255,this.output.array[d+4]=b>>24&255,this.output.array[d+5]=b>> +16&255,this.output.array[d+6]=b>>8&255,this.output.array[d+7]=b&255);this.writeTypeAndLength(a,this.length-c)};TlvEncoder.prototype.writeOptionalNonNegativeIntegerTlv=function(a,b){null!=b&&0<=b&&this.writeNonNegativeIntegerTlv(a,b)};TlvEncoder.prototype.writeBlobTlv=function(a,b){null==b?this.writeTypeAndLength(a,0):(this.length+=b.length,this.output.copyFromBack(b,this.length),this.writeTypeAndLength(a,b.length))}; +TlvEncoder.prototype.writeOptionalBlobTlv=function(a,b){null!=b&&0firstOctet?firstOctet:this.readExtendedVarNumber(firstOctet)}; +TlvDecoder.prototype.readExtendedVarNumber=function(a){253==a?(result=(this.input[this.offset]<<8)+this.input[this.offset+1],this.offset+=2):254==a?(result=(this.input[this.offset]<<24)+(this.input[this.offset+1]<<16)+(this.input[this.offset+2]<<8)+this.input[this.offset+3],this.offset+=4):(result=(this.input[this.offset]<<56)+(this.input[this.offset+1]<<48)+(this.input[this.offset+2]<<40)+(this.input[this.offset+3]<<32)+(this.input[this.offset+4]<<24)+(this.input[this.offset+5]<<16)+(this.input[this.offset+ +6]<<8)+this.input[this.offset+7],this.offset+=8);return result};TlvDecoder.prototype.readTypeAndLength=function(a){if(this.readVarNumber()!=a)throw new DecodingException("Did not get the expected TLV type");a=this.readVarNumber();if(this.offset+a>this.input.length)throw new DecodingException("TLV length exceeds the buffer length");return a};TlvDecoder.prototype.readNestedTlvsStart=function(a){return this.readTypeAndLength(a)+this.offset}; +TlvDecoder.prototype.finishNestedTlvs=function(a){if(this.offset!=a){for(;this.offsetthis.input.length)throw new DecodingException("TLV length exceeds the buffer length");}if(this.offset!=a)throw new DecodingException("TLV length does not equal the total length of the nested TLVs");}}; +TlvDecoder.prototype.peekType=function(a,b){if(this.offset>=b)return!1;var c=this.offset,d=this.readVarNumber();this.offset=c;return d==a}; +TlvDecoder.prototype.readNonNegativeInteger=function(a){var b;if(1==a)b=this.input[this.offset];else if(2==a)b=(this.input[this.offset]<<8)+this.input[this.offset+1];else if(4==a)b=(this.input[this.offset]<<24)+(this.input[this.offset+1]<<16)+(this.input[this.offset+2]<<8)+this.input[this.offset+3];else if(8==a)b=(this.input[this.offset]<<56)+(this.input[this.offset+1]<<48)+(this.input[this.offset+2]<<40)+(this.input[this.offset+3]<<32)+(this.input[this.offset+4]<<24)+(this.input[this.offset+5]<< +16)+(this.input[this.offset+6]<<8)+this.input[this.offset+7];else throw new DecodingException("Invalid length for a TLV nonNegativeInteger");this.offset+=a;return b};TlvDecoder.prototype.readNonNegativeIntegerTlv=function(a){a=this.readTypeAndLength(a);return this.readNonNegativeInteger(a)};TlvDecoder.prototype.readOptionalNonNegativeIntegerTlv=function(a,b){return this.peekType(a,b)?this.readNonNegativeIntegerTlv(a):null}; +TlvDecoder.prototype.readBlobTlv=function(a){a=this.readTypeAndLength(a);var b=this.input.slice(this.offset,this.offset+a);this.offset+=a;return b};TlvDecoder.prototype.readOptionalBlobTlv=function(a,b){return this.peekType(a,b)?this.readBlobTlv(a):null};TlvDecoder.prototype.readBooleanTlv=function(a,b){if(this.peekType(a,b)){var c=this.readTypeAndLength(a);this.offset+=c;return!0}return!1};TlvDecoder.prototype.getOffset=function(){return this.offset}; +TlvDecoder.prototype.seek=function(a){this.offset=a};var TlvDecoder=require("./tlv-decoder.js").TlvDecoder,TlvStructureDecoder=function TlvStructureDecoder(){this.gotElementEnd=!1;this.offset=0;this.state=TlvStructureDecoder.READ_TYPE;this.headerLength=0;this.useHeaderBuffer=!1;this.headerBuffer=new Buffer(8);this.nBytesToRead=0};exports.TlvStructureDecoder=TlvStructureDecoder;TlvStructureDecoder.READ_TYPE=0;TlvStructureDecoder.READ_TYPE_BYTES=1;TlvStructureDecoder.READ_LENGTH=2; +TlvStructureDecoder.READ_LENGTH_BYTES=3;TlvStructureDecoder.READ_VALUE_BYTES=4; +TlvStructureDecoder.prototype.findElementEnd=function(a){if(this.gotElementEnd)return!0;for(var b=new TlvDecoder(a);;){if(this.offset>=a.length)return!1;if(this.state==TlvStructureDecoder.READ_TYPE){var c=a[this.offset];this.offset+=1;253>c?this.state=TlvStructureDecoder.READ_LENGTH:(this.nBytesToRead=253==c?2:254==c?4:8,this.state=TlvStructureDecoder.READ_TYPE_BYTES)}else if(this.state==TlvStructureDecoder.READ_TYPE_BYTES){c=a.length-this.offset;if(cc){this.nBytesToRead=c;if(0==this.nBytesToRead)return this.gotElementEnd=!0;this.state=TlvStructureDecoder.READ_VALUE_BYTES}else this.nBytesToRead=253==c?2:254==c?4:8,this.firstOctet=c,this.state=TlvStructureDecoder.READ_LENGTH_BYTES;else if(this.state==TlvStructureDecoder.READ_LENGTH_BYTES){c=a.length-this.offset;if(!this.useHeaderBuffer&& +c>=this.nBytesToRead)b.seek(this.offset),this.nBytesToRead=b.readExtendedVarNumber(this.firstOctet),this.offset=b.getOffset();else{this.useHeaderBuffer=!0;var d=this.nBytesToRead-this.headerLength;if(d>c){if(this.headerLength+c>headerBuffer.length)throw Error("Cannot store more header bytes than the size of headerBuffer");a.slice(this.offset,this.offset+c).copy(this.headerBuffer,this.headerLength);this.offset+=c;this.headerLength+=c;return!1}if(this.headerLength+d>headerBuffer.length)throw Error("Cannot store more header bytes than the size of headerBuffer"); +a.slice(this.offset,this.offset+d).copy(this.headerBuffer,this.headerLength);this.offset+=d;this.nBytesToRead=(new TlvDecoder(this.headerBuffer)).readExtendedVarNumber(this.firstOctet)}if(0==this.nBytesToRead)return this.gotElementEnd=!0;this.state=TlvStructureDecoder.READ_VALUE_BYTES}else{if(this.state==TlvStructureDecoder.READ_VALUE_BYTES){c=a.length-this.offset;if(c=a.length)break;this.useTlv=a[0]==Tlv.Interest||a[0]==Tlv.Data||128==a[0]?!0:!1}var b,c;this.useTlv?(this.tlvStructureDecoder.seek(0),b=this.tlvStructureDecoder.findElementEnd(a),c=this.tlvStructureDecoder.getOffset()):(this.binaryXmlStructureDecoder.seek(0),b=this.binaryXmlStructureDecoder.findElementEnd(a),c=this.binaryXmlStructureDecoder.offset);if(b){this.dataParts.push(a.slice(0,c));b=DataUtils.concatArrays(this.dataParts); +this.dataParts=[];try{this.elementListener.onReceivedElement(b)}catch(d){console.log("ElementReader: ignoring exception from onReceivedElement: "+d)}a=a.slice(c,a.length);this.binaryXmlStructureDecoder=new BinaryXMLStructureDecoder;this.tlvStructureDecoder=new TlvStructureDecoder;if(0==a.length)break}else{this.dataParts.push(a);3b)throw Error("Invalid publisher ID, got unexpected type");this.publisherID=a.readBinaryDTagElement(b);if(null==this.publisherID)throw new DecodingException(Error("Cannot parse publisher ID of type : "+b+"."));}; +PublisherID.prototype.to_ndnb=function(a){if(!this.validate())throw Error("Cannot encode "+this.getClass().getName()+": field values missing.");a.writeDTagElement(this.getElementLabel(),this.publisherID)}; +PublisherID.peekAndGetNextDTag=function(a){return a.peekDTag(NDNProtocolDTags.PublisherPublicKeyDigest)?NDNProtocolDTags.PublisherPublicKeyDigest:a.peekDTag(NDNProtocolDTags.PublisherCertificateDigest)?NDNProtocolDTags.PublisherCertificateDigest:a.peekDTag(NDNProtocolDTags.PublisherIssuerKeyDigest)?NDNProtocolDTags.PublisherIssuerKeyDigest:a.peekDTag(NDNProtocolDTags.PublisherIssuerCertificateDigest)?NDNProtocolDTags.PublisherIssuerCertificateDigest:-1};PublisherID.peek=function(a){return 0<=PublisherID.peekAndGetNextDTag(a)}; +PublisherID.prototype.getElementLabel=function(){return this.publisherType.Tag};PublisherID.prototype.validate=function(){return null!=id()&&null!=type()};Blob=require("./util/blob.js").Blob;DataUtils=require("./encoding/data-utils.js").DataUtils;BinaryXMLEncoder=require("./encoding/binary-xml-encoder.js").BinaryXMLEncoder;BinaryXMLDecoder=require("./encoding/binary-xml-decoder.js").BinaryXMLDecoder;NDNProtocolDTags=require("./util/ndn-protoco-id-tags.js").NDNProtocolDTags;LOG=require("./log.js").Log.LOG; +Name=function Name(b){if("string"==typeof b)3=a.length)return[];var b=a.indexOf(":");if(0<=b){var c=a.indexOf("/");if(0>c||bb)return[];a=a.substr(b+1,a.length-b-1).trim()}else a=a.substr(1,a.length-1).trim();a=a.split("/");for(b=0;ba?this.getSubName(0,this.components.length+a):this.getSubName(0,a)};Name.prototype.cut=function(a){return new Name(this.components.slice(0,this.components.length-a))};Name.prototype.size=function(){return this.components.length}; +Name.prototype.get=function(a){if(0<=a){if(a>=this.components.length)throw Error("Name.get: Index is out of bounds");return new Name.Component(this.components[a])}if(a<-this.components.length)throw Error("Name.get: Index is out of bounds");return new Name.Component(this.components[this.components.length- -a])};Name.prototype.getComponentCount=function(){return this.components.length};Name.prototype.getComponent=function(a){return new Buffer(this.components[a].getValue())}; +Name.prototype.indexOfFileName=function(){for(var a=this.size()-1;0<=a;--a){var b=this.components[a].getValue();if(!(0>=b.length)&&!(0==b[0]||192==b[0]||193==b[0]||245<=b[0]&&255>=b[0]))return a}return-1};Name.prototype.equals=function(a){if(this.components.length!=a.components.length)return!1;for(var b=this.components.length-1;0<=b;--b)if(!this.components[b].equals(a.components[b]))return!1;return!0};Name.prototype.equalsName=function(a){return this.equals(a)}; +Name.prototype.getContentDigestValue=function(){for(var a=this.size()-1;0<=a;--a){var b=Name.getComponentContentDigestValue(this.components[a]);if(null!=b)return b}return null}; +Name.getComponentContentDigestValue=function(a){"object"==typeof a&&a instanceof Name.Component&&(a=a.getValue());return a.length==Name.ContentDigestPrefix.length+32+Name.ContentDigestSuffix.length&&DataUtils.arraysEqual(a.slice(0,Name.ContentDigestPrefix.length),Name.ContentDigestPrefix)&&DataUtils.arraysEqual(a.slice(a.length-Name.ContentDigestSuffix.length,a.length),Name.ContentDigestSuffix)?a.slice(Name.ContentDigestPrefix.length,Name.ContentDigestPrefix.length+32):null}; +Name.ContentDigestPrefix=new Buffer([193,46,77,46,71,193,1,170,2,133]);Name.ContentDigestSuffix=new Buffer([0]);Name.toEscapedString=function(a){"object"==typeof a&&a instanceof Name.Component&&(a=a.getValue());for(var b="",c=!1,d=0;d=c||65<=c&&90>=c||97<=c&&122>=c||43==c||45==c||46==c||95==c?b+String.fromCharCode(c):b+("%"+(16>c?"0":"")+c.toString(16).toUpperCase());else{b="...";for(d=0;d=a.length?null:DataUtils.toNumbersFromString(a.substr(3,a.length-3)):DataUtils.toNumbersFromString(a)};Name.prototype.match=function(a){var b=this.components;a=a.components;if(b.length>a.length)return!1;for(var c=0;cthis.freshnessSeconds?null:1E3*this.freshnessSeconds};MetaInfo.prototype.getFinalBlockID=function(){return this.finalBlockID};MetaInfo.prototype.setType=function(a){this.type=null==a||0>a?ContentType.BLOB:a};MetaInfo.prototype.setFreshnessPeriod=function(a){this.freshnessSeconds=null==a||0>a?null:a/1E3}; +MetaInfo.prototype.setFinalBlockID=function(a){this.finalBlockID=null==a?null:"object"===typeof a&&a instanceof Blob?a.buf():"object"===typeof a&&a instanceof Name.Component?a.getValue():new Buffer(a)}; +MetaInfo.prototype.setFields=function(){var a=globalKeyManager.getKey();this.publisher=new PublisherPublicKeyDigest(a.getKeyID());var b=(new Date).getTime();this.timestamp=new NDNTime(b);4Exclude.compareComponents(a,e))return!0}else if(0>Exclude.compareComponents(a,e))return!0;b=d-1}else if(null!=c){if(0b.length)return 1;for(var c=0;cb[c])return 1}return 0}; +var Blob=require("./util/blob.js").Blob,Name=require("./name.js").Name,Exclude=require("./exclude.js").Exclude,PublisherPublicKeyDigest=require("./publisher-public-key-digest.js").PublisherPublicKeyDigest,KeyLocator=require("./key-locator.js").KeyLocator,WireFormat=require("./encoding/wire-format.js").WireFormat,Interest=function Interest(b,c,d,e,f,g,h,j,k,m){"object"===typeof b&&b instanceof Interest?(b.name&&(this.name=new Name(b.name)),this.maxSuffixComponents=b.maxSuffixComponents,this.minSuffixComponents= +b.minSuffixComponents,this.publisherPublicKeyDigest=b.publisherPublicKeyDigest,this.keyLocator=new KeyLocator(b.keyLocator),this.exclude=new Exclude(b.exclude),this.childSelector=b.childSelector,this.answerOriginKind=b.answerOriginKind,this.scope=b.scope,this.interestLifetime=b.interestLifetime,b.nonce&&(this.nonce=new Buffer(b.nonce))):(this.name="object"===typeof b&&b instanceof Name?new Name(b):new Name,this.maxSuffixComponents=d,this.minSuffixComponents=c,this.publisherPublicKeyDigest=e,this.keyLocator= +new KeyLocator,this.exclude="object"===typeof f&&f instanceof Exclude?new Exclude(f):new Exclude,this.childSelector=g,this.answerOriginKind=h,this.scope=j,this.interestLifetime=k,m&&(this.nonce=new Buffer(m)))};exports.Interest=Interest;Interest.RECURSIVE_POSTFIX="*";Interest.CHILD_SELECTOR_LEFT=0;Interest.CHILD_SELECTOR_RIGHT=1;Interest.ANSWER_NO_CONTENT_STORE=0;Interest.ANSWER_CONTENT_STORE=1;Interest.ANSWER_GENERATED=2;Interest.ANSWER_STALE=4;Interest.MARK_STALE=16; +Interest.DEFAULT_ANSWER_ORIGIN_KIND=Interest.ANSWER_CONTENT_STORE|Interest.ANSWER_GENERATED;Interest.prototype.matchesName=function(a){return!this.name.match(a)||null!=this.minSuffixComponents&&!(a.size()+1-this.name.size()>=this.minSuffixComponents)||null!=this.maxSuffixComponents&&!(a.size()+1-this.name.size()<=this.maxSuffixComponents)||null!=this.exclude&&a.size()>this.name.size()&&this.exclude.matches(a.components[this.name.size()])?!1:!0};Interest.prototype.matches_name=function(a){return this.matchesName(a)}; +Interest.prototype.clone=function(){return new Interest(this.name,this.minSuffixComponents,this.maxSuffixComponents,this.publisherPublicKeyDigest,this.exclude,this.childSelector,this.answerOriginKind,this.scope,this.interestLifetime,this.nonce)};Interest.prototype.getName=function(){return this.name};Interest.prototype.getMinSuffixComponents=function(){return this.minSuffixComponents};Interest.prototype.getMaxSuffixComponents=function(){return this.maxSuffixComponents}; +Interest.prototype.getKeyLocator=function(){return this.keyLocator};Interest.prototype.getExclude=function(){return this.exclude};Interest.prototype.getChildSelector=function(){return this.childSelector};Interest.prototype.getAnswerOriginKind=function(){return this.answerOriginKind};Interest.prototype.getMustBeFresh=function(){return null==this.answerOriginKind||0>this.answerOriginKind?!0:0==(this.answerOriginKind&Interest.ANSWER_STALE)};Interest.prototype.getNonce=function(){return this.nonce}; +Interest.prototype.getScope=function(){return this.scope};Interest.prototype.getInterestLifetimeMilliseconds=function(){return this.interestLifetime};Interest.prototype.setName=function(a){this.nonce=null;this.name="object"===typeof a&&a instanceof Interest?new Name(a):new Name};Interest.prototype.setMinSuffixComponents=function(a){this.nonce=null;this.minSuffixComponents=a};Interest.prototype.setMaxSuffixComponents=function(a){this.nonce=null;this.maxSuffixComponents=a}; +Interest.prototype.setExclude=function(a){this.nonce=null;this.exclude="object"===typeof a&&a instanceof Exclude?new Exclude(a):new Exclude};Interest.prototype.setChildSelector=function(a){this.nonce=null;this.childSelector=a};Interest.prototype.setAnswerOriginKind=function(a){this.nonce=null;this.answerOriginKind=a}; +Interest.prototype.setMustBeFresh=function(a){this.nonce=null;null==this.answerOriginKind||0>this.answerOriginKind?a||(this.answerOriginKind=Interest.ANSWER_STALE):this.answerOriginKind=a?this.answerOriginKind&~Interest.ANSWER_STALE:this.answerOriginKind|Interest.ANSWER_STALE};Interest.prototype.setScope=function(a){this.nonce=null;this.scope=a};Interest.prototype.setInterestLifetimeMilliseconds=function(a){this.nonce=null;this.interestLifetime=a}; +Interest.prototype.setNonce=function(a){this.nonce=a?new Buffer(a):null}; +Interest.prototype.toUri=function(){var a="";null!=this.minSuffixComponents&&(a+="&ndn.MinSuffixComponents="+this.minSuffixComponents);null!=this.maxSuffixComponents&&(a+="&ndn.MaxSuffixComponents="+this.maxSuffixComponents);null!=this.childSelector&&(a+="&ndn.ChildSelector="+this.childSelector);null!=this.answerOriginKind&&(a+="&ndn.AnswerOriginKind="+this.answerOriginKind);null!=this.scope&&(a+="&ndn.Scope="+this.scope);null!=this.interestLifetime&&(a+="&ndn.InterestLifetime="+this.interestLifetime); +null!=this.publisherPublicKeyDigest&&(a+="&ndn.PublisherPublicKeyDigest="+Name.toEscapedString(this.publisherPublicKeyDigest.publisherPublicKeyDigest));null!=this.nonce&&(a+="&ndn.Nonce="+Name.toEscapedString(this.nonce));null!=this.exclude&&0a.getNonce().length){var d=Buffer(4);0e;++e)d[e]=crypto.randomBytes(1)[0]; +b.writeBlobTlv(Tlv.Nonce,d)}else 4==a.getNonce().length?b.writeBlobTlv(Tlv.Nonce,a.getNonce()):b.writeBlobTlv(Tlv.Nonce,a.getNonce().slice(0,4));Tlv0_1a2WireFormat.encodeSelectors(a,b);Tlv0_1a2WireFormat.encodeName(a.getName(),b);b.writeTypeAndLength(Tlv.Interest,b.getLength()-c);return new Blob(b.getOutput(),!1)}; +Tlv0_1a2WireFormat.prototype.decodeInterest=function(a,b){var c=new TlvDecoder(b),d=c.readNestedTlvsStart(Tlv.Interest);Tlv0_1a2WireFormat.decodeName(a.getName(),c);c.peekType(Tlv.Selectors,d)&&Tlv0_1a2WireFormat.decodeSelectors(a,c);var e=c.readBlobTlv(Tlv.Nonce);a.setScope(c.readOptionalNonNegativeIntegerTlv(Tlv.Scope,d));a.setInterestLifetimeMilliseconds(c.readOptionalNonNegativeIntegerTlv(Tlv.InterestLifetime,d));a.setNonce(e);c.finishNestedTlvs(d)}; +Tlv0_1a2WireFormat.prototype.encodeData=function(a){var b=new TlvEncoder(1500),c=b.getLength();b.writeBlobTlv(Tlv.SignatureValue,a.getSignature().getSignature());var d=b.getLength();Tlv0_1a2WireFormat.encodeSignatureSha256WithRsaValue(a.getSignature(),b,a.getSignatureOrMetaInfoKeyLocator());b.writeBlobTlv(Tlv.Content,a.getContent());Tlv0_1a2WireFormat.encodeMetaInfo(a.getMetaInfo(),b);Tlv0_1a2WireFormat.encodeName(a.getName(),b);a=b.getLength();b.writeTypeAndLength(Tlv.Data,b.getLength()-c);c=b.getLength()- +a;d=b.getLength()-d;return{encoding:new Blob(b.getOutput(),!1),signedPortionBeginOffset:c,signedPortionEndOffset:d}}; +Tlv0_1a2WireFormat.prototype.decodeData=function(a,b){var c=new TlvDecoder(b),d=c.readNestedTlvsStart(Tlv.Data),e=c.getOffset();Tlv0_1a2WireFormat.decodeName(a.getName(),c);Tlv0_1a2WireFormat.decodeMetaInfo(a.getMetaInfo(),c);a.setContent(c.readBlobTlv(Tlv.Content));Tlv0_1a2WireFormat.decodeSignatureInfo(a,c);null!=a.getSignature()&&(null!=a.getSignature().getKeyLocator()&&null!=a.getMetaInfo())&&(a.getMetaInfo().locator=a.getSignature().getKeyLocator());var f=c.getOffset();a.getSignature().setSignature(c.readBlobTlv(Tlv.SignatureValue)); +c.finishNestedTlvs(d);return{signedPortionBeginOffset:e,signedPortionEndOffset:f}};Tlv0_1a2WireFormat.get=function(){null===Tlv0_1a2WireFormat.instance&&(Tlv0_1a2WireFormat.instance=new Tlv0_1a2WireFormat);return Tlv0_1a2WireFormat.instance};Tlv0_1a2WireFormat.encodeName=function(a,b){for(var c=b.getLength(),d=a.size()-1;0<=d;--d)b.writeBlobTlv(Tlv.NameComponent,a.get(d).getValue());b.writeTypeAndLength(Tlv.Name,b.getLength()-c)}; +Tlv0_1a2WireFormat.decodeName=function(a,b){a.clear();for(var c=b.readNestedTlvsStart(Tlv.Name);b.getOffset()"):a.signedInfo.locator.type==KeyLocatorType.KEY_LOCATOR_DIGEST?b+("KeyLocatorDigest: "+DataUtils.toHex(a.signedInfo.locator.getKeyData()).toLowerCase()+"
"):a.signedInfo.locator.type==KeyLocatorType.CERTIFICATE?b+("Certificate: "+DataUtils.toHex(a.signedInfo.locator.certificate).toLowerCase()+"
"):a.signedInfo.locator.type==KeyLocatorType.KEYNAME?b+("KeyName: "+a.signedInfo.locator.keyName.contentName.to_uri()+ +"
"):b+("[unrecognized ndn_KeyLocatorType "+a.signedInfo.locator.type+"]
"))}return b};EncodingUtils.contentObjectToHtml=function(a){return EncodingUtils.dataToHtml(a)}; +var encodeToHexInterest=function(a){return EncodingUtils.encodeToHexInterest(a)},encodeToHexContentObject=function(a){return EncodingUtils.encodeToHexData(a)},encodeForwardingEntry=function(a){return EncodingUtils.encodeForwardingEntry(a)},decodeHexFaceInstance=function(a){return EncodingUtils.decodeHexFaceInstance(a)},decodeHexInterest=function(a){return EncodingUtils.decodeHexInterest(a)},decodeHexContentObject=function(a){return EncodingUtils.decodeHexData(a)},decodeHexForwardingEntry=function(a){return EncodingUtils.decodeHexForwardingEntry(a)}, +decodeSubjectPublicKeyInfo=function(a){return EncodingUtils.decodeSubjectPublicKeyInfo(a)},contentObjectToHtml=function(a){return EncodingUtils.dataToHtml(a)};function encodeToBinaryInterest(a){return a.wireEncode().buf()}function encodeToBinaryContentObject(a){return a.wireEncode().buf()} +var crypto=require("crypto"),DataUtils=require("./encoding/data-utils.js").DataUtils,Name=require("./name.js").Name,Interest=require("./interest.js").Interest,Data=require("./data.js").Data,MetaInfo=require("./meta-info.js").MetaInfo,ForwardingEntry=require("./forwarding-entry.js").ForwardingEntry,TlvWireFormat=require("./encoding/tlv-wire-format.js").TlvWireFormat,BinaryXmlWireFormat=require("./encoding/binary-xml-wire-format.js").BinaryXmlWireFormat,Tlv=require("./encoding/tlv/tlv.js").Tlv,TlvDecoder= +require("./encoding/tlv/tlv-decoder.js").TlvDecoder,BinaryXMLDecoder=require("./encoding/binary-xml-decoder.js").BinaryXMLDecoder,BinaryXMLEncoder=require("./encoding/binary-xml-encoder.js").BinaryXMLEncoder,NDNProtocolDTags=require("./util/ndn-protoco-id-tags.js").NDNProtocolDTags,Key=require("./key.js").Key,KeyLocatorType=require("./key-locator.js").KeyLocatorType,ForwardingFlags=require("./forwarding-flags.js").ForwardingFlags,Closure=require("./closure.js").Closure,UpcallInfo=require("./closure.js").UpcallInfo, +TcpTransport=require("./transport/tcp-transport.js").TcpTransport,LOG=require("./log.js").Log.LOG,Face=function Face(b){if(!Face.supported)throw Error("The necessary JavaScript support is not available on this platform.");b=b||{};this.transport=(b.getTransport||function(){return new TcpTransport})();this.getHostAndPort=b.getHostAndPort||this.transport.defaultGetHostAndPort;this.host=void 0!==b.host?b.host:null;this.port=b.port||("undefined"!=typeof WebSocketTransport?9696:6363);this.readyStatus=Face.UNOPEN; +this.verify=void 0!==b.verify?b.verify:!1;this.onopen=b.onopen||function(){3b.keyName.contentName.components.length))b=Face.KeyStore[c];return b};Face.prototype.close=function(){if(this.readyStatus!=Face.OPENED)throw Error("Cannot close because Face connection is not opened.");this.readyStatus=Face.CLOSED;this.transport.close()};Face.PITTable=[]; +var PITEntry=function(a,b){this.interest=a;this.closure=b;this.timerID=-1};Face.extractEntriesForExpressedInterest=function(a){for(var b=[],c=Face.PITTable.length-1;0<=c;--c){var d=Face.PITTable[c];d.interest.matchesName(a)&&(clearTimeout(d.timerID),b.push(d),Face.PITTable.splice(c,1))}return b};Face.registeredPrefixTable=[];var RegisteredPrefix=function(a,b){this.prefix=a;this.closure=b}; +function getEntryForRegisteredPrefix(a){for(var b=-1,c=0;cb||Face.registeredPrefixTable[c].prefix.size()>Face.registeredPrefixTable[b].prefix.size()))b=c;return 0<=b?Face.registeredPrefixTable[b]:null} +Face.makeShuffledGetHostAndPort=function(a,b){a=a.slice(0,a.length);DataUtils.shuffle(a);return function(){return 0==a.length?null:{host:a.splice(0,1)[0],port:b}}}; +Face.prototype.expressInterest=function(a,b,c,d){b&&b.upcall&&"function"==typeof b.upcall?c?this.expressInterestWithClosure(a,b,c):this.expressInterestWithClosure(a,b):("object"==typeof a&&a instanceof Interest?(a=new Interest(a),c=c?c:function(){}):(a=new Interest(a),b&&"object"==typeof b&&b instanceof Interest?(a.minSuffixComponents=b.minSuffixComponents,a.maxSuffixComponents=b.maxSuffixComponents,a.publisherPublicKeyDigest=b.publisherPublicKeyDigest,a.exclude=b.exclude,a.childSelector=b.childSelector, +a.answerOriginKind=b.answerOriginKind,a.scope=b.scope,a.interestLifetime=b.interestLifetime,b=c,c=d?d:function(){}):(a.interestLifetime=4E3,c=c?c:function(){})),this.expressInterestWithClosure(a,new Face.CallbackClosure(b,c)))};Face.CallbackClosure=function(a,b,c,d,e){Closure.call(this);this.onData=a;this.onTimeout=b;this.onInterest=c;this.prefix=d;this.transport=e}; +Face.CallbackClosure.prototype.upcall=function(a,b){if(a==Closure.UPCALL_CONTENT||a==Closure.UPCALL_CONTENT_UNVERIFIED)this.onData(b.interest,b.data);else if(a==Closure.UPCALL_INTEREST_TIMED_OUT)this.onTimeout(b.interest);else if(a==Closure.UPCALL_INTEREST)this.onInterest(this.prefix,b.interest,this.transport);return Closure.RESULT_OK}; +Face.prototype.expressInterestWithClosure=function(a,b,c){var d=new Interest(a);null!=c?(d.minSuffixComponents=c.minSuffixComponents,d.maxSuffixComponents=c.maxSuffixComponents,d.publisherPublicKeyDigest=c.publisherPublicKeyDigest,d.exclude=c.exclude,d.childSelector=c.childSelector,d.answerOriginKind=c.answerOriginKind,d.scope=c.scope,d.interestLifetime=c.interestLifetime):d.interestLifetime=4E3;if(null==this.host||null==this.port)if(null==this.getHostAndPort)console.log("ERROR: host OR port NOT SET"); +else{var e=this;this.connectAndExecute(function(){e.reconnectAndExpressInterest(d,b)})}else this.reconnectAndExpressInterest(d,b)};Face.prototype.reconnectAndExpressInterest=function(a,b){if(this.transport.connectedHost!=this.host||this.transport.connectedPort!=this.port){var c=this;this.transport.connect(c,function(){c.expressInterestHelper(a,b)});this.readyStatus=Face.OPENED}else this.expressInterestHelper(a,b)}; +Face.prototype.expressInterestHelper=function(a,b){var c=a.wireEncode(),d=this;if(null!=b){var e=new PITEntry(a,b);Face.PITTable.push(e);b.pitEntry=e;var f=a.interestLifetime||4E3,g=function(){1b.data.getName().size()||!b.data.getName().get(0).equals(c.get(0))||!b.data.getName().get(2).equals(c.get(2)))this.onRegisterFailed(this.prefix);else return Closure.RESULT_OK}; +Face.prototype.registerPrefixHelper=function(a,b,c,d){c=new ForwardingEntry("selfreg",a,null,null,c,null);var e=new BinaryXMLEncoder;c.to_ndnb(e);c=e.getReducedOstream();e=new MetaInfo;e.setFields();c=new Data((new Name).append(crypto.randomBytes(4)),e,c);c.sign(BinaryXmlWireFormat.get());c=c.wireEncode(BinaryXmlWireFormat.get());c=new Name(["ndnx",this.ndndid,"selfreg",c]);c=new Interest(c);c.setInterestLifetimeMilliseconds(4E3);c.setScope(1);3 - -

<%= header %>

- - <%= include localCam %> + +<%= include logTop %> - <%= include remoteStreams %> +
+

<%= title %>

- - -<%= include layoutBottom %> \ No newline at end of file + Login + Signup +
+ +<%= include logBottom %> \ No newline at end of file diff --git a/views/localCam.ejs b/views/localCam.ejs index c0d7ed8..fdfa88d 100644 --- a/views/localCam.ejs +++ b/views/localCam.ejs @@ -2,15 +2,14 @@

Local Camera

-

Username :

-

Private :

+

Stream name :

  • -
    +

    Share this link :

    diff --git a/views/logBottom.ejs b/views/logBottom.ejs new file mode 100644 index 0000000..17c7245 --- /dev/null +++ b/views/logBottom.ejs @@ -0,0 +1,3 @@ +
    + + \ No newline at end of file diff --git a/views/logTop.ejs b/views/logTop.ejs new file mode 100644 index 0000000..38c52fd --- /dev/null +++ b/views/logTop.ejs @@ -0,0 +1,12 @@ + + + + <%= title %> + + + + + +
    \ No newline at end of file diff --git a/views/login.ejs b/views/login.ejs new file mode 100644 index 0000000..e4c91b7 --- /dev/null +++ b/views/login.ejs @@ -0,0 +1,34 @@ + +<%= include logTop %> + +
    + +

    Login

    + + + <% if (message.length > 0) { %> +
    <%= message %>
    + <% } %> + + +
    +
    + + +
    +
    + + +
    + + +
    + +
    + +

    Need an account? Signup

    +

    Or go home.

    + +
    + +<%= include logBottom %> \ No newline at end of file diff --git a/views/main.ejs b/views/main.ejs new file mode 100644 index 0000000..ac387d1 --- /dev/null +++ b/views/main.ejs @@ -0,0 +1,21 @@ +<%= include layoutTop %> + +

    <%= header %>

    +

    Hello <%= user %>

    + + <%= include localCam %> + + <%= include remoteStreams %> + + + +<%= include layoutBottom %> \ No newline at end of file diff --git a/views/remoteStreams.ejs b/views/remoteStreams.ejs index 761eba2..0650ba9 100644 --- a/views/remoteStreams.ejs +++ b/views/remoteStreams.ejs @@ -3,6 +3,7 @@

    Remote Streams

    + @@ -18,4 +19,9 @@
    + +
  • + Refresh +
  • +
    \ No newline at end of file diff --git a/views/signup.ejs b/views/signup.ejs new file mode 100644 index 0000000..b3c53fe --- /dev/null +++ b/views/signup.ejs @@ -0,0 +1,33 @@ +<%= include logTop %> + +
    + +

    Signup

    + + + <% if (message.length > 0) { %> +
    <%= message %>
    + <% } %> + + +
    +
    + + +
    +
    + + +
    + + +
    + +
    + +

    Already have an account? Login

    +

    Or go home.

    + +
    + +<%= include logBottom %> \ No newline at end of file