-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathModule.php
371 lines (335 loc) · 9.34 KB
/
Module.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php declare(strict_types=1);
/**
* Copyright (C) Apis Networks, Inc - All Rights Reserved.
*
* MIT License
*
* Written by Matt Saladna <[email protected]>, August 2018
*/
namespace Opcenter\Dns\Providers\Digitalocean;
use GuzzleHttp\Exception\ClientException;
use Module\Provider\Contracts\ProviderInterface;
use Opcenter\Crypto\Keyring;
use Opcenter\Crypto\KeyringTrait;
use Opcenter\Dns\Record as BaseRecord;
class Module extends \Dns_Module implements ProviderInterface
{
use \NamespaceUtilitiesTrait;
use KeyringTrait;
/**
* apex markers are marked with @
*/
protected const HAS_ORIGIN_MARKER = true;
protected static $permitted_records = [
'A',
'AAAA',
'CAA',
'CNAME',
'MX',
'NS',
'SRV',
'TXT',
];
// @var int minimum TTL
public const DNS_TTL_MIN = 30;
// Avoid duplicating apex NS records
public const SHOW_NS_APEX = false;
// @var array API credentials
private $key;
public function __construct()
{
parent::__construct();
$this->key = $this->getServiceValue('dns', 'key', DNS_PROVIDER_KEY);
if (Keyring::is($this->key)) {
$this->key = $this->readKeyringValue($this->key);
}
}
/**
* Add a DNS record
*
* @param string $zone
* @param string $subdomain
* @param string $rr
* @param string $param
* @param int $ttl
* @return bool
*/
public function add_record(
string $zone,
string $subdomain,
string $rr,
string $param,
int $ttl = self::DNS_TTL
): bool {
if (!$this->canonicalizeRecord($zone, $subdomain, $rr, $param, $ttl)) {
return false;
}
if (!$this->owned_zone($zone)) {
return error("Domain `%s' not owned by account", $zone);
}
$api = $this->makeApi();
$record = new Record($zone, [
'name' => $subdomain,
'rr' => $rr,
'parameter' => $param,
'ttl' => $ttl
]);
if ($record['name'] === '') {
$record['name'] = '@';
}
try {
$this->formatRecord($record);
$ret = $api->do('POST', "domains/{$zone}/records", $this->formatRecord($record));
if (!isset($ret['id']) && isset($ret['domain_record'])) {
// pluck from domain_record.id
$ret = $ret['domain_record'];
}
$record->setMeta('id', $ret['id']);
$this->addCache($record);
} catch (ClientException $e) {
$fqdn = ltrim(implode('.', [$subdomain, $zone]), '.');
return error("Failed to create record `%s' type %s: %s", $fqdn, $rr, $e->getMessage());
}
return (bool)$ret;
}
/**
* @inheritDoc
*/
public function remove_record(string $zone, string $subdomain, string $rr, string $param = ''): bool
{
if (!$this->canonicalizeRecord($zone, $subdomain, $rr, $param, $ttl)) {
return false;
}
if (!$this->owned_zone($zone)) {
return error("Domain `%s' not owned by account", $zone);
}
$api = $this->makeApi();
$id = $this->getRecordId($r = new Record($zone,
['name' => $subdomain, 'rr' => $rr, 'parameter' => $param, 'ttl' => null]));
if (!$id) {
$fqdn = ltrim(implode('.', [$subdomain, $zone]), '.');
return error("Record `%s' (rr: `%s', param: `%s') does not exist", $fqdn, $rr, $param);
}
try {
$api->do('DELETE', "domains/{$zone}/records/{$id}");
} catch (ClientException $e) {
$fqdn = ltrim(implode('.', [$subdomain, $zone]), '.');
return error("Failed to delete record `%s' type %s", $fqdn, $rr);
}
array_forget_first($this->zoneCache[$r->getZone()], $this->getCacheKey($r), static function ($v) use ($r) {
return $v['id'] === $r['id'];
});
return $api->getResponse()->getStatusCode() === 204;
}
/**
* Get hosting nameservers
*
* @param string|null $domain
* @return array
*/
public function get_hosting_nameservers(string $domain = null): array
{
return ['ns1.digitalocean.com', 'ns2.digitalocean.com', 'ns3.digitalocean.com'];
}
/**
* Add DNS zone to service
*
* @param string $domain
* @param string $ip
* @return bool
*/
public function add_zone_backend(string $domain, string $ip): bool
{
/**
* @var Zones $api
*/
$api = $this->makeApi();
try {
$api->do('POST', 'domains', [
'name' => $domain,
'ip_address' => $ip
]);
} catch (ClientException $e) {
return error("Failed to add zone `%s', error: %s", $domain, $e->getMessage());
}
return true;
}
/**
* Remove DNS zone from nameserver
*
* @param string $domain
* @return bool
*/
public function remove_zone_backend(string $domain): bool
{
$api = $this->makeApi();
try {
$api->do('DELETE', "domains/{$domain}");
} catch (ClientException $e) {
return error("Failed to remove zone `%s', error: %s", $domain, $e->getMessage());
}
return true;
}
/**
* Get raw zone data
*
* @param string $domain
* @return null|string
*/
protected function zoneAxfr(string $domain): ?string
{
$client = $this->makeApi();
try {
$axfr = $client->do('GET', "domains/{$domain}?per_page=100");
if (empty($axfr['domain']['zone_file'])) {
// zone doesn't exist
return null;
}
} catch (ClientException $e) {
return null;
}
for ($i = 0; $i < 5; $i++) {
try {
$records = [];
$zoneText = $axfr['domain']['zone_file'];
$url = "domains/{$domain}/records";
$queryStr = "per_page=100";
while (true) {
$batch = $client->do('GET', "$url?$queryStr");
$records = array_merge_recursive($records, $batch['domain_records']);
if (!$url = array_get($batch, 'links.pages.next')) {
break;
}
$queryStr = parse_url($url)['query'];
}
} catch (ClientException $e) {
error('Failed to transfer DNS records from DO - try again later');
return null;
}
}
$this->zoneCache[$domain] = [];
foreach ($records as $r) {
switch ($r['type']) {
case 'SOA':
// SOA records are improperly formatted
continue 2;
case 'CAA':
$parameter = $r['flags'] . ' ' . $r['tag'] . ' ' . $r['data'];
break;
case 'SRV':
$parameter = $r['priority'] . ' ' . $r['weight'] . ' ' . $r['port'] . ' ' . $r['data'];
break;
case 'MX':
$parameter = $r['priority'] . ' ' . $r['data'];
break;
default:
$parameter = $r['data'];
}
$this->addCache(new Record($domain,
[
'name' => $r['name'],
'rr' => $r['type'],
'ttl' => $r['ttl'] ?? static::DNS_TTL,
'parameter' => $parameter,
'meta' => [
'id' => $r['id']
]
]
));
}
return $zoneText;
}
private function makeApi(): Api
{
return new Api($this->key);
}
/**
* Modify a DNS record
*
* @param string $zone
* @param Record $old
* @param Record $new
* @return bool
*/
protected function atomicUpdate(string $zone, BaseRecord $old, BaseRecord $new): bool
{
// @var \Cloudflare\Api\Endpoints\DNS @api
if (!$this->canonicalizeRecord($zone, $old['name'], $old['rr'], $old['parameter'], $old['ttl'])) {
return false;
}
$old['ttl'] = null;
if (!($id = $this->getRecordId($old))) {
return error("failed to find record ID in DO zone `%s' - does `%s' (rr: `%s', parameter: `%s') exist?",
$zone, $old['name'], $old['rr'], $old['parameter']);
}
if (!$this->canonicalizeRecord($zone, $new['name'], $new['rr'], $new['parameter'], $new['ttl'])) {
return false;
}
$api = $this->makeApi();
try {
$merged = clone $old;
$new = $merged->merge($new);
$ret = $api->do('PUT', "domains/{$zone}/records/{$id}", $this->formatRecord($new));
if (isset($ret['domain_record'])) {
$ret = $ret['domain_record'];
}
$new->setMeta('id', $ret['id'] ?? null);
} catch (ClientException $e) {
$reason = \json_decode($e->getResponse()->getBody()->getContents());
$msg = $reason->errors[0]->message ?? $reason->message;
return error("Failed to update record `%s' on zone `%s' (old - rr: `%s', param: `%s'; new - rr: `%s', param: `%s'): %s",
$old['name'],
$zone,
$old['rr'],
$old['parameter'], $new['name'] ?? $old['name'], $new['parameter'] ?? $old['parameter'],
$msg
);
}
array_forget_first($this->zoneCache[$old->getZone()], $this->getCacheKey($old), static function ($v) use ($old) {
return $v['id'] === $old['id'];
});
$this->addCache($new);
return true;
}
protected function formatRecord(Record $r)
{
$args = [
'type' => strtoupper($r['rr']),
'ttl' => (int)($r['ttl'] ?? static::DNS_TTL),
'name' => $r['name']
];
switch ($args['type']) {
case 'CNAME':
case 'NS':
$r['parameter'] = rtrim($r['parameter'], '.') . '.';
case 'A':
case 'AAAA':
case 'TXT':
return $args + ['data' => $r['parameter']];
case 'MX':
return $args + [
'priority' => (int)$r->getMeta('priority'),
'data' => rtrim($r->getMeta('data'), '.') . '.'
];
case 'SRV':
return $args + [
'priority' => (int)$r->getMeta('priority'),
'weight' => (int)$r->getMeta('weight'),
'port' => (int)$r->getMeta('port'),
'data' => rtrim($r->getMeta('data'), '.') . '.'
];
case 'CAA':
return $args + [
'flags' => (int)$r->getMeta('flags'),
'tag' => $r->getMeta('tag'),
'data' => $r->getMeta('data')
];
default:
fatal("Unsupported DNS RR type `%s'", $r['type']);
}
}
protected function hasCnameApexRestriction(): bool
{
return false;
}
}