I'm trying to create a connection between the client and the server (with 2-way TLS).
Client.php
$stream_context = stream_context_create(['ssl' => [
'local_cert' => "path/to/cer.pem",
'verify_peer' => true,
'verify_peer_name' => false,
'passphrase' => "password to cert",
'verify_depth' => 0
]]);
$socket = stream_socket_client("tlsv1.2://127.0.0.1:8000", $errno, $errstr, 3, STREAM_CLIENT_CONNECT, $stream_context);
if ($socket === false) {
return false;
}
$req = "POST /Serwer.php HTTP/1.1\r\n" .
"Content-Type: text/xml;charset=UTF-8\r\n" .
"Host: 127.0.0.1\r\n" .
"Connection: Close\r\n" .
"Hello world!\r\n";
$start = time();
fwrite($socket, $req);
$resp = '';
while (!feof($socket)) {
if (time() - $start > 15) {
break;
}
$f = fgets($socket);
$resp .= $f;
}
fclose($socket);
echo $resp;
Server.php
$stream_context = stream_context_create(['ssl' => [
'local_cert' => "path/to/cert.pem",
'passphrase' => "password to cert",
'allow_self_signed' => true,
'verify_peer' => true
]]);
$server = stream_socket_server("tlsv1.2://0.0.0.0:8000",$errno, $error, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $stream_context);
if ($server === false) {
return false;
}
$connects = array();
while (true) {
$read = $connects;
$read []= $server;
$write = $except = null;
$mod_fd = stream_select($read, $write, $except, 3); // return always 0, I don't know why
if ($mod_fd === false) {
break;
}
if (in_array($server, $read)) {
$connect = stream_socket_accept($server, -1);
$connects[] = $connect;
unset($read[ array_search($server, $read) ]);
}
foreach($read as $connect) {
$headers = '';
while ($buffer = rtrim(fgets($connect))) {
$headers .= $buffer;
}
fwrite($connect, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\nHello!");
fclose($connect);
unset($connects[ array_search($connect, $connects) ]);
}
fclose($server);
In this example server and client are on different machines.
I must to use TLS v 1.2.
Address and port on the client and the server must be the same or different? (For example in server.php I use address 0.0.0.0 and port 8000, but in client.php 127.0.0.1 and port 8000)
How the server and the client must accept the certificates TLS?
How read on server side phrase "Hello world" from client?
Related
I'm working with a websocket connection and I can't get it to return a correct connection. I have no errors. It just tells me that the connection is failed.
The test token is real: $token = 'TYcagYNyseG4aFooYjU1hy0lIsXDrrk34mWcDn4N2VE=';
<?php
$urlwebsocket = 'wss.remarkets.primary.com.ar';
$host = 'wss.remarkets.primary.com.ar';
$port = 443;
$token = 'TYcagYNyseG4aFooYjU1hy0lIsXDrrk34mWcDn4N2VE=';
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$socket){
echo "Error socket";
exit;
}
// Connect host
$result = socket_connect($socket, $host, $port);
if(!$result){
echo "Error connect host";
socket_close($socket);
exit;
}
// send auth
$request = [
'event' => 'auth',
'data' => [
'token' => $token
]
];
$request = json_encode($request);
$request = "\x00" . $request . "\xff";
socket_write($socket, $request, strlen($request));
// good connect
$response = socket_read($socket, 1024);
if(strpos($response, 'Welcome') !== false){
echo "Connect";
} else{
echo "No connect";
}
// Close socket
socket_close($socket);
?>
I am sending push notification using php code and ios didn't get notification so whats the exact issue i don't know please help.
public static function ios_push($device_token,$title,$msg,$description,$type = "",$r_type = "")
{
\Log::info('device_token', ['context' => $device_token]);
\Log::info($device_token);
$badge_count =2;
$streamContext = stream_context_create();
$connectTimeout = 60;
stream_context_set_option($streamContext, 'ssl', 'passphrase',IPHONE_CERTIFICATE_PASSWORD);
\Log::info(IPHONE_CERTIFICATE_TYPE);
if(IPHONE_CERTIFICATE_TYPE == "Development")
{
//For Development
stream_context_set_option($streamContext, 'ssl', 'local_cert',IOS_PUSH_DEV_PEM_PATH);
$apns = stream_socket_client('ssl://gateway.push.apple.com:2195', $error, $errorString, $connectTimeout, STREAM_CLIENT_CONNECT |STREAM_CLIENT_PERSISTENT, $streamContext);
}
else
{
//For Production
stream_context_set_option($streamContext, 'ssl', 'local_cert',WWW_ROOT_PATH.IOS_PUSH_DEV_PEM_PATH);
$apns = stream_socket_client('ssl://gateway.push.apple.com:2195', $error, $errorString, $connectTimeout, STREAM_CLIENT_CONNECT |STREAM_CLIENT_PERSISTENT, $streamContext);
}
if (!$apns) {
\Log::info('Error : '.$error.' '.$errorString);
} else {
\Log::info("success");
}
$music = 'default';
$payload['aps'] = array('alert' => ['title'=>$title,'body'=>$msg], 'badge' => $badge_count,'title'=>$description,'sound'=> $music , 'notification_type' => $type);
//$payload['aps'] = array('alert' => "vikas", 'badge' => $badge_count,'sound'=> $music , 'notification_type' => $type);
// $data['notification_type'] = $notification_type;
// $data['sender_first_name'] = $sender_first_name;
// $data['sender_last_name'] = $sender_last_name;
// $data['sender_user_id'] = $sender_user_id;
$data['sound'] = $music;
$data['title'] = $title;
$data['notification_type'] = $type;
$data['report_type'] = !empty($r_type) ? substr($r_type, 0, -8) : "";
$payload['data'] = $data;
$payload = json_encode($payload);
\Log::info('Log message', ['payload' => json_encode($payload)]);
$apnsMessage = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($payload)) . $payload;
$fwriteRes = fwrite($apns, $apnsMessage, strlen($apnsMessage));
fclose($apns);
return true;
}
This is my function
But IOS didn't get any notification in mobile
SO whats the issue
The issue for 2195 port is close thats why?
This solution is perfectly help for me!!!!
-----------==> Step 1
First of all you need to install this composer library.
compose require lcobucci/jwt:^3.3.1
-----------==> Step 2
Then write code like..
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
public static function generateiosauthtoken() {
$key = file_get_contents('Your p8 file'); // p8 file
$signer = new Sha256();
$time = time();
return (new Builder())->issuedBy("TEAMID") // iss claim
->permittedFor('https://appleid.apple.com') // aud claim
->expiresAt($time + 3600) // exp claim
->issuedAt($time) // iat claim
->withHeader('kid', "KEYID") // kid header
->getToken($signer, new Key($key));
}
public static function ios_push($device_token,$title,$msg,$description)
{
$token = ApiHelper::generateiosauthtoken();
$music = 'default';
$payload['aps'] = array('alert' => ['title'=>$title,'body'=>$msg], 'badge' => 1,'title'=>$description,'sound'=> $music , 'notification_type' => $type);
$data['sound'] = $music;
$data['title'] = $title;
$payload['data'] = $data;
$payload = json_encode($payload);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTP09_ALLOWED, true);
curl_setopt_array($curl, array(
CURLOPT_PORT => "443",
CURLOPT_URL => "https://api.push.apple.com:443/3/device/".$device_token."",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => array(
"apns-topic: bundleid", // put it here your aplication bundle id
"authorization: bearer ".$token."",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$arr = array("code" => 400, "msg" => $err,"flag" => false , "data" => (object)array());
\Response::json($arr);
} else {
echo $response;
}
}
I think port 443 is used now
Sending Notification Requests to APNs
https://support.apple.com/en-us/HT203609
https://developer.apple.com/documentation/usernotifications/sending_push_notifications_using_command-line_tools?language=objc
I've been talking to Apple via the developer portal and so far this is all I know. I've now decided to just cherry pick and see what other devs that use APNS did to keep the deliveries successful. I asked this question too and now that I'm browsing the Apple-Push-Notifications tag, I see others are too.
This function is meant to download .zip files
function download($url, $debug = false)
{
$client = new Client([
'connect_timeout' => 10,
'timeout' => 60.0,
'debug' => $debug
]);
$response = $client->request('GET', $url);
try {
if ($response->getStatusCode() == 200) {
return $response->getBody()->getContents();
}
} catch (RequestException $e) {
//var_dump($response->getBody()->getContents());
$txt = json_encode(['log_error' => $e->getResponse(), 'response' => $response->getBody()->getContents(), 'url' => $url]);
file_put_contents(storage_path() . '/logs-etiquetas/log-' . microtime(true) . '-' . auth()->user()->company_id . '.txt', $txt);
}
return false;
}
I'm getting error below
production_ERROR: Client error: GET https: //api.mercadolibre.com/shipment_labels? shipment_ids = 27868452659,27864682043,27168438675,27868264704,27868866716,27868738288,27867965828 & response_type = zpl2 & caller.id = 23264143 & access_token = 400 Bad Request response:
bad_request
I am making a chatroom using WebSockets, which is working fine when I use an unencrypted connection, but after I use a certificate it doesn't work anymore.
In JavaScript I was opening the connection to the WebSocket server at serverr.php like this:
var wsUri = "ws://mydomain.com:9002/chat/serverr.php";
websocket1 = new WebSocket(wsUri);
Now I know that I must use wss:// instead of ws:// so now I am using:
var wsUri = "wss://mydomain.com:9002/chat/serverr.php";
websocket1 = new WebSocket(wsUri);
But I get the following error:
WebSocket connection to 'wss://mydomain.com:9002/chat/serverr.php' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR
But I don't know how to make a wss:// connection. I tried to modify my code with the following part:
set_time_limit(0);
require_once($_SERVER['DOCUMENT_ROOT']."../../../home/username/public_html/config/config.php");
$host = 'ssl://0.0.0.0'; //host
$port = '9002'; //port
$null = NULL; //null var
// Generate certificate
$privkey = openssl_pkey_new();
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 365);
// Generate PEM file
# Optionally change the passphrase from 'comet' to whatever you want, or leave it empty for no passphrase
$pem_passphrase = 'comet';
$pem = array();
openssl_x509_export($cert, $pem[0]);
openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
$pem = implode($pem);
// Save PEM file
$pemfile = 'server.pem';
file_put_contents($pemfile, $pem);
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_option($socket, SOL_SOCKET, 'ssl', 'local_cert', $pemfile);
socket_set_option($socket, SOL_SOCKET, 'ssl', 'passphrase', $pem_passphrase);
socket_set_option($socket, SOL_SOCKET, 'ssl', 'allow_self_signed', true);
socket_set_option($socket, SOL_SOCKET, 'ssl', 'verify_peer', false);
//bind socket to specified host
socket_bind($socket, 0, $port);
//the rest of code is still unmodified is like in the page serverr.php
Code in serverr.php
set_time_limit(0);
require_once($_SERVER['DOCUMENT_ROOT']."../../../home/username/public_html/config/config.php");
$host = 'localhost'; //host
$port = '9002'; //port
$null = NULL; //null var
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//bind socket to specified host
socket_bind($socket, 0, $port);
//listen to port
socket_listen($socket);
perform_handshaking($header, $socket_new, $host, $port);
//create & add listning socket to the list
$clients = array($socket);
//start endless loop, so that our script doesn't stop
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, 1024); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
//luam ultimele 15 mesaje start
$cerereinitialachat=mysqli_query($conexiune,"SELECT * FROM `chat_messages` ORDER BY `datesend` DESC LIMIT 17");
$obiectinitialchat=null;
$obiectobjectcount=0;
while ($rezultat=mysqli_fetch_assoc($cerereinitialachat)) {
$row=$rezultat;
$id;
$sender_steamid;
$avatar;
$sender_name;
$message;
$datesend;
$steamprofile;
$color;
foreach($row as $key=>$value){
if($key=="id"){
$id=$value;
}
if($key=="sender_steamid"){
$sender_steamid=$value;
}
if($key=="avatar"){
$avatar=$value;
}
if($key=="sender_name"){
$sender_name=$value;
}
if($key=="message"){
$message=$value;
}
if($key=="datesend"){
$datesend=$value;
}
if($key=="steamprofile"){
$steamprofile=$value;
}
if($key=="color"){
$color=$value;
}
}
$obiectinitialchat[$obiectobjectcount]=new stdClass;
$obiectinitialchat[$obiectobjectcount]->avatar=$avatar;
$obiectinitialchat[$obiectobjectcount]->name=$sender_name;
$obiectinitialchat[$obiectobjectcount]->message=$message;
$obiectinitialchat[$obiectobjectcount]->datesend=$datesend;
$obiectinitialchat[$obiectobjectcount]->steamprofile=$steamprofile;
$obiectinitialchat[$obiectobjectcount]->color=$color;
$obiectobjectcount=$obiectobjectcount+1;
}
//luam ultimele 15 mesaje stop
$cererenumaruonline=mysqli_query($conexiune,"SELECT * FROM `users` WHERE `online`!='0'");
$numaruonline=mysqli_num_rows($cererenumaruonline);
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected', 'uonline'=>$numaruonline, 'lastmessages'=>$obiectinitialchat))); //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]);
}
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1){
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text); //json decode
$user_steamid = esc($conexiune,$tst_msg->steamid); //sender steamid
$user_avatar = esc($conexiune,$tst_msg->avatar); //avatar
$user_name = esc($conexiune,$tst_msg->name); //sender name
$user_message = esc($conexiune,$tst_msg->message); //message text
$user_steamprofile = esc($conexiune,$tst_msg->steamprofile); //steamprofile
$user_message_date = time(); //message text date
$user_message=preg_replace("/\r|\n/", "", $user_message);//scoate enterurile
if (ctype_space($user_message)) {
//daca e numai spatiii libere(albe)
$user_message=preg_replace('/\s+/', "", $user_message);//scoate spatiile albe
}
$admin;
$color="normal";
$raspuns=mysqli_query($conexiune,"SELECT * FROM `users` WHERE `steamid`='".$user_steamid."'");
while($rezultat=mysqli_fetch_assoc($raspuns)){
$row=$rezultat;
foreach($row as $key=>$value){
if($key=="dirijor"){
$admin=$value;
}
}
}
if($admin=="Yes" || $user_steamid=="76561197997524415"){
$color="red";
}
if($user_steamid!="" && $user_steamid!=null && $user_message!="" && $user_message!=null){
mysqli_query($conexiune,"INSERT INTO `chat_messages` (`sender_steamid`,`avatar`,`sender_name`,`message`,`datesend`,`steamprofile`,`color`) VALUES ('".$user_steamid."','".$user_avatar."','".$user_name."','".$user_message."','".$user_message_date."','".$user_steamprofile."','".$color."')");
//prepare data to be sent to client
$response_text = mask(json_encode(array('type'=>'usermsg', 'avatar'=>$user_avatar, 'name'=>$user_name, 'message'=>$user_message, 'datesend'=>$user_message_date, 'steamprofile'=>$user_steamprofile, 'color'=>$color)));
send_message($response_text); //send data
}
break 2; //exist this loop
}
$buf = #socket_read($changed_socket, 1024, 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]);
$cererenumaruonline2=mysqli_query($conexiune,"SELECT * FROM `users` WHERE `online`!='0'");
$numaruonline2=mysqli_num_rows($cererenumaruonline);
$response = mask(json_encode(array('type'=>'upadateusersonline','uonline'=>$numaruonline)));
send_message($response);
//notify all users about disconnected connection
//$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
//send_message($response);
}
}
}
// close the listening socket
socket_close($sock);
function send_message($msg)
{
global $clients;
foreach($clients as $changed_socket)
{
#socket_write($changed_socket,$msg,strlen($msg));
}
return true;
}
//Unmask incoming framed message
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host/demo/shout.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));
}
I am connecting my website to a server having an application in VB6. I connect to an IP on a specified port using PHP. My code is as follows:
public static function hello()
{
static::$version = Config::get('socket.version');
static::$user = Config::get('socket.user');
static::$pwd = Config::get('socket.password');
$xmlstr = '<?xml version="1.0"?>';
$xmlstr .= '<HelloRequest version="' . static::$version . '" user="' . static::$user . '" pwd="' . static::$pwd . '" />';
//$xmlstr = '|'.strlen($xmlstr).'|'.$xmlstr; // Appending Length
return static::runRequest($xmlstr);
}
and it calls runRequest($xmlstr) method in the same class:
public static function runRequest($request)
{
static::$address = Config::get('socket.address');
static::$port = Config::get('socket.port');
static::$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!static::$socket) {
return (object) array(
'error' => true,
'message' => "socket_create() failed: reason: " . socket_strerror(socket_last_error())
);
}
socket_set_option(static::$socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0));
$result = socket_connect(static::$socket, static::$address, static::$port);
if (!$result) {
static::close();
return (object) array(
'error' => true,
'message' => "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error(static::$socket))
);
}
$bytes = socket_send(static::$socket, $request, strlen($request), 0);
if ($bytes > 0) {
$buf = " ";
$totalBytes = 0;
$outbuf = "";
$maxlen = 4096;
$loopcnt = 0;
$maxloops = 100;
while (true) {
$receivedBytes = socket_recv(static::$socket, $buf, $maxlen, 0);
if ($receivedBytes > 0) {
$buf = str_replace("&", "&", $buf);
$outbuf .= $buf;
$totalBytes += $receivedBytes;
if(strrpos($outbuf, "\r\n") == true)
break;
}
$loopcnt++;
}
$outbuf = str_replace("\r\n", "", $outbuf);
socket_close(static::$socket);
return (object) array(
'error' => false,
'message' => $outbuf
);
}
socket_close(static::$socket);
return (object) array(
'error' => true,
'message' => 'Something went wrong. Please try again.'
);
}
PROBLEM IS THAT THE CODE STUCKS at:
$receivedBytes = socket_recv(static::$socket, $buf, $maxlen, 0);
and returns 500 internal Server Error in Page Title and Request Time out on Page:
Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'.
Any Clue on it what might be wrong. Username/Paswords, IP and ports are correct, tested using putty.
We are using litespeed server (not apache). Here are the logs for the event:
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] Connection idle time: 121 while in state: 6 watching for event: 25,close!
2015-06-15 17:46:35.201 [NOTICE] [ip.address.removed:62539:HTTP2-1] Content len: 0, Request line: 'GET /socket/hello HTTP/1.1'
2015-06-15 17:46:35.201 [NOTICE] [ip.address.removed:62539:HTTP2-1] Redirect: #1, URL: /index.php/socket/hello
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] HttpExtConnector state: 8, request body sent: 0, response body size: -2, response body sent:0, left in buffer: 0, attempts: 0.
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] Lsapi connection state: 3, watching event: 25, respState: 1, m_iTotalPending:0, m_iPacketLeft:0, m_iCurRespHeader:791624304, req sent for 121 seconds,Total processing time: 121.
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] Abort request processing by PID:4736, kill: 1, begin time: 121, sent time: 121, req processed: 0