I have a PHP file with the following content that works perfectly on development ceritficates, but when I switch to a production certificate the PHP errors and gives the below message, but it only does this about 50% of the time. The other 50% it works. Anyone know why this might be happening?
<?php
// masked for security reason
$deviceToken = 'xxxxxx'; // jq
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', dirname(__FILE__)."/prod.pem");
$number = 5;
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect $err $errstr\n";
}
else {
print "Connection OK\n";
$msg = $_GET['msg'];
$payload['aps'] = array('alert' => $msg, 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "\n";
fwrite($fp, $msg);
fclose($fp);
}
?>
The PHP error:
Warning: stream_socket_client() [function.stream-socket-client]: Unable to set local cert chain file `/var/www/vhosts/thissite.com/httpdocs/prod.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in /var/www/vhosts/thissite.com/httpdocs/pushMessageLive.php on line 19
Warning: stream_socket_client() [function.stream-socket-client]: failed to create an SSL handle in /var/www/vhosts/thissite.com/httpdocs/pushMessageLive.php on line 19
Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in /var/www/vhosts/thissite.com/httpdocs/pushMessageLive.php on line 19
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in /var/www/vhosts/thissite.com/httpdocs/pushMessageLive.php on line 19
Failed to connect 0
I had the same issue. You have to make a persistent socket connection with Apple's Push Notification Server. I've written up a tutorial for a python daemon called pyapns (http://github.com/samuraisam/pyapns) which worked very well for me:
http://www.how2s.org/index.php/How_to_get_started_with_Apple_Push_Notifications_for_iPhone_or_iPhone_Touch
This works assuming you are running Debian and have root access to install the required packages such as python-twisted, libcurl4-openssl-dev etc.
Sounds like too many connects. Apple's docs state that you need to hold the connection open and send as many as you can at the same time. Re-opening is considered DOS attack. So try making it persistent and see if you get same error.
I don't know if the error you are experiencing are because of too many connects to the push servers... In my experience, those limits are a bit hard to reach.
But PHP on the other hand have been acting strange when I've tried to send batches of push notifications. I'm not sure from your sample code, but I guess you do a stream_socket_client() and fclose() for every message? Using that technique with SSL sockets in PHP, the only thing I've personally have accomplished is failure...
I'm not sure if you have the possibility to run Ruby on your server, but if you can, I recommend switching to ruby-apns-daemon to handle the talk with Apple's servers. It's lightweight and easy to implement in PHP (you practically compose the same payload-JSON, but send it to ruby-apns-daemon instead of through a socket).
I've had the same issue and certificate was in fault. You can see solutions here How can I do an SSL connection with PHP and here Error using ssl cert with PHP.
Hope it'll help you.
And for the record you are not obliged to make a persistent connection with APNS. Though it's best to send all your messages at once, you can connect and disconnect multiple times. I quote Apple's website :
You should also retain connections
with APNs across multiple
notifications. APNs may consider
connections that are rapidly and
repeatedly established and torn down
as a denial-of-service attack. Upon
error, APNs closes the connection on
which the error occurred.
If you don't create hundred of connections at a time you should not get troubles.
Related
I'm using Gallery 3 for image upload.
When I use https://domain the upload works fine. But as I use https://domain Gallery3 is not able to make a connection.
Errors : **fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in fileName**
**fsockopen(): Failed to enable crypto in finleName**
**fsockopen(): unable to connect to ssl://domain:443 (Unknown error) in /**
Below are the observations:
The URL to connect becomes ssl://domain having port 443
fsockopen fails to make a connects and throws error.
What is going wrong ? I have a valid https certificate on my server and also openssl is installed.
Anything else required ?
PHP 5.6+ updated the default ciphers based on the Mozilla cipher recommendations. There is more detail about what ciphers are used in the RFC for improving tls defaults. Overall this change removed support for Anonymous Diffie-Hellman and RC4, it's likely your server still uses RC4.
There are two options:
Update the ciphers your server is using based on the Mozilla ciper recommendations
Update the gallery3 code to use RC4, since it hasn't been updated since 2013 you can probably do this option without too much concern
For option 2 it looks like the call is done in gallery3/modules/gallery/helpers/MY_remote.php on line 73/74:
$handle = fsockopen(
$url_components['fsockhost'], $url_components['port'], $errno, $errstr, 5);
You can change this to use stream_socket_client which is compatible with fsockopen:
$context = stream_context_create(['ssl' => [
'ciphers' => 'RC4-MD5'
]]);
$timeout = ini_get('default_socket_timeout');
$handle = stream_socket_client('ssl://' . $url_components['fsockhost'] . ':' . $url_components['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
I am trying to create an HTTP request to read the URL, and this code was working fine 15 days back, but now it's not working.
<?php
$source_url = 'https://www.facebook.com/stepblogging';
$rest_url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=" . urlencode($source_url);
$xml_response = file_get_contents($rest_url);
$xml_record = simplexml_load_string($xml_response);
$fb_share_count = $xml_record->link_stat->share_count;
$fb_like_count = $xml_record->link_stat->like_count;
$fb_comment_count = $xml_record->link_stat->comment_count;
$fb_total = $xml_record->link_stat->total_count;
echo 'Facebook Share:' . $fb_share_count . '<br/>';
echo 'Facebook Like:' . $fb_like_count . '<br/>';
echo 'Facebook Comment:' . $fb_comment_count . '<br/>';
After running this code, the output is:
Notice: file_get_contents(): send of 103 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. in E:\workspace\php\htdocs\connectivity\fbcount2.php on line 4
Notice: file_get_contents(): send of 24 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. in E:\workspace\php\htdocs\connectivity\fbcount2.php on line 4
Notice: file_get_contents(): send of 2 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. in E:\workspace\php\htdocs\connectivity\fbcount2.php on line 4
I am new to PHP. Please help me.
Actually, I found the answer by my own. This error was because of the k9 software, so I uninstalled it, and now there is no error regarding connection establishing. If anyone is getting this error, he/she should uninstall the software such as Skype, k9 (protocol using software) type of software.
I had a similar issue and it turned out that it wasn't my machine closing the connection but rather the server with which I was connected was kicking me due to an error in my code that spammed the site.
For anyone who has this issue, check that you aren't doing the same thing I was. If you think it's the server, it may be that the server is trying to handle too many requests all at once, not always from the same source.
I have hosted my PHP code on google cloud.
I want to send push notifications to ios app. I have enabled port 2195 and 2196.
While sending the push notification I got the following error :
Warning: stream_socket_client(): SSL: Connection reset by peer
Warning: stream_socket_client(): Failed to enable crypto
Warning: stream_socket_client(): unable to connect to
ssl://gateway.push.apple.com:2195 (Unknown error)
I am not much familiar with Google Cloud. What should I do to make it working?
Here is code:
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', PEM_FILE_PATH . 'apns-dev.pem');
$fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
$data['msgs'] = "Failed to connect $err $errstr \n";
} else {
$payload = json_encode($body);
$msg = chr(0) . pack("n", 32) . pack("H*", str_replace(" ", "", $deviceToken)) . pack("n", strlen($payload)) . $payload;
$result = fwrite($fp, $msg);
if (!$result) {
$data['msgs'] = 'Message not delivered'; //. PHP_EOL;
} else {
$data['msgs'] = 'Success'; //. PHP_EOL;
}
fclose($fp);
}
return $data;
The main problem when we are trying to send data to the APNS (Apple Push Notification Service) servers is the SSL certificates.
APNS uses this technology in order to serve more secure connection to its users.
As it is said at APNS documentation: "Each certificate is limited to a single app and is also limited to one of two development environments, each with its own assigned hostname". So you can use two environments
Development (testing environment): ssl://gateway.sandbox.push.apple.com:2195
Production (once the app is launched): ssl://gateway.push.apple.com:2195
If you want to test if you can connect to APNS server, just try the following command:
$ telnet gateway.sandbox.push.apple.com 2195
Trying 17.172.232.226...
Connected to gateway.sandbox.push-apple.com.akadns.net.
Escape character is '^]'.
If you get an error then make sure your firewall allows outgoing connections on port 2195.
Then you can test if your SSL certificate and private key are working and it can be set up a secure connection:
$ openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert YourDevCert.pem -key YourPrivateKey.pem
Enter pass phrase for YourPrivateKey.pem: ******
If this works it means that your certificates are correctly set up (you should see a whole bunch of output, which is openssl letting you know what is going on under the hood).
Once knowing all of this information, I see that you have one mistake in your code and also you should check something else:
Check if you have a good connection with APNS server.
Check that your $payload variable is a json string.
Check that you have a correct $deviceToken.
Check that you are using the right certificate with the right environtment. In this case, you are setting a apns-dev.pem certificate and you are sending it to the production environment (I interpret that your production certificate is apns-prod.pem so check it).
Check that your PHP file can find your certificate.
One of your problems, you haven't set any password for your private key. You should add the following line once you have added your certificate:
stream_context_set_option($ctx, "ssl", "passphrase", "your_private_key");
If you have some troubles or doubts, I followed this tutorial to send my first APNS Push Notifications.
I have a problem, I'd like to send out push notifications using php, however I keep getting this error:
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection refused) in /home/colupon/public_html/iPhone/push/index.php on line 21
Failed to connect: 111 Connection refused
My code is as follows:
$deviceToken = '0f************************************************************78';
$passphrase = '************';
$message = 'My first push notification!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
$filename = 'ckdev.pem';
stream_context_set_option($ctx, 'ssl', 'local_cert', $filename);
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) .
$payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered'.PHP_EOL;
// Close the connection to the server
fclose($fp);
?>
I believe the problem is with the server I'm using because I posted the same code and the same .pem file on a different server and it sent the notification without any problem. I attempted to open up ports on the firewall for my server because I read that might cause this problem, but the same error message still showed up. Is there anything else I can do? Any help would be greatly appreciated, thanks!
This issue is common problem in Apple Push notification, to resolve this error you have to go through as follows:
Test your pem files locally and remotely in server if the problem is server go to 2 else build pem correct file.
Set up the permission wrong on the folder that had the certificate file. This worked for me:
chmod 755 your_folder_that_has_certificate_files
3.Check connectivity of apns port 2195 from your hosting server as follows:
run
telnet gateway.push.apple.com 2195
if this is the problem
Trying 17.172.233.36...
telnet: connect to address 17.172.233.36: Connection refused
you can solve this issue by opening the port 2195 on the production server. You can verify by following command $telnet gateway.push.apple.com 2195
-bash-3.2# telnet gateway.push.apple.com 2195
Trying 17.149.38.141...
Connected to gateway.push.apple.com (17.149.38.141).
Escape character is '^]'.
Connection closed by foreign host.
In case of MAC,
(built-in server was working fine using terminal but not through browser, for me, so i installed MAMP.)
1.Go to---> /Library/WebServer/Documents/----copy both php and ckdev.pem file here.
2 go to terminal-->$open /private/etc-->go to--->apache2>originals>httpd.config file-->
**"#LoadModule php5_module libexec/apache2/libphp5.so", remove "#"..(perhaps, you would have to change the permission also..!)
then goto browser and check--> localhost/yourPhpFile.php
In Case of Windows system,
1.Install WAMP,
2.goto php.ini file--->search for this ";extension=php_openssl.dll" line and remove semicolon ";".
3.click WAMP icon from right-bottom goto PHP>PHP Extensions>select php_openssl..
That's it..hope this may help further seekers.
In my case the problem was that I forgot to setup my passphrase correctly in php script.
<?php
// Put your device token here (without spaces):
$deviceToken = 'xxx';
// Put your private key's passphrase here:
$passphrase = 'xxx';
To me, it was the SELinux issue.
So in your /etc/selinux/config file, set the SELINUX=enforcing to SELINUX=disabled. And restart. Thats it.
I just had the SAME error and I found the solution for my problem.
‚mypassword‘ instead of 'mypassword'
Seems like notepad changed the quotes. This literally took me 4 hours... Hopefully someone will read this and save some time...
I am using the certificate, and the private key
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certfile);
stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
$fp = stream_socket_client('ssl://gateway.xyz.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
Its running in my local XAMPP Server, but its not working in the external server:
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home/biranchi/public_html/push.php on line 42
Failed to connect 110
What is the error? Do i need to change some setting in the server?
I had fixed the issue by opening the port 2195 on the production server. You can verify by following command $telnet gateway.push.apple.com 2195
-bash-3.2# telnet gateway.push.apple.com 2195
Trying 17.149.38.141...
Connected to gateway.push.apple.com (17.149.38.141).
Escape character is '^]'.
Connection closed by foreign host.
Check your personal firewall settings and make sure you're not blocking this out. Try disabling the firewall.
Also, some APIs like requests to come from an actual domain rather than a desktop. I don't have reason to believe Apple works this way, but that's something to check also.
Also make sure and ping gateway.sandbox.push.apple.com and make sure you have a good connection.
You have to set your firewall to allow all the 17.0.0.0/8 block (it all belongs to Apple!). Check THIS ANSWER
And according to Apple:
The APNs servers use load balancing, so your devices won't always connect to the same public IP address for notifications. It's best to allow access to these ports on the entire 17.0.0.0/8 address block, which is assigned to Apple.
If you are using CSF firewall (like me), I'd recommend to add this line to csf.allow file:
tcp|out|d=2195|d=17.0.0.0/8
Then restart CSF. Using the above instead of just "17.0.0.0/8" will allow only outbond connections to Apple and specifically to port 2195. NSA won't like it but this is much more precise and safe! ;)