Example #1
0
File: Knot.js Project: Floby/nigel
function md5 (str) {
    var h = crypto.createHash('md5');
    h.update(str);
    return h.digest('hex');
}
Example #2
0
User.statics.hash = User.hash = function(login, rawPass) {
    var hash = crypto.createHash('sha1');
    hash.update('' + login + config.get('auth:secret') + rawPass, 'utf8');

    return hash.digest('hex');
};
Example #3
0
 validOldKey: function (key, encrypted) {
   return encrypted === crypto.createHash('sha1').update(key).digest('hex');
 }
Example #4
0
 encryptPassword: function(plainText, salt) {
   var hash = crypto.createHash('sha1');
   hash.update(plainText);
   hash.update(salt);
   return hash.digest('hex')
 }
// a filter that just verifies a shasum
function HashStream() {
  Stream.call(this);

  this.readable = this.writable = true;
  this._hasher = crypto.createHash('sha1');
}
 me.generateMD5 = function(data){
     var hash = crypto.createHash('md5');
     hash.update(data);
     return hash.digest('hex');
 }
                json.id = function () {

                    var crypto = require('crypto');
                    var name = json.title;
                    return crypto.createHash('md5').update(name).digest('hex');
                }();
Example #8
0
module.exports = function compile_self(base_path, src_path, lib_path, start_time) {
    var output_options = {'beautify': true, 'private_scope': false, 'omit_baselib': true, 'write_name': false};
	var baselib = RapydScript.parse_baselib(src_path, true);

    function timed(name, cont) {
        var t1 = new Date().getTime();
        console.log('Compiling', name, '...');
        var ret = cont();
        console.log('Compiled in', (new Date().getTime() - t1)/1000, 'seconds\n');
        return ret;
    }

	function parse_file(code, file) {
		return RapydScript.parse(code, {
			filename: file,
			readfile: fs.readFileSync,
			basedir: path.dirname(file),
			auto_bind: false,
			libdir: path.join(src_path, 'lib'),
		});
	}


    var saved_hashes = {}, hashes = {}, compiled = {};
    var compiler_changed = false, sha1sum;
    var signatures = path.join(lib_path, 'signatures.json');
    try {
        saved_hashes = JSON.parse(fs.readFileSync(signatures, 'utf-8'));
    } catch (e) {
        if (e.code != 'ENOENT') throw (e);
    }

    sha1sum = crypto.createHash('sha1');
    RapydScript.FILES.concat([module.filename, path.join(base_path, 'tools', 'compiler.js')]).forEach(function (fpath) {
        sha1sum.update(fs.readFileSync(fpath));
    });
    hashes['#compiler#'] = sha1sum.digest('hex');
    RapydScript.FILENAMES.forEach(function (fname) {
        var src = path.join(src_path, fname + '.pyj');
        var h = crypto.createHash('sha1');
        h.update(fs.readFileSync(src));
        hashes[fname] = h.digest('hex');
    });
    compiler_changed = (hashes['#compiler#'] != saved_hashes['#compiler#']) ? true : false;
    function changed(name) {
        return compiler_changed || hashes[name] != saved_hashes[name];
    }

    function generate_baselib() {
//        var output = '';
//        Object.keys(baselib).forEach(function(key) {
//            output += String(baselib[key]) + '\n\n';
//        });
//        return output;
        timed('baselib', function() {
            var src = path.join(src_path, 'baselib.pyj');
            var toplevel = parse_file('', src);
            Object.keys(baselib).forEach(function(key){
                toplevel.baselib[key] = true;
            });
            var output = RapydScript.OutputStream({
                'beautify': true,
                'private_scope': false,
                'omit_baselib': false,
                'write_name': false,
                'baselib': baselib
            });
            toplevel.print(output);
            compiled['baselib'] = output.get();
        });
    }

//    if (changed('baselib')) compiled.baselib = timed('baselib', generate_baselib);
    generate_baselib();
    if (changed('baselib')) generate_baselib();
    RapydScript.FILENAMES.slice(1).forEach(function (fname) {
        if (changed(fname)) {
            var src = path.join(src_path, fname + '.pyj');
            timed(fname, function() {
                var toplevel = parse_file(fs.readFileSync(src, "utf-8"), src);
                var output = RapydScript.OutputStream(output_options);
                toplevel.print(output);
                compiled[fname] = output.get();
            });
        }
    });
    console.log('Compiling RapydScript succeeded (', (new Date().getTime() - start_time)/1000, 'seconds ), writing output...');
    Object.keys(compiled).forEach(function (fname) {
        fs.writeFileSync(path.join(lib_path, fname + '.js'), compiled[fname], "utf8");
    });
    fs.writeFileSync(signatures, JSON.stringify(hashes, null, 4));
};
Example #9
0
 RapydScript.FILENAMES.forEach(function (fname) {
     var src = path.join(src_path, fname + '.pyj');
     var h = crypto.createHash('sha1');
     h.update(fs.readFileSync(src));
     hashes[fname] = h.digest('hex');
 });
Example #10
0
"use strict";var crypto=require("crypto");var fs=require("fs");var utils=require("./utils");var ENCODING="utf8";var UNDEFINED="undefined";var FUNCTION="function";var REG_1=/[\n\r\t]+/g;var REG_2=/\s{2,}/g;exports.parseMULTIPART=function(req,contentType,maximumSize,tmpDirectory,onXSS,callback){var parser=new MultipartParser;var boundary=contentType.split(";")[1];var isFile=false;var size=0;var stream=null;var tmp={name:"",value:"",contentType:"",fileName:"",fileNameTmp:"",fileSize:0,isFile:false,step:0,width:0,height:0};var ip=req.ip.replace(/\./g,"");var close=0;var isXSS=false;var rm=null;boundary=boundary.substring(boundary.indexOf("=")+1);req.buffer_exceeded=false;req.buffer_has=true;parser.initWithBoundary(boundary);parser.onPartBegin=function(){tmp.value="";tmp.fileSize=0;tmp.step=0;tmp.isFile=false};parser.onHeaderValue=function(buffer,start,end){if(req.buffer_exceeded)return;if(isXSS)return;var arr=buffer.slice(start,end).toString(ENCODING).split(";");if(tmp.step===1){tmp.contentType=arr[0];tmp.step=2;return}if(tmp.step!==0)return;tmp.name=arr[1].substring(arr[1].indexOf("=")+2);tmp.name=tmp.name.substring(0,tmp.name.length-1);tmp.step=1;if(arr.length!==3)return;tmp.fileName=arr[2].substring(arr[2].indexOf("=")+2);tmp.fileName=tmp.fileName.substring(0,tmp.fileName.length-1);tmp.isFile=true;tmp.fileNameTmp=utils.combine(tmpDirectory,ip+"-"+(new Date).getTime()+"-"+utils.random(1e5)+".upload");stream=fs.createWriteStream(tmp.fileNameTmp,{flags:"w"});stream.once("close",function(){close--});stream.once("error",function(){close--});close++};parser.onPartData=function(buffer,start,end){if(req.buffer_exceeded)return;if(isXSS)return;var data=buffer.slice(start,end);var length=data.length;size+=length;if(size>=maximumSize){req.buffer_exceeded=true;if(rm===null)rm=[tmp.fileNameTmp];else rm.push(tmp.fileNameTmp);return}if(!tmp.isFile){tmp.value+=data.toString(ENCODING);return}if(tmp.fileSize===0){var wh=null;switch(tmp.contentType){case"image/jpeg":wh=require("./image").measureJPG(data);break;case"image/gif":wh=require("./image").measureGIF(data);break;case"image/png":wh=require("./image").measurePNG(data);break}if(wh){tmp.width=wh.width;tmp.height=wh.height}}stream.write(data);tmp.fileSize+=length};parser.onPartEnd=function(){if(stream!==null){stream.end();stream=null}if(req.buffer_exceeded)return;if(tmp.isFile){req.data.files.push(new HttpFile(tmp.name,tmp.fileName,tmp.fileNameTmp,tmp.fileSize,tmp.contentType,tmp.width,tmp.height));return}if(onXSS(tmp.value))isXSS=true;var temporary=req.data.post[tmp.name];if(typeof temporary===UNDEFINED){req.data.post[tmp.name]=tmp.value;return}if(utils.isArray(temporary)){req.data.post[tmp.name].push(tmp.value);return}temporary=[temporary];temporary.push(tmp.value);req.data.post[tmp.name]=temporary};parser.onEnd=function(){var cb=function(){if(close>0){setImmediate(cb);return}if(isXSS){req.flags.push("xss");framework.stats.request.xss++}if(rm!==null)framework.unlink(rm);callback()};cb()};req.on("data",parser.write.bind(parser));req.on("end",parser.end.bind(parser))};exports.parseMULTIPART_MIXED=function(req,contentType,tmpDirectory,onFile,callback){var parser=new MultipartParser;var boundary=contentType.split(";")[1];var stream=null;var tmp={name:"",contentType:"",fileName:"",fileNameTmp:"",fileSize:0,isFile:false,step:0,width:0,height:0};var ip=req.ip.replace(/\./g,"");var close=0;boundary=boundary.substring(boundary.indexOf("=")+1);req.buffer_exceeded=false;req.buffer_has=true;parser.initWithBoundary(boundary);parser.onPartBegin=function(){tmp.fileSize=0;tmp.step=0;tmp.isFile=false};parser.onHeaderValue=function(buffer,start,end){if(req.buffer_exceeded||tmp.step>1)return;var arr=buffer.slice(start,end).toString(ENCODING).split(";");if(tmp.step===1){tmp.contentType=arr[0];tmp.step=2;return}if(tmp.step===0){tmp.name=arr[1].substring(arr[1].indexOf("=")+2);tmp.name=tmp.name.substring(0,tmp.name.length-1);tmp.step=1;if(arr.length!==3)return;tmp.fileName=arr[2].substring(arr[2].indexOf("=")+2);tmp.fileName=tmp.fileName.substring(0,tmp.fileName.length-1);tmp.isFile=true;tmp.fileNameTmp=utils.combine(tmpDirectory,ip+"-"+(new Date).getTime()+"-"+utils.random(1e5)+".upload");stream=fs.createWriteStream(tmp.fileNameTmp,{flags:"w"});stream.on("close",function(){close--});stream.on("error",function(){close--});close++;return}};parser.onPartData=function(buffer,start,end){var data=buffer.slice(start,end);var length=data.length;if(!tmp.isFile)return;if(tmp.fileSize===0){var wh=null;switch(tmp.contentType){case"image/jpeg":wh=require("./image").measureJPG(data);break;case"image/gif":wh=require("./image").measureGIF(data);break;case"image/png":wh=require("./image").measurePNG(data);break}if(wh){tmp.width=wh.width;tmp.height=wh.height}}stream.write(data);tmp.fileSize+=length};parser.onPartEnd=function(){if(stream!==null){stream.end();stream=null}if(!tmp.isFile)return;onFile(new HttpFile(tmp.name,tmp.fileName,tmp.fileNameTmp,tmp.fileSize,tmp.contentType,tmp.width,tmp.height))};parser.onEnd=function(){var cb=function cb(){if(close>0){setImmediate(cb);return}onFile(null);callback()};cb()};req.on("data",parser.write.bind(parser))};exports.routeSplit=function(url,noLower){if(!noLower)url=url.toLowerCase();if(url[0]==="/")url=url.substring(1);if(url[url.length-1]==="/")url=url.substring(0,url.length-1);var arr=url.split("/");if(arr.length===1&&arr[0]==="")arr[0]="/";return arr};exports.routeCompare=function(url,route,isSystem,isAsterix){var length=url.length;if(route.length!==length&&!isAsterix)return false;var skip=length===1&&url[0]==="/";for(var i=0;i<length;i++){var value=route[i];if(!isSystem&&isAsterix&&typeof value===UNDEFINED)return true;if(!isSystem&&(!skip&&value[0]==="{"))continue;if(url[i]!==value){if(!isSystem)return isAsterix;return false}}return true};exports.routeCompareSubdomain=function(subdomain,arr){if(arr===null||subdomain===null||arr.length===0)return true;return arr.indexOf(subdomain)>-1};exports.routeCompareFlags=function(arr1,arr2,noLoggedUnlogged){var isXSS=false;var length=arr2.length;var AUTHORIZE="authorize";for(var i=0;i<length;i++){var value=arr2[i];if(value[0]==="!")continue;if(noLoggedUnlogged&&value===AUTHORIZE)continue;var index=arr1.indexOf(value);if(index===-1&&value==="xss"){isXSS=true;continue}if(value==="xss")isXSS=true;if(index===-1)return value===AUTHORIZE?-1:0}if(!isXSS&&arr1.indexOf("xss")!==-1)return 0;return 1};exports.routeParam=function(routeUrl,route){var arr=[];if(!route||!routeUrl)return arr;var length=route.param.length;if(length===0)return arr;for(var i=0;i<length;i++){var value=routeUrl[route.param[i]];arr.push(value==="/"?"":value)}return arr};function HttpFile(name,filename,path,length,contentType,width,height){this.name=name;this.filename=filename;this.length=length;this.contentType=contentType;this.path=path;this.width=width;this.height=height}HttpFile.prototype.copy=function(filename,callback){var self=this;if(!callback){fs.createReadStream(self.path).pipe(fs.createWriteStream(filename));return}var reader=fs.createReadStream(self.path);var writer=fs.createWriteStream(filename);reader.on("close",callback);reader.pipe(writer);return self};HttpFile.prototype.readSync=function(){return fs.readFileSync(this.path)};HttpFile.prototype.read=function(callback){var self=this;fs.readFile(self.path,callback);return self};HttpFile.prototype.md5=function(callback){var self=this;var md5=crypto.createHash("md5");var stream=fs.createReadStream(self.path);stream.on("data",function(buffer){md5.update(buffer)});stream.on("error",function(error){callback(error,null)});stream.on("end",function(){callback(null,md5.digest("hex"))});return self};HttpFile.prototype.stream=function(options){var self=this;return fs.createReadStream(self.path,options)};HttpFile.prototype.pipe=function(stream,options){var self=this;return fs.createReadStream(self.path,options).pipe(stream,options)};HttpFile.prototype.isImage=function(){var self=this;return self.contentType.indexOf("image/")!==-1};HttpFile.prototype.isVideo=function(){var self=this;return self.contentType.indexOf("video/")!==-1};HttpFile.prototype.isAudio=function(){var self=this;return self.contentType.indexOf("audio/")!==-1};HttpFile.prototype.image=function(imageMagick){var im=imageMagick;if(typeof im===UNDEFINED)im=framework.config["default-image-converter"]==="im";return require("./image").init(this.path,im)};function compile_jscss(css){var comments=[];var beg=0;var end=0;var tmp="";while(true){beg=css.indexOf("/*",beg);if(beg===-1){tmp+=css;break}end=css.indexOf("*/",beg);if(end===-1)continue;comments.push(css.substring(beg,end).trim());beg=0;css=css.substring(end+2)}css=tmp.trim();var length=comments.length;var code="";var avp="@#auto-vendor-prefix#@";var isAuto=css.startsWith(avp);if(isAuto)css=css.replace(avp,"");tmp="";for(var i=0;i<length;i++){var comment=comments[i];if(comment.indexOf("auto")!==-1&&comment.length<=10){isAuto=true;continue}if(comment.indexOf("var ")!==-1||comment.indexOf("function ")!==-1)code+=comment.replace("/*","").replace("*/","")+"\n\n"}beg=0;end=0;var output="";tmp=css;while(true){beg=tmp.indexOf("$");if(beg===-1){output+=tmp.replace(/\\/g,"\\\\").replace(/\"/g,'\\"').replace(/\n/g,"");break}output+=tmp.substring(0,beg).replace(/\n/g,"");tmp=tmp.substring(beg);length=tmp.length;end=0;var skipA=0;var skipB=0;var skipC=0;for(var i=0;i<length;i++){if(tmp[i]==='"'){if(skipA>0){skipA--;continue}skipA++}if(tmp[i]==="{")skipC++;if(tmp[i]==="'"){if(skipB>0){skipB--;continue}skipB++}if(tmp[i]==="}"&&skipC>0){skipC--;continue}if(skipA>0||skipB>0||skipC>0)continue;if(tmp[i]===";"||tmp[i]==="}"||tmp[i]==="\n"){end=i;break}}if(end===0)continue;var cmd=tmp.substring(0,end);tmp=tmp.substring(end);output+='"+'+cmd.substring(1)+'+"'}var length=output.length;var compiled="";output=code+'\n\n;compiled = "'+output+(output[length-1]==='"'?"":'"');eval(output);var reg1=/\n|\s{2,}/g;var reg2=/\s?\{\s{1,}/g;var reg3=/\s?\}\s{1,}/g;var reg4=/\s?\:\s{1,}/g;var reg5=/\s?\;\s{1,}/g;if(isAuto)compiled=autoprefixer(compiled);return compiled.replace(reg1,"").replace(reg2,"{").replace(reg3,"}").replace(reg4,":").replace(reg5,";").replace(/\s\}/g,"}").replace(/\s\{/g,"{").trim()}function autoprefixer(value){var prefix=["appearance","column-count","column-gap","column-rule","display","transform","transform-origin","transition","user-select","animation","animation-name","animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-play-state","opacity","background","background-image","font-smoothing"];value=autoprefixer_keyframes(value);var builder=[];var index=0;var property;for(var i=0;i<prefix.length;i++){property=prefix[i];index=0;while(index!==-1){index=value.indexOf(property,index+1);if(index===-1)continue;var a=value.indexOf(";",index);var b=value.indexOf("}",index);var end=Math.min(a,b);if(end===-1)end=Math.max(a,b);if(end===-1)continue;if(property==="transform"&&value.substring(index-1,index)==="-")continue;var css=value.substring(index,end);end=css.indexOf(":");if(end===-1)continue;if(css.substring(0,end+1).replace(/\s/g,"")!==property+":")continue;builder.push({name:property,property:css})}}var output=[];var length=builder.length;for(var i=0;i<length;i++){var name=builder[i].name;property=builder[i].property;var plus=property;var delimiter=";";var updated=plus+delimiter;if(name==="opacity"){var opacity=parseFloat(plus.replace("opacity","").replace(":","").replace(/\s/g,""));if(isNaN(opacity))continue;updated+="filter:alpha(opacity="+Math.floor(opacity*100)+");";value=value.replacer(property,"@[["+output.length+"]]");output.push(updated);continue}if(name==="background"||name==="background-image"){if(property.indexOf("linear-gradient")===-1)continue;updated=plus.replacer("linear-","-webkit-linear-")+delimiter;updated+=plus.replacer("linear-","-moz-linear-")+delimiter;updated+=plus.replacer("linear-","-o-linear-")+delimiter;updated+=plus.replacer("linear-","-ms-linear-");updated+=plus+delimiter;value=value.replacer(property,"@[["+output.length+"]]");output.push(updated);continue}if(name==="text-overflow"){updated=plus+delimiter;updated+=plus.replacer("text-overflow","-ms-text-overflow");value=value.replacer(property,"@[["+output.length+"]]");output.push(updated);continue}if(name==="display"){if(property.indexOf("box")===-1)continue;updated=plus+delimiter;updated+=plus.replacer("box","-webkit-box")+delimiter;updated+=plus.replacer("box","-moz-box");value=value.replacer(property,"@[["+output.length+"]]");output.push(updated);continue}updated+="-webkit-"+plus+delimiter;updated+="-moz-"+plus;if(name.indexOf("animation")===-1)updated+=delimiter+"-ms-"+plus;updated+=delimiter+"-o-"+plus;value=value.replacer(property,"@[["+output.length+"]]");output.push(updated)}length=output.length;for(var i=0;i<length;i++)value=value.replacer("@[["+i+"]]",output[i]);output=null;builder=null;prefix=null;return value}function autoprefixer_keyframes(value){var builder=[];var index=0;while(index!==-1){index=value.indexOf("@keyframes",index+1);if(index===-1)continue;var counter=0;var end=-1;for(var indexer=index+10;indexer<value.length;indexer++){if(value[indexer]==="{")counter++;if(value[indexer]!=="}")continue;if(counter>1){counter--;continue}end=indexer;break}if(end===-1)continue;var css=value.substring(index,end+1);builder.push({name:"keyframes",property:css})}var output=[];var length=builder.length;for(var i=0;i<length;i++){var name=builder[i].name;var property=builder[i].property;if(name!=="keyframes")continue;var plus=property.substring(1);var delimiter="\n";var updated="@"+plus+delimiter;updated+="@-webkit-"+plus+delimiter;updated+="@-moz-"+plus+delimiter;updated+="@-o-"+plus;value=value.replacer(property,"@[["+output.length+"]]");output.push(updated)}length=output.length;for(var i=0;i<length;i++)value=value.replace("@[["+i+"]]",output[i]);builder=null;output=null;return value}exports.compile_css=function(value,minify,framework){if(framework){if(framework.onCompileCSS!==null)return framework.onCompileCSS("",value)}return compile_jscss(value)};function JavaScript(source){var EOF=-1;var sb=[];var theA;var theB;var theLookahead=EOF;var index=0;function jsmin(){theA=13;action(3);var indexer=0;while(theA!==EOF){switch(theA){case 32:if(isAlphanum(theB))action(1);else action(2);break;case 13:switch(theB){case 123:case 91:case 40:case 43:case 45:action(1);break;case 32:action(3);break;default:if(isAlphanum(theB))action(1);else action(2);break}break;default:switch(theB){case 32:if(isAlphanum(theA)){action(1);break}action(3);break;case 13:switch(theA){case 125:case 93:case 41:case 43:case 45:case 34:case 92:action(1);break;default:if(isAlphanum(theA))action(1);else action(3);break}break;default:action(1);break}break}}}function action(d){if(d<=1){put(theA)}if(d<=2){theA=theB;if(theA===39||theA===34){for(;;){put(theA);theA=get();if(theA===theB){break}if(theA<=13){c=EOF;return}if(theA===92){put(theA);theA=get()}}}}if(d<=3){theB=next();if(theB===47&&(theA===40||theA===44||theA===61||theA===91||theA===33||theA===58||theA===38||theA===124||theA===63||theA===123||theA===125||theA===59||theA===13)){put(theA);put(theB);for(;;){theA=get();if(theA===47){break}else if(theA===92){put(theA);theA=get()}else if(theA<=13){c=EOF;return}put(theA)}theB=next()}}}function next(){var c=get();if(c!==47)return c;switch(peek()){case 47:for(;;){c=get();if(c<=13)return c}break;case 42:get();for(;;){switch(get()){case 42:if(peek()===47){get();return 32}break;case EOF:c=EOF;return}}break;default:return c}return c}function peek(){theLookahead=get();return theLookahead}function get(){var c=theLookahead;theLookahead=EOF;if(c===EOF){c=source.charCodeAt(index++);if(isNaN(c))c=EOF}if(c>=32||c===13||c===EOF){return c}if(c===10){return 13}return 32}function put(c){if(c===13||c===10)sb.push(" ");else sb.push(String.fromCharCode(c))}function isAlphanum(c){return c>=97&&c<=122||c>=48&&c<=57||c>=65&&c<=90||c===95||c===36||c===92||c>126}jsmin();return sb.join("")}exports.compile_javascript=function(source,framework){try{if(framework){if(framework.onCompileJS!==null)return framework.onCompileJS("",source)}return JavaScript(source)}catch(ex){if(framework)framework.error(ex,"JavaScript compressor");return source}};var Buffer=require("buffer").Buffer,s=0,S={PARSER_UNINITIALIZED:s++,START:s++,START_BOUNDARY:s++,HEADER_FIELD_START:s++,HEADER_FIELD:s++,HEADER_VALUE_START:s++,HEADER_VALUE:s++,HEADER_VALUE_ALMOST_DONE:s++,HEADERS_ALMOST_DONE:s++,PART_DATA_START:s++,PART_DATA:s++,PART_END:s++,END:s++},f=1,F={PART_BOUNDARY:f,LAST_BOUNDARY:f*=2},LF=10,CR=13,SPACE=32,HYPHEN=45,COLON=58,A=97,Z=122,lower=function(c){return c|32};for(s in S){exports[s]=S[s]}function MultipartParser(){this.boundary=null;this.boundaryChars=null;this.lookbehind=null;this.state=S.PARSER_UNINITIALIZED;this.index=null;this.flags=0}exports.MultipartParser=MultipartParser;MultipartParser.stateToString=function(stateNumber){for(var state in S){var number=S[state];if(number===stateNumber)return state}};MultipartParser.prototype.initWithBoundary=function(str){var self=this;self.boundary=new Buffer(str.length+4);if(framework.versionNode>=1111){self.boundary.write("\r\n--",0,"ascii");self.boundary.write(str,4,"ascii")}else{self.boundary.write("\r\n--","ascii",0);self.boundary.write(str,"ascii",4)}self.lookbehind=new Buffer(self.boundary.length+8);self.state=S.START;self.boundaryChars={};for(var i=0;i<self.boundary.length;i++){self.boundaryChars[self.boundary[i]]=true}};MultipartParser.prototype.write=function(buffer){var self=this,i=0,len=buffer.length,prevIndex=self.index,index=self.index,state=self.state,flags=self.flags,lookbehind=self.lookbehind,boundary=self.boundary,boundaryChars=self.boundaryChars,boundaryLength=self.boundary.length,boundaryEnd=boundaryLength-1,bufferLength=buffer.length,c,cl,mark=function(name){self[name+"Mark"]=i},clear=function(name){delete self[name+"Mark"]},callback=function(name,buffer,start,end){if(start!==undefined&&start===end){return}var callbackSymbol="on"+name.substr(0,1).toUpperCase()+name.substr(1);if(callbackSymbol in self){self[callbackSymbol](buffer,start,end)}},dataCallback=function(name,clear){var markSymbol=name+"Mark";if(!(markSymbol in self)){return}if(!clear){callback(name,buffer,self[markSymbol],buffer.length);self[markSymbol]=0}else{callback(name,buffer,self[markSymbol],i);delete self[markSymbol]}};for(i=0;i<len;i++){c=buffer[i];switch(state){case S.PARSER_UNINITIALIZED:return i;case S.START:index=0;state=S.START_BOUNDARY;case S.START_BOUNDARY:if(index==boundary.length-2){if(c==HYPHEN){flags|=F.LAST_BOUNDARY}else if(c!=CR){return i}index++;break}else if(index-1==boundary.length-2){if(flags&F.LAST_BOUNDARY&&c==HYPHEN){callback("end");state=S.END;flags=0}else if(!(flags&F.LAST_BOUNDARY)&&c==LF){index=0;callback("partBegin");state=S.HEADER_FIELD_START}else{return i}break}if(c!=boundary[index+2]){index=-2}if(c==boundary[index+2]){index++}break;case S.HEADER_FIELD_START:state=S.HEADER_FIELD;mark("headerField");index=0;case S.HEADER_FIELD:if(c==CR){clear("headerField");state=S.HEADERS_ALMOST_DONE;break}index++;if(c==HYPHEN){break}if(c==COLON){if(index==1){return i}dataCallback("headerField",true);state=S.HEADER_VALUE_START;break}cl=lower(c);if(cl<A||cl>Z){return i}break;case S.HEADER_VALUE_START:if(c==SPACE){break}mark("headerValue");state=S.HEADER_VALUE;case S.HEADER_VALUE:if(c==CR){dataCallback("headerValue",true);callback("headerEnd");state=S.HEADER_VALUE_ALMOST_DONE}break;case S.HEADER_VALUE_ALMOST_DONE:if(c!=LF){return i}state=S.HEADER_FIELD_START;break;case S.HEADERS_ALMOST_DONE:if(c!=LF){return i}callback("headersEnd");state=S.PART_DATA_START;break;case S.PART_DATA_START:state=S.PART_DATA;mark("partData");case S.PART_DATA:prevIndex=index;if(index===0){i+=boundaryEnd;while(i<bufferLength&&!(buffer[i]in boundaryChars)){i+=boundaryLength}i-=boundaryEnd;c=buffer[i]}if(index<boundary.length){if(boundary[index]==c){if(index===0){dataCallback("partData",true)}index++}else{index=0}}else if(index==boundary.length){index++;if(c==CR){flags|=F.PART_BOUNDARY}else if(c==HYPHEN){flags|=F.LAST_BOUNDARY}else{index=0}}else if(index-1==boundary.length){if(flags&F.PART_BOUNDARY){index=0;if(c==LF){flags&=~F.PART_BOUNDARY;callback("partEnd");callback("partBegin");state=S.HEADER_FIELD_START;break}}else if(flags&F.LAST_BOUNDARY){if(c==HYPHEN){callback("partEnd");callback("end");state=S.END;flags=0}else{index=0}}else{index=0}}if(index>0){lookbehind[index-1]=c}else if(prevIndex>0){callback("partData",lookbehind,0,prevIndex);prevIndex=0;mark("partData");i--}break;case S.END:break;default:return i}}dataCallback("headerField");dataCallback("headerValue");dataCallback("partData");self.index=index;self.state=state;self.flags=flags;return len};MultipartParser.prototype.end=function(){var self=this;var callback=function(self,name){var callbackSymbol="on"+name.substr(0,1).toUpperCase()+name.substr(1);if(callbackSymbol in self){self[callbackSymbol]()}};if(self.state==S.HEADER_FIELD_START&&self.index===0||self.state==S.PART_DATA&&self.index==self.boundary.length){callback(self,"partEnd");callback(self,"end")}else if(self.state!=S.END){callback(self,"partEnd");callback(self,"end");return new Error("MultipartParser.end(): stream ended unexpectedly: "+self.explain())}};MultipartParser.prototype.explain=function(){return"state = "+MultipartParser.stateToString(this.state)};function View(controller){this.controller=controller;this.cache=controller.cache;this.prefix=controller.prefix}function Content(controller){this.controller=controller;this.cache=controller.cache;this.prefix=controller.prefix}function view_parse(content,minify){content=removeComments(compressCSS(compressJS(content,0,framework),0,framework));var builder="";var command=view_find_command(content,0);if(command===null)builder="+'"+compressHTML(content,minify).replace(/\\\'/g,"\\\\'").replace(/\'/g,"\\'").replace(/\n/g,"\\n")+"'";var old=null;var condition=0;var is=false;while(command!==null){if(condition===0&&builder!=="")builder+="+";if(old!==null){var text=content.substring(old.end+1,command.beg);if(text!==""){if(view_parse_plus(builder))builder+="+";builder+="'"+compressHTML(text,minify).replace(/\\\'/g,"\\\\'").replace(/\'/g,"\\'").replace(/\n/g,"\\n")+"'"}}else{var text=content.substring(0,command.beg);if(text!==""){if(view_parse_plus(builder))builder+="+";builder+="'"+compressHTML(text,minify).replace(/\\\'/g,"\\\\'").replace(/\'/g,"\\'").replace(/\n/g,"\\n")+"'"}}var cmd=content.substring(command.beg+2,command.end);if(cmd.substring(0,3)==="if "){if(view_parse_plus(builder))builder+="+";condition=1;builder+="("+cmd.substring(3)+"?";is=true}else if(cmd==="else"){condition=2;builder+=":";is=true}else if(cmd==="endif"){if(condition===1)builder+=":''";condition=0;builder+=")";is=true}else{if(view_parse_plus(builder))builder+="+";builder+=view_prepare(command.command)}if(!is){}old=command;command=view_find_command(content,command.end)}if(old!==null){var text=content.substring(old.end+1);if(text.length>0)builder+="+'"+compressHTML(text,minify).replace(/\\\'/g,"\\\\'").replace(/\'/g,"\\'").replace(/\n/g,"\\n")+"'"}var fn="(function(self,repository,model,session,get,post,url,global,helpers,user,config,functions,index,sitemap,output){var controller=self;return "+builder.substring(1)+"})";return eval(fn)}function view_parse_plus(builder){var c=builder[builder.length-1];if(c!=="!"&&c!=="?"&&c!=="+"&&c!=="."&&c!==":")return true;return false}function view_prepare(command){var a=command.indexOf(".");var b=command.indexOf("(");var c=command.indexOf("[");if(a===-1)a=b;if(b===-1)b=a;if(a===-1)a=c;if(b===-1)b=c;var index=Math.min(a,b);if(index===-1)index=command.length;var name=command.substring(0,index);switch(name){case"controller":case"repository":case"model":case"get":case"post":case"global":case"session":case"user":case"config":case"model":if(view_is_assign(command))return"self.$set("+command+")";return"("+command+").toString().encode()";case"functions":return"("+command+").toString().encode()";case"!controller":case"!repository":case"!get":case"!post":case"!global":case"!session":case"!user":case"!config":case"!functions":case"!model":return"("+command.substring(1)+")";case"body":return"output";case"resource":return"(self."+command+").toString().encode()";case"!resource":return"(self."+command.substring(1)+")";case"host":case"hostname":if(command.indexOf("(")===-1)return"self.host()";return"self."+command;case"url":if(command.indexOf("(")!==-1)return"self.$"+command;return command="url";case"title":case"description":case"keywords":if(command.indexOf("(")!==-1)return"self."+command;return"(repository['$"+command+"'] || '').toString().encode()";case"!title":case"!description":case"!keywords":return"(repository['$"+command.substring(1)+"'] || '')";case"head":if(command.indexOf("(")!==-1)return"self.$"+command;return"self."+command+"()";case"place":case"sitemap":if(command.indexOf("(")!==-1)return"self.$"+command;return"(repository['$"+command+"'] || '')";case"meta":if(command.indexOf("(")!==-1)return"self.$"+command;return"self.$meta()";case"js":case"script":case"css":case"favicon":return"self.$"+command+(command.indexOf("(")===-1?"()":"");case"index":return"("+command+")";case"routeJS":case"routeCSS":case"routeImage":case"routeFont":case"routeDownload":case"routeVideo":case"routeStatic":return"self."+command;case"ng":case"ngTemplate":case"ngController":case"ngCommon":case"ngInclude":case"ngLocale":case"ngService":case"ngFilter":case"ngDirective":case"ngResource":case"ngStyle":return"self.$"+command;case"canonical":case"checked":case"helper":case"component":case"componentToggle":case"content":case"contentToggle":case"currentContent":case"currentCSS":case"currentDownload":case"currentImage":case"currentJS":case"currentTemplate":case"currentVideo":case"currentView":case"disabled":case"dns":case"download":case"etag":case"header":case"image":case"json":case"layout":case"modified":case"next":case"options":case"prefetch":case"prerender":case"prev":case"readonly":case"selected":case"template":case"templateToggle":case"view":case"viewToggle":return"self.$"+command;case"radio":case"text":case"checkbox":case"hidden":case"textarea":case"password":return"self.$"+exports.appendModel(command);default:return"helpers."+view_insert_call(command)}return command}function view_insert_call(command){var beg=command.indexOf("(");if(beg===-1)return command;var length=command.length;var count=0;for(var i=beg+1;i<length;i++){var c=command[i];if(c!=="("&&c!==")")continue;if(c==="("){count++;continue}if(count>0){count--;continue}return command.substring(0,beg)+".call(self, "+command.substring(beg+1)}return command}function view_is_assign(value){var length=value.length;var skip=0;var plus=0;for(var i=0;i<length;i++){var c=value[i];if(c==="["){skip++;continue}if(c==="]"){skip--;continue}var next=value[i+1]||"";if(c==="+"&&(next==="+"||next==="=")){if(skip===0)return true}if(c==="-"&&(next==="-"||next==="=")){if(skip===0)return true}if(c==="*"&&(next==="*"||next==="=")){if(skip===0)return true}if(c==="="){if(skip===0)return true}}return false}function view_find_command(content,index){var index=content.indexOf("@{",index);if(index===-1)return null;var length=content.length;var count=0;for(var i=index+2;i<length;i++){var c=content[i];if(c==="{"){count++;continue}if(c!=="}")continue;else{if(count>0){count--;continue}}return{beg:index,end:i,command:content.substring(index+2,i).trim()}}return null}function removeCondition(text,beg){if(beg){if(text[0]==="+")return text.substring(1,text.length)}else{if(text[text.length-1]==="+")return text.substring(0,text.length-1)}return text}function removeComments(html){var tagBeg="<!--";var tagEnd="-->";var beg=html.indexOf(tagBeg);var end=0;while(beg!==-1){end=html.indexOf(tagEnd,beg+4);if(end===-1)break;var comment=html.substring(beg,end+3);if(comment.indexOf("[if")!==-1||comment.indexOf("[endif")!==-1){beg=html.indexOf(tagBeg,end+3);continue}html=html.replacer(comment,"");beg=html.indexOf(tagBeg,end+3)}return html}function compressJS(html,index,framework){var strFrom='<script type="text/javascript">';var strTo="</script>";var indexBeg=html.indexOf(strFrom,index||0);if(indexBeg===-1){strFrom="<script>";indexBeg=html.indexOf(strFrom,index||0);if(indexBeg===-1)return html}var indexEnd=html.indexOf(strTo,indexBeg+strFrom.length);if(indexEnd===-1)return html;var js=html.substring(indexBeg,indexEnd+strTo.length).trim();var beg=html.indexOf(js);if(beg===-1)return html;var val=js.substring(strFrom.length,js.length-strTo.length).trim();var compiled=exports.compile_javascript(val,framework).replace(/\\\\/g,"\\\\\\\\").replace(/\\n/g,"'+(String.fromCharCode(13)+String.fromCharCode(10))+'");html=html.replacer(js,strFrom+compiled.dollar().trim()+strTo.trim());return compressJS(html,indexBeg+compiled.length+9,framework)}function compressCSS(html,index,framework){var strFrom='<style type="text/css">';var strTo="</style>";var indexBeg=html.indexOf(strFrom,index||0);if(indexBeg===-1){strFrom="<style>";indexBeg=html.indexOf(strFrom,index||0);if(indexBeg===-1)return html}var indexEnd=html.indexOf(strTo,indexBeg+strFrom.length);if(indexEnd===-1)return html;var css=html.substring(indexBeg,indexEnd+strTo.length);var val=css.substring(strFrom.length,css.length-strTo.length).trim();var compiled=exports.compile_css(val,true,framework);html=html.replacer(css,(strFrom+compiled.trim()+strTo).trim());return compressCSS(html,indexBeg+compiled.length+8,framework)}function compressHTML(html,minify){if(html===null||html===""||!minify)return html;html=removeComments(html);var tags=["script","textarea","pre","code"];var id="["+(new Date).getTime()+"]#";var cache={};var indexer=0;var length=tags.length;for(var i=0;i<length;i++){var o=tags[i];var tagBeg="<"+o;var tagEnd="</"+o;var beg=html.indexOf(tagBeg);var end=0;var len=tagEnd.length;while(beg!==-1){end=html.indexOf(tagEnd,beg+3);if(end===-1)break;var key=id+indexer++;var value=html.substring(beg,end+len);if(i===0){end=value.indexOf(">");len=value.indexOf('type="text/template"');if(len<end&&len!==-1)break;len=value.indexOf('type="text/html"');if(len<end&&len!==-1)break;len=value.indexOf('type="text/ng-template"');if(len<end&&len!==-1)break}cache[key]=value.replace(/\n/g,"\\n");html=html.replacer(value,key);beg=html.indexOf(tagBeg,beg+tagBeg.length)}}html=html.replace(REG_1,"").replace(REG_2,"");var keys=Object.keys(cache);length=keys.length;for(var i=0;i<length;i++){var key=keys[i];html=html.replacer(key,cache[key])}return html}View.prototype.read=function(name){var self=this;var config=self.controller.config;var isOut=name[0]===".";var filename=isOut?name.substring(1)+".html":utils.combine(config["directory-views"],name+".html");if(fs.existsSync(filename))return view_parse(fs.readFileSync(filename).toString("utf8"),config["allow-compress-html"]);if(isOut)return null;var index=name.lastIndexOf("/");if(index===-1)return null;name=name.substring(index+1);if(name.indexOf("#")!==-1)return null;filename=name[0]==="."?name.substring(1):utils.combine(config["directory-views"],name+".html");if(fs.existsSync(filename))return view_parse(fs.readFileSync(filename).toString("utf8"),config["allow-compress-html"]);return null};View.prototype.load=function(name,prefix,filename){var self=this;if(name.indexOf("@{")!==-1||name.indexOf("<")!==-1)return self.dynamic(name);var isPrefix=(prefix||"").length>0;var key="view."+filename+(isPrefix?"#"+prefix:"");var generator=self.controller.framework.temporary.views[key]||null;if(generator!==null)return generator;generator=self.read(filename+(isPrefix?"#"+prefix:""));if(generator===null&&isPrefix)generator=self.read(filename);if(generator!==null&&!self.controller.isDebug)self.controller.framework.temporary.views[key]=generator;return generator};View.prototype.dynamic=function(content){var self=this;var key=content.md5();var generator=self.controller.framework.temporary.views[key]||null;if(generator!==null)return generator;generator=view_parse(content,self.controller,self.controller.config["allow-compress-html"]);if(generator!==null&&!self.controller.isDebug)self.controller.framework.temporary.views[key]=generator;
Example #11
0
File: cron.js Project: ryush00/mcs2
 var createHash = function(record) {
   if(!record.port || record.port <= 0 || record.port >= 65535) record.port = 25565;
   return record.hash = crypto.createHash("md5").update(record.host.toLowerCase().trim()+record.port).digest("hex");
 };
Example #12
0
      super();

      this._buffers = [];
      this.once('finish', function() {
        callback(null, Buffer.concat(this._buffers));
      });
    }

    _write(data, encoding, done) {
      this._buffers.push(data);
      return done(null);
    }
  }

  // Create an md5 hash of "Hallo world"
  const hasher1 = crypto.createHash('md5');
  hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) {
    assert.strictEqual(err, null);
    assert.strictEqual(
      hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'
    );
  })));
  hasher1.end('Hallo world');

  // Simpler check for unpipe, setEncoding, pause and resume
  crypto.createHash('md5').unpipe({});
  crypto.createHash('md5').setEncoding('utf8');
  crypto.createHash('md5').pause();
  crypto.createHash('md5').resume();
}
Example #13
0
function cryptoPass(pass) {
    return crypto.createHash('sha512').update(pass).digest('hex');
}
Example #14
0
 values.forEach((value, index) => {
     hashs.push('_:' + Hash('md5').update(value).digest('hex'));
 });
Example #15
0
 function hash(string) {
     var sha512 = crypto.createHash("sha512")
     sha512.update(string, "utf8")
     return sha512.digest("base64")
 }
Example #16
0
 var str_md5 = function (buffer) {
   var md5 = lib_crypto.createHash('md5');
   md5.update(buffer);
   return md5.digest('hex');
 };
Example #17
0
var md5 = (text) => crypto.createHash('md5').update(text).digest('hex');
Example #18
0
function sha1crypt(password) {
  return '{SHA}' + crypto.createHash('sha1').update(password).digest('base64');
}
var crypto = require('crypto');

var string = "This is another test.";

var md5sum = crypto.createHash('md5').update(string).digest('hex');
var sha1sum = crypto.createHash('sha1').update(string).digest('hex');

function getValueOfDigit(digit, alphabet)
{
   var pos = alphabet.indexOf(digit);
   return pos;
}

function convert(src, srcAlphabet, dstAlphabet)
{
   var srcBase = srcAlphabet.length;
   var dstBase = dstAlphabet.length;

   var wet     = src;
   var val     = 0;
   var mlt     = 1;

   while (wet.length > 0)
   {
     var digit  = wet.charAt(wet.length - 1);
     val       += mlt * getValueOfDigit(digit, srcAlphabet);
     wet        = wet.substring(0, wet.length - 1);
     mlt       *= srcBase;
   }

   wet          = val;
Example #20
0
// Ported to javascript from http://code.activestate.com/recipes/325204-passwd-file-compatible-1-md5-crypt/
function md5crypt(password, salt, magic) {
  var rearranged = '',
      mixin, final, m, v, i;

  m = crypto.createHash('md5');
  m.update(password + magic + salt);
  mixin = crypto.createHash('md5').update(password + salt + password).digest("binary");

  for (i = 0; i < password.length; i++) {
    m.update(mixin[i % 16]);
  }

  // Weird shit..
  for (i = password.length; i > 0; i >>= 1) {
    if (i & 1) {
      m.update('\x00');
    } else {
      m.update(password[0]);
    }
  }

  final = m.digest("binary");

  // Slow it down there...
  for (i = 0; i < 1000; i ++) {
    m = crypto.createHash('md5');

    if (i & 1) {
      m.update(password);
    } else {
      m.update(final);
    }

    if (i % 3) {
      m.update(salt);
    }

    if (i % 7) {
      m.update(password);
    }

    if (i & 1) {
      m.update(final);
    } else {
      m.update(password);
    }

    final = m.digest("binary");
  }


  for (i = 0; i < TUPLES.length; i++) {
    v = final.charCodeAt(TUPLES[i][0]) << 16 | final.charCodeAt(TUPLES[i][1]) << 8 | final.charCodeAt(TUPLES[i][2]);
    rearranged += ITOA64[v & 0x3f]; v >>= 6;
    rearranged += ITOA64[v & 0x3f]; v >>= 6;
    rearranged += ITOA64[v & 0x3f]; v >>= 6;
    rearranged += ITOA64[v & 0x3f]; v >>= 6;
  }

  v = final.charCodeAt(11);
  rearranged += ITOA64[v & 0x3f]; v >>= 6;
  rearranged += ITOA64[v & 0x3f]; v >>= 6;

  return magic + salt + '$' + rearranged;
}
Example #21
0
function md5(string) {
  return createHash('md5').update(string).digest('hex');
}
Example #22
0
      db.db(authdb).command(cmd, { connection: connection }, function(err, r) {
        // Do we have an error, handle it
        if(handleError(err, r) == false) {
          count = count - 1;

          if(count == 0 && numberOfValidConnections > 0) {
            // Store the auth details
            addAuthSession(new AuthSession(db, username, password));
            // Return correct authentication
            return callback(null, true);
          } else if(count == 0) {
            if(errorObject == null) errorObject = utils.toError(f("failed to authenticate using scram"));
            return callback(errorObject, false);
          }

          return;
        }

        // Get the dictionary
        var dict = parsePayload(r.payload.value())

        // Unpack dictionary
        var iterations = parseInt(dict.i, 10);
        var salt = dict.s;
        var rnonce = dict.r;

        // Set up start of proof
        var withoutProof = f("c=biws,r=%s", rnonce);
        var passwordDig = passwordDigest(username, password);
        var saltedPassword = hi(passwordDig
            , new Buffer(salt, 'base64')
            , iterations);
        
        // Create the client key
        var hmac = crypto.createHmac('sha1', saltedPassword);
        hmac.update(new Buffer("Client Key"));
        var clientKey = hmac.digest();

        // Create the stored key
        var hash = crypto.createHash('sha1');
        hash.update(clientKey);
        var storedKey = hash.digest();

        // Create the authentication message
        var authMsg = [firstBare, r.payload.value().toString('base64'), withoutProof].join(',');

        // Create client signature
        var hmac = crypto.createHmac('sha1', storedKey);
        hmac.update(new Buffer(authMsg));          
        var clientSig = hmac.digest();

        // Create client proof
        var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64'));

        // Create client final
        var clientFinal = [withoutProof, clientProof].join(',');

        // Generate server key
        var hmac = crypto.createHmac('sha1', saltedPassword);
        hmac.update(new Buffer('Server Key'))
        var serverKey = hmac.digest();

        // Generate server signature
        var hmac = crypto.createHmac('sha1', serverKey);
        hmac.update(new Buffer(authMsg))
        var serverSig = hmac.digest();

        //
        // Create continue message
        var cmd = {
            saslContinue: 1
          , conversationId: r.conversationId
          , payload: new Binary(new Buffer(clientFinal))
        }

        //
        // Execute sasl continue
        db.db(authdb).command(cmd, { connection: connection }, function(err, r) {
            if(r.done == false) {
              var cmd = {
                  saslContinue: 1
                , conversationId: r.conversationId
                , payload: new Buffer(0)
              }

              db.db(authdb).command(cmd, { connection: connection }, function(err, r) {
                handleEnd(err, r);
              });
            } else {
              handleEnd(err, r);
            }
        });
      });
Example #23
0
 computeHash: function(info){
     var encoded = bencode.encode(info), hash = cryptolib.createHash('sha1');
     hash.update(encoded);
     return hash.digest('binary');
 },
	var hashes = _.map(urls, (url) => {
		return crypto.createHash('sha1').update(url).digest('hex');
	});
var crypto = require('crypto');
var fs = require('fs');
var h = crypto.createHash('sha256');

var inStream = fs.ReadStream(__filename);
inStream.addListener('data', function(data) {
  h.update(data);
});
inStream.addListener('end', function() {
	console.log(h.digest('hex')+'\n');
});

Example #26
0
exports.md5 = function (str, encoding){
  return crypto
    .createHash('md5')
    .update(str)
    .digest(encoding || 'hex');
};
Example #27
0
function cookie(message){
  return crypto
    .createHash('md5')
    .update(message.userId() || message.sessionId())
    .digest('hex');
}
Example #28
0
 strHash : function(str) {
   return crypto.createHash('md5').update(str.toLowerCase()).digest("hex");
 },
Example #29
0
http.createServer(function (request, response) {
  if (request.method != 'GET' && request.method != 'POST') {
    response.statusCode = 405;
    response.end();
    return;
  }
  response.from = extract_from(request);
  var parsed_url = url.parse(request.url);
  if (! parsed_url) {
    log.error(response.from + "Unable to parse url " + request.url);
    response.statusCode = 500;
    response.end();
    return;
  }
  if (request.method == 'GET' && parsed_url.path == '/reload_all_git_repos') {
    var command = '';
    if (argv.http_proxy) {
      command += 'export http_proxy=' + argv.http_proxy + ' && ';
    }
    if (argv.http_proxy) {
      command += 'export https_proxy=' + argv.https_proxy + ' && ';
    }
    command += 'cd storage && export home_dir=`pwd`; for i in `find . -name "packed-refs"`; do echo "Reloading `dirname $i`" && cd $home_dir && cd `dirname $i` && git fetch -q origin && git update-server-info || exit 1; done && echo "OK";';
    var child = spawn('/bin/sh', ['-c', command]);
    var out = '';
    log.debug(response.from + 'Launching command', command);
    child.stdout.on('data', function(d) {
      out += d.toString();
    });
    child.on('exit', function(code) {
      log.debug(response.from + 'Command result', code);
      if (code == 0) {
        response.statusCode = 200;
        response.setHeader('Content-Type', 'text/plain');
        response.end(out);
      }
      else {
        response.statusCode = 500;
        response.end();
      }
    });
    return;
  }
  if (parsed_url.protocol != 'http:') {
     log.error(response.from + "Wrong protoocol " + parsed_url.protocol);
    response.statusCode = 500;
    response.end();
    return;
  }
  var directory = "storage/" + parsed_url.host + (parsed_url.pathname || '');
  log.debug(response.from + "Incoming request " + parsed_url.href);
  if (request.headers['user-agent'] && request.headers['user-agent'].match(/^git/)) {
    process_git_request(response, request.url, directory);
    return;
  }
  if (parsed_url.query) {
    var shasum = crypto.createHash('sha1');
    shasum.update(parsed_url.query);
    var hash = shasum.digest('hex');
    directory += '/' + hash;
  }
  var not_found = argv.no_proxy ? function(response, headers, parsed_url, directory) {
    response.statusCode = 500;
    response.end();
    log.error(response.from + 'File not found on proxy', directory);
  } : proxy;
  if (request.method == 'GET') {
    process_req(response, request.headers, parsed_url, directory, undefined, not_found);
  }
  else {
    var shasum = crypto.createHash('sha1');
    var body_chunks = [];
    request.on('data', function(chunk) {
      shasum.update(chunk);
      body_chunks.push(chunk);
    })
    request.on('end', function() {
      var hash = shasum.digest('hex');
      directory += '/' + hash;
      process_req(response, request.headers, parsed_url, directory, body_chunks, not_found);
    })
  }
}).on('clientError', function(e) {
Example #30
0
exports.calcBlobRef = function(buffer) {
  var hash = crypto.createHash('sha1');
  hash.update(buffer.toString('binary'));
  return 'sha1-' + hash.digest('hex');
};