-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTlsEnabler.php
68 lines (57 loc) · 2.02 KB
/
TlsEnabler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
/**
* Nucleus - XMPP Library for PHP
*
* Copyright (C) 2016, Some rights reserved.
*
* @author Kacper "Kadet" Donat <[email protected]>
*
* Contact with author:
* Xmpp: [email protected]
* E-mail: [email protected]
*
* From Kadet with love.
*/
namespace Kadet\Xmpp\Component;
use Kadet\Xmpp\Exception\Protocol\TlsException;
use Kadet\Xmpp\Network\SecureStream;
use Kadet\Xmpp\Stream\Features;
use Kadet\Xmpp\Utils\filter as with;
use Kadet\Xmpp\Xml\XmlElement;
use Kadet\Xmpp\XmppClient;
class TlsEnabler extends Component
{
public function init()
{
$this->_client->on('features', function (Features $features) {
return !$this->startTls($features);
}, null, 10);
$this->_client->on('element', function (XmlElement $element) {
return $this->handleTls($element);
}, with\element\xmlns(Features\StartTls::XMLNS));
}
public function startTls(Features $features)
{
if ($features->startTls) {
if ($this->_client->getDecorated() instanceof SecureStream) {
$this->_client->write(new Features\StartTls());
return true; // Stop processing
} elseif ($features->startTls->required) {
throw new TlsException('Encryption is not available, but server requires it.');
}
$this->_client->getLogger()->warning('Server offers TLS encryption, but stream is not capable of it.');
}
return false;
}
private function handleTls(XmlElement $response)
{
if ($response->localName !== 'proceed') {
throw new TlsException('TLS negotiation failed.'); // XMPP does not provide any useful information why it happened
}
// this function is called only by event, which can be only fired after instanceof check
/** @noinspection PhpUndefinedMethodInspection */
$this->_client->getDecorated()->encrypt(STREAM_CRYPTO_METHOD_TLS_CLIENT);
$this->_client->restart();
$this->_client->state = 'secured';
}
}