stream_socket_enable_crypto(); Disables stream_set

2019-09-17 03:18发布

问题:

I have created an xmpp server, first using non tls which works as I want with no errors. The hole authentication works and I can chat with no problems.

Before I start reading from the socket I did:

stream_set_timeout($sock, 0, 1000); 

This will let me do things within the time when there is no new data from the server.

Now I implemented starttls. I did

stream_socket_enable_crypto($sock, true, STREAM_CRYPTO_METHOD_TLS_SERVER);

which negotates the tls for me. This didn't worked because the read timeout occured and the tls negotation failed.

I changed the above stream_socket_enable_crypto to

stream_set_timeout($sock, 30, 0);
stream_socket_enable_crypto($sock, true, STREAM_CRYPTO_METHOD_TLS_SERVER);
stream_set_timeout($sock, 0, 1000);

To set the timeout a bit higher, so the client has 30 seconds time to accept the certificate (if self signged) and do all the tls stuff. After this is finished I really need to set the timeout back to 1000 microseconds. The TLS-Negotation worked after this change, but I lost my timeout settings.

This is my problem. The stream_set_timeout call after stream_socket_enable_crypto does not work.

I have a log entry

echo "AFTER PROCESS MESSAGE QUEUE\n";
$buffer = fread($sock, 4096);
echo "AFTER SOCKET READ\n";

The message AFTER PROCESS MESSAGE QUEUE is printed but the AFTER SOCKET READ is not printed out and it does not matter how long I wait.

Does anybody has a glue how I can set the stream read timeout back to 1000 microseconds?

For your info: A solution where I should set stream_set_blocking to false is currently NOT wanted. For now I only want a blocking solution. If there is REALLY no other solution as to use non-blocking, then of course I want to know :)

回答1:

I had the same problem. stream_select helped me solve the problem:

$buffer='';
$select=array('con1'=>$socket);
$timeout_sec=1;
if(stream_select($select, $null, $null, $timeout_sec)){
    $buffer = fread($socket, $size);
}