Example #1
0
    fs.readFileSync = function (pathArgument, options) {
      const { isAsar, asarPath, filePath } = splitPath(pathArgument)
      if (!isAsar) return readFileSync.apply(this, arguments)

      const archive = getOrCreateArchive(asarPath)
      if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath })

      const info = archive.getFileInfo(filePath)
      if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })

      if (info.size === 0) return (options) ? '' : Buffer.alloc(0)
      if (info.unpacked) {
        const realPath = archive.copyFileOut(filePath)
        return fs.readFileSync(realPath, options)
      }

      if (!options) {
        options = { encoding: null }
      } else if (typeof options === 'string') {
        options = { encoding: options }
      } else if (typeof options !== 'object') {
        throw new TypeError('Bad arguments')
      }

      const { encoding } = options
      const buffer = Buffer.alloc(info.size)
      const fd = archive.getFd()
      if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath })

      logASARAccess(asarPath, filePath, info.offset)
      fs.readSync(fd, buffer, 0, info.size, info.offset)
      return (encoding) ? buffer.toString(encoding) : buffer
    }
Example #2
0
    fs.readFile = function (pathArgument, options, callback) {
      const { isAsar, asarPath, filePath } = splitPath(pathArgument)
      if (!isAsar) return readFile.apply(this, arguments)

      if (typeof options === 'function') {
        callback = options
        options = { encoding: null }
      } else if (typeof options === 'string') {
        options = { encoding: options }
      } else if (options === null || options === undefined) {
        options = { encoding: null }
      } else if (typeof options !== 'object') {
        throw new TypeError('Bad arguments')
      }

      const { encoding } = options
      const archive = getOrCreateArchive(asarPath)
      if (!archive) {
        const error = createError(AsarError.INVALID_ARCHIVE, { asarPath })
        nextTick(callback, [error])
        return
      }

      const info = archive.getFileInfo(filePath)
      if (!info) {
        const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
        nextTick(callback, [error])
        return
      }

      if (info.size === 0) {
        nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)])
        return
      }

      if (info.unpacked) {
        const realPath = archive.copyFileOut(filePath)
        return fs.readFile(realPath, options, callback)
      }

      const buffer = Buffer.alloc(info.size)
      const fd = archive.getFd()
      if (!(fd >= 0)) {
        const error = createError(AsarError.NOT_FOUND, { asarPath, filePath })
        nextTick(callback, [error])
        return
      }

      logASARAccess(asarPath, filePath, info.offset)
      fs.read(fd, buffer, 0, info.size, info.offset, error => {
        callback(error, encoding ? buffer.toString(encoding) : buffer)
      })
    }
Example #3
0
	handleNewData(newData) {
		try {
			//console.log( "BLE: newData:" + JSON.stringify(newData));
			var rxBuffers = this.state.rxBuffers;
			// Convert bytes array to string
			data = newData.value;
			characteristic = newData.characteristic;
			var tmpData = Buffer.alloc(data.length);
			var tmpDataLen = 0;
			for (var i = 0; i < data.length; i++) {
				var oneChar = data[i];
				// Do we have the end-of-json delimeter?
				if (oneChar == ";".charCodeAt(0)) {
					if (tmpData.length > 0) {
						// Push the new bytes avail
						tmpDataBuffer = Buffer.alloc(tmpDataLen);
						tmpData.copy(tmpDataBuffer, 0, 0, tmpDataLen);
						rxBuffers.push(tmpDataBuffer);
					}
					newMessage = Buffer.concat(rxBuffers);
					var newState = JSON.parse(newMessage.toString('ascii'));

					// Setup the app-specific mediaState structure
					this.setState({ mediaState: BLEBoardData.updateMediaState(this.state.mediaState, newState) });
					rxBuffers = [];
					this.setState({ rxBuffers: rxBuffers });
					tmpData = Buffer.alloc(1024);
					tmpDataLen = 0;
				} else {
					// Add characters to buffer
					if (oneChar > 0) {
						tmpData[tmpDataLen] = oneChar;
						tmpDataLen++;
					}
				}
			}
			tmpDataBuffer = Buffer.alloc(tmpDataLen);
			tmpData.copy(tmpDataBuffer, 0, 0, tmpDataLen);
			if (tmpDataLen > 0) {
				if (!rxBuffers) {
					rxBuffers = [tmpDataBuffer];
				} else {
					rxBuffers.push(tmpDataBuffer);
				}
			}
		} catch (error) {
			console.log("BLE:handleNewData error: " + error);
			console.log("BLE:handleNewData message: " + newMessage);
			rxBuffers = [];
			this.setState({ rxBuffers: rxBuffers });
		}
	}
Example #4
0
Zlib.prototype.flush = function (kind, callback) {
  var _this2 = this;

  var ws = this._writableState;

  if (typeof kind === 'function' || kind === undefined && !callback) {
    callback = kind;
    kind = binding.Z_FULL_FLUSH;
  }

  if (ws.ended) {
    if (callback) process.nextTick(callback);
  } else if (ws.ending) {
    if (callback) this.once('end', callback);
  } else if (ws.needDrain) {
    if (callback) {
      this.once('drain', function () {
        return _this2.flush(kind, callback);
      });
    }
  } else {
    this._flushFlag = kind;
    this.write(Buffer.alloc(0), '', callback);
  }
};
Example #5
0
function ReadFixedRequest(length, callback)
{
    this.length = length;
    this.callback = callback;
    this.data = Buffer.alloc(length);
    this.received_bytes = 0;
}
Example #6
0
async function readFileHandle(filehandle, options) {
  const statFields = await binding.fstat(filehandle.fd, false, kUsePromises);

  let size;
  if ((statFields[1/* mode */] & S_IFMT) === S_IFREG) {
    size = statFields[8/* size */];
  } else {
    size = 0;
  }

  if (size > kMaxLength)
    throw new ERR_FS_FILE_TOO_LARGE(size);

  const chunks = [];
  const chunkSize = size === 0 ?
    kReadFileMaxChunkSize :
    Math.min(size, kReadFileMaxChunkSize);
  let endOfFile = false;
  do {
    const buf = Buffer.alloc(chunkSize);
    const { bytesRead, buffer } =
      await read(filehandle, buf, 0, chunkSize, -1);
    endOfFile = bytesRead === 0;
    if (bytesRead > 0)
      chunks.push(buffer.slice(0, bytesRead));
  } while (!endOfFile);

  const result = Buffer.concat(chunks);
  if (options.encoding) {
    return result.toString(options.encoding);
  } else {
    return result;
  }
}
Example #7
0
File: zlib.js Project: Frrank1/node
Zlib.prototype.flush = function flush(kind, callback) {
  var ws = this._writableState;

  if (typeof kind === 'function' || (kind === undefined && !callback)) {
    callback = kind;
    kind = Z_FULL_FLUSH;
  }

  if (ws.ended) {
    if (callback)
      process.nextTick(callback);
  } else if (ws.ending) {
    if (callback)
      this.once('end', callback);
  } else if (ws.needDrain) {
    const alreadyHadFlushScheduled = this._scheduledFlushFlag !== Z_NO_FLUSH;
    this._scheduledFlushFlag = maxFlush(kind, this._scheduledFlushFlag);

    // If a callback was passed, always register a new `drain` + flush handler,
    // mostly because that's simpler and flush callbacks piling up is a rare
    // thing anyway.
    if (!alreadyHadFlushScheduled || callback) {
      const drainHandler = () => this.flush(this._scheduledFlushFlag, callback);
      this.once('drain', drainHandler);
    }
  } else {
    this._flushFlag = kind;
    this.write(Buffer.alloc(0), '', callback);
    this._scheduledFlushFlag = Z_NO_FLUSH;
  }
};
Example #8
0
function scrypt(password, salt, keylen, options, callback = defaults) {
  if (callback === defaults) {
    callback = options;
    options = defaults;
  }

  options = check(password, salt, keylen, options);
  const { N, r, p, maxmem } = options;
  ({ password, salt, keylen } = options);

  if (typeof callback !== 'function')
    throw new ERR_INVALID_CALLBACK();

  const encoding = getDefaultEncoding();
  const keybuf = Buffer.alloc(keylen);

  const wrap = new AsyncWrap(Providers.SCRYPTREQUEST);
  wrap.ondone = (ex) => {  // Retains keybuf while request is in flight.
    if (ex) return callback.call(wrap, ex);
    if (encoding === 'buffer') return callback.call(wrap, null, keybuf);
    callback.call(wrap, null, keybuf.toString(encoding));
  };

  handleError(keybuf, password, salt, N, r, p, maxmem, wrap);
}
Example #9
0
 }))).then(function() {
     if (!acc.length) return Buffer.alloc(0);
     else if (typeof acc[0] === 'string')
         return acc.join('');
     else
         return Buffer.concat(acc);
 });
Example #10
0
Bytes.prototype.__mul__ = function(other) {
    var types = require('../types')

    if (types.isinstance(other, [types.Bool, types.Int])) {
        // Check if value of 'other' Int/Bool value is truthy
        // and 'this' byte object is non-empty
        if (other.valueOf() > 0 && this.valueOf().length > 0) {
            let thisByteLength = this.valueOf().length
            let thisValue = this.valueOf().toString()
            let otherValue = other.valueOf()

            // Add at least one copy of byte object string into buffer
            let byteBuffer = Buffer.alloc(thisByteLength * otherValue)
            byteBuffer.write(thisValue)

            // repeat adding copies as necessary
            if (otherValue > 1) {
                for (let i = 1; i < otherValue; i++) {
                    byteBuffer.write(thisValue, i * thisByteLength)
                }
            }

            return new Bytes(byteBuffer)
        } else {
            return new Bytes('')
        }
    } else {
        throw new exceptions.TypeError.$pyclass("can't multiply sequence by non-int of type '" + type_name(other) + "'")
    }
}
Example #11
0
IndexEntry.prototype.toBuffer = function(version) {
    var output = Concentrate()

        // ctime
        .uint32be(this.getCTime().getTime())
        .uint32be(0)

        // mtime
        .uint32be(this.getMTime().getTime())
        .uint32be(0)

        .uint32be(this.getDev())
        .uint32be(this.getIno())
        .uint32be(this.getUid())
        .uint32be(this.getGid())
        .uint32be(this.getEntrySize())
        .buffer((new Buffer(this.getSha())).toString('hex'))
        .uint16be(this.getFlags());


    if (version >= 3) output = output.uint16be(this.getExtendedFlags());
    output = output.string(this.getPath());

    var buf = output.result();
    var padlen = (8 - (buf.length % 8)) || 8;

    return Buffer.concat([
        buf,
        Buffer.alloc(padlen, 0)
    ]);
};
Example #12
0
module.exports.buildChoke = () => {
  const buf = Buffer.alloc(5);
  // length
  buf.writeUInt32BE(1, 0);
  // id
  buf.writeUInt8(0, 4);
  return buf;
};
Example #13
0
module.exports.buildUninterested = () => {
  const buf = Buffer.alloc(5);
  // length
  buf.writeUInt32BE(1, 0);
  // id
  buf.writeUInt8(3, 4);
  return buf;
};
Example #14
0
function pbkdf2Sync(password, salt, iterations, keylen, digest) {
  ({ password, salt, iterations, keylen, digest } =
    check(password, salt, iterations, keylen, digest));
  const keybuf = Buffer.alloc(keylen);
  handleError(keybuf, password, salt, iterations, digest);
  const encoding = getDefaultEncoding();
  if (encoding === 'buffer') return keybuf;
  return keybuf.toString(encoding);
}
Example #15
0
function packSbox(input) {
  const ret = Buffer.alloc(input.length / 2);
  const rows = input.length & 0xF0;
  for (let idx=0; idx<input.length; idx+=2) {
    let retIdx = (rows - 0x10 - (idx & 0xF0)) | idx & 0x0F;
    ret[retIdx >> 1] = input[idx] << 4 | input[idx+1];
  }
  return ret;
}
Example #16
0
Socket.prototype.send = function(buffer,
                                 offset,
                                 length,
                                 port,
                                 address,
                                 callback) {
  const self = this;
  let list;

  if (address || (port && typeof port !== 'function')) {
    buffer = sliceBuffer(buffer, offset, length);
  } else {
    callback = port;
    port = offset;
    address = length;
  }

  if (!Array.isArray(buffer)) {
    if (typeof buffer === 'string') {
      list = [ Buffer.from(buffer) ];
    } else if (!(buffer instanceof Buffer)) {
      throw new TypeError('First argument must be a buffer or a string');
    } else {
      list = [ buffer ];
    }
  } else if (!(list = fixBufferList(buffer))) {
    throw new TypeError('Buffer list arguments must be buffers or strings');
  }

  port = port >>> 0;
  if (port === 0 || port > 65535)
    throw new RangeError('Port should be > 0 and < 65536');

  // Normalize callback so it's either a function or undefined but not anything
  // else.
  if (typeof callback !== 'function')
    callback = undefined;

  self._healthCheck();

  if (self._bindState == BIND_STATE_UNBOUND)
    self.bind({port: 0, exclusive: true}, null);

  if (list.length === 0)
    list.push(Buffer.alloc(0));

  // If the socket hasn't been bound yet, push the outbound packet onto the
  // send queue and send after binding is complete.
  if (self._bindState != BIND_STATE_BOUND) {
    enqueue(self, self.send.bind(self, list, port, address, callback));
    return;
  }

  self._handle.lookup(address, function afterDns(ex, ip) {
    doSend(ex, self, ip, list, address, port, callback);
  });
};
Example #17
0
function scryptSync(password, salt, keylen, options = defaults) {
  options = check(password, salt, keylen, options);
  const { N, r, p, maxmem } = options;
  ({ password, salt, keylen } = options);
  const keybuf = Buffer.alloc(keylen);
  handleError(keybuf, password, salt, N, r, p, maxmem);
  const encoding = getDefaultEncoding();
  if (encoding === 'buffer') return keybuf;
  return keybuf.toString(encoding);
}
Example #18
0
 reset() {
   if (this._http) {
     this._http.destroy();
   }
   this._http = null;
   this._lastId = 0;
   this._socket = null;
   this._pending = {};
   this._unprocessed = Buffer.alloc(0);
 }
Example #19
0
module.exports.buildPort = payload => {
  const buf = Buffer.alloc(7);
  // length
  buf.writeUInt32BE(3, 0);
  // id
  buf.writeUInt8(9, 4);
  // listen-port
  buf.writeUInt16BE(payload, 5);
  return buf;
};
Example #20
0
module.exports.buildBitfield = bitfield => {
  const buf = Buffer.alloc(14);
  // length
  buf.writeUInt32BE(payload.length + 1, 0);
  // id
  buf.writeUInt8(5, 4);
  // bitfield
  bitfield.copy(buf, 5);
  return buf;
};
Example #21
0
module.exports.buildHave = payload => {
  const buf = Buffer.alloc(9);
  // length
  buf.writeUInt32BE(5, 0);
  // id
  buf.writeUInt8(4, 4);
  // piece index
  buf.writeUInt32BE(payload, 5);
  return buf;
};
Example #22
0
function buildAnnounceReq(torrent, id, connResp) {
  const connectionId = connResp.connectionId;
  const action = bignum.toBuffer(1, {size: 4});
  const transactionId = bignum.toBuffer(util.randInt32(), {size: 4});
  const infoHash = torrentParser.infoHash(torrent);
  const peerId = Buffer.from(id);
  const downloaded = Buffer.alloc(8, 0);
  const left = bignum.toBuffer(torrentParser.size(torrent), {size: 8});
  const uploaded = Buffer.alloc(8, 0);
  const event = Buffer.alloc(4, 0);
  const ipAddress = Buffer.alloc(4, 0);
  const key = bignum.toBuffer(util.randInt32(), {size: 4});
  const numWant = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF]);
  const port = bignum.toBuffer(6881, {size: 2});

  const buffers = [connectionId, action, transactionId, infoHash, peerId,
    downloaded, left, uploaded, event, ipAddress, key, numWant, port];

  return Buffer.concat(buffers, 98);
}
Example #23
0
module.exports.readPng = function(path)
{
    var pngData = fs.readFileSync(path);
    var j = new PNG(pngData);
    var imageData = {};
    imageData.width = j.width;
    imageData.height = j.height;
    imageData.data = Buffer.alloc(j.width*j.height*4);
    j.render(imageData);
    return imageData;
}
Example #24
0
var decode_data = function (parsed, pw) {
    var bkey;

    var ctx = Gost.init();
    var buf, obuf;
    bkey = convert_password(parsed, pw, true);
    ctx.key(bkey);

    if (parsed.format === 'IIT') {
        buf = Buffer.concat([parsed.body, parsed.pad]);
        obuf = Buffer.alloc(buf.length);
        ctx.decrypt(buf, obuf);
        return obuf.slice(0, parsed.body.length);
    }
    if (parsed.format === 'PBES2') {
        buf = parsed.body;
        obuf = Buffer.alloc(buf.length);
        ctx.decrypt_cfb(parsed.iv, buf, obuf);
        return obuf;
    }
};
Example #25
0
  flush (kind) {
    if (kind === undefined)
      kind = constants.Z_FULL_FLUSH

    if (this.ended)
      return

    const flushFlag = this[_flushFlag]
    this[_flushFlag] = kind
    this.write(Buffer.alloc(0))
    this[_flushFlag] = flushFlag
  }
BufferList.prototype.concat = function (n) {
  if (this.length === 0) return Buffer.alloc(0);
  if (this.length === 1) return this.head.data;
  var ret = Buffer.allocUnsafe(n >>> 0);
  var p = this.head;
  var i = 0;
  while (p) {
    p.data.copy(ret, i);
    i += p.data.length;
    p = p.next;
  }
  return ret;
};
Example #27
0
 concat(n) {
   if (this.length === 0)
     return Buffer.alloc(0);
   const ret = Buffer.allocUnsafe(n >>> 0);
   var p = this.head;
   var i = 0;
   while (p) {
     copyBuffer(p.data, ret, i);
     i += p.data.length;
     p = p.next;
   }
   return ret;
 }
Example #28
0
function encodeFrameHybi17(payload) {
  var i;

  const dataLength = payload.length;

  let singleByteLength;
  let additionalLength;
  if (dataLength > kMaxTwoBytePayloadLength) {
    singleByteLength = kEightBytePayloadLengthField;
    additionalLength = Buffer.alloc(8);
    let remaining = dataLength;
    for (i = 0; i < 8; ++i) {
      additionalLength[7 - i] = remaining & 0xFF;
      remaining >>= 8;
    }
  } else if (dataLength > kMaxSingleBytePayloadLength) {
    singleByteLength = kTwoBytePayloadLengthField;
    additionalLength = Buffer.alloc(2);
    additionalLength[0] = (dataLength & 0xFF00) >> 8;
    additionalLength[1] = dataLength & 0xFF;
  } else {
    additionalLength = Buffer.alloc(0);
    singleByteLength = dataLength;
  }

  const header = Buffer.from([
    kFinalBit | kOpCodeText,
    kMaskBit | singleByteLength,
  ]);

  const mask = Buffer.alloc(4);
  const masked = Buffer.alloc(dataLength);
  for (i = 0; i < dataLength; ++i) {
    masked[i] = payload[i] ^ mask[i % kMaskingKeyWidthInBytes];
  }

  return Buffer.concat([header, additionalLength, mask, masked]);
}
Example #29
0
module.exports.buildPiece = payload => {
  const buf = Buffer.alloc(payload.block.length + 13);
  // length
  buf.writeUInt32BE(payload.block.length + 9, 0);
  // id
  buf.writeUInt8(7, 4);
  // piece index
  buf.writeUInt32BE(payload.index, 5);
  // begin
  buf.writeUInt32BE(payload.begin, 9);
  // block
  payload.block.copy(buf, 13);
  return buf;
};
Example #30
0
module.exports.buildRequest = payload => {
  const buf = Buffer.alloc(17);
  // length
  buf.writeUInt32BE(13, 0);
  // id
  buf.writeUInt8(6, 4);
  // piece index
  buf.writeUInt32BE(payload.index, 5);
  // begin
  buf.writeUInt32BE(payload.begin, 9);
  // length
  buf.writeUInt32BE(payload.length, 13);
  return buf;
};