dns-over-https/lib/QueryEncoder.php

57 lines
1.7 KiB
PHP
Raw Normal View History

2019-06-11 20:07:46 +02:00
<?php declare(strict_types = 1);
2019-06-10 21:04:10 +02:00
/**
2019-06-11 20:07:46 +02:00
* Encodes Message objects to raw network data.
2019-06-10 21:04:10 +02:00
*
* PHP version 5.4
*
* @category LibDNS
* @package Encoder
* @author Chris Wright <https://github.com/DaveRandom>
* @copyright Copyright (c) Chris Wright <https://github.com/DaveRandom>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 2.0.0
*/
2019-06-11 20:07:46 +02:00
2019-06-10 21:04:10 +02:00
namespace Amp\DoH;
use \LibDNS\Messages\Message;
2019-06-11 20:07:46 +02:00
use Amp\Dns\DnsException;
2019-06-11 16:40:22 +02:00
use LibDNS\Messages\MessageTypes;
2019-06-10 21:04:10 +02:00
/**
2019-06-11 20:07:46 +02:00
* Encodes Message objects to raw network data.
2019-06-10 21:04:10 +02:00
*
* @category LibDNS
* @package Encoder
* @author Chris Wright <https://github.com/DaveRandom>
*/
class QueryEncoder
{
/**
2019-06-11 20:07:46 +02:00
* Encode a Message to URL payload.
2019-06-10 21:04:10 +02:00
*
* @param \LibDNS\Messages\Message $message The Message to encode
* @return string
*/
public function encode(Message $message): string
{
2019-06-11 16:40:22 +02:00
if ($message->getType() !== MessageTypes::QUERY) {
throw new DnsException('Invalid question: is not a question record');
}
$questions = $message->getQuestionRecords();
if ($questions->count() === 0) {
throw new DnsException('Invalid question: 0 question records provided');
}
$question = $questions->getRecordByIndex(0);
return \http_build_query(
[
'cd' => 0, // Do not disable result validation
'do' => 0, // Do not send me DNSSEC data
'type' => $question->getType(), // Record type being requested
2019-06-11 20:07:46 +02:00
'name' => \implode('.', $question->getName()->getLabels()), // Record name being requested
2019-06-11 16:40:22 +02:00
'ct' => 'application/dns-json', // Content-type of request
]
);
2019-06-10 21:04:10 +02:00
}
}