Skip to content

Commit

Permalink
Added support for TLS ALPN to connect via MQTT protocol to a TLS encr…
Browse files Browse the repository at this point in the history
…ypted HTTP port 443 (#181)

* Update ConnectionSettings.php

added TLS ALPN option

* Update MqttClient.php

Added TLS ALPN option to the TLS options

* Update MqttClient.php

* Update README.md

Added TLS ALPN to the ConnectSettings options
  • Loading branch information
jonofe authored Apr 24, 2024
1 parent 0d9f829 commit 8258141
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,10 @@ $connectionSettings = (new \PhpMqtt\Client\ConnectionSettings)
// This option requires ConnectionSettings::setTlsClientCertificateFile() and
// ConnectionSettings::setTlsClientCertificateKeyFile() to be used as well.
->setTlsClientCertificateKeyPassphrase(null);

// The TLS ALPN is used to establish a TLS encrypted mqtt connection on port 443,
// which usually is reserved for TLS encrypted HTTP traffic.
->setTlsAlpn(null);
```

## Features
Expand Down
22 changes: 22 additions & 0 deletions src/ConnectionSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class ConnectionSettings
private ?string $tlsClientCertificateFile = null;
private ?string $tlsClientCertificateKeyFile = null;
private ?string $tlsClientCertificateKeyPassphrase = null;
private ?string $tlsAlpn = null;

/**
* The username used for authentication when connecting to the broker.
Expand Down Expand Up @@ -531,4 +532,25 @@ public function getTlsClientCertificateKeyPassphrase(): ?string
{
return $this->tlsClientCertificateKeyPassphrase;
}

/**
* The TLS ALPN is used to establish a TLS encrypted mqtt connection on port 443,
* which usually is reserved for TLS encrypted HTTP traffic.
*
* @return ConnectionSettings A copy of the original object with the new setting applied.
*/
public function setTlsAlpn(?string $tlsAlpn): ConnectionSettings
{
$copy = clone $this;

$copy->tlsAlpn = $tlsAlpn;

return $copy;
}

public function getTlsAlpn(): ?string
{
return $this->tlsAlpn;
}

}
4 changes: 4 additions & 0 deletions src/MqttClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,10 @@ protected function establishSocketConnection(): void
$tlsOptions['passphrase'] = $this->settings->getTlsClientCertificateKeyPassphrase();
}

if ($this->settings->getTlsAlpn() !== null) {
$tlsOptions['alpn_protocols'] = $this->settings->getTlsAlpn();
}

$contextOptions['ssl'] = $tlsOptions;
}

Expand Down

0 comments on commit 8258141

Please sign in to comment.