/usr/lib/nodejs/connect/utils.js is in node-connect 1.7.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | /*!
* Connect - utils
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var crypto = require('crypto')
, Path = require('path')
, fs = require('fs');
/**
* Flatten the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
exports.flatten = function(arr, ret){
var ret = ret || []
, len = arr.length;
for (var i = 0; i < len; ++i) {
if (Array.isArray(arr[i])) {
exports.flatten(arr[i], ret);
} else {
ret.push(arr[i]);
}
}
return ret;
};
/**
* Return md5 hash of the given string and optional encoding,
* defaulting to hex.
*
* utils.md5('wahoo');
* // => "e493298061761236c96b02ea6aa8a2ad"
*
* @param {String} str
* @param {String} encoding
* @return {String}
* @api public
*/
exports.md5 = function(str, encoding){
return crypto
.createHash('md5')
.update(str)
.digest(encoding || 'hex');
};
/**
* Merge object b with object a.
*
* var a = { foo: 'bar' }
* , b = { bar: 'baz' };
*
* utils.merge(a, b);
* // => { foo: 'bar', bar: 'baz' }
*
* @param {Object} a
* @param {Object} b
* @return {Object}
* @api public
*/
exports.merge = function(a, b){
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api public
*/
exports.escape = function(html){
return String(html)
.replace(/&(?!\w+;)/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
/**
* Return a unique identifier with the given `len`.
*
* utils.uid(10);
* // => "FDaS435D2z"
*
* @param {Number} len
* @return {String}
* @api public
*/
exports.uid = function(len) {
var buf = []
, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
, charlen = chars.length;
for (var i = 0; i < len; ++i) {
buf.push(chars[getRandomInt(0, charlen - 1)]);
}
return buf.join('');
};
/**
* Parse the given cookie string into an object.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parseCookie = function(str){
var obj = {}
, pairs = str.split(/[;,] */);
for (var i = 0, len = pairs.length; i < len; ++i) {
var pair = pairs[i]
, eqlIndex = pair.indexOf('=')
, key = pair.substr(0, eqlIndex).trim().toLowerCase()
, val = pair.substr(++eqlIndex, pair.length).trim();
// quoted values
if ('"' == val[0]) val = val.slice(1, -1);
// only assign once
if (undefined == obj[key]) {
val = val.replace(/\+/g, ' ');
try {
obj[key] = decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
obj[key] = val;
} else {
throw err;
}
}
}
}
return obj;
};
/**
* Serialize the given object into a cookie string.
*
* utils.serializeCookie('name', 'tj', { httpOnly: true })
* // => "name=tj; httpOnly"
*
* @param {String} name
* @param {String} val
* @param {Object} obj
* @return {String}
* @api public
*/
exports.serializeCookie = function(name, val, obj){
var pairs = [name + '=' + encodeURIComponent(val)]
, obj = obj || {};
if (obj.domain) pairs.push('domain=' + obj.domain);
if (obj.path) pairs.push('path=' + obj.path);
if (obj.expires) pairs.push('expires=' + obj.expires.toUTCString());
if (obj.httpOnly) pairs.push('httpOnly');
if (obj.secure) pairs.push('secure');
return pairs.join('; ');
};
/**
* Pause `data` and `end` events on the given `obj`.
* Middleware performing async tasks _should_ utilize
* this utility (or similar), to re-emit data once
* the async operation has completed, otherwise these
* events may be lost.
*
* var pause = utils.pause(req);
* fs.readFile(path, function(){
* next();
* pause.resume();
* });
*
* @param {Object} obj
* @return {Object}
* @api public
*/
exports.pause = function(obj){
var onData
, onEnd
, events = [];
// buffer data
obj.on('data', onData = function(data, encoding){
events.push(['data', data, encoding]);
});
// buffer end
obj.on('end', onEnd = function(data, encoding){
events.push(['end', data, encoding]);
});
return {
end: function(){
obj.removeListener('data', onData);
obj.removeListener('end', onEnd);
},
resume: function(){
this.end();
for (var i = 0, len = events.length; i < len; ++i) {
obj.emit.apply(obj, events[i]);
}
}
};
};
/**
* Check `req` and `res` to see if it has been modified.
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @return {Boolean}
* @api public
*/
exports.modified = function(req, res, headers) {
var headers = headers || res._headers || {}
, modifiedSince = req.headers['if-modified-since']
, lastModified = headers['last-modified']
, noneMatch = req.headers['if-none-match']
, etag = headers['etag'];
if (noneMatch) noneMatch = noneMatch.split(/ *, */);
// check If-None-Match
if (noneMatch && etag && ~noneMatch.indexOf(etag)) {
return false;
}
// check If-Modified-Since
if (modifiedSince && lastModified) {
modifiedSince = new Date(modifiedSince);
lastModified = new Date(lastModified);
// Ignore invalid dates
if (!isNaN(modifiedSince.getTime())) {
if (lastModified <= modifiedSince) return false;
}
}
return true;
};
/**
* Strip `Content-*` headers from `res`.
*
* @param {ServerResponse} res
* @api public
*/
exports.removeContentHeaders = function(res){
Object.keys(res._headers).forEach(function(field){
if (0 == field.indexOf('content')) {
res.removeHeader(field);
}
});
};
/**
* Check if `req` is a conditional GET request.
*
* @param {IncomingMessage} req
* @return {Boolean}
* @api public
*/
exports.conditionalGET = function(req) {
return req.headers['if-modified-since']
|| req.headers['if-none-match'];
};
/**
* Respond with 403 "Forbidden".
*
* @param {ServerResponse} res
* @api public
*/
exports.forbidden = function(res) {
var body = 'Forbidden';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.statusCode = 403;
res.end(body);
};
/**
* Respond with 401 "Unauthorized".
*
* @param {ServerResponse} res
* @param {String} realm
* @api public
*/
exports.unauthorized = function(res, realm) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
res.end('Unauthorized');
};
/**
* Respond with 400 "Bad Request".
*
* @param {ServerResponse} res
* @api public
*/
exports.badRequest = function(res) {
res.statusCode = 400;
res.end('Bad Request');
};
/**
* Respond with 304 "Not Modified".
*
* @param {ServerResponse} res
* @param {Object} headers
* @api public
*/
exports.notModified = function(res) {
exports.removeContentHeaders(res);
res.statusCode = 304;
res.end();
};
/**
* Return an ETag in the form of `"<size>-<mtime>"`
* from the given `stat`.
*
* @param {Object} stat
* @return {String}
* @api public
*/
exports.etag = function(stat) {
return '"' + stat.size + '-' + Number(stat.mtime) + '"';
};
/**
* Parse "Range" header `str` relative to the given file `size`.
*
* @param {Number} size
* @param {String} str
* @return {Array}
* @api public
*/
exports.parseRange = function(size, str){
var valid = true;
var arr = str.substr(6).split(',').map(function(range){
var range = range.split('-')
, start = parseInt(range[0], 10)
, end = parseInt(range[1], 10);
// -500
if (isNaN(start)) {
start = size - end;
end = size - 1;
// 500-
} else if (isNaN(end)) {
end = size - 1;
}
// Invalid
if (isNaN(start) || isNaN(end) || start > end) valid = false;
return { start: start, end: end };
});
return valid ? arr : undefined;
};
/**
* Parse the given Cache-Control `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parseCacheControl = function(str){
var directives = str.split(',')
, obj = {};
for(var i = 0, len = directives.length; i < len; i++) {
var parts = directives[i].split('=')
, key = parts.shift().trim()
, val = parseInt(parts.shift(), 10);
obj[key] = isNaN(val) ? true : val;
}
return obj;
};
/**
* Convert array-like object to an `Array`.
*
* node-bench measured "16.5 times faster than Array.prototype.slice.call()"
*
* @param {Object} obj
* @return {Array}
* @api public
*/
var toArray = exports.toArray = function(obj){
var len = obj.length
, arr = new Array(len);
for (var i = 0; i < len; ++i) {
arr[i] = obj[i];
}
return arr;
};
/**
* Retrun a random int, used by `utils.uid()`
*
* @param {Number} min
* @param {Number} max
* @return {Number}
* @api private
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
|