Example #1
0
CommonStream.prototype.emitEvent_ = function(err, data, fin) {
  if (err) {
    this.readable = false;
    this.writeable = false;
    this.emit('error', err);
    return;
  }

  if (this.outputEncoding_ != 'binary') {
    var str = data;
    var len = Buffer.byteLength(str, 'binary');
    data = new Buffer(len);
    if (len > 0) {
      data.write(str, 'binary', 0); 
    }

    if (this.outputEncoding_ != null) {
      data = data.toString(this.outputEncoding_, 0, data.length);
    }
  }
  this.dataQueue_.push(data);

  if (fin) {
    this.dataQueue_.push(null);
  }
  this.emitData_();
};
Example #2
0
  scanText: function () {
    var index = this.buffer.indexOf(this.otag);
    
    if (index === -1) {
      index = this.buffer.length;
    }
    
    var content = this.buffer.substring(0, index)
                             .replace(carriageRegExp, '\r\n')
                             .replace(newlineRegExp, '\n'),
        buffer  = new Buffer(Buffer.byteLength(content));
    
    if (content !== '') {
      buffer.write(content);
      this.appendMultiContent(content);
      this.tokens.push(['static', content, buffer]);
    }
   
    var line = this.currentLine + content;

    this.currentLine = line.substring(line.lastIndexOf('\n') + 1, line.length);
    // console.log('line:', this.buffer.lastIndexOf(newline) + newline.length, index, '>', this.currentLine, '/end');
    this.buffer = this.buffer.substring(index + this.otag.length);
    this.state  = 'tag';
  },
            // Serve the file directly using buffers
            function onRead(err, data) {
                if (err) {
                    next(err);
                    return;
                }

                // For older versions of node convert the string to a buffer.
                if (typeof data === 'string') {
                    var b = new Buffer(data.length);
                    b.write(data, "binary");
                    data = b;
                }

                // Zero length buffers act funny, use a string
                if (data.length === 0) {
                  data = "";
                }

                res.writeHead(200, {
                    "Content-Type": utils.mime.type(filename),
                    "Content-Length": data.length,
                    "Last-Modified": stat.mtime.toUTCString(),
                    "Cache-Control": "public max-age=" + maxAge
                });
                res.end(data);
            }
Example #4
0
CommonStream.prototype.write = function(data, opt_encoding) {
  if (!this.writeable) {
    return true;
  }

  var self = this;
  var buffer = null;

  var encoding = null;
  if (!Buffer.isBuffer(data)) {
    encoding = opt_encoding || this.inputEncoding_ || 'utf8';
  }

  if (encoding !== null) {
    // Not buffer input.
    var len = Buffer.byteLength(data, encoding);
    if (len > 0) {
      buffer = new Buffer(len);
      buffer.write(data, encoding, 0);
    }
  } else {
    buffer = data;
  }

  if (Buffer.isBuffer(buffer)) {
    this.impl_.write(buffer, function(err, data) {
      self.emitEvent_(err, data);
    });
  } else {
    process.nextTick(function() {
      self.emitEvent_(Error('Fishy input'), null);
    });
  }
  return true;
};
Example #5
0
  self.writeMessage = function writeMessage(cmd, data, callback) {
    var len = data ? data.length : 0;
    var buf = new Buffer(5 + len);

    // Command
    buf[0] = cmd;

    // Length
    buf[4] = len & 0xff;
    buf[3] = (len >> 8) & 0xff;
    buf[2] = (len >> 16) & 0xff;
    buf[1] = (len >> 24) & 0xff;

    // Data
    if(data instanceof Buffer) data.copy(buf, 5, 0, len);
    else if(typeof data == 'string') buf.write(data, 5, 'ascii');
    
    if(self.opened) {
      writeMessage_(buf, callback);
      //console.log("Writing message");
      return true;
    }
    else {
      queueMessage_(buf, callback);
      //console.log("Queueing message");
      return false;
    }
  };
Example #6
0
function createBuffer(str, enc) {
  enc = enc || 'utf8';
  var len = Buffer.byteLength(str, enc);
  var buf = new Buffer(len);
  buf.write(str, enc, 0);
  return buf;
}
Example #7
0
 emptyBuffer: function emptyBuffer(bytes) {
   $.checkArgumentType(bytes, 'number', 'bytes');
   var result = new buffer.Buffer(bytes);
   for (var i = 0; i < bytes; i++) {
     result.write('\0', i);
   }
   return result;
 },
Example #8
0
test(function parserError() {
    var boundary = 'abc',
        buffer = new Buffer(5);

    parser.initWithBoundary(boundary);
    buffer.write('--ad', 'ascii', 0);
    assert.equal(parser.write(buffer), 5);
});
Example #9
0
 function processFile(err, string) {
   if (err) { callback(err); return; }
   var headers = {
     "Content-Type": Mime.type(path),
     "Cache-Control": "public, max-age=32000000"
   };
   var buffer = new Buffer(string.length);
   buffer.write(string, 'binary');
   postProcess(headers, buffer, version, path, this);
 },
Example #10
0
 var md51 = function (str) {
     var Buffer = require('buffer').Buffer;
     var buf = new Buffer(1024);
     var len = buf.write(str, 0);
     str = buf.toString('binary', 0, len);
     var md5sum = crypto.createHash('md5');
     md5sum.update(str);
     str = md5sum.digest('hex');
     return str;
 };
['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
  buf.fill(0xFF);
  written = buf.write('abcd', 0, 2, encoding);
  console.log(buf);
  assert.equal(written, 2);
  assert.equal(buf[0], 0x61);
  assert.equal(buf[1], 0x00);
  assert.equal(buf[2], 0xFF);
  assert.equal(buf[3], 0xFF);
});
Connection.prototype.onbody = function(body){
  if(this.connection.key_3) return;
  
  var tmp = new Buffer(8);
  tmp.write(body, "utf8", 0);
  
  this.connection.key_3 = tmp.toString("utf8", 0, 8);
  tmp = undefined;
  
  this.emit("handshake");
};
Example #13
0
Rcon.prototype.send = function(data, cmd, id) {
  cmd = cmd || PacketType.COMMAND;
  id = id || this.rconId;

  var sendBuf = new Buffer(data.length + 16);
  sendBuf.writeInt32LE(data.length + 12, 0);
  sendBuf.writeInt32LE(id, 4);
  sendBuf.writeInt32LE(cmd, 8);
  sendBuf.write(data, 12);
  sendBuf.writeInt32LE(0, data.length + 12);
  this.socket.write(sendBuf.toString('binary'), 'binary');
};
Example #14
0
 function send_response(stream, cookie, challenge) {
     var hash = require('crypto').createHash('md5');
     debug("Sending for cookie="+cookie+", challenge="+challenge);
     hash.update(cookie);
     hash.update(challenge.toString());
     var buf = new Buffer(19);
     write_int(buf, 17, 0, 2);
     buf[2] = 97; // 'a'
     buf.write(hash.digest('binary'), 3, 'binary');
     debug("snd answer: " + buf_to_string(buf));
     stream.write(buf);
 }
Example #15
0
Protocol.prototype.execute = function(d) {
  var res = this.res;
  res.raw += d;

  switch (this.state) {
    case 'headers':
      var endHeaderIndex = res.raw.indexOf('\r\n\r\n');

      if (endHeaderIndex < 0) break;

      var rawHeader = res.raw.slice(0, endHeaderIndex);
      var endHeaderByteIndex = Buffer.byteLength(rawHeader, 'utf8');
      var lines = rawHeader.split('\r\n');
      for (var i = 0; i < lines.length; i++) {
        var kv = lines[i].split(/: +/);
        res.headers[kv[0]] = kv[1];
      }

      this.contentLength = +res.headers['Content-Length'];
      this.bodyStartByteIndex = endHeaderByteIndex + 4;

      this.state = 'body';

      var len = Buffer.byteLength(res.raw, 'utf8');
      if (len - this.bodyStartByteIndex < this.contentLength) {
        break;
      }
      // falls through
    case 'body':
      var resRawByteLength = Buffer.byteLength(res.raw, 'utf8');

      if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) {
        var buf = new Buffer(resRawByteLength);
        buf.write(res.raw, 0, resRawByteLength, 'utf8');
        res.body =
            buf.slice(this.bodyStartByteIndex,
                      this.bodyStartByteIndex +
                      this.contentLength).toString('utf8');
        // JSON parse body?
        res.body = res.body.length ? JSON.parse(res.body) : {};

        // Done!
        this.onResponse(res);

        this._newRes(buf.slice(this.bodyStartByteIndex +
                               this.contentLength).toString('utf8'));
      }
      break;

    default:
      throw new Error('Unknown state');
  }
};
Example #16
0
exports.inflate = function(buffer, ready) {
  try {
    var hex = buffer.toString('base64'),
        result = jxg.JXG.decompress(hex),
        bytes = Buffer.byteLength(result),
        buff = new Buffer(bytes);

    buff.write(result); 
    setTimeout(function(){ ready(null, buff); }, 0);
  } catch(err) {
    setTimeout(function(){ ready(err); }, 0);
  } 
};
Example #17
0
Utf7IMAPEncoder.prototype.end = function() {
    var buf = new Buffer(10), bufIdx = 0;
    if (this.inBase64) {
        if (this.base64AccumIdx > 0) {
            bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
            this.base64AccumIdx = 0;
        }

        buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
        this.inBase64 = false;
    }

    return buf.slice(0, bufIdx);
}
Example #18
0
  var server = dgram.createSocket('udp4', function(msg, rinfo) {
    console.log('server got: ' + msg +
                ' from ' + rinfo.address + ':' + rinfo.port);

    if (/PING/.exec(msg)) {
      var buf = new Buffer(4);
      buf.write('PONG');
      server.send(buf, 0, buf.length,
                  rinfo.port, rinfo.address,
                  function(err, sent) {
                    callbacks++;
                  });
    }
  });
Example #19
0
  var server = dgram.createSocket(function (msg, rinfo) {
    console.log("connection: " + rinfo.address + ":"+ rinfo.port);

    console.log("server got: " + msg);

    if (/PING/.exec(msg)) {
      var buf = new Buffer(4);
      buf.write('PONG');
      server.send(rinfo.port, rinfo.address, buf, 0, buf.length, function (err, sent) {
        callbacks++;
      });
    }

  });
Example #20
0
 res.write = function (chunk, encoding) {
     if (typeof chunk === 'string') {
         var length;
         if (!encoding || encoding === 'utf8') {
             length = Buffer.byteLength(chunk);
         }
         var buffer = new Buffer(length);
         buffer.write(chunk, encoding);
         chunks.push(buffer);
     } else {
         chunks.push(chunk);
     }
     totalSize += chunk.length;
 };
Example #21
0
function write_boot2() {
	if (typeof boot2_enc_algo === "undefined") {
		/* Add 16 zeros for MIC */
		var zero_buf = new Buffer(16);
		zero_buf.fill(0);
		boot2_buf.write(zero_buf.toString('hex'), es_size + boot2_len, 16, 'hex');
	}
	/* Add 16 to length for MIC */
	boot2_len += 16;
	boot2_buf = boot2_buf.slice(0, es_size + boot2_len);
	var filename = get_outfile_name();
	fs.writeFileSync(filename, boot2_buf, 'hex');

	console.log("\r\nGenerated " + filename);
}
Example #22
0
var srv = net.createServer(function(s) {
  var str = JSON.stringify(DATA) + '\n';

  DATA.ord = DATA.ord + 1;
  var buf = new buffer.Buffer(str.length);
  buf.write(JSON.stringify(DATA) + '\n', 'utf8');

  s.write(str, 'utf8', pipeFDs[1]);
  if (s.write(buf, undefined, pipeFDs[1])) {
    netBinding.close(pipeFDs[1]);
  } else {
    s.addListener('drain', function() {
      netBinding.close(pipeFDs[1]);
    });
  }
});
Example #23
0
['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
  var f = new Buffer('über', encoding);
  console.error('f.length: %d     (should be 8)', f.length);
  assert.deepEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0]));

  var f = new Buffer('привет', encoding);
  console.error('f.length: %d     (should be 12)', f.length);
  assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4]));
  assert.equal(f.toString(encoding), 'привет');

  var f = new Buffer([0, 0, 0, 0, 0]);
  assert.equal(f.length, 5);
  var size = f.write('あいうえお', encoding);
  console.error('bytes written to buffer: %d     (should be 4)', size);
  assert.equal(size, 4);
  assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00]));
});
Example #24
0
    encode: function (val) {
        if (typeof(val) !== 'string')
            throw new TypeError('Name (string) is required');

        var parts = val.split(/\./i);
        var buff = new Buffer(parts.toString().length + 2);
        var offset = 0;

        // [3]www[5]google[2]pl[0]
        for (var i = 0; i < parts.length; ++i) {
            var len = parts[i].length;
            buff[offset] = len;
            buff.write(parts[i], ++offset, len, 'utf8');
            offset += len;
        }
        buff[offset] = 0x00;
        return buff;
    },
Example #25
0
    self.write = function() {
        var bl = (typeof arguments[0] === 'string') ?
            Buffer.byteLength(arguments[0], arguments[1]) :
            arguments[0].length;

        if (bufOffset + bl >= buf.length) {
            var b = new Buffer(((bufOffset + bl + bufSz - 1) / bufSz) * bufSz);
            buf.copy(b, 0, 0, bufOffset);
            buf = b;
        }

        if (typeof arguments[0] === 'string') {
            buf.write(arguments[0], bufOffset, arguments[1]);
        } else {
            arguments[0].copy(buf, bufOffset, 0, arguments[0].length);
        }

        bufOffset += bl;
    };
Example #26
0
    rfb.addListener('endRects', function (nRects) {
        if (nRects > 1) {
            var png = pngStack.encode();
            var pngBuf = new Buffer(png.length);
            pngBuf.write(png, 'binary');

            var dims = pngStack.dimensions();
            vm.emit('png', {
                image : pngBuf,
                image64 : base64_encode(pngBuf),
                width : dims.width,
                height : dims.height,
                x : dims.x,
                y : dims.y
            });
        }
        if (screencastRequests && screencastId) {
            vm.emit('screencastEndPush');
        }
    });
Example #27
0
  socketOnConnect() {
    this.emit('connect');

    if (this.tcp) {
      this.send(this.password, PacketType.AUTH);
    } else if (this.challenge) {
      let str = "challenge rcon\n";
      let sendBuf = new Buffer(str.length + 4);
      sendBuf.writeInt32LE(-1, 0);
      sendBuf.write(str, 4);
      this._sendSocket(sendBuf);
    } else {
      let sendBuf = new Buffer(5);
      sendBuf.writeInt32LE(-1, 0);
      sendBuf.writeUInt8(0, 4);
      this._sendSocket(sendBuf);

      this.hasAuthed = true;
      this.emit('auth');
    }
  }
Example #28
0
  server.addListener("listening", function () {
    console.log("server listening on " + port + " " + host);

    var buf = new Buffer(4);
    buf.write('PING');

    var client = dgram.createSocket();

    client.addListener("message", function (msg, rinfo) {
      console.log("client got: " + msg);
      assert.equal("PONG", msg.toString('ascii'));

      count += 1;

      if (count < N) {
        client.send(port, host, buf, 0, buf.length);
      } else {
        sent_final_ping = true;
        client.send(port, host, buf, 0, buf.length);
        process.nextTick(function() {
          client.close();
        });
      }
    });

    client.addListener("close", function () {
      console.log('client.close');
      assert.equal(N, count);
      tests_run += 1;
      server.close();
      assert.equal(N-1, callbacks);
    });

    client.addListener("error", function (e) {
      throw e;
    });

    client.send(port, host, buf, 0, buf.length);
    count += 1;
  });
Example #29
0
    'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi',
    'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser',
    '-agent10010120020120220320420520630030130230330430530630740040140240340440',
    '5406407408409410411412413414415416417500501502503504505accept-rangesageeta',
    'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic',
    'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran',
    'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati',
    'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo',
    'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe',
    'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic',
    'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1',
    '.1statusversionurl'
  ].join(''),
  flatDict = new Buffer(flatDictStr.length + 1);

flatDict.write(flatDictStr, 'ascii');
flatDict[flatDict.length - 1] = 0;

var ZLib = exports.ZLib = function() {
  this.context = new ZLibContext(flatDict);
};

exports.createZLib = function() {
  return new ZLib();
};

ZLib.prototype.deflate = function(buffer) {
  return this.context.deflate(buffer);
};

ZLib.prototype.inflate = function(buffer) {
Example #30
0
 it('writes a string to a buffer.', function () {
   var buffer = new Buffer(128);
   buffer.write('안녕, 세계!');
   assert.equal(buffer.toString('UTF-8', 0, 15), '안녕, 세계!');
 });