1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Nucleus - XMPP Library for PHP |
4
|
|
|
* |
5
|
|
|
* Copyright (C) 2016, Some rights reserved. |
6
|
|
|
* |
7
|
|
|
* @author Kacper "Kadet" Donat <[email protected]> |
8
|
|
|
* |
9
|
|
|
* Contact with author: |
10
|
|
|
* Xmpp: [email protected] |
11
|
|
|
* E-mail: [email protected] |
12
|
|
|
* |
13
|
|
|
* From Kadet with love. |
14
|
|
|
*/ |
15
|
|
|
|
16
|
|
|
namespace Kadet\Xmpp\Module; |
17
|
|
|
|
18
|
|
|
use Kadet\Xmpp\Exception\Protocol\TlsException; |
19
|
|
|
use Kadet\Xmpp\Network\SecureStream; |
20
|
|
|
use Kadet\Xmpp\Stream\Features; |
21
|
|
|
use Kadet\Xmpp\Utils\filter as with; |
22
|
|
|
use Kadet\Xmpp\Xml\XmlElement; |
23
|
|
|
use Kadet\Xmpp\XmppClient; |
24
|
|
|
|
25
|
|
|
class TlsEnabler extends ClientModule |
26
|
|
|
{ |
27
|
4 |
|
public function setClient(XmppClient $client) |
28
|
|
|
{ |
29
|
4 |
|
parent::setClient($client); |
30
|
|
|
|
31
|
|
|
$client->on('features', function (Features $features) { |
32
|
|
|
return !$this->startTls($features); |
33
|
4 |
|
}, null, 10); |
34
|
|
|
|
35
|
4 |
|
$client->on('element', function (XmlElement $element) { |
36
|
2 |
|
$this->handleTls($element); |
37
|
4 |
|
}, with\xmlns(Features\StartTls::XMLNS)); |
38
|
4 |
|
} |
39
|
|
|
|
40
|
4 |
|
public function startTls(Features $features) |
41
|
|
|
{ |
42
|
4 |
|
if ($features->startTls) { |
43
|
4 |
|
if ($this->_client->getDecorated() instanceof SecureStream) { |
44
|
2 |
|
$this->_client->write(new Features\StartTls()); |
45
|
|
|
|
46
|
2 |
|
return true; // Stop processing |
47
|
2 |
|
} elseif ($features->startTls->required) { |
48
|
1 |
|
throw new TlsException('Encryption is not available, but server requires it.'); |
49
|
|
|
} else { |
50
|
1 |
|
$this->_client->getLogger()->warning('Server offers TLS encryption, but stream is not capable of it.'); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
2 |
|
private function handleTls(XmlElement $response) |
58
|
|
|
{ |
59
|
2 |
|
if ($response->localName === 'proceed') { |
60
|
|
|
// this function is called only by event, which can be only fired after instanceof check |
61
|
|
|
/** @noinspection PhpUndefinedMethodInspection */ |
62
|
2 |
|
$this->_client->getDecorated()->encrypt(STREAM_CRYPTO_METHOD_TLS_CLIENT); |
|
|
|
|
63
|
2 |
|
$this->_client->restart(); |
64
|
|
|
} else { |
65
|
|
|
throw new TlsException('TLS negotiation failed.'); // XMPP does not provide any useful information why it happened |
66
|
|
|
} |
67
|
2 |
|
} |
68
|
|
|
} |
69
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: