MediaWiki master
DnsSrvDiscoverer.php
Go to the documentation of this file.
1<?php
16 private $service;
17
21 private $protocol;
22
26 private $domain;
27
31 private $resolver;
32
44 public function __construct(
45 string $service,
46 string $protocol = 'tcp',
47 ?string $domain = null,
48 ?callable $resolver = null
49 ) {
50 $this->service = $service;
51 $this->protocol = $protocol;
52 $this->domain = $domain;
53
54 $this->resolver = $resolver ?? static function ( $srv ) {
55 return dns_get_record( $srv, DNS_SRV );
56 };
57 }
58
66 public function getRecords() {
67 $result = [];
68
69 $records = ( $this->resolver )( $this->getSrvName() );
70
71 // Respect RFC 2782 with regard to a single '.' entry denoting a valid
72 // empty response
73 if (
74 !$records
75 || ( count( $records ) === 1 && $records[0]['target'] === '.' )
76 ) {
77 return $result;
78 }
79
80 foreach ( $records as $record ) {
81 $result[] = [
82 'target' => $record['target'],
83 'port' => (int)$record['port'],
84 'pri' => (int)$record['pri'],
85 'weight' => (int)$record['weight'],
86 ];
87 }
88
89 return $result;
90 }
91
99 public function getServers() {
100 $records = $this->getRecords();
101
102 usort( $records, static function ( $a, $b ) {
103 if ( $a['pri'] === $b['pri'] ) {
104 return mt_rand( 0, 1 ) ? 1 : -1;
105 }
106
107 return $a['pri'] - $b['pri'];
108 } );
109
110 $serversAndPorts = [];
111
112 foreach ( $records as $record ) {
113 $serversAndPorts[] = [ $record['target'], $record['port'] ];
114 }
115
116 return $serversAndPorts;
117 }
118
122 public function getSrvName(): string {
123 $srv = "_{$this->service}._{$this->protocol}";
124
125 if ( $this->domain === null || $this->domain === '' ) {
126 return $srv;
127 }
128
129 return "$srv.{$this->domain}";
130 }
131}
__construct(string $service, string $protocol='tcp', ?string $domain=null, ?callable $resolver=null)
Construct a new discoverer for the given domain, service, and protocol.
getRecords()
Queries the resolver for an SRV resource record matching the service, protocol, and domain and return...
getServers()
Performs discovery for the domain, service, and protocol, and returns a list of resolved server name/...
getSrvName()
Returns the SRV resource record name.