I set up a basic video chat app using the WebRTC APIs in Chrome along with a WebSocket script I wrote myself following the W3C specs and other questions here on SO.
Sometimes though, when one PC sends ICE candidate info to the other PC via the WebSocket connection, a bunch of garbled text is attached to the end of the JSON-stringified candidate info.
This problem only happens sometimes though, and it never happens with the SDP info sent via the createOffer and createAnswer methods.
Please see the following link for an example of what I'm talking about:
http://s1290.beta.photobucket.com/user/HartleySan83/media/NGdata_zps0a7203e7.png.html?sort=3&o=0
Because the JSON-stringified candidate info always ends with '}}', by adding an if condition to the WebSocket server script, I was able to circumvent this problem and get the video chat app to work. Unfortunately, this is a hack that I'd like to avoid. Plus, I'd like to know why this is happening in the first place.
It's worth noting that when I either alert or echo the candidate info to the console on the client side before it's sent to the WebSocket server script, none of the extra garbled text is present, so I'm not sure why it's present with the candidate info on the server side and only sometimes.
The following is a code snippet of the client-side code where the candidate info is sent to the server-side script:
function startPeerConnection() {
navigator.webkitGetUserMedia({ audio: true, video: true }, function (stream) {
document.getElementById('vid1').src = webkitURL.createObjectURL(stream);
pc = new webkitRTCPeerConnection(null);
pc.onicecandidate = function (evt) {
if (evt.candidate) {
socket.send(JSON.stringify({ candidate: evt.candidate }));
}
};
pc.onaddstream = function (evt) {
document.getElementById('vid2').src = webkitURL.createObjectURL(evt.stream);
};
pc.addStream(stream);
}, function () {});
}
And the following is the server-side code that unmasks the received WebSocket data:
$len = ord($buffer[1]) & 127;
if ($len === 126) {
$masks_start = 4;
} else if ($len === 127) {
$masks_start = 10;
} else {
$masks_start = 2;
}
$masks = substr($buffer, $masks_start, 4);
$data = substr($buffer, $masks_start + 4);
$len = strlen($data);
$text = '';
for ($i = 0; $i < $len; $i++) {
$text .= $data[$i] ^ $masks[$i % 4];
}
if (($end = strpos($text, '}}')) !== false) {
// This if condition eliminates the garbled text.
// Without it, a "Could not decode a text frame as UTF-8"
// error is output to the Chrome console.
$text = substr($text, 0, $end + 2);
$len = strlen($text);
}
if ($len <= 125) {
$header = pack('C*', 129, $len);
} else if (($len > 125) && ($len < 65536)) {
$header = pack('C*', 129, 126, ($len >> 8) & 255, $len & 255);
} else if ($len >= 65536) {
$header = pack('C*', 129, 127, ($len >> 56) & 255, ($len >> 48) & 255, ($len >> 40) & 255, ($len >> 32) & 255, ($len >> 24) & 255, ($len >> 16) & 255, ($len >> 8) & 255, $len & 255);
}
$server_response = $header . $text;
foreach ($users as $user) {
if ($user !== $users[$user_idx]) {
#socket_write($user['socket'], $server_response, strlen($server_response));
}
}
I've searched high and low on the Internet for anyone else with the same problem, but I can't find anyone or anything in the specs that talks about this, so I imagine it's some problem with my code.
Any guidance that anyone can offer as to the source of the problem would be much appreciated.
Thank you.
Well, I finally found the problem. My server-side WebSocket code was indeed wrong. The problem was that I was miscalculating the length. I, unfortunately, was relying on some page I found about WebSockets in PHP, and as it turns out, the page had a number of errors in its code, which I slowly started to realize more and more. Anyway, here's the proper way to calculate the length of messages sent from a client to the server:
$len = ord($buffer[1]) & 127; // This is the default payload length.
if ($len === 126) { // If 126, then need to use the payload length at the 3rd and 4th bytes.
$masks_start = 4;
$len = (ord($buffer[2]) << 8) + ord($buffer[3]);
} else if ($len === 127) { // If 127, then need to use the next 8 bytes to calculate the length.
$masks_start = 10;
$len = (ord($buffer[2]) << 56) + (ord($buffer[3]) << 48) + (ord($buffer[4]) << 40) + (ord($buffer[5]) << 32) + (ord($buffer[6]) << 24) + (ord($buffer[7]) << 16) + (ord($buffer[8]) << 8) + ord($buffer[9]);
} else { // Otherwise, the default payload length is correct.
$masks_start = 2;
}
After doing that, everything worked great. Well, I'm still haven't figured out how to properly close a WebSocket connection, but other than that, the WebRTC video is working great.
Is the garbled binary data being added by client1 before it sends it to the Websocket server? Or are you only seeing it on the client2 after it's been processed by the websocket server? I ask because I ran into a similar problem where my signaling server (SignalR in this case) had a bug that corrupted the SDP I was sending in-between PeerConnections.
Related
I'm looking for a way to decrypt a file since a few weeks. But it's impossible to recover the file intact in PHP, only with node. But I would like to do it without node.
If someone can tell me where I could be wrong... ?
I tried with openssl_encrypt/decrypt then with OPENSSL_NO_PADDING & ZERO_PADDING options. Transform the result in base64 but impossible to have the good result...
I thank you in advance I do not know what to do...
Here is my NodeJs crypto code :
decrypt(encryptedBuffer) {
const PASSPHRASE = "";
let decryptedBuffer = Buffer.alloc(encryptedBuffer.length);
let chunkSize = 2048;
let progress = 0;
while (progress < encryptedBuffer.length) {
if ((encryptedBuffer.length - progress) < 2048) {
chunkSize = encryptedBuffer.length - progress;
}
let encryptedChunk = encryptedBuffer.slice(progress, progress + chunkSize);
// Only decrypt every third chunk and only if not at the end
if (progress % (chunkSize * 3) === 0 && chunkSize === 2048) {
let cipher = crypto.createDecipheriv('bf-cbc', PASSPHRASE, Buffer.from([0, 1, 2, 3, 4, 5, 6, 7]));
cipher.setAutoPadding(false);
encryptedChunk = Buffer.concat([cipher.update(encryptedChunk), cipher.final()]);
}
decryptedBuffer.write(encryptedChunk.toString('binary'), progress, encryptedChunk.length, 'binary');
progress += chunkSize;
}
return decryptedBuffer;
}
Here in PHP
public function decrypt($encryptedBuffer)
{
ini_set('memory_limit', '1G');
$f = fopen('myfile', 'wb+');
$chunkSize = 2048;
$progress = 0;
$passphrase = "h5ihb>p9`'yjmkhf";
while ($progress > strlen($encryptedBuffer)) {
// If the buffer is if the end calculate the valid chunksize
if ((strlen($encryptedBuffer) - $progress) < 2048) {
$chunkSize = strlen($encryptedBuffer) - $progress;
}
/** Getting the encrypted chunk part */
$encryptedChunk = substr($encryptedBuffer, $progress, $progress + $chunkSize);
// Only decrypt every third chunk and only if not at the end
if ($progress % ($chunkSize * 3) === 0 && $chunkSize === 2048) {
$encryptedChunk = openssl_decrypt($encryptedChunk, 'bf-cbc', $passphrase, OPENSSL_ZERO_PADDING, '01234567');
}
fwrite($f, $encryptedChunk);
$progress += $chunkSize;
}
}
There are several flaws in the PHP code:
The condition in the while loop is wrong and should be:
$progress < strlen($encryptedBuffer).
$encryptedChunk is determined incorrectly because substr() expects the length in the third parameter. The correct way is:
$encryptedChunk = substr($encryptedBuffer, $progress, $chunkSize);
In the openssl_decrypt() call, too few flags are set in the fourth parameter:
Apart from disabling the padding, the default Base64 decoding has to be disabled with OPENSSL_RAW_DATA.
For key sizes smaller than 16 bytes, the padding of the key with 0x00 values to a length of 16 bytes has to be disabled with OPENSSL_DONT_ZERO_PAD_KEY. This is a PHP bug (s. here). The fix, i.e. the flag is available as of version 7.1.8.
Overall: OPENSSL_DONT_ZERO_PAD_KEY | OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING.
The wrong IV is used, correct would be: hex2bin('0001020304050607').
With these changes, decryption with the PHP code works.
Regarding security: The short block size makes Blowfish vulnerable to birthday attacks, see here. Using a static IV is generally insecure. Rather, a random IV should be generated for each encryption.
Hope this wasn't solved here before, but I was really trying to look for answer!
I Have a problem with receiving frames via socket_recv in PHP server. Problem appears when I send more than 1 messages from client in one time (e.g. in cycle). By the stream length it's match frames count but I'm not able to unmask frames correctly and my unmask function return only first frame. I'm using part of php server I found here and for one message it's working properly, but when I receive more messages at time, it don't unmask all.
I tryed to add loop to go thru all frames, but I'm not able to find end of frame and continue to other.
Here is main while of server:
while (true) {
//manage multipal connections
$changed = $clients;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accpet new socket
$clients[] = $socket_new; //add socket to client array
$header = socket_read($socket_new, 10240); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type' => 'system', 'status' => true, "id" => "SRV_CONNECTED", 'message' => $ip . ' connected'))); //prepare json data
send_message($response); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
foreach ($changed as $changed_socket) {
while (#socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text, true); //json decode
$response_text = parse_msg($tst_msg, $changed_socket);
break 2; //exit this loop
}
$buf = #socket_read($changed_socket, 10240, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected')));
send_message($response);
}
}
I Need to call parse_msg by count of frames received in #socket_recv which should be returned by unmask function.
And here is unmask function:
function unmask($payload){
$decMessages = Array();
do { // This should be running until all frames are unmasked and added to $decMessages Array
$length = ord($payload[1]) & 127;
if($length == 126) {
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
$len = (ord($payload[2]) << 8) + ord($payload[3]);
}elseif($length == 127) {
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
$len = (ord($payload[2]) << 56) + (ord($payload[3]) << 48) +
(ord($payload[4]) << 40) + (ord($payload[5]) << 32) +
(ord($payload[6]) << 24) +(ord($payload[7]) << 16) +
(ord($payload[8]) << 8) + ord($payload[9]);
}else {
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
$len = $length;
}
$text = '';
for ($i = 0; $i < $len; ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
$decMessages[] = $text;
// Here is problem. It doesn't put correct substr to $payload, so it could run again on stream shorted by last message
$payload = substr($payload, $length, strlen($payload));
}while (($len < strlen($data)) and $countert < 10);
return $decMessages;
}
I think my problem is here: $payload = substr($payload, $length, strlen($payload)); Where I'm putting wrongly rest of stream?
So my questions are:
Why #socket_recv return more than one frame
How can i change my unmask function to go thru all frames, not just a first one
I will be extremelly greatfull for any help, because I'm fighting with this more than I should.
Thanks in advance
Klara!
so, I found solution for this. As I thought, problem was multiple frames in one receive. I needed to edit my unmask function to check if there are still frames in stream.
Basically, what I had was right but $length in
$payload = substr($payload, $length, strlen($payload));
was wrong. Instead of $length I used $len + 8, 14 od 6 depend on $length. I'm not sure how to describe why this but I'm sure somebody will. That's all. Now it's working as it should!
Thanks!
I am having some fun playing around with an Arduino (Uno rev 3) and a thermal printer (this model https://www.sparkfun.com/products/10438). The Arduino makes a request every 10 seconds to my local machine (via an Ethernet shield) and stores the response (if 200) on an SD card. It then prints this out using this library https://github.com/adafruit/Adafruit-Thermal-Printer-Library .
So far I have it correctly polling, storing and printing basic text but now I'm trying to use some of the more advanced commands (underline, inverse etc). My ultimate goal is to send images down and handle all of the rendering on the server ala http://printer.gofreerange.com/ .
The problem is that the commands I am sending are been outputted as text characters. Some commands work (line feed), but others are garbled. I have attached both the Arduino code and the basic PHP script it is calling. Any help?
Arduino:
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <SoftwareSerial.h>
#include "Adafruit_Thermal.h"
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const char host[] = "192.168.1.100";
char cacheFilename[] = "TMP";
const byte printer_RX_Pin = 8; // this is the green wire
const byte printer_TX_Pin = 9; // this is the yellow wire
const byte SD_Pin = 4; // the SD Card SPI pin
bool downloadWaiting = false;
bool statusOk = false;
unsigned long content_length = 0;
EthernetClient client;
Adafruit_Thermal printer(printer_RX_Pin, printer_TX_Pin);
void die(unsigned int times) {
while(true);
}
void checkForDownload() {
Serial.println("checkForDownload");
content_length = 0;
statusOk = false;
unsigned long length = 0;
if (SD.exists(cacheFilename)) {
if (!SD.remove(cacheFilename)) {
die(4);
}
}
File cache = SD.open(cacheFilename, FILE_WRITE);
if(client.connect(host, 80)) {
client.println("GET /printer.php HTTP/1.1");
client.print("Host: "); client.println(host);
client.println("User-Agent: arduino-ethernet");
client.println("Connection: close");
client.println();
bool parsingHeader = true;
while(client.connected()) {
while(client.available()) {
if (parsingHeader) {
client.find((char*)"HTTP/1.1 ");
char statusCode[] = "000";
client.readBytes(statusCode, 3);
statusOk = (strcmp(statusCode, "200") == 0);
client.find((char*)"Content-Length: ");
char c;
while (isdigit(c = client.read())) {
content_length = (content_length * 10) + (c - '0');
}
client.find((char*)"\n\r\n");
parsingHeader = false;
} else {
if(length < content_length) {
cache.write((byte)client.read());
length++;
} else {
client.read();
}
}
}
}
client.stop();
cache.seek(0);
if (statusOk && content_length > 0 && (content_length == length) && (content_length == cache.size())) {
downloadWaiting = true;
}
} else {
client.stop();
}
cache.close();
}
void printFromDownload() {
Serial.println("printFromDownload");
File cache = SD.open(cacheFilename);
byte b;
while (content_length--) {
printer.write((byte)cache.read());
}
printer.feed();
cache.close();
downloadWaiting = false;
}
void setup(){
pinMode(SD_Pin, OUTPUT);
if (!SD.begin(SD_Pin)) {
die(2);
}
if (Ethernet.begin(mac) == 0) {
die(3);
}
Serial.begin(9600);
printer.begin(255);
delay(1000);
}
void loop() {
if (downloadWaiting) {
printFromDownload();
delay(5000);
} else {
checkForDownload();
if (!downloadWaiting) {
delay(10000);
}
}
}
PHP:
<?php
ob_start();
// Turn on Inverse mode
// Doesn't work
echo pack('S', 29);
echo pack('S', 66);
echo pack('S', 1);
$string = 'Testing 1, 2, 3';
foreach(str_split($string) as $char) {
echo pack('S', ord($char)); // works
}
// Turn off Inverse mode
echo pack('S', 29);
echo pack('S', 66);
echo pack('S', 0);
// Line feed
echo pack('S', 10); // works
$content = ob_get_clean();
$length = strlen($content);
header("Content-Length: $length");
echo $content;
It seems that you can't print bitmap data directly with printer.write(). The printer expects some special bytes to turn on bitmap printing mode as you can see in the printBitmap() method. (writeBytes(18, 42, chunkHeight, rowBytesClipped))
void Adafruit_Thermal::printBitmap(
int w, int h, const uint8_t *bitmap, bool fromProgMem) {
int rowBytes, rowBytesClipped, rowStart, chunkHeight, x, y, i;
rowBytes = (w + 7) / 8; // Round up to next byte boundary
rowBytesClipped = (rowBytes >= 48) ? 48 : rowBytes; // 384 pixels max width
for(i=rowStart=0; rowStart < h; rowStart += 255) {
// Issue up to 255 rows at a time:
chunkHeight = h - rowStart;
if(chunkHeight > 255) chunkHeight = 255;
writeBytes(18, 42, chunkHeight, rowBytesClipped);
for(y=0; y < chunkHeight; y++) {
for(x=0; x < rowBytesClipped; x++, i++) {
PRINTER_PRINT(fromProgMem ? pgm_read_byte(bitmap + i) : *(bitmap+i));
}
i += rowBytes - rowBytesClipped;
}
timeoutSet(chunkHeight * dotPrintTime);
}
prevByte = '\n';
}
Your sketch will need to understand the data coming from the PHP and know when to send individual characters as bytes with printer.write() and when to send bytes as an image with printer.printBitmap(). This way the printer is receiving the proper commands to prep it for printing the appropriate data. You will need to construct some metadata around what you want to print in PHP and send that to the Arduino. A JSON format might look like this:
{"reciept": [
{
"type": "text",
"style": "bold",
"value": "Thank you for your purchase"
},
{
"type": "bitmap",
"pos": "center",
"value": ".... binary data ..."
}
]}
Now your Arduino sketch will understand when to send bytes individually as text and when to send a lot of data as a bitmap.
A more compact format might use line feeds as a break between segments:
F|bold
T|Thank you for shopping with us\r
P|Center
B|...binary data (with \r escaped)... \r
Or, you can send the amount of data with each segment to avoid escaping binary data much like the Content-Length header of HTTP
F4|boldT32|Thank you for shopping with us\rP6|CenterB3000|...binary data...
I am developing a simple websocket server in PHP. I know there are quite a few existing implementations but I want to make my own so to learn the protocol better. I managed to do the handshaking fine and my clients connect to the server. I also managed to decode the data from the client but I have problems sending back messages. The client disconnects when it receives my response. Firefox says The connection to ws://localhost:12345/ was interrupted while the page was loading..
I used this answer as a guide.
Here is my code for wrapping the data:
private function wrap($msg = ""){
$length = strlen($msg);
$this->log("wrapping (" . $length . " bytes): " . $msg);
$bytesFormatted = chr(129);
if($length <= 125){
$bytesFormatted .= chr($length);
} else if($length >= 126 && $length <= 65535) {
$bytesFormatted .= chr(126);
$bytesFormatted .= chr(( $length >> 8 ) & 255);
$bytesFormatted .= chr(( $length ) & 255);
} else {
$bytesFormatted .= chr(127);
$bytesFormatted .= chr(( $length >> 56 ) & 255);
$bytesFormatted .= chr(( $length >> 48 ) & 255);
$bytesFormatted .= chr(( $length >> 40 ) & 255);
$bytesFormatted .= chr(( $length >> 32 ) & 255);
$bytesFormatted .= chr(( $length >> 24 ) & 255);
$bytesFormatted .= chr(( $length >> 16 ) & 255);
$bytesFormatted .= chr(( $length >> 8 ) & 255);
$bytesFormatted .= chr(( $length ) & 255);
}
$bytesFormatted .= $msg;
$this->log("wrapped (" . strlen($bytesFormatted) . " bytes): " . $bytesFormatted);
return $bytesFormatted;
}
UPDATE: I tried it with Chrome and I got the following error, printed in the console: A server must not mask any frames that it sends to the client.
I put some console printouts on the server. It is a basic echo server. I try with aaaa. So the actual wrapped message must be 6 bytes. Right?
Chrome prints the above error. Note also that after wrapping the message I simply write it to the socket:
$sent = socket_write($client, $bytesFormatted, strlen($bytesFormatted));
$this->say("! " . $sent);
It prints 6 meaning 6 bytes are actually written to the wire.
If I try with aaa, Chrome doesn't print the error but doesn't call my onmessage handler either. It hangs as if waiting for more data.
Any help highly appreciated. Thanks.
I had the same problem: for some messages sent from the server there was no response in the browser, for some the error "A server must not mask any frames ..." was displayed, though I did not add any mask.
The reason was in the handshake sent.
The handshake was:
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
...
"WebSocket-Location: ws://{$host}{$resource}\r\n\r\n" . chr(0)
That chr(0) was the reason, after I removed it everything works.
When I wrote my websocket classes, I had the same issue.
In my case, I used output buffering to determine that I was echo'ing something out before I sent the reply.
Might try that and see if it's the problem.
So Chrome 14 has implemented hybi10 version of websockets. I have a in house program that our company uses via chrome that uses websockets which is broken with this change.
Has anyone been successful framing the data using a php server? I am able to get the new handshake to work but I can't seem to figure out the framing. There is a python example here https://github.com/kanaka/websockify/blob/master/websocket.py#L233 but I am having a difficult time converting this to php, anyone have a suggestion?
I should mention that the function in question on the python example is decode_hybi().
i just completed a class wich makes the PHP-Websocket-Server of Nico Kaiser (https://github.com/nicokaiser/php-websocket) capable of handling hybi-10 frames and handshake. You can download the new class here: http://lemmingzshadow.net/386/php-websocket-serverclient-nach-draft-hybi-10/ (Connection.php)
This code assumes no errors or malformed frames and is based on this answer - How to (de)construct data frames in WebSockets hybi 08+?.
This code is very basic and is far from a complete solution. It works for my purposes (which are pretty basic). Hopefully it is of use to others.
function handle_data($data){
$bytes = $data;
$data_length = "";
$mask = "";
$coded_data = "" ;
$decoded_data = "";
$data_length = $bytes[1] & 127;
if($data_length === 126){
$mask = substr($bytes, 4, 8);
$coded_data = substr($bytes, 8);
}else if($data_length === 127){
$mask = substr($bytes, 10, 14);
$coded_data = substr($bytes, 14);
}else{
$mask = substr($bytes, 2, 6);
$coded_data = substr($bytes, 6);
}
for($i=0;$i<strlen($coded_data);$i++){
$decoded_data .= $coded_data[$i] ^ $mask[$i%4];
}
$this->log("Server Received->".$decoded_data);
return true;
}
Here is the code to send data back. Again this is pretty basic, it assumes you are sending a single text frame. No continuation frames etc. No error checking either. Hopefully others find it useful.
public function send($data)
{
$frame = Array();
$encoded = "";
$frame[0] = 0x81;
$data_length = strlen($data);
if($data_length <= 125){
$frame[1] = $data_length;
}else{
$frame[1] = 126;
$frame[2] = $data_length >> 8;
$frame[3] = $data_length & 0xFF;
}
for($i=0;$i<sizeof($frame);$i++){
$encoded .= chr($frame[$i]);
}
$encoded .= $data;
write_to_socket($this->socket, $encoded);
return true;
}