/*
Converts a Record into canonical DNS uncompressed wire format (all names are
converted to lowercase), optionally ignoring the TTL.
161103
private byte []
toWireCanonical(boolean noTTL) {
	DNSOutput out = new DNSOutput();
	toWireCanonical(out, noTTL);
	return out.toByteArray();
}
896505
async function decodeData (record) {
    // convert null values to undefined
    for (const key of Object.keys(record)) {
        if (record[key] === null) {
            record[key] = undefined
        }
    }
    // get data column to decode data
    var dataColumn = this.columnName('data')
    // skip if no data column
    if (!defined(dataColumn) || !defined(record[dataColumn])) {
        return
    }
    // decompress if compresion in use
    if (this.compression) {
        // decompress data
        record[dataColumn] = await snappyUncompress(Buffer.from(record[dataColumn], 'base64'), {asBuffer: false})
    }
    // decode data
    record[dataColumn] = JSON.parse(record[dataColumn])
}
992690
def _update_record(self, identifier=None, rtype=None, name=None, content=None):  # pylint: disable=too-many-locals,too-many-branches
        
        with self._session(self.domain, self.domain_id) as ddata:
            # Validate method parameters
            if identifier:
                dtype, dname, dcontent = self._parse_identifier(identifier, ddata['zone']['data'])
                if dtype and dname and dcontent:
                    rtype = rtype if rtype else dtype
                    name = name if name else dname
                    content = content if content else dcontent
                else:
                    LOGGER.warning('Hetzner => Record with identifier \'%s\' does not exist',
                                   identifier)
                    return False

            elif rtype and name and content:
                dtype, dname, dcontent = rtype, name, None
            else:
                LOGGER.warning('Hetzner => Record has no rtype|name|content specified')
                return False

            dname = ddata['cname'] if ddata['cname'] else self._fqdn_name(dname)
            records = self._list_records_in_zone(ddata['zone']['data'], dtype, dname, dcontent)
            if len(records) == 1:
                # Remove record from zone
                rrset = ddata['zone']['data'].get_rdataset(records[0]['name'] + '.',
                                                           rdtype=records[0]['type'])
                rdatas = []
                for rdata in rrset:
                    if self._convert_content(records[0]['type'],
                                             records[0]['content']) != rdata.to_text():
                        rdatas.append(rdata.to_text())
                if rdatas:
                    rdataset = dns.rdataset.from_text_list(rrset.rdclass, rrset.rdtype,
                                                           records[0]['ttl'], rdatas)
                    ddata['zone']['data'].replace_rdataset(records[0]['name'] + '.', rdataset)
                else:
                    ddata['zone']['data'].delete_rdataset(records[0]['name'] + '.',
                                                          records[0]['type'])
                # Add record to zone
                name = ddata['cname'] if ddata['cname'] else self._fqdn_name(name)
                rrset = ddata['zone']['data'].get_rdataset(name, rdtype=rtype, create=True)
                synced_change = False
                for rdata in rrset:
                    if self._convert_content(rtype, content) == rdata.to_text():
                        LOGGER.info('Hetzner => Record with content \'%s\' already exists',
                                    content)
                        synced_change = True
                        break
                if not synced_change:
                    ttl = (rrset.ttl if 0 < rrset.ttl < self._get_lexicon_option('ttl')
                           else self._get_lexicon_option('ttl'))
                    rdataset = dns.rdataset.from_text(rrset.rdclass, rrset.rdtype, ttl,
                                                      self._convert_content(rtype, content))
                    rrset.update(rdataset)
                # Post zone to Hetzner
                synced_change = self._post_zone(ddata['zone'])
                if synced_change:
                    self._propagated_record(rtype, name, self._convert_content(rtype, content),
                                            ddata['nameservers'])
                return synced_change

            LOGGER.warning('Hetzner => Record lookup has not only one match')
            return False
1319124
function parseDistinguishedName(dn) {
  log.trace('parseDistinguishedName(%s)', dn);
  if (! dn) return(dn);

  dn = dn.replace(/"/g, '\\"');
  return(dn.replace('\\,', '\\\\,'));
}
655163
function getDN($format = self::DN_ARRAY, $dn = null)
    {
        if (!isset($dn)) {
            $dn = isset($this->currentCert['tbsCertList']) ? $this->currentCert['tbsCertList']['issuer'] : $this->dn;
        }

        switch ((int) $format) {
            case self::DN_ARRAY:
                return $dn;
            case self::DN_ASN1:
                $asn1 = new ASN1();
                $asn1->loadOIDs($this->oids);
                $filters = array();
                $filters['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING);
                $asn1->loadFilters($filters);
                $this->_mapOutDNs($dn, 'rdnSequence', $asn1);
                return $asn1->encodeDER($dn, $this->Name);
            case self::DN_CANON:
                //  No SEQUENCE around RDNs and all string values normalized as
                // trimmed lowercase UTF-8 with all spacing as one blank.
                // constructed RDNs will not be canonicalized
                $asn1 = new ASN1();
                $asn1->loadOIDs($this->oids);
                $filters = array();
                $filters['value'] = array('type' => ASN1::TYPE_UTF8_STRING);
                $asn1->loadFilters($filters);
                $result = '';
                $this->_mapOutDNs($dn, 'rdnSequence', $asn1);
                foreach ($dn['rdnSequence'] as $rdn) {
                    foreach ($rdn as $i => $attr) {
                        $attr = &$rdn[$i];
                        if (is_array($attr['value'])) {
                            foreach ($attr['value'] as $type => $v) {
                                $type = array_search($type, $asn1->ANYmap, true);
                                if ($type !== false && isset($asn1->stringTypeSize[$type])) {
                                    $v = $asn1->convert($v, $type);
                                    if ($v !== false) {
                                        $v = preg_replace('/\s+/', ' ', $v);
                                        $attr['value'] = strtolower(trim($v));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    $result .= $asn1->encodeDER($rdn, $this->RelativeDistinguishedName);
                }
                return $result;
            case self::DN_HASH:
                $dn = $this->getDN(self::DN_CANON, $dn);
                $hash = new Hash('sha1');
                $hash = $hash->hash($dn);
                extract(unpack('Vhash', $hash));
                return strtolower(bin2hex(pack('N', $hash)));
        }

        // Default is to return a string.
        $start = true;
        $output = '';

        $result = array();
        $asn1 = new ASN1();
        $asn1->loadOIDs($this->oids);
        $filters = array();
        $filters['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING);
        $asn1->loadFilters($filters);
        $this->_mapOutDNs($dn, 'rdnSequence', $asn1);

        foreach ($dn['rdnSequence'] as $field) {
            $prop = $field[0]['type'];
            $value = $field[0]['value'];

            $delim = ', ';
            switch ($prop) {
                case 'id-at-countryName':
                    $desc = 'C';
                    break;
                case 'id-at-stateOrProvinceName':
                    $desc = 'ST';
                    break;
                case 'id-at-organizationName':
                    $desc = 'O';
                    break;
                case 'id-at-organizationalUnitName':
                    $desc = 'OU';
                    break;
                case 'id-at-commonName':
                    $desc = 'CN';
                    break;
                case 'id-at-localityName':
                    $desc = 'L';
                    break;
                case 'id-at-surname':
                    $desc = 'SN';
                    break;
                case 'id-at-uniqueIdentifier':
                    $delim = '/';
                    $desc = 'x500UniqueIdentifier';
                    break;
                case 'id-at-postalAddress':
                    $delim = '/';
                    $desc = 'postalAddress';
                    break;
                default:
                    $delim = '/';
                    $desc = preg_replace('#.+-([^-]+)$#', '$1', $prop);
            }

            if (!$start) {
                $output.= $delim;
            }
            if (is_array($value)) {
                foreach ($value as $type => $v) {
                    $type = array_search($type, $asn1->ANYmap, true);
                    if ($type !== false && isset($asn1->stringTypeSize[$type])) {
                        $v = $asn1->convert($v, $type);
                        if ($v !== false) {
                            $value = $v;
                            break;
                        }
                    }
                }
                if (is_array($value)) {
                    $value = array_pop($value); // Always strip data type.
                }
            } elseif (is_object($value) && $value instanceof Element) {
                $callback = function ($x) {
                    return "\x" . bin2hex($x[0]);
                };
                $value = strtoupper(preg_replace_callback('#[^\x20-\x7E]#', $callback, $value->element));
            }
            $output.= $desc . '=' . $value;
            $result[$desc] = isset($result[$desc]) ?
                array_merge((array) $dn[$prop], array($value)) :
                $value;
            $start = false;
        }

        return $format == self::DN_OPENSSL ? $result : $output;
    }
647121
def output_dns_records(gandi, records, output_keys, justify=12):
    
    for key in output_keys:
        real_key = 'rrset_%s' % key
        if real_key in records:
            val = records[real_key]
            if key == 'values':
                val = format_list(records[real_key])
            output_line(gandi, key, val, justify)
584056
def reverse_dns_sna(ipaddress):
    """"""

    r = requests.get("http://api.statdns.com/x/%s" % ipaddress)

    if r.status_code == 200:
        names = []

        for item in r.json()['answer']:
            name = str(item['rdata']).strip(".")
            names.append(name)

        return names
    elif r.json()['code'] == 503:
        # NXDOMAIN - no PTR record
        return None
164816
public static CERTRecord
buildRecord(Name name, int dclass, long ttl, Certificate cert) {
	return buildRecord(name, dclass, ttl, cert, 0, 0);
}
49803
private Record setDefault(Record record) {
        int size = record.size();
        for (int i = 0; i < size; i++)
            if (record.get(i) == null) {
                @SuppressWarnings("unchecked")
                Field<Object> field = (Field<Object>) record.field(i);
                if (!field.getDataType().nullable() && !field.getDataType().identity())
                    record.set(field, DSL.defaultValue());
            }
        return record;
    }
1079129
public TLSARecord getTLSARecord(URL url) {

        String recordValue;

        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
        }
        String tlsaRecordName = String.format("_%s._tcp.%s", port, DNSUtil.ensureDot(url.getHost()));
        try {
            recordValue = this.dnssecResolver.resolve(tlsaRecordName, Type.TLSA);
        } catch (DNSSECException e) {
            return null;
        }

        if (recordValue.equals("")) return null;

        // Process TLSA Record
        String[] tlsaValues = recordValue.split(" ");
        if (tlsaValues.length != 4) return null;
        try {
            return new TLSARecord(
                    new Name(tlsaRecordName),
                    DClass.IN,
                    0,
                    Integer.parseInt(tlsaValues[0]),
                    Integer.parseInt(tlsaValues[1]),
                    Integer.parseInt(tlsaValues[2]),
                    BaseEncoding.base16().decode(tlsaValues[3])
            );
        } catch (TextParseException e) {
            return null;
        }
    }
894289
public static ByteBuf createDnsQueryPayload(DnsTransaction transaction) {
		ByteBuf byteBuf = ByteBufPool.allocate(MAX_SIZE);

		byteBuf.writeShort(transaction.getId());
		// standard query flags, 1 question and 0 of other stuff
		byteBuf.write(STANDARD_QUERY_HEADER);

		// query domain name
		byte componentSize = 0;
		DnsQuery query = transaction.getQuery();
		byte[] domainBytes = query.getDomainName().getBytes(US_ASCII);

		int pos = -1;
		while (++pos < domainBytes.length) {
			if (domainBytes[pos] != '.') {
				componentSize++;
				continue;
			}
			byteBuf.writeByte(componentSize);
			byteBuf.write(domainBytes, pos - componentSize, componentSize);
			componentSize = 0;
		}
		byteBuf.writeByte(componentSize);
		byteBuf.write(domainBytes, pos - componentSize, componentSize);
		byteBuf.writeByte((byte) 0x0); // terminator byte

		// query record type
		byteBuf.writeShort(query.getRecordType().getCode());
		// query class: IN
		byteBuf.writeShort(QueryClass.INTERNET.getCode());
		return byteBuf;
	}
1320599
def _update_record_with_name(self, old_record, rtype, new_name, content):
        """"""
        new_type = rtype if rtype else old_record['type']

        new_ttl = self._get_lexicon_option('ttl')
        if new_ttl is None and 'ttl' in old_record:
            new_ttl = old_record['ttl']

        new_priority = self._get_lexicon_option('priority')
        if new_priority is None and 'priority' in old_record:
            new_priority = old_record['priority']

        new_content = content
        if new_content is None and 'content' in old_record:
            new_content = old_record['content']

        record = self._create_request_record(None,
                                             new_type,
                                             new_name,
                                             new_content,
                                             new_ttl,
                                             new_priority)

        # This will be a different domain name, so no name collision should
        # happen. First create a new entry and when it succeeds, delete the old
        # one.
        self._request_add_dns_record(record)
        self._request_delete_dns_record_by_id(old_record['id'])
1018665
public static long rawUncompress(long inputAddr, long inputSize, long destAddr)
            throws IOException
    {
        return impl.rawUncompress(inputAddr, inputSize, destAddr);
    }
791680
def from_text_list(name, ttl, rdclass, rdtype, text_rdatas):
    

    if isinstance(name, (str, unicode)):
        name = dns.name.from_text(name, None)
    if isinstance(rdclass, (str, unicode)):
        rdclass = dns.rdataclass.from_text(rdclass)
    if isinstance(rdtype, (str, unicode)):
        rdtype = dns.rdatatype.from_text(rdtype)
    r = RRset(name, rdclass, rdtype)
    r.update_ttl(ttl)
    for t in text_rdatas:
        rd = dns.rdata.from_text(r.rdclass, r.rdtype, t)
        r.add(rd)
    return r
1031379
private void convertLink2Record(final Object iKey) {
		if (status == MULTIVALUE_CONTENT_TYPE.ALL_RECORDS)
			return;

		final Object value;

		if (iKey instanceof ORID)
			value = iKey;
		else
			value = super.get(iKey);

		if (value != null && value instanceof ORID) {
			final ORID rid = (ORID) value;
			marshalling = true;
			try {
				try {
					// OVERWRITE IT
					super.put(iKey, rid.getRecord());
				} catch (ORecordNotFoundException e) {
					// IGNORE THIS
				}
			} finally {
				marshalling = false;
			}
		}
	}
1181885
public static URI[] fromDNSName(String srvName) throws NamingException {
    List<URI> uris = new ArrayList<>();
    Hashtable<String, String> env = new Hashtable<>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    env.put("java.naming.provider.url", "dns:");

    DirContext ctx = new InitialDirContext(env);
    Attributes attributes = ctx.getAttributes(srvName, new String[]{"SRV"});
    NamingEnumeration<? extends Attribute> records = attributes.getAll();

    while (records.hasMore()) {
      Attribute next = records.next();

      @SuppressWarnings("unchecked")
      NamingEnumeration<String> values = (NamingEnumeration<String>) next.getAll();
      while (values.hasMore()) {
        String dns = values.next();
        String[] split = dns.split(" ");
        String port = split[2];
        String host = split[3];
        if (host.endsWith(".")) {
          host = host.substring(0, host.length() - 1);
        }
        URI uri = URI.create("http://" + host + ":" + port);
        uris.add(uri);
      }
    }
    return uris.toArray(new URI[uris.size()]);
  }
783515
public static KEYRecord
buildRecord(Name name, int dclass, long ttl, int flags, int proto,
	    PublicKey key)
{
	byte alg;

	if (key instanceof RSAPublicKey) {
		alg = DNSSEC.RSAMD5;
	}
	else if (key instanceof DHPublicKey) {
		alg = DNSSEC.DH;
	}
	else if (key instanceof DSAPublicKey) {
		alg = DNSSEC.DSA;
	}
	else
		return null;

	return (KEYRecord) buildRecord(name, Type.KEY, dclass, ttl, flags,
				       proto, alg, key);
}