Gets Binary Packets

See '6. Binary Packet Protocol' of rfc4253 for more info.

@see self::_send_binary_packet()
@return string
@access private
518813
function _get_binary_packet($skip_channel_filter = false)
    {
        if (!is_resource($this->fsock) || feof($this->fsock)) {
            user_error('Connection closed prematurely');
            $this->bitmap = 0;
            return false;
        }

        $start = microtime(true);
        $raw = stream_get_contents($this->fsock, $this->decrypt_block_size);

        if (!strlen($raw)) {
            return '';
        }

        if ($this->decrypt !== false) {
            $raw = $this->decrypt->decrypt($raw);
        }
        if ($raw === false) {
            user_error('Unable to decrypt content');
            return false;
        }

        if (strlen($raw) < 5) {
            return false;
        }
        extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));

        $remaining_length = $packet_length + 4 - $this->decrypt_block_size;

        // quoting <http://tools.ietf.org/html/rfc4253#section-6.1>,
        // "implementations SHOULD check that the packet length is reasonable"
        // PuTTY uses 0x9000 as the actual max packet size and so to shall we
        if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {
            if (!$this->bad_key_size_fix && $this->_bad_algorithm_candidate($this->decrypt_algorithm) && !($this->bitmap & SSH2::MASK_LOGIN)) {
                $this->bad_key_size_fix = true;
                $this->_reset_connection(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
                return false;
            }
            user_error('Invalid size');
            return false;
        }

        $buffer = '';
        while ($remaining_length > 0) {
            $temp = stream_get_contents($this->fsock, $remaining_length);
            if ($temp === false || feof($this->fsock)) {
                user_error('Error reading from socket');
                $this->bitmap = 0;
                return false;
            }
            $buffer.= $temp;
            $remaining_length-= strlen($temp);
        }

        $stop = microtime(true);
        if (strlen($buffer)) {
            $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
        }

        $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);
        $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty

        if ($this->hmac_check !== false) {
            $hmac = stream_get_contents($this->fsock, $this->hmac_size);
            if ($hmac === false || strlen($hmac) != $this->hmac_size) {
                user_error('Error reading socket');
                $this->bitmap = 0;
                return false;
            } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
                user_error('Invalid HMAC');
                return false;
            }
        }

        //if ($this->decompress) {
        //    $payload = gzinflate(substr($payload, 2));
        //}

        $this->get_seq_no++;

        if (defined('NET_SSH2_LOGGING')) {
            $current = microtime(true);
            $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
            $message_number = '<- ' . $message_number .
                              ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
            $this->_append_log($message_number, $payload);
            $this->last_packet = $current;
        }

        return $this->_filter($payload, $skip_channel_filter);
    }
119143
public function toBytes(): string
    {
        $bytes = '';
        $hex = $this->toHex();

        foreach (range(0, 30, 2) as $i) {
            $bytes .= chr(hexdec(substr($hex, $i, 2)));
        }

        return $bytes;
    }
1279856
public static function getMaxAllowedPacket(): int
  {
    if (!isset(self::$maxAllowedPacket))
    {
      $query              = "show variables like 'max_allowed_packet'";
      $max_allowed_packet = self::executeRow1($query);

      self::$maxAllowedPacket = $max_allowed_packet['Value'];

      // Note: When setting $chunkSize equal to $maxAllowedPacket it is not possible to transmit a LOB
      // with size $maxAllowedPacket bytes (but only $maxAllowedPacket - 8 bytes). But when setting the size of
      // $chunkSize less than $maxAllowedPacket than it is possible to transmit a LOB with size
      // $maxAllowedPacket bytes.
      self::$chunkSize = (int)min(self::$maxAllowedPacket - 8, 1024 * 1024);
    }

    return (int)self::$maxAllowedPacket;
  }
971073
function _send_binary_packet($data)
    {
        if (feof($this->fsock)) {
            //user_error('connection closed prematurely');
            return false;
        }

        $length = strlen($data) + 4;

        $padding = Random::string(8 - ($length & 7));

        $orig = $data;
        $data = $padding . $data;
        $data.= pack('N', $this->_crc($data));

        if ($this->crypto !== false) {
            $data = $this->crypto->encrypt($data);
        }

        $packet = pack('Na*', $length, $data);

        $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
        $result = strlen($packet) == fputs($this->fsock, $packet);
        $stop = strtok(microtime(), ' ') + strtok('');

        if (defined('NET_SSH1_LOGGING')) {
            $temp = isset($this->protocol_flags[ord($orig[0])]) ? $this->protocol_flags[ord($orig[0])] : 'UNKNOWN';
            $temp = '-> ' . $temp .
                    ' (' . round($stop - $start, 4) . 's)';
            $this->_append_log($temp, $orig);
        }

        return $result;
    }
1250720
public static function getByteOrder()
	{
		if (!isset(self::$_byte_order)) {
			// Check if "pack" gives the required IEEE 64bit float
			$teststr = pack("d", 1.2345);
			$number  = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
			if ($number == $teststr) {
				$byte_order = 0;    // Little Endian
			} elseif ($number == strrev($teststr)){
				$byte_order = 1;    // Big Endian
			} else {
				// Give up. I'll fix this in a later version.
				throw new PHPExcel_Writer_Exception("Required floating point format not supported on this platform.");
			}
			self::$_byte_order = $byte_order;
		}

		return self::$_byte_order;
	}
894933
public function decodeUint64()
    {
        $value = $this->decodeBytes(8);
        if ($value === null) {
            return null;
        }
        return gmp_init(bin2hex($value), 16);
    }
1111391
public function to_bin()
   {
         $out = "";
      for ($i=0; $i<$this->dataLength($this->data); $i++)
         $out = sprintf("%08b",$this->data[$i]).$out;
      return $out;      
   }
949716
public static function getByte(&$p)
    {
        $r = static::bytes2int($p{0});
        $p = static::binarySubstr($p, 1);

        return (int) $r;
    }
10799
public function serializePartialToString() {
    $enc = new Encoder();
    $this->outputPartial($enc);
    $res = $enc->toString();

    # Continue to be a little paranoid about the correctness of the protocol
    # buffer implementation.
    if (mt_rand(0, 99) === 0 && $this->byteSizePartial() !== strlen($res)) {
      throw new ProtocolBufferEncodeError(
        "Internal bug: Encoded size doesn't match predicted");
    }
    return $res;
  }
30513
public function getMinHostBinary()
    {
        if ($this->network_size === 32 || $this->network_size === 31) {
            return implode('', array_map(
                function ($quad) {
                    return sprintf(self::FORMAT_BINARY, $quad);
                },
                $this->quads
            ));
        }
        return $this->minHostCalculation(self::FORMAT_BINARY);
    }
446132
protected function getBinaryBuffer() {
		// catch the GD2 output
		ob_start();

		// convert a (probably) color/greyscale image to the monochrome counterpart.
		imagewbmp($this->image);

		// catch contents of the WBMP file.
		$wbmp = ob_get_clean();

		// ignore 2 bytes of WBMP file header
		$i = 2;

		// ignore 2 VLQ's (variable-length quantities) describing WBMP resolution.
		for($j = 0; $j < 2; ++$j) {
			do {
				$test = ord($wbmp[$i]) & 0x80;
				++$i;
			} while($test);
		}

		// return binary buffer as a string of chars (bytes)
		return substr($wbmp, $i);
	}
104404
public function getBinaryMessage()
    {
        $encodedPayload = $this->jsonEncode($this->payload->getPayload());

        return chr(0).
               chr(0).
               chr(32).
               pack('H*', $this->deviceToken).
               chr(0).chr(strlen($encodedPayload)).
               $encodedPayload;
    }
491889
private function readPacket()
    {
        if ($packet = fread($this->_sock, self::HEADER_LEN)) {
            $resp = $this->decodePacketHeader($packet);
            $resp['content'] = '';
            if ($resp['contentLength']) {
                $len  = $resp['contentLength'];
                while ($len && ($buf=fread($this->_sock, $len)) !== false) {
                    $len -= strlen($buf);
                    $resp['content'] .= $buf;
                }
            }
            if ($resp['paddingLength']) {
                $buf = fread($this->_sock, $resp['paddingLength']);
            }
            return $resp;
        } else {
            return false;
        }
    }
1127321
public function consumeUint64()
    {
        $s = $this->consume(8);
        if (self::$native64BitPack) {
            list(, $ret) = unpack("Q", self::$isLittleEndian ? self::swapEndian64($s) : $s);
        } else {
            $d = unpack("Lh/Ll", self::$isLittleEndian ? self::swapHalvedEndian64($s) : $s);
            $ret = $d["h"] << 32 | $d["l"];
        }
        return $ret;
    }
668338
public static function getBinary(): string
    {
        // Custom PHP path
        if (self::$binary === null) {
            if ((self::$binary = getenv('PHP_BINARY_CUSTOM')) === false) {
                self::$binary = PHP_BINARY;
            }
        }

        // HHVM
        if (self::$binary === null && self::isHHVM()) {
            if ((self::$binary = getenv('PHP_BINARY')) === false) {
                self::$binary = PHP_BINARY;
            }
            self::$binary = escapeshellarg(self::$binary) . ' --php';
        }

        // PHP >= 5.4.0
        if (self::$binary === null && defined('PHP_BINARY')) {
            self::$binary = escapeshellarg(PHP_BINARY);
        }

        // PHP < 5.4.0
        if (self::$binary === null) {
            if (PHP_SAPI === 'cli' && isset($_SERVER['_'])) {
                if (strpos($_SERVER['_'], 'phpunit') !== false) {
                    $file = file($_SERVER['_']);

                    if (strpos($file[0], ' ') !== false) {
                        $tmp = explode(' ', $file[0]);
                        self::$binary = escapeshellarg(trim($tmp[1]));
                    } else {
                        self::$binary = escapeshellarg(ltrim(trim($file[0]), '#!'));
                    }
                } elseif (strpos(basename($_SERVER['_']), 'php') !== false) {
                    self::$binary = escapeshellarg($_SERVER['_']);
                }
            }
        }

        if (self::$binary === null) {
            $binaryLocations = [
                PHP_BINDIR . '/php',
                PHP_BINDIR . '/php-cli.exe',
                PHP_BINDIR . '/php.exe',
            ];

            foreach ($binaryLocations as $binary) {
                if (is_readable($binary)) {
                    self::$binary = escapeshellarg($binary);
                    break;
                }
            }
        }

        if (self::$binary === null) {
            self::$binary = 'php';
        }

        return self::$binary;
    }
410719
public function getBinary()
    {
        $result  = $this->getIdentifier();
        $result .= $this->createLengthPart();
        $result .= $this->getEncodedValue();

        return $result;
    }
969
public function asBinary() : string
    {
        static $wkbWriter;

        if ($wkbWriter === null) {
            $wkbWriter = new WKBWriter();
        }

        return $wkbWriter->write($this);
    }