�ɲɾ�����ӯ�����һ��ˣ��������С���˴��ͣ�������P���ҹ��ñ˽��ά�Բ��������˸߸ԣ�������ơ��ҹ��ñ�����ά�Բ���ˡ���˳^�ӣ������ӡ� ���ͯj�ӣ��ƺ���ӣ� ? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!PK{ 1]T\kk keymgr.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ from __future__ import print_function import os, sys, argparse, glob, re, time, calendar, pprint from collections import defaultdict prog='dnssec-keymgr' from isc import dnskey, keydict, keyseries, policy, parsetab, utils ############################################################################ # print a fatal error and exit ############################################################################ def fatal(*args, **kwargs): print(*args, **kwargs) sys.exit(1) ############################################################################ # find the location of an external command ############################################################################ def set_path(command, default=None): """ find the location of a specified command. If a default is supplied, exists and it's an executable, we use it; otherwise we search PATH for an alternative. :param command: command to look for :param default: default value to use :return: PATH with the location of a suitable binary """ fpath = default if not fpath or not os.path.isfile(fpath) or not os.access(fpath, os.X_OK): path = os.environ["PATH"] if not path: path = os.path.defpath for directory in path.split(os.pathsep): fpath = directory + os.sep + command if os.path.isfile(fpath) and os.access(fpath, os.X_OK): break fpath = None return fpath ############################################################################ # parse arguments ############################################################################ def parse_args(): """ Read command line arguments, returns 'args' object :return: args object properly prepared """ keygen = set_path('dnssec-keygen', os.path.join(utils.prefix('sbin'), 'dnssec-keygen')) settime = set_path('dnssec-settime', os.path.join(utils.prefix('sbin'), 'dnssec-settime')) parser = argparse.ArgumentParser(description=prog + ': schedule ' 'DNSSEC key rollovers according to a ' 'pre-defined policy') parser.add_argument('zone', type=str, nargs='*', default=None, help='Zone(s) to which the policy should be applied ' + '(default: all zones in the directory)') parser.add_argument('-K', dest='path', type=str, help='Directory containing keys', metavar='dir') parser.add_argument('-c', dest='policyfile', type=str, help='Policy definition file', metavar='file') parser.add_argument('-g', dest='keygen', default=keygen, type=str, help='Path to \'dnssec-keygen\'', metavar='path') parser.add_argument('-r', dest='randomdev', type=str, default=None, help='Path to a file containing random data to pass to \'dnssec-keygen\'', metavar='path') parser.add_argument('-s', dest='settime', default=settime, type=str, help='Path to \'dnssec-settime\'', metavar='path') parser.add_argument('-k', dest='no_zsk', action='store_true', default=False, help='Only apply policy to key-signing keys (KSKs)') parser.add_argument('-z', dest='no_ksk', action='store_true', default=False, help='Only apply policy to zone-signing keys (ZSKs)') parser.add_argument('-f', '--force', dest='force', action='store_true', default=False, help='Force updates to key events '+ 'even if they are in the past') parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', default=False, help='Update keys silently') parser.add_argument('-v', '--version', action='version', version=utils.version) args = parser.parse_args() if args.no_zsk and args.no_ksk: fatal("ERROR: -z and -k cannot be used together.") if args.keygen is None: fatal("ERROR: dnssec-keygen not found") if args.settime is None: fatal("ERROR: dnssec-settime not found") # if a policy file was specified, check that it exists. # if not, use the default file, unless it doesn't exist if args.policyfile is not None: if not os.path.exists(args.policyfile): fatal('ERROR: Policy file "%s" not found' % args.policyfile) else: args.policyfile = os.path.join(utils.sysconfdir, 'dnssec-policy.conf') if not os.path.exists(args.policyfile): args.policyfile = None return args ############################################################################ # main ############################################################################ def main(): args = parse_args() # As we may have specific locations for the binaries, we put that info # into a context object that can be passed around context = {'keygen_path': args.keygen, 'settime_path': args.settime, 'keys_path': args.path, 'randomdev': args.randomdev} try: dp = policy.dnssec_policy(args.policyfile) except Exception as e: fatal('Unable to load DNSSEC policy: ' + str(e)) try: kd = keydict(dp, path=args.path, zones=args.zone) except Exception as e: fatal('Unable to build key dictionary: ' + str(e)) try: ks = keyseries(kd, context=context) except Exception as e: fatal('Unable to build key series: ' + str(e)) try: ks.enforce_policy(dp, ksk=args.no_zsk, zsk=args.no_ksk, force=args.force, quiet=args.quiet) except Exception as e: fatal('Unable to apply policy: ' + str(e)) PK{ 1]'ס&& checkds.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ import argparse import os import sys from subprocess import Popen, PIPE from isc.utils import prefix,version prog = 'dnssec-checkds' ############################################################################ # SECRR class: # Class for DS/DLV resource record ############################################################################ class SECRR: hashalgs = {1: 'SHA-1', 2: 'SHA-256', 3: 'GOST', 4: 'SHA-384'} rrname = '' rrclass = 'IN' keyid = None keyalg = None hashalg = None digest = '' ttl = 0 def __init__(self, rrtext, dlvname = None): if not rrtext: raise Exception # 'str' does not have decode method in python3 if type(rrtext) is not str: fields = rrtext.decode('ascii').split() else: fields = rrtext.split() if len(fields) < 7: raise Exception if dlvname: self.rrtype = "DLV" self.dlvname = dlvname.lower() parent = fields[0].lower().strip('.').split('.') parent.reverse() dlv = dlvname.split('.') dlv.reverse() while len(dlv) != 0 and len(parent) != 0 and parent[0] == dlv[0]: parent = parent[1:] dlv = dlv[1:] if dlv: raise Exception parent.reverse() self.parent = '.'.join(parent) self.rrname = self.parent + '.' + self.dlvname + '.' else: self.rrtype = "DS" self.rrname = fields[0].lower() fields = fields[1:] if fields[0].upper() in ['IN', 'CH', 'HS']: self.rrclass = fields[0].upper() fields = fields[1:] else: self.ttl = int(fields[0]) self.rrclass = fields[1].upper() fields = fields[2:] if fields[0].upper() != self.rrtype: raise Exception('%s does not match %s' % (fields[0].upper(), self.rrtype)) self.keyid, self.keyalg, self.hashalg = map(int, fields[1:4]) self.digest = ''.join(fields[4:]).upper() def __repr__(self): return '%s %s %s %d %d %d %s' % \ (self.rrname, self.rrclass, self.rrtype, self.keyid, self.keyalg, self.hashalg, self.digest) def __eq__(self, other): return self.__repr__() == other.__repr__() ############################################################################ # check: # Fetch DS/DLV RRset for the given zone from the DNS; fetch DNSKEY # RRset from the masterfile if specified, or from DNS if not. # Generate a set of expected DS/DLV records from the DNSKEY RRset, # and report on congruency. ############################################################################ def check(zone, args, masterfile=None, lookaside=None): rrlist = [] cmd = [args.dig, "+noall", "+answer", "-t", "dlv" if lookaside else "ds", "-q", zone + "." + lookaside if lookaside else zone] fp, _ = Popen(cmd, stdout=PIPE).communicate() for line in fp.splitlines(): if type(line) is not str: line = line.decode('ascii') rrlist.append(SECRR(line, lookaside)) rrlist = sorted(rrlist, key=lambda rr: (rr.keyid, rr.keyalg, rr.hashalg)) klist = [] if masterfile: cmd = [args.dsfromkey, "-f", masterfile] if lookaside: cmd += ["-l", lookaside] cmd.append(zone) fp, _ = Popen(cmd, stdout=PIPE).communicate() else: intods, _ = Popen([args.dig, "+noall", "+answer", "-t", "dnskey", "-q", zone], stdout=PIPE).communicate() cmd = [args.dsfromkey, "-f", "-"] if lookaside: cmd += ["-l", lookaside] cmd.append(zone) fp, _ = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(intods) for line in fp.splitlines(): if type(line) is not str: line = line.decode('ascii') klist.append(SECRR(line, lookaside)) if len(klist) < 1: print("No DNSKEY records found in zone apex") return False found = False for rr in klist: if rr in rrlist: print("%s for KSK %s/%03d/%05d (%s) found in parent" % (rr.rrtype, rr.rrname.strip('.'), rr.keyalg, rr.keyid, SECRR.hashalgs[rr.hashalg])) found = True else: print("%s for KSK %s/%03d/%05d (%s) missing from parent" % (rr.rrtype, rr.rrname.strip('.'), rr.keyalg, rr.keyid, SECRR.hashalgs[rr.hashalg])) if not found: print("No %s records were found for any DNSKEY" % ("DLV" if lookaside else "DS")) return found ############################################################################ # parse_args: # Read command line arguments, set global 'args' structure ############################################################################ def parse_args(): parser = argparse.ArgumentParser(description=prog + ': checks DS coverage') bindir = 'bin' sbindir = 'bin' if os.name == 'nt' else 'sbin' parser.add_argument('zone', type=str, help='zone to check') parser.add_argument('-f', '--file', dest='masterfile', type=str, help='zone master file') parser.add_argument('-l', '--lookaside', dest='lookaside', type=str, help='DLV lookaside zone') parser.add_argument('-d', '--dig', dest='dig', default=os.path.join(prefix(bindir), 'dig'), type=str, help='path to \'dig\'') parser.add_argument('-D', '--dsfromkey', dest='dsfromkey', default=os.path.join(prefix(sbindir), 'dnssec-dsfromkey'), type=str, help='path to \'dnssec-dsfromkey\'') parser.add_argument('-v', '--version', action='version', version=version) args = parser.parse_args() args.zone = args.zone.strip('.') if args.lookaside: args.lookaside = args.lookaside.strip('.') return args ############################################################################ # Main ############################################################################ def main(): args = parse_args() found = check(args.zone, args, args.masterfile, args.lookaside) exit(0 if found else 1) PK{ 1]׀} keyevent.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ import time ######################################################################## # Class keyevent ######################################################################## class keyevent: """ A discrete key event, e.g., Publish, Activate, Inactive, Delete, etc. Stores the date of the event, and identifying information about the key to which the event will occur.""" def __init__(self, what, key, when=None): self.what = what self.when = when or key.gettime(what) self.key = key self.sep = key.sep self.zone = key.name self.alg = key.alg self.keyid = key.keyid def __repr__(self): return repr((self.when, self.what, self.keyid, self.sep, self.zone, self.alg)) def showtime(self): return time.strftime("%a %b %d %H:%M:%S UTC %Y", self.when) # update sets of active and published keys, based on # the contents of this keyevent def status(self, active, published, output = None): def noop(*args, **kwargs): pass if not output: output = noop if not active: active = set() if not published: published = set() if self.what == "Activate": active.add(self.keyid) elif self.what == "Publish": published.add(self.keyid) elif self.what == "Inactive": if self.keyid not in active: output("\tWARNING: %s scheduled to become inactive " "before it is active" % repr(self.key)) else: active.remove(self.keyid) elif self.what == "Delete": if self.keyid in published: published.remove(self.keyid) else: output("WARNING: key %s is scheduled for deletion " "before it is published" % repr(self.key)) elif self.what == "Revoke": # We don't need to worry about the logic of this one; # just stop counting this key as either active or published if self.keyid in published: published.remove(self.keyid) if self.keyid in active: active.remove(self.keyid) return active, published PK{ 1]+V! ! keydict.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ from collections import defaultdict from . import dnskey import os import glob ######################################################################## # Class keydict ######################################################################## class keydict: """ A dictionary of keys, indexed by name, algorithm, and key id """ _keydict = defaultdict(lambda: defaultdict(dict)) _defttl = None _missing = [] def __init__(self, dp=None, **kwargs): self._defttl = kwargs.get('keyttl', None) zones = kwargs.get('zones', None) if not zones: path = kwargs.get('path',None) or '.' self.readall(path) else: for zone in zones: if 'path' in kwargs and kwargs['path'] is not None: path = kwargs['path'] else: path = dp and dp.policy(zone).directory or '.' if not self.readone(path, zone): self._missing.append(zone) def readall(self, path): files = glob.glob(os.path.join(path, '*.private')) for infile in files: key = dnskey(infile, path, self._defttl) self._keydict[key.name][key.alg][key.keyid] = key def readone(self, path, zone): if not zone.endswith('.'): zone += '.' match='K' + zone + '+*.private' files = glob.glob(os.path.join(path, match)) found = False for infile in files: key = dnskey(infile, path, self._defttl) if key.fullname != zone: # shouldn't ever happen continue keyname=key.name if zone != '.' else '.' self._keydict[keyname][key.alg][key.keyid] = key found = True return found def __iter__(self): for zone, algorithms in self._keydict.items(): for alg, keys in algorithms.items(): for key in keys.values(): yield key def __getitem__(self, name): return self._keydict[name] def zones(self): return (self._keydict.keys()) def algorithms(self, zone): return (self._keydict[zone].keys()) def keys(self, zone, alg): return (self._keydict[zone][alg].keys()) def missing(self): return (self._missing) PK{ 1]M2"" keyseries.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ from collections import defaultdict from .dnskey import * from .keydict import * from .keyevent import * from .policy import * import time class keyseries: _K = defaultdict(lambda: defaultdict(list)) _Z = defaultdict(lambda: defaultdict(list)) _zones = set() _kdict = None _context = None def __init__(self, kdict, now=time.time(), context=None): self._kdict = kdict self._context = context self._zones = set(kdict.missing()) for zone in kdict.zones(): self._zones.add(zone) for alg, keys in kdict[zone].items(): for k in keys.values(): if k.sep: if not (k.delete() and k.delete() < now): self._K[zone][alg].append(k) else: if not (k.delete() and k.delete() < now): self._Z[zone][alg].append(k) self._K[zone][alg].sort() self._Z[zone][alg].sort() def __iter__(self): for zone in self._zones: for collection in [self._K, self._Z]: if zone not in collection: continue for alg, keys in collection[zone].items(): for key in keys: yield key def dump(self): for k in self: print("%s" % repr(k)) def fixseries(self, keys, policy, now, **kwargs): force = kwargs.get('force', False) if not keys: return # handle the first key key = keys[0] if key.sep: rp = policy.ksk_rollperiod prepub = policy.ksk_prepublish or (30 * 86400) postpub = policy.ksk_postpublish or (30 * 86400) else: rp = policy.zsk_rollperiod prepub = policy.zsk_prepublish or (30 * 86400) postpub = policy.zsk_postpublish or (30 * 86400) # the first key should be published and active p = key.publish() a = key.activate() if not p or p > now: key.setpublish(now) p = now if not a or a > now: key.setactivate(now) a = now i = key.inactive() fudge = 300 if not rp: key.setinactive(None, **kwargs) key.setdelete(None, **kwargs) elif not i or a + rp != i: if not i and a + rp > now + prepub + fudge: key.setinactive(a + rp, **kwargs) key.setdelete(a + rp + postpub, **kwargs) elif not i: key.setinactive(now + prepub + fudge, **kwargs) key.setdelete(now + prepub + postpub + fudge, **kwargs) elif i < now: pass elif a + rp > i: key.setinactive(a + rp, **kwargs) key.setdelete(a + rp + postpub, **kwargs) elif a + rp > now + prepub + fudge: key.setinactive(a + rp, **kwargs) key.setdelete(a + rp + postpub, **kwargs) else: key.setinactive(now + prepub + fudge, **kwargs) key.setdelete(now + prepub + postpub + fudge, **kwargs) else: d = key.delete() if not d or i + postpub > now + fudge: key.setdelete(i + postpub, **kwargs) elif not d: key.setdelete(now + postpub + fudge, **kwargs) elif d < now + fudge: pass elif d < i + postpub: key.setdelete(i + postpub, **kwargs) if policy.keyttl != key.ttl: key.setttl(policy.keyttl) # handle all the subsequent keys prev = key for key in keys[1:]: # if no rollperiod, then all keys after the first in # the series kept inactive. # (XXX: we need to change this to allow standby keys) if not rp: key.setpublish(None, **kwargs) key.setactivate(None, **kwargs) key.setinactive(None, **kwargs) key.setdelete(None, **kwargs) if policy.keyttl != key.ttl: key.setttl(policy.keyttl) continue # otherwise, ensure all dates are set correctly based on # the initial key a = prev.inactive() p = a - prepub key.setactivate(a, **kwargs) key.setpublish(p, **kwargs) key.setinactive(a + rp, **kwargs) key.setdelete(a + rp + postpub, **kwargs) prev.setdelete(a + postpub, **kwargs) if policy.keyttl != key.ttl: key.setttl(policy.keyttl) prev = key # if we haven't got sufficient coverage, create successor key(s) while rp and prev.inactive() and \ prev.inactive() < now + policy.coverage: # commit changes to predecessor: a successor can only be # generated if Inactive has been set in the predecessor key prev.commit(self._context['settime_path'], **kwargs) key = prev.generate_successor(self._context['keygen_path'], self._context['randomdev'], prepub, **kwargs) key.setinactive(key.activate() + rp, **kwargs) key.setdelete(key.inactive() + postpub, **kwargs) keys.append(key) prev = key # last key? we already know we have sufficient coverage now, so # disable the inactivation of the final key (if it was set), # ensuring that if dnssec-keymgr isn't run again, the last key # in the series will at least remain usable. prev.setinactive(None, **kwargs) prev.setdelete(None, **kwargs) # commit changes for key in keys: key.commit(self._context['settime_path'], **kwargs) def enforce_policy(self, policies, now=time.time(), **kwargs): # If zones is provided as a parameter, use that list. # If not, use what we have in this object zones = kwargs.get('zones', self._zones) keys_dir = kwargs.get('dir', self._context.get('keys_path', None)) force = kwargs.get('force', False) for zone in zones: collections = [] policy = policies.policy(zone) keys_dir = keys_dir or policy.directory or '.' alg = policy.algorithm algnum = dnskey.algnum(alg) if 'ksk' not in kwargs or not kwargs['ksk']: if len(self._Z[zone][algnum]) == 0: k = dnskey.generate(self._context['keygen_path'], self._context['randomdev'], keys_dir, zone, alg, policy.zsk_keysize, False, policy.keyttl or 3600, **kwargs) self._Z[zone][algnum].append(k) collections.append(self._Z[zone]) if 'zsk' not in kwargs or not kwargs['zsk']: if len(self._K[zone][algnum]) == 0: k = dnskey.generate(self._context['keygen_path'], self._context['randomdev'], keys_dir, zone, alg, policy.ksk_keysize, True, policy.keyttl or 3600, **kwargs) self._K[zone][algnum].append(k) collections.append(self._K[zone]) for collection in collections: for algorithm, keys in collection.items(): if algorithm != algnum: continue try: self.fixseries(keys, policy, now, **kwargs) except Exception as e: raise Exception('%s/%s: %s' % (zone, dnskey.algstr(algnum), str(e))) PK{ 1]LL'__pycache__/policy.cpython-36.opt-1.pycnu[3 ~j2g@s:ddlZddljZddljZddlTddlmZGdddZGdddZGdd d e Z Gd d d Z e d kr6ddl Z e jd dkree jdZejZejed dZejenxe jd dkr6y4e e jddddZeejdeejdWn2e k r4ZzeejdWYddZ[XnXdS)N)*)copyc @seZdZd3Zed4ZiZdZdZdZdZ dZ ddZ ddZ d d!Z d"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2S)5 PolicyLexPOLICYALGORITHM_POLICYZONE ALGORITHM DIRECTORYKEYTTLKEY_SIZE ROLL_PERIOD PRE_PUBLISH POST_PUBLISHCOVERAGESTANDBYNONE DATESUFFIXKEYTYPEALGNAMESTRQSTRINGNUMBERLBRACERBRACESEMIz z (//|\#).*z\{z\};cCs|jj|jjd7_dS)z\n+ N)lexerlinenovaluecount)selftr#/usr/lib/python3.6/policy.py t_newline7szPolicyLex.t_newlinecCs|jj|jjd7_dS)z/\*(.|\n)*?\*/rN)rrrr )r!r"r#r#r$ t_comment;szPolicyLex.t_commentcCstjd|jjdj|_|S)z(?i)(?<=[0-9 \t])(y(?:ears|ear|ea|e)?|mo(?:nths|nth|nt|n)?|w(?:eeks|eek|ee|e)?|d(?:ays|ay|a)?|h(?:ours|our|ou|o)?|mi(?:nutes|nute|nut|nu|n)?|s(?:econds|econd|econ|eco|ec|e)?)\bz(?i)(y|mo|w|d|h|mi|s)([a-z]*))rematchrgrouplower)r!r"r#r#r$ t_DATESUFFIX?szPolicyLex.t_DATESUFFIXcCs|jj|_|S)z(?i)\b(KSK|ZSK)\b)rupper)r!r"r#r#r$ t_KEYTYPEDs zPolicyLex.t_KEYTYPEcCs|jj|_|S)z(?i)\b(RSAMD5|DH|DSA|NSEC3DSA|ECC|RSASHA1|NSEC3RSASHA1|RSASHA256|RSASHA512|ECCGOST|ECDSAP256SHA256|ECDSAP384SHA384|ED25519|ED448)\b)rr-)r!r"r#r#r$ t_ALGNAMEIs zPolicyLex.t_ALGNAMEcCs|jj|jd|_|S)z[A-Za-z._-][\w._-]*r) reserved_mapgetrtype)r!r"r#r#r$t_STRNszPolicyLex.t_STRcCs&|jj|jd|_|jdd|_|S)z"([^"\n]|(\\"))*"rr')r0r1rr2)r!r"r#r#r$ t_QSTRINGSszPolicyLex.t_QSTRINGcCst|j|_|S)z\d+)intr)r!r"r#r#r$t_NUMBERYs zPolicyLex.t_NUMBERcCs"td|jd|jjddS)NzIllegal character '%s'rr')printrrskip)r!r"r#r#r$t_error^szPolicyLex.t_errorcKsbdttkrtjdd}n tdd}x"|jD]}||j|jj|<q,Wtjfd|i||_dS)N maketrans_-object) dirstrr;reservedr0r+ translatelexr)r!kwargsZtransrr#r#r$__init__bs    zPolicyLex.__init__cCs.|jj|x|jj}|sPt|qWdS)N)rinputtokenr8)r!textr"r#r#r$testks   zPolicyLex.testN) rrrrr r r r r rrrr) rrrrrrrrr)__name__ __module__ __qualname__rAtokensr0Zt_ignoreZt_ignore_olcommentZt_LBRACEZt_RBRACEZt_SEMIr%r&r,r.r/r3r5r7r:rFrJr#r#r#r$rsN rc @seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZddgddgddgddgddgddgddgdddddd ZdddZd d Zd d Zd dZddZddZdS)PolicyFNiii) DSANSEC3DSARSAMD5RSASHA1 NSEC3RSASHA1 RSASHA256 RSASHA512ECCGOSTECDSAP256SHA256ECDSAP384SHA384ED25519ED448cCs||_||_||_dS)N)name algorithmparent)r!r\r]r^r#r#r$rFszPolicy.__init__cCsFd|jr dp"|jrdp"|jr dp"d|jp*d|jr8|jjp:d|jrRdt|jdpTd|jp\d|jrlt|jpnd|j r~t|j pd|j rt|j pd|j rt|j pd|j rt|j pd|j rt|j pd|jrt|jpd|jrt|jpd|jrt|jpd|jrt|jpd|jr(t|jp*d|jr>t|jp@dfS) Na%spolicy %s: inherits %s directory %s algorithm %s coverage %s ksk_keysize %s zsk_keysize %s ksk_rollperiod %s zsk_rollperiod %s ksk_prepublish %s ksk_postpublish %s zsk_prepublish %s zsk_postpublish %s ksk_standby %s zsk_standby %s keyttl %s z constructed zzone z algorithm ZUNKNOWNNone")is_constructedis_zoneis_algr\r^ directoryr@r]coverage ksk_keysize zsk_keysizeksk_rollperiodzsk_rollperiodksk_prepublishksk_postpublishzsk_prepublishzsk_postpublish ksk_standby zsk_standbykeyttl)r!r#r#r$__repr__s(   zPolicy.__repr__cCs |d|ko|dkSS)Nrr'r#)r!Zkey_sizeZ size_ranger#r#r$Z __verify_sizeszPolicy.__verify_sizecCs|jS)N)r\)r!r#r#r$get_nameszPolicy.get_namecCs|jS)N)rb)r!r#r#r$ constructedszPolicy.constructedcCs$|jr:|jdk r:|j|jkr:t|jdd|j|jffS|jrj|jdk rj|j|jkrjdd|j|jffS|jr|jdk r|j|jkrdd|j|jffS|jr|jdk r|j|jkrdd|j|jffS|jo|jo|jo|j|j|jkrdd|j|j|jffS|jrL|jrL|jrL|j|j|jkrLdd|j|j|jffS|jdk r |jj |j}|dk r|j |j |sdd |j |ffS|j |j |sdd |j |ffS|jdkr|j ddkrdd|j fS|jdkr|j ddkrdd|j fS|jd kr d|_ d|_ d!S)"zr Check if the values in the policy make sense :return: True/False if the policy passes validation NFz6KSK pre-publish period (%d) exceeds rollover period %dz7KSK post-publish period (%d) exceeds rollover period %dz6ZSK pre-publish period (%d) exceeds rollover period %dz7ZSK post-publish period (%d) exceeds rollover period %dz%KSK pre/post-publish periods (%d/%d) z"combined exceed rollover period %dz%ZSK pre/post-publish periods (%d/%d) z&KSK key size %d outside valid range %sz&ZSK key size %d outside valid range %srPrQ@rz$KSK key size %d not divisible by 64 zas required for DSAz$ZSK key size %d not divisible by 64 rWrXrYrZr[Tr_zGKSK pre/post-publish periods (%d/%d) combined exceed rollover period %dzGZSK pre/post-publish periods (%d/%d) combined exceed rollover period %d)rPrQz7KSK key size %d not divisible by 64 as required for DSA)rPrQz7ZSK key size %d not divisible by 64 as required for DSA)rWrXrYrZr[)Tr_) rirkr8rlrjrmrnr]valid_key_sz_per_algor1_Policy__verify_sizergrh)r!Z key_sz_ranger#r#r$validates                  zPolicy.validate)NNN)rKrLrMrcrdrbrirjrkrmrlrnrgrhrorprqrfrervrFrrrwrsrtrxr#r#r#r$rOvsD &rOc@s eZdZdS)PolicyExceptionN)rKrLrMr#r#r#r$ry)sryc@s.eZdZiZiZiZdZdZdZdEddZ ddZ ddZ d d Z d d Z d dZddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Z d3d4Z!d5d6Z"d7d8Z#d9d:Z$d;d<Z%d=d>Z&d?d@Z'dAdBZ(dCdDZ)dS)F dnssec_policyNTcKst|_|jj|_d|kr"d|d<d|kr2d|d<tjfd|i||_|jdt}d|_d|_d|_ d|_ t ||j d<d|j d_d|j d_ d |j d_ t ||j d <d |j d _d |j d _ d |j d _ t ||j d <d |j d _d |j d _ t ||j d <d |j d _d |j d _ t ||j d <d |j d _d |j d _ t ||j d<d|j d_d|j d_ t ||j d<d|j d_d|j d_ t ||j d<d|j d_d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ |r|j|dS)NdebugF write_tablesmoduleapolicy global { algorithm rsasha256; key-size ksk 2048; key-size zsk 2048; roll-period ksk 0; roll-period zsk 1y; pre-publish ksk 1mo; pre-publish zsk 1mo; post-publish ksk 1mo; post-publish zsk 1mo; standby ksk 0; standby zsk 0; keyttl 1h; coverage 6mo; }; policy default { policy global; };TirPirQrRrSrTrUrVrWrXrYrZr[)rplexrNyaccparsersetuprOr]rdrgrhr alg_policyr\load)r!filenamerDpr#r#r$rF4s|                                    zdnssec_policy.__init__c CsH||_d|_t|$}|j}d|jj_|jj|WdQRXd|_dS)NTr) rinitialopenreadr~rrrparse)r!rfrIr#r#r$rs  zdnssec_policy.loadcCs d|_d|jj_|jj|dS)NTr)rr~rrrr)r!rIr#r#r$rs zdnssec_policy.setupc Ks`|j}d}||jkr |j|}|dkrBt|jd}||_d|_|jdkr|jpZ|jd}x|rr|j rr|j}q^W|r~|jpd|_|j|jkr|j|j}nt d|j dkr|jp|jd}x|dk r|j r|j}qW|o|j |_ |j dkr:|jp|jd}x|r"|j r"|j}qW|r2|j p6|j |_ |j dkr|jpV|jd}x|jrv|j rv|j}qZW|r|j p|j |_ |j dkr|jp|jd}x|jr|j r|j}qW|r|j p|j |_ |jdkr6|jp|jd}x|jr|j r|j}qW|r.|jp2|j|_|jdkr|jpR|jd}x|jrr|j rr|j}qVW|r|jp|j|_|jdkr|jp|jd}x|jr|j r|j}qW|r|jp|j|_|jdkr2|jp|jd}x|jr|j r|j}qW|r*|jp.|j|_|jdkr|jpN|jd}x|jrn|j rn|j}qRW|r~|jp|j|_|jdkr|jp|jd}x|jr|j r|j}qW|r|jp|j|_|jdkr(|jp|jd}x |dk r|j r|j}qW|o$|j|_d|ks>|d r\|j\}}|s\t |dS|S)NdefaultTzalgorithm not foundZ novalidate)r+ zone_policyr named_policyr\rbr]r^rryrerfrgrhrirjrkrmrlrnrqrx) r!ZzonerDzrr^ZapZvalidmsgr#r#r$policys                             zdnssec_policy.policycCsdS)zBpolicylist : init policy | policylist policyNr#)r!rr#r#r$ p_policylist szdnssec_policy.p_policylistcCs d|_dS)zinit :FN)r)r!rr#r#r$p_initszdnssec_policy.p_initcCsdS)zTpolicy : alg_policy | zone_policy | named_policyNr#)r!rr#r#r$p_policyszdnssec_policy.p_policycCs|d|d<dS)zAname : STR | KEYTYPE | DATESUFFIXr'rNr#)r!rr#r#r$p_names zdnssec_policy.p_namecCs,|dj|d<tjd|ds(tddS)zcdomain : STR | QSTRING | KEYTYPE | DATESUFFIXr'rz^[\w.-][\w.-]*$zinvalid domainN)stripr(r)ry)r!rr#r#r$p_domain szdnssec_policy.p_domaincCs t|_dS)z new_policy :N)rOcurrent)r!rr#r#r$ p_new_policy*szdnssec_policy.p_new_policycCs(|d|j_d|j_|j|j|d<dS)zFalg_policy : ALGORITHM_POLICY ALGNAME new_policy alg_option_group SEMITN)rr\rdr)r!rr#r#r$ p_alg_policy.s zdnssec_policy.p_alg_policycCs8|djd|j_d|j_|j|j|djdj<dS)z=zone_policy : ZONE domain new_policy policy_option_group SEMIr.TN)rstriprr\rcrr+)r!rr#r#r$ p_zone_policy5szdnssec_policy.p_zone_policycCs$|d|j_|j|j|dj<dS)z>named_policy : POLICY name new_policy policy_option_group SEMIrN)rr\rr+)r!rr#r#r$p_named_policy<s zdnssec_policy.p_named_policycCs|d|d<dS)zduration : NUMBERr'rNr#)r!rr#r#r$ p_duration_1Bs zdnssec_policy.p_duration_1cCs d|d<dS)zduration : NONENrr#)r!rr#r#r$ p_duration_2Gszdnssec_policy.p_duration_2cCs|ddkr|dd|d<n|ddkr<|dd|d<n|ddkrZ|dd |d<n||dd krx|dd |d<n^|dd kr|dd |d<n@|ddkr|dd|d<n"|ddkr|d|d<ntddS)zduration : NUMBER DATESUFFIXryr'i3rmoi'wi: diQhiZmi<szinvalid durationN)ry)r!rr#r#r$ p_duration_3Ls       zdnssec_policy.p_duration_3cCsdS)z6policy_option_group : LBRACE policy_option_list RBRACENr#)r!rr#r#r$p_policy_option_group_sz#dnssec_policy.p_policy_option_groupcCsdS)zmpolicy_option_list : policy_option SEMI | policy_option_list policy_option SEMINr#)r!rr#r#r$p_policy_option_listcsz"dnssec_policy.p_policy_option_listcCsdS)apolicy_option : parent_option | directory_option | coverage_option | rollperiod_option | prepublish_option | postpublish_option | keysize_option | algorithm_option | keyttl_option | standby_optionNr#)r!rr#r#r$p_policy_optionhs zdnssec_policy.p_policy_optioncCsdS)z0alg_option_group : LBRACE alg_option_list RBRACENr#)r!rr#r#r$p_alg_option_groupusz dnssec_policy.p_alg_option_groupcCsdS)z^alg_option_list : alg_option SEMI | alg_option_list alg_option SEMINr#)r!rr#r#r$p_alg_option_listyszdnssec_policy.p_alg_option_listcCsdS)aalg_option : coverage_option | rollperiod_option | prepublish_option | postpublish_option | keyttl_option | keysize_option | standby_optionNr#)r!rr#r#r$ p_alg_option~szdnssec_policy.p_alg_optioncCs|j|dj|j_dS)zparent_option : POLICY namerN)rr+rr^)r!rr#r#r$p_parent_optionszdnssec_policy.p_parent_optioncCs|d|j_dS)z$directory_option : DIRECTORY QSTRINGrN)rre)r!rr#r#r$p_directory_optionsz dnssec_policy.p_directory_optioncCs|d|j_dS)z#coverage_option : COVERAGE durationrN)rrf)r!rr#r#r$p_coverage_optionszdnssec_policy.p_coverage_optioncCs*|ddkr|d|j_n |d|j_dS)z0rollperiod_option : ROLL_PERIOD KEYTYPE durationrKSKN)rrirj)r!rr#r#r$p_rollperiod_options z!dnssec_policy.p_rollperiod_optioncCs*|ddkr|d|j_n |d|j_dS)z0prepublish_option : PRE_PUBLISH KEYTYPE durationrrrN)rrkrm)r!rr#r#r$p_prepublish_options z!dnssec_policy.p_prepublish_optioncCs*|ddkr|d|j_n |d|j_dS)z2postpublish_option : POST_PUBLISH KEYTYPE durationrrrN)rrlrn)r!rr#r#r$p_postpublish_options z"dnssec_policy.p_postpublish_optioncCs*|ddkr|d|j_n |d|j_dS)z(keysize_option : KEY_SIZE KEYTYPE NUMBERrrrN)rrgrh)r!rr#r#r$p_keysize_options zdnssec_policy.p_keysize_optioncCs*|ddkr|d|j_n |d|j_dS)z'standby_option : STANDBY KEYTYPE NUMBERrrrN)rrorp)r!rr#r#r$p_standby_options zdnssec_policy.p_standby_optioncCs|d|j_dS)zkeyttl_option : KEYTTL durationrN)rrq)r!rr#r#r$p_keyttl_optionszdnssec_policy.p_keyttl_optioncCs|d|j_dS)z$algorithm_option : ALGORITHM ALGNAMErN)rr])r!rr#r#r$p_algorithm_optionsz dnssec_policy.p_algorithm_optioncCsd|r.td|jpd|jrdnd|j|jfn2|js`td|jp@d|jrJdnd|rV|jpXdfdS)Nz%s%s%d:syntax error near '%s'r_:z%s%s%d:unexpected end of inputr)r8rrrrry)r!rr#r#r$p_errorszdnssec_policy.p_error)N)*rKrLrMrrrrrrrFrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr#r#r#r$rz,sN _ h   rz__main__r'rCr)r{rT)r|r{rznonexistent.zone)r(Zply.lexrCZply.yaccrstringrrrO ExceptionryrzrKsysargvrfilerrIcloser~rJZppr8rreargsr#r#r#r$ s6   `4!   PK{ 1]LL!__pycache__/policy.cpython-36.pycnu[3 ~j2g@s:ddlZddljZddljZddlTddlmZGdddZGdddZGdd d e Z Gd d d Z e d kr6ddl Z e jd dkree jdZejZejed dZejenxe jd dkr6y4e e jddddZeejdeejdWn2e k r4ZzeejdWYddZ[XnXdS)N)*)copyc @seZdZd3Zed4ZiZdZdZdZdZ dZ ddZ ddZ d d!Z d"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2S)5 PolicyLexPOLICYALGORITHM_POLICYZONE ALGORITHM DIRECTORYKEYTTLKEY_SIZE ROLL_PERIOD PRE_PUBLISH POST_PUBLISHCOVERAGESTANDBYNONE DATESUFFIXKEYTYPEALGNAMESTRQSTRINGNUMBERLBRACERBRACESEMIz z (//|\#).*z\{z\};cCs|jj|jjd7_dS)z\n+ N)lexerlinenovaluecount)selftr#/usr/lib/python3.6/policy.py t_newline7szPolicyLex.t_newlinecCs|jj|jjd7_dS)z/\*(.|\n)*?\*/rN)rrrr )r!r"r#r#r$ t_comment;szPolicyLex.t_commentcCstjd|jjdj|_|S)z(?i)(?<=[0-9 \t])(y(?:ears|ear|ea|e)?|mo(?:nths|nth|nt|n)?|w(?:eeks|eek|ee|e)?|d(?:ays|ay|a)?|h(?:ours|our|ou|o)?|mi(?:nutes|nute|nut|nu|n)?|s(?:econds|econd|econ|eco|ec|e)?)\bz(?i)(y|mo|w|d|h|mi|s)([a-z]*))rematchrgrouplower)r!r"r#r#r$ t_DATESUFFIX?szPolicyLex.t_DATESUFFIXcCs|jj|_|S)z(?i)\b(KSK|ZSK)\b)rupper)r!r"r#r#r$ t_KEYTYPEDs zPolicyLex.t_KEYTYPEcCs|jj|_|S)z(?i)\b(RSAMD5|DH|DSA|NSEC3DSA|ECC|RSASHA1|NSEC3RSASHA1|RSASHA256|RSASHA512|ECCGOST|ECDSAP256SHA256|ECDSAP384SHA384|ED25519|ED448)\b)rr-)r!r"r#r#r$ t_ALGNAMEIs zPolicyLex.t_ALGNAMEcCs|jj|jd|_|S)z[A-Za-z._-][\w._-]*r) reserved_mapgetrtype)r!r"r#r#r$t_STRNszPolicyLex.t_STRcCs&|jj|jd|_|jdd|_|S)z"([^"\n]|(\\"))*"rr')r0r1rr2)r!r"r#r#r$ t_QSTRINGSszPolicyLex.t_QSTRINGcCst|j|_|S)z\d+)intr)r!r"r#r#r$t_NUMBERYs zPolicyLex.t_NUMBERcCs"td|jd|jjddS)NzIllegal character '%s'rr')printrrskip)r!r"r#r#r$t_error^szPolicyLex.t_errorcKsbdttkrtjdd}n tdd}x"|jD]}||j|jj|<q,Wtjfd|i||_dS)N maketrans_-object) dirstrr;reservedr0r+ translatelexr)r!kwargsZtransrr#r#r$__init__bs    zPolicyLex.__init__cCs.|jj|x|jj}|sPt|qWdS)N)rinputtokenr8)r!textr"r#r#r$testks   zPolicyLex.testN) rrrrr r r r r rrrr) rrrrrrrrr)__name__ __module__ __qualname__rAtokensr0Zt_ignoreZt_ignore_olcommentZt_LBRACEZt_RBRACEZt_SEMIr%r&r,r.r/r3r5r7r:rFrJr#r#r#r$rsN rc @seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZddgddgddgddgddgddgddgdddddd ZdddZd d Zd d Zd dZddZddZdS)PolicyFNiii) DSANSEC3DSARSAMD5RSASHA1 NSEC3RSASHA1 RSASHA256 RSASHA512ECCGOSTECDSAP256SHA256ECDSAP384SHA384ED25519ED448cCs||_||_||_dS)N)name algorithmparent)r!r\r]r^r#r#r$rFszPolicy.__init__cCsFd|jr dp"|jrdp"|jr dp"d|jp*d|jr8|jjp:d|jrRdt|jdpTd|jp\d|jrlt|jpnd|j r~t|j pd|j rt|j pd|j rt|j pd|j rt|j pd|j rt|j pd|jrt|jpd|jrt|jpd|jrt|jpd|jrt|jpd|jr(t|jp*d|jr>t|jp@dfS) Na%spolicy %s: inherits %s directory %s algorithm %s coverage %s ksk_keysize %s zsk_keysize %s ksk_rollperiod %s zsk_rollperiod %s ksk_prepublish %s ksk_postpublish %s zsk_prepublish %s zsk_postpublish %s ksk_standby %s zsk_standby %s keyttl %s z constructed zzone z algorithm ZUNKNOWNNone")is_constructedis_zoneis_algr\r^ directoryr@r]coverage ksk_keysize zsk_keysizeksk_rollperiodzsk_rollperiodksk_prepublishksk_postpublishzsk_prepublishzsk_postpublish ksk_standby zsk_standbykeyttl)r!r#r#r$__repr__s(   zPolicy.__repr__cCs |d|ko|dkSS)Nrr'r#)r!Zkey_sizeZ size_ranger#r#r$Z __verify_sizeszPolicy.__verify_sizecCs|jS)N)r\)r!r#r#r$get_nameszPolicy.get_namecCs|jS)N)rb)r!r#r#r$ constructedszPolicy.constructedcCs$|jr:|jdk r:|j|jkr:t|jdd|j|jffS|jrj|jdk rj|j|jkrjdd|j|jffS|jr|jdk r|j|jkrdd|j|jffS|jr|jdk r|j|jkrdd|j|jffS|jo|jo|jo|j|j|jkrdd|j|j|jffS|jrL|jrL|jrL|j|j|jkrLdd|j|j|jffS|jdk r |jj |j}|dk r|j |j |sdd |j |ffS|j |j |sdd |j |ffS|jdkr|j ddkrdd|j fS|jdkr|j ddkrdd|j fS|jd kr d|_ d|_ d!S)"zr Check if the values in the policy make sense :return: True/False if the policy passes validation NFz6KSK pre-publish period (%d) exceeds rollover period %dz7KSK post-publish period (%d) exceeds rollover period %dz6ZSK pre-publish period (%d) exceeds rollover period %dz7ZSK post-publish period (%d) exceeds rollover period %dz%KSK pre/post-publish periods (%d/%d) z"combined exceed rollover period %dz%ZSK pre/post-publish periods (%d/%d) z&KSK key size %d outside valid range %sz&ZSK key size %d outside valid range %srPrQ@rz$KSK key size %d not divisible by 64 zas required for DSAz$ZSK key size %d not divisible by 64 rWrXrYrZr[Tr_zGKSK pre/post-publish periods (%d/%d) combined exceed rollover period %dzGZSK pre/post-publish periods (%d/%d) combined exceed rollover period %d)rPrQz7KSK key size %d not divisible by 64 as required for DSA)rPrQz7ZSK key size %d not divisible by 64 as required for DSA)rWrXrYrZr[)Tr_) rirkr8rlrjrmrnr]valid_key_sz_per_algor1_Policy__verify_sizergrh)r!Z key_sz_ranger#r#r$validates                  zPolicy.validate)NNN)rKrLrMrcrdrbrirjrkrmrlrnrgrhrorprqrfrervrFrrrwrsrtrxr#r#r#r$rOvsD &rOc@s eZdZdS)PolicyExceptionN)rKrLrMr#r#r#r$ry)sryc@s.eZdZiZiZiZdZdZdZdEddZ ddZ ddZ d d Z d d Z d dZddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Z d3d4Z!d5d6Z"d7d8Z#d9d:Z$d;d<Z%d=d>Z&d?d@Z'dAdBZ(dCdDZ)dS)F dnssec_policyNTcKst|_|jj|_d|kr"d|d<d|kr2d|d<tjfd|i||_|jdt}d|_d|_d|_ d|_ t ||j d<d|j d_d|j d_ d |j d_ t ||j d <d |j d _d |j d _ d |j d _ t ||j d <d |j d _d |j d _ t ||j d <d |j d _d |j d _ t ||j d <d |j d _d |j d _ t ||j d<d|j d_d|j d_ t ||j d<d|j d_d|j d_ t ||j d<d|j d_d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ t ||j d<d|j d_d|j d_ d|j d_ d|j d_ |r|j|dS)NdebugF write_tablesmoduleapolicy global { algorithm rsasha256; key-size ksk 2048; key-size zsk 2048; roll-period ksk 0; roll-period zsk 1y; pre-publish ksk 1mo; pre-publish zsk 1mo; post-publish ksk 1mo; post-publish zsk 1mo; standby ksk 0; standby zsk 0; keyttl 1h; coverage 6mo; }; policy default { policy global; };TirPirQrRrSrTrUrVrWrXrYrZr[)rplexrNyaccparsersetuprOr]rdrgrhr alg_policyr\load)r!filenamerDpr#r#r$rF4s|                                    zdnssec_policy.__init__c CsH||_d|_t|$}|j}d|jj_|jj|WdQRXd|_dS)NTr) rinitialopenreadr~rrrparse)r!rfrIr#r#r$rs  zdnssec_policy.loadcCs d|_d|jj_|jj|dS)NTr)rr~rrrr)r!rIr#r#r$rs zdnssec_policy.setupc Ks`|j}d}||jkr |j|}|dkrBt|jd}||_d|_|jdkr|jpZ|jd}x|rr|j rr|j}q^W|r~|jpd|_|j|jkr|j|j}nt d|j dkr|jp|jd}x|dk r|j r|j}qW|o|j |_ |j dkr:|jp|jd}x|r"|j r"|j}qW|r2|j p6|j |_ |j dkr|jpV|jd}x|jrv|j rv|j}qZW|r|j p|j |_ |j dkr|jp|jd}x|jr|j r|j}qW|r|j p|j |_ |jdkr6|jp|jd}x|jr|j r|j}qW|r.|jp2|j|_|jdkr|jpR|jd}x|jrr|j rr|j}qVW|r|jp|j|_|jdkr|jp|jd}x|jr|j r|j}qW|r|jp|j|_|jdkr2|jp|jd}x|jr|j r|j}qW|r*|jp.|j|_|jdkr|jpN|jd}x|jrn|j rn|j}qRW|r~|jp|j|_|jdkr|jp|jd}x|jr|j r|j}qW|r|jp|j|_|jdkr(|jp|jd}x |dk r|j r|j}qW|o$|j|_d|ks>|d r\|j\}}|s\t |dS|S)NdefaultTzalgorithm not foundZ novalidate)r+ zone_policyr named_policyr\rbr]r^rryrerfrgrhrirjrkrmrlrnrqrx) r!ZzonerDzrr^ZapZvalidmsgr#r#r$policys                             zdnssec_policy.policycCsdS)zBpolicylist : init policy | policylist policyNr#)r!rr#r#r$ p_policylist szdnssec_policy.p_policylistcCs d|_dS)zinit :FN)r)r!rr#r#r$p_initszdnssec_policy.p_initcCsdS)zTpolicy : alg_policy | zone_policy | named_policyNr#)r!rr#r#r$p_policyszdnssec_policy.p_policycCs|d|d<dS)zAname : STR | KEYTYPE | DATESUFFIXr'rNr#)r!rr#r#r$p_names zdnssec_policy.p_namecCs,|dj|d<tjd|ds(tddS)zcdomain : STR | QSTRING | KEYTYPE | DATESUFFIXr'rz^[\w.-][\w.-]*$zinvalid domainN)stripr(r)ry)r!rr#r#r$p_domain szdnssec_policy.p_domaincCs t|_dS)z new_policy :N)rOcurrent)r!rr#r#r$ p_new_policy*szdnssec_policy.p_new_policycCs(|d|j_d|j_|j|j|d<dS)zFalg_policy : ALGORITHM_POLICY ALGNAME new_policy alg_option_group SEMITN)rr\rdr)r!rr#r#r$ p_alg_policy.s zdnssec_policy.p_alg_policycCs8|djd|j_d|j_|j|j|djdj<dS)z=zone_policy : ZONE domain new_policy policy_option_group SEMIr.TN)rstriprr\rcrr+)r!rr#r#r$ p_zone_policy5szdnssec_policy.p_zone_policycCs$|d|j_|j|j|dj<dS)z>named_policy : POLICY name new_policy policy_option_group SEMIrN)rr\rr+)r!rr#r#r$p_named_policy<s zdnssec_policy.p_named_policycCs|d|d<dS)zduration : NUMBERr'rNr#)r!rr#r#r$ p_duration_1Bs zdnssec_policy.p_duration_1cCs d|d<dS)zduration : NONENrr#)r!rr#r#r$ p_duration_2Gszdnssec_policy.p_duration_2cCs|ddkr|dd|d<n|ddkr<|dd|d<n|ddkrZ|dd |d<n||dd krx|dd |d<n^|dd kr|dd |d<n@|ddkr|dd|d<n"|ddkr|d|d<ntddS)zduration : NUMBER DATESUFFIXryr'i3rmoi'wi: diQhiZmi<szinvalid durationN)ry)r!rr#r#r$ p_duration_3Ls       zdnssec_policy.p_duration_3cCsdS)z6policy_option_group : LBRACE policy_option_list RBRACENr#)r!rr#r#r$p_policy_option_group_sz#dnssec_policy.p_policy_option_groupcCsdS)zmpolicy_option_list : policy_option SEMI | policy_option_list policy_option SEMINr#)r!rr#r#r$p_policy_option_listcsz"dnssec_policy.p_policy_option_listcCsdS)apolicy_option : parent_option | directory_option | coverage_option | rollperiod_option | prepublish_option | postpublish_option | keysize_option | algorithm_option | keyttl_option | standby_optionNr#)r!rr#r#r$p_policy_optionhs zdnssec_policy.p_policy_optioncCsdS)z0alg_option_group : LBRACE alg_option_list RBRACENr#)r!rr#r#r$p_alg_option_groupusz dnssec_policy.p_alg_option_groupcCsdS)z^alg_option_list : alg_option SEMI | alg_option_list alg_option SEMINr#)r!rr#r#r$p_alg_option_listyszdnssec_policy.p_alg_option_listcCsdS)aalg_option : coverage_option | rollperiod_option | prepublish_option | postpublish_option | keyttl_option | keysize_option | standby_optionNr#)r!rr#r#r$ p_alg_option~szdnssec_policy.p_alg_optioncCs|j|dj|j_dS)zparent_option : POLICY namerN)rr+rr^)r!rr#r#r$p_parent_optionszdnssec_policy.p_parent_optioncCs|d|j_dS)z$directory_option : DIRECTORY QSTRINGrN)rre)r!rr#r#r$p_directory_optionsz dnssec_policy.p_directory_optioncCs|d|j_dS)z#coverage_option : COVERAGE durationrN)rrf)r!rr#r#r$p_coverage_optionszdnssec_policy.p_coverage_optioncCs*|ddkr|d|j_n |d|j_dS)z0rollperiod_option : ROLL_PERIOD KEYTYPE durationrKSKN)rrirj)r!rr#r#r$p_rollperiod_options z!dnssec_policy.p_rollperiod_optioncCs*|ddkr|d|j_n |d|j_dS)z0prepublish_option : PRE_PUBLISH KEYTYPE durationrrrN)rrkrm)r!rr#r#r$p_prepublish_options z!dnssec_policy.p_prepublish_optioncCs*|ddkr|d|j_n |d|j_dS)z2postpublish_option : POST_PUBLISH KEYTYPE durationrrrN)rrlrn)r!rr#r#r$p_postpublish_options z"dnssec_policy.p_postpublish_optioncCs*|ddkr|d|j_n |d|j_dS)z(keysize_option : KEY_SIZE KEYTYPE NUMBERrrrN)rrgrh)r!rr#r#r$p_keysize_options zdnssec_policy.p_keysize_optioncCs*|ddkr|d|j_n |d|j_dS)z'standby_option : STANDBY KEYTYPE NUMBERrrrN)rrorp)r!rr#r#r$p_standby_options zdnssec_policy.p_standby_optioncCs|d|j_dS)zkeyttl_option : KEYTTL durationrN)rrq)r!rr#r#r$p_keyttl_optionszdnssec_policy.p_keyttl_optioncCs|d|j_dS)z$algorithm_option : ALGORITHM ALGNAMErN)rr])r!rr#r#r$p_algorithm_optionsz dnssec_policy.p_algorithm_optioncCsd|r.td|jpd|jrdnd|j|jfn2|js`td|jp@d|jrJdnd|rV|jpXdfdS)Nz%s%s%d:syntax error near '%s'r_:z%s%s%d:unexpected end of inputr)r8rrrrry)r!rr#r#r$p_errorszdnssec_policy.p_error)N)*rKrLrMrrrrrrrFrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr#r#r#r$rz,sN _ h   rz__main__r'rCr)r{rT)r|r{rznonexistent.zone)r(Zply.lexrCZply.yaccrstringrrrO ExceptionryrzrKsysargvrfilerrIcloser~rJZppr8rreargsr#r#r#r$ s6   `4!   PK{ 1]T^X5X5'__pycache__/dnskey.cpython-36.opt-1.pycnu[3 ~j @@sJddlZddlZddlZddlmZmZGdddeZGdddZdS)N)PopenPIPEcseZdZfddZZS)TimePastcstt|jd|||fdS)Nz'%s time for key %s (%d) is already past)superr__init__)selfkeypropvalue) __class__/usr/lib/python3.6/dnskey.pyrs zTimePast.__init__)__name__ __module__ __qualname__r __classcell__r r )r r rsrc@seZdZdZdqZdrZdsZdtd!d"Zd#d$Zd%d&Z e dud'd(Z d)d*Z e d+d,Ze d-d.Zdvd/d0Ze d1d2Ze d3d4Ze d5d6Ze d7d8Zd9d:Zd;d<Zd=d>Zd?d@ZdAdBZdCdDZejfdEdFZdGdHZejfdIdJZdKdLZejfdMdNZ dOdPZ!ejfdQdRZ"dSdTZ#ejfdUdVZ$dWdXZ%ejfdYdZZ&d[d\Z'ejfd]d^Z(d_d`Z)dadbZ*dcddZ+dedfZ,dgdhZ-didjZ.dwdkdlZ/dxdmdnZ0e dodpZ1d S)ydnskeyztAn individual DNSSEC key. Identified by path, name, algorithm, keyid. Contains a dictionary of metadata events.CreatedPublishActivateInactiveDeleteRevoke DSPublish SyncPublish SyncDeleteN-P-A-I-D-R-Psync-DsyncRSAMD5DHDSAECCRSASHA1NSEC3DSA NSEC3RSASHA1 RSASHA256 RSASHA512ECCGOSTECDSAP256SHA256ECDSAP384SHA384ED25519ED448cCst|tr:t|dkr:|pd|_|\}}}|j|||||pLtjj|pLd|_tjj|}|j d\}}}|dd}t |}t |j dd}|j||||dS)N.+r) isinstancetuplelen_dir fromtupleospathdirnamebasenamesplitint)rrZ directorykeyttlnamealgkeyidr r r r&s    zdnskey.__init__cs|jdr|}|jd}n|d}d|||f}|j|jr@tjpBd|d}|j|jr^tjp`d|d}||_||_t||_t||_ ||_ t |d} x| D]zddkrqj } | sq| d j dkrd } ||_nd} |st| d n||_t| | d @d krd|_qd|_qW| jt |d} t|_t|_t|_t|_t|_t|_t|_d|_x| D]j svddkrqvfdddDtg} tdd| D}d|j}|djdj}||j|<qvWxtjD]}d|j|<||jkrn|j|j|}||j|<|j ||j|<|j!||j|<|j||j|<n(d|j|<d|j|<d|j|<d|j|<qW| jdS)Nr2z K%s+%03d+%05dz.keyz.privaterr;r4inchhsr1TFZrUz!#csg|]}j|qSr )find).0c)liner r lsz$dnskey.fromtuple..z:= cSsg|]}|dkr|qS)r4r5r )rMposr r r rPms)rHrIrJ)"endswithrstripr9r;sepkeystrrBr@rCrDfullnameopenr?lowerttlclosedictZmetadata_changed_delete_times_fmttime _timestamps _original_origttlstripr8minlstripr_PROPS parsetime formattime epochfromtime)rrBrCrDrArVrUZkey_fileZ private_fileZkfptokensZseptokenZpfpZ punctuationfoundr r tr )rOr r:5sv                 zdnskey.fromtuplecKsr|jdd}g}d}|jdk r0|dt|jg7}xlttjtjD]Z\}}| s@|j| r\q@d}||j krx|j |rxd}|rdn|j |} ||| g7}d}q@W|rn|d|j g||j g} |st ddj| y0t| ttd } | j\} } | rtt| Wn8tk r:}ztd |t|fWYdd}~XnXd|_x*tjD] }|j||j|<d|j|<qJWdS) NquietFTz-LZnonez-Kz#  )stdoutstderrzunable to run %s: %s)getrbstrrYziprrf_OPTSr\r]r_r9rUprintjoinrr communicate Exceptionr`ra)rZ settime_binkwargsrmcmdfirstr optdeleteZwhenZfullcmdprorper r r commits<    " z dnskey.commitc KsL| jdd} |dd|dt|g} |r0| d|g7} |r>| jd|rN| d|g7} |rb| d t|g7} | rtj| }| d tj|g7} | rtj| }| d tj| g7} | j|| std d j| t| t t d}|j \}}|rt dt|y"|j dj d}t|||}|St k rF}zt dt|WYdd}~XnXdS)NrmFz-qz-Kz-Lz-rz-fkz-az-bz-Pz-Az# rn)rorpzunable to generate key: rasciiz!unable to parse generated key: %s)rqrrappendr timefromepochrhrurvrrrwrx splitlinesdecode)cls keygen_bin randomdevZkeys_dirrBrCZkeysizerTrYpublishactivateryrm keygen_cmdrlr~rorprUnewkeyrr r r generates:         zdnskey.generatec Ks|jdd}|js td||dd|jd|jg}|jrL|dt|jg7}|r\|d|g7}|rp|d t|g7}|std d j|t |t t d }|j \}} | rtd | y&|j dj d} t| |j|j} | Std|YnXdS)NrmFz'predecessor key %s has no inactive datez-qz-Kz-Sz-Lz-rz-iz# rn)rorpzunable to generate key: rrz'unable to generate successor for key %s)rqinactiverxr9rUrYrrrurvrrrwrrr) rrrZ prepublishryrmrr~rorprUrr r r generate_successors,     zdnskey.generate_successorcCs0d}|tttjkr tj|}|r(|Sd|S)Nz%03d)ranger8r _ALGNAMES)rCrBr r r algstrs z dnskey.algstrc Cs6|sdS|j}y tjj|Stk r0dSXdS)N)upperrrindex ValueError)rCr r r algnums z dnskey.algnumcCs|j|p |jS)N)rrC)rrCr r r algnameszdnskey.algnamecCs tj|S)N)timeZgmtime)secsr r r rszdnskey.timefromepochcCs tj|dS)Nz %Y%m%d%H%M%S)rZstrptime)stringr r r rg szdnskey.parsetimecCs tj|S)N)calendarZtimegm)rlr r r riszdnskey.epochfromtimecCs tjd|S)Nz %Y%m%d%H%M%S)rZstrftime)rlr r r rhszdnskey.formattimecKs|jdd}|j||krdS|j|dk rR|j||krR| rRt|||j||dkr|j|dkrldnd|j|<d|j|<d|j|<d|j|<d|j|<dS|j|}||j|<||j|<|j ||j|<|j||j|krdnd|j|<dS)NforceFT) rqr`rarr\r]r^r_rrh)rr rnowryrrlr r r setmetas$        zdnskey.setmetacCs |j|S)N)r^)rr r r r gettime2szdnskey.gettimecCs |j|S)N)r_)rr r r r getfmttime5szdnskey.getfmttimecCs |j|S)N)r`)rr r r r gettimestamp8szdnskey.gettimestampcCs |jdS)Nr)r`)rr r r created;szdnskey.createdcCs |jdS)Nr)r`)rr r r syncpublish>szdnskey.syncpublishcKs|jd||f|dS)Nr)r)rrrryr r r setsyncpublishAszdnskey.setsyncpublishcCs |jdS)Nr)r`)rr r r rDszdnskey.publishcKs|jd||f|dS)Nr)r)rrrryr r r setpublishGszdnskey.setpublishcCs |jdS)Nr)r`)rr r r rJszdnskey.activatecKs|jd||f|dS)Nr)r)rrrryr r r setactivateMszdnskey.setactivatecCs |jdS)Nr)r`)rr r r revokePsz dnskey.revokecKs|jd||f|dS)Nr)r)rrrryr r r setrevokeSszdnskey.setrevokecCs |jdS)Nr)r`)rr r r rVszdnskey.inactivecKs|jd||f|dS)Nr)r)rrrryr r r setinactiveYszdnskey.setinactivecCs |jdS)Nr)r`)rr r r r}\sz dnskey.deletecKs|jd||f|dS)Nr)r)rrrryr r r setdelete_szdnskey.setdeletecCs |jdS)Nr)r`)rr r r syncdeletebszdnskey.syncdeletecKs|jd||f|dS)Nr)r)rrrryr r r setsyncdeleteeszdnskey.setsyncdeletecCsR|dks|j|krdS|jdkr0|j|_||_n|j|krHd|_||_n||_dS)N)rYrb)rrYr r r setttlhs  z dnskey.setttlcCs|jr dSdS)NKSKZSK)rT)rr r r keytypetszdnskey.keytypecCsd|j|j|jfS)Nz %s/%s/%05d)rBrrD)rr r r __str__wszdnskey.__str__cCs"d|j|j|j|jrdndfS)Nz%s/%s/%05d (%s)rr)rBrrDrT)rr r r __repr__{szdnskey.__repr__cCs|jp|jp|jS)N)rrr)rr r r datesz dnskey.datecCs@|j|jkr|j|jkS|j|jkr0|j|jkS|j|jkS)N)rBrCr)rotherr r r __lt__s     z dnskey.__lt__cCsdd}|s|}ttj}|j}|j}|s4dS|sT||krP|dt|dS||krh||krhdS||kr|dt|tj|jpdfdS||kr|dt|dS|jdk r|||jkr|d t|tj|jpdfdSdS) Nc_sdS)Nr )argsryr r r noopsz!dnskey.check_prepub..noopFzFWARNING: Key %s is scheduled for activation but not for publication.TzWARNING: %s is scheduled to be published and activated at the same time. This could result in a coverage gap if the zone was previously signed. Activation should be at least %s after publication.zone DNSKEY TTLz0WARNING: Key %s is active before it is publishedzWARNING: Key %s is activated too soon after publication; this could result in coverage gaps due to resolver caches containing old data. Activation should be at least %s after publication.)r@rrrreprrdurationrY)routputrrar~r r r check_prepubs<   zdnskey.check_prepubcCsdd}|dkr|}|dkr"|j}|dkr>|dt|d }tj}|j}|j}|s^dS|s~||krz|dt|dS||kr||krdS||kr|d t|dS|||kr|d t|tj|fdSdS) Nc_sdS)Nr )rryr r r rsz"dnskey.check_postpub..noopz"WARNING: Key %s using default TTL.<FzEWARNING: Key %s is scheduled for deletion but not for inactivation.Tz@WARNING: Key %s is scheduled for deletion before inactivation.zWARNING: Key %s scheduled for deletion too soon after deactivation; this may result in coverage gaps due to resolver caches containing old data. Deletion should be at least %s after inactivation.iiQ)rYrrr}rrr)rrZtimespanrrdir r r check_postpubs:   zdnskey.check_postpubcCsz|sdSddddddg}g}xR|D]J}||d ||d }}|d kr"|jd ||d |d krbdndfq"Wdj|S) Nyearrrimmonthdayhourminutesecondr4rz%d %s%ssrEz, iiQ3)rriiQ')rriQ)rr)rr)rr)rr4)rrv)rZunitsrZunitvr r r rs (zdnskey.duration) rrrrrrrrr) Nrrrrr Nr!r")Nr#r$r%r&r'r(r)r*Nr+Nr,r-r.r/r0)NN)NN)N)N)NN)2rrr__doc__rfrtrrr:r classmethodrr staticmethodrrrrrgrirhrrrrrrrrrrrrrrrrr}rrrrrrrrrrrrr r r r rsb M% *        1 -r) r;rr subprocessrrrxrrr r r r  s PK{ 1]u*e(__pycache__/checkds.cpython-36.opt-1.pycnu[3 ~j&@shddlZddlZddlZddlmZmZddlmZmZdZ GdddZ d ddZ d d Z d d Z dS)N)PopenPIPE)prefixversionzdnssec-checkdsc@sPeZdZdddddZdZdZdZdZdZdZ d Z dd d Z d d Z ddZ dS)SECRRzSHA-1zSHA-256ZGOSTzSHA-384)INNrcCs|stt|tk r$|jdj}n|j}t|dkrWt | dkrt ddSd} xv| D]n} | |krt d| j| jjd| j| jt j| jfd} n,t d| j| jjd| j| jt j| jfqW| s"t d|rdnd| S)Nz+noallz+answerz-tr,Zdsz-qr)stdoutr cSs|j|j|jfS)N)r'r(r))rrr-r-r.mszcheck..)keyz-fz-lZdnskey-)stdinr7rz$No DNSKEY records found in zone apexFz,%s for KSK %s/%03d/%05d (%s) found in parentTz0%s for KSK %s/%03d/%05d (%s) missing from parentz'No %s records were found for any DNSKEYrr)digrrZ communicate splitlinesrrrappendrsorted dsfromkeyrprintrr!rr(r'r6r)) zoneargs masterfile lookasideZrrlistcmdfp_lineZklistZintodsfoundr8r-r-r.checkcsV           rLcCstjtdd}d}tjdkr"dnd}|jdtdd|jd d d td d |jdddtdd |jdddtjjt |dtdd|jdddtjjt |dtdd|jdddt d|j }|j j d |_ |jr|jj d |_|S)!Nz: checks DS coverage) descriptionbinntZsbinrCz zone to check)rhelpz-fz--filerEzzone master file)destrrPz-lz --lookasiderFzDLV lookaside zonez-dz--digr=z path to 'dig')rQdefaultrrPz-Dz --dsfromkeyrAzdnssec-dsfromkeyzpath to 'dnssec-dsfromkey'z-vz --versionr)actionrr)argparseArgumentParserprogosname add_argumentrpathrrr parse_argsrCrrF)parserZbindirZsbindirrDr-r-r.r[s,        r[cCs.t}t|j||j|j}t|r$dnddS)Nrr)r[rLrCrErFexit)rDrKr-r-r.mainsr^)NN)rTrWsys subprocessrrZ isc.utilsrrrVrrLr[r^r-r-r-r. sI ; PK{ 1]~)__pycache__/__init__.cpython-36.opt-1.pycnu[3 ~j @sjdddddddddd d d d g Zd dlTd dlTd dlTd dlTd dlTd dlTd dlTd dlTd dl TdS)ZcheckdsZcoverageZkeymgrZdnskeyZ eventlistZkeydictZkeyeventZ keyseriesZkeyzoneZpolicyZparsetabZrndcZutils)*N) __all__Z isc.dnskeyZ isc.eventlistZ isc.keydictZ isc.keyeventZ isc.keyseriesZ isc.keyzoneZ isc.policyZisc.rndcZ isc.utilsrr/usr/lib/python3.6/__init__.py s   PK{ 1]6_uu'__pycache__/keymgr.cpython-36.opt-1.pycnu[3 ~jk@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z dZ ddl mZmZmZmZmZmZddZddd Zd d Zd d ZdS))print_functionN) defaultdictz dnssec-keymgr)dnskeykeydict keyseriespolicyparsetabutilscOst||tjddS)N)printsysexit)argskwargsr/usr/lib/python3.6/keymgr.pyfatals rcCs|}| s(tjj| s(tj|tj rtjd}|s>tjj}xB|jtjD]2}|tj |}tjj|rztj|tjrzPd}qLW|S)a2 find the location of a specified command. If a default is supplied, exists and it's an executable, we use it; otherwise we search PATH for an alternative. :param command: command to look for :param default: default value to use :return: PATH with the location of a suitable binary PATHN) ospathisfileaccessX_OKenvirondefpathsplitpathsepsep)ZcommanddefaultZfpathrZ directoryrrrset_paths$ rcCstdtjjtjdd}tdtjjtjdd}tjtdd}|j dt ddd;d |j d d t ddd|j ddt ddd|j dd|t dd d|j ddt ddd d|j dd|t dd d|j d d!d"d#d$d%|j d&d'd"d#d(d%|j d)d*d+d"d#d s @   GPK{ 1]@9 "__pycache__/keydict.cpython-36.pycnu[3 ~j! @s:ddlmZddlmZddlZddlZGdddZdS)) defaultdict)dnskeyNc@sneZdZdZeddZdZgZdddZddZ d d Z d d Z d dZ ddZ ddZddZddZdS)keydictz> A dictionary of keys, indexed by name, algorithm, and key id cCsttS)N)rdictrr/usr/lib/python3.6/keydict.pyszkeydict.NcKs|jdd|_|jdd}|s:|jddp,d}|j|nXxV|D]N}d|krb|ddk rb|d}n|rr|j|jptd}|j||s@|jj|q@WdS)NZkeyttlzonespath.)get_defttlreadallZpolicyZ directoryreadone_missingappend)selfZdpkwargsr r zonerrr__init__s     zkeydict.__init__cCsLtjtjj|d}x2|D]*}t|||j}||j|j|j|j <qWdS)Nz *.private) globosr joinrr_keydictnamealgkeyid)rr filesinfilekeyrrrr,s zkeydict.readallc Cs|jds|d7}d|d}tjtjj||}d}xR|D]J}t|||j}|j|krZq<|dkrh|jnd}||j ||j |j <d}q s  PK{ 1]%*__pycache__/keyseries.cpython-36.opt-1.pycnu[3 ~j"@sFddlmZddlTddlTddlTddlTddlZGdddZdS)) defaultdict)*Nc@sleZdZeddZeddZeZdZdZ e j dfddZ ddZ d d Z d d Ze j fd dZdS) keyseriescCsttS)N)rlistrr/usr/lib/python3.6/keyseries.pyszkeyseries.cCsttS)N)rrrrrrr sNcCs||_||_t|j|_x|jD]}|jj|x||jD]\}}xh|jD]\}|j r|j op|j |ks|j ||j |qT|j o|j |ksT|j ||j |qTW|j ||j|j ||jqBWq$WdS)N)_kdict_contextsetZmissing_zoneszonesadditemsvaluessepdelete_Kappend_Zsort)selfZkdictnowcontextzonealgkeyskrrr__init__s zkeyseries.__init__ccsbx\|jD]R}xL|j|jgD]<}||kr(qx,||jD]\}}x|D] }|VqDWq6WqWqWdS)N)r rrr)rr collectionrrkeyrrr__iter__.s  zkeyseries.__iter__cCs"x|D]}tdt|qWdS)Nz%s)printrepr)rrrrrdump7s zkeyseries.dumpcKs|jdd}|sdS|d}|jr>|j}|jp0d }|jp:d } n|j}|jpLd }|jpVd} |j} |j } | sv| |kr|j ||} | s| |kr|j ||} |j } d} |s|j d||jd|n| s| || kr| r(| |||| kr(|j | |f||j| || f|n| s`|j ||| f||j||| | f|n| |krln| || kr|j | |f||j| || f|np| |||| kr|j | |f||j| || f|n0|j ||| f||j||| | f|n|j}| s8| | || krL|j| | f|nN|sj|j|| | f|n0||| krzn || | kr|j| | f||j|jkr|j|j|}x|ddD]}|s|j d||j d||j d||jd||j|jkr|j|jq|j } | |} |j | f||j | f||j | |f||j| || f||j| | f||j|jkr|j|j|}qWx|r>|j r>|j ||jkr>|j|jdf||j|jd |jd |f|}|j |j |f||j|j | f||j||}qW|j d||jd|x"|D]}|j|jdf|q^WdS)NforceFriQi,rZ settime_path keygen_path randomdevi'i'i'i')N)N)N)N)N)N)N)N)getrZksk_rollperiodZksk_prepublishZksk_postpublishZzsk_rollperiodZzsk_prepublishZzsk_postpublishZpublishZactivateZ setpublishZ setactivateZinactiveZ setinactiveZ setdeleterkeyttlZttlZsetttlZcoverageZcommitr Zgenerate_successorr)rrpolicyrkwargsr&r!ZrpZprepubZpostpubpaiZfudgedprevrrr fixseries;s                        zkeyseries.fixseriescKs|jd|j}|jd|jjdd}|jdd}x|D]}g}|j|} |pX| jpXd}| j} tj| } d|ks||d rt|j || dkrtj |jd |jd ||| | j d| j pd f|} |j || j | |j |j |d |ks|d  rht|j|| dkrXtj |jd |jd ||| | jd | j prrrrrs   vr)r<rr7ZkeydictZkeyeventr,rBrrrrr s PK{ 1]@9 (__pycache__/keydict.cpython-36.opt-1.pycnu[3 ~j! @s:ddlmZddlmZddlZddlZGdddZdS)) defaultdict)dnskeyNc@sneZdZdZeddZdZgZdddZddZ d d Z d d Z d dZ ddZ ddZddZddZdS)keydictz> A dictionary of keys, indexed by name, algorithm, and key id cCsttS)N)rdictrr/usr/lib/python3.6/keydict.pyszkeydict.NcKs|jdd|_|jdd}|s:|jddp,d}|j|nXxV|D]N}d|krb|ddk rb|d}n|rr|j|jptd}|j||s@|jj|q@WdS)NZkeyttlzonespath.)get_defttlreadallZpolicyZ directoryreadone_missingappend)selfZdpkwargsr r zonerrr__init__s     zkeydict.__init__cCsLtjtjj|d}x2|D]*}t|||j}||j|j|j|j <qWdS)Nz *.private) globosr joinrr_keydictnamealgkeyid)rr filesinfilekeyrrrr,s zkeydict.readallc Cs|jds|d7}d|d}tjtjj||}d}xR|D]J}t|||j}|j|krZq<|dkrh|jnd}||j ||j |j <d}q s  PK{ 1]u*e"__pycache__/checkds.cpython-36.pycnu[3 ~j&@shddlZddlZddlZddlmZmZddlmZmZdZ GdddZ d ddZ d d Z d d Z dS)N)PopenPIPE)prefixversionzdnssec-checkdsc@sPeZdZdddddZdZdZdZdZdZdZ d Z dd d Z d d Z ddZ dS)SECRRzSHA-1zSHA-256ZGOSTzSHA-384)INNrcCs|stt|tk r$|jdj}n|j}t|dkrWt | dkrt ddSd} xv| D]n} | |krt d| j| jjd| j| jt j| jfd} n,t d| j| jjd| j| jt j| jfqW| s"t d|rdnd| S)Nz+noallz+answerz-tr,Zdsz-qr)stdoutr cSs|j|j|jfS)N)r'r(r))rrr-r-r.mszcheck..)keyz-fz-lZdnskey-)stdinr7rz$No DNSKEY records found in zone apexFz,%s for KSK %s/%03d/%05d (%s) found in parentTz0%s for KSK %s/%03d/%05d (%s) missing from parentz'No %s records were found for any DNSKEYrr)digrrZ communicate splitlinesrrrappendrsorted dsfromkeyrprintrr!rr(r'r6r)) zoneargs masterfile lookasideZrrlistcmdfp_lineZklistZintodsfoundr8r-r-r.checkcsV           rLcCstjtdd}d}tjdkr"dnd}|jdtdd|jd d d td d |jdddtdd |jdddtjjt |dtdd|jdddtjjt |dtdd|jdddt d|j }|j j d |_ |jr|jj d |_|S)!Nz: checks DS coverage) descriptionbinntZsbinrCz zone to check)rhelpz-fz--filerEzzone master file)destrrPz-lz --lookasiderFzDLV lookaside zonez-dz--digr=z path to 'dig')rQdefaultrrPz-Dz --dsfromkeyrAzdnssec-dsfromkeyzpath to 'dnssec-dsfromkey'z-vz --versionr)actionrr)argparseArgumentParserprogosname add_argumentrpathrrr parse_argsrCrrF)parserZbindirZsbindirrDr-r-r.r[s,        r[cCs.t}t|j||j|j}t|r$dnddS)Nrr)r[rLrCrErFexit)rDrKr-r-r.mainsr^)NN)rTrWsys subprocessrrZ isc.utilsrrrVrrLr[r^r-r-r-r. sI ; PK{ 1]6_uu!__pycache__/keymgr.cpython-36.pycnu[3 ~jk@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z dZ ddl mZmZmZmZmZmZddZddd Zd d Zd d ZdS))print_functionN) defaultdictz dnssec-keymgr)dnskeykeydict keyseriespolicyparsetabutilscOst||tjddS)N)printsysexit)argskwargsr/usr/lib/python3.6/keymgr.pyfatals rcCs|}| s(tjj| s(tj|tj rtjd}|s>tjj}xB|jtjD]2}|tj |}tjj|rztj|tjrzPd}qLW|S)a2 find the location of a specified command. If a default is supplied, exists and it's an executable, we use it; otherwise we search PATH for an alternative. :param command: command to look for :param default: default value to use :return: PATH with the location of a suitable binary PATHN) ospathisfileaccessX_OKenvirondefpathsplitpathsepsep)ZcommanddefaultZfpathrZ directoryrrrset_paths$ rcCstdtjjtjdd}tdtjjtjdd}tjtdd}|j dt ddd;d |j d d t ddd|j ddt ddd|j dd|t dd d|j ddt ddd d|j dd|t dd d|j d d!d"d#d$d%|j d&d'd"d#d(d%|j d)d*d+d"d#d s @   GPK{ 1]:]\ __pycache__/utils.cpython-36.pycnu[3 ~j@sTddlZejdkr"ddlZddlZd ddZddZdZejdkrHd Zned ZdS) Nntc Cs tjdkrtjjd|Stj}d}tj}d}d}ytj||d|}Wnd}YnX|sd}|tj B}ytj||d|}Wnd}YnX|sd}|tj B}ytj||d|}Wnd}YnX|rytj |d\}} Wnd}YnXtj ||rtjj||Stjjtj |S)Nrz/usrzSoftware\ISC\BINDTrFZ InstallDir)osnamepathjoinwin32conHKEY_LOCAL_MACHINEZKEY_READwin32apiZ RegOpenKeyExZKEY_WOW64_64KEYZKEY_WOW64_32KEYZRegQueryValueExZ RegCloseKeyZGetSystemDirectory) ZbindirZhklmZ bind_subkeyZsamZh_keyZ key_foundZsam64Zsam32Z named_base_r /usr/lib/python3.6/utils.pyprefixsD        rcCs2tjdkrd|jdddSd|jdddS)Nr"z"\"'z'\'')rrreplace)sr r r shellquote=s rz#9.11.36-RedHat-9.11.36-16.el8_10.14z/etcZetc)r)rrrr rrversionZ sysconfdirr r r r  s  ) PK{ 1]q@@)__pycache__/keyevent.cpython-36.opt-1.pycnu[3 ~j @sddlZGdddZdS)Nc@s4eZdZdZd ddZddZddZd d d ZdS) keyeventz A discrete key event, e.g., Publish, Activate, Inactive, Delete, etc. Stores the date of the event, and identifying information about the key to which the event will occur.NcCs@||_|p|j||_||_|j|_|j|_|j|_|j|_dS)N) whatZgettimewhenkeysepnamezonealgkeyid)selfrrrr /usr/lib/python3.6/keyevent.py__init__szkeyevent.__init__cCs t|j|j|j|j|j|jfS)N)reprrrr rrr )r r r r __repr__ szkeyevent.__repr__cCstjd|jS)Nz%a %b %d %H:%M:%S UTC %Y)timeZstrftimer)r r r r showtime$szkeyevent.showtimecCsdd}|s|}|st}|s$t}|jdkr<|j|jn|jdkrT|j|jn|jdkr|j|kr||dt|jq|j|jnl|jdkr|j|kr|j|jq|dt|jn6|jd kr|j|kr|j|j|j|kr|j|j||fS) Nc_sdS)Nr )argskwargsr r r noop*szkeyevent.status..noopZActivateZPublishZInactivez= WARNING: %s scheduled to become inactive before it is activeZDeletez@WARNING: key %s is scheduled for deletion before it is publishedZRevoke)setraddr rrremove)r ZactiveZ publishedoutputrr r r status)s6           zkeyevent.status)N)N)__name__ __module__ __qualname____doc__rrrrr r r r rs  r)rrr r r r  sPK{ 1]vPҔ#__pycache__/parsetab.cpython-36.pycnu[3 j"~j};@s dZdZdZddddddd d d d d g d ddd d d d d d d d g fddddddd d d d d g d ddd d d d d d d d g fddddddd d dd d dd ddgd ddd d d d d dd d dd d d gfddddd d d d d g dd d d d d d d d g fddgddgfdddgdddgfdd gd!d"gfddd#d$d%d&d'dgdd(d)d*d+d,d-d(gfdddd.gdd/d/d0gfdd1dd!ddddd(d/d2ddg d! d! d d d1 d d! d d d d3ddg fdd(d/d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLd.dMdNdOdPdQd"dd0dRdSdTdUdVg*d d d d d d dWd= d> dX d# d$ d% dY dd4 d3 d5 d d6 d dZ d7 d8 d9 d: d[d d d( dC d2 dd& d' dD d/ d d? d@ dA dB g*fd3ddZddWdd[dgdXdXdXdXd; d d< d gfd3ddZddWdd[dgd#d#d#d#d; d d< d gfd3ddZddWdd[dgd$d$d$d$d; d d< d gfd3ddZddWdd[dgd%d%d%d%d; d d< d gfd3ddZddWdd[dgdYdYdYdYd; d d< d gfd3ddZddWdd[dgd&d&d&d&d; d d< d gfd3ddZddWdd[dgd'd'd'd'd; d d< d gfddddgd d d d gfddddgddd d gfdZddWdd[dgdJdOd; d d< d gfdXdYd)d*d+d,d-gd.d.d.d.d.dUdVgfdXdYd)d*d+gdMdMdMdMdMgfd\ZiZxXejD]L\ZZx@eededD]*\Z Z e ek riee <e ee e<qWqW[dgdgfdgdgfddgdd gfddgddgfddgddgfddgd d gfdgd1gfddgddQgfdd1dgd2ddgfd2gd4gfddgd5d6gfd3gdZgfd3dZgd7dKgfd3ddZdgd8dBd8dBgfd3ddZdgd9dCd9dCgfd3ddZdgd:dDd:dDgfd3ddZdgd;dEd;dEgfd3ddZdgddId>dIgfdgdgfddgd?dPgfddgd@d@gfddgdAdAgfddgdGdGgfdXdYd)d*d+gdLdNdRdSdTgfd]Z iZ xXe jD]L\ZZx@eededD]*\Z Z e e k rie e <e e e e<qWqW[ d^d_dd`d`d`fdadbddcdddefdfdbddcdddgfdhdiddjdddkfdldmddndddofdpdmddndddqfdrdmddndddsfdtduddvdddwfdxduddvdddyfdzduddvddd{fd|d}dd~dddfdd}dd~dddfdd}dd~dddfdd}dd~dddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfg6Z d`S(z3.8ZLALRZ C2FE91AF256AF1CCEB499107DA2CFE7E .>/MX ;= P <O()*,-EFGIJCR  !"#$%&0123456789:?@BDHKLNSTUVWA'+Q)ZALGORITHM_POLICYZZONEZPOLICYz$endZALGNAMEZSTRZQSTRINGZKEYTYPEZ DATESUFFIXLBRACESEMIZCOVERAGEZ ROLL_PERIODZ PRE_PUBLISHZ POST_PUBLISHZKEYTTLZKEY_SIZEZSTANDBYZ DIRECTORYZ ALGORITHMRBRACENUMBERZNONE) policylistinitpolicy alg_policy zone_policy named_policydomainname new_policyalg_option_grouppolicy_option_groupalg_option_list alg_optioncoverage_optionrollperiod_optionprepublish_optionpostpublish_option keyttl_optionkeysize_optionstandby_optionpolicy_option_list policy_option parent_optiondirectory_optionalgorithm_optiondurationzS' -> policylistzS'Nzpolicylist -> init policyr^Z p_policylistz policy.pyi zpolicylist -> policylist policyi zinit -> r_Zp_initizpolicy -> alg_policyr`Zp_policyizpolicy -> zone_policyizpolicy -> named_policyiz name -> STRreZp_nameizname -> KEYTYPEizname -> DATESUFFIXiz domain -> STRrdZp_domaini!zdomain -> QSTRINGi"zdomain -> KEYTYPEi#zdomain -> DATESUFFIXi$znew_policy -> rfZ p_new_policyi+zGalg_policy -> ALGORITHM_POLICY ALGNAME new_policy alg_option_group SEMIraZ p_alg_policyi/z>zone_policy -> ZONE domain new_policy policy_option_group SEMIrbZ p_zone_policyi6z?named_policy -> POLICY name new_policy policy_option_group SEMIrcZp_named_policyi=zduration -> NUMBERrwZ p_duration_1iCzduration -> NONEZ p_duration_2iHzduration -> NUMBER DATESUFFIXZ p_duration_3iMz7policy_option_group -> LBRACE policy_option_list RBRACErhZp_policy_option_groupi`z(policy_option_list -> policy_option SEMIrrZp_policy_option_listidz;policy_option_list -> policy_option_list policy_option SEMIiezpolicy_option -> parent_optionrsZp_policy_optioniiz!policy_option -> directory_optionijz policy_option -> coverage_optionikz"policy_option -> rollperiod_optionilz"policy_option -> prepublish_optionimz#policy_option -> postpublish_optioninzpolicy_option -> keysize_optionioz!policy_option -> algorithm_optionipzpolicy_option -> keyttl_optioniqzpolicy_option -> standby_optionirz1alg_option_group -> LBRACE alg_option_list RBRACErgZp_alg_option_groupivz"alg_option_list -> alg_option SEMIriZp_alg_option_listizz2alg_option_list -> alg_option_list alg_option SEMIi{zalg_option -> coverage_optionrjZ p_alg_optionizalg_option -> rollperiod_optionizalg_option -> prepublish_optioniz alg_option -> postpublish_optionizalg_option -> keyttl_optionizalg_option -> keysize_optionizalg_option -> standby_optionizparent_option -> POLICY namertZp_parent_optioniz%directory_option -> DIRECTORY QSTRINGruZp_directory_optioniz$coverage_option -> COVERAGE durationrkZp_coverage_optioniz1rollperiod_option -> ROLL_PERIOD KEYTYPE durationrlZp_rollperiod_optioniz1prepublish_option -> PRE_PUBLISH KEYTYPE durationrmZp_prepublish_optioniz3postpublish_option -> POST_PUBLISH KEYTYPE durationrnZp_postpublish_optioniz)keysize_option -> KEY_SIZE KEYTYPE NUMBERrpZp_keysize_optioniz(standby_option -> STANDBY KEYTYPE NUMBERrqZp_standby_optioniz keyttl_option -> KEYTTL durationroZp_keyttl_optioniz%algorithm_option -> ALGORITHM ALGNAMErvZp_algorithm_optioni)Z _tabversionZ _lr_methodZ _lr_signatureZ_lr_action_itemsZ _lr_actionitemsZ_kZ_vzipZ_xZ_yZ_lr_goto_itemsZ_lr_gotoZ_lr_productionsrzrz/usr/lib/python3.6/parsetab.pys  PK{ 1]s$__pycache__/eventlist.cpython-36.pycnu[3 ~j@s6ddlmZddlTddlTddlTGdddZdS)) defaultdict)*c@s`eZdZeddZeddZeZdZddZ dddZ d d Z e d d Z e d dZdS) eventlistcCsttS)N)rlistrr/usr/lib/python3.6/eventlist.pyszeventlist.cCsttS)N)rrrrrrr sNc Csddddddg}||_x|jD]}|jj|x||jD]\}}xj|jD]^}xX|D]P}|j|}|snqZt|||} |jr|j ||j | qZ|j ||j | qZWqPWt |j ||ddd |j ||<t |j ||d dd |j ||<q>Wq WdS) NZ SyncPublishZPublishZ SyncDeleteZActivateZInactiveZDeletecSs|jS)N)when)eventrrrr +sz$eventlist.__init__..)keycSs|jS)N)r )r rrrr -s) _kdictZzones_zonesadditemsvaluesZgettimekeyeventsep_Kappend_Zsorted) selfZkdictZ propertieszonealgkeyskZpropterrr__init__s&     zeventlist.__init__c Csdd}|s|}|r |dkr dnd}|r4|dkr4dnd}d}} d} |rb||jkrb|d|dS|rd} |s~|j|d||}|s|j|d||} n`x^|jD]T} | r| |jjkrd} |j| d||}| r| |jjkrd} |j| d||} qW| s|ddS|o| S) Nc_sdS)Nr)argskwargsrrrnoop2sz eventlist.coverage..noopKSKTFZZSKz!ERROR: No key events found for %szERROR: No key events found)r checkzonerrr) rrkeytypeuntiloutputr"Zno_zskZno_kskZkokZzokfoundzrrrcoverage1s6  zeventlist.coveragec Csxd}|dkr|j|}n |j|}xP|jD]D}|d||tj|ftj|||||}|rh|d|on|}q,W|S)NTr#z9Checking scheduled %s events for zone %s, algorithm %s...zNo errors found)rrrdnskeyZalgstrrcheckset) rrr%r&r'ZallokZkzrokrrrr$Ts   zeventlist.checkzonecCsR|sdS|d|djdddx(|D] }|d|jt|jfddq*WdS)Nz r:F)skipz %s: %s)ZshowtimeZwhatreprr )eventsetr'r rrrshowsetfs  zeventlist.showsetc CsNt}t}d}xZ|D]R}d}| s4|dj|jkr>|j||dj|jkr|j|t}|j|qW|rz|j||s|d|dSd}} x|D]}|rtj|dj|kr|dtjdtj|dSx|D]}|j|| \}} qWt j |||s|d|dS| s,|d|dS| j |s|d |dSqWdS) NFTrzERROR: No %s events foundzIgnoring events after %sz%a %b %d %H:%M:%S UTC %Yz*ERROR: No %s's are active after this eventz-ERROR: No %s's are published after this eventz=ERROR: No %s's are both active and published after this event) rr rZcalendarZtimegmZtimeZstrftimeZgmtimeZstatusrr2 intersection) r1r%r&r'groupsgroupZ eventsfoundr ZactiveZ publishedrrrr,nsL          zeventlist.checkset)N)__name__ __module__ __qualname__rrrsetrr rr*r$ staticmethodr2r,rrrrrs   # rN) collectionsrr+Zkeydictrrrrrr s PK{ 1]:]\&__pycache__/utils.cpython-36.opt-1.pycnu[3 ~j@sTddlZejdkr"ddlZddlZd ddZddZdZejdkrHd Zned ZdS) Nntc Cs tjdkrtjjd|Stj}d}tj}d}d}ytj||d|}Wnd}YnX|sd}|tj B}ytj||d|}Wnd}YnX|sd}|tj B}ytj||d|}Wnd}YnX|rytj |d\}} Wnd}YnXtj ||rtjj||Stjjtj |S)Nrz/usrzSoftware\ISC\BINDTrFZ InstallDir)osnamepathjoinwin32conHKEY_LOCAL_MACHINEZKEY_READwin32apiZ RegOpenKeyExZKEY_WOW64_64KEYZKEY_WOW64_32KEYZRegQueryValueExZ RegCloseKeyZGetSystemDirectory) ZbindirZhklmZ bind_subkeyZsamZh_keyZ key_foundZsam64Zsam32Z named_base_r /usr/lib/python3.6/utils.pyprefixsD        rcCs2tjdkrd|jdddSd|jdddS)Nr"z"\"'z'\'')rrreplace)sr r r shellquote=s rz#9.11.36-RedHat-9.11.36-16.el8_10.14z/etcZetc)r)rrrr rrversionZ sysconfdirr r r r  s  ) PK{ 1]t}U#__pycache__/coverage.cpython-36.pycnu[3 ~j&@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z dZ ddl mZmZmZmZmZmZddZdad d Zd d Zd dZdddZddZddZdS))print_functionN) defaultdictzdnssec-coverage)dnskey eventlistkeydictkeyeventkeyzoneutilscOst||tjddS)N)printsysexit)argskwargsr/usr/lib/python3.6/coverage.pyfatals rTcOsJd|kr|d}|jddnd}tr,dan |r8td|rFt||dS)zuoutput text, adding a vertical space this is *not* the first first section being printed since a call to vreset()skipNTF)pop _firstliner )rrrrrroutput'srcCsdadS)zreset vertical spacingTN)rrrrrvreset8src Cs|j}yt|Stk r$YnXtjd}|j|}|sJtd||j\}}t|}|j}|jdrx|dS|jdr|dS|jdr|dS|jd r|d S|jd r|d S|jd r|dS|jdr|Std|dS)z convert a formatted time (e.g., 1y, 6mo, 15mi, etc) into seconds :param s: String with some text representing a time interval :return: Integer with the number of seconds in the time interval z([0-9][0-9]*)\s*([A-Za-z]*)zCannot parse %syi3moi'wi: diQhiZmi<szInvalid suffix %sN) stripint ValueErrorrecompilematchgroupslower startswith)rrmnZunitrrr parse_timeAs6           r,cCs|}| s(tjj| s(tj|tj rtjd}|s>tjj}xB|jtjD]2}tjj ||}tjj|rztj|tjrzPd}qLW|S)a1 find the location of a specified command. if a default is supplied and it works, we use it; otherwise we search PATH for a match. :param command: string with a command to look for in the path :param default: default location to use :return: detected location for the desired command PATHN) ospathisfileaccessX_OKenvirondefpathsplitpathsepjoin)ZcommanddefaultZfpathr/Z directoryrrrset_pathks$ r9c 0CsDtdtjjtjdd}tjtddd}|j dt dddFd |j d d dt ddd|j ddt ddd|j ddt ddd|j ddt ddd|j ddd t d!dd|j d"d#|t d$d d|j d%d&t d'd(dd)|j d*d+d,d-d.d/|j d0d1d,d-d2d/|j d3d4d5d,d-d6d/|j d7d8d9tj d:|j }|j rJ|jrJtd;n*|j sZ|jrn|j rfdkrtd?d@dA|jD|_y|jrt|j}||_Wntk rYnXy|jrt|j}||_Wntk r YnXy|jr(t|j}||_Wntk r@YnXy<|jr||j}t|j}|dBkrnd|_ntj||_Wntk rYnX|jr|jr|S|jr*|jr*y:t|jdB|j|j}|jp|j|_|jp|j|_Wn4tk r(}ztdC|j|WYdd}~XnX|js@tdDdE|_|S)Gz8Read command line arguments, set global 'args' structureznamed-compilezoneZsbinz: checks future zDNSKEY coverage for a zone) descriptionzone*Nzzone(s) to checkz%(default: all zones in the directory))typenargsr8helpz-Kr/.z&a directory containing keys to processdir)destr8r=r?metavarz-ffilenamezzone master filefile)rBr=r?rCz-mmaxttlzthe longest TTL in the zone(s)timez-dkeyttlzthe DNSKEY TTLz-rresignZ1944000z:the RRSIG refresh interval in seconds [default: 22.5 days]z-c compilezonezpath to 'named-compilezone'z-l checklimit0zDLength of time to check for DNSSEC coverage [default: 0 (unlimited)])rBr=r8r?rCz-zno_ksk store_trueFz#Only check zone-signing keys (ZSKs))rBactionr8r?z-kno_zskz"Only check key-signing keys (KSKs)z-Dz--debugZ debug_modezTurn on debugging outputz-vz --versionversion)rOrQz)ERROR: -z and -k cannot be used together.ZKSKZZSKr z)ERROR: -f can only be used with one zone.cSs4g|],}t|dkr,|ddkr,|ddn|qS)r r@NrR)len).0xrrr szparse_args..rz"Unable to load zone data from %s: zWARNING: Maximum TTL value was not specified. Using 1 week (604800 seconds); re-run with the -m option to get more accurate results.i: z5zone(s) to check(default: all zones in the directory)) r9r.r/r7r prefixargparseArgumentParserprog add_argumentstrrQ parse_argsrPrMrkeytyperDrSr;rFr,r"rHrIrKrGrrJ Exceptionr r) rJparserrr*kr)Zlimr;errrr]s                       "r]c(Cspt}tdyt|j|j|jd}Wn2tk rX}ztdt|WYdd}~XnXx<|D]4}|j t |j r|j t q`|j t |j |jq`Wt dty t|}Wn2tk r}ztdt|WYdd}~XnXd}|js|jd|j|jt sXd}nJxH|jD]>}y|j||j|jt s6d}Wnt d|YnXqWtj|rfd nd dS) Nz;PHASE 1--Loading keys to check for internal timing problems)r/ZzonesrHz'ERROR: Unable to build key dictionary: z9PHASE 2--Scanning future key events for coverage failuresz#ERROR: Unable to build event list: FTz&ERROR: Coverage check failed for zone r r)r]r rr/r;rHr_rr\Z check_prepubrsepZ check_postpubrFrIrrZcoverager^rKr r )rZkdrbkeyZelisterrorsr;rrrmains:"    "   rf)N)Z __future__rr.r rXZglobr#rGZcalendarpprint collectionsrrZZiscrrrrrr rrrrr,r9r]rfrrrr s&    * xPK{ 1]E__pycache__/rndc.cpython-36.pycnu[3 ~j+@sXddlmZddlZddlZddlZddlZddlZddlZddlZGddde Z dS)) OrderedDictNc@sleZdZdZdddddddZd d Zd d ZdddZddZddZ ddZ ddZ ddZ ddZ dS)rndczRNDC protocol client library)md5Zsha1Zsha224Zsha256Zsha384Zsha512cCsb||_|j}|jdr$|dd}||_tt||_tj||_ t j dd|_ d|_ |jdS)zCreates a persistent connection to RNDC and logs in host - (ip, port) tuple algo - HMAC algorithm: one of md5, sha1, sha224, sha256, sha384, sha512 (with optional prefix 'hmac-') secret - HMAC secret, base64 encodedzhmac-Nri)hostlower startswithalgogetattrhashlibhlalgobase64 b64decodesecretrandomZrandintsernonce_rndc__connect_login)selfrrrr/usr/lib/python3.6/rndc.py__init__$s    z rndc.__init__cCst|j|ddS)zCall a RNDC command, all parsing is done on the server side cmd - a complete string with a command (eg 'reload zone example.com') )type_data)dict_rndc__command)rcmdrrrcall5sz rndc.callFcCst}x|jD]\}}|r(|dkr(q|tjdt||jd7}t|tkrt|tjddt||jd7}qt|tkr|tjddt||7}qt|tkr|tjddt||7}qt|t kr|j |}|tjddt||7}qt dt|qW|S)N_authBasciiz>BIr z#Cannot serialize element of type %s) bytearrayitemsstructpacklenencoder strbytesr_rndc__serialize_dictNotImplementedError)rdata ignore_authrvkvZsdrrrZ__serialize_dict;s"  "    zrndc.__serialize_dictc Os,|jd7_ttj}t||}t}t|d<t|d<t|j|dd<t||dd<t|d|dd<|jdk r|j|dd<||d <|j|d d }tj|j ||j j }t j |}|jd krtjd ||dd<n"ttjd|j|j||dd<|j|}tjdt|dd|}|S)Nr r&_ctrlZ_serZ_tim<Z_exp_noncer!T)r5r Z22shmd5ZB88shshaz>II)rinttimerr0rr2hmacnewrrdigestrZ b64encoderr,r-r* _rndc__algosr.) rargskwargsZnowr4dmsghashbhashrrrZ__prep_messageOs,        zrndc.__prep_messagecCs|jdk r |dd|jkr dS|jdkr8|dd}n|dddd}t|tkrb|jd }|d d t|d 7}tj|}|j|d d }t j |j ||j j }||kS)Nr9r;Fr r&r<r=r r(=r>T)r5)rrr r1decoder.rrr2rArBrrrC)rrHrJZ remote_hashZmy_msgZmy_hashrrrZ __verify_msgjs    zrndc.__verify_msgc Os|j||}|jj|}|t|kr,td|jjd}t|dkrLtdtjd|\}}|dkrptd||d8}|jj|tj }t||krtdt |t krt |}|j |}|j|std |S) NzCannot send the messagezCan't read response headerz>IIr zWrong message version %dr>zCan't read response datazAuthentication failure)_rndc__prep_messagesocketsendr.IOErrorZrecvr,unpackr3Z MSG_WAITALLr r0r*_rndc__parse_message_rndc__verify_msg) rrErFrHZsentheaderZlengthversionr4rrrZ __commandys(          zrndc.__commandcCs2tj|j|_d|_|jdd}|dd|_dS)NZnull)r r9r;)rOZcreate_connectionrrr#)rrHrrrZ__connect_logins zrndc.__connect_loginc Csd}||}|d7}||||jd}||7}||}|d7}tjd|||dd}|d7}||||}||7}||d}|dkr|||fS|dkrt} x(t|dkr|j|\} } }| | | <qW|| |fStd|dS)Nrr r(z>Ir>r)zUnknown element type %d)rLr,rRrr._rndc__parse_elementr3) rinputposZlabellenlabelr Zdatalenr4restrGZilabelvaluerrrZ__parse_elements*    zrndc.__parse_elementcCs8t}d}x(t|dkr2|j|\}}}|||<q W|S)Nr)rr.rW)rrXr6ZhdatarZr\rrrZ__parse_messages  zrndc.__parse_messageN)F)__name__ __module__ __qualname____doc__rDrr%r2rNrTr#rrWrSrrrrrs  r) collectionsrr@r,rrArrrOobjectrrrrrs PK{ 1]T^X5X5!__pycache__/dnskey.cpython-36.pycnu[3 ~j @@sJddlZddlZddlZddlmZmZGdddeZGdddZdS)N)PopenPIPEcseZdZfddZZS)TimePastcstt|jd|||fdS)Nz'%s time for key %s (%d) is already past)superr__init__)selfkeypropvalue) __class__/usr/lib/python3.6/dnskey.pyrs zTimePast.__init__)__name__ __module__ __qualname__r __classcell__r r )r r rsrc@seZdZdZdqZdrZdsZdtd!d"Zd#d$Zd%d&Z e dud'd(Z d)d*Z e d+d,Ze d-d.Zdvd/d0Ze d1d2Ze d3d4Ze d5d6Ze d7d8Zd9d:Zd;d<Zd=d>Zd?d@ZdAdBZdCdDZejfdEdFZdGdHZejfdIdJZdKdLZejfdMdNZ dOdPZ!ejfdQdRZ"dSdTZ#ejfdUdVZ$dWdXZ%ejfdYdZZ&d[d\Z'ejfd]d^Z(d_d`Z)dadbZ*dcddZ+dedfZ,dgdhZ-didjZ.dwdkdlZ/dxdmdnZ0e dodpZ1d S)ydnskeyztAn individual DNSSEC key. Identified by path, name, algorithm, keyid. Contains a dictionary of metadata events.CreatedPublishActivateInactiveDeleteRevoke DSPublish SyncPublish SyncDeleteN-P-A-I-D-R-Psync-DsyncRSAMD5DHDSAECCRSASHA1NSEC3DSA NSEC3RSASHA1 RSASHA256 RSASHA512ECCGOSTECDSAP256SHA256ECDSAP384SHA384ED25519ED448cCst|tr:t|dkr:|pd|_|\}}}|j|||||pLtjj|pLd|_tjj|}|j d\}}}|dd}t |}t |j dd}|j||||dS)N.+r) isinstancetuplelen_dir fromtupleospathdirnamebasenamesplitint)rrZ directorykeyttlnamealgkeyidr r r r&s    zdnskey.__init__cs|jdr|}|jd}n|d}d|||f}|j|jr@tjpBd|d}|j|jr^tjp`d|d}||_||_t||_t||_ ||_ t |d} x| D]zddkrqj } | sq| d j dkrd } ||_nd} |st| d n||_t| | d @d krd|_qd|_qW| jt |d} t|_t|_t|_t|_t|_t|_t|_d|_x| D]j svddkrqvfdddDtg} tdd| D}d|j}|djdj}||j|<qvWxtjD]}d|j|<||jkrn|j|j|}||j|<|j ||j|<|j!||j|<|j||j|<n(d|j|<d|j|<d|j|<d|j|<qW| jdS)Nr2z K%s+%03d+%05dz.keyz.privaterr;r4inchhsr1TFZrUz!#csg|]}j|qSr )find).0c)liner r lsz$dnskey.fromtuple..z:= cSsg|]}|dkr|qS)r4r5r )rMposr r r rPms)rHrIrJ)"endswithrstripr9r;sepkeystrrBr@rCrDfullnameopenr?lowerttlclosedictZmetadata_changed_delete_times_fmttime _timestamps _original_origttlstripr8minlstripr_PROPS parsetime formattime epochfromtime)rrBrCrDrArVrUZkey_fileZ private_fileZkfptokensZseptokenZpfpZ punctuationfoundr r tr )rOr r:5sv                 zdnskey.fromtuplecKsr|jdd}g}d}|jdk r0|dt|jg7}xlttjtjD]Z\}}| s@|j| r\q@d}||j krx|j |rxd}|rdn|j |} ||| g7}d}q@W|rn|d|j g||j g} |st ddj| y0t| ttd } | j\} } | rtt| Wn8tk r:}ztd |t|fWYdd}~XnXd|_x*tjD] }|j||j|<d|j|<qJWdS) NquietFTz-LZnonez-Kz#  )stdoutstderrzunable to run %s: %s)getrbstrrYziprrf_OPTSr\r]r_r9rUprintjoinrr communicate Exceptionr`ra)rZ settime_binkwargsrmcmdfirstr optdeleteZwhenZfullcmdprorper r r commits<    " z dnskey.commitc KsL| jdd} |dd|dt|g} |r0| d|g7} |r>| jd|rN| d|g7} |rb| d t|g7} | rtj| }| d tj|g7} | rtj| }| d tj| g7} | j|| std d j| t| t t d}|j \}}|rt dt|y"|j dj d}t|||}|St k rF}zt dt|WYdd}~XnXdS)NrmFz-qz-Kz-Lz-rz-fkz-az-bz-Pz-Az# rn)rorpzunable to generate key: rasciiz!unable to parse generated key: %s)rqrrappendr timefromepochrhrurvrrrwrx splitlinesdecode)cls keygen_bin randomdevZkeys_dirrBrCZkeysizerTrYpublishactivateryrm keygen_cmdrlr~rorprUnewkeyrr r r generates:         zdnskey.generatec Ks|jdd}|js td||dd|jd|jg}|jrL|dt|jg7}|r\|d|g7}|rp|d t|g7}|std d j|t |t t d }|j \}} | rtd | y&|j dj d} t| |j|j} | Std|YnXdS)NrmFz'predecessor key %s has no inactive datez-qz-Kz-Sz-Lz-rz-iz# rn)rorpzunable to generate key: rrz'unable to generate successor for key %s)rqinactiverxr9rUrYrrrurvrrrwrrr) rrrZ prepublishryrmrr~rorprUrr r r generate_successors,     zdnskey.generate_successorcCs0d}|tttjkr tj|}|r(|Sd|S)Nz%03d)ranger8r _ALGNAMES)rCrBr r r algstrs z dnskey.algstrc Cs6|sdS|j}y tjj|Stk r0dSXdS)N)upperrrindex ValueError)rCr r r algnums z dnskey.algnumcCs|j|p |jS)N)rrC)rrCr r r algnameszdnskey.algnamecCs tj|S)N)timeZgmtime)secsr r r rszdnskey.timefromepochcCs tj|dS)Nz %Y%m%d%H%M%S)rZstrptime)stringr r r rg szdnskey.parsetimecCs tj|S)N)calendarZtimegm)rlr r r riszdnskey.epochfromtimecCs tjd|S)Nz %Y%m%d%H%M%S)rZstrftime)rlr r r rhszdnskey.formattimecKs|jdd}|j||krdS|j|dk rR|j||krR| rRt|||j||dkr|j|dkrldnd|j|<d|j|<d|j|<d|j|<d|j|<dS|j|}||j|<||j|<|j ||j|<|j||j|krdnd|j|<dS)NforceFT) rqr`rarr\r]r^r_rrh)rr rnowryrrlr r r setmetas$        zdnskey.setmetacCs |j|S)N)r^)rr r r r gettime2szdnskey.gettimecCs |j|S)N)r_)rr r r r getfmttime5szdnskey.getfmttimecCs |j|S)N)r`)rr r r r gettimestamp8szdnskey.gettimestampcCs |jdS)Nr)r`)rr r r created;szdnskey.createdcCs |jdS)Nr)r`)rr r r syncpublish>szdnskey.syncpublishcKs|jd||f|dS)Nr)r)rrrryr r r setsyncpublishAszdnskey.setsyncpublishcCs |jdS)Nr)r`)rr r r rDszdnskey.publishcKs|jd||f|dS)Nr)r)rrrryr r r setpublishGszdnskey.setpublishcCs |jdS)Nr)r`)rr r r rJszdnskey.activatecKs|jd||f|dS)Nr)r)rrrryr r r setactivateMszdnskey.setactivatecCs |jdS)Nr)r`)rr r r revokePsz dnskey.revokecKs|jd||f|dS)Nr)r)rrrryr r r setrevokeSszdnskey.setrevokecCs |jdS)Nr)r`)rr r r rVszdnskey.inactivecKs|jd||f|dS)Nr)r)rrrryr r r setinactiveYszdnskey.setinactivecCs |jdS)Nr)r`)rr r r r}\sz dnskey.deletecKs|jd||f|dS)Nr)r)rrrryr r r setdelete_szdnskey.setdeletecCs |jdS)Nr)r`)rr r r syncdeletebszdnskey.syncdeletecKs|jd||f|dS)Nr)r)rrrryr r r setsyncdeleteeszdnskey.setsyncdeletecCsR|dks|j|krdS|jdkr0|j|_||_n|j|krHd|_||_n||_dS)N)rYrb)rrYr r r setttlhs  z dnskey.setttlcCs|jr dSdS)NKSKZSK)rT)rr r r keytypetszdnskey.keytypecCsd|j|j|jfS)Nz %s/%s/%05d)rBrrD)rr r r __str__wszdnskey.__str__cCs"d|j|j|j|jrdndfS)Nz%s/%s/%05d (%s)rr)rBrrDrT)rr r r __repr__{szdnskey.__repr__cCs|jp|jp|jS)N)rrr)rr r r datesz dnskey.datecCs@|j|jkr|j|jkS|j|jkr0|j|jkS|j|jkS)N)rBrCr)rotherr r r __lt__s     z dnskey.__lt__cCsdd}|s|}ttj}|j}|j}|s4dS|sT||krP|dt|dS||krh||krhdS||kr|dt|tj|jpdfdS||kr|dt|dS|jdk r|||jkr|d t|tj|jpdfdSdS) Nc_sdS)Nr )argsryr r r noopsz!dnskey.check_prepub..noopFzFWARNING: Key %s is scheduled for activation but not for publication.TzWARNING: %s is scheduled to be published and activated at the same time. This could result in a coverage gap if the zone was previously signed. Activation should be at least %s after publication.zone DNSKEY TTLz0WARNING: Key %s is active before it is publishedzWARNING: Key %s is activated too soon after publication; this could result in coverage gaps due to resolver caches containing old data. Activation should be at least %s after publication.)r@rrrreprrdurationrY)routputrrar~r r r check_prepubs<   zdnskey.check_prepubcCsdd}|dkr|}|dkr"|j}|dkr>|dt|d }tj}|j}|j}|s^dS|s~||krz|dt|dS||kr||krdS||kr|d t|dS|||kr|d t|tj|fdSdS) Nc_sdS)Nr )rryr r r rsz"dnskey.check_postpub..noopz"WARNING: Key %s using default TTL.<FzEWARNING: Key %s is scheduled for deletion but not for inactivation.Tz@WARNING: Key %s is scheduled for deletion before inactivation.zWARNING: Key %s scheduled for deletion too soon after deactivation; this may result in coverage gaps due to resolver caches containing old data. Deletion should be at least %s after inactivation.iiQ)rYrrr}rrr)rrZtimespanrrdir r r check_postpubs:   zdnskey.check_postpubcCsz|sdSddddddg}g}xR|D]J}||d ||d }}|d kr"|jd ||d |d krbdndfq"Wdj|S) Nyearrrimmonthdayhourminutesecondr4rz%d %s%ssrEz, iiQ3)rriiQ')rriQ)rr)rr)rr)rr4)rrv)rZunitsrZunitvr r r rs (zdnskey.duration) rrrrrrrrr) Nrrrrr Nr!r")Nr#r$r%r&r'r(r)r*Nr+Nr,r-r.r/r0)NN)NN)N)N)NN)2rrr__doc__rfrtrrr:r classmethodrr staticmethodrrrrrgrirhrrrrrrrrrrrrrrrrr}rrrrrrrrrrrrr r r r rsb M% *        1 -r) r;rr subprocessrrrxrrr r r r  s PK{ 1]E%__pycache__/rndc.cpython-36.opt-1.pycnu[3 ~j+@sXddlmZddlZddlZddlZddlZddlZddlZddlZGddde Z dS)) OrderedDictNc@sleZdZdZdddddddZd d Zd d ZdddZddZddZ ddZ ddZ ddZ ddZ dS)rndczRNDC protocol client library)md5Zsha1Zsha224Zsha256Zsha384Zsha512cCsb||_|j}|jdr$|dd}||_tt||_tj||_ t j dd|_ d|_ |jdS)zCreates a persistent connection to RNDC and logs in host - (ip, port) tuple algo - HMAC algorithm: one of md5, sha1, sha224, sha256, sha384, sha512 (with optional prefix 'hmac-') secret - HMAC secret, base64 encodedzhmac-Nri)hostlower startswithalgogetattrhashlibhlalgobase64 b64decodesecretrandomZrandintsernonce_rndc__connect_login)selfrrrr/usr/lib/python3.6/rndc.py__init__$s    z rndc.__init__cCst|j|ddS)zCall a RNDC command, all parsing is done on the server side cmd - a complete string with a command (eg 'reload zone example.com') )type_data)dict_rndc__command)rcmdrrrcall5sz rndc.callFcCst}x|jD]\}}|r(|dkr(q|tjdt||jd7}t|tkrt|tjddt||jd7}qt|tkr|tjddt||7}qt|tkr|tjddt||7}qt|t kr|j |}|tjddt||7}qt dt|qW|S)N_authBasciiz>BIr z#Cannot serialize element of type %s) bytearrayitemsstructpacklenencoder strbytesr_rndc__serialize_dictNotImplementedError)rdata ignore_authrvkvZsdrrrZ__serialize_dict;s"  "    zrndc.__serialize_dictc Os,|jd7_ttj}t||}t}t|d<t|d<t|j|dd<t||dd<t|d|dd<|jdk r|j|dd<||d <|j|d d }tj|j ||j j }t j |}|jd krtjd ||dd<n"ttjd|j|j||dd<|j|}tjdt|dd|}|S)Nr r&_ctrlZ_serZ_tim<Z_exp_noncer!T)r5r Z22shmd5ZB88shshaz>II)rinttimerr0rr2hmacnewrrdigestrZ b64encoderr,r-r* _rndc__algosr.) rargskwargsZnowr4dmsghashbhashrrrZ__prep_messageOs,        zrndc.__prep_messagecCs|jdk r |dd|jkr dS|jdkr8|dd}n|dddd}t|tkrb|jd }|d d t|d 7}tj|}|j|d d }t j |j ||j j }||kS)Nr9r;Fr r&r<r=r r(=r>T)r5)rrr r1decoder.rrr2rArBrrrC)rrHrJZ remote_hashZmy_msgZmy_hashrrrZ __verify_msgjs    zrndc.__verify_msgc Os|j||}|jj|}|t|kr,td|jjd}t|dkrLtdtjd|\}}|dkrptd||d8}|jj|tj }t||krtdt |t krt |}|j |}|j|std |S) NzCannot send the messagezCan't read response headerz>IIr zWrong message version %dr>zCan't read response datazAuthentication failure)_rndc__prep_messagesocketsendr.IOErrorZrecvr,unpackr3Z MSG_WAITALLr r0r*_rndc__parse_message_rndc__verify_msg) rrErFrHZsentheaderZlengthversionr4rrrZ __commandys(          zrndc.__commandcCs2tj|j|_d|_|jdd}|dd|_dS)NZnull)r r9r;)rOZcreate_connectionrrr#)rrHrrrZ__connect_logins zrndc.__connect_loginc Csd}||}|d7}||||jd}||7}||}|d7}tjd|||dd}|d7}||||}||7}||d}|dkr|||fS|dkrt} x(t|dkr|j|\} } }| | | <qW|| |fStd|dS)Nrr r(z>Ir>r)zUnknown element type %d)rLr,rRrr._rndc__parse_elementr3) rinputposZlabellenlabelr Zdatalenr4restrGZilabelvaluerrrZ__parse_elements*    zrndc.__parse_elementcCs8t}d}x(t|dkr2|j|\}}}|||<q W|S)Nr)rr.rW)rrXr6ZhdatarZr\rrrZ__parse_messages  zrndc.__parse_messageN)F)__name__ __module__ __qualname____doc__rDrr%r2rNrTr#rrWrSrrrrrs  r) collectionsrr@r,rrArrrOobjectrrrrrs PK{ 1]%$__pycache__/keyseries.cpython-36.pycnu[3 ~j"@sFddlmZddlTddlTddlTddlTddlZGdddZdS)) defaultdict)*Nc@sleZdZeddZeddZeZdZdZ e j dfddZ ddZ d d Z d d Ze j fd dZdS) keyseriescCsttS)N)rlistrr/usr/lib/python3.6/keyseries.pyszkeyseries.cCsttS)N)rrrrrrr sNcCs||_||_t|j|_x|jD]}|jj|x||jD]\}}xh|jD]\}|j r|j op|j |ks|j ||j |qT|j o|j |ksT|j ||j |qTW|j ||j|j ||jqBWq$WdS)N)_kdict_contextsetZmissing_zoneszonesadditemsvaluessepdelete_Kappend_Zsort)selfZkdictnowcontextzonealgkeyskrrr__init__s zkeyseries.__init__ccsbx\|jD]R}xL|j|jgD]<}||kr(qx,||jD]\}}x|D] }|VqDWq6WqWqWdS)N)r rrr)rr collectionrrkeyrrr__iter__.s  zkeyseries.__iter__cCs"x|D]}tdt|qWdS)Nz%s)printrepr)rrrrrdump7s zkeyseries.dumpcKs|jdd}|sdS|d}|jr>|j}|jp0d }|jp:d } n|j}|jpLd }|jpVd} |j} |j } | sv| |kr|j ||} | s| |kr|j ||} |j } d} |s|j d||jd|n| s| || kr| r(| |||| kr(|j | |f||j| || f|n| s`|j ||| f||j||| | f|n| |krln| || kr|j | |f||j| || f|np| |||| kr|j | |f||j| || f|n0|j ||| f||j||| | f|n|j}| s8| | || krL|j| | f|nN|sj|j|| | f|n0||| krzn || | kr|j| | f||j|jkr|j|j|}x|ddD]}|s|j d||j d||j d||jd||j|jkr|j|jq|j } | |} |j | f||j | f||j | |f||j| || f||j| | f||j|jkr|j|j|}qWx|r>|j r>|j ||jkr>|j|jdf||j|jd |jd |f|}|j |j |f||j|j | f||j||}qW|j d||jd|x"|D]}|j|jdf|q^WdS)NforceFriQi,rZ settime_path keygen_path randomdevi'i'i'i')N)N)N)N)N)N)N)N)getrZksk_rollperiodZksk_prepublishZksk_postpublishZzsk_rollperiodZzsk_prepublishZzsk_postpublishZpublishZactivateZ setpublishZ setactivateZinactiveZ setinactiveZ setdeleterkeyttlZttlZsetttlZcoverageZcommitr Zgenerate_successorr)rrpolicyrkwargsr&r!ZrpZprepubZpostpubpaiZfudgedprevrrr fixseries;s                        zkeyseries.fixseriescKs|jd|j}|jd|jjdd}|jdd}x|D]}g}|j|} |pX| jpXd}| j} tj| } d|ks||d rt|j || dkrtj |jd |jd ||| | j d| j pd f|} |j || j | |j |j |d |ks|d  rht|j|| dkrXtj |jd |jd ||| | jd | j prrrrrs   vr)r<rr7ZkeydictZkeyeventr,rBrrrrr s PK{ 1]vPҔ)__pycache__/parsetab.cpython-36.opt-1.pycnu[3 j"~j};@s dZdZdZddddddd d d d d g d ddd d d d d d d d g fddddddd d d d d g d ddd d d d d d d d g fddddddd d dd d dd ddgd ddd d d d d dd d dd d d gfddddd d d d d g dd d d d d d d d g fddgddgfdddgdddgfdd gd!d"gfddd#d$d%d&d'dgdd(d)d*d+d,d-d(gfdddd.gdd/d/d0gfdd1dd!ddddd(d/d2ddg d! d! d d d1 d d! d d d d3ddg fdd(d/d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLd.dMdNdOdPdQd"dd0dRdSdTdUdVg*d d d d d d dWd= d> dX d# d$ d% dY dd4 d3 d5 d d6 d dZ d7 d8 d9 d: d[d d d( dC d2 dd& d' dD d/ d d? d@ dA dB g*fd3ddZddWdd[dgdXdXdXdXd; d d< d gfd3ddZddWdd[dgd#d#d#d#d; d d< d gfd3ddZddWdd[dgd$d$d$d$d; d d< d gfd3ddZddWdd[dgd%d%d%d%d; d d< d gfd3ddZddWdd[dgdYdYdYdYd; d d< d gfd3ddZddWdd[dgd&d&d&d&d; d d< d gfd3ddZddWdd[dgd'd'd'd'd; d d< d gfddddgd d d d gfddddgddd d gfdZddWdd[dgdJdOd; d d< d gfdXdYd)d*d+d,d-gd.d.d.d.d.dUdVgfdXdYd)d*d+gdMdMdMdMdMgfd\ZiZxXejD]L\ZZx@eededD]*\Z Z e ek riee <e ee e<qWqW[dgdgfdgdgfddgdd gfddgddgfddgddgfddgd d gfdgd1gfddgddQgfdd1dgd2ddgfd2gd4gfddgd5d6gfd3gdZgfd3dZgd7dKgfd3ddZdgd8dBd8dBgfd3ddZdgd9dCd9dCgfd3ddZdgd:dDd:dDgfd3ddZdgd;dEd;dEgfd3ddZdgddId>dIgfdgdgfddgd?dPgfddgd@d@gfddgdAdAgfddgdGdGgfdXdYd)d*d+gdLdNdRdSdTgfd]Z iZ xXe jD]L\ZZx@eededD]*\Z Z e e k rie e <e e e e<qWqW[ d^d_dd`d`d`fdadbddcdddefdfdbddcdddgfdhdiddjdddkfdldmddndddofdpdmddndddqfdrdmddndddsfdtduddvdddwfdxduddvdddyfdzduddvddd{fd|d}dd~dddfdd}dd~dddfdd}dd~dddfdd}dd~dddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfdddddddfg6Z d`S(z3.8ZLALRZ C2FE91AF256AF1CCEB499107DA2CFE7E .>/MX ;= P <O()*,-EFGIJCR  !"#$%&0123456789:?@BDHKLNSTUVWA'+Q)ZALGORITHM_POLICYZZONEZPOLICYz$endZALGNAMEZSTRZQSTRINGZKEYTYPEZ DATESUFFIXLBRACESEMIZCOVERAGEZ ROLL_PERIODZ PRE_PUBLISHZ POST_PUBLISHZKEYTTLZKEY_SIZEZSTANDBYZ DIRECTORYZ ALGORITHMRBRACENUMBERZNONE) policylistinitpolicy alg_policy zone_policy named_policydomainname new_policyalg_option_grouppolicy_option_groupalg_option_list alg_optioncoverage_optionrollperiod_optionprepublish_optionpostpublish_option keyttl_optionkeysize_optionstandby_optionpolicy_option_list policy_option parent_optiondirectory_optionalgorithm_optiondurationzS' -> policylistzS'Nzpolicylist -> init policyr^Z p_policylistz policy.pyi zpolicylist -> policylist policyi zinit -> r_Zp_initizpolicy -> alg_policyr`Zp_policyizpolicy -> zone_policyizpolicy -> named_policyiz name -> STRreZp_nameizname -> KEYTYPEizname -> DATESUFFIXiz domain -> STRrdZp_domaini!zdomain -> QSTRINGi"zdomain -> KEYTYPEi#zdomain -> DATESUFFIXi$znew_policy -> rfZ p_new_policyi+zGalg_policy -> ALGORITHM_POLICY ALGNAME new_policy alg_option_group SEMIraZ p_alg_policyi/z>zone_policy -> ZONE domain new_policy policy_option_group SEMIrbZ p_zone_policyi6z?named_policy -> POLICY name new_policy policy_option_group SEMIrcZp_named_policyi=zduration -> NUMBERrwZ p_duration_1iCzduration -> NONEZ p_duration_2iHzduration -> NUMBER DATESUFFIXZ p_duration_3iMz7policy_option_group -> LBRACE policy_option_list RBRACErhZp_policy_option_groupi`z(policy_option_list -> policy_option SEMIrrZp_policy_option_listidz;policy_option_list -> policy_option_list policy_option SEMIiezpolicy_option -> parent_optionrsZp_policy_optioniiz!policy_option -> directory_optionijz policy_option -> coverage_optionikz"policy_option -> rollperiod_optionilz"policy_option -> prepublish_optionimz#policy_option -> postpublish_optioninzpolicy_option -> keysize_optionioz!policy_option -> algorithm_optionipzpolicy_option -> keyttl_optioniqzpolicy_option -> standby_optionirz1alg_option_group -> LBRACE alg_option_list RBRACErgZp_alg_option_groupivz"alg_option_list -> alg_option SEMIriZp_alg_option_listizz2alg_option_list -> alg_option_list alg_option SEMIi{zalg_option -> coverage_optionrjZ p_alg_optionizalg_option -> rollperiod_optionizalg_option -> prepublish_optioniz alg_option -> postpublish_optionizalg_option -> keyttl_optionizalg_option -> keysize_optionizalg_option -> standby_optionizparent_option -> POLICY namertZp_parent_optioniz%directory_option -> DIRECTORY QSTRINGruZp_directory_optioniz$coverage_option -> COVERAGE durationrkZp_coverage_optioniz1rollperiod_option -> ROLL_PERIOD KEYTYPE durationrlZp_rollperiod_optioniz1prepublish_option -> PRE_PUBLISH KEYTYPE durationrmZp_prepublish_optioniz3postpublish_option -> POST_PUBLISH KEYTYPE durationrnZp_postpublish_optioniz)keysize_option -> KEY_SIZE KEYTYPE NUMBERrpZp_keysize_optioniz(standby_option -> STANDBY KEYTYPE NUMBERrqZp_standby_optioniz keyttl_option -> KEYTTL durationroZp_keyttl_optioniz%algorithm_option -> ALGORITHM ALGNAMErvZp_algorithm_optioni)Z _tabversionZ _lr_methodZ _lr_signatureZ_lr_action_itemsZ _lr_actionitemsZ_kZ_vzipZ_xZ_yZ_lr_goto_itemsZ_lr_gotoZ_lr_productionsrzrz/usr/lib/python3.6/parsetab.pys  PK{ 1]s*__pycache__/eventlist.cpython-36.opt-1.pycnu[3 ~j@s6ddlmZddlTddlTddlTGdddZdS)) defaultdict)*c@s`eZdZeddZeddZeZdZddZ dddZ d d Z e d d Z e d dZdS) eventlistcCsttS)N)rlistrr/usr/lib/python3.6/eventlist.pyszeventlist.cCsttS)N)rrrrrrr sNc Csddddddg}||_x|jD]}|jj|x||jD]\}}xj|jD]^}xX|D]P}|j|}|snqZt|||} |jr|j ||j | qZ|j ||j | qZWqPWt |j ||ddd |j ||<t |j ||d dd |j ||<q>Wq WdS) NZ SyncPublishZPublishZ SyncDeleteZActivateZInactiveZDeletecSs|jS)N)when)eventrrrr +sz$eventlist.__init__..)keycSs|jS)N)r )r rrrr -s) _kdictZzones_zonesadditemsvaluesZgettimekeyeventsep_Kappend_Zsorted) selfZkdictZ propertieszonealgkeyskZpropterrr__init__s&     zeventlist.__init__c Csdd}|s|}|r |dkr dnd}|r4|dkr4dnd}d}} d} |rb||jkrb|d|dS|rd} |s~|j|d||}|s|j|d||} n`x^|jD]T} | r| |jjkrd} |j| d||}| r| |jjkrd} |j| d||} qW| s|ddS|o| S) Nc_sdS)Nr)argskwargsrrrnoop2sz eventlist.coverage..noopKSKTFZZSKz!ERROR: No key events found for %szERROR: No key events found)r checkzonerrr) rrkeytypeuntiloutputr"Zno_zskZno_kskZkokZzokfoundzrrrcoverage1s6  zeventlist.coveragec Csxd}|dkr|j|}n |j|}xP|jD]D}|d||tj|ftj|||||}|rh|d|on|}q,W|S)NTr#z9Checking scheduled %s events for zone %s, algorithm %s...zNo errors found)rrrdnskeyZalgstrrcheckset) rrr%r&r'ZallokZkzrokrrrr$Ts   zeventlist.checkzonecCsR|sdS|d|djdddx(|D] }|d|jt|jfddq*WdS)Nz r:F)skipz %s: %s)ZshowtimeZwhatreprr )eventsetr'r rrrshowsetfs  zeventlist.showsetc CsNt}t}d}xZ|D]R}d}| s4|dj|jkr>|j||dj|jkr|j|t}|j|qW|rz|j||s|d|dSd}} x|D]}|rtj|dj|kr|dtjdtj|dSx|D]}|j|| \}} qWt j |||s|d|dS| s,|d|dS| j |s|d |dSqWdS) NFTrzERROR: No %s events foundzIgnoring events after %sz%a %b %d %H:%M:%S UTC %Yz*ERROR: No %s's are active after this eventz-ERROR: No %s's are published after this eventz=ERROR: No %s's are both active and published after this event) rr rZcalendarZtimegmZtimeZstrftimeZgmtimeZstatusrr2 intersection) r1r%r&r'groupsgroupZ eventsfoundr ZactiveZ publishedrrrr,nsL          zeventlist.checkset)N)__name__ __module__ __qualname__rrrsetrr rr*r$ staticmethodr2r,rrrrrs   # rN) collectionsrr+Zkeydictrrrrrr s PK{ 1]j(__pycache__/keyzone.cpython-36.opt-1.pycnu[3 ~j@sJddlZddlZddlZddlmZmZGdddeZGdddZdS)N)PopenPIPEc@s eZdZdS)KeyZoneExceptionN)__name__ __module__ __qualname__rr/usr/lib/python3.6/keyzone.pyrsrc@seZdZdZddZdS)keyzonez/reads a zone file to find data relevant to keysc Csd|_d|_|sdS| s8tjj| s8tj|tj rDtddSd}}t|dd||gt t dj \}}xv|j D]j}t |t k r|jd}tjd|rqv|j} | st| d|krt| d}| dd krvt| d}qvW||_||_dS) Nz"named-compilezone" not foundz-o-)stdoutstderrasciiz ^[:space:]*;ZDNSKEY)maxttlkeyttlospathisfileaccessX_OKrrrZ communicate splitlinestypestrdecoderesearchsplitint) selfnamefilenameZczpathrrfp_lineZfieldsrrr __init__s.     zkeyzone.__init__N)rrr__doc__r&rrrr r sr ) rsysr subprocessrr Exceptionrr rrrr  s PK{ 1]q@@#__pycache__/keyevent.cpython-36.pycnu[3 ~j @sddlZGdddZdS)Nc@s4eZdZdZd ddZddZddZd d d ZdS) keyeventz A discrete key event, e.g., Publish, Activate, Inactive, Delete, etc. Stores the date of the event, and identifying information about the key to which the event will occur.NcCs@||_|p|j||_||_|j|_|j|_|j|_|j|_dS)N) whatZgettimewhenkeysepnamezonealgkeyid)selfrrrr /usr/lib/python3.6/keyevent.py__init__szkeyevent.__init__cCs t|j|j|j|j|j|jfS)N)reprrrr rrr )r r r r __repr__ szkeyevent.__repr__cCstjd|jS)Nz%a %b %d %H:%M:%S UTC %Y)timeZstrftimer)r r r r showtime$szkeyevent.showtimecCsdd}|s|}|st}|s$t}|jdkr<|j|jn|jdkrT|j|jn|jdkr|j|kr||dt|jq|j|jnl|jdkr|j|kr|j|jq|dt|jn6|jd kr|j|kr|j|j|j|kr|j|j||fS) Nc_sdS)Nr )argskwargsr r r noop*szkeyevent.status..noopZActivateZPublishZInactivez= WARNING: %s scheduled to become inactive before it is activeZDeletez@WARNING: key %s is scheduled for deletion before it is publishedZRevoke)setraddr rrremove)r ZactiveZ publishedoutputrr r r status)s6           zkeyevent.status)N)N)__name__ __module__ __qualname____doc__rrrrr r r r rs  r)rrr r r r  sPK{ 1]j"__pycache__/keyzone.cpython-36.pycnu[3 ~j@sJddlZddlZddlZddlmZmZGdddeZGdddZdS)N)PopenPIPEc@s eZdZdS)KeyZoneExceptionN)__name__ __module__ __qualname__rr/usr/lib/python3.6/keyzone.pyrsrc@seZdZdZddZdS)keyzonez/reads a zone file to find data relevant to keysc Csd|_d|_|sdS| s8tjj| s8tj|tj rDtddSd}}t|dd||gt t dj \}}xv|j D]j}t |t k r|jd}tjd|rqv|j} | st| d|krt| d}| dd krvt| d}qvW||_||_dS) Nz"named-compilezone" not foundz-o-)stdoutstderrasciiz ^[:space:]*;ZDNSKEY)maxttlkeyttlospathisfileaccessX_OKrrrZ communicate splitlinestypestrdecoderesearchsplitint) selfnamefilenameZczpathrrfp_lineZfieldsrrr __init__s.     zkeyzone.__init__N)rrr__doc__r&rrrr r sr ) rsysr subprocessrr Exceptionrr rrrr  s PK{ 1]~#__pycache__/__init__.cpython-36.pycnu[3 ~j @sjdddddddddd d d d g Zd dlTd dlTd dlTd dlTd dlTd dlTd dlTd dlTd dl TdS)ZcheckdsZcoverageZkeymgrZdnskeyZ eventlistZkeydictZkeyeventZ keyseriesZkeyzoneZpolicyZparsetabZrndcZutils)*N) __all__Z isc.dnskeyZ isc.eventlistZ isc.keydictZ isc.keyeventZ isc.keyseriesZ isc.keyzoneZ isc.policyZisc.rndcZ isc.utilsrr/usr/lib/python3.6/__init__.py s   PK{ 1]t}U)__pycache__/coverage.cpython-36.opt-1.pycnu[3 ~j&@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z dZ ddl mZmZmZmZmZmZddZdad d Zd d Zd dZdddZddZddZdS))print_functionN) defaultdictzdnssec-coverage)dnskey eventlistkeydictkeyeventkeyzoneutilscOst||tjddS)N)printsysexit)argskwargsr/usr/lib/python3.6/coverage.pyfatals rTcOsJd|kr|d}|jddnd}tr,dan |r8td|rFt||dS)zuoutput text, adding a vertical space this is *not* the first first section being printed since a call to vreset()skipNTF)pop _firstliner )rrrrrroutput'srcCsdadS)zreset vertical spacingTN)rrrrrvreset8src Cs|j}yt|Stk r$YnXtjd}|j|}|sJtd||j\}}t|}|j}|jdrx|dS|jdr|dS|jdr|dS|jd r|d S|jd r|d S|jd r|dS|jdr|Std|dS)z convert a formatted time (e.g., 1y, 6mo, 15mi, etc) into seconds :param s: String with some text representing a time interval :return: Integer with the number of seconds in the time interval z([0-9][0-9]*)\s*([A-Za-z]*)zCannot parse %syi3moi'wi: diQhiZmi<szInvalid suffix %sN) stripint ValueErrorrecompilematchgroupslower startswith)rrmnZunitrrr parse_timeAs6           r,cCs|}| s(tjj| s(tj|tj rtjd}|s>tjj}xB|jtjD]2}tjj ||}tjj|rztj|tjrzPd}qLW|S)a1 find the location of a specified command. if a default is supplied and it works, we use it; otherwise we search PATH for a match. :param command: string with a command to look for in the path :param default: default location to use :return: detected location for the desired command PATHN) ospathisfileaccessX_OKenvirondefpathsplitpathsepjoin)ZcommanddefaultZfpathr/Z directoryrrrset_pathks$ r9c 0CsDtdtjjtjdd}tjtddd}|j dt dddFd |j d d dt ddd|j ddt ddd|j ddt ddd|j ddt ddd|j ddd t d!dd|j d"d#|t d$d d|j d%d&t d'd(dd)|j d*d+d,d-d.d/|j d0d1d,d-d2d/|j d3d4d5d,d-d6d/|j d7d8d9tj d:|j }|j rJ|jrJtd;n*|j sZ|jrn|j rfdkrtd?d@dA|jD|_y|jrt|j}||_Wntk rYnXy|jrt|j}||_Wntk r YnXy|jr(t|j}||_Wntk r@YnXy<|jr||j}t|j}|dBkrnd|_ntj||_Wntk rYnX|jr|jr|S|jr*|jr*y:t|jdB|j|j}|jp|j|_|jp|j|_Wn4tk r(}ztdC|j|WYdd}~XnX|js@tdDdE|_|S)Gz8Read command line arguments, set global 'args' structureznamed-compilezoneZsbinz: checks future zDNSKEY coverage for a zone) descriptionzone*Nzzone(s) to checkz%(default: all zones in the directory))typenargsr8helpz-Kr/.z&a directory containing keys to processdir)destr8r=r?metavarz-ffilenamezzone master filefile)rBr=r?rCz-mmaxttlzthe longest TTL in the zone(s)timez-dkeyttlzthe DNSKEY TTLz-rresignZ1944000z:the RRSIG refresh interval in seconds [default: 22.5 days]z-c compilezonezpath to 'named-compilezone'z-l checklimit0zDLength of time to check for DNSSEC coverage [default: 0 (unlimited)])rBr=r8r?rCz-zno_ksk store_trueFz#Only check zone-signing keys (ZSKs))rBactionr8r?z-kno_zskz"Only check key-signing keys (KSKs)z-Dz--debugZ debug_modezTurn on debugging outputz-vz --versionversion)rOrQz)ERROR: -z and -k cannot be used together.ZKSKZZSKr z)ERROR: -f can only be used with one zone.cSs4g|],}t|dkr,|ddkr,|ddn|qS)r r@NrR)len).0xrrr szparse_args..rz"Unable to load zone data from %s: zWARNING: Maximum TTL value was not specified. Using 1 week (604800 seconds); re-run with the -m option to get more accurate results.i: z5zone(s) to check(default: all zones in the directory)) r9r.r/r7r prefixargparseArgumentParserprog add_argumentstrrQ parse_argsrPrMrkeytyperDrSr;rFr,r"rHrIrKrGrrJ Exceptionr r) rJparserrr*kr)Zlimr;errrr]s                       "r]c(Cspt}tdyt|j|j|jd}Wn2tk rX}ztdt|WYdd}~XnXx<|D]4}|j t |j r|j t q`|j t |j |jq`Wt dty t|}Wn2tk r}ztdt|WYdd}~XnXd}|js|jd|j|jt sXd}nJxH|jD]>}y|j||j|jt s6d}Wnt d|YnXqWtj|rfd nd dS) Nz;PHASE 1--Loading keys to check for internal timing problems)r/ZzonesrHz'ERROR: Unable to build key dictionary: z9PHASE 2--Scanning future key events for coverage failuresz#ERROR: Unable to build event list: FTz&ERROR: Coverage check failed for zone r r)r]r rr/r;rHr_rr\Z check_prepubrsepZ check_postpubrFrIrrZcoverager^rKr r )rZkdrbkeyZelisterrorsr;rrrmains:"    "   rf)N)Z __future__rr.r rXZglobr#rGZcalendarpprint collectionsrrZZiscrrrrrr rrrrr,r9r]rfrrrr s&    * xPK{ 1]5&& coverage.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ from __future__ import print_function import os import sys import argparse import glob import re import time import calendar import pprint from collections import defaultdict prog = 'dnssec-coverage' from isc import dnskey, eventlist, keydict, keyevent, keyzone, utils ############################################################################ # print a fatal error and exit ############################################################################ def fatal(*args, **kwargs): print(*args, **kwargs) sys.exit(1) ############################################################################ # output: ############################################################################ _firstline = True def output(*args, **kwargs): """output text, adding a vertical space this is *not* the first first section being printed since a call to vreset()""" global _firstline if 'skip' in kwargs: skip = kwargs['skip'] kwargs.pop('skip', None) else: skip = True if _firstline: _firstline = False elif skip: print('') if args: print(*args, **kwargs) def vreset(): """reset vertical spacing""" global _firstline _firstline = True ############################################################################ # parse_time ############################################################################ def parse_time(s): """ convert a formatted time (e.g., 1y, 6mo, 15mi, etc) into seconds :param s: String with some text representing a time interval :return: Integer with the number of seconds in the time interval """ s = s.strip() # if s is an integer, we're done already try: return int(s) except ValueError: pass # try to parse as a number with a suffix indicating unit of time r = re.compile(r'([0-9][0-9]*)\s*([A-Za-z]*)') m = r.match(s) if not m: raise ValueError("Cannot parse %s" % s) n, unit = m.groups() n = int(n) unit = unit.lower() if unit.startswith('y'): return n * 31536000 elif unit.startswith('mo'): return n * 2592000 elif unit.startswith('w'): return n * 604800 elif unit.startswith('d'): return n * 86400 elif unit.startswith('h'): return n * 3600 elif unit.startswith('mi'): return n * 60 elif unit.startswith('s'): return n else: raise ValueError("Invalid suffix %s" % unit) ############################################################################ # set_path: ############################################################################ def set_path(command, default=None): """ find the location of a specified command. if a default is supplied and it works, we use it; otherwise we search PATH for a match. :param command: string with a command to look for in the path :param default: default location to use :return: detected location for the desired command """ fpath = default if not fpath or not os.path.isfile(fpath) or not os.access(fpath, os.X_OK): path = os.environ["PATH"] if not path: path = os.path.defpath for directory in path.split(os.pathsep): fpath = os.path.join(directory, command) if os.path.isfile(fpath) and os.access(fpath, os.X_OK): break fpath = None return fpath ############################################################################ # parse_args: ############################################################################ def parse_args(): """Read command line arguments, set global 'args' structure""" compilezone = set_path('named-compilezone', os.path.join(utils.prefix('sbin'), 'named-compilezone')) parser = argparse.ArgumentParser(description=prog + ': checks future ' + 'DNSKEY coverage for a zone') parser.add_argument('zone', type=str, nargs='*', default=None, help='zone(s) to check' + '(default: all zones in the directory)') parser.add_argument('-K', dest='path', default='.', type=str, help='a directory containing keys to process', metavar='dir') parser.add_argument('-f', dest='filename', type=str, help='zone master file', metavar='file') parser.add_argument('-m', dest='maxttl', type=str, help='the longest TTL in the zone(s)', metavar='time') parser.add_argument('-d', dest='keyttl', type=str, help='the DNSKEY TTL', metavar='time') parser.add_argument('-r', dest='resign', default='1944000', type=str, help='the RRSIG refresh interval ' 'in seconds [default: 22.5 days]', metavar='time') parser.add_argument('-c', dest='compilezone', default=compilezone, type=str, help='path to \'named-compilezone\'', metavar='path') parser.add_argument('-l', dest='checklimit', type=str, default='0', help='Length of time to check for ' 'DNSSEC coverage [default: 0 (unlimited)]', metavar='time') parser.add_argument('-z', dest='no_ksk', action='store_true', default=False, help='Only check zone-signing keys (ZSKs)') parser.add_argument('-k', dest='no_zsk', action='store_true', default=False, help='Only check key-signing keys (KSKs)') parser.add_argument('-D', '--debug', dest='debug_mode', action='store_true', default=False, help='Turn on debugging output') parser.add_argument('-v', '--version', action='version', version=utils.version) args = parser.parse_args() if args.no_zsk and args.no_ksk: fatal("ERROR: -z and -k cannot be used together.") elif args.no_zsk or args.no_ksk: args.keytype = "KSK" if args.no_zsk else "ZSK" else: args.keytype = None if args.filename and len(args.zone) > 1: fatal("ERROR: -f can only be used with one zone.") # strip trailing dots if any args.zone = [x[:-1] if (len(x) > 1 and x[-1] == '.') else x for x in args.zone] # convert from time arguments to seconds try: if args.maxttl: m = parse_time(args.maxttl) args.maxttl = m except ValueError: pass try: if args.keyttl: k = parse_time(args.keyttl) args.keyttl = k except ValueError: pass try: if args.resign: r = parse_time(args.resign) args.resign = r except ValueError: pass try: if args.checklimit: lim = args.checklimit r = parse_time(args.checklimit) if r == 0: args.checklimit = None else: args.checklimit = time.time() + r except ValueError: pass # if we've got the values we need from the command line, stop now if args.maxttl and args.keyttl: return args # load keyttl and maxttl data from zonefile if args.zone and args.filename: try: zone = keyzone(args.zone[0], args.filename, args.compilezone) args.maxttl = args.maxttl or zone.maxttl args.keyttl = args.maxttl or zone.keyttl except Exception as e: print("Unable to load zone data from %s: " % args.filename, e) if not args.maxttl: output("WARNING: Maximum TTL value was not specified. Using 1 week\n" "\t (604800 seconds); re-run with the -m option to get more\n" "\t accurate results.") args.maxttl = 604800 return args ############################################################################ # Main ############################################################################ def main(): args = parse_args() print("PHASE 1--Loading keys to check for internal timing problems") try: kd = keydict(path=args.path, zones=args.zone, keyttl=args.keyttl) except Exception as e: fatal('ERROR: Unable to build key dictionary: ' + str(e)) for key in kd: key.check_prepub(output) if key.sep: key.check_postpub(output) else: key.check_postpub(output, args.maxttl + args.resign) output("PHASE 2--Scanning future key events for coverage failures") vreset() try: elist = eventlist(kd) except Exception as e: fatal('ERROR: Unable to build event list: ' + str(e)) errors = False if not args.zone: if not elist.coverage(None, args.keytype, args.checklimit, output): errors = True else: for zone in args.zone: try: if not elist.coverage(zone, args.keytype, args.checklimit, output): errors = True except: output('ERROR: Coverage check failed for zone ' + zone) sys.exit(1 if errors else 0) PK{ 1]=2g2g policy.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ import re import ply.lex as lex import ply.yacc as yacc from string import * from copy import copy ############################################################################ # PolicyLex: a lexer for the policy file syntax. ############################################################################ class PolicyLex: reserved = ('POLICY', 'ALGORITHM_POLICY', 'ZONE', 'ALGORITHM', 'DIRECTORY', 'KEYTTL', 'KEY_SIZE', 'ROLL_PERIOD', 'PRE_PUBLISH', 'POST_PUBLISH', 'COVERAGE', 'STANDBY', 'NONE') tokens = reserved + ('DATESUFFIX', 'KEYTYPE', 'ALGNAME', 'STR', 'QSTRING', 'NUMBER', 'LBRACE', 'RBRACE', 'SEMI') reserved_map = {} t_ignore = ' \t' t_ignore_olcomment = r'(//|\#).*' t_LBRACE = r'\{' t_RBRACE = r'\}' t_SEMI = r';'; def t_newline(self, t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_comment(self, t): r'/\*(.|\n)*?\*/' t.lexer.lineno += t.value.count('\n') def t_DATESUFFIX(self, t): r'(?i)(?<=[0-9 \t])(y(?:ears|ear|ea|e)?|mo(?:nths|nth|nt|n)?|w(?:eeks|eek|ee|e)?|d(?:ays|ay|a)?|h(?:ours|our|ou|o)?|mi(?:nutes|nute|nut|nu|n)?|s(?:econds|econd|econ|eco|ec|e)?)\b' t.value = re.match(r'(?i)(y|mo|w|d|h|mi|s)([a-z]*)', t.value).group(1).lower() return t def t_KEYTYPE(self, t): r'(?i)\b(KSK|ZSK)\b' t.value = t.value.upper() return t def t_ALGNAME(self, t): r'(?i)\b(RSAMD5|DH|DSA|NSEC3DSA|ECC|RSASHA1|NSEC3RSASHA1|RSASHA256|RSASHA512|ECCGOST|ECDSAP256SHA256|ECDSAP384SHA384|ED25519|ED448)\b' t.value = t.value.upper() return t def t_STR(self, t): r'[A-Za-z._-][\w._-]*' t.type = self.reserved_map.get(t.value, "STR") return t def t_QSTRING(self, t): r'"([^"\n]|(\\"))*"' t.type = self.reserved_map.get(t.value, "QSTRING") t.value = t.value[1:-1] return t def t_NUMBER(self, t): r'\d+' t.value = int(t.value) return t def t_error(self, t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) def __init__(self, **kwargs): if 'maketrans' in dir(str): trans = str.maketrans('_', '-') else: trans = maketrans('_', '-') for r in self.reserved: self.reserved_map[r.lower().translate(trans)] = r self.lexer = lex.lex(object=self, **kwargs) def test(self, text): self.lexer.input(text) while True: t = self.lexer.token() if not t: break print(t) ############################################################################ # Policy: this object holds a set of DNSSEC policy settings. ############################################################################ class Policy: is_zone = False is_alg = False is_constructed = False ksk_rollperiod = None zsk_rollperiod = None ksk_prepublish = None zsk_prepublish = None ksk_postpublish = None zsk_postpublish = None ksk_keysize = None zsk_keysize = None ksk_standby = None zsk_standby = None keyttl = None coverage = None directory = None valid_key_sz_per_algo = {'DSA': [512, 1024], 'NSEC3DSA': [512, 1024], 'RSAMD5': [512, 4096], 'RSASHA1': [512, 4096], 'NSEC3RSASHA1': [512, 4096], 'RSASHA256': [512, 4096], 'RSASHA512': [512, 4096], 'ECCGOST': None, 'ECDSAP256SHA256': None, 'ECDSAP384SHA384': None, 'ED25519': None, 'ED448': None} def __init__(self, name=None, algorithm=None, parent=None): self.name = name self.algorithm = algorithm self.parent = parent pass def __repr__(self): return ("%spolicy %s:\n" "\tinherits %s\n" "\tdirectory %s\n" "\talgorithm %s\n" "\tcoverage %s\n" "\tksk_keysize %s\n" "\tzsk_keysize %s\n" "\tksk_rollperiod %s\n" "\tzsk_rollperiod %s\n" "\tksk_prepublish %s\n" "\tksk_postpublish %s\n" "\tzsk_prepublish %s\n" "\tzsk_postpublish %s\n" "\tksk_standby %s\n" "\tzsk_standby %s\n" "\tkeyttl %s\n" % ((self.is_constructed and 'constructed ' or \ self.is_zone and 'zone ' or \ self.is_alg and 'algorithm ' or ''), self.name or 'UNKNOWN', self.parent and self.parent.name or 'None', self.directory and ('"' + str(self.directory) + '"') or 'None', self.algorithm or 'None', self.coverage and str(self.coverage) or 'None', self.ksk_keysize and str(self.ksk_keysize) or 'None', self.zsk_keysize and str(self.zsk_keysize) or 'None', self.ksk_rollperiod and str(self.ksk_rollperiod) or 'None', self.zsk_rollperiod and str(self.zsk_rollperiod) or 'None', self.ksk_prepublish and str(self.ksk_prepublish) or 'None', self.ksk_postpublish and str(self.ksk_postpublish) or 'None', self.zsk_prepublish and str(self.zsk_prepublish) or 'None', self.zsk_postpublish and str(self.zsk_postpublish) or 'None', self.ksk_standby and str(self.ksk_standby) or 'None', self.zsk_standby and str(self.zsk_standby) or 'None', self.keyttl and str(self.keyttl) or 'None')) def __verify_size(self, key_size, size_range): return (size_range[0] <= key_size <= size_range[1]) def get_name(self): return self.name def constructed(self): return self.is_constructed def validate(self): """ Check if the values in the policy make sense :return: True/False if the policy passes validation """ if self.ksk_rollperiod and \ self.ksk_prepublish is not None and \ self.ksk_prepublish > self.ksk_rollperiod: print(self.ksk_rollperiod) return (False, ('KSK pre-publish period (%d) exceeds rollover period %d' % (self.ksk_prepublish, self.ksk_rollperiod))) if self.ksk_rollperiod and \ self.ksk_postpublish is not None and \ self.ksk_postpublish > self.ksk_rollperiod: return (False, ('KSK post-publish period (%d) exceeds rollover period %d' % (self.ksk_postpublish, self.ksk_rollperiod))) if self.zsk_rollperiod and \ self.zsk_prepublish is not None and \ self.zsk_prepublish >= self.zsk_rollperiod: return (False, ('ZSK pre-publish period (%d) exceeds rollover period %d' % (self.zsk_prepublish, self.zsk_rollperiod))) if self.zsk_rollperiod and \ self.zsk_postpublish is not None and \ self.zsk_postpublish >= self.zsk_rollperiod: return (False, ('ZSK post-publish period (%d) exceeds rollover period %d' % (self.zsk_postpublish, self.zsk_rollperiod))) if self.ksk_rollperiod and \ self.ksk_prepublish and self.ksk_postpublish and \ self.ksk_prepublish + self.ksk_postpublish >= self.ksk_rollperiod: return (False, (('KSK pre/post-publish periods (%d/%d) ' + 'combined exceed rollover period %d') % (self.ksk_prepublish, self.ksk_postpublish, self.ksk_rollperiod))) if self.zsk_rollperiod and \ self.zsk_prepublish and self.zsk_postpublish and \ self.zsk_prepublish + self.zsk_postpublish >= self.zsk_rollperiod: return (False, (('ZSK pre/post-publish periods (%d/%d) ' + 'combined exceed rollover period %d') % (self.zsk_prepublish, self.zsk_postpublish, self.zsk_rollperiod))) if self.algorithm is not None: # Validate the key size key_sz_range = self.valid_key_sz_per_algo.get(self.algorithm) if key_sz_range is not None: # Verify KSK if not self.__verify_size(self.ksk_keysize, key_sz_range): return False, 'KSK key size %d outside valid range %s' \ % (self.ksk_keysize, key_sz_range) # Verify ZSK if not self.__verify_size(self.zsk_keysize, key_sz_range): return False, 'ZSK key size %d outside valid range %s' \ % (self.zsk_keysize, key_sz_range) # Specific check for DSA keys if self.algorithm in ['DSA', 'NSEC3DSA'] and \ self.ksk_keysize % 64 != 0: return False, \ ('KSK key size %d not divisible by 64 ' + 'as required for DSA') % self.ksk_keysize if self.algorithm in ['DSA', 'NSEC3DSA'] and \ self.zsk_keysize % 64 != 0: return False, \ ('ZSK key size %d not divisible by 64 ' + 'as required for DSA') % self.zsk_keysize if self.algorithm in ['ECCGOST', \ 'ECDSAP256SHA256', \ 'ECDSAP384SHA384', \ 'ED25519', \ 'ED448']: self.ksk_keysize = None self.zsk_keysize = None return True, '' ############################################################################ # dnssec_policy: # This class reads a dnssec.policy file and creates a dictionary of # DNSSEC policy rules from which a policy for a specific zone can # be generated. ############################################################################ class PolicyException(Exception): pass class dnssec_policy: alg_policy = {} named_policy = {} zone_policy = {} current = None filename = None initial = True def __init__(self, filename=None, **kwargs): self.plex = PolicyLex() self.tokens = self.plex.tokens if 'debug' not in kwargs: kwargs['debug'] = False if 'write_tables' not in kwargs: kwargs['write_tables'] = False self.parser = yacc.yacc(module=self, **kwargs) # set defaults self.setup('''policy global { algorithm rsasha256; key-size ksk 2048; key-size zsk 2048; roll-period ksk 0; roll-period zsk 1y; pre-publish ksk 1mo; pre-publish zsk 1mo; post-publish ksk 1mo; post-publish zsk 1mo; standby ksk 0; standby zsk 0; keyttl 1h; coverage 6mo; }; policy default { policy global; };''') p = Policy() p.algorithm = None p.is_alg = True p.ksk_keysize = 2048; p.zsk_keysize = 2048; # set default algorithm policies # these need a lower default key size: self.alg_policy['DSA'] = copy(p) self.alg_policy['DSA'].algorithm = "DSA" self.alg_policy['DSA'].name = "DSA" self.alg_policy['DSA'].ksk_keysize = 1024; self.alg_policy['NSEC3DSA'] = copy(p) self.alg_policy['NSEC3DSA'].algorithm = "NSEC3DSA" self.alg_policy['NSEC3DSA'].name = "NSEC3DSA" self.alg_policy['NSEC3DSA'].ksk_keysize = 1024; # these can use default settings self.alg_policy['RSAMD5'] = copy(p) self.alg_policy['RSAMD5'].algorithm = "RSAMD5" self.alg_policy['RSAMD5'].name = "RSAMD5" self.alg_policy['RSASHA1'] = copy(p) self.alg_policy['RSASHA1'].algorithm = "RSASHA1" self.alg_policy['RSASHA1'].name = "RSASHA1" self.alg_policy['NSEC3RSASHA1'] = copy(p) self.alg_policy['NSEC3RSASHA1'].algorithm = "NSEC3RSASHA1" self.alg_policy['NSEC3RSASHA1'].name = "NSEC3RSASHA1" self.alg_policy['RSASHA256'] = copy(p) self.alg_policy['RSASHA256'].algorithm = "RSASHA256" self.alg_policy['RSASHA256'].name = "RSASHA256" self.alg_policy['RSASHA512'] = copy(p) self.alg_policy['RSASHA512'].algorithm = "RSASHA512" self.alg_policy['RSASHA512'].name = "RSASHA512" self.alg_policy['ECCGOST'] = copy(p) self.alg_policy['ECCGOST'].algorithm = "ECCGOST" self.alg_policy['ECCGOST'].name = "ECCGOST" self.alg_policy['ECDSAP256SHA256'] = copy(p) self.alg_policy['ECDSAP256SHA256'].algorithm = "ECDSAP256SHA256" self.alg_policy['ECDSAP256SHA256'].name = "ECDSAP256SHA256" self.alg_policy['ECDSAP256SHA256'].ksk_keysize = None; self.alg_policy['ECDSAP256SHA256'].zsk_keysize = None; self.alg_policy['ECDSAP384SHA384'] = copy(p) self.alg_policy['ECDSAP384SHA384'].algorithm = "ECDSAP384SHA384" self.alg_policy['ECDSAP384SHA384'].name = "ECDSAP384SHA384" self.alg_policy['ECDSAP384SHA384'].ksk_keysize = None; self.alg_policy['ECDSAP384SHA384'].zsk_keysize = None; self.alg_policy['ED25519'] = copy(p) self.alg_policy['ED25519'].algorithm = "ED25519" self.alg_policy['ED25519'].name = "ED25519" self.alg_policy['ED25519'].ksk_keysize = None; self.alg_policy['ED25519'].zsk_keysize = None; self.alg_policy['ED448'] = copy(p) self.alg_policy['ED448'].algorithm = "ED448" self.alg_policy['ED448'].name = "ED448" self.alg_policy['ED448'].ksk_keysize = None; self.alg_policy['ED448'].zsk_keysize = None; if filename: self.load(filename) def load(self, filename): self.filename = filename self.initial = True with open(filename) as f: text = f.read() self.plex.lexer.lineno = 0 self.parser.parse(text) self.filename = None def setup(self, text): self.initial = True self.plex.lexer.lineno = 0 self.parser.parse(text) def policy(self, zone, **kwargs): z = zone.lower() p = None if z in self.zone_policy: p = self.zone_policy[z] if p is None: p = copy(self.named_policy['default']) p.name = zone p.is_constructed = True if p.algorithm is None: parent = p.parent or self.named_policy['default'] while parent and not parent.algorithm: parent = parent.parent p.algorithm = parent and parent.algorithm or None if p.algorithm in self.alg_policy: ap = self.alg_policy[p.algorithm] else: raise PolicyException('algorithm not found') if p.directory is None: parent = p.parent or self.named_policy['default'] while parent is not None and not parent.directory: parent = parent.parent p.directory = parent and parent.directory if p.coverage is None: parent = p.parent or self.named_policy['default'] while parent and not parent.coverage: parent = parent.parent p.coverage = parent and parent.coverage or ap.coverage if p.ksk_keysize is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.ksk_keysize: parent = parent.parent p.ksk_keysize = parent and parent.ksk_keysize or ap.ksk_keysize if p.zsk_keysize is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.zsk_keysize: parent = parent.parent p.zsk_keysize = parent and parent.zsk_keysize or ap.zsk_keysize if p.ksk_rollperiod is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.ksk_rollperiod: parent = parent.parent p.ksk_rollperiod = parent and \ parent.ksk_rollperiod or ap.ksk_rollperiod if p.zsk_rollperiod is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.zsk_rollperiod: parent = parent.parent p.zsk_rollperiod = parent and \ parent.zsk_rollperiod or ap.zsk_rollperiod if p.ksk_prepublish is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.ksk_prepublish: parent = parent.parent p.ksk_prepublish = parent and \ parent.ksk_prepublish or ap.ksk_prepublish if p.zsk_prepublish is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.zsk_prepublish: parent = parent.parent p.zsk_prepublish = parent and \ parent.zsk_prepublish or ap.zsk_prepublish if p.ksk_postpublish is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.ksk_postpublish: parent = parent.parent p.ksk_postpublish = parent and \ parent.ksk_postpublish or ap.ksk_postpublish if p.zsk_postpublish is None: parent = p.parent or self.named_policy['default'] while parent.parent and not parent.zsk_postpublish: parent = parent.parent p.zsk_postpublish = parent and \ parent.zsk_postpublish or ap.zsk_postpublish if p.keyttl is None: parent = p.parent or self.named_policy['default'] while parent is not None and not parent.keyttl: parent = parent.parent p.keyttl = parent and parent.keyttl if 'novalidate' not in kwargs or not kwargs['novalidate']: (valid, msg) = p.validate() if not valid: raise PolicyException(msg) return None return p def p_policylist(self, p): '''policylist : init policy | policylist policy''' pass def p_init(self, p): "init :" self.initial = False def p_policy(self, p): '''policy : alg_policy | zone_policy | named_policy''' pass def p_name(self, p): '''name : STR | KEYTYPE | DATESUFFIX''' p[0] = p[1] pass def p_domain(self, p): '''domain : STR | QSTRING | KEYTYPE | DATESUFFIX''' p[0] = p[1].strip() if not re.match(r'^[\w.-][\w.-]*$', p[0]): raise PolicyException('invalid domain') pass def p_new_policy(self, p): "new_policy :" self.current = Policy() def p_alg_policy(self, p): "alg_policy : ALGORITHM_POLICY ALGNAME new_policy alg_option_group SEMI" self.current.name = p[2] self.current.is_alg = True self.alg_policy[p[2]] = self.current pass def p_zone_policy(self, p): "zone_policy : ZONE domain new_policy policy_option_group SEMI" self.current.name = p[2].rstrip('.') self.current.is_zone = True self.zone_policy[p[2].rstrip('.').lower()] = self.current pass def p_named_policy(self, p): "named_policy : POLICY name new_policy policy_option_group SEMI" self.current.name = p[2] self.named_policy[p[2].lower()] = self.current pass def p_duration_1(self, p): "duration : NUMBER" p[0] = p[1] pass def p_duration_2(self, p): "duration : NONE" p[0] = None pass def p_duration_3(self, p): "duration : NUMBER DATESUFFIX" if p[2] == "y": p[0] = p[1] * 31536000 # year elif p[2] == "mo": p[0] = p[1] * 2592000 # month elif p[2] == "w": p[0] = p[1] * 604800 # week elif p[2] == "d": p[0] = p[1] * 86400 # day elif p[2] == "h": p[0] = p[1] * 3600 # hour elif p[2] == "mi": p[0] = p[1] * 60 # minute elif p[2] == "s": p[0] = p[1] # second else: raise PolicyException('invalid duration') def p_policy_option_group(self, p): "policy_option_group : LBRACE policy_option_list RBRACE" pass def p_policy_option_list(self, p): '''policy_option_list : policy_option SEMI | policy_option_list policy_option SEMI''' pass def p_policy_option(self, p): '''policy_option : parent_option | directory_option | coverage_option | rollperiod_option | prepublish_option | postpublish_option | keysize_option | algorithm_option | keyttl_option | standby_option''' pass def p_alg_option_group(self, p): "alg_option_group : LBRACE alg_option_list RBRACE" pass def p_alg_option_list(self, p): '''alg_option_list : alg_option SEMI | alg_option_list alg_option SEMI''' pass def p_alg_option(self, p): '''alg_option : coverage_option | rollperiod_option | prepublish_option | postpublish_option | keyttl_option | keysize_option | standby_option''' pass def p_parent_option(self, p): "parent_option : POLICY name" self.current.parent = self.named_policy[p[2].lower()] def p_directory_option(self, p): "directory_option : DIRECTORY QSTRING" self.current.directory = p[2] def p_coverage_option(self, p): "coverage_option : COVERAGE duration" self.current.coverage = p[2] def p_rollperiod_option(self, p): "rollperiod_option : ROLL_PERIOD KEYTYPE duration" if p[2] == "KSK": self.current.ksk_rollperiod = p[3] else: self.current.zsk_rollperiod = p[3] def p_prepublish_option(self, p): "prepublish_option : PRE_PUBLISH KEYTYPE duration" if p[2] == "KSK": self.current.ksk_prepublish = p[3] else: self.current.zsk_prepublish = p[3] def p_postpublish_option(self, p): "postpublish_option : POST_PUBLISH KEYTYPE duration" if p[2] == "KSK": self.current.ksk_postpublish = p[3] else: self.current.zsk_postpublish = p[3] def p_keysize_option(self, p): "keysize_option : KEY_SIZE KEYTYPE NUMBER" if p[2] == "KSK": self.current.ksk_keysize = p[3] else: self.current.zsk_keysize = p[3] def p_standby_option(self, p): "standby_option : STANDBY KEYTYPE NUMBER" if p[2] == "KSK": self.current.ksk_standby = p[3] else: self.current.zsk_standby = p[3] def p_keyttl_option(self, p): "keyttl_option : KEYTTL duration" self.current.keyttl = p[2] def p_algorithm_option(self, p): "algorithm_option : ALGORITHM ALGNAME" self.current.algorithm = p[2] def p_error(self, p): if p: print("%s%s%d:syntax error near '%s'" % (self.filename or "", ":" if self.filename else "", p.lineno, p.value)) else: if not self.initial: raise PolicyException("%s%s%d:unexpected end of input" % (self.filename or "", ":" if self.filename else "", p and p.lineno or 0)) if __name__ == "__main__": import sys if sys.argv[1] == "lex": file = open(sys.argv[2]) text = file.read() file.close() plex = PolicyLex(debug=1) plex.test(text) elif sys.argv[1] == "parse": try: pp = dnssec_policy(sys.argv[2], write_tables=True, debug=True) print(pp.named_policy['default']) print(pp.policy("nonexistent.zone")) except Exception as e: print(e.args[0]) PK{ 1]Snտ keyzone.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ import os import sys import re from subprocess import Popen, PIPE ######################################################################## # Exceptions ######################################################################## class KeyZoneException(Exception): pass ######################################################################## # class keyzone ######################################################################## class keyzone: """reads a zone file to find data relevant to keys""" def __init__(self, name, filename, czpath): self.maxttl = None self.keyttl = None if not name: return if not czpath or not os.path.isfile(czpath) \ or not os.access(czpath, os.X_OK): raise KeyZoneException('"named-compilezone" not found') return maxttl = keyttl = None fp, _ = Popen([czpath, "-o", "-", name, filename], stdout=PIPE, stderr=PIPE).communicate() for line in fp.splitlines(): if type(line) is not str: line = line.decode('ascii') if re.search('^[:space:]*;', line): continue fields = line.split() if not maxttl or int(fields[1]) > maxttl: maxttl = int(fields[1]) if fields[3] == "DNSKEY": keyttl = int(fields[1]) self.keyttl = keyttl self.maxttl = maxttl PK{ 1]A eventlist.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ from collections import defaultdict from .dnskey import * from .keydict import * from .keyevent import * class eventlist: _K = defaultdict(lambda: defaultdict(list)) _Z = defaultdict(lambda: defaultdict(list)) _zones = set() _kdict = None def __init__(self, kdict): properties = ["SyncPublish", "Publish", "SyncDelete", "Activate", "Inactive", "Delete"] self._kdict = kdict for zone in kdict.zones(): self._zones.add(zone) for alg, keys in kdict[zone].items(): for k in keys.values(): for prop in properties: t = k.gettime(prop) if not t: continue e = keyevent(prop, k, t) if k.sep: self._K[zone][alg].append(e) else: self._Z[zone][alg].append(e) self._K[zone][alg] = sorted(self._K[zone][alg], key=lambda event: event.when) self._Z[zone][alg] = sorted(self._Z[zone][alg], key=lambda event: event.when) # scan events per zone, algorithm, and key type, in order of # occurrence, noting inconsistent states when found def coverage(self, zone, keytype, until, output = None): def noop(*args, **kwargs): pass if not output: output = noop no_zsk = True if (keytype and keytype == "KSK") else False no_ksk = True if (keytype and keytype == "ZSK") else False kok = zok = True found = False if zone and not zone in self._zones: output("ERROR: No key events found for %s" % zone) return False if zone: found = True if not no_ksk: kok = self.checkzone(zone, "KSK", until, output) if not no_zsk: zok = self.checkzone(zone, "ZSK", until, output) else: for z in self._zones: if not no_ksk and z in self._K.keys(): found = True kok = self.checkzone(z, "KSK", until, output) if not no_zsk and z in self._Z.keys(): found = True zok = self.checkzone(z, "ZSK", until, output) if not found: output("ERROR: No key events found") return False return (kok and zok) def checkzone(self, zone, keytype, until, output): allok = True if keytype == "KSK": kz = self._K[zone] else: kz = self._Z[zone] for alg in kz.keys(): output("Checking scheduled %s events for zone %s, " "algorithm %s..." % (keytype, zone, dnskey.algstr(alg))) ok = eventlist.checkset(kz[alg], keytype, until, output) if ok: output("No errors found") allok = allok and ok return allok @staticmethod def showset(eventset, output): if not eventset: return output(" " + eventset[0].showtime() + ":", skip=False) for event in eventset: output(" %s: %s" % (event.what, repr(event.key)), skip=False) @staticmethod def checkset(eventset, keytype, until, output): groups = list() group = list() # collect up all events that have the same time eventsfound = False for event in eventset: # we found an event eventsfound = True # add event to current group if (not group or group[0].when == event.when): group.append(event) # if we're at the end of the list, we're done. if # we've found an event with a later time, start a new group if (group[0].when != event.when): groups.append(group) group = list() group.append(event) if group: groups.append(group) if not eventsfound: output("ERROR: No %s events found" % keytype) return False active = published = None for group in groups: if (until and calendar.timegm(group[0].when) > until): output("Ignoring events after %s" % time.strftime("%a %b %d %H:%M:%S UTC %Y", time.gmtime(until))) return True for event in group: (active, published) = event.status(active, published) eventlist.showset(group, output) # and then check for inconsistencies: if not active: output("ERROR: No %s's are active after this event" % keytype) return False elif not published: output("ERROR: No %s's are published after this event" % keytype) return False elif not published.intersection(active): output("ERROR: No %s's are both active and published " "after this event" % keytype) return False return True PK{ 1]!utils.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ import os # These routines permit platform-independent location of BIND 9 tools if os.name == 'nt': import win32con import win32api def prefix(bindir=''): if os.name != 'nt': return os.path.join('/usr', bindir) hklm = win32con.HKEY_LOCAL_MACHINE bind_subkey = "Software\\ISC\\BIND" sam = win32con.KEY_READ h_key = None key_found = True # can fail if the registry redirected for 32/64 bits try: h_key = win32api.RegOpenKeyEx(hklm, bind_subkey, 0, sam) except: key_found = False # retry for 32 bit python with 64 bit bind9 if not key_found: key_found = True sam64 = sam | win32con.KEY_WOW64_64KEY try: h_key = win32api.RegOpenKeyEx(hklm, bind_subkey, 0, sam64) except: key_found = False # retry 64 bit python with 32 bit bind9 if not key_found: key_found = True sam32 = sam | win32con.KEY_WOW64_32KEY try: h_key = win32api.RegOpenKeyEx(hklm, bind_subkey, 0, sam32) except: key_found = False if key_found: try: (named_base, _) = win32api.RegQueryValueEx(h_key, "InstallDir") except: key_found = False win32api.RegCloseKey(h_key) if key_found: return os.path.join(named_base, bindir) return os.path.join(win32api.GetSystemDirectory(), bindir) def shellquote(s): if os.name == 'nt': return '"' + s.replace('"', '"\\"') + '"' return "'" + s.replace("'", "'\\''") + "'" version = '9.11.36-RedHat-9.11.36-16.el8_10.14' if os.name != 'nt': sysconfdir = '/etc' else: sysconfdir = prefix('etc') PK{ 1]~Q3++rndc.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ ############################################################################ # rndc.py # This module implements the RNDC control protocol. ############################################################################ from collections import OrderedDict import time import struct import hashlib import hmac import base64 import random import socket class rndc(object): """RNDC protocol client library""" __algos = {'md5': 157, 'sha1': 161, 'sha224': 162, 'sha256': 163, 'sha384': 164, 'sha512': 165} def __init__(self, host, algo, secret): """Creates a persistent connection to RNDC and logs in host - (ip, port) tuple algo - HMAC algorithm: one of md5, sha1, sha224, sha256, sha384, sha512 (with optional prefix 'hmac-') secret - HMAC secret, base64 encoded""" self.host = host algo = algo.lower() if algo.startswith('hmac-'): algo = algo[5:] self.algo = algo self.hlalgo = getattr(hashlib, algo) self.secret = base64.b64decode(secret) self.ser = random.randint(0, 1 << 24) self.nonce = None self.__connect_login() def call(self, cmd): """Call a RNDC command, all parsing is done on the server side cmd - a complete string with a command (eg 'reload zone example.com') """ return dict(self.__command(type=cmd)['_data']) def __serialize_dict(self, data, ignore_auth=False): rv = bytearray() for k, v in data.items(): if ignore_auth and k == '_auth': continue rv += struct.pack('B', len(k)) + k.encode('ascii') if type(v) == str: rv += struct.pack('>BI', 1, len(v)) + v.encode('ascii') elif type(v) == bytes: rv += struct.pack('>BI', 1, len(v)) + v elif type(v) == bytearray: rv += struct.pack('>BI', 1, len(v)) + v elif type(v) == OrderedDict: sd = self.__serialize_dict(v) rv += struct.pack('>BI', 2, len(sd)) + sd else: raise NotImplementedError('Cannot serialize element of type %s' % type(v)) return rv def __prep_message(self, *args, **kwargs): self.ser += 1 now = int(time.time()) data = OrderedDict(*args, **kwargs) d = OrderedDict() d['_auth'] = OrderedDict() d['_ctrl'] = OrderedDict() d['_ctrl']['_ser'] = str(self.ser) d['_ctrl']['_tim'] = str(now) d['_ctrl']['_exp'] = str(now+60) if self.nonce is not None: d['_ctrl']['_nonce'] = self.nonce d['_data'] = data msg = self.__serialize_dict(d, ignore_auth=True) hash = hmac.new(self.secret, msg, self.hlalgo).digest() bhash = base64.b64encode(hash) if self.algo == 'md5': d['_auth']['hmd5'] = struct.pack('22s', bhash) else: d['_auth']['hsha'] = bytearray(struct.pack('B88s', self.__algos[self.algo], bhash)) msg = self.__serialize_dict(d) msg = struct.pack('>II', len(msg) + 4, 1) + msg return msg def __verify_msg(self, msg): if self.nonce is not None and msg['_ctrl']['_nonce'] != self.nonce: return False if self.algo == 'md5': bhash = msg['_auth']['hmd5'] else: bhash = msg['_auth']['hsha'][1:] if type(bhash) == bytes: bhash = bhash.decode('ascii') bhash += '=' * (4 - (len(bhash) % 4)) remote_hash = base64.b64decode(bhash) my_msg = self.__serialize_dict(msg, ignore_auth=True) my_hash = hmac.new(self.secret, my_msg, self.hlalgo).digest() return (my_hash == remote_hash) def __command(self, *args, **kwargs): msg = self.__prep_message(*args, **kwargs) sent = self.socket.send(msg) if sent != len(msg): raise IOError("Cannot send the message") header = self.socket.recv(8) if len(header) != 8: # What should we throw here? Bad auth can cause this... raise IOError("Can't read response header") length, version = struct.unpack('>II', header) if version != 1: raise NotImplementedError('Wrong message version %d' % version) # it includes the header length -= 4 data = self.socket.recv(length, socket.MSG_WAITALL) if len(data) != length: raise IOError("Can't read response data") if type(data) == str: data = bytearray(data) msg = self.__parse_message(data) if not self.__verify_msg(msg): raise IOError("Authentication failure") return msg def __connect_login(self): self.socket = socket.create_connection(self.host) self.nonce = None msg = self.__command(type='null') self.nonce = msg['_ctrl']['_nonce'] def __parse_element(self, input): pos = 0 labellen = input[pos] pos += 1 label = input[pos:pos+labellen].decode('ascii') pos += labellen type = input[pos] pos += 1 datalen = struct.unpack('>I', input[pos:pos+4])[0] pos += 4 data = input[pos:pos+datalen] pos += datalen rest = input[pos:] if type == 1: # raw binary value return label, data, rest elif type == 2: # dictionary d = OrderedDict() while len(data) > 0: ilabel, value, data = self.__parse_element(data) d[ilabel] = value return label, d, rest # TODO type 3 - list else: raise NotImplementedError('Unknown element type %d' % type) def __parse_message(self, input): rv = OrderedDict() hdata = None while len(input) > 0: label, value, input = self.__parse_element(input) rv[label] = value return rv PK{ 1]oެX}} parsetab.pynu[ # parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.8' _lr_method = 'LALR' _lr_signature = 'C2FE91AF256AF1CCEB499107DA2CFE7E' _lr_action_items = {'ALGORITHM_POLICY':([0,1,2,3,4,5,6,10,29,46,62,],[-3,7,7,-2,-4,-5,-6,-1,-15,-16,-17,]),'ZONE':([0,1,2,3,4,5,6,10,29,46,62,],[-3,8,8,-2,-4,-5,-6,-1,-15,-16,-17,]),'POLICY':([0,1,2,3,4,5,6,10,27,29,46,47,62,77,88,],[-3,9,9,-2,-4,-5,-6,-1,59,-15,-16,59,-17,-22,-23,]),'$end':([1,3,4,5,6,10,29,46,62,],[0,-2,-4,-5,-6,-1,-15,-16,-17,]),'ALGNAME':([7,61,],[11,80,]),'STR':([8,9,59,],[13,18,18,]),'QSTRING':([8,60,],[14,79,]),'KEYTYPE':([8,9,40,41,42,44,45,59,],[15,19,69,70,71,73,74,19,]),'DATESUFFIX':([8,9,59,67,],[16,20,20,82,]),'LBRACE':([11,12,13,14,15,16,17,18,19,20,21,22,23,],[-14,-14,-10,-11,-12,-13,-14,-7,-8,-9,25,27,27,]),'SEMI':([18,19,20,24,26,28,31,32,33,34,35,36,37,38,48,49,50,51,52,53,54,55,56,57,58,63,64,66,67,68,72,75,76,78,79,80,82,83,84,85,86,87,],[-7,-8,-9,29,46,62,65,-37,-38,-39,-40,-41,-42,-43,77,-24,-25,-26,-27,-28,-29,-30,-31,-32,-33,-34,81,-46,-18,-19,-52,-21,88,-44,-45,-53,-20,-47,-48,-49,-50,-51,]),'COVERAGE':([25,27,30,47,65,77,81,88,],[39,39,39,39,-35,-22,-36,-23,]),'ROLL_PERIOD':([25,27,30,47,65,77,81,88,],[40,40,40,40,-35,-22,-36,-23,]),'PRE_PUBLISH':([25,27,30,47,65,77,81,88,],[41,41,41,41,-35,-22,-36,-23,]),'POST_PUBLISH':([25,27,30,47,65,77,81,88,],[42,42,42,42,-35,-22,-36,-23,]),'KEYTTL':([25,27,30,47,65,77,81,88,],[43,43,43,43,-35,-22,-36,-23,]),'KEY_SIZE':([25,27,30,47,65,77,81,88,],[44,44,44,44,-35,-22,-36,-23,]),'STANDBY':([25,27,30,47,65,77,81,88,],[45,45,45,45,-35,-22,-36,-23,]),'DIRECTORY':([27,47,77,88,],[60,60,-22,-23,]),'ALGORITHM':([27,47,77,88,],[61,61,-22,-23,]),'RBRACE':([30,47,65,77,81,88,],[63,75,-35,-22,-36,-23,]),'NUMBER':([39,43,69,70,71,73,74,],[67,67,67,67,67,86,87,]),'NONE':([39,43,69,70,71,],[68,68,68,68,68,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'policylist':([0,],[1,]),'init':([0,],[2,]),'policy':([1,2,],[3,10,]),'alg_policy':([1,2,],[4,4,]),'zone_policy':([1,2,],[5,5,]),'named_policy':([1,2,],[6,6,]),'domain':([8,],[12,]),'name':([9,59,],[17,78,]),'new_policy':([11,12,17,],[21,22,23,]),'alg_option_group':([21,],[24,]),'policy_option_group':([22,23,],[26,28,]),'alg_option_list':([25,],[30,]),'alg_option':([25,30,],[31,64,]),'coverage_option':([25,27,30,47,],[32,51,32,51,]),'rollperiod_option':([25,27,30,47,],[33,52,33,52,]),'prepublish_option':([25,27,30,47,],[34,53,34,53,]),'postpublish_option':([25,27,30,47,],[35,54,35,54,]),'keyttl_option':([25,27,30,47,],[36,57,36,57,]),'keysize_option':([25,27,30,47,],[37,55,37,55,]),'standby_option':([25,27,30,47,],[38,58,38,58,]),'policy_option_list':([27,],[47,]),'policy_option':([27,47,],[48,76,]),'parent_option':([27,47,],[49,49,]),'directory_option':([27,47,],[50,50,]),'algorithm_option':([27,47,],[56,56,]),'duration':([39,43,69,70,71,],[66,72,83,84,85,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> policylist","S'",1,None,None,None), ('policylist -> init policy','policylist',2,'p_policylist','policy.py',523), ('policylist -> policylist policy','policylist',2,'p_policylist','policy.py',524), ('init -> ','init',0,'p_init','policy.py',528), ('policy -> alg_policy','policy',1,'p_policy','policy.py',532), ('policy -> zone_policy','policy',1,'p_policy','policy.py',533), ('policy -> named_policy','policy',1,'p_policy','policy.py',534), ('name -> STR','name',1,'p_name','policy.py',538), ('name -> KEYTYPE','name',1,'p_name','policy.py',539), ('name -> DATESUFFIX','name',1,'p_name','policy.py',540), ('domain -> STR','domain',1,'p_domain','policy.py',545), ('domain -> QSTRING','domain',1,'p_domain','policy.py',546), ('domain -> KEYTYPE','domain',1,'p_domain','policy.py',547), ('domain -> DATESUFFIX','domain',1,'p_domain','policy.py',548), ('new_policy -> ','new_policy',0,'p_new_policy','policy.py',555), ('alg_policy -> ALGORITHM_POLICY ALGNAME new_policy alg_option_group SEMI','alg_policy',5,'p_alg_policy','policy.py',559), ('zone_policy -> ZONE domain new_policy policy_option_group SEMI','zone_policy',5,'p_zone_policy','policy.py',566), ('named_policy -> POLICY name new_policy policy_option_group SEMI','named_policy',5,'p_named_policy','policy.py',573), ('duration -> NUMBER','duration',1,'p_duration_1','policy.py',579), ('duration -> NONE','duration',1,'p_duration_2','policy.py',584), ('duration -> NUMBER DATESUFFIX','duration',2,'p_duration_3','policy.py',589), ('policy_option_group -> LBRACE policy_option_list RBRACE','policy_option_group',3,'p_policy_option_group','policy.py',608), ('policy_option_list -> policy_option SEMI','policy_option_list',2,'p_policy_option_list','policy.py',612), ('policy_option_list -> policy_option_list policy_option SEMI','policy_option_list',3,'p_policy_option_list','policy.py',613), ('policy_option -> parent_option','policy_option',1,'p_policy_option','policy.py',617), ('policy_option -> directory_option','policy_option',1,'p_policy_option','policy.py',618), ('policy_option -> coverage_option','policy_option',1,'p_policy_option','policy.py',619), ('policy_option -> rollperiod_option','policy_option',1,'p_policy_option','policy.py',620), ('policy_option -> prepublish_option','policy_option',1,'p_policy_option','policy.py',621), ('policy_option -> postpublish_option','policy_option',1,'p_policy_option','policy.py',622), ('policy_option -> keysize_option','policy_option',1,'p_policy_option','policy.py',623), ('policy_option -> algorithm_option','policy_option',1,'p_policy_option','policy.py',624), ('policy_option -> keyttl_option','policy_option',1,'p_policy_option','policy.py',625), ('policy_option -> standby_option','policy_option',1,'p_policy_option','policy.py',626), ('alg_option_group -> LBRACE alg_option_list RBRACE','alg_option_group',3,'p_alg_option_group','policy.py',630), ('alg_option_list -> alg_option SEMI','alg_option_list',2,'p_alg_option_list','policy.py',634), ('alg_option_list -> alg_option_list alg_option SEMI','alg_option_list',3,'p_alg_option_list','policy.py',635), ('alg_option -> coverage_option','alg_option',1,'p_alg_option','policy.py',639), ('alg_option -> rollperiod_option','alg_option',1,'p_alg_option','policy.py',640), ('alg_option -> prepublish_option','alg_option',1,'p_alg_option','policy.py',641), ('alg_option -> postpublish_option','alg_option',1,'p_alg_option','policy.py',642), ('alg_option -> keyttl_option','alg_option',1,'p_alg_option','policy.py',643), ('alg_option -> keysize_option','alg_option',1,'p_alg_option','policy.py',644), ('alg_option -> standby_option','alg_option',1,'p_alg_option','policy.py',645), ('parent_option -> POLICY name','parent_option',2,'p_parent_option','policy.py',649), ('directory_option -> DIRECTORY QSTRING','directory_option',2,'p_directory_option','policy.py',653), ('coverage_option -> COVERAGE duration','coverage_option',2,'p_coverage_option','policy.py',657), ('rollperiod_option -> ROLL_PERIOD KEYTYPE duration','rollperiod_option',3,'p_rollperiod_option','policy.py',661), ('prepublish_option -> PRE_PUBLISH KEYTYPE duration','prepublish_option',3,'p_prepublish_option','policy.py',668), ('postpublish_option -> POST_PUBLISH KEYTYPE duration','postpublish_option',3,'p_postpublish_option','policy.py',675), ('keysize_option -> KEY_SIZE KEYTYPE NUMBER','keysize_option',3,'p_keysize_option','policy.py',682), ('standby_option -> STANDBY KEYTYPE NUMBER','standby_option',3,'p_standby_option','policy.py',689), ('keyttl_option -> KEYTTL duration','keyttl_option',2,'p_keyttl_option','policy.py',696), ('algorithm_option -> ALGORITHM ALGNAME','algorithm_option',2,'p_algorithm_option','policy.py',700), ] PK{ 1]WC @ @ dnskey.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ import os import time import calendar from subprocess import Popen, PIPE ######################################################################## # Class dnskey ######################################################################## class TimePast(Exception): def __init__(self, key, prop, value): super(TimePast, self).__init__('%s time for key %s (%d) is already past' % (prop, key, value)) class dnskey: """An individual DNSSEC key. Identified by path, name, algorithm, keyid. Contains a dictionary of metadata events.""" _PROPS = ('Created', 'Publish', 'Activate', 'Inactive', 'Delete', 'Revoke', 'DSPublish', 'SyncPublish', 'SyncDelete') _OPTS = (None, '-P', '-A', '-I', '-D', '-R', None, '-Psync', '-Dsync') _ALGNAMES = (None, 'RSAMD5', 'DH', 'DSA', 'ECC', 'RSASHA1', 'NSEC3DSA', 'NSEC3RSASHA1', 'RSASHA256', None, 'RSASHA512', None, 'ECCGOST', 'ECDSAP256SHA256', 'ECDSAP384SHA384', 'ED25519', 'ED448') def __init__(self, key, directory=None, keyttl=None): # this makes it possible to use algname as a class or instance method if isinstance(key, tuple) and len(key) == 3: self._dir = directory or '.' (name, alg, keyid) = key self.fromtuple(name, alg, keyid, keyttl) self._dir = directory or os.path.dirname(key) or '.' key = os.path.basename(key) (name, alg, keyid) = key.split('+') name = name[1:-1] alg = int(alg) keyid = int(keyid.split('.')[0]) self.fromtuple(name, alg, keyid, keyttl) def fromtuple(self, name, alg, keyid, keyttl): if name.endswith('.'): fullname = name name = name.rstrip('.') else: fullname = name + '.' keystr = "K%s+%03d+%05d" % (fullname, alg, keyid) key_file = self._dir + (self._dir and os.sep or '') + keystr + ".key" private_file = (self._dir + (self._dir and os.sep or '') + keystr + ".private") self.keystr = keystr self.name = name self.alg = int(alg) self.keyid = int(keyid) self.fullname = fullname kfp = open(key_file, "r") for line in kfp: if line[0] == ';': continue tokens = line.split() if not tokens: continue if tokens[1].lower() in ('in', 'ch', 'hs'): septoken = 3 self.ttl = keyttl else: septoken = 4 self.ttl = int(tokens[1]) if not keyttl else keyttl if (int(tokens[septoken]) & 0x1) == 1: self.sep = True else: self.sep = False kfp.close() pfp = open(private_file, "rU") self.metadata = dict() self._changed = dict() self._delete = dict() self._times = dict() self._fmttime = dict() self._timestamps = dict() self._original = dict() self._origttl = None for line in pfp: line = line.strip() if not line or line[0] in ('!#'): continue punctuation = [line.find(c) for c in ':= '] + [len(line)] found = min([pos for pos in punctuation if pos != -1]) name = line[:found].rstrip() value = line[found:].lstrip(":= ").rstrip() self.metadata[name] = value for prop in dnskey._PROPS: self._changed[prop] = False if prop in self.metadata: t = self.parsetime(self.metadata[prop]) self._times[prop] = t self._fmttime[prop] = self.formattime(t) self._timestamps[prop] = self.epochfromtime(t) self._original[prop] = self._timestamps[prop] else: self._times[prop] = None self._fmttime[prop] = None self._timestamps[prop] = None self._original[prop] = None pfp.close() def commit(self, settime_bin, **kwargs): quiet = kwargs.get('quiet', False) cmd = [] first = True if self._origttl is not None: cmd += ["-L", str(self.ttl)] for prop, opt in zip(dnskey._PROPS, dnskey._OPTS): if not opt or not self._changed[prop]: continue delete = False if prop in self._delete and self._delete[prop]: delete = True when = 'none' if delete else self._fmttime[prop] cmd += [opt, when] first = False if cmd: fullcmd = [settime_bin, "-K", self._dir] + cmd + [self.keystr,] if not quiet: print('# ' + ' '.join(fullcmd)) try: p = Popen(fullcmd, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() if stderr: raise Exception(str(stderr)) except Exception as e: raise Exception('unable to run %s: %s' % (settime_bin, str(e))) self._origttl = None for prop in dnskey._PROPS: self._original[prop] = self._timestamps[prop] self._changed[prop] = False @classmethod def generate(cls, keygen_bin, randomdev, keys_dir, name, alg, keysize, sep, ttl, publish=None, activate=None, **kwargs): quiet = kwargs.get('quiet', False) keygen_cmd = [keygen_bin, "-q", "-K", keys_dir, "-L", str(ttl)] if randomdev: keygen_cmd += ["-r", randomdev] if sep: keygen_cmd.append("-fk") if alg: keygen_cmd += ["-a", alg] if keysize: keygen_cmd += ["-b", str(keysize)] if publish: t = dnskey.timefromepoch(publish) keygen_cmd += ["-P", dnskey.formattime(t)] if activate: t = dnskey.timefromepoch(activate) keygen_cmd += ["-A", dnskey.formattime(activate)] keygen_cmd.append(name) if not quiet: print('# ' + ' '.join(keygen_cmd)) p = Popen(keygen_cmd, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() if stderr: raise Exception('unable to generate key: ' + str(stderr)) try: keystr = stdout.splitlines()[0].decode('ascii') newkey = dnskey(keystr, keys_dir, ttl) return newkey except Exception as e: raise Exception('unable to parse generated key: %s' % str(e)) def generate_successor(self, keygen_bin, randomdev, prepublish, **kwargs): quiet = kwargs.get('quiet', False) if not self.inactive(): raise Exception("predecessor key %s has no inactive date" % self) keygen_cmd = [keygen_bin, "-q", "-K", self._dir, "-S", self.keystr] if self.ttl: keygen_cmd += ["-L", str(self.ttl)] if randomdev: keygen_cmd += ["-r", randomdev] if prepublish: keygen_cmd += ["-i", str(prepublish)] if not quiet: print('# ' + ' '.join(keygen_cmd)) p = Popen(keygen_cmd, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() if stderr: raise Exception('unable to generate key: ' + stderr) try: keystr = stdout.splitlines()[0].decode('ascii') newkey = dnskey(keystr, self._dir, self.ttl) return newkey except: raise Exception('unable to generate successor for key %s' % self) @staticmethod def algstr(alg): name = None if alg in range(len(dnskey._ALGNAMES)): name = dnskey._ALGNAMES[alg] return name if name else ("%03d" % alg) @staticmethod def algnum(alg): if not alg: return None alg = alg.upper() try: return dnskey._ALGNAMES.index(alg) except ValueError: return None def algname(self, alg=None): return self.algstr(alg or self.alg) @staticmethod def timefromepoch(secs): return time.gmtime(secs) @staticmethod def parsetime(string): return time.strptime(string, "%Y%m%d%H%M%S") @staticmethod def epochfromtime(t): return calendar.timegm(t) @staticmethod def formattime(t): return time.strftime("%Y%m%d%H%M%S", t) def setmeta(self, prop, secs, now, **kwargs): force = kwargs.get('force', False) if self._timestamps[prop] == secs: return if self._original[prop] is not None and \ self._original[prop] < now and not force: raise TimePast(self, prop, self._original[prop]) if secs is None: self._changed[prop] = False \ if self._original[prop] is None else True self._delete[prop] = True self._timestamps[prop] = None self._times[prop] = None self._fmttime[prop] = None return t = self.timefromepoch(secs) self._timestamps[prop] = secs self._times[prop] = t self._fmttime[prop] = self.formattime(t) self._changed[prop] = False if \ self._original[prop] == self._timestamps[prop] else True def gettime(self, prop): return self._times[prop] def getfmttime(self, prop): return self._fmttime[prop] def gettimestamp(self, prop): return self._timestamps[prop] def created(self): return self._timestamps["Created"] def syncpublish(self): return self._timestamps["SyncPublish"] def setsyncpublish(self, secs, now=time.time(), **kwargs): self.setmeta("SyncPublish", secs, now, **kwargs) def publish(self): return self._timestamps["Publish"] def setpublish(self, secs, now=time.time(), **kwargs): self.setmeta("Publish", secs, now, **kwargs) def activate(self): return self._timestamps["Activate"] def setactivate(self, secs, now=time.time(), **kwargs): self.setmeta("Activate", secs, now, **kwargs) def revoke(self): return self._timestamps["Revoke"] def setrevoke(self, secs, now=time.time(), **kwargs): self.setmeta("Revoke", secs, now, **kwargs) def inactive(self): return self._timestamps["Inactive"] def setinactive(self, secs, now=time.time(), **kwargs): self.setmeta("Inactive", secs, now, **kwargs) def delete(self): return self._timestamps["Delete"] def setdelete(self, secs, now=time.time(), **kwargs): self.setmeta("Delete", secs, now, **kwargs) def syncdelete(self): return self._timestamps["SyncDelete"] def setsyncdelete(self, secs, now=time.time(), **kwargs): self.setmeta("SyncDelete", secs, now, **kwargs) def setttl(self, ttl): if ttl is None or self.ttl == ttl: return elif self._origttl is None: self._origttl = self.ttl self.ttl = ttl elif self._origttl == ttl: self._origttl = None self.ttl = ttl else: self.ttl = ttl def keytype(self): return ("KSK" if self.sep else "ZSK") def __str__(self): return ("%s/%s/%05d" % (self.name, self.algname(), self.keyid)) def __repr__(self): return ("%s/%s/%05d (%s)" % (self.name, self.algname(), self.keyid, ("KSK" if self.sep else "ZSK"))) def date(self): return (self.activate() or self.publish() or self.created()) # keys are sorted first by zone name, then by algorithm. within # the same name/algorithm, they are sorted according to their # 'date' value: the activation date if set, OR the publication # if set, OR the creation date. def __lt__(self, other): if self.name != other.name: return self.name < other.name if self.alg != other.alg: return self.alg < other.alg return self.date() < other.date() def check_prepub(self, output=None): def noop(*args, **kwargs): pass if not output: output = noop now = int(time.time()) a = self.activate() p = self.publish() if not a: return False if not p: if a > now: output("WARNING: Key %s is scheduled for\n" "\t activation but not for publication." % repr(self)) return False if p <= now and a <= now: return True if p == a: output("WARNING: %s is scheduled to be\n" "\t published and activated at the same time. This\n" "\t could result in a coverage gap if the zone was\n" "\t previously signed. Activation should be at least\n" "\t %s after publication." % (repr(self), dnskey.duration(self.ttl) or 'one DNSKEY TTL')) return True if a < p: output("WARNING: Key %s is active before it is published" % repr(self)) return False if self.ttl is not None and a - p < self.ttl: output("WARNING: Key %s is activated too soon\n" "\t after publication; this could result in coverage \n" "\t gaps due to resolver caches containing old data.\n" "\t Activation should be at least %s after\n" "\t publication." % (repr(self), dnskey.duration(self.ttl) or 'one DNSKEY TTL')) return False return True def check_postpub(self, output = None, timespan = None): def noop(*args, **kwargs): pass if output is None: output = noop if timespan is None: timespan = self.ttl if timespan is None: output("WARNING: Key %s using default TTL." % repr(self)) timespan = (60*60*24) now = time.time() d = self.delete() i = self.inactive() if not d: return False if not i: if d > now: output("WARNING: Key %s is scheduled for\n" "\t deletion but not for inactivation." % repr(self)) return False if d < now and i < now: return True if d < i: output("WARNING: Key %s is scheduled for\n" "\t deletion before inactivation." % repr(self)) return False if d - i < timespan: output("WARNING: Key %s scheduled for\n" "\t deletion too soon after deactivation; this may \n" "\t result in coverage gaps due to resolver caches\n" "\t containing old data. Deletion should be at least\n" "\t %s after inactivation." % (repr(self), dnskey.duration(timespan))) return False return True @staticmethod def duration(secs): if not secs: return None units = [("year", 60*60*24*365), ("month", 60*60*24*30), ("day", 60*60*24), ("hour", 60*60), ("minute", 60), ("second", 1)] output = [] for unit in units: v, secs = secs // unit[1], secs % unit[1] if v > 0: output.append("%d %s%s" % (v, unit[0], "s" if v > 1 else "")) return ", ".join(output) PK{ 1]`J __init__.pynu[############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. ############################################################################ __all__ = ['checkds', 'coverage', 'keymgr', 'dnskey', 'eventlist', 'keydict', 'keyevent', 'keyseries', 'keyzone', 'policy', 'parsetab', 'rndc', 'utils'] from isc.dnskey import * from isc.eventlist import * from isc.keydict import * from isc.keyevent import * from isc.keyseries import * from isc.keyzone import * from isc.policy import * from isc.rndc import * from isc.utils import * PKֺ1]xUthread.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_THREAD_H #define ISC_THREAD_H 1 /*! \file */ #include #if defined(HAVE_PTHREAD_NP_H) #include #endif #include #include ISC_LANG_BEGINDECLS typedef pthread_t isc_thread_t; typedef void * isc_threadresult_t; typedef void * isc_threadarg_t; typedef isc_threadresult_t (*isc_threadfunc_t)(isc_threadarg_t); typedef pthread_key_t isc_thread_key_t; isc_result_t isc_thread_create(isc_threadfunc_t, isc_threadarg_t, isc_thread_t *); void isc_thread_setconcurrency(unsigned int level); void isc_thread_yield(void); void isc_thread_setname(isc_thread_t thread, const char *name); /* XXX We could do fancier error handling... */ #define isc_thread_join(t, rp) \ ((pthread_join((t), (rp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #define isc_thread_self \ (unsigned long)pthread_self #define isc_thread_key_create pthread_key_create #define isc_thread_key_getspecific pthread_getspecific #define isc_thread_key_setspecific pthread_setspecific #define isc_thread_key_delete pthread_key_delete ISC_LANG_ENDDECLS #endif /* ISC_THREAD_H */ PKֺ1]F'}}stats.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STATS_H #define ISC_STATS_H 1 /*! \file isc/stats.h */ #include #include ISC_LANG_BEGINDECLS /*%< * Flag(s) for isc_stats_dump(). */ #define ISC_STATSDUMP_VERBOSE 0x00000001 /*%< dump 0-value counters */ /*%< * Dump callback type. */ typedef void (*isc_stats_dumper_t)(isc_statscounter_t, uint64_t, void *); isc_result_t isc_stats_create(isc_mem_t *mctx, isc_stats_t **statsp, int ncounters); /*%< * Create a statistics counter structure of general type. It counts a general * set of counters indexed by an ID between 0 and ncounters -1. * * Requires: *\li 'mctx' must be a valid memory context. * *\li 'statsp' != NULL && '*statsp' == NULL. * * Returns: *\li ISC_R_SUCCESS -- all ok * *\li anything else -- failure */ void isc_stats_attach(isc_stats_t *stats, isc_stats_t **statsp); /*%< * Attach to a statistics set. * * Requires: *\li 'stats' is a valid isc_stats_t. * *\li 'statsp' != NULL && '*statsp' == NULL */ void isc_stats_detach(isc_stats_t **statsp); /*%< * Detaches from the statistics set. * * Requires: *\li 'statsp' != NULL and '*statsp' is a valid isc_stats_t. */ int isc_stats_ncounters(isc_stats_t *stats); /*%< * Returns the number of counters contained in stats. * * Requires: *\li 'stats' is a valid isc_stats_t. * */ void isc_stats_increment(isc_stats_t *stats, isc_statscounter_t counter); /*%< * Increment the counter-th counter of stats. * * Requires: *\li 'stats' is a valid isc_stats_t. * *\li counter is less than the maximum available ID for the stats specified * on creation. */ void isc_stats_decrement(isc_stats_t *stats, isc_statscounter_t counter); /*%< * Decrement the counter-th counter of stats. * * Requires: *\li 'stats' is a valid isc_stats_t. */ void isc_stats_dump(isc_stats_t *stats, isc_stats_dumper_t dump_fn, void *arg, unsigned int options); /*%< * Dump the current statistics counters in a specified way. For each counter * in stats, dump_fn is called with its current value and the given argument * arg. By default counters that have a value of 0 is skipped; if options has * the ISC_STATSDUMP_VERBOSE flag, even such counters are dumped. * * Requires: *\li 'stats' is a valid isc_stats_t. */ void isc_stats_set(isc_stats_t *stats, uint64_t val, isc_statscounter_t counter); /*%< * Set the given counter to the specified value. * * Requires: *\li 'stats' is a valid isc_stats_t. */ void isc_stats_set(isc_stats_t *stats, uint64_t val, isc_statscounter_t counter); /*%< * Set the given counter to the specified value. * * Requires: *\li 'stats' is a valid isc_stats_t. */ void isc_stats_update_if_greater(isc_stats_t *stats, isc_statscounter_t counter, uint64_t value); /*%< * Atomically assigns 'value' to 'counter' if value > counter. * * Requires: *\li 'stats' is a valid isc_stats_t. * *\li counter is less than the maximum available ID for the stats specified * on creation. */ uint64_t isc_stats_get_counter(isc_stats_t *stats, isc_statscounter_t counter); /*%< * Returns value currently stored in counter. * * Requires: *\li 'stats' is a valid isc_stats_t. * *\li counter is less than the maximum available ID for the stats specified * on creation. */ ISC_LANG_ENDDECLS #endif /* ISC_STATS_H */ PKֺ1]eHHsafe.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SAFE_H #define ISC_SAFE_H 1 /*! \file isc/safe.h */ #include #include #include ISC_LANG_BEGINDECLS bool isc_safe_memequal(const void *s1, const void *s2, size_t n); /*%< * Returns true iff. two blocks of memory are equal, otherwise * false. * */ int isc_safe_memcompare(const void *b1, const void *b2, size_t len); /*%< * Clone of libc memcmp() which is safe to differential timing attacks. */ void isc_safe_memwipe(void *ptr, size_t len); /*%< * Clear the memory of length `len` pointed to by `ptr`. * * Some crypto code calls memset() on stack allocated buffers just * before return so that they are wiped. Such memset() calls can be * optimized away by the compiler. We provide this external non-inline C * function to perform the memset operation so that the compiler cannot * infer about what the function does and optimize the call away. */ ISC_LANG_ENDDECLS #endif /* ISC_SAFE_H */ PKֺ1]Cendian.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #pragma once #if defined(__DragonFly__) || defined(__FreeBSD__) || \ defined(__NetBSD__) || defined (__OpenBSD__) || defined(__bsdi__) # include /* * Recent BSDs should have [bl]e{16,32,64}toh() defined in . * Older ones might not, but these should have the alternatively named * [bl]etoh{16,32,64}() functions defined. */ # ifndef be16toh # define be16toh(x) betoh16(x) # define le16toh(x) letoh16(x) # define be32toh(x) betoh32(x) # define le32toh(x) letoh32(x) # define be64toh(x) betoh64(x) # define le64toh(x) letoh64(x) # endif /* !be16toh */ #elif defined(_WIN32) /* * Windows is always little-endian and has its own byte-swapping routines, so * use these. */ # include # define htobe16(x) _byteswap_ushort(x) # define htole16(x) (x) # define be16toh(x) _byteswap_ushort(x) # define le16toh(x) (x) # define htobe32(x) _byteswap_ulong(x) # define htole32(x) (x) # define be32toh(x) _byteswap_ulong(x) # define le32toh(x) (x) # define htobe64(x) _byteswap_uint64(x) # define htole64(x) (x) # define be64toh(x) _byteswap_uint64(x) # define le64toh(x) (x) #elif defined __APPLE__ /* * macOS has its own byte-swapping routines, so use these. */ # include # define htobe16(x) OSSwapHostToBigInt16(x) # define htole16(x) OSSwapHostToLittleInt16(x) # define be16toh(x) OSSwapBigToHostInt16(x) # define le16toh(x) OSSwapLittleToHostInt16(x) # define htobe32(x) OSSwapHostToBigInt32(x) # define htole32(x) OSSwapHostToLittleInt32(x) # define be32toh(x) OSSwapBigToHostInt32(x) # define le32toh(x) OSSwapLittleToHostInt32(x) # define htobe64(x) OSSwapHostToBigInt64(x) # define htole64(x) OSSwapHostToLittleInt64(x) # define be64toh(x) OSSwapBigToHostInt64(x) # define le64toh(x) OSSwapLittleToHostInt64(x) #elif defined(sun) || defined(__sun) || defined(__SVR4) /* * For Solaris, rely on the fallback definitions below, though use * Solaris-specific versions of bswap_{16,32,64}(). */ # include # define bswap_16(x) BSWAP_16(x) # define bswap_32(x) BSWAP_32(x) # define bswap_64(x) BSWAP_64(x) #elif defined(__ANDROID__) || defined(__CYGWIN__) || \ defined(__GNUC__) || defined(__GNU__) # include # include #else #endif /* Specific platform support */ /* * Fallback definitions. */ #include #ifndef bswap_16 # define bswap_16(x) \ ((uint16_t)((((uint16_t) (x) & 0xff00) >> 8) | \ (((uint16_t) (x) & 0x00ff) << 8))) #endif /* !bswap_16 */ #ifndef bswap_32 # define bswap_32(x) \ ((uint32_t)((((uint32_t) (x) & 0xff000000) >> 24) | \ (((uint32_t) (x) & 0x00ff0000) >> 8) | \ (((uint32_t) (x) & 0x0000ff00) << 8) | \ (((uint32_t) (x) & 0x000000ff) << 24))) #endif /* !bswap_32 */ #ifndef bswap_64 # define bswap_64(x) \ ((uint64_t)((((uint64_t) (x) & 0xff00000000000000ULL) >> 56) | \ (((uint64_t) (x) & 0x00ff000000000000ULL) >> 40) | \ (((uint64_t) (x) & 0x0000ff0000000000ULL) >> 24) | \ (((uint64_t) (x) & 0x000000ff00000000ULL) >> 8) | \ (((uint64_t) (x) & 0x00000000ff000000ULL) << 8) | \ (((uint64_t) (x) & 0x0000000000ff0000ULL) << 24) | \ (((uint64_t) (x) & 0x000000000000ff00ULL) << 40) | \ (((uint64_t) (x) & 0x00000000000000ffULL) << 56))) #endif /* !bswap_64 */ #ifndef htobe16 # if WORDS_BIGENDIAN # define htobe16(x) (x) # define htole16(x) bswap_16(x) # define be16toh(x) (x) # define le16toh(x) bswap_16(x) # else /* WORDS_BIGENDIAN */ # define htobe16(x) bswap_16(x) # define htole16(x) (x) # define be16toh(x) bswap_16(x) # define le16toh(x) (x) # endif /* WORDS_BIGENDIAN */ #endif /* !htobe16 */ #ifndef htobe32 # if WORDS_BIGENDIAN # define htobe32(x) (x) # define htole32(x) bswap_32(x) # define be32toh(x) (x) # define le32toh(x) bswap_32(x) # else /* WORDS_BIGENDIAN */ # define htobe32(x) bswap_32(x) # define htole32(x) (x) # define be32toh(x) bswap_32(x) # define le32toh(x) (x) # endif /* WORDS_BIGENDIAN */ #endif /* !htobe32 */ #ifndef htobe64 # if WORDS_BIGENDIAN # define htobe64(x) (x) # define htole64(x) bswap_64(x) # define be64toh(x) (x) # define le64toh(x) bswap_64(x) #else /* WORDS_BIGENDIAN */ # define htobe64(x) bswap_64(x) # define htole64(x) (x) # define be64toh(x) bswap_64(x) # define le64toh(x) (x) # endif /* WORDS_BIGENDIAN */ #endif /* !htobe64 */ PKֺ1]Ɉ>p>plog.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LOG_H #define ISC_LOG_H 1 /*! \file isc/log.h */ #include #include #include #include /* XXXDCL NT */ #include #include #include #include /*@{*/ /*! * \brief Severity levels, patterned after Unix's syslog levels. * */ #define ISC_LOG_DEBUG(level) (level) /*! * #ISC_LOG_DYNAMIC can only be used for defining channels with * isc_log_createchannel(), not to specify a level in isc_log_write(). */ #define ISC_LOG_DYNAMIC 0 #define ISC_LOG_INFO (-1) #define ISC_LOG_NOTICE (-2) #define ISC_LOG_WARNING (-3) #define ISC_LOG_ERROR (-4) #define ISC_LOG_CRITICAL (-5) /*@}*/ /*@{*/ /*! * \brief Destinations. */ #define ISC_LOG_TONULL 1 #define ISC_LOG_TOSYSLOG 2 #define ISC_LOG_TOFILE 3 #define ISC_LOG_TOFILEDESC 4 /*@}*/ /*@{*/ /*% * Channel flags. */ #define ISC_LOG_PRINTTIME 0x0001 #define ISC_LOG_PRINTLEVEL 0x0002 #define ISC_LOG_PRINTCATEGORY 0x0004 #define ISC_LOG_PRINTMODULE 0x0008 #define ISC_LOG_PRINTTAG 0x0010 /* tag and ":" */ #define ISC_LOG_PRINTPREFIX 0x0020 /* tag only, no colon */ #define ISC_LOG_PRINTALL 0x003F #define ISC_LOG_BUFFERED 0x0040 #define ISC_LOG_DEBUGONLY 0x1000 #define ISC_LOG_OPENERR 0x8000 /* internal */ /*@}*/ /*@{*/ /*! * \brief Other options. * * XXXDCL INFINITE doesn't yet work. Arguably it isn't needed, but * since I am intend to make large number of versions work efficiently, * INFINITE is going to be trivial to add to that. */ #define ISC_LOG_ROLLINFINITE (-1) #define ISC_LOG_ROLLNEVER (-2) /*@}*/ /*! * \brief Used to name the categories used by a library. * * An array of isc_logcategory * structures names each category, and the id value is initialized by calling * isc_log_registercategories. */ struct isc_logcategory { const char *name; unsigned int id; }; /*% * Similar to isc_logcategory, but for all the modules a library defines. */ struct isc_logmodule { const char *name; unsigned int id; }; /*% * The isc_logfile structure is initialized as part of an isc_logdestination * before calling isc_log_createchannel(). * * When defining an #ISC_LOG_TOFILE * channel the name, versions and maximum_size should be set before calling * isc_log_createchannel(). To define an #ISC_LOG_TOFILEDESC channel set only * the stream before the call. * * Setting maximum_size to zero implies no maximum. */ typedef struct isc_logfile { FILE *stream; /*%< Initialized to NULL for #ISC_LOG_TOFILE. */ const char *name; /*%< NULL for #ISC_LOG_TOFILEDESC. */ int versions; /* >= 0, #ISC_LOG_ROLLNEVER, #ISC_LOG_ROLLINFINITE. */ /*% * stdio's ftell is standardized to return a long, which may well not * be big enough for the largest file supportable by the operating * system (though it is _probably_ big enough for the largest log * anyone would want). st_size returned by fstat should be typedef'd * to a size large enough for the largest possible file on a system. */ isc_offset_t maximum_size; bool maximum_reached; /*%< Private. */ } isc_logfile_t; /*% * Passed to isc_log_createchannel to define the attributes of either * a stdio or a syslog log. */ typedef union isc_logdestination { isc_logfile_t file; int facility; /* XXXDCL NT */ } isc_logdestination_t; /*@{*/ /*% * The built-in categories of libisc. * * Each library registering categories should provide library_LOGCATEGORY_name * definitions with indexes into its isc_logcategory structure corresponding to * the order of the names. */ LIBISC_EXTERNAL_DATA extern isc_logcategory_t isc_categories[]; LIBISC_EXTERNAL_DATA extern isc_log_t *isc_lctx; LIBISC_EXTERNAL_DATA extern isc_logmodule_t isc_modules[]; /*@}*/ /*@{*/ /*% * Do not log directly to DEFAULT. Use another category. When in doubt, * use GENERAL. */ #define ISC_LOGCATEGORY_DEFAULT (&isc_categories[0]) #define ISC_LOGCATEGORY_GENERAL (&isc_categories[1]) /*@}*/ #define ISC_LOGMODULE_SOCKET (&isc_modules[0]) #define ISC_LOGMODULE_TIME (&isc_modules[1]) #define ISC_LOGMODULE_INTERFACE (&isc_modules[2]) #define ISC_LOGMODULE_TIMER (&isc_modules[3]) #define ISC_LOGMODULE_FILE (&isc_modules[4]) #define ISC_LOGMODULE_OTHER (&isc_modules[5]) ISC_LANG_BEGINDECLS isc_result_t isc_log_create(isc_mem_t *mctx, isc_log_t **lctxp, isc_logconfig_t **lcfgp); /*%< * Establish a new logging context, with default channels. * * Notes: *\li isc_log_create() calls isc_logconfig_create(), so see its comment * below for more information. * * Requires: *\li mctx is a valid memory context. *\li lctxp is not null and *lctxp is null. *\li lcfgp is null or lcfgp is not null and *lcfgp is null. * * Ensures: *\li *lctxp will point to a valid logging context if all of the necessary * memory was allocated, or NULL otherwise. *\li *lcfgp will point to a valid logging configuration if all of the * necessary memory was allocated, or NULL otherwise. *\li On failure, no additional memory is allocated. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource limit: Out of memory */ isc_result_t isc_logconfig_create(isc_log_t *lctx, isc_logconfig_t **lcfgp); /*%< * Create the data structure that holds all of the configurable information * about where messages are actually supposed to be sent -- the information * that could changed based on some configuration file, as opposed to the * the category/module specification of isc_log_[v]write[1] that is compiled * into a program, or the debug_level which is dynamic state information. * * Notes: *\li It is necessary to specify the logging context the configuration * will be used with because the number of categories and modules * needs to be known in order to set the configuration. However, * the configuration is not used by the logging context until the * isc_logconfig_use function is called. * *\li The memory context used for operations that allocate memory for * the configuration is that of the logging context, as specified * in the isc_log_create call. * *\li Four default channels are established: *\verbatim * default_syslog * - log to syslog's daemon facility #ISC_LOG_INFO or higher * default_stderr * - log to stderr #ISC_LOG_INFO or higher * default_debug * - log to stderr #ISC_LOG_DEBUG dynamically * null * - log nothing *\endverbatim * * Requires: *\li lctx is a valid logging context. *\li lcftp is not null and *lcfgp is null. * * Ensures: *\li *lcfgp will point to a valid logging context if all of the necessary * memory was allocated, or NULL otherwise. *\li On failure, no additional memory is allocated. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource limit: Out of memory */ isc_logconfig_t * isc_logconfig_get(isc_log_t *lctx); /*%< * Returns a pointer to the configuration currently in use by the log context. * * Requires: *\li lctx is a valid context. * * Ensures: *\li The configuration pointer is non-null. * * Returns: *\li The configuration pointer. */ isc_result_t isc_logconfig_use(isc_log_t *lctx, isc_logconfig_t *lcfg); /*%< * Associate a new configuration with a logging context. * * Notes: *\li This is thread safe. The logging context will lock a mutex * before attempting to swap in the new configuration, and isc_log_doit * (the internal function used by all of isc_log_[v]write[1]) locks * the same lock for the duration of its use of the configuration. * * Requires: *\li lctx is a valid logging context. *\li lcfg is a valid logging configuration. *\li lctx is the same configuration given to isc_logconfig_create * when the configuration was created. * * Ensures: *\li Future calls to isc_log_write will use the new configuration. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource limit: Out of memory */ void isc_log_destroy(isc_log_t **lctxp); /*%< * Deallocate the memory associated with a logging context. * * Requires: *\li *lctx is a valid logging context. * * Ensures: *\li All of the memory associated with the logging context is returned * to the free memory pool. * *\li Any open files are closed. * *\li The logging context is marked as invalid. */ void isc_logconfig_destroy(isc_logconfig_t **lcfgp); /*%< * Destroy a logging configuration. * * Notes: *\li This function cannot be used directly with the return value of * isc_logconfig_get, because a logging context must always have * a valid configuration associated with it. * * Requires: *\li lcfgp is not null and *lcfgp is a valid logging configuration. *\li The logging configuration is not in use by an existing logging context. * * Ensures: *\li All memory allocated for the configuration is freed. * *\li The configuration is marked as invalid. */ void isc_log_registercategories(isc_log_t *lctx, isc_logcategory_t categories[]); /*%< * Identify logging categories a library will use. * * Notes: *\li A category should only be registered once, but no mechanism enforces * this rule. * *\li The end of the categories array is identified by a NULL name. * *\li Because the name is used by #ISC_LOG_PRINTCATEGORY, it should not * be altered or destroyed after isc_log_registercategories(). * *\li Because each element of the categories array is used by * isc_log_categorybyname, it should not be altered or destroyed * after registration. * *\li The value of the id integer in each structure is overwritten * by this function, and so id need not be initialized to any particular * value prior to the function call. * *\li A subsequent call to isc_log_registercategories with the same * logging context (but new categories) will cause the last * element of the categories array from the prior call to have * its "name" member changed from NULL to point to the new * categories array, and its "id" member set to UINT_MAX. * * Requires: *\li lctx is a valid logging context. *\li categories != NULL. *\li categories[0].name != NULL. * * Ensures: * \li There are references to each category in the logging context, * so they can be used with isc_log_usechannel() and isc_log_write(). */ void isc_log_registermodules(isc_log_t *lctx, isc_logmodule_t modules[]); /*%< * Identify logging categories a library will use. * * Notes: *\li A module should only be registered once, but no mechanism enforces * this rule. * *\li The end of the modules array is identified by a NULL name. * *\li Because the name is used by #ISC_LOG_PRINTMODULE, it should not * be altered or destroyed after isc_log_registermodules(). * *\li Because each element of the modules array is used by * isc_log_modulebyname, it should not be altered or destroyed * after registration. * *\li The value of the id integer in each structure is overwritten * by this function, and so id need not be initialized to any particular * value prior to the function call. * *\li A subsequent call to isc_log_registermodules with the same * logging context (but new modules) will cause the last * element of the modules array from the prior call to have * its "name" member changed from NULL to point to the new * modules array, and its "id" member set to UINT_MAX. * * Requires: *\li lctx is a valid logging context. *\li modules != NULL. *\li modules[0].name != NULL; * * Ensures: *\li Each module has a reference in the logging context, so they can be * used with isc_log_usechannel() and isc_log_write(). */ isc_result_t isc_log_createchannel(isc_logconfig_t *lcfg, const char *name, unsigned int type, int level, const isc_logdestination_t *destination, unsigned int flags); /*%< * Specify the parameters of a logging channel. * * Notes: *\li The name argument is copied to memory in the logging context, so * it can be altered or destroyed after isc_log_createchannel(). * *\li Defining a very large number of channels will have a performance * impact on isc_log_usechannel(), since the names are searched * linearly until a match is made. This same issue does not affect * isc_log_write, however. * *\li Channel names can be redefined; this is primarily useful for programs * that want their own definition of default_syslog, default_debug * and default_stderr. * *\li Any channel that is redefined will not affect logging that was * already directed to its original definition, _except_ for the * default_stderr channel. This case is handled specially so that * the default logging category can be changed by redefining * default_stderr. (XXXDCL Though now that I think of it, the default * logging category can be changed with only one additional function * call by defining a new channel and then calling isc_log_usechannel() * for #ISC_LOGCATEGORY_DEFAULT.) * *\li Specifying #ISC_LOG_PRINTTIME or #ISC_LOG_PRINTTAG for syslog is * allowed, but probably not what you wanted to do. * * #ISC_LOG_DEBUGONLY will mark the channel as usable only when the * debug level of the logging context (see isc_log_setdebuglevel) * is non-zero. * * Requires: *\li lcfg is a valid logging configuration. * *\li name is not NULL. * *\li type is #ISC_LOG_TOSYSLOG, #ISC_LOG_TOFILE, #ISC_LOG_TOFILEDESC or * #ISC_LOG_TONULL. * *\li destination is not NULL unless type is #ISC_LOG_TONULL. * *\li level is >= #ISC_LOG_CRITICAL (the most negative logging level). * *\li flags does not include any bits aside from the ISC_LOG_PRINT* bits, * #ISC_LOG_DEBUGONLY or #ISC_LOG_BUFFERED. * * Ensures: *\li #ISC_R_SUCCESS * A channel with the given name is usable with * isc_log_usechannel(). * *\li #ISC_R_NOMEMORY or #ISC_R_UNEXPECTED * No additional memory is being used by the logging context. * Any channel that previously existed with the given name * is not redefined. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource limit: Out of memory *\li #ISC_R_UNEXPECTED type was out of range and REQUIRE() * was disabled. */ isc_result_t isc_log_usechannel(isc_logconfig_t *lcfg, const char *name, const isc_logcategory_t *category, const isc_logmodule_t *module); /*%< * Associate a named logging channel with a category and module that * will use it. * * Notes: *\li The name is searched for linearly in the set of known channel names * until a match is found. (Note the performance impact of a very large * number of named channels.) When multiple channels of the same * name are defined, the most recent definition is found. * *\li Specifying a very large number of channels for a category will have * a moderate impact on performance in isc_log_write(), as each * call looks up the category for the start of a linked list, which * it follows all the way to the end to find matching modules. The * test for matching modules is integral, though. * *\li If category is NULL, then the channel is associated with the indicated * module for all known categories (including the "default" category). * *\li If module is NULL, then the channel is associated with every module * that uses that category. * *\li Passing both category and module as NULL would make every log message * use the indicated channel. * * \li Specifying a channel that is #ISC_LOG_TONULL for a category/module pair * has no effect on any other channels associated with that pair, * regardless of ordering. Thus you cannot use it to "mask out" one * category/module pair when you have specified some other channel that * is also used by that category/module pair. * * Requires: *\li lcfg is a valid logging configuration. * *\li category is NULL or has an id that is in the range of known ids. * * module is NULL or has an id that is in the range of known ids. * * Ensures: *\li #ISC_R_SUCCESS * The channel will be used by the indicated category/module * arguments. * *\li #ISC_R_NOMEMORY * If assignment for a specific category has been requested, * the channel has not been associated with the indicated * category/module arguments and no additional memory is * used by the logging context. * If assignment for all categories has been requested * then _some_ may have succeeded (starting with category * "default" and progressing through the order of categories * passed to isc_log_registercategories()) and additional memory * is being used by whatever assignments succeeded. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource limit: Out of memory */ /* Attention: next four comments PRECEDE code */ /*! * \brief * Write a message to the log channels. * * Notes: *\li Log messages containing natural language text should be logged with * isc_log_iwrite() to allow for localization. * *\li lctx can be NULL; this is allowed so that programs which use * libraries that use the ISC logging system are not required to * also use it. * *\li The format argument is a printf(3) string, with additional arguments * as necessary. * * Requires: *\li lctx is a valid logging context. * *\li The category and module arguments must have ids that are in the * range of known ids, as established by isc_log_registercategories() * and isc_log_registermodules(). * *\li level != #ISC_LOG_DYNAMIC. ISC_LOG_DYNAMIC is used only to define * channels, and explicit debugging level must be identified for * isc_log_write() via ISC_LOG_DEBUG(level). * *\li format != NULL. * * Ensures: *\li The log message is written to every channel associated with the * indicated category/module pair. * * Returns: *\li Nothing. Failure to log a message is not construed as a * meaningful error. */ void isc_log_write(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, const char *format, ...) ISC_FORMAT_PRINTF(5, 6); /*% * Write a message to the log channels. * * Notes: *\li lctx can be NULL; this is allowed so that programs which use * libraries that use the ISC logging system are not required to * also use it. * *\li The format argument is a printf(3) string, with additional arguments * as necessary. * * Requires: *\li lctx is a valid logging context. * *\li The category and module arguments must have ids that are in the * range of known ids, as established by isc_log_registercategories() * and isc_log_registermodules(). * *\li level != #ISC_LOG_DYNAMIC. ISC_LOG_DYNAMIC is used only to define * channels, and explicit debugging level must be identified for * isc_log_write() via ISC_LOG_DEBUG(level). * *\li format != NULL. * * Ensures: *\li The log message is written to every channel associated with the * indicated category/module pair. * * Returns: *\li Nothing. Failure to log a message is not construed as a * meaningful error. */ void isc_log_vwrite(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, const char *format, va_list args) ISC_FORMAT_PRINTF(5, 0); /*% * Write a message to the log channels, pruning duplicates that occur within * a configurable amount of seconds (see isc_log_[sg]etduplicateinterval). * This function is otherwise identical to isc_log_write(). */ void isc_log_write1(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, const char *format, ...) ISC_FORMAT_PRINTF(5, 6); /*% * Write a message to the log channels, pruning duplicates that occur within * a configurable amount of seconds (see isc_log_[sg]etduplicateinterval). * This function is otherwise identical to isc_log_vwrite(). */ void isc_log_vwrite1(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, const char *format, va_list args) ISC_FORMAT_PRINTF(5, 0); /*% * These are four internationalized versions of the isc_log_[v]write[1] * functions. * * The only difference is that they take arguments for a message * catalog, message set, and message number, all immediately preceding the * format argument. The format argument becomes the default text, a la * isc_msgcat_get. If the message catalog is NULL, no lookup is attempted * for a message -- which makes the message set and message number irrelevant, * and the non-internationalized call should have probably been used instead. * * Yes, that means there are now *eight* interfaces to logging a message. * Sheesh. Make the madness stop! */ /*@{*/ void isc_log_iwrite(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, isc_msgcat_t *msgcat, int msgset, int message, const char *format, ...) ISC_FORMAT_PRINTF(8, 9); void isc_log_ivwrite(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, isc_msgcat_t *msgcat, int msgset, int message, const char *format, va_list args) ISC_FORMAT_PRINTF(8, 0); void isc_log_iwrite1(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, isc_msgcat_t *msgcat, int msgset, int message, const char *format, ...) ISC_FORMAT_PRINTF(8, 9); void isc_log_ivwrite1(isc_log_t *lctx, isc_logcategory_t *category, isc_logmodule_t *module, int level, isc_msgcat_t *msgcat, int msgset, int message, const char *format, va_list args) ISC_FORMAT_PRINTF(8, 0); /*@}*/ void isc_log_setdebuglevel(isc_log_t *lctx, unsigned int level); /*%< * Set the debugging level used for logging. * * Notes: *\li Setting the debugging level to 0 disables debugging log messages. * * Requires: *\li lctx is a valid logging context. * * Ensures: *\li The debugging level is set to the requested value. */ unsigned int isc_log_getdebuglevel(isc_log_t *lctx); /*%< * Get the current debugging level. * * Notes: *\li This is provided so that a program can have a notion of * "increment debugging level" or "decrement debugging level" * without needing to keep track of what the current level is. * *\li A return value of 0 indicates that debugging messages are disabled. * * Requires: *\li lctx is a valid logging context. * * Ensures: *\li The current logging debugging level is returned. */ bool isc_log_wouldlog(isc_log_t *lctx, int level); /*%< * Determine whether logging something to 'lctx' at 'level' would * actually cause something to be logged somewhere. * * If #false is returned, it is guaranteed that nothing would * be logged, allowing the caller to omit unnecessary * isc_log_write() calls and possible message preformatting. */ void isc_log_setduplicateinterval(isc_logconfig_t *lcfg, unsigned int interval); /*%< * Set the interval over which duplicate log messages will be ignored * by isc_log_[v]write1(), in seconds. * * Notes: *\li Increasing the duplicate interval from X to Y will not necessarily * filter out duplicates of messages logged in Y - X seconds since the * increase. (Example: Message1 is logged at midnight. Message2 * is logged at 00:01:00, when the interval is only 30 seconds, causing * Message1 to be expired from the log message history. Then the interval * is increased to 3000 (five minutes) and at 00:04:00 Message1 is logged * again. It will appear the second time even though less than five * passed since the first occurrence. * * Requires: *\li lctx is a valid logging context. */ unsigned int isc_log_getduplicateinterval(isc_logconfig_t *lcfg); /*%< * Get the current duplicate filtering interval. * * Requires: *\li lctx is a valid logging context. * * Returns: *\li The current duplicate filtering interval. */ isc_result_t isc_log_settag(isc_logconfig_t *lcfg, const char *tag); /*%< * Set the program name or other identifier for #ISC_LOG_PRINTTAG. * * Requires: *\li lcfg is a valid logging configuration. * * Notes: *\li If this function has not set the tag to a non-NULL, non-empty value, * then the #ISC_LOG_PRINTTAG channel flag will not print anything. * Unlike some implementations of syslog on Unix systems, you *must* set * the tag in order to get it logged. It is not implicitly derived from * the program name (which is pretty impossible to infer portably). * *\li Setting the tag to NULL or the empty string will also cause the * #ISC_LOG_PRINTTAG channel flag to not print anything. If tag equals the * empty string, calls to isc_log_gettag will return NULL. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource Limit: Out of memory * * XXXDCL when creating a new isc_logconfig_t, it might be nice if the tag * of the currently active isc_logconfig_t was inherited. this does not * currently happen. */ char * isc_log_gettag(isc_logconfig_t *lcfg); /*%< * Get the current identifier printed with #ISC_LOG_PRINTTAG. * * Requires: *\li lcfg is a valid logging configuration. * * Notes: *\li Since isc_log_settag() will not associate a zero-length string * with the logging configuration, attempts to do so will cause * this function to return NULL. However, a determined programmer * will observe that (currently) a tag of length greater than zero * could be set, and then modified to be zero length. * * Returns: *\li A pointer to the current identifier, or NULL if none has been set. */ void isc_log_opensyslog(const char *tag, int options, int facility); /*%< * Initialize syslog logging. * * Notes: *\li XXXDCL NT * This is currently equivalent to openlog(), but is not going to remain * that way. In the meantime, the arguments are all identical to * those used by openlog(3), as follows: * * \code * tag: The string to use in the position of the program * name in syslog messages. Most (all?) syslogs * will use basename(argv[0]) if tag is NULL. * * options: LOG_CONS, LOG_PID, LOG_NDELAY ... whatever your * syslog supports. * * facility: The default syslog facility. This is irrelevant * since isc_log_write will ALWAYS use the channel's * declared facility. * \endcode * *\li Zero effort has been made (yet) to accommodate systems with openlog() * that only takes two arguments, or to identify valid syslog * facilities or options for any given architecture. * *\li It is necessary to call isc_log_opensyslog() to initialize * syslogging on machines which do not support network connections to * syslogd because they require a Unix domain socket to be used. Since * this is a chore to determine at run-time, it is suggested that it * always be called by programs using the ISC logging system. * * Requires: *\li Nothing. * * Ensures: *\li openlog() is called to initialize the syslog system. */ void isc_log_closefilelogs(isc_log_t *lctx); /*%< * Close all open files used by #ISC_LOG_TOFILE channels. * * Notes: *\li This function is provided for programs that want to use their own * log rolling mechanism rather than the one provided internally. * For example, a program that wanted to keep daily logs would define * a channel which used #ISC_LOG_ROLLNEVER, then once a day would * rename the log file and call isc_log_closefilelogs(). * *\li #ISC_LOG_TOFILEDESC channels are unaffected. * * Requires: *\li lctx is a valid context. * * Ensures: *\li The open files are closed and will be reopened when they are * next needed. */ isc_logcategory_t * isc_log_categorybyname(isc_log_t *lctx, const char *name); /*%< * Find a category by its name. * * Notes: *\li The string name of a category is not required to be unique. * * Requires: *\li lctx is a valid context. *\li name is not NULL. * * Returns: *\li A pointer to the _first_ isc_logcategory_t structure used by "name". * *\li NULL if no category exists by that name. */ isc_logmodule_t * isc_log_modulebyname(isc_log_t *lctx, const char *name); /*%< * Find a module by its name. * * Notes: *\li The string name of a module is not required to be unique. * * Requires: *\li lctx is a valid context. *\li name is not NULL. * * Returns: *\li A pointer to the _first_ isc_logmodule_t structure used by "name". * *\li NULL if no module exists by that name. */ void isc_log_setcontext(isc_log_t *lctx); /*%< * Sets the context used by the libisc for logging. * * Requires: *\li lctx be a valid context. */ isc_result_t isc_logfile_roll(isc_logfile_t *file); /*%< * Roll a logfile. * * Requires: *\li file is not NULL. */ ISC_LANG_ENDDECLS #endif /* ISC_LOG_H */ PKֺ1]߾<: fsaccess.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_FSACCESS_H #define ISC_FSACCESS_H 1 /*! \file isc/fsaccess.h * \brief The ISC filesystem access module encapsulates the setting of file * and directory access permissions into one API that is meant to be * portable to multiple operating systems. * * The two primary operating system flavors that are initially accommodated * are POSIX and Windows NT 4.0 and later. The Windows NT access model is * considerable more flexible than POSIX's model (as much as I am loathe to * admit it), and so the ISC API has a higher degree of complexity than would * be needed to simply address POSIX's needs. * * The full breadth of NT's flexibility is not available either, for the * present time. Much of it is to provide compatibility with what Unix * programmers are expecting. This is also due to not yet really needing all * of the functionality of an NT system (or, for that matter, a POSIX system) * in BIND9, and so resolving how to handle the various incompatibilities has * been a purely theoretical exercise with no operational experience to * indicate how flawed the thinking may be. * * Some of the more notable dumbing down of NT for this API includes: * *\li Each of FILE_READ_DATA and FILE_READ_EA are set with #ISC_FSACCESS_READ. * * \li All of FILE_WRITE_DATA, FILE_WRITE_EA and FILE_APPEND_DATA are * set with #ISC_FSACCESS_WRITE. FILE_WRITE_ATTRIBUTES is not set * so as to be consistent with Unix, where only the owner of the file * or the superuser can change the attributes/mode of a file. * * \li Both of FILE_ADD_FILE and FILE_ADD_SUBDIRECTORY are set with * #ISC_FSACCESS_CREATECHILD. This is similar to setting the WRITE * permission on a Unix directory. * * \li SYNCHRONIZE is always set for files and directories, unless someone * can give me a reason why this is a bad idea. * * \li READ_CONTROL and FILE_READ_ATTRIBUTES are always set; this is * consistent with Unix, where any file or directory can be stat()'d * unless the directory path disallows complete access somewhere along * the way. * * \li WRITE_DAC is only set for the owner. This too is consistent with * Unix, and is tighter security than allowing anyone else to be * able to set permissions. * * \li DELETE is only set for the owner. On Unix the ability to delete * a file is controlled by the directory permissions, but it isn't * currently clear to me what happens on NT if the directory has * FILE_DELETE_CHILD set but a file within it does not have DELETE * set. Always setting DELETE on the file/directory for the owner * gives maximum flexibility to the owner without exposing the * file to deletion by others. * * \li WRITE_OWNER is never set. This too is consistent with Unix, * and is also tighter security than allowing anyone to change the * ownership of the file apart from the superu..ahem, Administrator. * * \li Inheritance is set to NO_INHERITANCE. * * Unix's dumbing down includes: * * \li The sticky bit cannot be set. * * \li setuid and setgid cannot be set. * * \li Only regular files and directories can be set. * * The rest of this comment discusses a few of the incompatibilities * between the two systems that need more thought if this API is to * be extended to accommodate them. * * The Windows standard access right "DELETE" doesn't have a direct * equivalent in the Unix world, so it isn't clear what should be done * with it. * * The Unix sticky bit is not supported. While NT does have a concept * of allowing users to create files in a directory but not delete or * rename them, it does not have a concept of allowing them to be deleted * if they are owned by the user trying to delete/rename. While it is * probable that something could be cobbled together in NT 5 with inheritance, * it can't really be done in NT 4 as a single property that you could * set on a directory. You'd need to coordinate something with file creation * so that every file created had DELETE set for the owner but no one else. * * On Unix systems, setting #ISC_FSACCESS_LISTDIRECTORY sets READ. * ... setting either #ISC_FSACCESS_CREATECHILD or #ISC_FSACCESS_DELETECHILD * sets WRITE. * ... setting #ISC_FSACCESS_ACCESSCHILD sets EXECUTE. * * On NT systems, setting #ISC_FSACCESS_LISTDIRECTORY sets FILE_LIST_DIRECTORY. * ... setting #ISC_FSACCESS_CREATECHILD sets FILE_CREATE_CHILD independently. * ... setting #ISC_FSACCESS_DELETECHILD sets FILE_DELETE_CHILD independently. * ... setting #ISC_FSACCESS_ACCESSCHILD sets FILE_TRAVERSE. * * Unresolved: XXXDCL * \li What NT access right controls the ability to rename a file? * \li How does DELETE work? If a directory has FILE_DELETE_CHILD but a * file or directory within it does not have DELETE, is that file * or directory deletable? * \li To implement isc_fsaccess_get(), mapping an existing Unix permission * mode_t back to an isc_fsaccess_t is pretty trivial; however, mapping * an NT DACL could be impossible to do in a responsible way. * \li Similarly, trying to implement the functionality of being able to * say "add group writability to whatever permissions already exist" * could be tricky on NT because of the order-of-entry issue combined * with possibly having one or more matching ACEs already explicitly * granting or denying access. Because this functionality is * not yet needed by the ISC, no code has been written to try to * solve this problem. */ #include #include #include /* * Trustees. */ #define ISC_FSACCESS_OWNER 0x1 /*%< User account. */ #define ISC_FSACCESS_GROUP 0x2 /*%< Primary group owner. */ #define ISC_FSACCESS_OTHER 0x4 /*%< Not the owner or the group owner. */ #define ISC_FSACCESS_WORLD 0x7 /*%< User, Group, Other. */ /* * Types of permission. */ #define ISC_FSACCESS_READ 0x00000001 /*%< File only. */ #define ISC_FSACCESS_WRITE 0x00000002 /*%< File only. */ #define ISC_FSACCESS_EXECUTE 0x00000004 /*%< File only. */ #define ISC_FSACCESS_CREATECHILD 0x00000008 /*%< Dir only. */ #define ISC_FSACCESS_DELETECHILD 0x00000010 /*%< Dir only. */ #define ISC_FSACCESS_LISTDIRECTORY 0x00000020 /*%< Dir only. */ #define ISC_FSACCESS_ACCESSCHILD 0x00000040 /*%< Dir only. */ /*% * Adding any permission bits beyond 0x200 would mean typedef'ing * isc_fsaccess_t as uint64_t, and redefining this value to * reflect the new range of permission types, Probably to 21 for * maximum flexibility. The number of bits has to accommodate all of * the permission types, and three full sets of them have to fit * within an isc_fsaccess_t. */ #define ISC__FSACCESS_PERMISSIONBITS 10 ISC_LANG_BEGINDECLS void isc_fsaccess_add(int trustee, int permission, isc_fsaccess_t *access); void isc_fsaccess_remove(int trustee, int permission, isc_fsaccess_t *access); isc_result_t isc_fsaccess_set(const char *path, isc_fsaccess_t access); ISC_LANG_ENDDECLS #endif /* ISC_FSACCESS_H */ PKֺ1]ajson.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_JSON_H #define ISC_JSON_H 1 #ifdef HAVE_JSON /* * This file is here mostly to make it easy to add additional libjson header * files as needed across all the users of this file. Rather than place * these libjson includes in each file, one include makes it easy to handle * the ifdef as well as adding the ability to add additional functions * which may be useful. */ #ifdef HAVE_JSON_C /* * We don't include as the subsequent includes do not * prefix the header file names with "json-c/" and using * -I /include/json-c results in too many filename collisions. */ #include #include #include #include #include #include #else #include #endif #endif #define ISC_JSON_RENDERCONFIG 0x00000001 /* render config data */ #define ISC_JSON_RENDERSTATS 0x00000002 /* render stats */ #define ISC_JSON_RENDERALL 0x000000ff /* render everything */ #endif /* ISC_JSON_H */ PKֺ1]$>>dir.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_DIR_H #define ISC_DIR_H 1 /*! \file */ #include /* Required on some systems. */ #include #include #include #include #define ISC_DIR_NAMEMAX NAME_MAX #define ISC_DIR_PATHMAX PATH_MAX /*% Directory Entry */ typedef struct isc_direntry { char name[NAME_MAX]; unsigned int length; } isc_direntry_t; /*% Directory */ typedef struct isc_dir { unsigned int magic; char dirname[PATH_MAX]; isc_direntry_t entry; DIR * handle; } isc_dir_t; ISC_LANG_BEGINDECLS void isc_dir_init(isc_dir_t *dir); isc_result_t isc_dir_open(isc_dir_t *dir, const char *dirname); isc_result_t isc_dir_read(isc_dir_t *dir); isc_result_t isc_dir_reset(isc_dir_t *dir); void isc_dir_close(isc_dir_t *dir); isc_result_t isc_dir_chdir(const char *dirname); isc_result_t isc_dir_chroot(const char *dirname); isc_result_t isc_dir_createunique(char *templet); /*!< * Use a templet (such as from isc_file_mktemplate()) to create a uniquely * named, empty directory. The templet string is modified in place. * If result == ISC_R_SUCCESS, it is the name of the directory that was * created. */ ISC_LANG_ENDDECLS #endif /* ISC_DIR_H */ PKֺ1]ؕ2 2 base64.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_BASE64_H #define ISC_BASE64_H 1 /*! \file isc/base64.h */ #include #include ISC_LANG_BEGINDECLS /*** *** Functions ***/ isc_result_t isc_base64_totext(isc_region_t *source, int wordlength, const char *wordbreak, isc_buffer_t *target); /*!< * \brief Convert data into base64 encoded text. * * Notes: *\li The base64 encoded text in 'target' will be divided into * words of at most 'wordlength' characters, separated by * the 'wordbreak' string. No parentheses will surround * the text. * * Requires: *\li 'source' is a region containing binary data *\li 'target' is a text buffer containing available space *\li 'wordbreak' points to a null-terminated string of * zero or more whitespace characters * * Ensures: *\li target will contain the base64 encoded version of the data * in source. The 'used' pointer in target will be advanced as * necessary. */ isc_result_t isc_base64_decodestring(const char *cstr, isc_buffer_t *target); /*!< * \brief Decode a null-terminated base64 string. * * Requires: *\li 'cstr' is non-null. *\li 'target' is a valid buffer. * * Returns: *\li #ISC_R_SUCCESS -- the entire decoded representation of 'cstring' * fit in 'target'. *\li #ISC_R_BADBASE64 -- 'cstr' is not a valid base64 encoding. * * Other error returns are any possible error code from: *\li isc_lex_create(), *\li isc_lex_openbuffer(), *\li isc_base64_tobuffer(). */ isc_result_t isc_base64_tobuffer(isc_lex_t *lexer, isc_buffer_t *target, int length); /*!< * \brief Convert base64 encoded text from a lexer context into * `target`. If 'length' is non-negative, it is the expected number of * encoded octets to convert. * * If 'length' is -1 then 0 or more encoded octets are expected. * If 'length' is -2 then 1 or more encoded octets are expected. * * Returns: *\li #ISC_R_BADBASE64 -- invalid base64 encoding. *\li #ISC_R_UNEXPECTEDEND: the text does not contain the expected * number of encoded octets. * * Requires: *\li 'lexer' is a valid lexer context *\li 'target' is a buffer containing binary data *\li 'length' is -2, -1, or non-negative * * Ensures: *\li target will contain the data represented by the base64 encoded * string parsed by the lexer. No more than `length` octets will * be read, if `length` is non-negative. The 'used' pointer in * 'target' will be advanced as necessary. */ ISC_LANG_ENDDECLS #endif /* ISC_BASE64_H */ PKֺ1]22likely.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LIKELY_H #define ISC_LIKELY_H 1 /*% * Performance */ #ifdef CPPCHECK #define ISC_LIKELY(x) (x) #define ISC_UNLIKELY(x) (x) #else #ifdef HAVE_BUILTIN_EXPECT #define ISC_LIKELY(x) __builtin_expect((x), 1) #define ISC_UNLIKELY(x) __builtin_expect((x), 0) #else #define ISC_LIKELY(x) (x) #define ISC_UNLIKELY(x) (x) #endif #endif #endif /* ISC_LIKELY_H */ PKֺ1]9errno2result.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef UNIX_ERRNO2RESULT_H #define UNIX_ERRNO2RESULT_H 1 /*! \file */ /* XXXDCL this should be moved to lib/isc/include/isc/errno2result.h. */ #include /* Provides errno. */ #include #include #include ISC_LANG_BEGINDECLS #define isc__errno2result(x) isc___errno2result(x, true, __FILE__, __LINE__) isc_result_t isc___errno2result(int posixerrno, bool dolog, const char *file, unsigned int line); ISC_LANG_ENDDECLS #endif /* UNIX_ERRNO2RESULT_H */ PKֺ1]10""time.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_TIME_H #define ISC_TIME_H 1 /*! \file */ #include #include #include #include /*** *** Intervals ***/ /*! * \brief * The contents of this structure are private, and MUST NOT be accessed * directly by callers. * * The contents are exposed only to allow callers to avoid dynamic allocation. */ struct isc_interval { unsigned int seconds; unsigned int nanoseconds; }; extern const isc_interval_t * const isc_interval_zero; /* * ISC_FORMATHTTPTIMESTAMP_SIZE needs to be 30 in C locale and potentially * more for other locales to handle longer national abbreviations when * expanding strftime's %a and %b. */ #define ISC_FORMATHTTPTIMESTAMP_SIZE 50 ISC_LANG_BEGINDECLS void isc_interval_set(isc_interval_t *i, unsigned int seconds, unsigned int nanoseconds); /*%< * Set 'i' to a value representing an interval of 'seconds' seconds and * 'nanoseconds' nanoseconds, suitable for use in isc_time_add() and * isc_time_subtract(). * * Requires: * *\li 't' is a valid pointer. *\li nanoseconds < 1000000000. */ bool isc_interval_iszero(const isc_interval_t *i); /*%< * Returns true iff. 'i' is the zero interval. * * Requires: * *\li 'i' is a valid pointer. */ /*** *** Absolute Times ***/ /*% * The contents of this structure are private, and MUST NOT be accessed * directly by callers. * * The contents are exposed only to allow callers to avoid dynamic allocation. */ struct isc_time { unsigned int seconds; unsigned int nanoseconds; }; extern const isc_time_t * const isc_time_epoch; void isc_time_set(isc_time_t *t, unsigned int seconds, unsigned int nanoseconds); /*%< * Set 't' to a value which represents the given number of seconds and * nanoseconds since 00:00:00 January 1, 1970, UTC. * * Notes: *\li The Unix version of this call is equivalent to: *\code * isc_time_settoepoch(t); * isc_interval_set(i, seconds, nanoseconds); * isc_time_add(t, i, t); *\endcode * * Requires: *\li 't' is a valid pointer. *\li nanoseconds < 1000000000. */ void isc_time_settoepoch(isc_time_t *t); /*%< * Set 't' to the time of the epoch. * * Notes: *\li The date of the epoch is platform-dependent. * * Requires: * *\li 't' is a valid pointer. */ bool isc_time_isepoch(const isc_time_t *t); /*%< * Returns true iff. 't' is the epoch ("time zero"). * * Requires: * *\li 't' is a valid pointer. */ #ifdef CLOCK_BOOTTIME isc_result_t isc_time_boottime(isc_time_t *t); /*%< * Set 't' to monotonic time from previous boot * it's not affected by system time change. It also * includes the time system was suspended * * Requires: *\li 't' is a valid pointer. * * Returns: * *\li Success *\li Unexpected error * Getting the time from the system failed. */ #endif /* CLOCK_BOOTTIME */ isc_result_t isc_time_now(isc_time_t *t); /*%< * Set 't' to the current absolute time. * * Requires: * *\li 't' is a valid pointer. * * Returns: * *\li Success *\li Unexpected error * Getting the time from the system failed. *\li Out of range * The time from the system is too large to be represented * in the current definition of isc_time_t. */ isc_result_t isc_time_nowplusinterval(isc_time_t *t, const isc_interval_t *i); /*%< * Set *t to the current absolute time + i. * * Note: *\li This call is equivalent to: * *\code * isc_time_now(t); * isc_time_add(t, i, t); *\endcode * * Requires: * *\li 't' and 'i' are valid pointers. * * Returns: * *\li Success *\li Unexpected error * Getting the time from the system failed. *\li Out of range * The interval added to the time from the system is too large to * be represented in the current definition of isc_time_t. */ int isc_time_compare(const isc_time_t *t1, const isc_time_t *t2); /*%< * Compare the times referenced by 't1' and 't2' * * Requires: * *\li 't1' and 't2' are valid pointers. * * Returns: * *\li -1 t1 < t2 (comparing times, not pointers) *\li 0 t1 = t2 *\li 1 t1 > t2 */ isc_result_t isc_time_add(const isc_time_t *t, const isc_interval_t *i, isc_time_t *result); /*%< * Add 'i' to 't', storing the result in 'result'. * * Requires: * *\li 't', 'i', and 'result' are valid pointers. * * Returns: *\li Success *\li Out of range * The interval added to the time is too large to * be represented in the current definition of isc_time_t. */ isc_result_t isc_time_subtract(const isc_time_t *t, const isc_interval_t *i, isc_time_t *result); /*%< * Subtract 'i' from 't', storing the result in 'result'. * * Requires: * *\li 't', 'i', and 'result' are valid pointers. * * Returns: *\li Success *\li Out of range * The interval is larger than the time since the epoch. */ uint64_t isc_time_microdiff(const isc_time_t *t1, const isc_time_t *t2); /*%< * Find the difference in microseconds between time t1 and time t2. * t2 is the subtrahend of t1; ie, difference = t1 - t2. * * Requires: * *\li 't1' and 't2' are valid pointers. * * Returns: *\li The difference of t1 - t2, or 0 if t1 <= t2. */ uint32_t isc_time_seconds(const isc_time_t *t); /*%< * Return the number of seconds since the epoch stored in a time structure. * * Requires: * *\li 't' is a valid pointer. */ isc_result_t isc_time_secondsastimet(const isc_time_t *t, time_t *secondsp); /*%< * Ensure the number of seconds in an isc_time_t is representable by a time_t. * * Notes: *\li The number of seconds stored in an isc_time_t might be larger * than the number of seconds a time_t is able to handle. Since * time_t is mostly opaque according to the ANSI/ISO standard * (essentially, all you can be sure of is that it is an arithmetic type, * not even necessarily integral), it can be tricky to ensure that * the isc_time_t is in the range a time_t can handle. Use this * function in place of isc_time_seconds() any time you need to set a * time_t from an isc_time_t. * * Requires: *\li 't' is a valid pointer. * * Returns: *\li Success *\li Out of range */ uint32_t isc_time_nanoseconds(const isc_time_t *t); /*%< * Return the number of nanoseconds stored in a time structure. * * Notes: *\li This is the number of nanoseconds in excess of the number * of seconds since the epoch; it will always be less than one * full second. * * Requires: *\li 't' is a valid pointer. * * Ensures: *\li The returned value is less than 1*10^9. */ void isc_time_formattimestamp(const isc_time_t *t, char *buf, unsigned int len); /*%< * Format the time 't' into the buffer 'buf' of length 'len', * using a format like "30-Aug-2000 04:06:47.997" and the local time zone. * If the text does not fit in the buffer, the result is indeterminate, * but is always guaranteed to be null terminated. * * Requires: *\li 'len' > 0 *\li 'buf' points to an array of at least len chars * */ void isc_time_formathttptimestamp(const isc_time_t *t, char *buf, unsigned int len); /*%< * Format the time 't' into the buffer 'buf' of length 'len', * using a format like "Mon, 30 Aug 2000 04:06:47 GMT" * If the text does not fit in the buffer, the result is indeterminate, * but is always guaranteed to be null terminated. * * Requires: *\li 'len' > 0 *\li 'buf' points to an array of at least len chars * */ isc_result_t isc_time_parsehttptimestamp(char *input, isc_time_t *t); /*%< * Parse the time in 'input' into the isc_time_t pointed to by 't', * expecting a format like "Mon, 30 Aug 2000 04:06:47 GMT" * * Requires: *\li 'buf' and 't' are not NULL. */ void isc_time_formatISO8601(const isc_time_t *t, char *buf, unsigned int len); /*%< * Format the time 't' into the buffer 'buf' of length 'len', * using the ISO8601 format: "yyyy-mm-ddThh:mm:ssZ" * If the text does not fit in the buffer, the result is indeterminate, * but is always guaranteed to be null terminated. * * Requires: *\li 'len' > 0 *\li 'buf' points to an array of at least len chars * */ void isc_time_formatISO8601ms(const isc_time_t *t, char *buf, unsigned int len); /*%< * Format the time 't' into the buffer 'buf' of length 'len', * using the ISO8601 format: "yyyy-mm-ddThh:mm:ss.sssZ" * If the text does not fit in the buffer, the result is indeterminate, * but is always guaranteed to be null terminated. * * Requires: *\li 'len' > 0 *\li 'buf' points to an array of at least len chars * */ ISC_LANG_ENDDECLS #endif /* ISC_TIME_H */ PKֺ1]; !F--file.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_FILE_H #define ISC_FILE_H 1 /*! \file isc/file.h */ #include #include #include #include #include ISC_LANG_BEGINDECLS isc_result_t isc_file_settime(const char *file, isc_time_t *time); isc_result_t isc_file_mode(const char *file, mode_t *modep); isc_result_t isc_file_getmodtime(const char *file, isc_time_t *time); /*!< * \brief Get the time of last modification of a file. * * Notes: *\li The time that is set is relative to the (OS-specific) epoch, as are * all isc_time_t structures. * * Requires: *\li file != NULL. *\li time != NULL. * * Ensures: *\li If the file could not be accessed, 'time' is unchanged. * * Returns: *\li #ISC_R_SUCCESS * Success. *\li #ISC_R_NOTFOUND * No such file exists. *\li #ISC_R_INVALIDFILE * The path specified was not usable by the operating system. *\li #ISC_R_NOPERM * The file's metainformation could not be retrieved because * permission was denied to some part of the file's path. *\li #ISC_R_IOERROR * Hardware error interacting with the filesystem. *\li #ISC_R_UNEXPECTED * Something totally unexpected happened. * */ isc_result_t isc_file_mktemplate(const char *path, char *buf, size_t buflen); /*!< * \brief Generate a template string suitable for use with isc_file_openunique(). * * Notes: *\li This function is intended to make creating temporary files * portable between different operating systems. * *\li The path is prepended to an implementation-defined string and * placed into buf. The string has no path characters in it, * and its maximum length is 14 characters plus a NUL. Thus * buflen should be at least strlen(path) + 15 characters or * an error will be returned. * * Requires: *\li buf != NULL. * * Ensures: *\li If result == #ISC_R_SUCCESS: * buf contains a string suitable for use as the template argument * to isc_file_openunique(). * *\li If result != #ISC_R_SUCCESS: * buf is unchanged. * * Returns: *\li #ISC_R_SUCCESS Success. *\li #ISC_R_NOSPACE buflen indicates buf is too small for the catenation * of the path with the internal template string. */ isc_result_t isc_file_openunique(char *templet, FILE **fp); isc_result_t isc_file_openuniqueprivate(char *templet, FILE **fp); isc_result_t isc_file_openuniquemode(char *templet, int mode, FILE **fp); isc_result_t isc_file_bopenunique(char *templet, FILE **fp); isc_result_t isc_file_bopenuniqueprivate(char *templet, FILE **fp); isc_result_t isc_file_bopenuniquemode(char *templet, int mode, FILE **fp); /*!< * \brief Create and open a file with a unique name based on 'templet'. * isc_file_bopen*() open the file in binary mode in Windows. * isc_file_open*() open the file in text mode in Windows. * * Notes: *\li 'template' is a reserved work in C++. If you want to complain * about the spelling of 'templet', first look it up in the * Merriam-Webster English dictionary. (http://www.m-w.com/) * *\li This function works by using the template to generate file names. * The template must be a writable string, as it is modified in place. * Trailing X characters in the file name (full file name on Unix, * basename on Win32 -- eg, tmp-XXXXXX vs XXXXXX.tmp, respectively) * are replaced with ASCII characters until a non-existent filename * is found. If the template does not include pathname information, * the files in the working directory of the program are searched. * *\li isc_file_mktemplate is a good, portable way to get a template. * * Requires: *\li 'fp' is non-NULL and '*fp' is NULL. * *\li 'template' is non-NULL, and of a form suitable for use by * the system as described above. * * Ensures: *\li If result is #ISC_R_SUCCESS: * *fp points to an stream opening in stdio's "w+" mode. * *\li If result is not #ISC_R_SUCCESS: * *fp is NULL. * * No file is open. Even if one was created (but unable * to be reopened as a stdio FILE pointer) then it has been * removed. * *\li This function does *not* ensure that the template string has not been * modified, even if the operation was unsuccessful. * * Returns: *\li #ISC_R_SUCCESS * Success. *\li #ISC_R_EXISTS * No file with a unique name could be created based on the * template. *\li #ISC_R_INVALIDFILE * The path specified was not usable by the operating system. *\li #ISC_R_NOPERM * The file could not be created because permission was denied * to some part of the file's path. *\li #ISC_R_IOERROR * Hardware error interacting with the filesystem. *\li #ISC_R_UNEXPECTED * Something totally unexpected happened. */ isc_result_t isc_file_remove(const char *filename); /*!< * \brief Remove the file named by 'filename'. */ isc_result_t isc_file_rename(const char *oldname, const char *newname); /*!< * \brief Rename the file 'oldname' to 'newname'. */ bool isc_file_exists(const char *pathname); /*!< * \brief Return #true if the calling process can tell that the given file exists. * Will not return true if the calling process has insufficient privileges * to search the entire path. */ bool isc_file_isabsolute(const char *filename); /*!< * \brief Return #true if the given file name is absolute. */ isc_result_t isc_file_isplainfile(const char *name); isc_result_t isc_file_isplainfilefd(int fd); /*!< * \brief Check that the file is a plain file * * Returns: *\li #ISC_R_SUCCESS * Success. The file is a plain file. *\li #ISC_R_INVALIDFILE * The path specified was not usable by the operating system. *\li #ISC_R_FILENOTFOUND * The file does not exist. This return code comes from * errno=ENOENT when stat returns -1. This code is mentioned * here, because in logconf.c, it is the one rcode that is * permitted in addition to ISC_R_SUCCESS. This is done since * the next call in logconf.c is to isc_stdio_open(), which * will create the file if it can. *\li other ISC_R_* errors translated from errno * These occur when stat returns -1 and an errno. */ isc_result_t isc_file_isdirectory(const char *name); /*!< * \brief Check that 'name' exists and is a directory. * * Returns: *\li #ISC_R_SUCCESS * Success, file is a directory. *\li #ISC_R_INVALIDFILE * File is not a directory. *\li #ISC_R_FILENOTFOUND * File does not exist. *\li other ISC_R_* errors translated from errno * These occur when stat returns -1 and an errno. */ bool isc_file_iscurrentdir(const char *filename); /*!< * \brief Return #true if the given file name is the current directory ("."). */ bool isc_file_ischdiridempotent(const char *filename); /*%< * Return #true if calling chdir(filename) multiple times will give * the same result as calling it once. */ const char * isc_file_basename(const char *filename); /*%< * Return the final component of the path in the file name. */ isc_result_t isc_file_progname(const char *filename, char *buf, size_t buflen); /*!< * \brief Given an operating system specific file name "filename" * referring to a program, return the canonical program name. * * Any directory prefix or executable file name extension (if * used on the OS in case) is stripped. On systems where program * names are case insensitive, the name is canonicalized to all * lower case. The name is written to 'buf', an array of 'buflen' * chars, and null terminated. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOSPACE The name did not fit in 'buf'. */ isc_result_t isc_file_template(const char *path, const char *templet, char *buf, size_t buflen); /*%< * Create an OS specific template using 'path' to define the directory * 'templet' to describe the filename and store the result in 'buf' * such that path can be renamed to buf atomically. */ isc_result_t isc_file_renameunique(const char *file, char *templet); /*%< * Rename 'file' using 'templet' as a template for the new file name. */ isc_result_t isc_file_absolutepath(const char *filename, char *path, size_t pathlen); /*%< * Given a file name, return the fully qualified path to the file. */ /* * XXX We should also have a isc_file_writeeopen() function * for safely open a file in a publicly writable directory * (see write_open() in BIND 8's ns_config.c). */ isc_result_t isc_file_truncate(const char *filename, isc_offset_t size); /*%< * Truncate/extend the file specified to 'size' bytes. */ isc_result_t isc_file_safecreate(const char *filename, FILE **fp); /*%< * Open 'filename' for writing, truncating if necessary. Ensure that * if it existed it was a normal file. If creating the file, ensure * that only the owner can read/write it. */ isc_result_t isc_file_splitpath(isc_mem_t *mctx, const char *path, char **dirname, char const **basename); /*%< * Split a path into dirname and basename. If 'path' contains no slash * (or, on windows, backslash), then '*dirname' is set to ".". * * Allocates memory for '*dirname', which can be freed with isc_mem_free(). * * Returns: * - ISC_R_SUCCESS on success * - ISC_R_INVALIDFILE if 'path' is empty or ends with '/' * - ISC_R_NOMEMORY if unable to allocate memory */ isc_result_t isc_file_getsize(const char *file, off_t *size); /*%< * Return the size of the file (stored in the parameter pointed * to by 'size') in bytes. * * Returns: * - ISC_R_SUCCESS on success */ isc_result_t isc_file_getsizefd(int fd, off_t *size); /*%< * Return the size of the file (stored in the parameter pointed * to by 'size') in bytes. * * Returns: * - ISC_R_SUCCESS on success */ void * isc_file_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset); /*%< * Portable front-end to mmap(). If mmap() is not defined on this * platform, then we simulate it by calling malloc() and read(). * (In this event, the addr, prot, and flags parameters are ignored). */ int isc_file_munmap(void *addr, size_t len); /*%< * Portable front-end to munmap(). If munmap() is not defined on * this platform, then we simply free the memory. */ isc_result_t isc_file_sanitize(const char *dir, const char *base, const char *ext, char *path, size_t length); /*%< * Generate a sanitized filename, such as for MKEYS or NZF files. * * Historically, MKEYS and NZF files used SHA256 hashes of the view * name for the filename; this was to deal with the possibility of * forbidden characters such as "/" being in a view name, and to * avoid problems with case-insensitive file systems. * * Given a basename 'base' and an extension 'ext', this function checks * for the existence of file using the old-style name format in directory * 'dir'. If found, it returns the path to that file. If there is no * file already in place, a new pathname is generated; if the basename * contains any excluded characters, then a truncated SHA256 hash is * used, otherwise the basename is used. The path name is copied * into 'path', which must point to a buffer of at least 'length' * bytes. * * Requires: * - base != NULL * - path != NULL * * Returns: * - ISC_R_SUCCESS on success * - ISC_R_NOSPACE if the resulting path would be longer than 'length' */ bool isc_file_isdirwritable(const char *path); /*%< * Return true if the path is a directory and is writable */ ISC_LANG_ENDDECLS #endif /* ISC_FILE_H */ PKֺ1]weesha2.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /* $FreeBSD: src/sys/crypto/sha2/sha2.h,v 1.1.2.1 2001/07/03 11:01:36 ume Exp $ */ /* $KAME: sha2.h,v 1.3 2001/03/12 08:27:48 itojun Exp $ */ /* * sha2.h * * Version 1.0.0beta1 * * Written by Aaron D. Gifford * * Copyright 2000 Aaron D. Gifford. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef ISC_SHA2_H #define ISC_SHA2_H #include #include #include #include /*** SHA-224/256/384/512 Various Length Definitions ***********************/ #define ISC_SHA224_BLOCK_LENGTH 64U #define ISC_SHA224_DIGESTLENGTH 28U #define ISC_SHA224_DIGESTSTRINGLENGTH (ISC_SHA224_DIGESTLENGTH * 2 + 1) #define ISC_SHA256_BLOCK_LENGTH 64U #define ISC_SHA256_DIGESTLENGTH 32U #define ISC_SHA256_DIGESTSTRINGLENGTH (ISC_SHA256_DIGESTLENGTH * 2 + 1) #define ISC_SHA384_BLOCK_LENGTH 128 #define ISC_SHA384_DIGESTLENGTH 48U #define ISC_SHA384_DIGESTSTRINGLENGTH (ISC_SHA384_DIGESTLENGTH * 2 + 1) #define ISC_SHA512_BLOCK_LENGTH 128U #define ISC_SHA512_DIGESTLENGTH 64U #define ISC_SHA512_DIGESTSTRINGLENGTH (ISC_SHA512_DIGESTLENGTH * 2 + 1) /*** SHA-256/384/512 Context Structures *******************************/ #if defined(ISC_PLATFORM_OPENSSLHASH) #include #include #endif #if defined(ISC_PLATFORM_OPENSSLHASH) && !defined(LIBRESSL_VERSION_NUMBER) typedef struct { EVP_MD_CTX *ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) EVP_MD_CTX _ctx; #endif } isc_sha2_t; typedef isc_sha2_t isc_sha256_t; typedef isc_sha2_t isc_sha512_t; #elif PKCS11CRYPTO #include typedef pk11_context_t isc_sha256_t; typedef pk11_context_t isc_sha512_t; #else /* * Keep buffer immediately after bitcount to preserve alignment. */ typedef struct { uint32_t state[8]; uint64_t bitcount; uint8_t buffer[ISC_SHA256_BLOCK_LENGTH]; } isc_sha256_t; /* * Keep buffer immediately after bitcount to preserve alignment. */ typedef struct { uint64_t state[8]; uint64_t bitcount[2]; uint8_t buffer[ISC_SHA512_BLOCK_LENGTH]; } isc_sha512_t; #endif typedef isc_sha256_t isc_sha224_t; typedef isc_sha512_t isc_sha384_t; ISC_LANG_BEGINDECLS /*** SHA-224/256/384/512 Function Prototypes ******************************/ void isc_sha224_init (isc_sha224_t *); void isc_sha224_invalidate (isc_sha224_t *); void isc_sha224_update (isc_sha224_t *, const uint8_t *, size_t); void isc_sha224_final (uint8_t[ISC_SHA224_DIGESTLENGTH], isc_sha224_t *); char *isc_sha224_end (isc_sha224_t *, char[ISC_SHA224_DIGESTSTRINGLENGTH]); char *isc_sha224_data (const uint8_t *, size_t, char[ISC_SHA224_DIGESTSTRINGLENGTH]); void isc_sha256_init (isc_sha256_t *); void isc_sha256_invalidate (isc_sha256_t *); void isc_sha256_update (isc_sha256_t *, const uint8_t *, size_t); void isc_sha256_final (uint8_t[ISC_SHA256_DIGESTLENGTH], isc_sha256_t *); char *isc_sha256_end (isc_sha256_t *, char[ISC_SHA256_DIGESTSTRINGLENGTH]); char *isc_sha256_data (const uint8_t *, size_t, char[ISC_SHA256_DIGESTSTRINGLENGTH]); void isc_sha384_init (isc_sha384_t *); void isc_sha384_invalidate (isc_sha384_t *); void isc_sha384_update (isc_sha384_t *, const uint8_t *, size_t); void isc_sha384_final (uint8_t[ISC_SHA384_DIGESTLENGTH], isc_sha384_t *); char *isc_sha384_end (isc_sha384_t *, char[ISC_SHA384_DIGESTSTRINGLENGTH]); char *isc_sha384_data (const uint8_t *, size_t, char[ISC_SHA384_DIGESTSTRINGLENGTH]); void isc_sha512_init (isc_sha512_t *); void isc_sha512_invalidate (isc_sha512_t *); void isc_sha512_update (isc_sha512_t *, const uint8_t *, size_t); void isc_sha512_final (uint8_t[ISC_SHA512_DIGESTLENGTH], isc_sha512_t *); char *isc_sha512_end (isc_sha512_t *, char[ISC_SHA512_DIGESTSTRINGLENGTH]); char *isc_sha512_data (const uint8_t *, size_t, char[ISC_SHA512_DIGESTSTRINGLENGTH]); ISC_LANG_ENDDECLS #endif /* ISC_SHA2_H */ PKֺ1]~[ stdatomic.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #pragma once #if !defined(__has_feature) #define __has_feature(x) 0 #endif #if !defined(__has_extension) #define __has_extension(x) __has_feature(x) #endif #if !defined(__GNUC_PREREQ__) #if defined(__GNUC__) && defined(__GNUC_MINOR__) #define __GNUC_PREREQ__(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) #else #define __GNUC_PREREQ__(maj, min) 0 #endif #endif #if !defined(__CLANG_ATOMICS) && !defined(__GNUC_ATOMICS) #if __has_extension(c_atomic) || __has_extension(cxx_atomic) #define __CLANG_ATOMICS #elif __GNUC_PREREQ__(4, 7) #define __GNUC_ATOMICS #elif !defined(__GNUC__) /* cppcheck-suppress preprocessorErrorDirective */ #error "isc/stdatomic.h does not support your compiler" #endif #endif #ifndef __ATOMIC_RELAXED #define __ATOMIC_RELAXED 0 #endif #ifndef __ATOMIC_CONSUME #define __ATOMIC_CONSUME 1 #endif #ifndef __ATOMIC_ACQUIRE #define __ATOMIC_ACQUIRE 2 #endif #ifndef __ATOMIC_RELEASE #define __ATOMIC_RELEASE 3 #endif #ifndef __ATOMIC_ACQ_REL #define __ATOMIC_ACQ_REL 4 #endif #ifndef __ATOMIC_SEQ_CST #define __ATOMIC_SEQ_CST 5 #endif enum memory_order { memory_order_relaxed = __ATOMIC_RELAXED, memory_order_consume = __ATOMIC_CONSUME, memory_order_acquire = __ATOMIC_ACQUIRE, memory_order_release = __ATOMIC_RELEASE, memory_order_acq_rel = __ATOMIC_ACQ_REL, memory_order_seq_cst = __ATOMIC_SEQ_CST }; typedef enum memory_order memory_order; typedef int_fast32_t atomic_int_fast32_t; typedef uint_fast32_t atomic_uint_fast32_t; typedef int_fast64_t atomic_int_fast64_t; typedef uint_fast64_t atomic_uint_fast64_t; #if defined(__CLANG_ATOMICS) /* __c11_atomic builtins */ #define atomic_init(obj, desired) \ __c11_atomic_init(obj, desired) #define atomic_load_explicit(obj, order) \ __c11_atomic_load(obj, order) #define atomic_store_explicit(obj, desired, order) \ __c11_atomic_store(obj, desired, order) #define atomic_fetch_add_explicit(obj, arg, order) \ __c11_atomic_fetch_add(obj, arg, order) #define atomic_fetch_sub_explicit(obj, arg, order) \ __c11_atomic_fetch_sub(obj, arg, order) #define atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, fail) \ __c11_atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, fail) #define atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, fail) \ __c11_atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, fail) #elif defined(__GNUC_ATOMICS) /* __atomic builtins */ #define atomic_init(obj, desired) \ (*obj = desired) #define atomic_load_explicit(obj, order) \ __atomic_load_n(obj, order) #define atomic_store_explicit(obj, desired, order) \ __atomic_store_n(obj, desired, order) #define atomic_fetch_add_explicit(obj, arg, order) \ __atomic_fetch_add(obj, arg, order) #define atomic_fetch_sub_explicit(obj, arg, order) \ __atomic_fetch_sub(obj, arg, order) #define atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, fail) \ __atomic_compare_exchange_n(obj, expected, desired, 0, succ, fail) #define atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, fail) \ __atomic_compare_exchange_n(obj, expected, desired, 1, succ, fail) #else /* __sync builtins */ #define atomic_init(obj, desired) \ (*obj = desired) #define atomic_load_explicit(obj, order) \ __sync_fetch_and_add(obj, 0) #define atomic_store_explicit(obj, desired, order) \ do { \ __sync_synchronize(); \ *obj = desired; \ __sync_synchronize(); \ } while (0); #define atomic_fetch_add_explicit(obj, arg, order) \ __sync_fetch_and_add(obj, arg) #define atomic_fetch_sub_explicit(obj, arg, order) \ __sync_fetch_and_sub(obj, arg, order) #define atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, fail) \ ({ \ __typeof__(obj) __v; \ _Bool __r; \ __v = __sync_val_compare_and_swap(obj, *(expected), desired); \ __r = *(expected) == __v; \ *(expected) = __v; \ __r; \ }) #define atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, fail) \ atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, fail) #endif #define atomic_load(obj) \ atomic_load_explicit(obj, memory_order_seq_cst) #define atomic_store(obj) \ atomic_store_explicit(obj, memory_order_seq_cst) #define atomic_fetch_add(obj) \ atomic_fetch_add_explicit(obj, arg, memory_order_seq_cst) #define atomic_fetch_sub(obj) \ atomic_fetch_sub_explicit(obj, arg, memory_order_seq_cst) #define atomic_compare_exchange_strong(obj, expected, desired) \ atomic_compare_exchange_strong_explicit(obj, expected, desired, memory_order_seq_cst, memory_order_seq_cst) #define atomic_compare_exchange_weak(obj, expected, desired) \ atomic_compare_exchange_weak_explicit(obj, expected, desired, memory_order_seq_cst, memory_order_seq_cst) PKֺ1]J RR boolean.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #pragma once /*! \file isc/boolean.h */ #define isc_boolean_t bool #define isc_boolean_false false #define isc_boolean_true true #define ISC_FALSE false #define ISC_TRUE true #define ISC_TF(x) (!!(x)) PKֺ1]toffset.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_OFFSET_H #define ISC_OFFSET_H 1 /*! \file * \brief * File offsets are operating-system dependent. */ #include /* Required for CHAR_BIT. */ #include #include /* For Linux Standard Base. */ typedef off_t isc_offset_t; #endif /* ISC_OFFSET_H */ PKֺ1]hvvresult.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_RESULT_H #define ISC_RESULT_H 1 /*! \file isc/result.h */ #include #include #define ISC_R_SUCCESS 0 /*%< success */ #define ISC_R_NOMEMORY 1 /*%< out of memory */ #define ISC_R_TIMEDOUT 2 /*%< timed out */ #define ISC_R_NOTHREADS 3 /*%< no available threads */ #define ISC_R_ADDRNOTAVAIL 4 /*%< address not available */ #define ISC_R_ADDRINUSE 5 /*%< address in use */ #define ISC_R_NOPERM 6 /*%< permission denied */ #define ISC_R_NOCONN 7 /*%< no pending connections */ #define ISC_R_NETUNREACH 8 /*%< network unreachable */ #define ISC_R_HOSTUNREACH 9 /*%< host unreachable */ #define ISC_R_NETDOWN 10 /*%< network down */ #define ISC_R_HOSTDOWN 11 /*%< host down */ #define ISC_R_CONNREFUSED 12 /*%< connection refused */ #define ISC_R_NORESOURCES 13 /*%< not enough free resources */ #define ISC_R_EOF 14 /*%< end of file */ #define ISC_R_BOUND 15 /*%< socket already bound */ #define ISC_R_RELOAD 16 /*%< reload */ #define ISC_R_SUSPEND ISC_R_RELOAD /*%< alias of 'reload' */ #define ISC_R_LOCKBUSY 17 /*%< lock busy */ #define ISC_R_EXISTS 18 /*%< already exists */ #define ISC_R_NOSPACE 19 /*%< ran out of space */ #define ISC_R_CANCELED 20 /*%< operation canceled */ #define ISC_R_NOTBOUND 21 /*%< socket is not bound */ #define ISC_R_SHUTTINGDOWN 22 /*%< shutting down */ #define ISC_R_NOTFOUND 23 /*%< not found */ #define ISC_R_UNEXPECTEDEND 24 /*%< unexpected end of input */ #define ISC_R_FAILURE 25 /*%< generic failure */ #define ISC_R_IOERROR 26 /*%< I/O error */ #define ISC_R_NOTIMPLEMENTED 27 /*%< not implemented */ #define ISC_R_UNBALANCED 28 /*%< unbalanced parentheses */ #define ISC_R_NOMORE 29 /*%< no more */ #define ISC_R_INVALIDFILE 30 /*%< invalid file */ #define ISC_R_BADBASE64 31 /*%< bad base64 encoding */ #define ISC_R_UNEXPECTEDTOKEN 32 /*%< unexpected token */ #define ISC_R_QUOTA 33 /*%< quota reached */ #define ISC_R_UNEXPECTED 34 /*%< unexpected error */ #define ISC_R_ALREADYRUNNING 35 /*%< already running */ #define ISC_R_IGNORE 36 /*%< ignore */ #define ISC_R_MASKNONCONTIG 37 /*%< addr mask not contiguous */ #define ISC_R_FILENOTFOUND 38 /*%< file not found */ #define ISC_R_FILEEXISTS 39 /*%< file already exists */ #define ISC_R_NOTCONNECTED 40 /*%< socket is not connected */ #define ISC_R_RANGE 41 /*%< out of range */ #define ISC_R_NOENTROPY 42 /*%< out of entropy */ #define ISC_R_MULTICAST 43 /*%< invalid use of multicast */ #define ISC_R_NOTFILE 44 /*%< not a file */ #define ISC_R_NOTDIRECTORY 45 /*%< not a directory */ #define ISC_R_QUEUEFULL 46 /*%< queue is full */ #define ISC_R_FAMILYMISMATCH 47 /*%< address family mismatch */ #define ISC_R_FAMILYNOSUPPORT 48 /*%< AF not supported */ #define ISC_R_BADHEX 49 /*%< bad hex encoding */ #define ISC_R_TOOMANYOPENFILES 50 /*%< too many open files */ #define ISC_R_NOTBLOCKING 51 /*%< not blocking */ #define ISC_R_UNBALANCEDQUOTES 52 /*%< unbalanced quotes */ #define ISC_R_INPROGRESS 53 /*%< operation in progress */ #define ISC_R_CONNECTIONRESET 54 /*%< connection reset */ #define ISC_R_SOFTQUOTA 55 /*%< soft quota reached */ #define ISC_R_BADNUMBER 56 /*%< not a valid number */ #define ISC_R_DISABLED 57 /*%< disabled */ #define ISC_R_MAXSIZE 58 /*%< max size */ #define ISC_R_BADADDRESSFORM 59 /*%< invalid address format */ #define ISC_R_BADBASE32 60 /*%< bad base32 encoding */ #define ISC_R_UNSET 61 /*%< unset */ #define ISC_R_MULTIPLE 62 /*%< multiple */ #define ISC_R_WOULDBLOCK 63 /*%< would block */ #define ISC_R_COMPLETE 64 /*%< complete */ #define ISC_R_CRYPTOFAILURE 65 /*%< cryptography library failure */ #define ISC_R_DISCQUOTA 66 /*%< disc quota */ #define ISC_R_DISCFULL 67 /*%< disc full */ #define ISC_R_DEFAULT 68 /*%< default */ #define ISC_R_IPV4PREFIX 69 /*%< IPv4 prefix */ #define ISC_R_TIMESHIFTED 70 /*%< system time changed */ #define ISC_R_NRESULTS 71 ISC_LANG_BEGINDECLS const char * isc_result_totext(isc_result_t); /*%< * Convert an isc_result_t into a string message describing the result. */ const char * isc_result_toid(isc_result_t); /*%< * Convert an isc_result_t into a string identifier such as * "ISC_R_SUCCESS". */ isc_result_t isc_result_register(unsigned int base, unsigned int nresults, const char **text, isc_msgcat_t *msgcat, int set); isc_result_t isc_result_registerids(unsigned int base, unsigned int nresults, const char **ids, isc_msgcat_t *msgcat, int set); ISC_LANG_ENDDECLS #endif /* ISC_RESULT_H */ PKֺ1]t.}} taskpool.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_TASKPOOL_H #define ISC_TASKPOOL_H 1 /***** ***** Module Info *****/ /*! \file isc/taskpool.h * \brief A task pool is a mechanism for sharing a small number of tasks * among a large number of objects such that each object is * assigned a unique task, but each task may be shared by several * objects. * * Task pools are used to let objects that can exist in large * numbers (e.g., zones) use tasks for synchronization without * the memory overhead and unfair scheduling competition that * could result from creating a separate task for each object. */ /*** *** Imports. ***/ #include #include #include ISC_LANG_BEGINDECLS /***** ***** Types. *****/ typedef struct isc_taskpool isc_taskpool_t; /***** ***** Functions. *****/ isc_result_t isc_taskpool_create(isc_taskmgr_t *tmgr, isc_mem_t *mctx, unsigned int ntasks, unsigned int quantum, isc_taskpool_t **poolp); /*%< * Create a task pool of "ntasks" tasks, each with quantum * "quantum". * * Requires: * *\li 'tmgr' is a valid task manager. * *\li 'mctx' is a valid memory context. * *\li poolp != NULL && *poolp == NULL * * Ensures: * *\li On success, '*taskp' points to the new task pool. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_UNEXPECTED */ void isc_taskpool_gettask(isc_taskpool_t *pool, isc_task_t **targetp); /*%< * Attach to a task from the pool. Currently the next task is chosen * from the pool at random. (This may be changed in the future to * something that guaratees balance.) */ int isc_taskpool_size(isc_taskpool_t *pool); /*%< * Returns the number of tasks in the task pool 'pool'. */ isc_result_t isc_taskpool_expand(isc_taskpool_t **sourcep, unsigned int size, isc_taskpool_t **targetp); /*%< * If 'size' is larger than the number of tasks in the pool pointed to by * 'sourcep', then a new taskpool of size 'size' is allocated, the existing * tasks from are moved into it, additional tasks are created to bring the * total number up to 'size', and the resulting pool is attached to * 'targetp'. * * If 'size' is less than or equal to the tasks in pool 'source', then * 'sourcep' is attached to 'targetp' without any other action being taken. * * In either case, 'sourcep' is detached. * * Requires: * * \li 'sourcep' is not NULL and '*source' is not NULL * \li 'targetp' is not NULL and '*source' is NULL * * Ensures: * * \li On success, '*targetp' points to a valid task pool. * \li On success, '*sourcep' points to NULL. * * Returns: * * \li #ISC_R_SUCCESS * \li #ISC_R_NOMEMORY */ void isc_taskpool_destroy(isc_taskpool_t **poolp); /*%< * Destroy a task pool. The tasks in the pool are detached but not * shut down. * * Requires: * \li '*poolp' is a valid task pool. */ void isc_taskpool_setprivilege(isc_taskpool_t *pool, bool priv); /*%< * Set the privilege flag on all tasks in 'pool' to 'priv'. If 'priv' is * true, then when the task manager is set into privileged mode, only * tasks wihin this pool will be able to execute. (Note: It is important * to turn the pool tasks' privilege back off before the last task finishes * executing.) * * Requires: * \li 'pool' is a valid task pool. */ ISC_LANG_ENDDECLS #endif /* ISC_TASKPOOL_H */ PKֺ1]6{ lfsr.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LFSR_H #define ISC_LFSR_H 1 /*! \file isc/lfsr.h */ #include #include #include typedef struct isc_lfsr isc_lfsr_t; /*% * This function is called when reseeding is needed. It is allowed to * modify any state in the LFSR in any way it sees fit OTHER THAN "bits". * * It MUST set "count" to a new value or the lfsr will never reseed again. * * Also, a reseed will never occur in the middle of an extraction. This * is purely an optimization, and is probably what one would want. */ typedef void (*isc_lfsrreseed_t)(isc_lfsr_t *, void *); /*% * The members of this structure can be used by the application, but care * needs to be taken to not change state once the lfsr is in operation. */ struct isc_lfsr { uint32_t state; /*%< previous state */ unsigned int bits; /*%< length */ uint32_t tap; /*%< bit taps */ unsigned int count; /*%< reseed count (in BITS!) */ isc_lfsrreseed_t reseed; /*%< reseed function */ void *arg; /*%< reseed function argument */ }; ISC_LANG_BEGINDECLS void isc_lfsr_init(isc_lfsr_t *lfsr, uint32_t state, unsigned int bits, uint32_t tap, unsigned int count, isc_lfsrreseed_t reseed, void *arg); /*%< * Initialize an LFSR. * * Note: * *\li Putting untrusted values into this function will cause the LFSR to * generate (perhaps) non-maximal length sequences. * * Requires: * *\li lfsr != NULL * *\li 8 <= bits <= 32 * *\li tap != 0 */ void isc_lfsr_generate(isc_lfsr_t *lfsr, void *data, unsigned int count); /*%< * Returns "count" bytes of data from the LFSR. * * Requires: * *\li lfsr be valid. * *\li data != NULL. * *\li count > 0. */ void isc_lfsr_skip(isc_lfsr_t *lfsr, unsigned int skip); /*%< * Skip "skip" states. * * Requires: * *\li lfsr be valid. */ uint32_t isc_lfsr_generate32(isc_lfsr_t *lfsr1, isc_lfsr_t *lfsr2); /*%< * Given two LFSRs, use the current state from each to skip entries in the * other. The next states are then xor'd together and returned. * * WARNING: * *\li This function is used only for very, very low security data, such * as DNS message IDs where it is desired to have an unpredictable * stream of bytes that are harder to predict than a simple flooding * attack. * * Notes: * *\li Since the current state from each of the LFSRs is used to skip * state in the other, it is important that no state be leaked * from either LFSR. * * Requires: * *\li lfsr1 and lfsr2 be valid. * *\li 1 <= skipbits <= 31 */ ISC_LANG_ENDDECLS #endif /* ISC_LFSR_H */ PKֺ1]z9crc64.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_CRC64_H #define ISC_CRC64_H 1 /*! \file isc/crc64.h * \brief CRC64 in C */ #include #include #include ISC_LANG_BEGINDECLS void isc_crc64_init(uint64_t *crc); /*% * Initialize a new CRC. * * Requires: * * 'crc' is not NULL. */ void isc_crc64_update(uint64_t *crc, const void *data, size_t len); /*% * Add data to the CRC. * * Requires: * * 'crc' is not NULL. * * 'data' is not NULL. */ void isc_crc64_final(uint64_t *crc); /*% * Finalize the CRC. * * Requires: * * 'crc' is not NULL. */ ISC_LANG_ENDDECLS #endif /* ISC_CRC64_H */ PKֺ1]   refcount.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_REFCOUNT_H #define ISC_REFCOUNT_H 1 #include #include #include #include #include #include #include #include #if defined(ISC_PLATFORM_HAVESTDATOMIC) #if defined (__cplusplus) #include #else #include #endif #endif /*! \file isc/refcount.h * \brief Implements a locked reference counter. * * These functions may actually be * implemented using macros, and implementations of these macros are below. * The isc_refcount_t type should not be accessed directly, as its contents * depend on the implementation. */ ISC_LANG_BEGINDECLS /* * Function prototypes */ /* * isc_result_t * isc_refcount_init(isc_refcount_t *ref, unsigned int n); * * Initialize the reference counter. There will be 'n' initial references. * * Requires: * ref != NULL */ /* * void * isc_refcount_destroy(isc_refcount_t *ref); * * Destroys a reference counter. * * Requires: * ref != NULL * The number of references is 0. */ /* * void * isc_refcount_increment(isc_refcount_t *ref, unsigned int *targetp); * isc_refcount_increment0(isc_refcount_t *ref, unsigned int *targetp); * * Increments the reference count, returning the new value in targetp if it's * not NULL. The reference counter typically begins with the initial counter * of 1, and will be destroyed once the counter reaches 0. Thus, * isc_refcount_increment() additionally requires the previous counter be * larger than 0 so that an error which violates the usage can be easily * caught. isc_refcount_increment0() does not have this restriction. * * Requires: * ref != NULL. */ /* * void * isc_refcount_decrement(isc_refcount_t *ref, unsigned int *targetp); * * Decrements the reference count, returning the new value in targetp if it's * not NULL. * * Requires: * ref != NULL. */ /* * Sample implementations */ #ifdef ISC_PLATFORM_USETHREADS #if defined(ISC_PLATFORM_HAVESTDATOMIC) # define ISC_REFCOUNT_HAVEATOMIC 1 # define ISC_REFCOUNT_HAVESTDATOMIC 1 #else /* defined(ISC_PLATFORM_HAVESTDATOMIC) */ # if defined(ISC_PLATFORM_HAVEXADD) # define ISC_REFCOUNT_HAVEATOMIC 1 # endif /* defined(ISC_PLATFORM_HAVEXADD */ #endif /* !defined(ISC_REFCOUNT_HAVEATOMIC) */ #if defined(ISC_REFCOUNT_HAVEATOMIC) typedef struct isc_refcount { #if defined(ISC_REFCOUNT_HAVESTDATOMIC) atomic_int_fast32_t refs; #else int32_t refs; #endif } isc_refcount_t; #if defined(ISC_REFCOUNT_HAVESTDATOMIC) #define isc_refcount_current(rp) \ ((unsigned int)(atomic_load_explicit(&(rp)->refs, \ memory_order_acquire))) #define isc_refcount_destroy(rp) ISC_REQUIRE(isc_refcount_current(rp) == 0) #define isc_refcount_increment0(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int32_t prev; \ prev = atomic_fetch_add_explicit \ (&(rp)->refs, 1, memory_order_relaxed); \ if (_tmp != NULL) \ *_tmp = prev + 1; \ } while (0) #define isc_refcount_increment(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int32_t prev; \ prev = atomic_fetch_add_explicit \ (&(rp)->refs, 1, memory_order_relaxed); \ ISC_REQUIRE(prev > 0); \ if (_tmp != NULL) \ *_tmp = prev + 1; \ } while (0) #define isc_refcount_decrement(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int32_t prev; \ prev = atomic_fetch_sub_explicit \ (&(rp)->refs, 1, memory_order_acq_rel); \ ISC_REQUIRE(prev > 0); \ if (_tmp != NULL) \ *_tmp = prev - 1; \ } while (0) #else /* defined(ISC_REFCOUNT_HAVESTDATOMIC) */ #define isc_refcount_current(rp) \ ((unsigned int)(isc_atomic_xadd(&(rp)->refs, 0))) #define isc_refcount_destroy(rp) ISC_REQUIRE(isc_refcount_current(rp) == 0) #define isc_refcount_increment0(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int32_t prev; \ prev = isc_atomic_xadd(&(rp)->refs, 1); \ if (_tmp != NULL) \ *_tmp = prev + 1; \ } while (0) #define isc_refcount_increment(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int32_t prev; \ prev = isc_atomic_xadd(&(rp)->refs, 1); \ ISC_REQUIRE(prev > 0); \ if (_tmp != NULL) \ *_tmp = prev + 1; \ } while (0) #define isc_refcount_decrement(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int32_t prev; \ prev = isc_atomic_xadd(&(rp)->refs, -1); \ ISC_REQUIRE(prev > 0); \ if (_tmp != NULL) \ *_tmp = prev - 1; \ } while (0) #endif /* defined(ISC_REFCOUNT_HAVESTDATOMIC) */ #else /* defined(ISC_REFCOUNT_HAVEATOMIC) */ typedef struct isc_refcount { int refs; isc_mutex_t lock; } isc_refcount_t; /*% Destroys a reference counter. */ #define isc_refcount_destroy(rp) \ do { \ isc_result_t _result; \ ISC_REQUIRE((rp)->refs == 0); \ _result = isc_mutex_destroy(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ } while (0) unsigned int isc_refcount_current(isc_refcount_t *rp); /*% * Increments the reference count, returning the new value in * 'tp' if it's not NULL. */ #define isc_refcount_increment0(rp, tp) \ do { \ isc_result_t _result; \ unsigned int *_tmp = (unsigned int *)(tp); \ _result = isc_mutex_lock(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ ++((rp)->refs); \ if (_tmp != NULL) \ *_tmp = ((rp)->refs); \ _result = isc_mutex_unlock(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ } while (0) #define isc_refcount_increment(rp, tp) \ do { \ isc_result_t _result; \ unsigned int *_tmp = (unsigned int *)(tp); \ _result = isc_mutex_lock(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ ISC_REQUIRE((rp)->refs > 0); \ ++((rp)->refs); \ if (_tmp != NULL) \ *_tmp = ((rp)->refs); \ _result = isc_mutex_unlock(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ } while (0) /*% * Decrements the reference count, returning the new value in 'tp' * if it's not NULL. */ #define isc_refcount_decrement(rp, tp) \ do { \ isc_result_t _result; \ unsigned int *_tmp = (unsigned int *)(tp); \ _result = isc_mutex_lock(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ ISC_REQUIRE((rp)->refs > 0); \ --((rp)->refs); \ if (_tmp != NULL) \ *_tmp = ((rp)->refs); \ _result = isc_mutex_unlock(&(rp)->lock); \ ISC_ERROR_RUNTIMECHECK(_result == ISC_R_SUCCESS); \ } while (0) #endif /* defined(ISC_REFCOUNT_ATOMIC) */ #else /* ISC_PLATFORM_USETHREADS */ typedef struct isc_refcount { int refs; } isc_refcount_t; #define isc_refcount_destroy(rp) ISC_REQUIRE((rp)->refs == 0) #define isc_refcount_current(rp) ((unsigned int)((rp)->refs)) #define isc_refcount_increment0(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int _n = ++(rp)->refs; \ if (_tmp != NULL) \ *_tmp = _n; \ } while (0) #define isc_refcount_increment(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int _n; \ ISC_REQUIRE((rp)->refs > 0); \ _n = ++(rp)->refs; \ if (_tmp != NULL) \ *_tmp = _n; \ } while (0) #define isc_refcount_decrement(rp, tp) \ do { \ unsigned int *_tmp = (unsigned int *)(tp); \ int _n; \ ISC_REQUIRE((rp)->refs > 0); \ _n = --(rp)->refs; \ if (_tmp != NULL) \ *_tmp = _n; \ } while (0) #endif /* ISC_PLATFORM_USETHREADS */ isc_result_t isc_refcount_init(isc_refcount_t *ref, unsigned int n); ISC_LANG_ENDDECLS #endif /* ISC_REFCOUNT_H */ PKֺ1]}} formatcheck.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_FORMATCHECK_H #define ISC_FORMATCHECK_H 1 /*! \file isc/formatcheck.h */ /*% * ISC_FORMAT_PRINTF(). * * \li fmt is the location of the format string parameter. * \li args is the location of the first argument (or 0 for no argument checking). * * Note: * \li The first parameter is 1, not 0. */ #ifdef __GNUC__ #define ISC_FORMAT_PRINTF(fmt, args) __attribute__((__format__(__printf__, fmt, args))) #else #define ISC_FORMAT_PRINTF(fmt, args) #endif #endif /* ISC_FORMATCHECK_H */ PKֺ1][ [ assertions.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/assertions.h */ #ifndef ISC_ASSERTIONS_H #define ISC_ASSERTIONS_H 1 #include #include #include ISC_LANG_BEGINDECLS /*% isc assertion type */ typedef enum { isc_assertiontype_require, isc_assertiontype_ensure, isc_assertiontype_insist, isc_assertiontype_invariant } isc_assertiontype_t; typedef void (*isc_assertioncallback_t)(const char *, int, isc_assertiontype_t, const char *); /* coverity[+kill] */ ISC_PLATFORM_NORETURN_PRE void isc_assertion_failed(const char *, int, isc_assertiontype_t, const char *) ISC_PLATFORM_NORETURN_POST; void isc_assertion_setcallback(isc_assertioncallback_t); const char * isc_assertion_typetotext(isc_assertiontype_t type); #if defined(ISC_CHECK_ALL) || defined(__COVERITY__) #define ISC_CHECK_REQUIRE 1 #define ISC_CHECK_ENSURE 1 #define ISC_CHECK_INSIST 1 #define ISC_CHECK_INVARIANT 1 #endif #if defined(ISC_CHECK_NONE) && !defined(__COVERITY__) #define ISC_CHECK_REQUIRE 0 #define ISC_CHECK_ENSURE 0 #define ISC_CHECK_INSIST 0 #define ISC_CHECK_INVARIANT 0 #endif #ifndef ISC_CHECK_REQUIRE #define ISC_CHECK_REQUIRE 1 #endif #ifndef ISC_CHECK_ENSURE #define ISC_CHECK_ENSURE 1 #endif #ifndef ISC_CHECK_INSIST #define ISC_CHECK_INSIST 1 #endif #ifndef ISC_CHECK_INVARIANT #define ISC_CHECK_INVARIANT 1 #endif #if ISC_CHECK_REQUIRE != 0 #define ISC_REQUIRE(cond) \ ((void) (ISC_LIKELY(cond) || \ ((isc_assertion_failed)(__FILE__, __LINE__, \ isc_assertiontype_require, \ #cond), 0))) #else #define ISC_REQUIRE(cond) ((void) ISC_LIKELY(cond)) #endif /* ISC_CHECK_REQUIRE */ #if ISC_CHECK_ENSURE != 0 #define ISC_ENSURE(cond) \ ((void) (ISC_LIKELY(cond) || \ ((isc_assertion_failed)(__FILE__, __LINE__, \ isc_assertiontype_ensure, \ #cond), 0))) #else #define ISC_ENSURE(cond) ((void) ISC_LIKELY(cond)) #endif /* ISC_CHECK_ENSURE */ #if ISC_CHECK_INSIST != 0 #define ISC_INSIST(cond) \ ((void) (ISC_LIKELY(cond) || \ ((isc_assertion_failed)(__FILE__, __LINE__, \ isc_assertiontype_insist, \ #cond), 0))) #else #define ISC_INSIST(cond) ((void) ISC_LIKELY(cond)) #endif /* ISC_CHECK_INSIST */ #if ISC_CHECK_INVARIANT != 0 #define ISC_INVARIANT(cond) \ ((void) (ISC_LIKELY(cond) || \ ((isc_assertion_failed)(__FILE__, __LINE__, \ isc_assertiontype_invariant, \ #cond), 0))) #else #define ISC_INVARIANT(cond) ((void) ISC_LIKELY(cond)) #endif /* ISC_CHECK_INVARIANT */ ISC_LANG_ENDDECLS #endif /* ISC_ASSERTIONS_H */ PKֺ1]J< mutex.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MUTEX_H #define ISC_MUTEX_H 1 /*! \file */ #include #include #include #include /* for ISC_R_ codes */ ISC_LANG_BEGINDECLS /*! * Supply mutex attributes that enable deadlock detection * (helpful when debugging). This is system dependent and * currently only supported on NetBSD. */ #if ISC_MUTEX_DEBUG && defined(__NetBSD__) && defined(PTHREAD_MUTEX_ERRORCHECK) extern pthread_mutexattr_t isc__mutex_attrs; #define ISC__MUTEX_ATTRS &isc__mutex_attrs #else #define ISC__MUTEX_ATTRS NULL #endif /* XXX We could do fancier error handling... */ /*! * Define ISC_MUTEX_PROFILE to turn on profiling of mutexes by line. When * enabled, isc_mutex_stats() can be used to print a table showing the * number of times each type of mutex was locked and the amount of time * waiting to obtain the lock. */ #ifndef ISC_MUTEX_PROFILE #define ISC_MUTEX_PROFILE 0 #endif #if ISC_MUTEX_PROFILE typedef struct isc_mutexstats isc_mutexstats_t; typedef struct { pthread_mutex_t mutex; /*%< The actual mutex. */ isc_mutexstats_t * stats; /*%< Mutex statistics. */ } isc_mutex_t; #else typedef pthread_mutex_t isc_mutex_t; #endif #if ISC_MUTEX_PROFILE #define isc_mutex_init(mp) \ isc_mutex_init_profile((mp), __FILE__, __LINE__) #else #if ISC_MUTEX_DEBUG && defined(PTHREAD_MUTEX_ERRORCHECK) #define isc_mutex_init(mp) \ isc_mutex_init_errcheck((mp)) #else #define isc_mutex_init(mp) \ isc__mutex_init((mp), __FILE__, __LINE__) isc_result_t isc__mutex_init(isc_mutex_t *mp, const char *file, unsigned int line); #endif #endif #if ISC_MUTEX_PROFILE #define isc_mutex_lock(mp) \ isc_mutex_lock_profile((mp), __FILE__, __LINE__) #else #define isc_mutex_lock(mp) \ ((pthread_mutex_lock((mp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #endif #if ISC_MUTEX_PROFILE #define isc_mutex_unlock(mp) \ isc_mutex_unlock_profile((mp), __FILE__, __LINE__) #else #define isc_mutex_unlock(mp) \ ((pthread_mutex_unlock((mp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #endif #if ISC_MUTEX_PROFILE #define isc_mutex_trylock(mp) \ ((pthread_mutex_trylock((&(mp)->mutex)) == 0) ? \ ISC_R_SUCCESS : ISC_R_LOCKBUSY) #else #define isc_mutex_trylock(mp) \ ((pthread_mutex_trylock((mp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_LOCKBUSY) #endif #if ISC_MUTEX_PROFILE #define isc_mutex_destroy(mp) \ ((pthread_mutex_destroy((&(mp)->mutex)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #else #define isc_mutex_destroy(mp) \ ((pthread_mutex_destroy((mp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #endif #if ISC_MUTEX_PROFILE #define isc_mutex_stats(fp) isc_mutex_statsprofile(fp); #else #define isc_mutex_stats(fp) #endif #if ISC_MUTEX_PROFILE isc_result_t isc_mutex_init_profile(isc_mutex_t *mp, const char * _file, int _line); isc_result_t isc_mutex_lock_profile(isc_mutex_t *mp, const char * _file, int _line); isc_result_t isc_mutex_unlock_profile(isc_mutex_t *mp, const char * _file, int _line); void isc_mutex_statsprofile(FILE *fp); #endif /* ISC_MUTEX_PROFILE */ isc_result_t isc_mutex_init_errcheck(isc_mutex_t *mp); ISC_LANG_ENDDECLS #endif /* ISC_MUTEX_H */ PKֺ1]˞ netaddr.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_NETADDR_H #define ISC_NETADDR_H 1 /*! \file isc/netaddr.h */ #include #include #include #include #include #ifdef ISC_PLATFORM_HAVESYSUNH #include #include #endif ISC_LANG_BEGINDECLS struct isc_netaddr { unsigned int family; union { struct in_addr in; struct in6_addr in6; #ifdef ISC_PLATFORM_HAVESYSUNH char un[sizeof(((struct sockaddr_un *)0)->sun_path)]; #endif } type; uint32_t zone; }; bool isc_netaddr_equal(const isc_netaddr_t *a, const isc_netaddr_t *b); /*%< * Compare network addresses 'a' and 'b'. Return #true if * they are equal, #false if not. */ bool isc_netaddr_eqprefix(const isc_netaddr_t *a, const isc_netaddr_t *b, unsigned int prefixlen); /*%< * Compare the 'prefixlen' most significant bits of the network * addresses 'a' and 'b'. If 'b''s scope is zero then 'a''s scope is * ignored. Return #true if they are equal, #false if not. */ isc_result_t isc_netaddr_masktoprefixlen(const isc_netaddr_t *s, unsigned int *lenp); /*%< * Convert a netmask in 's' into a prefix length in '*lenp'. * The mask should consist of zero or more '1' bits in the * most significant part of the address, followed by '0' bits. * If this is not the case, #ISC_R_MASKNONCONTIG is returned. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_MASKNONCONTIG */ isc_result_t isc_netaddr_totext(const isc_netaddr_t *netaddr, isc_buffer_t *target); /*%< * Append a text representation of 'sockaddr' to the buffer 'target'. * The text is NOT null terminated. Handles IPv4 and IPv6 addresses. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOSPACE The text or the null termination did not fit. *\li #ISC_R_FAILURE Unspecified failure */ void isc_netaddr_format(const isc_netaddr_t *na, char *array, unsigned int size); /*%< * Format a human-readable representation of the network address '*na' * into the character array 'array', which is of size 'size'. * The resulting string is guaranteed to be null-terminated. */ #define ISC_NETADDR_FORMATSIZE \ sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:XXX.XXX.XXX.XXX%SSSSSSSSSS") /*%< * Minimum size of array to pass to isc_netaddr_format(). */ void isc_netaddr_fromsockaddr(isc_netaddr_t *netaddr, const isc_sockaddr_t *source); void isc_netaddr_fromin(isc_netaddr_t *netaddr, const struct in_addr *ina); void isc_netaddr_fromin6(isc_netaddr_t *netaddr, const struct in6_addr *ina6); isc_result_t isc_netaddr_frompath(isc_netaddr_t *netaddr, const char *path); void isc_netaddr_setzone(isc_netaddr_t *netaddr, uint32_t zone); uint32_t isc_netaddr_getzone(const isc_netaddr_t *netaddr); void isc_netaddr_any(isc_netaddr_t *netaddr); /*%< * Return the IPv4 wildcard address. */ void isc_netaddr_any6(isc_netaddr_t *netaddr); /*%< * Return the IPv6 wildcard address. */ bool isc_netaddr_ismulticast(isc_netaddr_t *na); /*%< * Returns true if the address is a multicast address. */ bool isc_netaddr_isexperimental(isc_netaddr_t *na); /*%< * Returns true if the address is a experimental (CLASS E) address. */ bool isc_netaddr_islinklocal(isc_netaddr_t *na); /*%< * Returns #true if the address is a link local address. */ bool isc_netaddr_issitelocal(isc_netaddr_t *na); /*%< * Returns #true if the address is a site local address. */ bool isc_netaddr_isnetzero(isc_netaddr_t *na); /*%< * Returns #true if the address is in net zero. */ void isc_netaddr_fromv4mapped(isc_netaddr_t *t, const isc_netaddr_t *s); /*%< * Convert an IPv6 v4mapped address into an IPv4 address. */ isc_result_t isc_netaddr_prefixok(const isc_netaddr_t *na, unsigned int prefixlen); /* * Test whether the netaddr 'na' and 'prefixlen' are consistent. * e.g. prefixlen within range. * na does not have bits set which are not covered by the prefixlen. * * Returns: * ISC_R_SUCCESS * ISC_R_RANGE prefixlen out of range * ISC_R_NOTIMPLEMENTED unsupported family * ISC_R_FAILURE extra bits. */ bool isc_netaddr_isloopback(const isc_netaddr_t *na); /* * Test whether the netaddr 'na' is a loopback IPv4 or IPv6 address (in * 127.0.0.0/8 or ::1). */ ISC_LANG_ENDDECLS #endif /* ISC_NETADDR_H */ PKֺ1]-V(( entropy.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ENTROPY_H #define ISC_ENTROPY_H 1 /***** ***** Module Info *****/ /*! \file isc/entropy.h * \brief The entropy API * * \li MP: * The entropy object is locked internally. All callbacks into * application-provided functions (for setup, gathering, and * shutdown of sources) are guaranteed to be called with the * entropy API lock held. This means these functions are * not permitted to call back into the entropy API. * * \li Reliability: * No anticipated impact. * * \li Resources: * A buffer, used as an entropy pool. * * \li Security: * While this code is believed to implement good entropy gathering * and distribution, it has not been reviewed by a cryptographic * expert. * Since the added entropy is only as good as the sources used, * this module could hand out bad data and never know it. * * \li Standards: * None. */ /*** *** Imports ***/ #include #include #include #include /*@{*/ /*% Entropy callback function. */ typedef isc_result_t (*isc_entropystart_t)(isc_entropysource_t *source, void *arg, bool blocking); typedef isc_result_t (*isc_entropyget_t)(isc_entropysource_t *source, void *arg, bool blocking); typedef void (*isc_entropystop_t)(isc_entropysource_t *source, void *arg); /*@}*/ /*** *** Flags. ***/ /*! * \brief * Extract only "good" data; return failure if there is not enough * data available and there are no sources which we can poll to get * data, or those sources are empty. * * */ #define ISC_ENTROPY_GOODONLY 0x00000001U /*! * \brief * Extract as much good data as possible, but if there isn't enough * at hand, return what is available. This flag only makes sense * when used with _GOODONLY. */ #define ISC_ENTROPY_PARTIAL 0x00000002U /*! * \brief * Block the task until data is available. This is contrary to the * ISC task system, where tasks should never block. However, if * this is a special purpose application where blocking a task is * acceptable (say, an offline zone signer) this flag may be set. * This flag only makes sense when used with _GOODONLY, and will * block regardless of the setting for _PARTIAL. */ #define ISC_ENTROPY_BLOCKING 0x00000004U /*! * \brief * Estimate the amount of entropy contained in the sample pool. * If this is not set, the source will be gathered and periodically * mixed into the entropy pool, but no increment in contained entropy * will be assumed. This flag only makes sense on sample sources. */ #define ISC_ENTROPYSOURCE_ESTIMATE 0x00000001U /* * For use with isc_entropy_usebestsource(). */ /*! * \brief * Use the keyboard as the only entropy source. */ #define ISC_ENTROPY_KEYBOARDYES 1 /*! * \brief * Never use the keyboard as an entropy source. */ #define ISC_ENTROPY_KEYBOARDNO 2 /*! * \brief * Use the keyboard as an entropy source only if opening the * random device fails. */ #define ISC_ENTROPY_KEYBOARDMAYBE 3 ISC_LANG_BEGINDECLS /*** *** Functions ***/ isc_result_t isc_entropy_create(isc_mem_t *mctx, isc_entropy_t **entp); /*!< * \brief Create a new entropy object. */ void isc_entropy_attach(isc_entropy_t *ent, isc_entropy_t **entp); /*!< * Attaches to an entropy object. */ void isc_entropy_detach(isc_entropy_t **entp); /*!< * \brief Detaches from an entropy object. */ isc_result_t isc_entropy_createfilesource(isc_entropy_t *ent, const char *fname); /*!< * \brief Create a new entropy source from a file. * * The file is assumed to contain good randomness, and will be mixed directly * into the pool with every byte adding 8 bits of entropy. * * The file will be put into non-blocking mode, so it may be a device file, * such as /dev/random. /dev/urandom should not be used here if it can * be avoided, since it will always provide data even if it isn't good. * We will make as much pseudorandom data as we need internally if our * caller asks for it. * * If we hit end-of-file, we will stop reading from this source. Callers * who require strong random data will get failure when our pool drains. * The file will never be opened/read again once EOF is reached. */ void isc_entropy_destroysource(isc_entropysource_t **sourcep); /*!< * \brief Removes an entropy source from the entropy system. */ isc_result_t isc_entropy_createsamplesource(isc_entropy_t *ent, isc_entropysource_t **sourcep); /*!< * \brief Create an entropy source that consists of samples. Each sample is * added to the source via isc_entropy_addsamples(), below. */ isc_result_t isc_entropy_createcallbacksource(isc_entropy_t *ent, isc_entropystart_t start, isc_entropyget_t get, isc_entropystop_t stop, void *arg, isc_entropysource_t **sourcep); /*!< * \brief Create an entropy source that is polled via a callback. * * This would be used when keyboard input is used, or a GUI input method. * It can also be used to hook in any external entropy source. * * Samples are added via isc_entropy_addcallbacksample(), below. * _addcallbacksample() is the only function which may be called from * within an entropy API callback function. */ void isc_entropy_stopcallbacksources(isc_entropy_t *ent); /*!< * \brief Call the stop functions for callback sources that have had their * start functions called. */ /*@{*/ isc_result_t isc_entropy_addcallbacksample(isc_entropysource_t *source, uint32_t sample, uint32_t extra); isc_result_t isc_entropy_addsample(isc_entropysource_t *source, uint32_t sample, uint32_t extra); /*!< * \brief Add a sample to the sample source. * * The sample MUST be a timestamp * that increases over time, with the exception of wrap-around for * extremely high resolution timers which will quickly wrap-around * a 32-bit integer. * * The "extra" parameter is used only to add a bit more unpredictable * data. It is not used other than included in the hash of samples. * * When in an entropy API callback function, _addcallbacksource() must be * used. At all other times, _addsample() must be used. */ /*@}*/ isc_result_t isc_entropy_getdata(isc_entropy_t *ent, void *data, unsigned int length, unsigned int *returned, unsigned int flags); /*!< * \brief Get random data from entropy pool 'ent'. * * If a hook has been set up using isc_entropy_sethook() and * isc_entropy_usehook(), then the hook function will be called to get * random data. * * Otherwise, randomness is extracted from the entropy pool set up in BIND. * This may cause the pool to be loaded from various sources. Ths is done * by stirring the pool and returning a part of hash as randomness. * (Note that no secrets are given away here since parts of the hash are * XORed together before returning.) * * 'flags' may contain ISC_ENTROPY_GOODONLY, ISC_ENTROPY_PARTIAL, or * ISC_ENTROPY_BLOCKING. These will be honored if the hook function is * not in use. If it is, the flags will be passed to the hook function * but it may ignore them. * * Up to 'length' bytes of randomness are retrieved and copied into 'data'. * (If 'returned' is not NULL, and the number of bytes copied is less than * 'length' - which may happen if ISC_ENTROPY_PARTIAL was used - then the * number of bytes copied will be stored in *returned.) * * Returns: * \li ISC_R_SUCCESS on success * \li ISC_R_NOENTROPY if entropy pool is empty * \li other error codes are possible when a hook is in use */ void isc_entropy_putdata(isc_entropy_t *ent, void *data, unsigned int length, uint32_t entropy); /*!< * \brief Add "length" bytes in "data" to the entropy pool, incrementing the * pool's entropy count by "entropy." * * These bytes will prime the pseudorandom portion even if no entropy is * actually added. */ void isc_entropy_stats(isc_entropy_t *ent, FILE *out); /*!< * \brief Dump some (trivial) stats to the stdio stream "out". */ unsigned int isc_entropy_status(isc_entropy_t *end); /* * Returns the number of bits the pool currently contains. This is just * an estimate. */ isc_result_t isc_entropy_usebestsource(isc_entropy_t *ectx, isc_entropysource_t **source, const char *randomfile, int use_keyboard); /*!< * \brief Use whatever source of entropy is best. * * Notes: *\li If "randomfile" is not NULL, open it with * isc_entropy_createfilesource(). * *\li If "randomfile" is NULL and the system's random device was detected * when the program was configured and built, open that device with * isc_entropy_createfilesource(). * *\li If "use_keyboard" is #ISC_ENTROPY_KEYBOARDYES, then always open * the keyboard as an entropy source (possibly in addition to * "randomfile" or the random device). * *\li If "use_keyboard" is #ISC_ENTROPY_KEYBOARDMAYBE, open the keyboard only * if opening the random file/device fails. A message will be * printed describing the need for keyboard input. * *\li If "use_keyboard" is #ISC_ENTROPY_KEYBOARDNO, the keyboard will * never be opened. * * Returns: *\li #ISC_R_SUCCESS if at least one source of entropy could be started. * *\li #ISC_R_NOENTROPY if use_keyboard is #ISC_ENTROPY_KEYBOARDNO and * there is no random device pathname compiled into the program. * *\li A return code from isc_entropy_createfilesource() or * isc_entropy_createcallbacksource(). */ void isc_entropy_usehook(isc_entropy_t *ectx, bool onoff); /*!< * \brief Configure entropy context 'ectx' to use the hook function * * Sets the entropy context to call the hook function for random number * generation, if such a function has been configured via * isc_entropy_sethook(), whenever isc_entropy_getdata() is called. */ void isc_entropy_sethook(isc_entropy_getdata_t myhook); /*!< * \brief Set the hook function. * * The hook function is a global value: only one hook function * can be set in the system. Individual entropy contexts may be * configured to use it, or not, by calling isc_entropy_usehook(). */ ISC_LANG_ENDDECLS #endif /* ISC_ENTROPY_H */ PKֺ1]čO__netdb.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_NETDB_H #define ISC_NETDB_H 1 /***** ***** Module Info *****/ /*! \file * \brief * Portable netdb.h support. * * This module is responsible for defining the getby APIs. * * MP: *\li No impact. * * Reliability: *\li No anticipated impact. * * Resources: *\li N/A. * * Security: *\li No anticipated impact. * * Standards: *\li BSD API */ /*** *** Imports. ***/ #include #include #endif /* ISC_NETDB_H */ PKֺ1]ไPTTqueue.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /* * This is a generic implementation of a two-lock concurrent queue. * There are built-in mutex locks for the head and tail of the queue, * allowing elements to be safely added and removed at the same time. * * NULL is "end of list" * -1 is "not linked" */ #ifndef ISC_QUEUE_H #define ISC_QUEUE_H 1 #include #include #include #ifdef ISC_QUEUE_CHECKINIT #define ISC_QLINK_INSIST(x) ISC_INSIST(x) #else #define ISC_QLINK_INSIST(x) (void)0 #endif #define ISC_QLINK(type) struct { type *prev, *next; } #define ISC_QLINK_INIT(elt, link) \ do { \ (elt)->link.next = (elt)->link.prev = (void *)(-1); \ } while(0) #define ISC_QLINK_LINKED(elt, link) ((void*)(elt)->link.next != (void*)(-1)) #define ISC_QUEUE(type) struct { \ type *head, *tail; \ isc_mutex_t headlock, taillock; \ } #define ISC_QUEUE_INIT(queue, link) \ do { \ (void) isc_mutex_init(&(queue).taillock); \ (void) isc_mutex_init(&(queue).headlock); \ (queue).tail = (queue).head = NULL; \ } while (0) #define ISC_QUEUE_EMPTY(queue) ((queue).head == NULL) #define ISC_QUEUE_DESTROY(queue) \ do { \ ISC_QLINK_INSIST(ISC_QUEUE_EMPTY(queue)); \ (void) isc_mutex_destroy(&(queue).taillock); \ (void) isc_mutex_destroy(&(queue).headlock); \ } while (0) /* * queues are meant to separate the locks at either end. For best effect, that * means keeping the ends separate - i.e. non-empty queues work best. * * a push to an empty queue has to take the pop lock to update * the pop side of the queue. * Popping the last entry has to take the push lock to update * the push side of the queue. * * The order is (pop, push), because a pop is presumably in the * latency path and a push is when we're done. * * We do an MT hot test in push to see if we need both locks, so we can * acquire them in order. Hopefully that makes the case where we get * the push lock and find we need the pop lock (and have to release it) rare. * * > 1 entry - no collision, push works on one end, pop on the other * 0 entry - headlock race * pop wins - return(NULL), push adds new as both head/tail * push wins - updates head/tail, becomes 1 entry case. * 1 entry - taillock race * pop wins - return(pop) sets head/tail NULL, becomes 0 entry case * push wins - updates {head,tail}->link.next, pop updates head * with new ->link.next and doesn't update tail * */ #define ISC_QUEUE_PUSH(queue, elt, link) \ do { \ bool headlocked = false; \ ISC_QLINK_INSIST(!ISC_QLINK_LINKED(elt, link)); \ LOCK(&(queue).taillock); \ if ((queue).tail == NULL) { \ UNLOCK(&(queue).taillock); \ LOCK(&(queue).headlock); \ LOCK(&(queue).taillock); \ headlocked = true; \ } \ (elt)->link.prev = (queue).tail; \ (elt)->link.next = NULL; \ if ((queue).tail != NULL) \ (queue).tail->link.next = (elt); \ (queue).tail = (elt); \ UNLOCK(&(queue).taillock); \ if (headlocked) { \ if ((queue).head == NULL) \ (queue).head = (elt); \ UNLOCK(&(queue).headlock); \ } \ } while (0) #define ISC_QUEUE_POP(queue, link, ret) \ do { \ LOCK(&(queue).headlock); \ ret = (queue).head; \ while (ret != NULL) { \ if (ret->link.next == NULL) { \ LOCK(&(queue).taillock); \ if (ret->link.next == NULL) { \ (queue).head = (queue).tail = NULL; \ UNLOCK(&(queue).taillock); \ break; \ }\ UNLOCK(&(queue).taillock); \ } \ (queue).head = ret->link.next; \ (queue).head->link.prev = NULL; \ break; \ } \ UNLOCK(&(queue).headlock); \ if (ret != NULL) \ (ret)->link.next = (ret)->link.prev = (void *)(-1); \ } while(0) #define ISC_QUEUE_UNLINK(queue, elt, link) \ do { \ ISC_QLINK_INSIST(ISC_QLINK_LINKED(elt, link)); \ LOCK(&(queue).headlock); \ LOCK(&(queue).taillock); \ if ((elt)->link.prev == NULL) \ (queue).head = (elt)->link.next; \ else \ (elt)->link.prev->link.next = (elt)->link.next; \ if ((elt)->link.next == NULL) \ (queue).tail = (elt)->link.prev; \ else \ (elt)->link.next->link.prev = (elt)->link.prev; \ UNLOCK(&(queue).taillock); \ UNLOCK(&(queue).headlock); \ (elt)->link.next = (elt)->link.prev = (void *)(-1); \ } while(0) #define ISC_QUEUE_UNLINKIFLINKED(queue, elt, link) \ do { \ LOCK(&(queue).headlock); \ LOCK(&(queue).taillock); \ if (ISC_QLINK_LINKED(elt, link)) { \ if ((elt)->link.prev == NULL) \ (queue).head = (elt)->link.next; \ else \ (elt)->link.prev->link.next = (elt)->link.next; \ if ((elt)->link.next == NULL) \ (queue).tail = (elt)->link.prev; \ else \ (elt)->link.next->link.prev = (elt)->link.prev; \ } \ UNLOCK(&(queue).taillock); \ UNLOCK(&(queue).headlock); \ (elt)->link.next = (elt)->link.prev = (void *)(-1); \ } while(0) #endif /* ISC_QUEUE_H */ PKֺ1]P r pool.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_OBJPOOL_H #define ISC_OBJPOOL_H 1 /***** ***** Module Info *****/ /*! \file isc/pool.h * \brief An object pool is a mechanism for sharing a small pool of * fungible objects among a large number of objects that depend on them. * * This is useful, for example, when it causes performance problems for * large number of zones to share a single memory context or task object, * but it would create a different set of problems for them each to have an * independent task or memory context. */ /*** *** Imports. ***/ #include #include #include ISC_LANG_BEGINDECLS /***** ***** Types. *****/ typedef void (*isc_pooldeallocator_t)(void **object); typedef isc_result_t (*isc_poolinitializer_t)(void **target, void *arg); typedef struct isc_pool isc_pool_t; /***** ***** Functions. *****/ isc_result_t isc_pool_create(isc_mem_t *mctx, unsigned int count, isc_pooldeallocator_t free, isc_poolinitializer_t init, void *initarg, isc_pool_t **poolp); /*%< * Create a pool of "count" object pointers. If 'free' is not NULL, * it points to a function that will detach the objects. 'init' * points to a function that will initialize the arguments, and * 'arg' to an argument to be passed into that function (for example, * a relevant manager or context object). * * Requires: * *\li 'mctx' is a valid memory context. * *\li init != NULL * *\li poolp != NULL && *poolp == NULL * * Ensures: * *\li On success, '*poolp' points to the new object pool. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_UNEXPECTED */ void * isc_pool_get(isc_pool_t *pool); /*%< * Returns a pointer to an object from the pool. Currently the object * is chosen from the pool at random. (This may be changed in the future * to something that guaratees balance.) */ int isc_pool_count(isc_pool_t *pool); /*%< * Returns the number of objcts in the pool 'pool'. */ isc_result_t isc_pool_expand(isc_pool_t **sourcep, unsigned int count, isc_pool_t **targetp); /*%< * If 'size' is larger than the number of objects in the pool pointed to by * 'sourcep', then a new pool of size 'count' is allocated, the existing * objects are copied into it, additional ones created to bring the * total number up to 'count', and the resulting pool is attached to * 'targetp'. * * If 'count' is less than or equal to the number of objects in 'source', then * 'sourcep' is attached to 'targetp' without any other action being taken. * * In either case, 'sourcep' is detached. * * Requires: * * \li 'sourcep' is not NULL and '*source' is not NULL * \li 'targetp' is not NULL and '*source' is NULL * * Ensures: * * \li On success, '*targetp' points to a valid task pool. * \li On success, '*sourcep' points to NULL. * * Returns: * * \li #ISC_R_SUCCESS * \li #ISC_R_NOMEMORY */ void isc_pool_destroy(isc_pool_t **poolp); /*%< * Destroy a task pool. The tasks in the pool are detached but not * shut down. * * Requires: * \li '*poolp' is a valid task pool. */ ISC_LANG_ENDDECLS #endif /* ISC_OBJPOOL_H */ PKֺ1]v} HHatomic.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ATOMIC_H #define ISC_ATOMIC_H 1 #include #include #include #ifdef ISC_PLATFORM_USEGCCASM /* * This routine atomically increments the value stored in 'p' by 'val', and * returns the previous value. */ static __inline__ int32_t isc_atomic_xadd(int32_t *p, int32_t val) { int32_t prev = val; __asm__ volatile( #ifdef ISC_PLATFORM_USETHREADS "lock;" #endif "xadd %0, %1" :"=q"(prev) :"m"(*p), "0"(prev) :"memory", "cc"); return (prev); } #ifdef ISC_PLATFORM_HAVEXADDQ static __inline__ int64_t isc_atomic_xaddq(int64_t *p, int64_t val) { int64_t prev = val; __asm__ volatile( #ifdef ISC_PLATFORM_USETHREADS "lock;" #endif "xaddq %0, %1" :"=q"(prev) :"m"(*p), "0"(prev) :"memory", "cc"); return (prev); } #endif /* ISC_PLATFORM_HAVEXADDQ */ /* * This routine atomically stores the value 'val' in 'p' (32-bit version). */ static __inline__ void isc_atomic_store(int32_t *p, int32_t val) { __asm__ volatile( #ifdef ISC_PLATFORM_USETHREADS /* * xchg should automatically lock memory, but we add it * explicitly just in case (it at least doesn't harm) */ "lock;" #endif "xchgl %1, %0" : : "r"(val), "m"(*p) : "memory"); } #ifdef ISC_PLATFORM_HAVEATOMICSTOREQ /* * This routine atomically stores the value 'val' in 'p' (64-bit version). */ static __inline__ void isc_atomic_storeq(int64_t *p, int64_t val) { __asm__ volatile( #ifdef ISC_PLATFORM_USETHREADS /* * xchg should automatically lock memory, but we add it * explicitly just in case (it at least doesn't harm) */ "lock;" #endif "xchgq %1, %0" : : "r"(val), "m"(*p) : "memory"); } #endif /* ISC_PLATFORM_HAVEATOMICSTOREQ */ /* * This routine atomically replaces the value in 'p' with 'val', if the * original value is equal to 'cmpval'. The original value is returned in any * case. */ static __inline__ int32_t isc_atomic_cmpxchg(int32_t *p, int32_t cmpval, int32_t val) { __asm__ volatile( #ifdef ISC_PLATFORM_USETHREADS "lock;" #endif "cmpxchgl %1, %2" : "=a"(cmpval) : "r"(val), "m"(*p), "a"(cmpval) : "memory"); return (cmpval); } #elif defined(ISC_PLATFORM_USESTDASM) /* * The following are "generic" assembly code which implements the same * functionality in case the gcc extension cannot be used. It should be * better to avoid inlining below, since we directly refer to specific * positions of the stack frame, which would not actually point to the * intended address in the embedded mnemonic. */ static int32_t isc_atomic_xadd(int32_t *p, int32_t val) { (void)(p); (void)(val); __asm ( "movl 8(%ebp), %ecx\n" "movl 12(%ebp), %edx\n" #ifdef ISC_PLATFORM_USETHREADS "lock;" #endif "xadd %edx, (%ecx)\n" /* * set the return value directly in the register so that we * can avoid guessing the correct position in the stack for a * local variable. */ "movl %edx, %eax" ); } static void isc_atomic_store(int32_t *p, int32_t val) { (void)(p); (void)(val); __asm ( "movl 8(%ebp), %ecx\n" "movl 12(%ebp), %edx\n" #ifdef ISC_PLATFORM_USETHREADS "lock;" #endif "xchgl (%ecx), %edx\n" ); } static int32_t isc_atomic_cmpxchg(int32_t *p, int32_t cmpval, int32_t val) { (void)(p); (void)(cmpval); (void)(val); __asm ( "movl 8(%ebp), %ecx\n" "movl 12(%ebp), %eax\n" /* must be %eax for cmpxchgl */ "movl 16(%ebp), %edx\n" #ifdef ISC_PLATFORM_USETHREADS "lock;" #endif /* * If (%ecx) == %eax then (%ecx) := %edx. % %eax is set to old (%ecx), which will be the return value. */ "cmpxchgl %edx, (%ecx)" ); } #else /* !ISC_PLATFORM_USEGCCASM && !ISC_PLATFORM_USESTDASM */ #error "unsupported compiler. disable atomic ops by --disable-atomic" #endif #endif /* ISC_ATOMIC_H */ PKֺ1]Ϳee eventclass.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_EVENTCLASS_H #define ISC_EVENTCLASS_H 1 /*! \file isc/eventclass.h ***** Registry of Predefined Event Type Classes *****/ /*% * An event class is an unsigned 16 bit number. Each class may contain up * to 65536 events. An event type is formed by adding the event number * within the class to the class number. * */ #define ISC_EVENTCLASS(eclass) ((eclass) << 16) /*@{*/ /*! * Classes < 1024 are reserved for ISC use. * Event classes >= 1024 and <= 65535 are reserved for application use. */ #define ISC_EVENTCLASS_TASK ISC_EVENTCLASS(0) #define ISC_EVENTCLASS_TIMER ISC_EVENTCLASS(1) #define ISC_EVENTCLASS_SOCKET ISC_EVENTCLASS(2) #define ISC_EVENTCLASS_FILE ISC_EVENTCLASS(3) #define ISC_EVENTCLASS_DNS ISC_EVENTCLASS(4) #define ISC_EVENTCLASS_APP ISC_EVENTCLASS(5) #define ISC_EVENTCLASS_OMAPI ISC_EVENTCLASS(6) #define ISC_EVENTCLASS_RATELIMITER ISC_EVENTCLASS(7) #define ISC_EVENTCLASS_ISCCC ISC_EVENTCLASS(8) /*@}*/ #endif /* ISC_EVENTCLASS_H */ PKֺ1]Ϡ random.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_RANDOM_H #define ISC_RANDOM_H 1 #include #include #include #include #include /*! \file isc/random.h * \brief Implements pseudo random number generators. * * Two pseudo-random number generators are implemented, in isc_random_* * and isc_rng_*. Neither one is very strong; they should not be used * in cryptography functions. * * isc_random_* is based on arc4random if it is available on the system. * Otherwise it is based on the posix srand() and rand() functions. * It is useful for jittering values a bit here and there, such as * timeouts, etc, but should not be relied upon to generate * unpredictable sequences (for example, when choosing transaction IDs). * * isc_rng_* is based on ChaCha20, and is seeded and stirred from the * system entropy source. It is stronger than isc_random_* and can * be used for generating unpredictable sequences. It is still not as * good as using system entropy directly (see entropy.h) and should not * be used for cryptographic functions such as key generation. */ ISC_LANG_BEGINDECLS typedef struct isc_rng isc_rng_t; /*%< * Opaque type */ void isc_random_seed(uint32_t seed); /*%< * Set the initial seed of the random state. */ void isc_random_get(uint32_t *val); /*%< * Get a random value. * * Requires: * val != NULL. */ uint32_t isc_random_jitter(uint32_t max, uint32_t jitter); /*%< * Get a random value between (max - jitter) and (max). * This is useful for jittering timer values. */ isc_result_t isc_rng_create(isc_mem_t *mctx, isc_entropy_t *entropy, isc_rng_t **rngp); /*%< * Creates and initializes a pseudo random number generator. The * returned RNG can be used to generate pseudo random numbers. * * The reference count of the returned RNG is set to 1. * * Requires: * \li mctx is a pointer to a valid memory context. * \li entropy is an optional entopy source (can be NULL) * \li rngp != NULL && *rngp == NULL is where a pointer to the RNG is * returned. * * Ensures: *\li If result is ISC_R_SUCCESS: * *rngp points to a valid RNG. * *\li If result is failure: * *rngp does not point to a valid RNG. * * Returns: *\li #ISC_R_SUCCESS Success *\li #ISC_R_NOMEMORY Resource limit: Out of Memory */ void isc_rng_attach(isc_rng_t *source, isc_rng_t **targetp); /*%< * Increments a reference count on the passed RNG. * * Requires: * \li source the RNG struct to attach to (is refcount is incremented) * \li targetp != NULL && *targetp == NULL where a pointer to the * reference incremented RNG is returned. */ void isc_rng_detach(isc_rng_t **rngp); /*%< * Decrements a reference count on the passed RNG. If the reference * count reaches 0, the RNG is destroyed. * * Requires: * \li rngp != NULL the RNG struct to decrement reference for */ uint16_t isc_rng_random(isc_rng_t *rngctx); /*%< * Returns a pseudo random 16-bit unsigned integer. */ uint16_t isc_rng_uniformrandom(isc_rng_t *rngctx, uint16_t upper_bound); /*%< * Returns a uniformly distributed pseudo-random 16-bit unsigned integer * less than 'upper_bound'. */ ISC_LANG_ENDDECLS #endif /* ISC_RANDOM_H */ PKֺ1]-@!LLsyslog.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SYSLOG_H #define ISC_SYSLOG_H 1 /*! \file */ #include #include ISC_LANG_BEGINDECLS isc_result_t isc_syslog_facilityfromstring(const char *str, int *facilityp); /*%< * Convert 'str' to the appropriate syslog facility constant. * * Requires: * *\li 'str' is not NULL *\li 'facilityp' is not NULL * * Returns: * \li #ISC_R_SUCCESS * \li #ISC_R_NOTFOUND */ ISC_LANG_ENDDECLS #endif /* ISC_SYSLOG_H */ PKֺ1]0] siphash.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/siphash.h */ #pragma once #include #include #include #define ISC_SIPHASH24_KEY_LENGTH 128 / 8 #define ISC_SIPHASH24_TAG_LENGTH 64 / 8 ISC_LANG_BEGINDECLS void isc_siphash24(const uint8_t *key, const uint8_t *in, const size_t inlen, uint8_t *out); ISC_LANG_ENDDECLS PKֺ1]Үd ondestroy.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ONDESTROY_H #define ISC_ONDESTROY_H 1 #include #include ISC_LANG_BEGINDECLS /*! \file isc/ondestroy.h * ondestroy handling. * * Any class ``X'' of objects that wants to send out notifications * on its destruction should declare a field of type isc_ondestroy_t * (call it 'ondest'). * * \code * typedef struct { * ... * isc_ondestroy_t ondest; * ... * } X; * \endcode * * When an object ``A'' of type X is created * it must initialize the field ondest with a call to * * \code * isc_ondestroy_init(&A->ondest). * \endcode * * X should also provide a registration function for third-party * objects to call to register their interest in being told about * the destruction of a particular instance of X. * * \code * isc_result_t * X_ondestroy(X *instance, isc_task_t *task, * isc_event_t **eventp) { * return(isc_ondestroy_register(&instance->ondest, task,eventp)); * } * \endcode * * Note: locking of the ondestory structure embedded inside of X, is * X's responsibility. * * When an instance of X is destroyed, a call to isc_ondestroy_notify() * sends the notifications: * * \code * X *instance; * isc_ondestroy_t ondest = instance->ondest; * * ... completely cleanup 'instance' here... * * isc_ondestroy_notify(&ondest, instance); * \endcode * * * see lib/dns/zone.c for an ifdef'd-out example. */ struct isc_ondestroy { unsigned int magic; isc_eventlist_t events; }; void isc_ondestroy_init(isc_ondestroy_t *ondest); /*%< * Initialize the on ondest structure. *must* be called before first call * to isc_ondestroy_register(). */ isc_result_t isc_ondestroy_register(isc_ondestroy_t *ondest, isc_task_t *task, isc_event_t **eventp); /*%< * Stores task and *eventp away inside *ondest. Ownership of **event is * taken from the caller (and *eventp is set to NULL). The task is attached * to. */ void isc_ondestroy_notify(isc_ondestroy_t *ondest, void *sender); /*%< * Dispatches the event(s) to the task(s) that were given in * isc_ondestroy_register call(s) (done via calls to * isc_task_sendanddetach()). Before dispatch, the sender value of each * event structure is set to the value of the sender parameter. The * internal structures of the ondest parameter are cleaned out, so no other * cleanup is needed. */ ISC_LANG_ENDDECLS #endif /* ISC_ONDESTROY_H */ PKֺ1]9`]string.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STRING_H #define ISC_STRING_H 1 /*! \file isc/string.h */ #include #include #include #include #include #include #ifdef ISC_PLATFORM_HAVESTRINGSH #include #endif #define ISC_STRING_MAGIC 0x5e ISC_LANG_BEGINDECLS uint64_t isc_string_touint64(char *source, char **endp, int base); /*%< * Convert the string pointed to by 'source' to uint64_t. * * On successful conversion 'endp' points to the first character * after conversion is complete. * * 'base': 0 or 2..36 * * If base is 0 the base is computed from the string type. * * On error 'endp' points to 'source'. */ isc_result_t isc_string_copy(char *target, size_t size, const char *source); /* * Copy the string pointed to by 'source' to 'target' which is a * pointer to a string of at least 'size' bytes. * * Requires: * 'target' is a pointer to a char[] of at least 'size' bytes. * 'size' an integer > 0. * 'source' == NULL or points to a NUL terminated string. * * Ensures: * If result == ISC_R_SUCCESS * 'target' will be a NUL terminated string of no more * than 'size' bytes (including NUL). * * If result == ISC_R_NOSPACE * 'target' is undefined. * * Returns: * ISC_R_SUCCESS -- 'source' was successfully copied to 'target'. * ISC_R_NOSPACE -- 'source' could not be copied since 'target' * is too small. */ void isc_string_copy_truncate(char *target, size_t size, const char *source); /* * Copy the string pointed to by 'source' to 'target' which is a * pointer to a string of at least 'size' bytes. * * Requires: * 'target' is a pointer to a char[] of at least 'size' bytes. * 'size' an integer > 0. * 'source' == NULL or points to a NUL terminated string. * * Ensures: * 'target' will be a NUL terminated string of no more * than 'size' bytes (including NUL). */ isc_result_t isc_string_append(char *target, size_t size, const char *source); /* * Append the string pointed to by 'source' to 'target' which is a * pointer to a NUL terminated string of at least 'size' bytes. * * Requires: * 'target' is a pointer to a NUL terminated char[] of at * least 'size' bytes. * 'size' an integer > 0. * 'source' == NULL or points to a NUL terminated string. * * Ensures: * If result == ISC_R_SUCCESS * 'target' will be a NUL terminated string of no more * than 'size' bytes (including NUL). * * If result == ISC_R_NOSPACE * 'target' is undefined. * * Returns: * ISC_R_SUCCESS -- 'source' was successfully appended to 'target'. * ISC_R_NOSPACE -- 'source' could not be appended since 'target' * is too small. */ void isc_string_append_truncate(char *target, size_t size, const char *source); /* * Append the string pointed to by 'source' to 'target' which is a * pointer to a NUL terminated string of at least 'size' bytes. * * Requires: * 'target' is a pointer to a NUL terminated char[] of at * least 'size' bytes. * 'size' an integer > 0. * 'source' == NULL or points to a NUL terminated string. * * Ensures: * 'target' will be a NUL terminated string of no more * than 'size' bytes (including NUL). */ isc_result_t isc_string_printf(char *target, size_t size, const char *format, ...) ISC_FORMAT_PRINTF(3, 4); /* * Print 'format' to 'target' which is a pointer to a string of at least * 'size' bytes. * * Requires: * 'target' is a pointer to a char[] of at least 'size' bytes. * 'size' an integer > 0. * 'format' == NULL or points to a NUL terminated string. * * Ensures: * If result == ISC_R_SUCCESS * 'target' will be a NUL terminated string of no more * than 'size' bytes (including NUL). * * If result == ISC_R_NOSPACE * 'target' is undefined. * * Returns: * ISC_R_SUCCESS -- 'format' was successfully printed to 'target'. * ISC_R_NOSPACE -- 'format' could not be printed to 'target' since it * is too small. */ void isc_string_printf_truncate(char *target, size_t size, const char *format, ...) ISC_FORMAT_PRINTF(3, 4); /* * Print 'format' to 'target' which is a pointer to a string of at least * 'size' bytes. * * Requires: * 'target' is a pointer to a char[] of at least 'size' bytes. * 'size' an integer > 0. * 'format' == NULL or points to a NUL terminated string. * * Ensures: * 'target' will be a NUL terminated string of no more * than 'size' bytes (including NUL). */ char * isc_string_regiondup(isc_mem_t *mctx, const isc_region_t *source); /* * Copy the region pointed to by r to a NUL terminated string * allocated from the memory context pointed to by mctx. * * The result should be deallocated using isc_mem_free() * * Requires: * 'mctx' is a point to a valid memory context. * 'source' is a pointer to a valid region. * * Returns: * a pointer to a NUL terminated string or * NULL if memory for the copy could not be allocated * */ char * isc_string_separate(char **stringp, const char *delim); #ifdef ISC_PLATFORM_NEEDSTRSEP #define strsep isc_string_separate #endif #ifdef ISC_PLATFORM_NEEDMEMMOVE #define memmove(a,b,c) bcopy(b,a,c) #endif size_t isc_string_strlcpy(char *dst, const char *src, size_t size); #ifdef ISC_PLATFORM_NEEDSTRLCPY #define strlcpy isc_string_strlcpy #endif size_t isc_string_strlcat(char *dst, const char *src, size_t size); #ifdef ISC_PLATFORM_NEEDSTRLCAT #define strlcat isc_string_strlcat #endif char * isc_string_strcasestr(const char *big, const char *little); #ifdef ISC_PLATFORM_NEEDSTRCASESTR #define strcasestr isc_string_strcasestr #endif ISC_LANG_ENDDECLS #endif /* ISC_STRING_H */ PKֺ1];a((app.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_APP_H #define ISC_APP_H 1 /***** ***** Module Info *****/ /*! \file isc/app.h * \brief ISC Application Support * * Dealing with program termination can be difficult, especially in a * multithreaded program. The routines in this module help coordinate * the shutdown process. They are used as follows by the initial (main) * thread of the application: * *\li isc_app_start(); Call very early in main(), before * any other threads have been created. * *\li isc_app_run(); This will post any on-run events, * and then block until application * shutdown is requested. A shutdown * request is made by calling * isc_app_shutdown(), or by sending * SIGINT or SIGTERM to the process. * After isc_app_run() returns, the * application should shutdown itself. * *\li isc_app_finish(); Call very late in main(). * * Applications that want to use SIGHUP/isc_app_reload() to trigger reloading * should check the result of isc_app_run() and call the reload routine if * the result is ISC_R_RELOAD. They should then call isc_app_run() again * to resume waiting for reload or termination. * * Use of this module is not required. In particular, isc_app_start() is * NOT an ISC library initialization routine. * * This module also supports per-thread 'application contexts'. With this * mode, a thread-based application will have a separate context, in which * it uses other ISC library services such as tasks or timers. Signals are * not caught in this mode, so that the application can handle the signals * in its preferred way. * * \li MP: * Clients must ensure that isc_app_start(), isc_app_run(), and * isc_app_finish() are called at most once. isc_app_shutdown() * is safe to use by any thread (provided isc_app_start() has been * called previously). * * The same note applies to isc_app_ctxXXX() functions, but in this case * it's a per-thread restriction. For example, a thread with an * application context must ensure that isc_app_ctxstart() with the * context is called at most once. * * \li Reliability: * No anticipated impact. * * \li Resources: * None. * * \li Security: * No anticipated impact. * * \li Standards: * None. */ #include #include #include #include #include /*** *** Types ***/ typedef isc_event_t isc_appevent_t; #define ISC_APPEVENT_FIRSTEVENT (ISC_EVENTCLASS_APP + 0) #define ISC_APPEVENT_SHUTDOWN (ISC_EVENTCLASS_APP + 1) #define ISC_APPEVENT_LASTEVENT (ISC_EVENTCLASS_APP + 65535) /*% * app module methods. Only app driver implementations use this structure. * Other clients should use the top-level interfaces (i.e., isc_app_xxx * functions). magic must be ISCAPI_APPMETHODS_MAGIC. */ typedef struct isc_appmethods { void (*ctxdestroy)(isc_appctx_t **ctxp); isc_result_t (*ctxstart)(isc_appctx_t *ctx); isc_result_t (*ctxrun)(isc_appctx_t *ctx); isc_result_t (*ctxsuspend)(isc_appctx_t *ctx); isc_result_t (*ctxshutdown)(isc_appctx_t *ctx); void (*ctxfinish)(isc_appctx_t *ctx); void (*settaskmgr)(isc_appctx_t *ctx, isc_taskmgr_t *timermgr); void (*setsocketmgr)(isc_appctx_t *ctx, isc_socketmgr_t *timermgr); void (*settimermgr)(isc_appctx_t *ctx, isc_timermgr_t *timermgr); isc_result_t (*ctxonrun)(isc_appctx_t *ctx, isc_mem_t *mctx, isc_task_t *task, isc_taskaction_t action, void *arg); } isc_appmethods_t; /*% * This structure is actually just the common prefix of an application context * implementation's version of an isc_appctx_t. * \brief * Direct use of this structure by clients is forbidden. app implementations * may change the structure. 'magic' must be ISCAPI_APPCTX_MAGIC for any * of the isc_app_ routines to work. app implementations must maintain * all app context invariants. */ struct isc_appctx { unsigned int impmagic; unsigned int magic; isc_appmethods_t *methods; }; #define ISCAPI_APPCTX_MAGIC ISC_MAGIC('A','a','p','c') #define ISCAPI_APPCTX_VALID(c) ((c) != NULL && \ (c)->magic == ISCAPI_APPCTX_MAGIC) ISC_LANG_BEGINDECLS isc_result_t isc_app_ctxstart(isc_appctx_t *ctx); isc_result_t isc_app_start(void); /*!< * \brief Start an ISC library application. * * Notes: * This call should be made before any other ISC library call, and as * close to the beginning of the application as possible. * * Requires: *\li 'ctx' is a valid application context (for app_ctxstart()). */ isc_result_t isc_app_ctxonrun(isc_appctx_t *ctx, isc_mem_t *mctx, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc_app_onrun(isc_mem_t *mctx, isc_task_t *task, isc_taskaction_t action, void *arg); /*!< * \brief Request delivery of an event when the application is run. * * Requires: *\li isc_app_start() has been called. *\li 'ctx' is a valid application context (for app_ctxonrun()). * * Returns: * ISC_R_SUCCESS * ISC_R_NOMEMORY */ isc_result_t isc_app_ctxrun(isc_appctx_t *ctx); isc_result_t isc_app_run(void); /*!< * \brief Run an ISC library application. * * Notes: *\li The caller (typically the initial thread of an application) will * block until shutdown is requested. When the call returns, the * caller should start shutting down the application. * * Requires: *\li isc_app_[ctx]start() has been called. * * Ensures: *\li Any events requested via isc_app_onrun() will have been posted (in * FIFO order) before isc_app_run() blocks. *\li 'ctx' is a valid application context (for app_ctxrun()). * * Returns: *\li ISC_R_SUCCESS Shutdown has been requested. *\li ISC_R_RELOAD Reload has been requested. */ bool isc_app_isrunning(void); /*!< * \brief Return if the ISC library application is running. * * Returns: *\li true App is running. *\li false App is not running. */ isc_result_t isc_app_ctxshutdown(isc_appctx_t *ctx); isc_result_t isc_app_shutdown(void); /*!< * \brief Request application shutdown. * * Notes: *\li It is safe to call isc_app_shutdown() multiple times. Shutdown will * only be triggered once. * * Requires: *\li isc_app_[ctx]run() has been called. *\li 'ctx' is a valid application context (for app_ctxshutdown()). * * Returns: *\li ISC_R_SUCCESS *\li ISC_R_UNEXPECTED */ isc_result_t isc_app_ctxsuspend(isc_appctx_t *ctx); /*!< * \brief This has the same behavior as isc_app_ctxsuspend(). */ isc_result_t isc_app_reload(void); /*!< * \brief Request application reload. * * Requires: *\li isc_app_run() has been called. * * Returns: *\li ISC_R_SUCCESS *\li ISC_R_UNEXPECTED */ void isc_app_ctxfinish(isc_appctx_t *ctx); void isc_app_finish(void); /*!< * \brief Finish an ISC library application. * * Notes: *\li This call should be made at or near the end of main(). * * Requires: *\li isc_app_start() has been called. *\li 'ctx' is a valid application context (for app_ctxfinish()). * * Ensures: *\li Any resources allocated by isc_app_start() have been released. */ void isc_app_block(void); /*!< * \brief Indicate that a blocking operation will be performed. * * Notes: *\li If a blocking operation is in process, a call to isc_app_shutdown() * or an external signal will abort the program, rather than allowing * clean shutdown. This is primarily useful for reading user input. * * Requires: * \li isc_app_start() has been called. * \li No other blocking operations are in progress. */ void isc_app_unblock(void); /*!< * \brief Indicate that a blocking operation is complete. * * Notes: * \li When a blocking operation has completed, return the program to a * state where a call to isc_app_shutdown() or an external signal will * shutdown normally. * * Requires: * \li isc_app_start() has been called. * \li isc_app_block() has been called by the same thread. */ isc_result_t isc_appctx_create(isc_mem_t *mctx, isc_appctx_t **ctxp); /*!< * \brief Create an application context. * * Requires: *\li 'mctx' is a valid memory context. *\li 'ctxp' != NULL && *ctxp == NULL. */ void isc_appctx_destroy(isc_appctx_t **ctxp); /*!< * \brief Destroy an application context. * * Requires: *\li '*ctxp' is a valid application context. * * Ensures: *\li *ctxp == NULL. */ void isc_appctx_settaskmgr(isc_appctx_t *ctx, isc_taskmgr_t *taskmgr); /*!< * \brief Associate a task manager with an application context. * * This must be done before running tasks within the application context. * * Requires: *\li 'ctx' is a valid application context. *\li 'taskmgr' is a valid task manager. */ void isc_appctx_setsocketmgr(isc_appctx_t *ctx, isc_socketmgr_t *socketmgr); /*!< * \brief Associate a socket manager with an application context. * * This must be done before handling socket events within the application * context. * * Requires: *\li 'ctx' is a valid application context. *\li 'socketmgr' is a valid socket manager. */ void isc_appctx_settimermgr(isc_appctx_t *ctx, isc_timermgr_t *timermgr); /*!< * \brief Associate a socket timer with an application context. * * This must be done before handling timer events within the application * context. * * Requires: *\li 'ctx' is a valid application context. *\li 'timermgr' is a valid timer manager. */ /*%< * See isc_appctx_create() above. */ typedef isc_result_t (*isc_appctxcreatefunc_t)(isc_mem_t *mctx, isc_appctx_t **ctxp); isc_result_t isc_app_register(isc_appctxcreatefunc_t createfunc); /*%< * Register a new application implementation and add it to the list of * supported implementations. This function must be called when a different * event library is used than the one contained in the ISC library. */ isc_result_t isc__app_register(void); /*%< * A short cut function that specifies the application module in the ISC * library for isc_app_register(). An application that uses the ISC library * usually do not have to care about this function: it would call * isc_lib_register(), which internally calls this function. */ ISC_LANG_ENDDECLS #endif /* ISC_APP_H */ PKֺ1]IE msgs.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MSGS_H #define ISC_MSGS_H 1 /*! \file isc/msgs.h */ #include /* Provide isc_msgcat global variable. */ #include /* Provide isc_msgcat_*() functions. */ /*@{*/ /*! * \brief Message sets, named per source file, excepting "GENERAL". * * IMPORTANT: The original list is alphabetical, but any new sets must * be added to the end. */ #define ISC_MSGSET_GENERAL 1 /* ISC_RESULT_RESULTSET 2 */ /* XXX */ /* ISC_RESULT_UNAVAILABLESET 3 */ /* XXX */ #define ISC_MSGSET_APP 4 #define ISC_MSGSET_COMMANDLINE 5 #define ISC_MSGSET_ENTROPY 6 #define ISC_MSGSET_IFITERIOCTL 7 #define ISC_MSGSET_IFITERSYSCTL 8 #define ISC_MSGSET_LEX 9 #define ISC_MSGSET_LOG 10 #define ISC_MSGSET_MEM 11 #define ISC_MSGSET_NETADDR 12 #define ISC_MSGSET_PRINT 13 #define ISC_MSGSET_RESULT 14 #define ISC_MSGSET_RWLOCK 15 #define ISC_MSGSET_SOCKADDR 16 #define ISC_MSGSET_SOCKET 17 #define ISC_MSGSET_TASK 18 #define ISC_MSGSET_TIMER 19 #define ISC_MSGSET_UTIL 20 #define ISC_MSGSET_IFITERGETIFADDRS 21 /*@}*/ /*@{*/ /*! * Message numbers * are only required to be unique per message set, * but are unique throughout the entire catalog to not be as confusing when * debugging. * * The initial numbering was done by multiply by 100 the set number the * message appears in then adding the incremental message number. */ #define ISC_MSG_FAILED 101 /*%< "failed" */ #define ISC_MSG_SUCCEEDED 102 /*%< Compatible with "failed" */ #define ISC_MSG_SUCCESS 103 /*%< More usual way to say "success" */ #define ISC_MSG_STARTING 104 /*%< As in "daemon: starting" */ #define ISC_MSG_STOPING 105 /*%< As in "daemon: stopping" */ #define ISC_MSG_ENTERING 106 /*%< As in "some_subr: entering" */ #define ISC_MSG_EXITING 107 /*%< As in "some_subr: exiting" */ #define ISC_MSG_CALLING 108 /*%< As in "calling some_subr()" */ #define ISC_MSG_RETURNED 109 /*%< As in "some_subr: returned " */ #define ISC_MSG_FATALERROR 110 /*%< "fatal error" */ #define ISC_MSG_SHUTTINGDOWN 111 /*%< "shutting down" */ #define ISC_MSG_RUNNING 112 /*%< "running" */ #define ISC_MSG_WAIT 113 /*%< "wait" */ #define ISC_MSG_WAITUNTIL 114 /*%< "waituntil" */ #define ISC_MSG_SIGNALSETUP 201 /*%< "handle_signal() %d setup: %s" */ #define ISC_MSG_ILLEGALOPT 301 /*%< "illegal option" */ #define ISC_MSG_OPTNEEDARG 302 /*%< "option requires an argument" */ #define ISC_MSG_ENTROPYSTATS 401 /*%< "Entropy pool %p: refcnt %u ..." */ #define ISC_MSG_MAKESCANSOCKET 501 /*%< "making interface scan socket: %s" */ #define ISC_MSG_GETIFCONFIG 502 /*%< "get interface configuration: %s" */ #define ISC_MSG_BUFFERMAX 503 /*%< "... maximum buffer size exceeded" */ #define ISC_MSG_GETDESTADDR 504 /*%< "%s: getting destination address: %s" */ #define ISC_MSG_GETNETMASK 505 /*%< "%s: getting netmask: %s" */ #define ISC_MSG_GETIFLISTSIZE 601 /*%< "getting interface list size: ..." */ #define ISC_MSG_GETIFLIST 602 /*%< "getting interface list: ..." */ #define ISC_MSG_UNEXPECTEDTYPE 603 /*%< "... unexpected ... message type" */ #define ISC_MSG_UNEXPECTEDSTATE 701 /*%< "Unexpected state %d" */ #define ISC_MSG_BADTIME 801 /*%< "Bad 00 99:99:99.999 " */ #define ISC_MSG_LEVEL 802 /*%< "level %d: " */ #define ISC_MSG_ADDTRACE 901 /*%< "add %p size %u " */ #define ISC_MSG_DELTRACE 902 /*%< "del %p size %u " */ #define ISC_MSG_POOLSTATS 903 /*%< "[Pool statistics]\n" */ #define ISC_MSG_POOLNAME 904 /*%< "name" */ #define ISC_MSG_POOLSIZE 905 /*%< "size" */ #define ISC_MSG_POOLMAXALLOC 906 /*%< "maxalloc" */ #define ISC_MSG_POOLALLOCATED 907 /*%< "allocated" */ #define ISC_MSG_POOLFREECOUNT 908 /*%< "freecount" */ #define ISC_MSG_POOLFREEMAX 909 /*%< "freemax" */ #define ISC_MSG_POOLFILLCOUNT 910 /*%< "fillcount" */ #define ISC_MSG_POOLGETS 911 /*%< "gets" */ #define ISC_MSG_DUMPALLOC 912 /*%< "DUMP OF ALL OUTSTANDING MEMORY ..." */ #define ISC_MSG_NONE 913 /*%< "\tNone.\n" */ #define ISC_MSG_PTRFILELINE 914 /*%< "\tptr %p file %s line %u\n" */ #define ISC_MSG_UNKNOWNADDR 1001 /*%< "" */ #define ISC_MSG_NOLONGDBL 1104 /*%< "long doubles are not supported" */ #define ISC_MSG_PRINTLOCK 1201 /*%< "rwlock %p thread %lu ..." */ #define ISC_MSG_READ 1202 /*%< "read" */ #define ISC_MSG_WRITE 1203 /*%< "write" */ #define ISC_MSG_READING 1204 /*%< "reading" */ #define ISC_MSG_WRITING 1205 /*%< "writing" */ #define ISC_MSG_PRELOCK 1206 /*%< "prelock" */ #define ISC_MSG_POSTLOCK 1207 /*%< "postlock" */ #define ISC_MSG_PREUNLOCK 1208 /*%< "preunlock" */ #define ISC_MSG_POSTUNLOCK 1209 /*%< "postunlock" */ #define ISC_MSG_PRINTLOCK2 1210 /*%< "rwlock %p thread %lu ..." w/ atomic */ #define ISC_MSG_UNKNOWNFAMILY 1301 /*%< "unknown address family: %d" */ #define ISC_MSG_WRITEFAILED 1401 /*%< "write() failed during watcher ..." */ #define ISC_MSG_READFAILED 1402 /*%< "read() failed during watcher ... " */ #define ISC_MSG_PROCESSCMSG 1403 /*%< "processing cmsg %p" */ #define ISC_MSG_IFRECEIVED 1404 /*%< "interface received on ifindex %u" */ #define ISC_MSG_SENDTODATA 1405 /*%< "sendto pktinfo data, ifindex %u" */ #define ISC_MSG_DOIORECV 1406 /*%< "doio_recv: recvmsg(%d) %d bytes ..." */ #define ISC_MSG_PKTRECV 1407 /*%< "packet received correctly" */ #define ISC_MSG_DESTROYING 1408 /*%< "destroying" */ #define ISC_MSG_CREATED 1409 /*%< "created" */ #define ISC_MSG_ACCEPTLOCK 1410 /*%< "internal_accept called, locked ..." */ #define ISC_MSG_ACCEPTEDCXN 1411 /*%< "accepted connection, new socket %p" */ #define ISC_MSG_INTERNALRECV 1412 /*%< "internal_recv: task %p got event %p" */ #define ISC_MSG_INTERNALSEND 1413 /*%< "internal_send: task %p got event %p" */ #define ISC_MSG_WATCHERMSG 1414 /*%< "watcher got message %d" */ #define ISC_MSG_SOCKETSREMAIN 1415 /*%< "sockets exist" */ #define ISC_MSG_PKTINFOPROVIDED 1416 /*%< "pktinfo structure provided, ..." */ #define ISC_MSG_BOUND 1417 /*%< "bound" */ #define ISC_MSG_ACCEPTRETURNED 1418 /*%< accept() returned %d/%s */ #define ISC_MSG_TOOMANYFDS 1419 /*%< %s: too many open file descriptors */ #define ISC_MSG_ZEROPORT 1420 /*%< dropping source port zero packet */ #define ISC_MSG_FILTER 1421 /*%< setsockopt(SO_ACCEPTFILTER): %s */ #define ISC_MSG_TOOMANYHANDLES 1422 /*%< %s: too many open WSA event handles: %s */ #define ISC_MSG_POKED 1423 /*%< "poked flags: %d" */ #define ISC_MSG_AWAKE 1502 /*%< "awake" */ #define ISC_MSG_WORKING 1503 /*%< "working" */ #define ISC_MSG_EXECUTE 1504 /*%< "execute action" */ #define ISC_MSG_EMPTY 1505 /*%< "empty" */ #define ISC_MSG_DONE 1506 /*%< "done" */ #define ISC_MSG_QUANTUM 1507 /*%< "quantum" */ #define ISC_MSG_SCHEDULE 1601 /*%< "schedule" */ #define ISC_MSG_SIGNALSCHED 1602 /*%< "signal (schedule)" */ #define ISC_MSG_SIGNALDESCHED 1603 /*%< "signal (deschedule)" */ #define ISC_MSG_SIGNALDESTROY 1604 /*%< "signal (destroy)" */ #define ISC_MSG_IDLERESCHED 1605 /*%< "idle reschedule" */ #define ISC_MSG_EVENTNOTALLOC 1606 /*%< "couldn't allocate event" */ #define ISC_MSG_SCHEDFAIL 1607 /*%< "couldn't schedule timer: %u" */ #define ISC_MSG_POSTING 1608 /*%< "posting" */ #define ISC_MSG_WAKEUP 1609 /*%< "wakeup" */ #define ISC_MSG_LOCK 1701 /*%< "LOCK" */ #define ISC_MSG_LOCKING 1702 /*%< "LOCKING" */ #define ISC_MSG_LOCKED 1703 /*%< "LOCKED" */ #define ISC_MSG_UNLOCKED 1704 /*%< "UNLOCKED" */ #define ISC_MSG_RWLOCK 1705 /*%< "RWLOCK" */ #define ISC_MSG_RWLOCKED 1706 /*%< "RWLOCKED" */ #define ISC_MSG_RWUNLOCK 1707 /*%< "RWUNLOCK" */ #define ISC_MSG_BROADCAST 1708 /*%< "BROADCAST" */ #define ISC_MSG_SIGNAL 1709 /*%< "SIGNAL" */ #define ISC_MSG_UTILWAIT 1710 /*%< "WAIT" */ #define ISC_MSG_WAITED 1711 /*%< "WAITED" */ #define ISC_MSG_GETIFADDRS 1801 /*%< "getting interface addresses: ..." */ /*@}*/ #endif /* ISC_MSGS_H */ PKֺ1]'Q- sockaddr.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SOCKADDR_H #define ISC_SOCKADDR_H 1 /*! \file isc/sockaddr.h */ #include #include #include #include #ifdef ISC_PLATFORM_HAVESYSUNH #include #endif struct isc_sockaddr { union { struct sockaddr sa; struct sockaddr_in sin; struct sockaddr_in6 sin6; struct sockaddr_storage ss; #ifdef ISC_PLATFORM_HAVESYSUNH struct sockaddr_un sunix; #endif } type; unsigned int length; /* XXXRTH beginning? */ ISC_LINK(struct isc_sockaddr) link; }; #define ISC_SOCKADDR_CMPADDR 0x0001 /*%< compare the address * sin_addr/sin6_addr */ #define ISC_SOCKADDR_CMPPORT 0x0002 /*%< compare the port * sin_port/sin6_port */ #define ISC_SOCKADDR_CMPSCOPE 0x0004 /*%< compare the scope * sin6_scope */ #define ISC_SOCKADDR_CMPSCOPEZERO 0x0008 /*%< when comparing scopes * zero scopes always match */ ISC_LANG_BEGINDECLS bool isc_sockaddr_compare(const isc_sockaddr_t *a, const isc_sockaddr_t *b, unsigned int flags); /*%< * Compare the elements of the two address ('a' and 'b') as specified * by 'flags' and report if they are equal or not. * * 'flags' is set from ISC_SOCKADDR_CMP*. */ bool isc_sockaddr_equal(const isc_sockaddr_t *a, const isc_sockaddr_t *b); /*%< * Return true iff the socket addresses 'a' and 'b' are equal. */ bool isc_sockaddr_eqaddr(const isc_sockaddr_t *a, const isc_sockaddr_t *b); /*%< * Return true iff the address parts of the socket addresses * 'a' and 'b' are equal, ignoring the ports. */ bool isc_sockaddr_eqaddrprefix(const isc_sockaddr_t *a, const isc_sockaddr_t *b, unsigned int prefixlen); /*%< * Return true iff the most significant 'prefixlen' bits of the * socket addresses 'a' and 'b' are equal, ignoring the ports. * If 'b''s scope is zero then 'a''s scope will be ignored. */ unsigned int isc_sockaddr_hash(const isc_sockaddr_t *sockaddr, bool address_only); /*%< * Return a hash value for the socket address 'sockaddr'. If 'address_only' * is true, the hash value will not depend on the port. * * IPv6 addresses containing mapped IPv4 addresses generate the same hash * value as the equivalent IPv4 address. */ void isc_sockaddr_any(isc_sockaddr_t *sockaddr); /*%< * Return the IPv4 wildcard address. */ void isc_sockaddr_any6(isc_sockaddr_t *sockaddr); /*%< * Return the IPv6 wildcard address. */ void isc_sockaddr_anyofpf(isc_sockaddr_t *sockaddr, int family); /*%< * Set '*sockaddr' to the wildcard address of protocol family * 'family'. * * Requires: * \li 'family' is AF_INET or AF_INET6. */ void isc_sockaddr_fromin(isc_sockaddr_t *sockaddr, const struct in_addr *ina, in_port_t port); /*%< * Construct an isc_sockaddr_t from an IPv4 address and port. */ void isc_sockaddr_fromin6(isc_sockaddr_t *sockaddr, const struct in6_addr *ina6, in_port_t port); /*%< * Construct an isc_sockaddr_t from an IPv6 address and port. */ void isc_sockaddr_v6fromin(isc_sockaddr_t *sockaddr, const struct in_addr *ina, in_port_t port); /*%< * Construct an IPv6 isc_sockaddr_t representing a mapped IPv4 address. */ void isc_sockaddr_fromnetaddr(isc_sockaddr_t *sockaddr, const isc_netaddr_t *na, in_port_t port); /*%< * Construct an isc_sockaddr_t from an isc_netaddr_t and port. */ int isc_sockaddr_pf(const isc_sockaddr_t *sockaddr); /*%< * Get the protocol family of 'sockaddr'. * * Requires: * *\li 'sockaddr' is a valid sockaddr with an address family of AF_INET * or AF_INET6. * * Returns: * *\li The protocol family of 'sockaddr', e.g. PF_INET or PF_INET6. */ void isc_sockaddr_setport(isc_sockaddr_t *sockaddr, in_port_t port); /*%< * Set the port of 'sockaddr' to 'port'. */ in_port_t isc_sockaddr_getport(const isc_sockaddr_t *sockaddr); /*%< * Get the port stored in 'sockaddr'. */ isc_result_t isc_sockaddr_totext(const isc_sockaddr_t *sockaddr, isc_buffer_t *target); /*%< * Append a text representation of 'sockaddr' to the buffer 'target'. * The text will include both the IP address (v4 or v6) and the port. * The text is null terminated, but the terminating null is not * part of the buffer's used region. * * Returns: * \li ISC_R_SUCCESS * \li ISC_R_NOSPACE The text or the null termination did not fit. */ void isc_sockaddr_format(const isc_sockaddr_t *sa, char *array, unsigned int size); /*%< * Format a human-readable representation of the socket address '*sa' * into the character array 'array', which is of size 'size'. * The resulting string is guaranteed to be null-terminated. */ bool isc_sockaddr_ismulticast(const isc_sockaddr_t *sa); /*%< * Returns #true if the address is a multicast address. */ bool isc_sockaddr_isexperimental(const isc_sockaddr_t *sa); /* * Returns true if the address is a experimental (CLASS E) address. */ bool isc_sockaddr_islinklocal(const isc_sockaddr_t *sa); /*%< * Returns true if the address is a link local address. */ bool isc_sockaddr_issitelocal(const isc_sockaddr_t *sa); /*%< * Returns true if the address is a sitelocal address. */ bool isc_sockaddr_isnetzero(const isc_sockaddr_t *sa); /*%< * Returns true if the address is in net zero. */ isc_result_t isc_sockaddr_frompath(isc_sockaddr_t *sockaddr, const char *path); /* * Create a UNIX domain sockaddr that refers to path. * * Returns: * \li ISC_R_NOSPACE * \li ISC_R_NOTIMPLEMENTED * \li ISC_R_SUCCESS */ #define ISC_SOCKADDR_FORMATSIZE \ sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:XXX.XXX.XXX.XXX%SSSSSSSSSS#YYYYY") /*%< * Minimum size of array to pass to isc_sockaddr_format(). */ ISC_LANG_ENDDECLS #endif /* ISC_SOCKADDR_H */ PKֺ1]:זheap.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_HEAP_H #define ISC_HEAP_H 1 /*! \file isc/heap.h */ #include #include #include ISC_LANG_BEGINDECLS /*% * The comparison function returns true if the first argument has * higher priority than the second argument, and false otherwise. */ typedef bool (*isc_heapcompare_t)(void *, void *); /*% * The index function allows the client of the heap to receive a callback * when an item's index number changes. This allows it to maintain * sync with its external state, but still delete itself, since deletions * from the heap require the index be provided. */ typedef void (*isc_heapindex_t)(void *, unsigned int); /*% * The heapaction function is used when iterating over the heap. * * NOTE: The heap structure CANNOT BE MODIFIED during the call to * isc_heap_foreach(). */ typedef void (*isc_heapaction_t)(void *, void *); typedef struct isc_heap isc_heap_t; isc_result_t isc_heap_create(isc_mem_t *mctx, isc_heapcompare_t compare, isc_heapindex_t index, unsigned int size_increment, isc_heap_t **heapp); /*!< * \brief Create a new heap. The heap is implemented using a space-efficient * storage method. When the heap elements are deleted space is not freed * but will be reused when new elements are inserted. * * Heap elements are indexed from 1. * * Requires: *\li "mctx" is valid. *\li "compare" is a function which takes two void * arguments and * returns true if the first argument has a higher priority than * the second, and false otherwise. *\li "index" is a function which takes a void *, and an unsigned int * argument. This function will be called whenever an element's * index value changes, so it may continue to delete itself from the * heap. This option may be NULL if this functionality is unneeded. *\li "size_increment" is a hint about how large the heap should grow * when resizing is needed. If this is 0, a default size will be * used, which is currently 1024, allowing space for an additional 1024 * heap elements to be inserted before adding more space. *\li "heapp" is not NULL, and "*heap" is NULL. * * Returns: *\li ISC_R_SUCCESS - success *\li ISC_R_NOMEMORY - insufficient memory */ void isc_heap_destroy(isc_heap_t **heapp); /*!< * \brief Destroys a heap. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. */ isc_result_t isc_heap_insert(isc_heap_t *heap, void *elt); /*!< * \brief Inserts a new element into a heap. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. */ void isc_heap_delete(isc_heap_t *heap, unsigned int index); /*!< * \brief Deletes an element from a heap, by element index. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. *\li "index" is a valid element index, as provided by the "index" callback * provided during heap creation. */ void isc_heap_increased(isc_heap_t *heap, unsigned int index); /*!< * \brief Indicates to the heap that an element's priority has increased. * This function MUST be called whenever an element has increased in priority. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. *\li "index" is a valid element index, as provided by the "index" callback * provided during heap creation. */ void isc_heap_decreased(isc_heap_t *heap, unsigned int index); /*!< * \brief Indicates to the heap that an element's priority has decreased. * This function MUST be called whenever an element has decreased in priority. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. *\li "index" is a valid element index, as provided by the "index" callback * provided during heap creation. */ void * isc_heap_element(isc_heap_t *heap, unsigned int index); /*!< * \brief Returns the element for a specific element index. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. *\li "index" is a valid element index, as provided by the "index" callback * provided during heap creation. * * Returns: *\li A pointer to the element for the element index. */ void isc_heap_foreach(isc_heap_t *heap, isc_heapaction_t action, void *uap); /*!< * \brief Iterate over the heap, calling an action for each element. The * order of iteration is not sorted. * * Requires: *\li "heapp" is not NULL and "*heap" points to a valid isc_heap_t. *\li "action" is not NULL, and is a function which takes two arguments. * The first is a void *, representing the element, and the second is * "uap" as provided to isc_heap_foreach. *\li "uap" is a caller-provided argument, and may be NULL. * * Note: *\li The heap structure CANNOT be modified during this iteration. The only * safe function to call while iterating the heap is isc_heap_element(). */ ISC_LANG_ENDDECLS #endif /* ISC_HEAP_H */ PKֺ1]xy  keyboard.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_KEYBOARD_H #define ISC_KEYBOARD_H 1 /*! \file */ #include #include #include #include ISC_LANG_BEGINDECLS typedef struct { int fd; struct termios saved_mode; isc_result_t result; } isc_keyboard_t; isc_result_t isc_keyboard_open(isc_keyboard_t *keyboard); isc_result_t isc_keyboard_close(isc_keyboard_t *keyboard, unsigned int sleepseconds); isc_result_t isc_keyboard_getchar(isc_keyboard_t *keyboard, unsigned char *cp); bool isc_keyboard_canceled(isc_keyboard_t *keyboard); ISC_LANG_ENDDECLS #endif /* ISC_KEYBOARD_H */ PKֺ1]); print.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_PRINT_H #define ISC_PRINT_H 1 /*! \file isc/print.h */ /*** *** Imports ***/ #include /* Required for ISC_FORMAT_PRINTF() macro. */ #include #include /*! * This block allows lib/isc/print.c to be cleanly compiled even if * the platform does not need it. The standard Makefile will still * not compile print.c or archive print.o, so this is just to make test * compilation ("make print.o") easier. */ #if !defined(ISC_PLATFORM_NEEDVSNPRINTF) && defined(ISC__PRINT_SOURCE) #define ISC_PLATFORM_NEEDVSNPRINTF #undef snprintf #undef vsnprintf #endif #if !defined(ISC_PLATFORM_NEEDSPRINTF) && defined(ISC__PRINT_SOURCE) #define ISC_PLATFORM_NEEDSPRINTF #undef sprintf #endif #if !defined(ISC_PLATFORM_NEEDFPRINTF) && defined(ISC__PRINT_SOURCE) #define ISC_PLATFORM_NEEDFPRINTF #undef fprintf #endif #if !defined(ISC_PLATFORM_NEEDPRINTF) && defined(ISC__PRINT_SOURCE) #define ISC_PLATFORM_NEEDPRINTF #undef printf #endif /*** *** Functions ***/ #ifdef ISC_PLATFORM_NEEDVSNPRINTF #include #include #endif #include ISC_LANG_BEGINDECLS #ifdef ISC_PLATFORM_NEEDVSNPRINTF int isc_print_vsnprintf(char *str, size_t size, const char *format, va_list ap) ISC_FORMAT_PRINTF(3, 0); #undef vsnprintf #define vsnprintf isc_print_vsnprintf int isc_print_snprintf(char *str, size_t size, const char *format, ...) ISC_FORMAT_PRINTF(3, 4); #undef snprintf #define snprintf isc_print_snprintf #endif /* ISC_PLATFORM_NEEDVSNPRINTF */ #ifdef ISC_PLATFORM_NEEDSPRINTF int isc_print_sprintf(char *str, const char *format, ...) ISC_FORMAT_PRINTF(2, 3); #undef sprintf #define sprintf isc_print_sprintf #endif #ifdef ISC_PLATFORM_NEEDPRINTF int isc_print_printf(const char *format, ...) ISC_FORMAT_PRINTF(1, 2); #undef printf #define printf isc_print_printf #endif #ifdef ISC_PLATFORM_NEEDFPRINTF int isc_print_fprintf(FILE * fp, const char *format, ...) ISC_FORMAT_PRINTF(2, 3); #undef fprintf #define fprintf isc_print_fprintf #endif ISC_LANG_ENDDECLS #endif /* ISC_PRINT_H */ PKֺ1]n//socket.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SOCKET_H #define ISC_SOCKET_H 1 /***** ***** Module Info *****/ /*! \file isc/socket.h * \brief Provides TCP and UDP sockets for network I/O. The sockets are event * sources in the task system. * * When I/O completes, a completion event for the socket is posted to the * event queue of the task which requested the I/O. * * \li MP: * The module ensures appropriate synchronization of data structures it * creates and manipulates. * Clients of this module must not be holding a socket's task's lock when * making a call that affects that socket. Failure to follow this rule * can result in deadlock. * The caller must ensure that isc_socketmgr_destroy() is called only * once for a given manager. * * \li Reliability: * No anticipated impact. * * \li Resources: * TBS * * \li Security: * No anticipated impact. * * \li Standards: * None. */ /*** *** Imports ***/ #include #include #include #include #include #include #include #include #include #include #include #ifdef WIN32 /* from the old namespace.h */ #define isc_socket_create isc__socket_create #define isc_socket_dup isc__socket_dup #define isc_socket_attach isc__socket_attach #define isc_socket_detach isc__socket_detach #define isc_socketmgr_create isc__socketmgr_create #define isc_socketmgr_create2 isc__socketmgr_create2 #define isc_socketmgr_destroy isc__socketmgr_destroy #define isc_socket_open isc__socket_open #define isc_socket_close isc__socket_close #define isc_socket_recvv isc__socket_recvv #define isc_socket_recv isc__socket_recv #define isc_socket_recv2 isc__socket_recv2 #define isc_socket_send isc__socket_send #define isc_socket_sendto isc__socket_sendto #define isc_socket_sendv isc__socket_sendv #define isc_socket_sendtov isc__socket_sendtov #define isc_socket_sendtov2 isc__socket_sendtov2 #define isc_socket_sendto2 isc__socket_sendto2 #define isc_socket_cleanunix isc__socket_cleanunix #define isc_socket_permunix isc__socket_permunix #define isc_socket_bind isc__socket_bind #define isc_socket_filter isc__socket_filter #define isc_socket_listen isc__socket_listen #define isc_socket_accept isc__socket_accept #define isc_socket_connect isc__socket_connect #define isc_socket_getfd isc__socket_getfd #define isc_socket_getname isc__socket_getname #define isc_socket_gettag isc__socket_gettag #define isc_socket_getpeername isc__socket_getpeername #define isc_socket_getsockname isc__socket_getsockname #define isc_socket_cancel isc__socket_cancel #define isc_socket_gettype isc__socket_gettype #define isc_socket_isbound isc__socket_isbound #define isc_socket_ipv6only isc__socket_ipv6only #define isc_socket_setname isc__socket_setname #define isc_socketmgr_getmaxsockets isc__socketmgr_getmaxsockets #define isc_socketmgr_setstats isc__socketmgr_setstats #define isc_socketmgr_setreserved isc__socketmgr_setreserved #define isc__socketmgr_maxudp isc___socketmgr_maxudp #define isc_socket_fdwatchcreate isc__socket_fdwatchcreate #define isc_socket_fdwatchpoke isc__socket_fdwatchpoke #define isc_socket_dscp isc__socket_dscp #endif ISC_LANG_BEGINDECLS /*** *** Constants ***/ /*% * Maximum number of buffers in a scatter/gather read/write. The operating * system in use must support at least this number (plus one on some.) */ #define ISC_SOCKET_MAXSCATTERGATHER 8 /*% * In isc_socket_bind() set socket option SO_REUSEADDR prior to calling * bind() if a non zero port is specified (AF_INET and AF_INET6). */ #define ISC_SOCKET_REUSEADDRESS 0x01U /*% * Statistics counters. Used as isc_statscounter_t values. */ enum { isc_sockstatscounter_udp4open = 0, isc_sockstatscounter_udp6open = 1, isc_sockstatscounter_tcp4open = 2, isc_sockstatscounter_tcp6open = 3, isc_sockstatscounter_unixopen = 4, isc_sockstatscounter_udp4openfail = 5, isc_sockstatscounter_udp6openfail = 6, isc_sockstatscounter_tcp4openfail = 7, isc_sockstatscounter_tcp6openfail = 8, isc_sockstatscounter_unixopenfail = 9, isc_sockstatscounter_udp4close = 10, isc_sockstatscounter_udp6close = 11, isc_sockstatscounter_tcp4close = 12, isc_sockstatscounter_tcp6close = 13, isc_sockstatscounter_unixclose = 14, isc_sockstatscounter_fdwatchclose = 15, isc_sockstatscounter_udp4bindfail = 16, isc_sockstatscounter_udp6bindfail = 17, isc_sockstatscounter_tcp4bindfail = 18, isc_sockstatscounter_tcp6bindfail = 19, isc_sockstatscounter_unixbindfail = 20, isc_sockstatscounter_fdwatchbindfail = 21, isc_sockstatscounter_udp4connect = 22, isc_sockstatscounter_udp6connect = 23, isc_sockstatscounter_tcp4connect = 24, isc_sockstatscounter_tcp6connect = 25, isc_sockstatscounter_unixconnect = 26, isc_sockstatscounter_fdwatchconnect = 27, isc_sockstatscounter_udp4connectfail = 28, isc_sockstatscounter_udp6connectfail = 29, isc_sockstatscounter_tcp4connectfail = 30, isc_sockstatscounter_tcp6connectfail = 31, isc_sockstatscounter_unixconnectfail = 32, isc_sockstatscounter_fdwatchconnectfail = 33, isc_sockstatscounter_tcp4accept = 34, isc_sockstatscounter_tcp6accept = 35, isc_sockstatscounter_unixaccept = 36, isc_sockstatscounter_tcp4acceptfail = 37, isc_sockstatscounter_tcp6acceptfail = 38, isc_sockstatscounter_unixacceptfail = 39, isc_sockstatscounter_udp4sendfail = 40, isc_sockstatscounter_udp6sendfail = 41, isc_sockstatscounter_tcp4sendfail = 42, isc_sockstatscounter_tcp6sendfail = 43, isc_sockstatscounter_unixsendfail = 44, isc_sockstatscounter_fdwatchsendfail = 45, isc_sockstatscounter_udp4recvfail = 46, isc_sockstatscounter_udp6recvfail = 47, isc_sockstatscounter_tcp4recvfail = 48, isc_sockstatscounter_tcp6recvfail = 49, isc_sockstatscounter_unixrecvfail = 50, isc_sockstatscounter_fdwatchrecvfail = 51, isc_sockstatscounter_udp4active = 52, isc_sockstatscounter_udp6active = 53, isc_sockstatscounter_tcp4active = 54, isc_sockstatscounter_tcp6active = 55, isc_sockstatscounter_unixactive = 56, isc_sockstatscounter_rawopen = 57, isc_sockstatscounter_rawopenfail = 58, isc_sockstatscounter_rawclose = 59, isc_sockstatscounter_rawrecvfail = 60, isc_sockstatscounter_rawactive = 61, isc_sockstatscounter_max = 62 }; /*** *** Types ***/ struct isc_socketevent { ISC_EVENT_COMMON(isc_socketevent_t); isc_result_t result; /*%< OK, EOF, whatever else */ unsigned int minimum; /*%< minimum i/o for event */ unsigned int n; /*%< bytes read or written */ unsigned int offset; /*%< offset into buffer list */ isc_region_t region; /*%< for single-buffer i/o */ isc_bufferlist_t bufferlist; /*%< list of buffers */ isc_sockaddr_t address; /*%< source address */ isc_time_t timestamp; /*%< timestamp of packet recv */ struct in6_pktinfo pktinfo; /*%< ipv6 pktinfo */ uint32_t attributes; /*%< see below */ isc_eventdestructor_t destroy; /*%< original destructor */ unsigned int dscp; /*%< UDP dscp value */ }; typedef struct isc_socket_newconnev isc_socket_newconnev_t; struct isc_socket_newconnev { ISC_EVENT_COMMON(isc_socket_newconnev_t); isc_socket_t * newsocket; isc_result_t result; /*%< OK, EOF, whatever else */ isc_sockaddr_t address; /*%< source address */ }; typedef struct isc_socket_connev isc_socket_connev_t; struct isc_socket_connev { ISC_EVENT_COMMON(isc_socket_connev_t); isc_result_t result; /*%< OK, EOF, whatever else */ }; /*@{*/ /*! * _ATTACHED: Internal use only. * _TRUNC: Packet was truncated on receive. * _CTRUNC: Packet control information was truncated. This can * indicate that the packet is not complete, even though * all the data is valid. * _TIMESTAMP: The timestamp member is valid. * _PKTINFO: The pktinfo member is valid. * _MULTICAST: The UDP packet was received via a multicast transmission. * _DSCP: The UDP DSCP value is valid. * _USEMINMTU: Set the per packet IPV6_USE_MIN_MTU flag. */ #define ISC_SOCKEVENTATTR_ATTACHED 0x10000000U /* internal */ #define ISC_SOCKEVENTATTR_TRUNC 0x00800000U /* public */ #define ISC_SOCKEVENTATTR_CTRUNC 0x00400000U /* public */ #define ISC_SOCKEVENTATTR_TIMESTAMP 0x00200000U /* public */ #define ISC_SOCKEVENTATTR_PKTINFO 0x00100000U /* public */ #define ISC_SOCKEVENTATTR_MULTICAST 0x00080000U /* public */ #define ISC_SOCKEVENTATTR_DSCP 0x00040000U /* public */ #define ISC_SOCKEVENTATTR_USEMINMTU 0x00020000U /* public */ /*@}*/ #define ISC_SOCKEVENT_ANYEVENT (0) #define ISC_SOCKEVENT_RECVDONE (ISC_EVENTCLASS_SOCKET + 1) #define ISC_SOCKEVENT_SENDDONE (ISC_EVENTCLASS_SOCKET + 2) #define ISC_SOCKEVENT_NEWCONN (ISC_EVENTCLASS_SOCKET + 3) #define ISC_SOCKEVENT_CONNECT (ISC_EVENTCLASS_SOCKET + 4) /* * Internal events. */ #define ISC_SOCKEVENT_INTR (ISC_EVENTCLASS_SOCKET + 256) #define ISC_SOCKEVENT_INTW (ISC_EVENTCLASS_SOCKET + 257) typedef enum { isc_sockettype_udp = 1, isc_sockettype_tcp = 2, isc_sockettype_unix = 3, isc_sockettype_fdwatch = 4, isc_sockettype_raw = 5 } isc_sockettype_t; /*@{*/ /*! * How a socket should be shutdown in isc_socket_shutdown() calls. */ #define ISC_SOCKSHUT_RECV 0x00000001 /*%< close read side */ #define ISC_SOCKSHUT_SEND 0x00000002 /*%< close write side */ #define ISC_SOCKSHUT_ALL 0x00000003 /*%< close them all */ /*@}*/ /*@{*/ /*! * What I/O events to cancel in isc_socket_cancel() calls. */ #define ISC_SOCKCANCEL_RECV 0x00000001 /*%< cancel recv */ #define ISC_SOCKCANCEL_SEND 0x00000002 /*%< cancel send */ #define ISC_SOCKCANCEL_ACCEPT 0x00000004 /*%< cancel accept */ #define ISC_SOCKCANCEL_CONNECT 0x00000008 /*%< cancel connect */ #define ISC_SOCKCANCEL_ALL 0x0000000f /*%< cancel everything */ /*@}*/ /*@{*/ /*! * Flags for isc_socket_send() and isc_socket_recv() calls. */ #define ISC_SOCKFLAG_IMMEDIATE 0x00000001 /*%< send event only if needed */ #define ISC_SOCKFLAG_NORETRY 0x00000002 /*%< drop failed UDP sends */ /*@}*/ /*@{*/ /*! * Flags for fdwatchcreate. */ #define ISC_SOCKFDWATCH_READ 0x00000001 /*%< watch for readable */ #define ISC_SOCKFDWATCH_WRITE 0x00000002 /*%< watch for writable */ /*@}*/ /*% Socket and socket manager methods */ typedef struct isc_socketmgrmethods { void (*destroy)(isc_socketmgr_t **managerp); isc_result_t (*socketcreate)(isc_socketmgr_t *manager, int pf, isc_sockettype_t type, isc_socket_t **socketp); isc_result_t (*fdwatchcreate)(isc_socketmgr_t *manager, int fd, int flags, isc_sockfdwatch_t callback, void *cbarg, isc_task_t *task, isc_socket_t **socketp); } isc_socketmgrmethods_t; typedef struct isc_socketmethods { void (*attach)(isc_socket_t *socket, isc_socket_t **socketp); void (*detach)(isc_socket_t **socketp); isc_result_t (*bind)(isc_socket_t *sock, isc_sockaddr_t *sockaddr, unsigned int options); isc_result_t (*sendto)(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo); isc_result_t (*sendto2)(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, isc_socketevent_t *event, unsigned int flags); isc_result_t (*connect)(isc_socket_t *sock, isc_sockaddr_t *addr, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t (*recv)(isc_socket_t *sock, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t (*recv2)(isc_socket_t *sock, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_socketevent_t *event, unsigned int flags); void (*cancel)(isc_socket_t *sock, isc_task_t *task, unsigned int how); isc_result_t (*getsockname)(isc_socket_t *sock, isc_sockaddr_t *addressp); isc_sockettype_t (*gettype)(isc_socket_t *sock); void (*ipv6only)(isc_socket_t *sock, bool yes); isc_result_t (*fdwatchpoke)(isc_socket_t *sock, int flags); isc_result_t (*dup)(isc_socket_t *socket, isc_socket_t **socketp); int (*getfd)(isc_socket_t *socket); void (*dscp)(isc_socket_t *socket, isc_dscp_t dscp); } isc_socketmethods_t; /*% * This structure is actually just the common prefix of a socket manager * object implementation's version of an isc_socketmgr_t. * \brief * Direct use of this structure by clients is forbidden. socket implementations * may change the structure. 'magic' must be ISCAPI_SOCKETMGR_MAGIC for any * of the isc_socket_ routines to work. socket implementations must maintain * all socket invariants. * In effect, this definition is used only for non-BIND9 version ("export") * of the library, and the export version does not work for win32. So, to avoid * the definition conflict with win32/socket.c, we enable this definition only * for non-Win32 (i.e. Unix) platforms. */ #ifndef WIN32 struct isc_socketmgr { unsigned int impmagic; unsigned int magic; isc_socketmgrmethods_t *methods; }; #endif #define ISCAPI_SOCKETMGR_MAGIC ISC_MAGIC('A','s','m','g') #define ISCAPI_SOCKETMGR_VALID(m) ((m) != NULL && \ (m)->magic == ISCAPI_SOCKETMGR_MAGIC) /*% * This is the common prefix of a socket object. The same note as * that for the socketmgr structure applies. */ #ifndef WIN32 struct isc_socket { unsigned int impmagic; unsigned int magic; isc_socketmethods_t *methods; }; #endif #define ISCAPI_SOCKET_MAGIC ISC_MAGIC('A','s','c','t') #define ISCAPI_SOCKET_VALID(s) ((s) != NULL && \ (s)->magic == ISCAPI_SOCKET_MAGIC) /*** *** Socket and Socket Manager Functions *** *** Note: all Ensures conditions apply only if the result is success for *** those functions which return an isc_result. ***/ isc_result_t isc_socket_fdwatchcreate(isc_socketmgr_t *manager, int fd, int flags, isc_sockfdwatch_t callback, void *cbarg, isc_task_t *task, isc_socket_t **socketp); /*%< * Create a new file descriptor watch socket managed by 'manager'. * * Note: * *\li 'fd' is the already-opened file descriptor (must be less * than maxsockets). *\li This function is not available on Windows. *\li The callback function is called "in-line" - this means the function * needs to return as fast as possible, as all other I/O will be suspended * until the callback completes. * * Requires: * *\li 'manager' is a valid manager * *\li 'socketp' is a valid pointer, and *socketp == NULL * *\li 'fd' be opened. * * Ensures: * * '*socketp' is attached to the newly created fdwatch socket * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_NORESOURCES *\li #ISC_R_UNEXPECTED *\li #ISC_R_RANGE */ isc_result_t isc_socket_fdwatchpoke(isc_socket_t *sock, int flags); /*%< * Poke a file descriptor watch socket informing the manager that it * should restart watching the socket * * Note: * *\li 'sock' is the socket returned by isc_socket_fdwatchcreate * *\li 'flags' indicates what the manager should watch for on the socket * in addition to what it may already be watching. It can be one or * both of ISC_SOCKFDWATCH_READ and ISC_SOCKFDWATCH_WRITE. To * temporarily disable watching on a socket the value indicating * no more data should be returned from the call back routine. * *\li This function is not available on Windows. * * Requires: * *\li 'sock' is a valid isc socket * * * Returns: * *\li #ISC_R_SUCCESS */ isc_result_t isc_socket_create(isc_socketmgr_t *manager, int pf, isc_sockettype_t type, isc_socket_t **socketp); /*%< * Create a new 'type' socket managed by 'manager'. * * For isc_sockettype_fdwatch sockets you should use isc_socket_fdwatchcreate() * rather than isc_socket_create(). * * Note: * *\li 'pf' is the desired protocol family, e.g. PF_INET or PF_INET6. * * Requires: * *\li 'manager' is a valid manager * *\li 'socketp' is a valid pointer, and *socketp == NULL * *\li 'type' is not isc_sockettype_fdwatch * * Ensures: * * '*socketp' is attached to the newly created socket * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_NORESOURCES *\li #ISC_R_UNEXPECTED */ isc_result_t isc_socket_dup(isc_socket_t *sock0, isc_socket_t **socketp); /*%< * Duplicate an existing socket, reusing its file descriptor. */ void isc_socket_cancel(isc_socket_t *sock, isc_task_t *task, unsigned int how); /*%< * Cancel pending I/O of the type specified by "how". * * Note: if "task" is NULL, then the cancel applies to all tasks using the * socket. * * Requires: * * \li "socket" is a valid socket * * \li "task" is NULL or a valid task * * "how" is a bitmask describing the type of cancellation to perform. * The type ISC_SOCKCANCEL_ALL will cancel all pending I/O on this * socket. * * \li ISC_SOCKCANCEL_RECV: * Cancel pending isc_socket_recv() calls. * * \li ISC_SOCKCANCEL_SEND: * Cancel pending isc_socket_send() and isc_socket_sendto() calls. * * \li ISC_SOCKCANCEL_ACCEPT: * Cancel pending isc_socket_accept() calls. * * \li ISC_SOCKCANCEL_CONNECT: * Cancel pending isc_socket_connect() call. */ void isc_socket_shutdown(isc_socket_t *sock, unsigned int how); /*%< * Shutdown 'socket' according to 'how'. * * Requires: * * \li 'socket' is a valid socket. * * \li 'task' is NULL or is a valid task. * * \li If 'how' is 'ISC_SOCKSHUT_RECV' or 'ISC_SOCKSHUT_ALL' then * * The read queue must be empty. * * No further read requests may be made. * * \li If 'how' is 'ISC_SOCKSHUT_SEND' or 'ISC_SOCKSHUT_ALL' then * * The write queue must be empty. * * No further write requests may be made. */ void isc_socket_attach(isc_socket_t *sock, isc_socket_t **socketp); /*%< * Attach *socketp to socket. * * Requires: * * \li 'socket' is a valid socket. * * \li 'socketp' points to a NULL socket. * * Ensures: * * \li *socketp is attached to socket. */ void isc_socket_detach(isc_socket_t **socketp); /*%< * Detach *socketp from its socket. * * Requires: * * \li 'socketp' points to a valid socket. * * \li If '*socketp' is the last reference to the socket, * then: * * There must be no pending I/O requests. * * Ensures: * * \li *socketp is NULL. * * \li If '*socketp' is the last reference to the socket, * then: * * The socket will be shutdown (both reading and writing) * for all tasks. * * All resources used by the socket have been freed */ isc_result_t isc_socket_open(isc_socket_t *sock); /*%< * Open a new socket file descriptor of the given socket structure. It simply * opens a new descriptor; all of the other parameters including the socket * type are inherited from the existing socket. This function is provided to * avoid overhead of destroying and creating sockets when many short-lived * sockets are frequently opened and closed. When the efficiency is not an * issue, it should be safer to detach the unused socket and re-create a new * one. This optimization may not be available for some systems, in which * case this function will return ISC_R_NOTIMPLEMENTED and must not be used. * * isc_socket_open() should not be called on sockets created by * isc_socket_fdwatchcreate(). * * Requires: * * \li there must be no other reference to this socket. * * \li 'socket' is a valid and previously closed by isc_socket_close() * * \li 'sock->type' is not isc_sockettype_fdwatch * * Returns: * Same as isc_socket_create(). * \li ISC_R_NOTIMPLEMENTED */ isc_result_t isc_socket_close(isc_socket_t *sock); /*%< * Close a socket file descriptor of the given socket structure. This function * is provided as an alternative to destroying an unused socket when overhead * destroying/re-creating sockets can be significant, and is expected to be * used with isc_socket_open(). This optimization may not be available for some * systems, in which case this function will return ISC_R_NOTIMPLEMENTED and * must not be used. * * isc_socket_close() should not be called on sockets created by * isc_socket_fdwatchcreate(). * * Requires: * * \li The socket must have a valid descriptor. * * \li There must be no other reference to this socket. * * \li There must be no pending I/O requests. * * \li 'sock->type' is not isc_sockettype_fdwatch * * Returns: * \li #ISC_R_NOTIMPLEMENTED */ isc_result_t isc_socket_bind(isc_socket_t *sock, isc_sockaddr_t *addressp, unsigned int options); /*%< * Bind 'socket' to '*addressp'. * * Requires: * * \li 'socket' is a valid socket * * \li 'addressp' points to a valid isc_sockaddr. * * Returns: * * \li ISC_R_SUCCESS * \li ISC_R_NOPERM * \li ISC_R_ADDRNOTAVAIL * \li ISC_R_ADDRINUSE * \li ISC_R_BOUND * \li ISC_R_UNEXPECTED */ isc_result_t isc_socket_filter(isc_socket_t *sock, const char *filter); /*%< * Inform the kernel that it should perform accept filtering. * If filter is NULL the current filter will be removed.:w */ isc_result_t isc_socket_listen(isc_socket_t *sock, unsigned int backlog); /*%< * Set listen mode on the socket. After this call, the only function that * can be used (other than attach and detach) is isc_socket_accept(). * * Notes: * * \li 'backlog' is as in the UNIX system call listen() and may be * ignored by non-UNIX implementations. * * \li If 'backlog' is zero, a reasonable system default is used, usually * SOMAXCONN. * * Requires: * * \li 'socket' is a valid, bound TCP socket or a valid, bound UNIX socket. * * Returns: * * \li ISC_R_SUCCESS * \li ISC_R_UNEXPECTED */ isc_result_t isc_socket_accept(isc_socket_t *sock, isc_task_t *task, isc_taskaction_t action, void *arg); /*%< * Queue accept event. When a new connection is received, the task will * get an ISC_SOCKEVENT_NEWCONN event with the sender set to the listen * socket. The new socket structure is sent inside the isc_socket_newconnev_t * event type, and is attached to the task 'task'. * * REQUIRES: * \li 'socket' is a valid TCP socket that isc_socket_listen() was called * on. * * \li 'task' is a valid task * * \li 'action' is a valid action * * RETURNS: * \li ISC_R_SUCCESS * \li ISC_R_NOMEMORY * \li ISC_R_UNEXPECTED */ isc_result_t isc_socket_connect(isc_socket_t *sock, isc_sockaddr_t *addressp, isc_task_t *task, isc_taskaction_t action, void *arg); /*%< * Connect 'socket' to peer with address *saddr. When the connection * succeeds, or when an error occurs, a CONNECT event with action 'action' * and arg 'arg' will be posted to the event queue for 'task'. * * Requires: * * \li 'socket' is a valid TCP socket * * \li 'addressp' points to a valid isc_sockaddr * * \li 'task' is a valid task * * \li 'action' is a valid action * * Returns: * * \li ISC_R_SUCCESS * \li ISC_R_NOMEMORY * \li ISC_R_UNEXPECTED * * Posted event's result code: * * \li ISC_R_SUCCESS * \li ISC_R_TIMEDOUT * \li ISC_R_CONNREFUSED * \li ISC_R_NETUNREACH * \li ISC_R_UNEXPECTED */ isc_result_t isc_socket_getpeername(isc_socket_t *sock, isc_sockaddr_t *addressp); /*%< * Get the name of the peer connected to 'socket'. * * Requires: * * \li 'socket' is a valid TCP socket. * * Returns: * * \li ISC_R_SUCCESS * \li ISC_R_TOOSMALL * \li ISC_R_UNEXPECTED */ isc_result_t isc_socket_getsockname(isc_socket_t *sock, isc_sockaddr_t *addressp); /*%< * Get the name of 'socket'. * * Requires: * * \li 'socket' is a valid socket. * * Returns: * * \li ISC_R_SUCCESS * \li ISC_R_TOOSMALL * \li ISC_R_UNEXPECTED */ /*@{*/ isc_result_t isc_socket_recv(isc_socket_t *sock, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc_socket_recvv(isc_socket_t *sock, isc_bufferlist_t *buflist, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc_socket_recv2(isc_socket_t *sock, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_socketevent_t *event, unsigned int flags); /*! * Receive from 'socket', storing the results in region. * * Notes: * *\li Let 'length' refer to the length of 'region' or to the sum of all * available regions in the list of buffers '*buflist'. * *\li If 'minimum' is non-zero and at least that many bytes are read, * the completion event will be posted to the task 'task.' If minimum * is zero, the exact number of bytes requested in the region must * be read for an event to be posted. This only makes sense for TCP * connections, and is always set to 1 byte for UDP. * *\li The read will complete when the desired number of bytes have been * read, if end-of-input occurs, or if an error occurs. A read done * event with the given 'action' and 'arg' will be posted to the * event queue of 'task'. * *\li The caller may not modify 'region', the buffers which are passed * into this function, or any data they refer to until the completion * event is received. * *\li For isc_socket_recvv(): * On successful completion, '*buflist' will be empty, and the list of * all buffers will be returned in the done event's 'bufferlist' * member. On error return, '*buflist' will be unchanged. * *\li For isc_socket_recv2(): * 'event' is not NULL, and the non-socket specific fields are * expected to be initialized. * *\li For isc_socket_recv2(): * The only defined value for 'flags' is ISC_SOCKFLAG_IMMEDIATE. If * set and the operation completes, the return value will be * ISC_R_SUCCESS and the event will be filled in and not sent. If the * operation does not complete, the return value will be * ISC_R_INPROGRESS and the event will be sent when the operation * completes. * * Requires: * *\li 'socket' is a valid, bound socket. * *\li For isc_socket_recv(): * 'region' is a valid region * *\li For isc_socket_recvv(): * 'buflist' is non-NULL, and '*buflist' contain at least one buffer. * *\li 'task' is a valid task * *\li For isc_socket_recv() and isc_socket_recvv(): * action != NULL and is a valid action * *\li For isc_socket_recv2(): * event != NULL * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_INPROGRESS *\li #ISC_R_NOMEMORY *\li #ISC_R_UNEXPECTED * * Event results: * *\li #ISC_R_SUCCESS *\li #ISC_R_UNEXPECTED *\li XXX needs other net-type errors */ /*@}*/ /*@{*/ isc_result_t isc_socket_send(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc_socket_sendto(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo); isc_result_t isc_socket_sendv(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc_socket_sendtov(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo); isc_result_t isc_socket_sendtov2(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, unsigned int flags); isc_result_t isc_socket_sendto2(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, isc_socketevent_t *event, unsigned int flags); /*! * Send the contents of 'region' to the socket's peer. * * Notes: * *\li Shutting down the requestor's task *may* result in any * still pending writes being dropped or completed, depending on the * underlying OS implementation. * *\li If 'action' is NULL, then no completion event will be posted. * *\li The caller may not modify 'region', the buffers which are passed * into this function, or any data they refer to until the completion * event is received. * *\li For isc_socket_sendv() and isc_socket_sendtov(): * On successful completion, '*buflist' will be empty, and the list of * all buffers will be returned in the done event's 'bufferlist' * member. On error return, '*buflist' will be unchanged. * *\li For isc_socket_sendto2(): * 'event' is not NULL, and the non-socket specific fields are * expected to be initialized. * *\li For isc_socket_sendto2(): * The only defined values for 'flags' are ISC_SOCKFLAG_IMMEDIATE * and ISC_SOCKFLAG_NORETRY. * *\li If ISC_SOCKFLAG_IMMEDIATE is set and the operation completes, the * return value will be ISC_R_SUCCESS and the event will be filled * in and not sent. If the operation does not complete, the return * value will be ISC_R_INPROGRESS and the event will be sent when * the operation completes. * *\li ISC_SOCKFLAG_NORETRY can only be set for UDP sockets. If set * and the send operation fails due to a transient error, the send * will not be retried and the error will be indicated in the event. * Using this option along with ISC_SOCKFLAG_IMMEDIATE allows the caller * to specify a region that is allocated on the stack. * * Requires: * *\li 'socket' is a valid, bound socket. * *\li For isc_socket_send(): * 'region' is a valid region * *\li For isc_socket_sendv() and isc_socket_sendtov(): * 'buflist' is non-NULL, and '*buflist' contain at least one buffer. * *\li 'task' is a valid task * *\li For isc_socket_sendv(), isc_socket_sendtov(), isc_socket_send(), and * isc_socket_sendto(): * action == NULL or is a valid action * *\li For isc_socket_sendto2(): * event != NULL * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_INPROGRESS *\li #ISC_R_NOMEMORY *\li #ISC_R_UNEXPECTED * * Event results: * *\li #ISC_R_SUCCESS *\li #ISC_R_UNEXPECTED *\li XXX needs other net-type errors */ /*@}*/ isc_result_t isc_socketmgr_createinctx(isc_mem_t *mctx, isc_appctx_t *actx, isc_socketmgr_t **managerp); isc_result_t isc_socketmgr_create(isc_mem_t *mctx, isc_socketmgr_t **managerp); isc_result_t isc_socketmgr_create2(isc_mem_t *mctx, isc_socketmgr_t **managerp, unsigned int maxsocks); /*%< * Create a socket manager. If "maxsocks" is non-zero, it specifies the * maximum number of sockets that the created manager should handle. * isc_socketmgr_create() is equivalent of isc_socketmgr_create2() with * "maxsocks" being zero. * isc_socketmgr_createinctx() also associates the new manager with the * specified application context. * * Notes: * *\li All memory will be allocated in memory context 'mctx'. * * Requires: * *\li 'mctx' is a valid memory context. * *\li 'managerp' points to a NULL isc_socketmgr_t. * *\li 'actx' is a valid application context (for createinctx()). * * Ensures: * *\li '*managerp' is a valid isc_socketmgr_t. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_UNEXPECTED *\li #ISC_R_NOTIMPLEMENTED */ isc_result_t isc_socketmgr_getmaxsockets(isc_socketmgr_t *manager, unsigned int *nsockp); /*%< * Returns in "*nsockp" the maximum number of sockets this manager may open. * * Requires: * *\li '*manager' is a valid isc_socketmgr_t. *\li 'nsockp' is not NULL. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOTIMPLEMENTED */ void isc_socketmgr_setstats(isc_socketmgr_t *manager, isc_stats_t *stats); /*%< * Set a general socket statistics counter set 'stats' for 'manager'. * * Requires: * \li 'manager' is valid, hasn't opened any socket, and doesn't have * stats already set. * *\li stats is a valid statistics supporting socket statistics counters * (see above). */ void isc_socketmgr_destroy(isc_socketmgr_t **managerp); /*%< * Destroy a socket manager. * * Notes: * *\li This routine blocks until there are no sockets left in the manager, * so if the caller holds any socket references using the manager, it * must detach them before calling isc_socketmgr_destroy() or it will * block forever. * * Requires: * *\li '*managerp' is a valid isc_socketmgr_t. * *\li All sockets managed by this manager are fully detached. * * Ensures: * *\li *managerp == NULL * *\li All resources used by the manager have been freed. */ isc_sockettype_t isc_socket_gettype(isc_socket_t *sock); /*%< * Returns the socket type for "sock." * * Requires: * *\li "sock" is a valid socket. */ /*@{*/ bool isc__socket_isbound(isc_socket_t *sock); /*% * Intended for internal use in BIND9 only */ void isc_socket_ipv6only(isc_socket_t *sock, bool yes); /*%< * If the socket is an IPv6 socket set/clear the IPV6_IPV6ONLY socket * option if the host OS supports this option. * * Requires: *\li 'sock' is a valid socket. */ /*@}*/ void isc_socket_dscp(isc_socket_t *sock, isc_dscp_t dscp); /*%< * Sets the Differentiated Services Code Point (DSCP) field for packets * transmitted on this socket. If 'dscp' is -1, return immediately. * * Requires: *\li 'sock' is a valid socket. */ isc_socketevent_t * isc_socket_socketevent(isc_mem_t *mctx, void *sender, isc_eventtype_t eventtype, isc_taskaction_t action, void *arg); /*%< * Get a isc_socketevent_t to be used with isc_socket_sendto2(), etc. */ void isc_socket_cleanunix(isc_sockaddr_t *addr, bool active); /*%< * Cleanup UNIX domain sockets in the file-system. If 'active' is true * then just unlink the socket. If 'active' is false try to determine * if there is a listener of the socket or not. If no listener is found * then unlink socket. * * Prior to unlinking the path is tested to see if it a socket. * * Note: there are a number of race conditions which cannot be avoided * both in the filesystem and any application using UNIX domain * sockets (e.g. socket is tested between bind() and listen(), * the socket is deleted and replaced in the file-system between * stat() and unlink()). */ isc_result_t isc_socket_permunix(isc_sockaddr_t *sockaddr, uint32_t perm, uint32_t owner, uint32_t group); /*%< * Set ownership and file permissions on the UNIX domain socket. * * Note: On Solaris and SunOS this secures the directory containing * the socket as Solaris and SunOS do not honour the filesystem * permissions on the socket. * * Requires: * \li 'sockaddr' to be a valid UNIX domain sockaddr. * * Returns: * \li #ISC_R_SUCCESS * \li #ISC_R_FAILURE */ void isc_socket_setname(isc_socket_t *socket, const char *name, void *tag); /*%< * Set the name and optional tag for a socket. This allows tracking of the * owner or purpose for this socket, and is useful for tracing and statistics * reporting. */ const char *isc_socket_getname(isc_socket_t *socket); /*%< * Get the name associated with a socket, if any. */ void *isc_socket_gettag(isc_socket_t *socket); /*%< * Get the tag associated with a socket, if any. */ int isc_socket_getfd(isc_socket_t *socket); /*%< * Get the file descriptor associated with a socket */ void isc__socketmgr_setreserved(isc_socketmgr_t *mgr, uint32_t); /*%< * Temporary. For use by named only. */ void isc__socketmgr_maxudp(isc_socketmgr_t *mgr, unsigned int maxudp); /*%< * Test interface. Drop UDP packet > 'maxudp'. */ #ifdef HAVE_LIBXML2 int isc_socketmgr_renderxml(isc_socketmgr_t *mgr, xmlTextWriterPtr writer); /*%< * Render internal statistics and other state into the XML document. */ #endif /* HAVE_LIBXML2 */ #ifdef HAVE_JSON isc_result_t isc_socketmgr_renderjson(isc_socketmgr_t *mgr, json_object *stats); /*%< * Render internal statistics and other state into JSON format. */ #endif /* HAVE_JSON */ /*%< * See isc_socketmgr_create() above. */ typedef isc_result_t (*isc_socketmgrcreatefunc_t)(isc_mem_t *mctx, isc_socketmgr_t **managerp); isc_result_t isc_socket_register(isc_socketmgrcreatefunc_t createfunc); /*%< * Register a new socket I/O implementation and add it to the list of * supported implementations. This function must be called when a different * event library is used than the one contained in the ISC library. */ isc_result_t isc__socket_register(void); /*%< * A short cut function that specifies the socket I/O module in the ISC * library for isc_socket_register(). An application that uses the ISC library * usually do not have to care about this function: it would call * isc_lib_register(), which internally calls this function. */ ISC_LANG_ENDDECLS #endif /* ISC_SOCKET_H */ PKֺ1]͓errno.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ERRNO_H #define ISC_ERRNO_H 1 /*! \file isc/file.h */ #include ISC_LANG_BEGINDECLS isc_result_t isc_errno_toresult(int err); /*!< * \brief Convert a POSIX errno value to an ISC result code. */ ISC_LANG_ENDDECLS #endif /* ISC_ERRNO_H */ PKֺ1]Yerror.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ERROR_H #define ISC_ERROR_H 1 /*! \file isc/error.h */ #include #include #include #include #include ISC_LANG_BEGINDECLS typedef void (*isc_errorcallback_t)(const char *, int, const char *, va_list); /*% set unexpected error */ void isc_error_setunexpected(isc_errorcallback_t); /*% set fatal error */ void isc_error_setfatal(isc_errorcallback_t); /*% unexpected error */ void isc_error_unexpected(const char *, int, const char *, ...) ISC_FORMAT_PRINTF(3, 4); /*% fatal error */ ISC_PLATFORM_NORETURN_PRE void isc_error_fatal(const char *, int, const char *, ...) ISC_FORMAT_PRINTF(3, 4) ISC_PLATFORM_NORETURN_POST; /*% runtimecheck error */ ISC_PLATFORM_NORETURN_PRE void isc_error_runtimecheck(const char *, int, const char *) ISC_PLATFORM_NORETURN_POST; #define ISC_ERROR_RUNTIMECHECK(cond) \ ((void) (ISC_LIKELY(cond) || \ ((isc_error_runtimecheck)(__FILE__, __LINE__, #cond), 0))) ISC_LANG_ENDDECLS #endif /* ISC_ERROR_H */ PKֺ1] ) parseint.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_PARSEINT_H #define ISC_PARSEINT_H 1 #include #include #include /*! \file isc/parseint.h * \brief Parse integers, in a saner way than atoi() or strtoul() do. */ /*** *** Functions ***/ ISC_LANG_BEGINDECLS isc_result_t isc_parse_uint32(uint32_t *uip, const char *string, int base); isc_result_t isc_parse_uint16(uint16_t *uip, const char *string, int base); isc_result_t isc_parse_uint8(uint8_t *uip, const char *string, int base); /*%< * Parse the null-terminated string 'string' containing a base 'base' * integer, storing the result in '*uip'. * The base is interpreted * as in strtoul(). Unlike strtoul(), leading whitespace, minus or * plus signs are not accepted, and all errors (including overflow) * are reported uniformly through the return value. * * Requires: *\li 'string' points to a null-terminated string *\li 0 <= 'base' <= 36 * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_BADNUMBER The string is not numeric (in the given base) *\li #ISC_R_RANGE The number is not representable as the requested type. */ ISC_LANG_ENDDECLS #endif /* ISC_PARSEINT_H */ PKֺ1]"l  httpd.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_HTTPD_H #define ISC_HTTPD_H 1 /*! \file */ #include #include #include #include #include #include #include /*% * HTTP urls. These are the URLs we manage, and the function to call to * provide the data for it. We pass in the base url (so the same function * can handle multiple requests), and a structure to fill in to return a * result to the client. We also pass in a pointer to be filled in for * the data cleanup function. */ struct isc_httpdurl { char *url; isc_httpdaction_t *action; void *action_arg; bool isstatic; isc_time_t loadtime; ISC_LINK(isc_httpdurl_t) link; }; #define HTTPD_EVENTCLASS ISC_EVENTCLASS(4300) #define HTTPD_SHUTDOWN (HTTPD_EVENTCLASS + 0x0001) #define ISC_HTTPDMGR_FLAGSHUTTINGDOWN 0x00000001 /* * Create a new http daemon which will send, once every time period, * a http-like header followed by HTTP data. */ isc_result_t isc_httpdmgr_create(isc_mem_t *mctx, isc_socket_t *sock, isc_task_t *task, isc_httpdclientok_t *client_ok, isc_httpdondestroy_t *ondestory, void *cb_arg, isc_timermgr_t *tmgr, isc_httpdmgr_t **httpdp); void isc_httpdmgr_shutdown(isc_httpdmgr_t **httpdp); isc_result_t isc_httpdmgr_addurl(isc_httpdmgr_t *httpdmgr, const char *url, isc_httpdaction_t *func, void *arg); isc_result_t isc_httpdmgr_addurl2(isc_httpdmgr_t *httpdmgr, const char *url, bool isstatic, isc_httpdaction_t *func, void *arg); isc_result_t isc_httpd_response(isc_httpd_t *httpd); isc_result_t isc_httpd_addheader(isc_httpd_t *httpd, const char *name, const char *val); isc_result_t isc_httpd_addheaderuint(isc_httpd_t *httpd, const char *name, int val); isc_result_t isc_httpd_endheaders(isc_httpd_t *httpd); void isc_httpd_setfinishhook(void (*fn)(void)); #endif /* ISC_HTTPD_H */ PKֺ1]_@stdio.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STDIO_H #define ISC_STDIO_H 1 /*! \file isc/stdio.h */ /*% * These functions are wrappers around the corresponding stdio functions. * * They return a detailed error code in the form of an an isc_result_t. ANSI C * does not guarantee that stdio functions set errno, hence these functions * must use platform dependent methods (e.g., the POSIX errno) to construct the * error code. */ #include #include #include ISC_LANG_BEGINDECLS /*% Open */ isc_result_t isc_stdio_open(const char *filename, const char *mode, FILE **fp); /*% Close */ isc_result_t isc_stdio_close(FILE *f); /*% Seek */ isc_result_t isc_stdio_seek(FILE *f, off_t offset, int whence); /*% Tell */ isc_result_t isc_stdio_tell(FILE *f, off_t *offsetp); /*% Read */ isc_result_t isc_stdio_read(void *ptr, size_t size, size_t nmemb, FILE *f, size_t *nret); /*% Write */ isc_result_t isc_stdio_write(const void *ptr, size_t size, size_t nmemb, FILE *f, size_t *nret); /*% Flush */ isc_result_t isc_stdio_flush(FILE *f); isc_result_t isc_stdio_sync(FILE *f); /*%< * Invoke fsync() on the file descriptor underlying an stdio stream, or an * equivalent system-dependent operation. Note that this function has no * direct counterpart in the stdio library. */ isc_result_t isc_stdio_fgetc(FILE *f, int *ret); ISC_LANG_ENDDECLS #endif /* ISC_STDIO_H */ PKֺ1]~a&)&)net.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_NET_H #define ISC_NET_H 1 /***** ***** Module Info *****/ /*! \file * \brief * Basic Networking Types * * This module is responsible for defining the following basic networking * types: * *\li struct in_addr *\li struct in6_addr *\li struct in6_pktinfo *\li struct sockaddr *\li struct sockaddr_in *\li struct sockaddr_in6 *\li struct sockaddr_storage *\li in_port_t * * It ensures that the AF_ and PF_ macros are defined. * * It declares ntoh[sl]() and hton[sl](). * * It declares inet_aton(), inet_ntop(), and inet_pton(). * * It ensures that #INADDR_LOOPBACK, #INADDR_ANY, #IN6ADDR_ANY_INIT, * IN6ADDR_V4MAPPED_INIT, in6addr_any, and in6addr_loopback are available. * * It ensures that IN_MULTICAST() is available to check for multicast * addresses. * * MP: *\li No impact. * * Reliability: *\li No anticipated impact. * * Resources: *\li N/A. * * Security: *\li No anticipated impact. * * Standards: *\li BSD Socket API *\li RFC2553 */ /*** *** Imports. ***/ #include #include #include #include /* Contractual promise. */ #include #include /* Contractual promise. */ #include /* Contractual promise. */ #ifdef ISC_PLATFORM_NEEDNETINETIN6H #include /* Required on UnixWare. */ #endif #ifdef ISC_PLATFORM_NEEDNETINET6IN6H #include /* Required on BSD/OS for in6_pktinfo. */ #endif #ifndef ISC_PLATFORM_HAVEIPV6 #include /* Contractual promise. */ #endif #include #include #ifdef ISC_PLATFORM_HAVEINADDR6 #define in6_addr in_addr6 /*%< Required for pre RFC2133 implementations. */ #endif #ifdef ISC_PLATFORM_HAVEIPV6 #ifndef IN6ADDR_ANY_INIT #ifdef s6_addr /*% * Required for some pre RFC2133 implementations. * IN6ADDR_ANY_INIT and IN6ADDR_LOOPBACK_INIT were added in * draft-ietf-ipngwg-bsd-api-04.txt or draft-ietf-ipngwg-bsd-api-05.txt. * If 's6_addr' is defined then assume that there is a union and three * levels otherwise assume two levels required. */ #define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } #else #define IN6ADDR_ANY_INIT { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } #endif #endif #ifndef IN6ADDR_LOOPBACK_INIT #ifdef s6_addr /*% IPv6 address loopback init */ #define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } #else #define IN6ADDR_LOOPBACK_INIT { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } #endif #endif #ifndef IN6ADDR_V4MAPPED_INIT #ifdef s6_addr /*% IPv6 v4mapped prefix init */ #define IN6ADDR_V4MAPPED_INIT { { { 0,0,0,0,0,0,0,0,0,0,0xff,0xff,0,0,0,0 } } } #else #define IN6ADDR_V4MAPPED_INIT { { 0,0,0,0,0,0,0,0,0,0,0xff,0xff,0,0,0,0 } } #endif #endif #ifndef IN6_IS_ADDR_V4MAPPED /*% Is IPv6 address V4 mapped? */ #define IN6_IS_ADDR_V4MAPPED(x) \ (memcmp((x)->s6_addr, in6addr_any.s6_addr, 10) == 0 && \ (x)->s6_addr[10] == 0xff && (x)->s6_addr[11] == 0xff) #endif #ifndef IN6_IS_ADDR_V4COMPAT /*% Is IPv6 address V4 compatible? */ #define IN6_IS_ADDR_V4COMPAT(x) \ (memcmp((x)->s6_addr, in6addr_any.s6_addr, 12) == 0 && \ ((x)->s6_addr[12] != 0 || (x)->s6_addr[13] != 0 || \ (x)->s6_addr[14] != 0 || \ ((x)->s6_addr[15] != 0 && (x)->s6_addr[15] != 1))) #endif #ifndef IN6_IS_ADDR_MULTICAST /*% Is IPv6 address multicast? */ #define IN6_IS_ADDR_MULTICAST(a) ((a)->s6_addr[0] == 0xff) #endif #ifndef IN6_IS_ADDR_LINKLOCAL /*% Is IPv6 address linklocal? */ #define IN6_IS_ADDR_LINKLOCAL(a) \ (((a)->s6_addr[0] == 0xfe) && (((a)->s6_addr[1] & 0xc0) == 0x80)) #endif #ifndef IN6_IS_ADDR_SITELOCAL /*% is IPv6 address sitelocal? */ #define IN6_IS_ADDR_SITELOCAL(a) \ (((a)->s6_addr[0] == 0xfe) && (((a)->s6_addr[1] & 0xc0) == 0xc0)) #endif #ifndef IN6_IS_ADDR_LOOPBACK /*% is IPv6 address loopback? */ #define IN6_IS_ADDR_LOOPBACK(x) \ (memcmp((x)->s6_addr, in6addr_loopback.s6_addr, 16) == 0) #endif #endif #ifndef AF_INET6 /*% IPv6 */ #define AF_INET6 99 #endif #ifndef PF_INET6 /*% IPv6 */ #define PF_INET6 AF_INET6 #endif #ifndef INADDR_ANY /*% inaddr any */ #define INADDR_ANY 0x00000000UL #endif #ifndef INADDR_LOOPBACK /*% inaddr loopback */ #define INADDR_LOOPBACK 0x7f000001UL #endif #ifndef ISC_PLATFORM_HAVEIN6PKTINFO /*% IPv6 packet info */ struct in6_pktinfo { struct in6_addr ipi6_addr; /*%< src/dst IPv6 address */ unsigned int ipi6_ifindex; /*%< send/recv interface index */ }; #endif #ifndef ISC_PLATFORM_HAVESOCKADDRSTORAGE #define _SS_MAXSIZE 128 #define _SS_ALIGNSIZE (sizeof (uint64_t)) #ifdef ISC_PLATFORM_HAVESALEN #define _SS_PAD1SIZE (_SS_ALIGNSIZE - (2 * sizeof(uint8_t))) #define _SS_PAD2SIZE (_SS_MAXSIZE - (_SS_ALIGNSIZE + _SS_PAD1SIZE \ + 2 * sizeof(uint8_t))) #else #define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(uint16_t)) #define _SS_PAD2SIZE (_SS_MAXSIZE - (_SS_ALIGNSIZE + _SS_PAD1SIZE \ + sizeof(uint16_t))) #endif struct sockaddr_storage { #ifdef ISC_PLATFORM_HAVESALEN uint8_t ss_len; uint8_t ss_family; #else uint16_t ss_family; #endif char __ss_pad1[_SS_PAD1SIZE]; uint64_t __ss_align; /* field to force desired structure */ char __ss_pad2[_SS_PAD2SIZE]; }; #endif #if defined(ISC_PLATFORM_HAVEIPV6) && defined(ISC_PLATFORM_NEEDIN6ADDRANY) extern const struct in6_addr isc_net_in6addrany; /*% * Cope with a missing in6addr_any and in6addr_loopback. */ #define in6addr_any isc_net_in6addrany #endif #if defined(ISC_PLATFORM_HAVEIPV6) && defined(ISC_PLATFORM_NEEDIN6ADDRLOOPBACK) extern const struct in6_addr isc_net_in6addrloop; #define in6addr_loopback isc_net_in6addrloop #endif #ifdef ISC_PLATFORM_FIXIN6ISADDR #undef IN6_IS_ADDR_GEOGRAPHIC /*! * \brief * Fix UnixWare 7.1.1's broken IN6_IS_ADDR_* definitions. */ #define IN6_IS_ADDR_GEOGRAPHIC(a) (((a)->S6_un.S6_l[0] & 0xE0) == 0x80) #undef IN6_IS_ADDR_IPX #define IN6_IS_ADDR_IPX(a) (((a)->S6_un.S6_l[0] & 0xFE) == 0x04) #undef IN6_IS_ADDR_LINKLOCAL #define IN6_IS_ADDR_LINKLOCAL(a) (((a)->S6_un.S6_l[0] & 0xC0FF) == 0x80FE) #undef IN6_IS_ADDR_MULTICAST #define IN6_IS_ADDR_MULTICAST(a) (((a)->S6_un.S6_l[0] & 0xFF) == 0xFF) #undef IN6_IS_ADDR_NSAP #define IN6_IS_ADDR_NSAP(a) (((a)->S6_un.S6_l[0] & 0xFE) == 0x02) #undef IN6_IS_ADDR_PROVIDER #define IN6_IS_ADDR_PROVIDER(a) (((a)->S6_un.S6_l[0] & 0xE0) == 0x40) #undef IN6_IS_ADDR_SITELOCAL #define IN6_IS_ADDR_SITELOCAL(a) (((a)->S6_un.S6_l[0] & 0xC0FF) == 0xC0FE) #endif /* ISC_PLATFORM_FIXIN6ISADDR */ #ifdef ISC_PLATFORM_NEEDPORTT /*% * Ensure type in_port_t is defined. */ typedef uint16_t in_port_t; #endif #ifndef MSG_TRUNC /*% * If this system does not have MSG_TRUNC (as returned from recvmsg()) * ISC_PLATFORM_RECVOVERFLOW will be defined. This will enable the MSG_TRUNC * faking code in socket.c. */ #define ISC_PLATFORM_RECVOVERFLOW #endif /*% IP address. */ #define ISC__IPADDR(x) ((uint32_t)htonl((uint32_t)(x))) /*% Is IP address multicast? */ #define ISC_IPADDR_ISMULTICAST(i) \ (((uint32_t)(i) & ISC__IPADDR(0xf0000000)) \ == ISC__IPADDR(0xe0000000)) #define ISC_IPADDR_ISEXPERIMENTAL(i) \ (((uint32_t)(i) & ISC__IPADDR(0xf0000000)) \ == ISC__IPADDR(0xf0000000)) /*** *** Functions. ***/ ISC_LANG_BEGINDECLS isc_result_t isc_net_probeipv4(void); /*%< * Check if the system's kernel supports IPv4. * * Returns: * *\li #ISC_R_SUCCESS IPv4 is supported. *\li #ISC_R_NOTFOUND IPv4 is not supported. *\li #ISC_R_DISABLED IPv4 is disabled. *\li #ISC_R_UNEXPECTED */ isc_result_t isc_net_probeipv6(void); /*%< * Check if the system's kernel supports IPv6. * * Returns: * *\li #ISC_R_SUCCESS IPv6 is supported. *\li #ISC_R_NOTFOUND IPv6 is not supported. *\li #ISC_R_DISABLED IPv6 is disabled. *\li #ISC_R_UNEXPECTED */ isc_result_t isc_net_probe_ipv6only(void); /*%< * Check if the system's kernel supports the IPV6_V6ONLY socket option. * * Returns: * *\li #ISC_R_SUCCESS the option is supported for both TCP and UDP. *\li #ISC_R_NOTFOUND IPv6 itself or the option is not supported. *\li #ISC_R_UNEXPECTED */ isc_result_t isc_net_probe_ipv6pktinfo(void); /* * Check if the system's kernel supports the IPV6_(RECV)PKTINFO socket option * for UDP sockets. * * Returns: * * \li #ISC_R_SUCCESS the option is supported. * \li #ISC_R_NOTFOUND IPv6 itself or the option is not supported. * \li #ISC_R_UNEXPECTED */ void isc_net_disableipv4(void); void isc_net_disableipv6(void); void isc_net_enableipv4(void); void isc_net_enableipv6(void); isc_result_t isc_net_probeunix(void); /* * Returns whether UNIX domain sockets are supported. */ #define ISC_NET_DSCPRECVV4 0x01 /* Can receive sent DSCP value IPv4 */ #define ISC_NET_DSCPRECVV6 0x02 /* Can receive sent DSCP value IPv6 */ #define ISC_NET_DSCPSETV4 0x04 /* Can set DSCP on socket IPv4 */ #define ISC_NET_DSCPSETV6 0x08 /* Can set DSCP on socket IPv6 */ #define ISC_NET_DSCPPKTV4 0x10 /* Can set DSCP on per packet IPv4 */ #define ISC_NET_DSCPPKTV6 0x20 /* Can set DSCP on per packet IPv6 */ #define ISC_NET_DSCPALL 0x3f /* All valid flags */ unsigned int isc_net_probedscp(void); /*%< * Probe the level of DSCP support. */ isc_result_t isc_net_getudpportrange(int af, in_port_t *low, in_port_t *high); /*%< * Returns system's default range of ephemeral UDP ports, if defined. * If the range is not available or unknown, ISC_NET_PORTRANGELOW and * ISC_NET_PORTRANGEHIGH will be returned. * * Requires: * *\li 'low' and 'high' must be non NULL. * * Returns: * *\li *low and *high will be the ports specifying the low and high ends of * the range. */ #ifdef ISC_PLATFORM_NEEDNTOP const char * isc_net_ntop(int af, const void *src, char *dst, size_t size); #undef inet_ntop #define inet_ntop isc_net_ntop #endif #ifdef ISC_PLATFORM_NEEDPTON int isc_net_pton(int af, const char *src, void *dst); #undef inet_pton #define inet_pton isc_net_pton #endif int isc_net_aton(const char *cp, struct in_addr *addr); #undef inet_aton #define inet_aton isc_net_aton ISC_LANG_ENDDECLS #endif /* ISC_NET_H */ PKֺ1]v!XXserial.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SERIAL_H #define ISC_SERIAL_H 1 #include #include #include #include /*! \file isc/serial.h * \brief Implement 32 bit serial space arithmetic comparison functions. * Note: Undefined results are returned as false. */ /*** *** Functions ***/ ISC_LANG_BEGINDECLS bool isc_serial_lt(uint32_t a, uint32_t b); /*%< * Return true if 'a' < 'b' otherwise false. */ bool isc_serial_gt(uint32_t a, uint32_t b); /*%< * Return true if 'a' > 'b' otherwise false. */ bool isc_serial_le(uint32_t a, uint32_t b); /*%< * Return true if 'a' <= 'b' otherwise false. */ bool isc_serial_ge(uint32_t a, uint32_t b); /*%< * Return true if 'a' >= 'b' otherwise false. */ bool isc_serial_eq(uint32_t a, uint32_t b); /*%< * Return true if 'a' == 'b' otherwise false. */ bool isc_serial_ne(uint32_t a, uint32_t b); /*%< * Return true if 'a' != 'b' otherwise false. */ ISC_LANG_ENDDECLS #endif /* ISC_SERIAL_H */ PKֺ1]ǵ,,ht.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * SPDX-License-Identifier: MPL-2.0 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /* ! \file */ #pragma once #include #include #include #include typedef struct isc_ht isc_ht_t; typedef struct isc_ht_iter isc_ht_iter_t; enum { ISC_HT_CASE_SENSITIVE = 0x00, ISC_HT_CASE_INSENSITIVE = 0x01 }; /*% * Initialize hashtable at *htp, using memory context and size of (1<=1 and 'bits' <=32 * */ void isc_ht_init(isc_ht_t **htp, isc_mem_t *mctx, uint8_t bits, unsigned int options); /*% * Destroy hashtable, freeing everything * * Requires: * \li '*htp' is valid hashtable */ void isc_ht_destroy(isc_ht_t **htp); /*% * Add a node to hashtable, pointed by binary key 'key' of size 'keysize'; * set its value to 'value' * * Requires: *\li 'ht' is a valid hashtable *\li write-lock * * Returns: *\li #ISC_R_NOMEMORY -- not enough memory to create pool *\li #ISC_R_EXISTS -- node of the same key already exists *\li #ISC_R_SUCCESS -- all is well. */ isc_result_t isc_ht_add(isc_ht_t *ht, const unsigned char *key, const uint32_t keysize, void *value); /*% * Find a node matching 'key'/'keysize' in hashtable 'ht'; * if found, set '*valuep' to its value. (If 'valuep' is NULL, * then simply return SUCCESS or NOTFOUND to indicate whether the * key exists in the hashtable.) * * Requires: * \li 'ht' is a valid hashtable * \li read-lock * * Returns: * \li #ISC_R_SUCCESS -- success * \li #ISC_R_NOTFOUND -- key not found */ isc_result_t isc_ht_find(const isc_ht_t *ht, const unsigned char *key, const uint32_t keysize, void **valuep); /*% * Delete node from hashtable * * Requires: *\li ht is a valid hashtable *\li write-lock * * Returns: *\li #ISC_R_NOTFOUND -- key not found *\li #ISC_R_SUCCESS -- all is well */ isc_result_t isc_ht_delete(isc_ht_t *ht, const unsigned char *key, const uint32_t keysize); /*% * Create an iterator for the hashtable; point '*itp' to it. * * Requires: *\li 'ht' is a valid hashtable *\li 'itp' is non NULL and '*itp' is NULL. */ void isc_ht_iter_create(isc_ht_t *ht, isc_ht_iter_t **itp); /*% * Destroy the iterator '*itp', set it to NULL * * Requires: *\li 'itp' is non NULL and '*itp' is non NULL. */ void isc_ht_iter_destroy(isc_ht_iter_t **itp); /*% * Set an iterator to the first entry. * * Requires: *\li 'it' is non NULL. * * Returns: * \li #ISC_R_SUCCESS -- success * \li #ISC_R_NOMORE -- no data in the hashtable */ isc_result_t isc_ht_iter_first(isc_ht_iter_t *it); /*% * Set an iterator to the next entry. * * Requires: *\li 'it' is non NULL. * * Returns: * \li #ISC_R_SUCCESS -- success * \li #ISC_R_NOMORE -- end of hashtable reached */ isc_result_t isc_ht_iter_next(isc_ht_iter_t *it); /*% * Delete current entry and set an iterator to the next entry. * * Requires: *\li 'it' is non NULL. * * Returns: * \li #ISC_R_SUCCESS -- success * \li #ISC_R_NOMORE -- end of hashtable reached */ isc_result_t isc_ht_iter_delcurrent_next(isc_ht_iter_t *it); /*% * Set 'value' to the current value under the iterator * * Requires: *\li 'it' is non NULL. *\li 'valuep' is non NULL and '*valuep' is NULL. */ void isc_ht_iter_current(isc_ht_iter_t *it, void **valuep); /*% * Set 'key' and 'keysize to the current key and keysize for the value * under the iterator * * Requires: *\li 'it' is non NULL. *\li 'key' is non NULL and '*key' is NULL. *\li 'keysize' is non NULL. */ void isc_ht_iter_currentkey(isc_ht_iter_t *it, unsigned char **key, size_t *keysize); /*% * Returns the number of items in the hashtable. * * Requires: *\li 'ht' is a valid hashtable */ size_t isc_ht_count(const isc_ht_t *ht); PKֺ1]Po( bufferlist.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_BUFFERLIST_H #define ISC_BUFFERLIST_H 1 /***** ***** Module Info *****/ /*! \file isc/bufferlist.h * * *\brief Buffer lists have no synchronization. Clients must ensure exclusive * access. * * \li Reliability: * No anticipated impact. * \li Security: * No anticipated impact. * * \li Standards: * None. */ /*** *** Imports ***/ #include #include ISC_LANG_BEGINDECLS /*** *** Functions ***/ unsigned int isc_bufferlist_usedcount(isc_bufferlist_t *bl); /*!< * \brief Return the length of the sum of all used regions of all buffers in * the buffer list 'bl' * * Requires: * *\li 'bl' is not NULL. * * Returns: *\li sum of all used regions' lengths. */ unsigned int isc_bufferlist_availablecount(isc_bufferlist_t *bl); /*!< * \brief Return the length of the sum of all available regions of all buffers in * the buffer list 'bl' * * Requires: * *\li 'bl' is not NULL. * * Returns: *\li sum of all available regions' lengths. */ ISC_LANG_ENDDECLS #endif /* ISC_BUFFERLIST_H */ PKֺ1]1 meminfo.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MEMINFO_H #define ISC_MEMINFO_H 1 #include #include #include ISC_LANG_BEGINDECLS uint64_t isc_meminfo_totalphys(void); /*%< * Return total available physical memory in bytes, or 0 if this cannot * be determined */ ISC_LANG_ENDDECLS #endif /* ISC_MEMINFO_H */ PKֺ1]W< portset.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/portset.h * \brief Transport Protocol Port Manipulation Module * * This module provides simple utilities to handle a set of transport protocol * (UDP or TCP) port numbers, e.g., for creating an ACL list. An isc_portset_t * object is an opaque instance of a port set, for which the user can add or * remove a specific port or a range of consecutive ports. This object is * expected to be used as a temporary work space only, and does not protect * simultaneous access from multiple threads. Therefore it must not be stored * in a place that can be accessed from multiple threads. */ #ifndef ISC_PORTSET_H #define ISC_PORTSET_H 1 /*** *** Imports ***/ #include #include /*** *** Functions ***/ ISC_LANG_BEGINDECLS isc_result_t isc_portset_create(isc_mem_t *mctx, isc_portset_t **portsetp); /*%< * Create a port set and initialize it as an empty set. * * Requires: *\li 'mctx' to be valid. *\li 'portsetp' to be non NULL and '*portsetp' to be NULL; * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY */ void isc_portset_destroy(isc_mem_t *mctx, isc_portset_t **portsetp); /*%< * Destroy a port set. * * Requires: *\li 'mctx' to be valid and must be the same context given when the port set * was created. *\li '*portsetp' to be a valid set. */ bool isc_portset_isset(isc_portset_t *portset, in_port_t port); /*%< * Test whether the given port is stored in the portset. * * Requires: *\li 'portset' to be a valid set. * * Returns * \li #true if the port is found, false otherwise. */ unsigned int isc_portset_nports(isc_portset_t *portset); /*%< * Provides the number of ports stored in the given portset. * * Requires: *\li 'portset' to be a valid set. * * Returns * \li the number of ports stored in portset. */ void isc_portset_add(isc_portset_t *portset, in_port_t port); /*%< * Add the given port to the portset. The port may or may not be stored in * the portset. * * Requires: *\li 'portlist' to be valid. */ void isc_portset_remove(isc_portset_t *portset, in_port_t port); /*%< * Remove the given port to the portset. The port may or may not be stored in * the portset. * * Requires: *\li 'portlist' to be valid. */ void isc_portset_addrange(isc_portset_t *portset, in_port_t port_lo, in_port_t port_hi); /*%< * Add a subset of [port_lo, port_hi] (inclusive) to the portset. Ports in the * subset may or may not be stored in portset. * * Requires: *\li 'portlist' to be valid. *\li port_lo <= port_hi */ void isc_portset_removerange(isc_portset_t *portset, in_port_t port_lo, in_port_t port_hi); /*%< * Subtract a subset of [port_lo, port_hi] (inclusive) from the portset. Ports * in the subset may or may not be stored in portset. * * Requires: *\li 'portlist' to be valid. *\li port_lo <= port_hi */ ISC_LANG_ENDDECLS #endif /* ISC_PORTSET_H */ PKֺ1]s quota.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_QUOTA_H #define ISC_QUOTA_H 1 /***** ***** Module Info *****/ /*! \file isc/quota.h * * \brief The isc_quota_t object is a simple helper object for implementing * quotas on things like the number of simultaneous connections to * a server. It keeps track of the amount of quota in use, and * encapsulates the locking necessary to allow multiple tasks to * share a quota. */ /*** *** Imports. ***/ #include #include #include /***** ***** Types. *****/ ISC_LANG_BEGINDECLS /*% isc_quota structure */ struct isc_quota { isc_mutex_t lock; /*%< Locked by lock. */ int max; int used; int soft; }; isc_result_t isc_quota_init(isc_quota_t *quota, int max); /*%< * Initialize a quota object. * * Returns: * ISC_R_SUCCESS * Other error Lock creation failed. */ void isc_quota_destroy(isc_quota_t *quota); /*%< * Destroy a quota object. */ void isc_quota_soft(isc_quota_t *quota, int soft); /*%< * Set a soft quota. */ void isc_quota_max(isc_quota_t *quota, int max); /*%< * Re-set a maximum quota. */ isc_result_t isc_quota_reserve(isc_quota_t *quota); /*%< * Attempt to reserve one unit of 'quota'. * * Returns: * \li #ISC_R_SUCCESS Success * \li #ISC_R_SOFTQUOTA Success soft quota reached * \li #ISC_R_QUOTA Quota is full */ void isc_quota_release(isc_quota_t *quota); /*%< * Release one unit of quota. */ isc_result_t isc_quota_attach(isc_quota_t *quota, isc_quota_t **p); /*%< * Like isc_quota_reserve, and also attaches '*p' to the * quota if successful (ISC_R_SUCCESS or ISC_R_SOFTQUOTA). */ isc_result_t isc_quota_force(isc_quota_t *quota, isc_quota_t **p); /*%< * Like isc_quota_attach, but will attach '*p' to the quota * even if the hard quota has been exceeded. */ void isc_quota_detach(isc_quota_t **p); /*%< * Like isc_quota_release, and also detaches '*p' from the * quota. */ unsigned int isc_quota_getused(isc_quota_t *quota); /*%< * Get the current usage of quota. */ ISC_LANG_ENDDECLS #endif /* ISC_QUOTA_H */ PKֺ1]Gttm.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_TM_H #define ISC_TM_H 1 /*! \file isc/tm.h * Provides portable conversion routines for struct tm. */ #include #include #include ISC_LANG_BEGINDECLS time_t isc_tm_timegm(struct tm *tm); /* * Convert a tm structure to time_t, using UTC rather than the local * time zone. */ char * isc_tm_strptime(const char *buf, const char *fmt, struct tm *tm); /* * Parse a formatted date string into struct tm. */ ISC_LANG_ENDDECLS #endif /* ISC_TIMER_H */ PKֺ1]once.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ONCE_H #define ISC_ONCE_H 1 /*! \file */ #include #include #include typedef pthread_once_t isc_once_t; #ifdef ISC_PLATFORM_BRACEPTHREADONCEINIT /*! * This accommodates systems that define PTHRAD_ONCE_INIT improperly. */ #define ISC_ONCE_INIT { PTHREAD_ONCE_INIT } #else /*! * This is the usual case. */ #define ISC_ONCE_INIT PTHREAD_ONCE_INIT #endif /* XXX We could do fancier error handling... */ #define isc_once_do(op, f) \ ((pthread_once((op), (f)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #endif /* ISC_ONCE_H */ PKֺ1]z>>bind9.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_BIND9_H #define ISC_BIND9_H 1 #include #include /* * This determines whether we are using the libisc/libdns libraries * in BIND9 or in some other application. For BIND9 (named and related * tools) it must be set to true at runtime. Export library clients * will call isc_lib_register(), which will set it to false. */ LIBISC_EXTERNAL_DATA extern bool isc_bind9; #endif /* ISC_BIND9_H */ PKֺ1]JvRvRmem.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MEM_H #define ISC_MEM_H 1 /*! \file isc/mem.h */ #include #include #include #include #include #include #include #include ISC_LANG_BEGINDECLS #define ISC_MEM_LOWATER 0 #define ISC_MEM_HIWATER 1 typedef void (*isc_mem_water_t)(void *, int); typedef void * (*isc_memalloc_t)(void *, size_t); typedef void (*isc_memfree_t)(void *, void *); /*% * Define ISC_MEM_TRACKLINES=1 to turn on detailed tracing of memory * allocation and freeing by file and line number. */ #ifndef ISC_MEM_TRACKLINES #define ISC_MEM_TRACKLINES 1 #endif /*% * Define ISC_MEM_CHECKOVERRUN=1 to turn on checks for using memory outside * the requested space. This will increase the size of each allocation. * * If we are performing a Coverity static analysis then ISC_MEM_CHECKOVERRUN * can hide bugs that would otherwise discovered so force to zero. */ #ifdef __COVERITY__ #undef ISC_MEM_CHECKOVERRUN #define ISC_MEM_CHECKOVERRUN 0 #endif #ifndef ISC_MEM_CHECKOVERRUN #define ISC_MEM_CHECKOVERRUN 1 #endif /*% * Define ISC_MEM_FILL=1 to fill each block of memory returned to the system * with the byte string '0xbe'. This helps track down uninitialized pointers * and the like. On freeing memory, the space is filled with '0xde' for * the same reasons. * * If we are performing a Coverity static analysis then ISC_MEM_FILL * can hide bugs that would otherwise discovered so force to zero. */ #ifdef __COVERITY__ #undef ISC_MEM_FILL #define ISC_MEM_FILL 0 #endif #ifndef ISC_MEM_FILL #define ISC_MEM_FILL 1 #endif /*% * Define ISC_MEMPOOL_NAMES=1 to make memory pools store a symbolic * name so that the leaking pool can be more readily identified in * case of a memory leak. */ #ifndef ISC_MEMPOOL_NAMES #define ISC_MEMPOOL_NAMES 1 #endif LIBISC_EXTERNAL_DATA extern unsigned int isc_mem_debugging; LIBISC_EXTERNAL_DATA extern unsigned int isc_mem_defaultflags; /*@{*/ #define ISC_MEM_DEBUGTRACE 0x00000001U #define ISC_MEM_DEBUGRECORD 0x00000002U #define ISC_MEM_DEBUGUSAGE 0x00000004U #define ISC_MEM_DEBUGSIZE 0x00000008U #define ISC_MEM_DEBUGCTX 0x00000010U #define ISC_MEM_DEBUGALL 0x0000001FU /*!< * The variable isc_mem_debugging holds a set of flags for * turning certain memory debugging options on or off at * runtime. It is initialized to the value ISC_MEM_DEGBUGGING, * which is 0 by default but may be overridden at compile time. * The following flags can be specified: * * \li #ISC_MEM_DEBUGTRACE * Log each allocation and free to isc_lctx. * * \li #ISC_MEM_DEBUGRECORD * Remember each allocation, and match them up on free. * Crash if a free doesn't match an allocation. * * \li #ISC_MEM_DEBUGUSAGE * If a hi_water mark is set, print the maximum inuse memory * every time it is raised once it exceeds the hi_water mark. * * \li #ISC_MEM_DEBUGSIZE * Check the size argument being passed to isc_mem_put() matches * that passed to isc_mem_get(). * * \li #ISC_MEM_DEBUGCTX * Check the mctx argument being passed to isc_mem_put() matches * that passed to isc_mem_get(). */ /*@}*/ #if ISC_MEM_TRACKLINES #define _ISC_MEM_FILELINE , __FILE__, __LINE__ #define _ISC_MEM_FLARG , const char *, unsigned int #else #define _ISC_MEM_FILELINE #define _ISC_MEM_FLARG #endif /*! * Define ISC_MEM_USE_INTERNAL_MALLOC=1 to use the internal malloc() * implementation in preference to the system one. The internal malloc() * is very space-efficient, and quite fast on uniprocessor systems. It * performs poorly on multiprocessor machines. * JT: we can overcome the performance issue on multiprocessor machines * by carefully separating memory contexts. */ #ifndef ISC_MEM_USE_INTERNAL_MALLOC #define ISC_MEM_USE_INTERNAL_MALLOC 1 #endif /* * Flags for isc_mem_create2()calls. */ #define ISC_MEMFLAG_NOLOCK 0x00000001 /* no lock is necessary */ #define ISC_MEMFLAG_INTERNAL 0x00000002 /* use internal malloc */ #if ISC_MEM_USE_INTERNAL_MALLOC #define ISC_MEMFLAG_DEFAULT ISC_MEMFLAG_INTERNAL #else #define ISC_MEMFLAG_DEFAULT 0 #endif /*%< * We use either isc___mem (three underscores) or isc__mem (two) depending on * whether it's for BIND9's internal purpose (with -DBIND9) or generic export * library. */ #define ISCMEMFUNC(sfx) isc__mem_ ## sfx #define ISCMEMPOOLFUNC(sfx) isc__mempool_ ## sfx #define isc_mem_get(c, s) ISCMEMFUNC(get)((c), (s) _ISC_MEM_FILELINE) #define isc_mem_allocate(c, s) ISCMEMFUNC(allocate)((c), (s) _ISC_MEM_FILELINE) #define isc_mem_reallocate(c, p, s) ISCMEMFUNC(reallocate)((c), (p), (s) _ISC_MEM_FILELINE) #define isc_mem_strdup(c, p) ISCMEMFUNC(strdup)((c), (p) _ISC_MEM_FILELINE) #define isc_mempool_get(c) ISCMEMPOOLFUNC(get)((c) _ISC_MEM_FILELINE) /*% * isc_mem_putanddetach() is a convenience function for use where you * have a structure with an attached memory context. * * Given: * * \code * struct { * ... * isc_mem_t *mctx; * ... * } *ptr; * * isc_mem_t *mctx; * * isc_mem_putanddetach(&ptr->mctx, ptr, sizeof(*ptr)); * \endcode * * is the equivalent of: * * \code * mctx = NULL; * isc_mem_attach(ptr->mctx, &mctx); * isc_mem_detach(&ptr->mctx); * isc_mem_put(mctx, ptr, sizeof(*ptr)); * isc_mem_detach(&mctx); * \endcode */ /*% memory and memory pool methods */ typedef struct isc_memmethods { void (*attach)(isc_mem_t *source, isc_mem_t **targetp); void (*detach)(isc_mem_t **mctxp); void (*destroy)(isc_mem_t **mctxp); void *(*memget)(isc_mem_t *mctx, size_t size _ISC_MEM_FLARG); void (*memput)(isc_mem_t *mctx, void *ptr, size_t size _ISC_MEM_FLARG); void (*memputanddetach)(isc_mem_t **mctxp, void *ptr, size_t size _ISC_MEM_FLARG); void *(*memallocate)(isc_mem_t *mctx, size_t size _ISC_MEM_FLARG); void *(*memreallocate)(isc_mem_t *mctx, void *ptr, size_t size _ISC_MEM_FLARG); char *(*memstrdup)(isc_mem_t *mctx, const char *s _ISC_MEM_FLARG); void (*memfree)(isc_mem_t *mctx, void *ptr _ISC_MEM_FLARG); void (*setdestroycheck)(isc_mem_t *mctx, bool flag); void (*setwater)(isc_mem_t *ctx, isc_mem_water_t water, void *water_arg, size_t hiwater, size_t lowater); void (*waterack)(isc_mem_t *ctx, int flag); size_t (*inuse)(isc_mem_t *mctx); size_t (*maxinuse)(isc_mem_t *mctx); size_t (*total)(isc_mem_t *mctx); bool (*isovermem)(isc_mem_t *mctx); isc_result_t (*mpcreate)(isc_mem_t *mctx, size_t size, isc_mempool_t **mpctxp); } isc_memmethods_t; typedef struct isc_mempoolmethods { void (*destroy)(isc_mempool_t **mpctxp); void *(*get)(isc_mempool_t *mpctx _ISC_MEM_FLARG); void (*put)(isc_mempool_t *mpctx, void *mem _ISC_MEM_FLARG); unsigned int (*getallocated)(isc_mempool_t *mpctx); void (*setmaxalloc)(isc_mempool_t *mpctx, unsigned int limit); void (*setfreemax)(isc_mempool_t *mpctx, unsigned int limit); void (*setname)(isc_mempool_t *mpctx, const char *name); void (*associatelock)(isc_mempool_t *mpctx, isc_mutex_t *lock); void (*setfillcount)(isc_mempool_t *mpctx, unsigned int limit); } isc_mempoolmethods_t; /*% * This structure is actually just the common prefix of a memory context * implementation's version of an isc_mem_t. * \brief * Direct use of this structure by clients is forbidden. mctx implementations * may change the structure. 'magic' must be ISCAPI_MCTX_MAGIC for any of the * isc_mem_ routines to work. mctx implementations must maintain all mctx * invariants. */ struct isc_mem { unsigned int impmagic; unsigned int magic; isc_memmethods_t *methods; }; #define ISCAPI_MCTX_MAGIC ISC_MAGIC('A','m','c','x') #define ISCAPI_MCTX_VALID(m) ((m) != NULL && \ (m)->magic == ISCAPI_MCTX_MAGIC) /*% * This is the common prefix of a memory pool context. The same note as * that for the mem structure applies. */ struct isc_mempool { unsigned int impmagic; unsigned int magic; isc_mempoolmethods_t *methods; }; #define ISCAPI_MPOOL_MAGIC ISC_MAGIC('A','m','p','l') #define ISCAPI_MPOOL_VALID(mp) ((mp) != NULL && \ (mp)->magic == ISCAPI_MPOOL_MAGIC) #define isc_mem_put(c, p, s) \ do { \ ISCMEMFUNC(put)((c), (p), (s) _ISC_MEM_FILELINE); \ (p) = NULL; \ } while (0) #define isc_mem_putanddetach(c, p, s) \ do { \ ISCMEMFUNC(putanddetach)((c), (p), (s) _ISC_MEM_FILELINE); \ (p) = NULL; \ } while (0) #define isc_mem_free(c, p) \ do { \ ISCMEMFUNC(free)((c), (p) _ISC_MEM_FILELINE); \ (p) = NULL; \ } while (0) #define isc_mempool_put(c, p) \ do { \ ISCMEMPOOLFUNC(put)((c), (p) _ISC_MEM_FILELINE); \ (p) = NULL; \ } while (0) /*@{*/ isc_result_t isc_mem_create(size_t max_size, size_t target_size, isc_mem_t **mctxp); isc_result_t isc_mem_create2(size_t max_size, size_t target_size, isc_mem_t **mctxp, unsigned int flags); isc_result_t isc_mem_createx(size_t max_size, size_t target_size, isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg, isc_mem_t **mctxp); isc_result_t isc_mem_createx2(size_t max_size, size_t target_size, isc_memalloc_t memalloc, isc_memfree_t memfree, void *arg, isc_mem_t **mctxp, unsigned int flags); /*!< * \brief Create a memory context. * * 'max_size' and 'target_size' are tuning parameters. When * ISC_MEMFLAG_INTERNAL is set, allocations smaller than 'max_size' * will be satisfied by getting blocks of size 'target_size' from the * system allocator and breaking them up into pieces; larger allocations * will use the system allocator directly. If 'max_size' and/or * 'target_size' are zero, default values will be * used. When * ISC_MEMFLAG_INTERNAL is not set, 'target_size' is ignored. * * 'max_size' is also used to size the statistics arrays and the array * used to record active memory when ISC_MEM_DEBUGRECORD is set. Setting * 'max_size' too low can have detrimental effects on performance. * * A memory context created using isc_mem_createx() will obtain * memory from the system by calling 'memalloc' and 'memfree', * passing them the argument 'arg'. A memory context created * using isc_mem_create() will use the standard library malloc() * and free(). * * If ISC_MEMFLAG_NOLOCK is set in 'flags', the corresponding memory context * will be accessed without locking. The user who creates the context must * ensure there be no race. Since this can be a source of bug, it is generally * inadvisable to use this flag unless the user is very sure about the race * condition and the access to the object is highly performance sensitive. * * Requires: * mctxp != NULL && *mctxp == NULL */ /*@}*/ /*@{*/ void isc_mem_attach(isc_mem_t *, isc_mem_t **); void isc_mem_detach(isc_mem_t **); /*!< * \brief Attach to / detach from a memory context. * * This is intended for applications that use multiple memory contexts * in such a way that it is not obvious when the last allocations from * a given context has been freed and destroying the context is safe. * * Most applications do not need to call these functions as they can * simply create a single memory context at the beginning of main() * and destroy it at the end of main(), thereby guaranteeing that it * is not destroyed while there are outstanding allocations. */ /*@}*/ void isc_mem_destroy(isc_mem_t **); /*%< * Destroy a memory context. */ isc_result_t isc_mem_ondestroy(isc_mem_t *ctx, isc_task_t *task, isc_event_t **event); /*%< * Request to be notified with an event when a memory context has * been successfully destroyed. */ void isc_mem_stats(isc_mem_t *mctx, FILE *out); /*%< * Print memory usage statistics for 'mctx' on the stream 'out'. */ void isc_mem_setdestroycheck(isc_mem_t *mctx, bool on); /*%< * If 'on' is true, 'mctx' will check for memory leaks when * destroyed and abort the program if any are present. */ /*@{*/ void isc_mem_setquota(isc_mem_t *, size_t); size_t isc_mem_getquota(isc_mem_t *); /*%< * Set/get the memory quota of 'mctx'. This is a hard limit * on the amount of memory that may be allocated from mctx; * if it is exceeded, allocations will fail. */ /*@}*/ size_t isc_mem_inuse(isc_mem_t *mctx); /*%< * Get an estimate of the amount of memory in use in 'mctx', in bytes. * This includes quantization overhead, but does not include memory * allocated from the system but not yet used. */ size_t isc_mem_maxinuse(isc_mem_t *mctx); /*%< * Get an estimate of the largest amount of memory that has been in * use in 'mctx' at any time. */ size_t isc_mem_total(isc_mem_t *mctx); /*%< * Get the total amount of memory in 'mctx', in bytes, including memory * not yet used. */ bool isc_mem_isovermem(isc_mem_t *mctx); /*%< * Return true iff the memory context is in "over memory" state, i.e., * a hiwater mark has been set and the used amount of memory has exceeds * the mark. */ void isc_mem_setwater(isc_mem_t *mctx, isc_mem_water_t water, void *water_arg, size_t hiwater, size_t lowater); /*%< * Set high and low water marks for this memory context. * * When the memory usage of 'mctx' exceeds 'hiwater', * '(water)(water_arg, #ISC_MEM_HIWATER)' will be called. 'water' needs to * call isc_mem_waterack() with #ISC_MEM_HIWATER to acknowledge the state * change. 'water' may be called multiple times. * * When the usage drops below 'lowater', 'water' will again be called, this * time with #ISC_MEM_LOWATER. 'water' need to calls isc_mem_waterack() with * #ISC_MEM_LOWATER to acknowledge the change. * * static void * water(void *arg, int mark) { * struct foo *foo = arg; * * LOCK(&foo->marklock); * if (foo->mark != mark) { * foo->mark = mark; * .... * isc_mem_waterack(foo->mctx, mark); * } * UNLOCK(&foo->marklock); * } * * If 'water' is NULL then 'water_arg', 'hi_water' and 'lo_water' are * ignored and the state is reset. * * Requires: * * 'water' is not NULL. * hi_water >= lo_water */ void isc_mem_waterack(isc_mem_t *ctx, int mark); /*%< * Called to acknowledge changes in signaled by calls to 'water'. */ void isc_mem_printactive(isc_mem_t *mctx, FILE *file); /*%< * Print to 'file' all active memory in 'mctx'. * * Requires ISC_MEM_DEBUGRECORD to have been set. */ void isc_mem_printallactive(FILE *file); /*%< * Print to 'file' all active memory in all contexts. * * Requires ISC_MEM_DEBUGRECORD to have been set. */ void isc_mem_checkdestroyed(FILE *file); /*%< * Check that all memory contexts have been destroyed. * Prints out those that have not been. * Fatally fails if there are still active contexts. */ unsigned int isc_mem_references(isc_mem_t *ctx); /*%< * Return the current reference count. */ void isc_mem_setname(isc_mem_t *ctx, const char *name, void *tag); /*%< * Name 'ctx'. * * Notes: * *\li Only the first 15 characters of 'name' will be copied. * *\li 'tag' is for debugging purposes only. * * Requires: * *\li 'ctx' is a valid ctx. */ const char * isc_mem_getname(isc_mem_t *ctx); /*%< * Get the name of 'ctx', as previously set using isc_mem_setname(). * * Requires: *\li 'ctx' is a valid ctx. * * Returns: *\li A non-NULL pointer to a null-terminated string. * If the ctx has not been named, the string is * empty. */ void * isc_mem_gettag(isc_mem_t *ctx); /*%< * Get the tag value for 'task', as previously set using isc_mem_setname(). * * Requires: *\li 'ctx' is a valid ctx. * * Notes: *\li This function is for debugging purposes only. * * Requires: *\li 'ctx' is a valid task. */ #ifdef HAVE_LIBXML2 int isc_mem_renderxml(xmlTextWriterPtr writer); /*%< * Render all contexts' statistics and status in XML for writer. */ #endif /* HAVE_LIBXML2 */ #ifdef HAVE_JSON isc_result_t isc_mem_renderjson(json_object *memobj); /*%< * Render all contexts' statistics and status in JSON. */ #endif /* HAVE_JSON */ /* * Memory pools */ isc_result_t isc_mempool_create(isc_mem_t *mctx, size_t size, isc_mempool_t **mpctxp); /*%< * Create a memory pool. * * Requires: *\li mctx is a valid memory context. *\li size > 0 *\li mpctxp != NULL and *mpctxp == NULL * * Defaults: *\li maxalloc = UINT_MAX *\li freemax = 1 *\li fillcount = 1 * * Returns: *\li #ISC_R_NOMEMORY -- not enough memory to create pool *\li #ISC_R_SUCCESS -- all is well. */ void isc_mempool_destroy(isc_mempool_t **mpctxp); /*%< * Destroy a memory pool. * * Requires: *\li mpctxp != NULL && *mpctxp is a valid pool. *\li The pool has no un"put" allocations outstanding */ void isc_mempool_setname(isc_mempool_t *mpctx, const char *name); /*%< * Associate a name with a memory pool. At most 15 characters may be used. * * Requires: *\li mpctx is a valid pool. *\li name != NULL; */ void isc_mempool_associatelock(isc_mempool_t *mpctx, isc_mutex_t *lock); /*%< * Associate a lock with this memory pool. * * This lock is used when getting or putting items using this memory pool, * and it is also used to set or get internal state via the isc_mempool_get*() * and isc_mempool_set*() set of functions. * * Multiple pools can each share a single lock. For instance, if "manager" * type object contained pools for various sizes of events, and each of * these pools used a common lock. Note that this lock must NEVER be used * by other than mempool routines once it is given to a pool, since that can * easily cause double locking. * * Requires: * *\li mpctpx is a valid pool. * *\li lock != NULL. * *\li No previous lock is assigned to this pool. * *\li The lock is initialized before calling this function via the normal * means of doing that. */ /* * The following functions get/set various parameters. Note that due to * the unlocked nature of pools these are potentially random values unless * the imposed externally provided locking protocols are followed. * * Also note that the quota limits will not always take immediate effect. * For instance, setting "maxalloc" to a number smaller than the currently * allocated count is permitted. New allocations will be refused until * the count drops below this threshold. * * All functions require (in addition to other requirements): * mpctx is a valid memory pool */ unsigned int isc_mempool_getfreemax(isc_mempool_t *mpctx); /*%< * Returns the maximum allowed size of the free list. */ void isc_mempool_setfreemax(isc_mempool_t *mpctx, unsigned int limit); /*%< * Sets the maximum allowed size of the free list. */ unsigned int isc_mempool_getfreecount(isc_mempool_t *mpctx); /*%< * Returns current size of the free list. */ unsigned int isc_mempool_getmaxalloc(isc_mempool_t *mpctx); /*!< * Returns the maximum allowed number of allocations. */ void isc_mempool_setmaxalloc(isc_mempool_t *mpctx, unsigned int limit); /*%< * Sets the maximum allowed number of allocations. * * Additional requirements: *\li limit > 0 */ unsigned int isc_mempool_getallocated(isc_mempool_t *mpctx); /*%< * Returns the number of items allocated from this pool. */ unsigned int isc_mempool_getfillcount(isc_mempool_t *mpctx); /*%< * Returns the number of items allocated as a block from the parent memory * context when the free list is empty. */ void isc_mempool_setfillcount(isc_mempool_t *mpctx, unsigned int limit); /*%< * Sets the fillcount. * * Additional requirements: *\li limit > 0 */ /* * Pseudo-private functions for use via macros. Do not call directly. */ void * ISCMEMFUNC(get)(isc_mem_t *, size_t _ISC_MEM_FLARG); void ISCMEMFUNC(putanddetach)(isc_mem_t **, void *, size_t _ISC_MEM_FLARG); void ISCMEMFUNC(put)(isc_mem_t *, void *, size_t _ISC_MEM_FLARG); void * ISCMEMFUNC(allocate)(isc_mem_t *, size_t _ISC_MEM_FLARG); void * ISCMEMFUNC(reallocate)(isc_mem_t *, void *, size_t _ISC_MEM_FLARG); void ISCMEMFUNC(free)(isc_mem_t *, void * _ISC_MEM_FLARG); char * ISCMEMFUNC(strdup)(isc_mem_t *, const char *_ISC_MEM_FLARG); void * ISCMEMPOOLFUNC(get)(isc_mempool_t * _ISC_MEM_FLARG); void ISCMEMPOOLFUNC(put)(isc_mempool_t *, void * _ISC_MEM_FLARG); /*%< * See isc_mem_create2() above. */ typedef isc_result_t (*isc_memcreatefunc_t)(size_t init_max_size, size_t target_size, isc_mem_t **ctxp, unsigned int flags); isc_result_t isc_mem_register(isc_memcreatefunc_t createfunc); /*%< * Register a new memory management implementation and add it to the list of * supported implementations. This function must be called when a different * memory management library is used than the one contained in the ISC library. */ isc_result_t isc__mem_register(void); /*%< * A short cut function that specifies the memory management module in the ISC * library for isc_mem_register(). An application that uses the ISC library * usually do not have to care about this function: it would call * isc_lib_register(), which internally calls this function. */ ISC_LANG_ENDDECLS #endif /* ISC_MEM_H */ PKֺ1]E=stdlib.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STDLIB_H #define ISC_STDLIB_H 1 /*! \file isc/stdlib.h */ #include #include #include #ifdef ISC_PLATFORM_NEEDSTRTOUL #define strtoul isc_strtoul #endif ISC_LANG_BEGINDECLS unsigned long isc_strtoul(const char *, char **, int); ISC_LANG_ENDDECLS #endif PKֺ1]"os.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_OS_H #define ISC_OS_H 1 /*! \file isc/os.h */ #include ISC_LANG_BEGINDECLS unsigned int isc_os_ncpus(void); /*%< * Return the number of CPUs available on the system, or 1 if this cannot * be determined. */ ISC_LANG_ENDDECLS #endif /* ISC_OS_H */ PKֺ1] __ mutexblock.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MUTEXBLOCK_H #define ISC_MUTEXBLOCK_H 1 /*! \file isc/mutexblock.h */ #include #include #include ISC_LANG_BEGINDECLS isc_result_t isc_mutexblock_init(isc_mutex_t *block, unsigned int count); /*%< * Initialize a block of locks. If an error occurs all initialized locks * will be destroyed, if possible. * * Requires: * *\li block != NULL * *\li count > 0 * * Returns: * *\li Any code isc_mutex_init() can return is a valid return for this * function. */ isc_result_t isc_mutexblock_destroy(isc_mutex_t *block, unsigned int count); /*%< * Destroy a block of locks. * * Requires: * *\li block != NULL * *\li count > 0 * *\li Each lock in the block be initialized via isc_mutex_init() or * the whole block was initialized via isc_mutex_initblock(). * * Returns: * *\li Any code isc_mutex_init() can return is a valid return for this * function. */ ISC_LANG_ENDDECLS #endif /* ISC_MUTEXBLOCK_H */ PKֺ1]Ќ. hmacmd5.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/hmacmd5.h * \brief This is the header file for the HMAC-MD5 keyed hash algorithm * described in RFC2104. */ #ifndef ISC_HMACMD5_H #define ISC_HMACMD5_H 1 #include #ifndef PK11_MD5_DISABLE #include #include #include #include #include #define ISC_HMACMD5_KEYLENGTH 64 #ifdef ISC_PLATFORM_OPENSSLHASH #include #include typedef struct { HMAC_CTX *ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) HMAC_CTX _ctx; #endif } isc_hmacmd5_t; #elif PKCS11CRYPTO #include typedef pk11_context_t isc_hmacmd5_t; #else typedef struct { isc_md5_t md5ctx; unsigned char key[ISC_HMACMD5_KEYLENGTH]; } isc_hmacmd5_t; #endif ISC_LANG_BEGINDECLS void isc_hmacmd5_init(isc_hmacmd5_t *ctx, const unsigned char *key, unsigned int len); void isc_hmacmd5_invalidate(isc_hmacmd5_t *ctx); void isc_hmacmd5_update(isc_hmacmd5_t *ctx, const unsigned char *buf, unsigned int len); void isc_hmacmd5_sign(isc_hmacmd5_t *ctx, unsigned char *digest); bool isc_hmacmd5_verify(isc_hmacmd5_t *ctx, unsigned char *digest); bool isc_hmacmd5_verify2(isc_hmacmd5_t *ctx, unsigned char *digest, size_t len); bool isc_hmacmd5_check(int testing); ISC_LANG_ENDDECLS #endif /* !PK11_MD5_DISABLE */ #endif /* ISC_HMACMD5_H */ PKֺ1]& oo deprecated.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_DEPRECATED_H #define ISC_DEPRECATED_H #if (__GNUC__ + 0) > 3 #define ISC_DEPRECATED __attribute__((deprecated)) #else #define ISC_DEPRECATED /* none */ #endif /* __GNUC__ > 3*/ #endif PKֺ1]y condition.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_CONDITION_H #define ISC_CONDITION_H 1 /*! \file */ #include #include #include #include typedef pthread_cond_t isc_condition_t; #define isc_condition_init(cp) \ ((pthread_cond_init((cp), NULL) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #if ISC_MUTEX_PROFILE #define isc_condition_wait(cp, mp) \ ((pthread_cond_wait((cp), &((mp)->mutex)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #else #define isc_condition_wait(cp, mp) \ ((pthread_cond_wait((cp), (mp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #endif #define isc_condition_signal(cp) \ ((pthread_cond_signal((cp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #define isc_condition_broadcast(cp) \ ((pthread_cond_broadcast((cp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) #define isc_condition_destroy(cp) \ ((pthread_cond_destroy((cp)) == 0) ? \ ISC_R_SUCCESS : ISC_R_UNEXPECTED) ISC_LANG_BEGINDECLS isc_result_t isc_condition_waituntil(isc_condition_t *, isc_mutex_t *, isc_time_t *); ISC_LANG_ENDDECLS #endif /* ISC_CONDITION_H */ PKֺ1]ׇL L md5.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/md5.h * \brief This is the header file for the MD5 message-digest algorithm. * * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. * * Changed so as no longer to depend on Colin Plumb's `usual.h' * header definitions; now uses stuff from dpkg's config.h * - Ian Jackson . * Still in the public domain. */ #ifndef ISC_MD5_H #define ISC_MD5_H 1 #include #ifndef PK11_MD5_DISABLE #include #include #include #include #define ISC_MD5_DIGESTLENGTH 16U #define ISC_MD5_BLOCK_LENGTH 64U #ifdef ISC_PLATFORM_OPENSSLHASH #include #include typedef struct { EVP_MD_CTX *ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) EVP_MD_CTX _ctx; #endif } isc_md5_t; #elif PKCS11CRYPTO #include typedef pk11_context_t isc_md5_t; #else typedef struct { uint32_t buf[4]; uint32_t bytes[2]; uint32_t in[16]; } isc_md5_t; #endif ISC_LANG_BEGINDECLS void isc_md5_init(isc_md5_t *ctx); void isc_md5_invalidate(isc_md5_t *ctx); void isc_md5_update(isc_md5_t *ctx, const unsigned char *buf, unsigned int len); void isc_md5_final(isc_md5_t *ctx, unsigned char *digest); bool isc_md5_check(bool testing); bool isc_md5_available(void); ISC_LANG_ENDDECLS #endif /* !PK11_MD5_DISABLE */ #endif /* ISC_MD5_H */ PKֺ1]5eebase32.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_BASE32_H #define ISC_BASE32_H 1 /*! \file */ /* * Routines for manipulating base 32 and base 32 hex encoded data. * Based on RFC 4648. * * Base 32 hex preserves the sort order of data when it is encoded / * decoded. * * Base 32 hex "np" is base 32 hex but no padding is produced or accepted. */ #include #include ISC_LANG_BEGINDECLS /*** *** Functions ***/ isc_result_t isc_base32_totext(isc_region_t *source, int wordlength, const char *wordbreak, isc_buffer_t *target); isc_result_t isc_base32hex_totext(isc_region_t *source, int wordlength, const char *wordbreak, isc_buffer_t *target); isc_result_t isc_base32hexnp_totext(isc_region_t *source, int wordlength, const char *wordbreak, isc_buffer_t *target); /*!< * \brief Convert data into base32 encoded text. * * Notes: *\li The base32 encoded text in 'target' will be divided into * words of at most 'wordlength' characters, separated by * the 'wordbreak' string. No parentheses will surround * the text. * * Requires: *\li 'source' is a region containing binary data *\li 'target' is a text buffer containing available space *\li 'wordbreak' points to a null-terminated string of * zero or more whitespace characters * * Ensures: *\li target will contain the base32 encoded version of the data * in source. The 'used' pointer in target will be advanced as * necessary. */ isc_result_t isc_base32_decodestring(const char *cstr, isc_buffer_t *target); isc_result_t isc_base32hex_decodestring(const char *cstr, isc_buffer_t *target); isc_result_t isc_base32hexnp_decodestring(const char *cstr, isc_buffer_t *target); /*!< * \brief Decode a null-terminated string in base32, base32hex, or * base32hex non-padded. * * Requires: *\li 'cstr' is non-null. *\li 'target' is a valid buffer. * * Returns: *\li #ISC_R_SUCCESS -- the entire decoded representation of 'cstring' * fit in 'target'. *\li #ISC_R_BADBASE32 -- 'cstr' is not a valid base32 encoding. * * Other error returns are any possible error code from: *\li isc_lex_create(), *\li isc_lex_openbuffer(), *\li isc_base32_tobuffer(). */ isc_result_t isc_base32_tobuffer(isc_lex_t *lexer, isc_buffer_t *target, int length); isc_result_t isc_base32hex_tobuffer(isc_lex_t *lexer, isc_buffer_t *target, int length); isc_result_t isc_base32hexnp_tobuffer(isc_lex_t *lexer, isc_buffer_t *target, int length); /*!< * \brief Convert text encoded in base32, base32hex, or base32hex * non-padded from a lexer context into `target`. If 'length' is * non-negative, it is the expected number of encoded octets to convert. * * If 'length' is -1 then 0 or more encoded octets are expected. * If 'length' is -2 then 1 or more encoded octets are expected. * * Returns: *\li #ISC_R_BADBASE32 -- invalid base32 encoding. *\li #ISC_R_UNEXPECTEDEND: the text does not contain the expected * number of encoded octets. * * Requires: *\li 'lexer' is a valid lexer context *\li 'target' is a buffer containing binary data *\li 'length' is -2, -1, or non-negative * * Ensures: *\li target will contain the data represented by the base32 encoded * string parsed by the lexer. No more than `length` octets will * be read, if `length` is non-negative. The 'used' pointer in * 'target' will be advanced as necessary. */ isc_result_t isc_base32_decoderegion(isc_region_t *source, isc_buffer_t *target); isc_result_t isc_base32hex_decoderegion(isc_region_t *source, isc_buffer_t *target); isc_result_t isc_base32hexnp_decoderegion(isc_region_t *source, isc_buffer_t *target); /*!< * \brief Decode a packed (no white space permitted) region in * base32, base32hex or base32hex non-padded. * * Requires: *\li 'source' is a valid region. *\li 'target' is a valid buffer. * * Returns: *\li #ISC_R_SUCCESS -- the entire decoded representation of 'cstring' * fit in 'target'. *\li #ISC_R_BADBASE32 -- 'source' is not a valid base32 encoding. */ ISC_LANG_ENDDECLS #endif /* ISC_BASE32_H */ PKֺ1]K counter.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_COUNTER_H #define ISC_COUNTER_H 1 /***** ***** Module Info *****/ /*! \file isc/counter.h * * \brief The isc_counter_t object is a simplified version of the * isc_quota_t object; it tracks the consumption of limited * resources, returning an error condition when the quota is * exceeded. However, unlike isc_quota_t, attaching and detaching * from a counter object does not increment or decrement the counter. */ /*** *** Imports. ***/ #include #include #include /***** ***** Types. *****/ ISC_LANG_BEGINDECLS isc_result_t isc_counter_create(isc_mem_t *mctx, int limit, isc_counter_t **counterp); /*%< * Allocate and initialize a counter object. */ isc_result_t isc_counter_increment(isc_counter_t *counter); /*%< * Increment the counter. * * If the counter limit is nonzero and has been reached, then * return ISC_R_QUOTA, otherwise ISC_R_SUCCESS. (The counter is * incremented regardless of return value.) */ unsigned int isc_counter_used(isc_counter_t *counter); /*%< * Return the current counter value. */ void isc_counter_setlimit(isc_counter_t *counter, int limit); /*%< * Set the counter limit. */ void isc_counter_attach(isc_counter_t *source, isc_counter_t **targetp); /*%< * Attach to a counter object, increasing its reference counter. */ void isc_counter_detach(isc_counter_t **counterp); /*%< * Detach (and destroy if reference counter has dropped to zero) * a counter object. */ ISC_LANG_ENDDECLS #endif /* ISC_COUNTER_H */ PKֺ1]cYӱ version.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/version.h */ #include LIBISC_EXTERNAL_DATA extern const char isc_version[]; LIBISC_EXTERNAL_DATA extern const unsigned int isc_libinterface; LIBISC_EXTERNAL_DATA extern const unsigned int isc_librevision; LIBISC_EXTERNAL_DATA extern const unsigned int isc_libage; PKֺ1]ß hmacsha.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/hmacsha.h * This is the header file for the HMAC-SHA1, HMAC-SHA224, HMAC-SHA256, * HMAC-SHA334 and HMAC-SHA512 hash algorithm described in RFC 2104. */ #ifndef ISC_HMACSHA_H #define ISC_HMACSHA_H 1 #include #include #include #include #include #include #define ISC_HMACSHA1_KEYLENGTH ISC_SHA1_BLOCK_LENGTH #define ISC_HMACSHA224_KEYLENGTH ISC_SHA224_BLOCK_LENGTH #define ISC_HMACSHA256_KEYLENGTH ISC_SHA256_BLOCK_LENGTH #define ISC_HMACSHA384_KEYLENGTH ISC_SHA384_BLOCK_LENGTH #define ISC_HMACSHA512_KEYLENGTH ISC_SHA512_BLOCK_LENGTH #ifdef ISC_PLATFORM_OPENSSLHASH #include #include typedef struct { HMAC_CTX *ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) HMAC_CTX _ctx; #endif } isc_hmacsha_t; typedef isc_hmacsha_t isc_hmacsha1_t; typedef isc_hmacsha_t isc_hmacsha224_t; typedef isc_hmacsha_t isc_hmacsha256_t; typedef isc_hmacsha_t isc_hmacsha384_t; typedef isc_hmacsha_t isc_hmacsha512_t; #elif PKCS11CRYPTO #include typedef pk11_context_t isc_hmacsha1_t; typedef pk11_context_t isc_hmacsha224_t; typedef pk11_context_t isc_hmacsha256_t; typedef pk11_context_t isc_hmacsha384_t; typedef pk11_context_t isc_hmacsha512_t; #else typedef struct { isc_sha1_t sha1ctx; unsigned char key[ISC_HMACSHA1_KEYLENGTH]; } isc_hmacsha1_t; typedef struct { isc_sha224_t sha224ctx; unsigned char key[ISC_HMACSHA224_KEYLENGTH]; } isc_hmacsha224_t; typedef struct { isc_sha256_t sha256ctx; unsigned char key[ISC_HMACSHA256_KEYLENGTH]; } isc_hmacsha256_t; typedef struct { isc_sha384_t sha384ctx; unsigned char key[ISC_HMACSHA384_KEYLENGTH]; } isc_hmacsha384_t; typedef struct { isc_sha512_t sha512ctx; unsigned char key[ISC_HMACSHA512_KEYLENGTH]; } isc_hmacsha512_t; #endif ISC_LANG_BEGINDECLS void isc_hmacsha1_init(isc_hmacsha1_t *ctx, const unsigned char *key, unsigned int len); void isc_hmacsha1_invalidate(isc_hmacsha1_t *ctx); void isc_hmacsha1_update(isc_hmacsha1_t *ctx, const unsigned char *buf, unsigned int len); void isc_hmacsha1_sign(isc_hmacsha1_t *ctx, unsigned char *digest, size_t len); bool isc_hmacsha1_verify(isc_hmacsha1_t *ctx, unsigned char *digest, size_t len); bool isc_hmacsha1_check(int testing); void isc_hmacsha224_init(isc_hmacsha224_t *ctx, const unsigned char *key, unsigned int len); void isc_hmacsha224_invalidate(isc_hmacsha224_t *ctx); void isc_hmacsha224_update(isc_hmacsha224_t *ctx, const unsigned char *buf, unsigned int len); void isc_hmacsha224_sign(isc_hmacsha224_t *ctx, unsigned char *digest, size_t len); bool isc_hmacsha224_verify(isc_hmacsha224_t *ctx, unsigned char *digest, size_t len); void isc_hmacsha256_init(isc_hmacsha256_t *ctx, const unsigned char *key, unsigned int len); void isc_hmacsha256_invalidate(isc_hmacsha256_t *ctx); void isc_hmacsha256_update(isc_hmacsha256_t *ctx, const unsigned char *buf, unsigned int len); void isc_hmacsha256_sign(isc_hmacsha256_t *ctx, unsigned char *digest, size_t len); bool isc_hmacsha256_verify(isc_hmacsha256_t *ctx, unsigned char *digest, size_t len); void isc_hmacsha384_init(isc_hmacsha384_t *ctx, const unsigned char *key, unsigned int len); void isc_hmacsha384_invalidate(isc_hmacsha384_t *ctx); void isc_hmacsha384_update(isc_hmacsha384_t *ctx, const unsigned char *buf, unsigned int len); void isc_hmacsha384_sign(isc_hmacsha384_t *ctx, unsigned char *digest, size_t len); bool isc_hmacsha384_verify(isc_hmacsha384_t *ctx, unsigned char *digest, size_t len); void isc_hmacsha512_init(isc_hmacsha512_t *ctx, const unsigned char *key, unsigned int len); void isc_hmacsha512_invalidate(isc_hmacsha512_t *ctx); void isc_hmacsha512_update(isc_hmacsha512_t *ctx, const unsigned char *buf, unsigned int len); void isc_hmacsha512_sign(isc_hmacsha512_t *ctx, unsigned char *digest, size_t len); bool isc_hmacsha512_verify(isc_hmacsha512_t *ctx, unsigned char *digest, size_t len); ISC_LANG_ENDDECLS #endif /* ISC_HMACSHA_H */ PKֺ1]Տ%sha1.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SHA1_H #define ISC_SHA1_H 1 /* $NetBSD: sha1.h,v 1.2 1998/05/29 22:55:44 thorpej Exp $ */ /*! \file isc/sha1.h * \brief SHA-1 in C * \author By Steve Reid * \note 100% Public Domain */ #include #include #include #include #define ISC_SHA1_DIGESTLENGTH 20U #define ISC_SHA1_BLOCK_LENGTH 64U #ifdef ISC_PLATFORM_OPENSSLHASH #include #include typedef struct { EVP_MD_CTX *ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) EVP_MD_CTX _ctx; #endif } isc_sha1_t; #elif PKCS11CRYPTO #include typedef pk11_context_t isc_sha1_t; #else typedef struct { uint32_t state[5]; uint32_t count[2]; unsigned char buffer[ISC_SHA1_BLOCK_LENGTH]; } isc_sha1_t; #endif ISC_LANG_BEGINDECLS void isc_sha1_init(isc_sha1_t *ctx); void isc_sha1_invalidate(isc_sha1_t *ctx); void isc_sha1_update(isc_sha1_t *ctx, const unsigned char *data, unsigned int len); void isc_sha1_final(isc_sha1_t *ctx, unsigned char *digest); bool isc_sha1_check(bool testing); ISC_LANG_ENDDECLS #endif /* ISC_SHA1_H */ PKֺ1]a<5 msgcat.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MSGCAT_H #define ISC_MSGCAT_H 1 /***** ***** Module Info *****/ /*! \file isc/msgcat.h * \brief The ISC Message Catalog * aids internationalization of applications by allowing * messages to be retrieved from locale-specific files instead of * hardwiring them into the application. This allows translations of * messages appropriate to the locale to be supplied without recompiling * the application. * * Notes: *\li It's very important that message catalogs work, even if only the * default_text can be used. * * MP: *\li The caller must ensure appropriate synchronization of * isc_msgcat_open() and isc_msgcat_close(). isc_msgcat_get() * ensures appropriate synchronization. * * Reliability: *\li No anticipated impact. * * Resources: *\li TBS * * \li Security: * No anticipated impact. * * \li Standards: * None. */ /***** ***** Imports *****/ #include #include ISC_LANG_BEGINDECLS /***** ***** Methods *****/ void isc_msgcat_open(const char *name, isc_msgcat_t **msgcatp); /*%< * Open a message catalog. * * Notes: * *\li If memory cannot be allocated or other failures occur, *msgcatp * will be set to NULL. If a NULL msgcat is given to isc_msgcat_get(), * the default_text will be returned, ensuring that some message text * will be available, no matter what's going wrong. * * Requires: * *\li 'name' is a valid string. * *\li msgcatp != NULL && *msgcatp == NULL */ void isc_msgcat_close(isc_msgcat_t **msgcatp); /*%< * Close a message catalog. * * Notes: * *\li Any string pointers returned by prior calls to isc_msgcat_get() are * invalid after isc_msgcat_close() has been called and must not be * used. * * Requires: * *\li *msgcatp is a valid message catalog or is NULL. * * Ensures: * *\li All resources associated with the message catalog are released. * *\li *msgcatp == NULL */ const char * isc_msgcat_get(isc_msgcat_t *msgcat, int set, int message, const char *default_text); /*%< * Get message 'message' from message set 'set' in 'msgcat'. If it * is not available, use 'default_text'. * * Requires: * *\li 'msgcat' is a valid message catalog or is NULL. * *\li set > 0 * *\li message > 0 * *\li 'default_text' is a valid string. */ ISC_LANG_ENDDECLS #endif /* ISC_MSGCAT_H */ PKֺ1]I+ event.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_EVENT_H #define ISC_EVENT_H 1 /*! \file isc/event.h */ #include #include /***** ***** Events. *****/ typedef void (*isc_eventdestructor_t)(isc_event_t *); #define ISC_EVENT_COMMON(ltype) \ size_t ev_size; \ unsigned int ev_attributes; \ void * ev_tag; \ isc_eventtype_t ev_type; \ isc_taskaction_t ev_action; \ void * ev_arg; \ void * ev_sender; \ isc_eventdestructor_t ev_destroy; \ void * ev_destroy_arg; \ ISC_LINK(ltype) ev_link; \ ISC_LINK(ltype) ev_ratelink /*% * Attributes matching a mask of 0x000000ff are reserved for the task library's * definition. Attributes of 0xffffff00 may be used by the application * or non-ISC libraries. */ #define ISC_EVENTATTR_NOPURGE 0x00000001 /*% * The ISC_EVENTATTR_CANCELED attribute is intended to indicate * that an event is delivered as a result of a canceled operation * rather than successful completion, by mutual agreement * between the sender and receiver. It is not set or used by * the task system. */ #define ISC_EVENTATTR_CANCELED 0x00000002 #define ISC_EVENT_INIT(event, sz, at, ta, ty, ac, ar, sn, df, da) \ do { \ (event)->ev_size = (sz); \ (event)->ev_attributes = (at); \ (event)->ev_tag = (ta); \ (event)->ev_type = (ty); \ (event)->ev_action = (ac); \ (event)->ev_arg = (ar); \ (event)->ev_sender = (sn); \ (event)->ev_destroy = (df); \ (event)->ev_destroy_arg = (da); \ ISC_LINK_INIT((event), ev_link); \ ISC_LINK_INIT((event), ev_ratelink); \ } while (0) /*% * This structure is public because "subclassing" it may be useful when * defining new event types. */ struct isc_event { ISC_EVENT_COMMON(struct isc_event); }; #define ISC_EVENTTYPE_FIRSTEVENT 0x00000000 #define ISC_EVENTTYPE_LASTEVENT 0xffffffff #define ISC_EVENT_PTR(p) ((isc_event_t **)(void *)(p)) ISC_LANG_BEGINDECLS isc_event_t * isc_event_allocate(isc_mem_t *mctx, void *sender, isc_eventtype_t type, isc_taskaction_t action, void *arg, size_t size); isc_event_t * isc_event_constallocate(isc_mem_t *mctx, void *sender, isc_eventtype_t type, isc_taskaction_t action, const void *arg, size_t size); /*%< * Allocate an event structure. * * Allocate and initialize in a structure with initial elements * defined by: * * \code * struct { * ISC_EVENT_COMMON(struct isc_event); * ... * }; * \endcode * * Requires: *\li 'size' >= sizeof(struct isc_event) *\li 'action' to be non NULL * * Returns: *\li a pointer to a initialized structure of the requested size. *\li NULL if unable to allocate memory. */ void isc_event_free(isc_event_t **); ISC_LANG_ENDDECLS #endif /* ISC_EVENT_H */ PKֺ1]6H ratelimiter.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_RATELIMITER_H #define ISC_RATELIMITER_H 1 /***** ***** Module Info *****/ /*! \file isc/ratelimiter.h * \brief A rate limiter is a mechanism for dispatching events at a limited * rate. This is intended to be used when sending zone maintenance * SOA queries, NOTIFY messages, etc. */ /*** *** Imports. ***/ #include #include #include #include ISC_LANG_BEGINDECLS /***** ***** Functions. *****/ isc_result_t isc_ratelimiter_create(isc_mem_t *mctx, isc_timermgr_t *timermgr, isc_task_t *task, isc_ratelimiter_t **ratelimiterp); /*%< * Create a rate limiter. The execution interval is initially undefined. */ isc_result_t isc_ratelimiter_setinterval(isc_ratelimiter_t *rl, isc_interval_t *interval); /*!< * Set the minimum interval between event executions. * The interval value is copied, so the caller need not preserve it. * * Requires: * '*interval' is a nonzero interval. */ void isc_ratelimiter_setpertic(isc_ratelimiter_t *rl, uint32_t perint); /*%< * Set the number of events processed per interval timer tick. * If 'perint' is zero it is treated as 1. */ void isc_ratelimiter_setpushpop(isc_ratelimiter_t *rl, bool pushpop); /*%< * Set / clear the ratelimiter to from push pop mode rather * first in - first out mode (default). */ isc_result_t isc_ratelimiter_enqueue(isc_ratelimiter_t *rl, isc_task_t *task, isc_event_t **eventp); /*%< * Queue an event for rate-limited execution. * * This is similar * to doing an isc_task_send() to the 'task', except that the * execution may be delayed to achieve the desired rate of * execution. * * '(*eventp)->ev_sender' is used to hold the task. The caller * must ensure that the task exists until the event is delivered. * * Requires: *\li An interval has been set by calling * isc_ratelimiter_setinterval(). * *\li 'task' to be non NULL. *\li '(*eventp)->ev_sender' to be NULL. */ isc_result_t isc_ratelimiter_dequeue(isc_ratelimiter_t *rl, isc_event_t *event); /* * Dequeue a event off the ratelimiter queue. * * Returns: * \li ISC_R_NOTFOUND if the event is no longer linked to the rate limiter. * \li ISC_R_SUCCESS */ void isc_ratelimiter_shutdown(isc_ratelimiter_t *ratelimiter); /*%< * Shut down a rate limiter. * * Ensures: *\li All events that have not yet been * dispatched to the task are dispatched immediately with * the #ISC_EVENTATTR_CANCELED bit set in ev_attributes. * *\li Further attempts to enqueue events will fail with * #ISC_R_SHUTTINGDOWN. * *\li The rate limiter is no longer attached to its task. */ void isc_ratelimiter_attach(isc_ratelimiter_t *source, isc_ratelimiter_t **target); /*%< * Attach to a rate limiter. */ void isc_ratelimiter_detach(isc_ratelimiter_t **ratelimiterp); /*%< * Detach from a rate limiter. */ isc_result_t isc_ratelimiter_stall(isc_ratelimiter_t *rl); /*%< * Stall event processing. */ isc_result_t isc_ratelimiter_release(isc_ratelimiter_t *rl); /*%< * Release a stalled rate limiter. */ ISC_LANG_ENDDECLS #endif /* ISC_RATELIMITER_H */ PKֺ1]hwwlist.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LIST_H #define ISC_LIST_H 1 #include #ifdef ISC_LIST_CHECKINIT #define ISC_LINK_INSIST(x) ISC_INSIST(x) #else #define ISC_LINK_INSIST(x) #endif #define ISC_LIST(type) struct { type *head, *tail; } #define ISC_LIST_INIT(list) \ do { (list).head = NULL; (list).tail = NULL; } while (0) #define ISC_LINK(type) struct { type *prev, *next; } #define ISC_LINK_INIT_TYPE(elt, link, type) \ do { \ (elt)->link.prev = (type *)(-1); \ (elt)->link.next = (type *)(-1); \ } while (0) #define ISC_LINK_INIT(elt, link) \ ISC_LINK_INIT_TYPE(elt, link, void) #define ISC_LINK_LINKED(elt, link) ((void *)((elt)->link.prev) != (void *)(-1)) #define ISC_LIST_HEAD(list) ((list).head) #define ISC_LIST_TAIL(list) ((list).tail) #define ISC_LIST_EMPTY(list) ((list).head == NULL) #define __ISC_LIST_PREPENDUNSAFE(list, elt, link) \ do { \ if ((list).head != NULL) \ (list).head->link.prev = (elt); \ else \ (list).tail = (elt); \ (elt)->link.prev = NULL; \ (elt)->link.next = (list).head; \ (list).head = (elt); \ } while (0) #define ISC_LIST_PREPEND(list, elt, link) \ do { \ ISC_LINK_INSIST(!ISC_LINK_LINKED(elt, link)); \ __ISC_LIST_PREPENDUNSAFE(list, elt, link); \ } while (0) #define ISC_LIST_INITANDPREPEND(list, elt, link) \ __ISC_LIST_PREPENDUNSAFE(list, elt, link) #define __ISC_LIST_APPENDUNSAFE(list, elt, link) \ do { \ if ((list).tail != NULL) \ (list).tail->link.next = (elt); \ else \ (list).head = (elt); \ (elt)->link.prev = (list).tail; \ (elt)->link.next = NULL; \ (list).tail = (elt); \ } while (0) #define ISC_LIST_APPEND(list, elt, link) \ do { \ ISC_LINK_INSIST(!ISC_LINK_LINKED(elt, link)); \ __ISC_LIST_APPENDUNSAFE(list, elt, link); \ } while (0) #define ISC_LIST_INITANDAPPEND(list, elt, link) \ __ISC_LIST_APPENDUNSAFE(list, elt, link) #define __ISC_LIST_UNLINKUNSAFE_TYPE(list, elt, link, type) \ do { \ if ((elt)->link.next != NULL) \ (elt)->link.next->link.prev = (elt)->link.prev; \ else { \ ISC_INSIST((list).tail == (elt)); \ (list).tail = (elt)->link.prev; \ } \ if ((elt)->link.prev != NULL) \ (elt)->link.prev->link.next = (elt)->link.next; \ else { \ ISC_INSIST((list).head == (elt)); \ (list).head = (elt)->link.next; \ } \ (elt)->link.prev = (type *)(-1); \ (elt)->link.next = (type *)(-1); \ ISC_INSIST((list).head != (elt)); \ ISC_INSIST((list).tail != (elt)); \ } while (0) #define __ISC_LIST_UNLINKUNSAFE(list, elt, link) \ __ISC_LIST_UNLINKUNSAFE_TYPE(list, elt, link, void) #define ISC_LIST_UNLINK_TYPE(list, elt, link, type) \ do { \ ISC_LINK_INSIST(ISC_LINK_LINKED(elt, link)); \ __ISC_LIST_UNLINKUNSAFE_TYPE(list, elt, link, type); \ } while (0) #define ISC_LIST_UNLINK(list, elt, link) \ ISC_LIST_UNLINK_TYPE(list, elt, link, void) #define ISC_LIST_PREV(elt, link) ((elt)->link.prev) #define ISC_LIST_NEXT(elt, link) ((elt)->link.next) #define __ISC_LIST_INSERTBEFOREUNSAFE(list, before, elt, link) \ do { \ if ((before)->link.prev == NULL) \ ISC_LIST_PREPEND(list, elt, link); \ else { \ (elt)->link.prev = (before)->link.prev; \ (before)->link.prev = (elt); \ (elt)->link.prev->link.next = (elt); \ (elt)->link.next = (before); \ } \ } while (0) #define ISC_LIST_INSERTBEFORE(list, before, elt, link) \ do { \ ISC_LINK_INSIST(ISC_LINK_LINKED(before, link)); \ ISC_LINK_INSIST(!ISC_LINK_LINKED(elt, link)); \ __ISC_LIST_INSERTBEFOREUNSAFE(list, before, elt, link); \ } while (0) #define __ISC_LIST_INSERTAFTERUNSAFE(list, after, elt, link) \ do { \ if ((after)->link.next == NULL) \ ISC_LIST_APPEND(list, elt, link); \ else { \ (elt)->link.next = (after)->link.next; \ (after)->link.next = (elt); \ (elt)->link.next->link.prev = (elt); \ (elt)->link.prev = (after); \ } \ } while (0) #define ISC_LIST_INSERTAFTER(list, after, elt, link) \ do { \ ISC_LINK_INSIST(ISC_LINK_LINKED(after, link)); \ ISC_LINK_INSIST(!ISC_LINK_LINKED(elt, link)); \ __ISC_LIST_INSERTAFTERUNSAFE(list, after, elt, link); \ } while (0) #define ISC_LIST_APPENDLIST(list1, list2, link) \ do { \ if (ISC_LIST_EMPTY(list1)) \ (list1) = (list2); \ else if (!ISC_LIST_EMPTY(list2)) { \ (list1).tail->link.next = (list2).head; \ (list2).head->link.prev = (list1).tail; \ (list1).tail = (list2).tail; \ } \ (list2).head = NULL; \ (list2).tail = NULL; \ } while (0) #define ISC_LIST_PREPENDLIST(list1, list2, link) \ do { \ if (ISC_LIST_EMPTY(list1)) \ (list1) = (list2); \ else if (!ISC_LIST_EMPTY(list2)) { \ (list2).tail->link.next = (list1).head; \ (list1).head->link.prev = (list2).tail; \ (list1).head = (list2).head; \ } \ (list2).head = NULL; \ (list2).tail = NULL; \ } while (0) #define ISC_LIST_ENQUEUE(list, elt, link) ISC_LIST_APPEND(list, elt, link) #define __ISC_LIST_ENQUEUEUNSAFE(list, elt, link) \ __ISC_LIST_APPENDUNSAFE(list, elt, link) #define ISC_LIST_DEQUEUE(list, elt, link) \ ISC_LIST_UNLINK_TYPE(list, elt, link, void) #define ISC_LIST_DEQUEUE_TYPE(list, elt, link, type) \ ISC_LIST_UNLINK_TYPE(list, elt, link, type) #define __ISC_LIST_DEQUEUEUNSAFE(list, elt, link) \ __ISC_LIST_UNLINKUNSAFE_TYPE(list, elt, link, void) #define __ISC_LIST_DEQUEUEUNSAFE_TYPE(list, elt, link, type) \ __ISC_LIST_UNLINKUNSAFE_TYPE(list, elt, link, type) #endif /* ISC_LIST_H */ PKֺ1]pggcmocka.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/cmocka.h */ #pragma once #include #include ISC_LANG_BEGINDECLS /* * Copy the test identified by 'name' from 'tests' to 'selected'. */ #define cmocka_add_test_byname(tests, name, selected) \ _cmocka_add_test_byname(tests, sizeof(tests) / sizeof(tests[0]), name, \ selected, \ sizeof(selected) / sizeof(selected[0])) static inline bool _cmocka_add_test_byname(const struct CMUnitTest *tests, size_t ntests, const char *name, struct CMUnitTest *selected, size_t nselected) { size_t i, j; for (i = 0; i < ntests && tests[i].name != NULL; i++) { if (strcmp(tests[i].name, name) != 0) { continue; } for (j = 0; j < nselected && selected[j].name != NULL; j++) { if (strcmp(tests[j].name, name) == 0) { break; } } if (j < nselected && selected[j].name == NULL) { selected[j] = tests[i]; } return (true); } return (false); } ISC_LANG_ENDDECLS PKֺ1]0%+*+*timer.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_TIMER_H #define ISC_TIMER_H 1 /***** ***** Module Info *****/ /*! \file isc/timer.h * \brief Provides timers which are event sources in the task system. * * Three types of timers are supported: * *\li 'ticker' timers generate a periodic tick event. * *\li 'once' timers generate an idle timeout event if they are idle for too * long, and generate a life timeout event if their lifetime expires. * They are used to implement both (possibly expiring) idle timers and * 'one-shot' timers. * *\li 'limited' timers generate a periodic tick event until they reach * their lifetime when they generate a life timeout event. * *\li 'inactive' timers generate no events. * * Timers can change type. It is typical to create a timer as * an 'inactive' timer and then change it into a 'ticker' or * 'once' timer. * *\li MP: * The module ensures appropriate synchronization of data structures it * creates and manipulates. * Clients of this module must not be holding a timer's task's lock when * making a call that affects that timer. Failure to follow this rule * can result in deadlock. * The caller must ensure that isc_timermgr_destroy() is called only * once for a given manager. * * \li Reliability: * No anticipated impact. * * \li Resources: * TBS * * \li Security: * No anticipated impact. * * \li Standards: * None. */ /*** *** Imports ***/ #include #include #include #include #include #include ISC_LANG_BEGINDECLS /*** *** Types ***/ /*% Timer Type */ typedef enum { isc_timertype_undefined = -1, /*%< Undefined */ isc_timertype_ticker = 0, /*%< Ticker */ isc_timertype_once = 1, /*%< Once */ isc_timertype_limited = 2, /*%< Limited */ isc_timertype_inactive = 3 /*%< Inactive */ } isc_timertype_t; typedef struct isc_timerevent { struct isc_event common; isc_time_t due; } isc_timerevent_t; #define ISC_TIMEREVENT_FIRSTEVENT (ISC_EVENTCLASS_TIMER + 0) #define ISC_TIMEREVENT_TICK (ISC_EVENTCLASS_TIMER + 1) #define ISC_TIMEREVENT_IDLE (ISC_EVENTCLASS_TIMER + 2) #define ISC_TIMEREVENT_LIFE (ISC_EVENTCLASS_TIMER + 3) #define ISC_TIMEREVENT_LASTEVENT (ISC_EVENTCLASS_TIMER + 65535) /*% Timer and timer manager methods */ typedef struct { void (*destroy)(isc_timermgr_t **managerp); isc_result_t (*timercreate)(isc_timermgr_t *manager, isc_timertype_t type, const isc_time_t *expires, const isc_interval_t *interval, isc_task_t *task, isc_taskaction_t action, void *arg, isc_timer_t **timerp); } isc_timermgrmethods_t; typedef struct { void (*attach)(isc_timer_t *timer, isc_timer_t **timerp); void (*detach)(isc_timer_t **timerp); isc_result_t (*reset)(isc_timer_t *timer, isc_timertype_t type, const isc_time_t *expires, const isc_interval_t *interval, bool purge); isc_result_t (*touch)(isc_timer_t *timer); } isc_timermethods_t; /*% * This structure is actually just the common prefix of a timer manager * object implementation's version of an isc_timermgr_t. * \brief * Direct use of this structure by clients is forbidden. timer implementations * may change the structure. 'magic' must be ISCAPI_TIMERMGR_MAGIC for any * of the isc_timer_ routines to work. timer implementations must maintain * all timer invariants. */ struct isc_timermgr { unsigned int impmagic; unsigned int magic; isc_timermgrmethods_t *methods; }; #define ISCAPI_TIMERMGR_MAGIC ISC_MAGIC('A','t','m','g') #define ISCAPI_TIMERMGR_VALID(m) ((m) != NULL && \ (m)->magic == ISCAPI_TIMERMGR_MAGIC) /*% * This is the common prefix of a timer object. The same note as * that for the timermgr structure applies. */ struct isc_timer { unsigned int impmagic; unsigned int magic; isc_timermethods_t *methods; }; #define ISCAPI_TIMER_MAGIC ISC_MAGIC('A','t','m','r') #define ISCAPI_TIMER_VALID(s) ((s) != NULL && \ (s)->magic == ISCAPI_TIMER_MAGIC) /*** *** Timer and Timer Manager Functions *** *** Note: all Ensures conditions apply only if the result is success for *** those functions which return an isc_result_t. ***/ isc_result_t isc_timer_create(isc_timermgr_t *manager, isc_timertype_t type, const isc_time_t *expires, const isc_interval_t *interval, isc_task_t *task, isc_taskaction_t action, void *arg, isc_timer_t **timerp); /*%< * Create a new 'type' timer managed by 'manager'. The timers parameters * are specified by 'expires' and 'interval'. Events will be posted to * 'task' and when dispatched 'action' will be called with 'arg' as the * arg value. The new timer is returned in 'timerp'. * * Notes: * *\li For ticker timers, the timer will generate a 'tick' event every * 'interval' seconds. The value of 'expires' is ignored. * *\li For once timers, 'expires' specifies the time when a life timeout * event should be generated. If 'expires' is 0 (the epoch), then no life * timeout will be generated. 'interval' specifies how long the timer * can be idle before it generates an idle timeout. If 0, then no * idle timeout will be generated. * *\li If 'expires' is NULL, the epoch will be used. * * If 'interval' is NULL, the zero interval will be used. * * Requires: * *\li 'manager' is a valid manager * *\li 'task' is a valid task * *\li 'action' is a valid action * *\li 'expires' points to a valid time, or is NULL. * *\li 'interval' points to a valid interval, or is NULL. * *\li type == isc_timertype_inactive || * ('expires' and 'interval' are not both 0) * *\li 'timerp' is a valid pointer, and *timerp == NULL * * Ensures: * *\li '*timerp' is attached to the newly created timer * *\li The timer is attached to the task * *\li An idle timeout will not be generated until at least Now + the * timer's interval if 'timer' is a once timer with a non-zero * interval. * * Returns: * *\li Success *\li No memory *\li Unexpected error */ isc_result_t isc_timer_reset(isc_timer_t *timer, isc_timertype_t type, const isc_time_t *expires, const isc_interval_t *interval, bool purge); /*%< * Change the timer's type, expires, and interval values to the given * values. If 'purge' is TRUE, any pending events from this timer * are purged from its task's event queue. * * Notes: * *\li If 'expires' is NULL, the epoch will be used. * *\li If 'interval' is NULL, the zero interval will be used. * * Requires: * *\li 'timer' is a valid timer * *\li The same requirements that isc_timer_create() imposes on 'type', * 'expires' and 'interval' apply. * * Ensures: * *\li An idle timeout will not be generated until at least Now + the * timer's interval if 'timer' is a once timer with a non-zero * interval. * * Returns: * *\li Success *\li No memory *\li Unexpected error */ isc_result_t isc_timer_touch(isc_timer_t *timer); /*%< * Set the last-touched time of 'timer' to the current time. * * Requires: * *\li 'timer' is a valid once timer. * * Ensures: * *\li An idle timeout will not be generated until at least Now + the * timer's interval if 'timer' is a once timer with a non-zero * interval. * * Returns: * *\li Success *\li Unexpected error */ void isc_timer_attach(isc_timer_t *timer, isc_timer_t **timerp); /*%< * Attach *timerp to timer. * * Requires: * *\li 'timer' is a valid timer. * *\li 'timerp' points to a NULL timer. * * Ensures: * *\li *timerp is attached to timer. */ void isc_timer_detach(isc_timer_t **timerp); /*%< * Detach *timerp from its timer. * * Requires: * *\li 'timerp' points to a valid timer. * * Ensures: * *\li *timerp is NULL. * *\li If '*timerp' is the last reference to the timer, * then: * *\code * The timer will be shutdown * * The timer will detach from its task * * All resources used by the timer have been freed * * Any events already posted by the timer will be purged. * Therefore, if isc_timer_detach() is called in the context * of the timer's task, it is guaranteed that no more * timer event callbacks will run after the call. *\endcode */ isc_timertype_t isc_timer_gettype(isc_timer_t *timer); /*%< * Return the timer type. * * Requires: * *\li 'timer' to be a valid timer. */ isc_result_t isc_timermgr_createinctx(isc_mem_t *mctx, isc_appctx_t *actx, isc_timermgr_t **managerp); isc_result_t isc_timermgr_create(isc_mem_t *mctx, isc_timermgr_t **managerp); /*%< * Create a timer manager. isc_timermgr_createinctx() also associates * the new manager with the specified application context. * * Notes: * *\li All memory will be allocated in memory context 'mctx'. * * Requires: * *\li 'mctx' is a valid memory context. * *\li 'managerp' points to a NULL isc_timermgr_t. * *\li 'actx' is a valid application context (for createinctx()). * * Ensures: * *\li '*managerp' is a valid isc_timermgr_t. * * Returns: * *\li Success *\li No memory *\li Unexpected error */ void isc_timermgr_destroy(isc_timermgr_t **managerp); /*%< * Destroy a timer manager. * * Notes: * *\li This routine blocks until there are no timers left in the manager, * so if the caller holds any timer references using the manager, it * must detach them before calling isc_timermgr_destroy() or it will * block forever. * * Requires: * *\li '*managerp' is a valid isc_timermgr_t. * * Ensures: * *\li *managerp == NULL * *\li All resources used by the manager have been freed. */ void isc_timermgr_poke(isc_timermgr_t *m); /*%< * See isc_timermgr_create() above. */ typedef isc_result_t (*isc_timermgrcreatefunc_t)(isc_mem_t *mctx, isc_timermgr_t **managerp); isc_result_t isc__timer_register(void); /*%< * Register a new timer management implementation and add it to the list of * supported implementations. This function must be called when a different * event library is used than the one contained in the ISC library. */ isc_result_t isc_timer_register(isc_timermgrcreatefunc_t createfunc); /*%< * A short cut function that specifies the timer management module in the ISC * library for isc_timer_register(). An application that uses the ISC library * usually do not have to care about this function: it would call * isc_lib_register(), which internally calls this function. */ ISC_LANG_ENDDECLS #endif /* ISC_TIMER_H */ PKֺ1]36Ѡutf8.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/utf8.h */ #pragma once #include #include ISC_LANG_BEGINDECLS bool isc_utf8_bom(const unsigned char *buf, size_t len); /*< * Returns 'true' if the string of bytes in 'buf' starts * with an UTF-8 Byte Order Mark. * * Requires: *\li 'buf' != NULL */ bool isc_utf8_valid(const unsigned char *buf, size_t len); /*< * Returns 'true' if the string of bytes in 'buf' is a valid UTF-8 * byte sequence otherwise 'false' is returned. * * Requires: *\li 'buf' != NULL */ ISC_LANG_ENDDECLS PKֺ1]~ۜffbuffer.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_BUFFER_H #define ISC_BUFFER_H 1 /***** ***** Module Info *****/ /*! \file isc/buffer.h * * \brief A buffer is a region of memory, together with a set of related subregions. * Buffers are used for parsing and I/O operations. * * The 'used region' and the 'available' region are disjoint, and their * union is the buffer's region. The used region extends from the beginning * of the buffer region to the last used byte. The available region * extends from one byte greater than the last used byte to the end of the * buffer's region. The size of the used region can be changed using various * buffer commands. Initially, the used region is empty. * * The used region is further subdivided into two disjoint regions: the * 'consumed region' and the 'remaining region'. The union of these two * regions is the used region. The consumed region extends from the beginning * of the used region to the byte before the 'current' offset (if any). The * 'remaining' region the current pointer to the end of the used * region. The size of the consumed region can be changed using various * buffer commands. Initially, the consumed region is empty. * * The 'active region' is an (optional) subregion of the remaining region. * It extends from the current offset to an offset in the remaining region * that is selected with isc_buffer_setactive(). Initially, the active region * is empty. If the current offset advances beyond the chosen offset, the * active region will also be empty. * * \verbatim * /------------entire length---------------\ * /----- used region -----\/-- available --\ * +----------------------------------------+ * | consumed | remaining | | * +----------------------------------------+ * a b c d e * * a == base of buffer. * b == current pointer. Can be anywhere between a and d. * c == active pointer. Meaningful between b and d. * d == used pointer. * e == length of buffer. * * a-e == entire length of buffer. * a-d == used region. * a-b == consumed region. * b-d == remaining region. * b-c == optional active region. *\endverbatim * * The following invariants are maintained by all routines: * *\code * length > 0 * * base is a valid pointer to length bytes of memory * * 0 <= used <= length * * 0 <= current <= used * * 0 <= active <= used * (although active < current implies empty active region) *\endcode * * \li MP: * Buffers have no synchronization. Clients must ensure exclusive * access. * * \li Reliability: * No anticipated impact. * * \li Resources: * Memory: 1 pointer + 6 unsigned integers per buffer. * * \li Security: * No anticipated impact. * * \li Standards: * None. */ /*** *** Imports ***/ #include #include #include #include #include #include #include #include /*! * To make many functions be inline macros (via \#define) define this. * If it is undefined, a function will be used. */ /* #define ISC_BUFFER_USEINLINE */ ISC_LANG_BEGINDECLS /*@{*/ /*! *** Magic numbers ***/ #define ISC_BUFFER_MAGIC 0x42756621U /* Buf!. */ #define ISC_BUFFER_VALID(b) ISC_MAGIC_VALID(b, ISC_BUFFER_MAGIC) /*@}*/ /*! * Size granularity for dynamically resizable buffers; when reserving * space in a buffer, we round the allocated buffer length up to the * nearest * multiple of this value. */ #define ISC_BUFFER_INCR 2048 /* * The following macros MUST be used only on valid buffers. It is the * caller's responsibility to ensure this by using the ISC_BUFFER_VALID * check above, or by calling another isc_buffer_*() function (rather than * another macro.) */ /*@{*/ /*! * Fundamental buffer elements. (A through E in the introductory comment.) */ #define isc_buffer_base(b) ((void *)(b)->base) /*a*/ #define isc_buffer_current(b) \ ((void *)((unsigned char *)(b)->base + (b)->current)) /*b*/ #define isc_buffer_active(b) \ ((void *)((unsigned char *)(b)->base + (b)->active)) /*c*/ #define isc_buffer_used(b) \ ((void *)((unsigned char *)(b)->base + (b)->used)) /*d*/ #define isc_buffer_length(b) ((b)->length) /*e*/ /*@}*/ /*@{*/ /*! * Derived lengths. (Described in the introductory comment.) */ #define isc_buffer_usedlength(b) ((b)->used) /* d-a */ #define isc_buffer_consumedlength(b) ((b)->current) /* b-a */ #define isc_buffer_remaininglength(b) ((b)->used - (b)->current) /* d-b */ #define isc_buffer_activelength(b) ((b)->active - (b)->current) /* c-b */ #define isc_buffer_availablelength(b) ((b)->length - (b)->used) /* e-d */ /*@}*/ /*! * Note that the buffer structure is public. This is principally so buffer * operations can be implemented using macros. Applications are strongly * discouraged from directly manipulating the structure. */ struct isc_buffer { unsigned int magic; void *base; /*@{*/ /*! The following integers are byte offsets from 'base'. */ unsigned int length; unsigned int used; unsigned int current; unsigned int active; /*@}*/ /*! linkable */ ISC_LINK(isc_buffer_t) link; /*! private internal elements */ isc_mem_t *mctx; /* automatically realloc buffer at put* */ bool autore; }; /*** *** Functions ***/ isc_result_t isc_buffer_allocate(isc_mem_t *mctx, isc_buffer_t **dynbuffer, unsigned int length); /*!< * \brief Allocate a dynamic linkable buffer which has "length" bytes in the * data region. * * Requires: *\li "mctx" is valid. * *\li "dynbuffer" is non-NULL, and "*dynbuffer" is NULL. * * Returns: *\li ISC_R_SUCCESS - success *\li ISC_R_NOMEMORY - no memory available * * Note: *\li Changing the buffer's length field is not permitted. */ isc_result_t isc_buffer_reallocate(isc_buffer_t **dynbuffer, unsigned int length); /*!< * \brief Reallocate the buffer to be "length" bytes long. The buffer * pointer may move when you call this function. * * Requires: *\li "dynbuffer" is not NULL. * *\li "*dynbuffer" is a valid dynamic buffer. * *\li 'length' > current length of buffer. * * Returns: *\li ISC_R_SUCCESS - success *\li ISC_R_NOMEMORY - no memory available * * Ensures: *\li "*dynbuffer" will be valid on return and will contain all the * original data. However, the buffer pointer may be moved during * reallocation. */ isc_result_t isc_buffer_reserve(isc_buffer_t **dynbuffer, unsigned int size); /*!< * \brief Make "size" bytes of space available in the buffer. The buffer * pointer may move when you call this function. * * Requires: *\li "dynbuffer" is not NULL. * *\li "*dynbuffer" is a valid dynamic buffer. * * Returns: *\li ISC_R_SUCCESS - success *\li ISC_R_NOMEMORY - no memory available * * Ensures: *\li "*dynbuffer" will be valid on return and will contain all the * original data. However, the buffer pointer may be moved during * reallocation. */ void isc_buffer_free(isc_buffer_t **dynbuffer); /*!< * \brief Release resources allocated for a dynamic buffer. * * Requires: *\li "dynbuffer" is not NULL. * *\li "*dynbuffer" is a valid dynamic buffer. * * Ensures: *\li "*dynbuffer" will be NULL on return, and all memory associated with * the dynamic buffer is returned to the memory context used in * isc_buffer_allocate(). */ void isc__buffer_init(isc_buffer_t *b, void *base, unsigned int length); /*!< * \brief Make 'b' refer to the 'length'-byte region starting at base. * * Requires: * *\li 'length' > 0 * *\li 'base' is a pointer to a sequence of 'length' bytes. * */ void isc__buffer_initnull(isc_buffer_t *b); /*!< *\brief Initialize a buffer 'b' with a null data and zero length/ */ void isc_buffer_reinit(isc_buffer_t *b, void *base, unsigned int length); /*!< * \brief Make 'b' refer to the 'length'-byte region starting at base. * Any existing data will be copied. * * Requires: * *\li 'length' > 0 AND length >= previous length * *\li 'base' is a pointer to a sequence of 'length' bytes. * */ void isc__buffer_invalidate(isc_buffer_t *b); /*!< * \brief Make 'b' an invalid buffer. * * Requires: *\li 'b' is a valid buffer. * * Ensures: *\li If assertion checking is enabled, future attempts to use 'b' without * calling isc_buffer_init() on it will cause an assertion failure. */ void isc_buffer_setautorealloc(isc_buffer_t *b, bool enable); /*!< * \brief Enable or disable autoreallocation on 'b'. * * Requires: *\li 'b' is a valid dynamic buffer (b->mctx != NULL). * */ void isc__buffer_region(isc_buffer_t *b, isc_region_t *r); /*!< * \brief Make 'r' refer to the region of 'b'. * * Requires: * *\li 'b' is a valid buffer. * *\li 'r' points to a region structure. */ void isc__buffer_usedregion(const isc_buffer_t *b, isc_region_t *r); /*!< * \brief Make 'r' refer to the used region of 'b'. * * Requires: * *\li 'b' is a valid buffer. * *\li 'r' points to a region structure. */ void isc__buffer_availableregion(isc_buffer_t *b, isc_region_t *r); /*!< * \brief Make 'r' refer to the available region of 'b'. * * Requires: * *\li 'b' is a valid buffer. * *\li 'r' points to a region structure. */ void isc__buffer_add(isc_buffer_t *b, unsigned int n); /*!< * \brief Increase the 'used' region of 'b' by 'n' bytes. * * Requires: * *\li 'b' is a valid buffer * *\li used + n <= length * */ void isc__buffer_subtract(isc_buffer_t *b, unsigned int n); /*!< * \brief Decrease the 'used' region of 'b' by 'n' bytes. * * Requires: * *\li 'b' is a valid buffer * *\li used >= n * */ void isc__buffer_clear(isc_buffer_t *b); /*!< * \brief Make the used region empty. * * Requires: * *\li 'b' is a valid buffer * * Ensures: * *\li used = 0 * */ void isc__buffer_consumedregion(isc_buffer_t *b, isc_region_t *r); /*!< * \brief Make 'r' refer to the consumed region of 'b'. * * Requires: * *\li 'b' is a valid buffer. * *\li 'r' points to a region structure. */ void isc__buffer_remainingregion(isc_buffer_t *b, isc_region_t *r); /*!< * \brief Make 'r' refer to the remaining region of 'b'. * * Requires: * *\li 'b' is a valid buffer. * *\li 'r' points to a region structure. */ void isc__buffer_activeregion(isc_buffer_t *b, isc_region_t *r); /*!< * \brief Make 'r' refer to the active region of 'b'. * * Requires: * *\li 'b' is a valid buffer. * *\li 'r' points to a region structure. */ void isc__buffer_setactive(isc_buffer_t *b, unsigned int n); /*!< * \brief Sets the end of the active region 'n' bytes after current. * * Requires: * *\li 'b' is a valid buffer. * *\li current + n <= used */ void isc__buffer_first(isc_buffer_t *b); /*!< * \brief Make the consumed region empty. * * Requires: * *\li 'b' is a valid buffer * * Ensures: * *\li current == 0 * */ void isc__buffer_forward(isc_buffer_t *b, unsigned int n); /*!< * \brief Increase the 'consumed' region of 'b' by 'n' bytes. * * Requires: * *\li 'b' is a valid buffer * *\li current + n <= used * */ void isc__buffer_back(isc_buffer_t *b, unsigned int n); /*!< * \brief Decrease the 'consumed' region of 'b' by 'n' bytes. * * Requires: * *\li 'b' is a valid buffer * *\li n <= current * */ void isc_buffer_compact(isc_buffer_t *b); /*!< * \brief Compact the used region by moving the remaining region so it occurs * at the start of the buffer. The used region is shrunk by the size of * the consumed region, and the consumed region is then made empty. * * Requires: * *\li 'b' is a valid buffer * * Ensures: * *\li current == 0 * *\li The size of the used region is now equal to the size of the remaining * region (as it was before the call). The contents of the used region * are those of the remaining region (as it was before the call). */ uint8_t isc_buffer_getuint8(isc_buffer_t *b); /*!< * \brief Read an unsigned 8-bit integer from 'b' and return it. * * Requires: * *\li 'b' is a valid buffer. * *\li The length of the available region of 'b' is at least 1. * * Ensures: * *\li The current pointer in 'b' is advanced by 1. * * Returns: * *\li A 8-bit unsigned integer. */ void isc__buffer_putuint8(isc_buffer_t *b, uint8_t val); /*!< * \brief Store an unsigned 8-bit integer from 'val' into 'b'. * * Requires: *\li 'b' is a valid buffer. * *\li The length of the unused region of 'b' is at least 1 * or the buffer has autoreallocation enabled. * * Ensures: *\li The used pointer in 'b' is advanced by 1. */ uint16_t isc_buffer_getuint16(isc_buffer_t *b); /*!< * \brief Read an unsigned 16-bit integer in network byte order from 'b', convert * it to host byte order, and return it. * * Requires: * *\li 'b' is a valid buffer. * *\li The length of the available region of 'b' is at least 2 * or the buffer has autoreallocation enabled. * * Ensures: * *\li The current pointer in 'b' is advanced by 2. * * Returns: * *\li A 16-bit unsigned integer. */ void isc__buffer_putuint16(isc_buffer_t *b, uint16_t val); /*!< * \brief Store an unsigned 16-bit integer in host byte order from 'val' * into 'b' in network byte order. * * Requires: *\li 'b' is a valid buffer. * *\li The length of the unused region of 'b' is at least 2 * or the buffer has autoreallocation enabled. * * Ensures: *\li The used pointer in 'b' is advanced by 2. */ uint32_t isc_buffer_getuint32(isc_buffer_t *b); /*!< * \brief Read an unsigned 32-bit integer in network byte order from 'b', convert * it to host byte order, and return it. * * Requires: * *\li 'b' is a valid buffer. * *\li The length of the available region of 'b' is at least 4. * * Ensures: * *\li The current pointer in 'b' is advanced by 4. * * Returns: * *\li A 32-bit unsigned integer. */ void isc__buffer_putuint32(isc_buffer_t *b, uint32_t val); /*!< * \brief Store an unsigned 32-bit integer in host byte order from 'val' * into 'b' in network byte order. * * Requires: *\li 'b' is a valid buffer. * *\li The length of the unused region of 'b' is at least 4 * or the buffer has autoreallocation enabled. * * Ensures: *\li The used pointer in 'b' is advanced by 4. */ uint64_t isc_buffer_getuint48(isc_buffer_t *b); /*!< * \brief Read an unsigned 48-bit integer in network byte order from 'b', * convert it to host byte order, and return it. * * Requires: * *\li 'b' is a valid buffer. * *\li The length of the available region of 'b' is at least 6. * * Ensures: * *\li The current pointer in 'b' is advanced by 6. * * Returns: * *\li A 48-bit unsigned integer (stored in a 64-bit integer). */ void isc__buffer_putuint48(isc_buffer_t *b, uint64_t val); /*!< * \brief Store an unsigned 48-bit integer in host byte order from 'val' * into 'b' in network byte order. * * Requires: *\li 'b' is a valid buffer. * *\li The length of the unused region of 'b' is at least 6 * or the buffer has autoreallocation enabled. * * Ensures: *\li The used pointer in 'b' is advanced by 6. */ void isc__buffer_putuint24(isc_buffer_t *b, uint32_t val); /*!< * Store an unsigned 24-bit integer in host byte order from 'val' * into 'b' in network byte order. * * Requires: *\li 'b' is a valid buffer. * * The length of the unused region of 'b' is at least 3 * or the buffer has autoreallocation enabled. * * Ensures: *\li The used pointer in 'b' is advanced by 3. */ void isc__buffer_putmem(isc_buffer_t *b, const unsigned char *base, unsigned int length); /*!< * \brief Copy 'length' bytes of memory at 'base' into 'b'. * * Requires: *\li 'b' is a valid buffer, and it has at least 'length' * or the buffer has autoreallocation enabled. * *\li 'base' points to 'length' bytes of valid memory. * */ void isc__buffer_putstr(isc_buffer_t *b, const char *source); /*!< * \brief Copy 'source' into 'b', not including terminating NUL. * * Requires: *\li 'b' is a valid buffer. * *\li 'source' to be a valid NULL terminated string. * *\li strlen(source) <= isc_buffer_available(b) || b->mctx != NULL */ void isc_buffer_putdecint(isc_buffer_t *b, int64_t v); /*!< * \brief Put decimal representation of 'v' in b * * Requires: *\li 'b' is a valid buffer. * *\li strlen(dec(v)) <= isc_buffer_available(b) || b->mctx != NULL */ isc_result_t isc_buffer_copyregion(isc_buffer_t *b, const isc_region_t *r); /*!< * \brief Copy the contents of 'r' into 'b'. * * Requires: *\li 'b' is a valid buffer. * *\li 'r' is a valid region. * * Returns: * *\li ISC_R_SUCCESS *\li ISC_R_NOSPACE The available region of 'b' is not * big enough. */ isc_result_t isc_buffer_dup(isc_mem_t *mctx, isc_buffer_t **dstp, const isc_buffer_t *src); /*!< * \brief Allocate 'dst' and copy used contents of 'src' into it * * Requires: *\li 'dstp' is not NULL and *dst is NULL *\li 'src' is a valid buffer. * * Returns: * *\li ISC_R_SUCCESS *\li ISC_R_NOSPACE The available region of 'b' is not * big enough. */ ISC_LANG_ENDDECLS /* * Inline macro versions of the functions. These should never be called * directly by an application, but will be used by the functions within * buffer.c. The callers should always use "isc_buffer_*()" names, never * ones beginning with "isc__" */ /*! \note * XXXDCL Something more could be done with initializing buffers that * point to const data. For example, isc_buffer_constinit() could * set a new boolean flag in the buffer structure indicating whether * the buffer was initialized with that function. * Then if the * boolean were true, the isc_buffer_put* functions could assert a * contractual requirement for a non-const buffer. * * One drawback is that the isc_buffer_* functions (macros) that return * pointers would still need to return non-const pointers to avoid compiler * warnings, so it would be up to code that uses them to have to deal * with the possibility that the buffer was initialized as const -- * a problem that they *already* have to deal with but have absolutely * no ability to. With a new isc_buffer_isconst() function returning * true/false, they could at least assert a contractual requirement for * non-const buffers when needed. */ #define ISC__BUFFER_INIT(_b, _base, _length) \ do { \ (_b)->base = _base; \ (_b)->length = (_length); \ (_b)->used = 0; \ (_b)->current = 0; \ (_b)->active = 0; \ (_b)->mctx = NULL; \ ISC_LINK_INIT(_b, link); \ (_b)->magic = ISC_BUFFER_MAGIC; \ (_b)->autore = false; \ } while (0) #define ISC__BUFFER_INITNULL(_b) ISC__BUFFER_INIT(_b, NULL, 0) #define ISC__BUFFER_INVALIDATE(_b) \ do { \ (_b)->magic = 0; \ (_b)->base = NULL; \ (_b)->length = 0; \ (_b)->used = 0; \ (_b)->current = 0; \ (_b)->active = 0; \ } while (0) #define ISC__BUFFER_REGION(_b, _r) \ do { \ (_r)->base = (_b)->base; \ (_r)->length = (_b)->length; \ } while (0) #define ISC__BUFFER_USEDREGION(_b, _r) \ do { \ (_r)->base = (_b)->base; \ (_r)->length = (_b)->used; \ } while (0) #define ISC__BUFFER_AVAILABLEREGION(_b, _r) \ do { \ (_r)->base = isc_buffer_used(_b); \ (_r)->length = isc_buffer_availablelength(_b); \ } while (0) #define ISC__BUFFER_ADD(_b, _n) \ do { \ (_b)->used += (_n); \ } while (0) #define ISC__BUFFER_SUBTRACT(_b, _n) \ do { \ (_b)->used -= (_n); \ if ((_b)->current > (_b)->used) \ (_b)->current = (_b)->used; \ if ((_b)->active > (_b)->used) \ (_b)->active = (_b)->used; \ } while (0) #define ISC__BUFFER_CLEAR(_b) \ do { \ (_b)->used = 0; \ (_b)->current = 0; \ (_b)->active = 0; \ } while (0) #define ISC__BUFFER_CONSUMEDREGION(_b, _r) \ do { \ (_r)->base = (_b)->base; \ (_r)->length = (_b)->current; \ } while (0) #define ISC__BUFFER_REMAININGREGION(_b, _r) \ do { \ (_r)->base = isc_buffer_current(_b); \ (_r)->length = isc_buffer_remaininglength(_b); \ } while (0) #define ISC__BUFFER_ACTIVEREGION(_b, _r) \ do { \ if ((_b)->current < (_b)->active) { \ (_r)->base = isc_buffer_current(_b); \ (_r)->length = isc_buffer_activelength(_b); \ } else { \ (_r)->base = NULL; \ (_r)->length = 0; \ } \ } while (0) #define ISC__BUFFER_SETACTIVE(_b, _n) \ do { \ (_b)->active = (_b)->current + (_n); \ } while (0) #define ISC__BUFFER_FIRST(_b) \ do { \ (_b)->current = 0; \ } while (0) #define ISC__BUFFER_FORWARD(_b, _n) \ do { \ (_b)->current += (_n); \ } while (0) #define ISC__BUFFER_BACK(_b, _n) \ do { \ (_b)->current -= (_n); \ } while (0) #define ISC__BUFFER_PUTMEM(_b, _base, _length) \ do { \ if (ISC_UNLIKELY((_b)->autore)) { \ isc_buffer_t *_tmp = _b; \ ISC_REQUIRE(isc_buffer_reserve(&_tmp, _length) \ == ISC_R_SUCCESS); \ } \ ISC_REQUIRE(isc_buffer_availablelength(_b) >= (unsigned int) _length); \ if (_length > 0U) { \ memmove(isc_buffer_used(_b), (_base), (_length)); \ (_b)->used += (_length); \ } \ } while (0) #define ISC__BUFFER_PUTSTR(_b, _source) \ do { \ unsigned int _length; \ unsigned char *_cp; \ _length = (unsigned int)strlen(_source); \ if (ISC_UNLIKELY((_b)->autore)) { \ isc_buffer_t *_tmp = _b; \ ISC_REQUIRE(isc_buffer_reserve(&_tmp, _length) \ == ISC_R_SUCCESS); \ } \ ISC_REQUIRE(isc_buffer_availablelength(_b) >= _length); \ _cp = isc_buffer_used(_b); \ memmove(_cp, (_source), _length); \ (_b)->used += (_length); \ } while (0) #define ISC__BUFFER_PUTUINT8(_b, _val) \ do { \ unsigned char *_cp; \ /* evaluate (_val) only once */ \ uint8_t _val2 = (_val); \ if (ISC_UNLIKELY((_b)->autore)) { \ isc_buffer_t *_tmp = _b; \ ISC_REQUIRE(isc_buffer_reserve(&_tmp, 1) \ == ISC_R_SUCCESS); \ } \ ISC_REQUIRE(isc_buffer_availablelength(_b) >= 1U); \ _cp = isc_buffer_used(_b); \ (_b)->used++; \ _cp[0] = _val2; \ } while (0) #define ISC__BUFFER_PUTUINT16(_b, _val) \ do { \ unsigned char *_cp; \ /* evaluate (_val) only once */ \ uint16_t _val2 = (_val); \ if (ISC_UNLIKELY((_b)->autore)) { \ isc_buffer_t *_tmp = _b; \ ISC_REQUIRE(isc_buffer_reserve(&_tmp, 2) \ == ISC_R_SUCCESS); \ } \ ISC_REQUIRE(isc_buffer_availablelength(_b) >= 2U); \ _cp = isc_buffer_used(_b); \ (_b)->used += 2; \ _cp[0] = _val2 >> 8; \ _cp[1] = _val2; \ } while (0) #define ISC__BUFFER_PUTUINT24(_b, _val) \ do { \ unsigned char *_cp; \ /* evaluate (_val) only once */ \ uint32_t _val2 = (_val); \ if (ISC_UNLIKELY((_b)->autore)) { \ isc_buffer_t *_tmp = _b; \ ISC_REQUIRE(isc_buffer_reserve(&_tmp, 3) \ == ISC_R_SUCCESS); \ } \ ISC_REQUIRE(isc_buffer_availablelength(_b) >= 3U); \ _cp = isc_buffer_used(_b); \ (_b)->used += 3; \ _cp[0] = _val2 >> 16; \ _cp[1] = _val2 >> 8; \ _cp[2] = _val2; \ } while (0) #define ISC__BUFFER_PUTUINT32(_b, _val) \ do { \ unsigned char *_cp; \ /* evaluate (_val) only once */ \ uint32_t _val2 = (_val); \ if (ISC_UNLIKELY((_b)->autore)) { \ isc_buffer_t *_tmp = _b; \ ISC_REQUIRE(isc_buffer_reserve(&_tmp, 4) \ == ISC_R_SUCCESS); \ } \ ISC_REQUIRE(isc_buffer_availablelength(_b) >= 4U); \ _cp = isc_buffer_used(_b); \ (_b)->used += 4; \ _cp[0] = _val2 >> 24; \ _cp[1] = _val2 >> 16; \ _cp[2] = _val2 >> 8; \ _cp[3] = _val2; \ } while (0) #if defined(ISC_BUFFER_USEINLINE) #define isc_buffer_init ISC__BUFFER_INIT #define isc_buffer_initnull ISC__BUFFER_INITNULL #define isc_buffer_invalidate ISC__BUFFER_INVALIDATE #define isc_buffer_region ISC__BUFFER_REGION #define isc_buffer_usedregion ISC__BUFFER_USEDREGION #define isc_buffer_availableregion ISC__BUFFER_AVAILABLEREGION #define isc_buffer_add ISC__BUFFER_ADD #define isc_buffer_subtract ISC__BUFFER_SUBTRACT #define isc_buffer_clear ISC__BUFFER_CLEAR #define isc_buffer_consumedregion ISC__BUFFER_CONSUMEDREGION #define isc_buffer_remainingregion ISC__BUFFER_REMAININGREGION #define isc_buffer_activeregion ISC__BUFFER_ACTIVEREGION #define isc_buffer_setactive ISC__BUFFER_SETACTIVE #define isc_buffer_first ISC__BUFFER_FIRST #define isc_buffer_forward ISC__BUFFER_FORWARD #define isc_buffer_back ISC__BUFFER_BACK #define isc_buffer_putmem ISC__BUFFER_PUTMEM #define isc_buffer_putstr ISC__BUFFER_PUTSTR #define isc_buffer_putuint8 ISC__BUFFER_PUTUINT8 #define isc_buffer_putuint16 ISC__BUFFER_PUTUINT16 #define isc_buffer_putuint24 ISC__BUFFER_PUTUINT24 #define isc_buffer_putuint32 ISC__BUFFER_PUTUINT32 #else #define isc_buffer_init isc__buffer_init #define isc_buffer_initnull isc__buffer_initnull #define isc_buffer_invalidate isc__buffer_invalidate #define isc_buffer_region isc__buffer_region #define isc_buffer_usedregion isc__buffer_usedregion #define isc_buffer_availableregion isc__buffer_availableregion #define isc_buffer_add isc__buffer_add #define isc_buffer_subtract isc__buffer_subtract #define isc_buffer_clear isc__buffer_clear #define isc_buffer_consumedregion isc__buffer_consumedregion #define isc_buffer_remainingregion isc__buffer_remainingregion #define isc_buffer_activeregion isc__buffer_activeregion #define isc_buffer_setactive isc__buffer_setactive #define isc_buffer_first isc__buffer_first #define isc_buffer_forward isc__buffer_forward #define isc_buffer_back isc__buffer_back #define isc_buffer_putmem isc__buffer_putmem #define isc_buffer_putstr isc__buffer_putstr #define isc_buffer_putuint8 isc__buffer_putuint8 #define isc_buffer_putuint16 isc__buffer_putuint16 #define isc_buffer_putuint24 isc__buffer_putuint24 #define isc_buffer_putuint32 isc__buffer_putuint32 #endif #define isc_buffer_constinit(_b, _d, _l) \ do { \ union { void *_var; const void *_const; } _deconst; \ _deconst._const = (_d); \ isc_buffer_init((_b), _deconst._var, (_l)); \ } while (0) /* * No inline method for this one (yet). */ #define isc_buffer_putuint48 isc__buffer_putuint48 #endif /* ISC_BUFFER_H */ PKֺ1] netscope.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_NETSCOPE_H #define ISC_NETSCOPE_H 1 /*! \file isc/netscope.h */ #include ISC_LANG_BEGINDECLS /*% * Convert a string of an IPv6 scope zone to zone index. If the conversion * succeeds, 'zoneid' will store the index value. * * XXXJT: when a standard interface for this purpose is defined, * we should use it. * * Returns: * \li ISC_R_SUCCESS: conversion succeeds * \li ISC_R_FAILURE: conversion fails */ isc_result_t isc_netscope_pton(int af, char *scopename, void *addr, uint32_t *zoneid); ISC_LANG_ENDDECLS #endif /* ISC_NETSCOPE_H */ PKֺ1]^P88aes.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/aes.h */ #ifndef ISC_AES_H #define ISC_AES_H 1 #include #include #include #define ISC_AES128_KEYLENGTH 16U #define ISC_AES192_KEYLENGTH 24U #define ISC_AES256_KEYLENGTH 32U #define ISC_AES_BLOCK_LENGTH 16U #ifdef ISC_PLATFORM_WANTAES ISC_LANG_BEGINDECLS void isc_aes128_crypt(const unsigned char *key, const unsigned char *in, unsigned char *out); void isc_aes192_crypt(const unsigned char *key, const unsigned char *in, unsigned char *out); void isc_aes256_crypt(const unsigned char *key, const unsigned char *in, unsigned char *out); ISC_LANG_ENDDECLS #endif /* ISC_PLATFORM_WANTAES */ #endif /* ISC_AES_H */ PKֺ1]?.iterated_hash.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_ITERATED_HASH_H #define ISC_ITERATED_HASH_H 1 #include #include /* * The maximal hash length that can be encoded in a name * using base32hex. floor(255/8)*5 */ #define NSEC3_MAX_HASH_LENGTH 155 /* * The maximum has that can be encoded in a single label using * base32hex. floor(63/8)*5 */ #define NSEC3_MAX_LABEL_HASH 35 ISC_LANG_BEGINDECLS int isc_iterated_hash(unsigned char out[NSEC3_MAX_HASH_LENGTH], unsigned int hashalg, int iterations, const unsigned char *salt, int saltlength, const unsigned char *in, int inlength); ISC_LANG_ENDDECLS #endif /* ISC_ITERATED_HASH_H */ PKֺ1]w hex.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_HEX_H #define ISC_HEX_H 1 /*! \file isc/hex.h */ #include #include ISC_LANG_BEGINDECLS /*** *** Functions ***/ isc_result_t isc_hex_totext(isc_region_t *source, int wordlength, const char *wordbreak, isc_buffer_t *target); /*!< * \brief Convert data into hex encoded text. * * Notes: *\li The hex encoded text in 'target' will be divided into * words of at most 'wordlength' characters, separated by * the 'wordbreak' string. No parentheses will surround * the text. * * Requires: *\li 'source' is a region containing binary data *\li 'target' is a text buffer containing available space *\li 'wordbreak' points to a null-terminated string of * zero or more whitespace characters * * Ensures: *\li target will contain the hex encoded version of the data * in source. The 'used' pointer in target will be advanced as * necessary. */ isc_result_t isc_hex_decodestring(const char *cstr, isc_buffer_t *target); /*!< * \brief Decode a null-terminated hex string. * * Requires: *\li 'cstr' is non-null. *\li 'target' is a valid buffer. * * Returns: *\li #ISC_R_SUCCESS -- the entire decoded representation of 'cstring' * fit in 'target'. *\li #ISC_R_BADHEX -- 'cstr' is not a valid hex encoding. * * Other error returns are any possible error code from: * isc_lex_create(), * isc_lex_openbuffer(), * isc_hex_tobuffer(). */ isc_result_t isc_hex_tobuffer(isc_lex_t *lexer, isc_buffer_t *target, int length); /*!< * \brief Convert hex-encoded text from a lexer context into * `target`. If 'length' is non-negative, it is the expected number of * encoded octets to convert. * * If 'length' is -1 then 0 or more encoded octets are expected. * If 'length' is -2 then 1 or more encoded octets are expected. * * Returns: *\li #ISC_R_BADHEX -- invalid hex encoding *\li #ISC_R_UNEXPECTEDEND: the text does not contain the expected * number of encoded octets. * * Requires: *\li 'lexer' is a valid lexer context *\li 'target' is a buffer containing binary data *\li 'length' is -2, -1, or non-negative * * Ensures: *\li target will contain the data represented by the hex encoded * string parsed by the lexer. No more than `length` octets will * be read, if `length` is non-negative. The 'used' pointer in * 'target' will be advanced as necessary. */ ISC_LANG_ENDDECLS #endif /* ISC_HEX_H */ PKֺ1]|FFxml.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_XML_H #define ISC_XML_H 1 /* * This file is here mostly to make it easy to add additional libxml header * files as needed across all the users of this file. Rather than place * these libxml includes in each file, one include makes it easy to handle * the ifdef as well as adding the ability to add additional functions * which may be useful. */ #ifdef HAVE_LIBXML2 #include #include #endif #define ISC_XMLCHAR (const xmlChar *) #define ISC_XML_RENDERCONFIG 0x00000001 /* render config data */ #define ISC_XML_RENDERSTATS 0x00000002 /* render stats */ #define ISC_XML_RENDERALL 0x000000ff /* render everything */ #endif /* ISC_XML_H */ PKֺ1]햄'. . resource.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_RESOURCE_H #define ISC_RESOURCE_H 1 /*! \file isc/resource.h */ #include #include #define ISC_RESOURCE_UNLIMITED ((isc_resourcevalue_t)UINT64_MAX) ISC_LANG_BEGINDECLS isc_result_t isc_resource_setlimit(isc_resource_t resource, isc_resourcevalue_t value); /*%< * Set the maximum limit for a system resource. * * Notes: *\li If 'value' exceeds the maximum possible on the operating system, * it is silently limited to that maximum -- or to "infinity", if * the operating system has that concept. #ISC_RESOURCE_UNLIMITED * can be used to explicitly ask for the maximum. * * Requires: *\li 'resource' is a valid member of the isc_resource_t enumeration. * * Returns: *\li #ISC_R_SUCCESS Success. *\li #ISC_R_NOTIMPLEMENTED 'resource' is not a type known by the OS. *\li #ISC_R_NOPERM The calling process did not have adequate permission * to change the resource limit. */ isc_result_t isc_resource_getlimit(isc_resource_t resource, isc_resourcevalue_t *value); /*%< * Get the maximum limit for a system resource. * * Notes: *\li 'value' is set to the maximum limit. * *\li #ISC_RESOURCE_UNLIMITED is the maximum value of isc_resourcevalue_t. * *\li On many (all?) Unix systems, RLIM_INFINITY is a valid value that is * significantly less than #ISC_RESOURCE_UNLIMITED, but which in practice * behaves the same. * *\li The current ISC libdns configuration file parser assigns a value * of UINT32_MAX for a size_spec of "unlimited" and ISC_UNIT32_MAX - 1 * for "default", the latter of which is supposed to represent "the * limit that was in force when the server started". Since these are * valid values in the middle of the range of isc_resourcevalue_t, * there is the possibility for confusion over what exactly those * particular values are supposed to represent in a particular context -- * discrete integral values or generalized concepts. * * Requires: *\li 'resource' is a valid member of the isc_resource_t enumeration. * * Returns: *\li #ISC_R_SUCCESS Success. *\li #ISC_R_NOTIMPLEMENTED 'resource' is not a type known by the OS. */ isc_result_t isc_resource_getcurlimit(isc_resource_t resource, isc_resourcevalue_t *value); /*%< * Same as isc_resource_getlimit(), but returns the current (soft) limit. * * Returns: *\li #ISC_R_SUCCESS Success. *\li #ISC_R_NOTIMPLEMENTED 'resource' is not a type known by the OS. */ ISC_LANG_ENDDECLS #endif /* ISC_RESOURCE_H */ PKֺ1]ryxtypes.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_TYPES_H #define ISC_TYPES_H 1 #include #include /*! \file isc/types.h * \brief * OS-specific types, from the OS-specific include directories. */ #include #include /* * XXXDCL should bool be moved here, requiring an explicit include */ /* * XXXDCL This is just for ISC_LIST and ISC_LINK, but gets all of the other * list macros too. */ #include /* Core Types. Alphabetized by defined type. */ typedef struct isc_appctx isc_appctx_t; /*%< Application context */ typedef struct isc_backtrace_symmap isc_backtrace_symmap_t; /*%< Symbol Table Entry */ typedef struct isc_buffer isc_buffer_t; /*%< Buffer */ typedef ISC_LIST(isc_buffer_t) isc_bufferlist_t; /*%< Buffer List */ typedef struct isc_constregion isc_constregion_t; /*%< Const region */ typedef struct isc_consttextregion isc_consttextregion_t; /*%< Const Text Region */ typedef struct isc_counter isc_counter_t; /*%< Counter */ typedef int16_t isc_dscp_t; /*%< Diffserv code point */ typedef struct isc_entropy isc_entropy_t; /*%< Entropy */ typedef struct isc_entropysource isc_entropysource_t; /*%< Entropy Source */ typedef struct isc_event isc_event_t; /*%< Event */ typedef ISC_LIST(isc_event_t) isc_eventlist_t; /*%< Event List */ typedef unsigned int isc_eventtype_t; /*%< Event Type */ typedef uint32_t isc_fsaccess_t; /*%< FS Access */ typedef struct isc_hash isc_hash_t; /*%< Hash */ typedef struct isc_httpd isc_httpd_t; /*%< HTTP client */ typedef void (isc_httpdfree_t)(isc_buffer_t *, void *); /*%< HTTP free function */ typedef struct isc_httpdmgr isc_httpdmgr_t; /*%< HTTP manager */ typedef struct isc_httpdurl isc_httpdurl_t; /*%< HTTP URL */ typedef void (isc_httpdondestroy_t)(void *); /*%< Callback on destroying httpd */ typedef struct isc_interface isc_interface_t; /*%< Interface */ typedef struct isc_interfaceiter isc_interfaceiter_t; /*%< Interface Iterator */ typedef struct isc_interval isc_interval_t; /*%< Interval */ typedef struct isc_lex isc_lex_t; /*%< Lex */ typedef struct isc_log isc_log_t; /*%< Log */ typedef struct isc_logcategory isc_logcategory_t; /*%< Log Category */ typedef struct isc_logconfig isc_logconfig_t; /*%< Log Configuration */ typedef struct isc_logmodule isc_logmodule_t; /*%< Log Module */ typedef struct isc_mem isc_mem_t; /*%< Memory */ typedef struct isc_mempool isc_mempool_t; /*%< Memory Pool */ typedef struct isc_msgcat isc_msgcat_t; /*%< Message Catalog */ typedef struct isc_ondestroy isc_ondestroy_t; /*%< On Destroy */ typedef struct isc_netaddr isc_netaddr_t; /*%< Net Address */ typedef struct isc_portset isc_portset_t; /*%< Port Set */ typedef struct isc_quota isc_quota_t; /*%< Quota */ typedef struct isc_random isc_random_t; /*%< Random */ typedef struct isc_ratelimiter isc_ratelimiter_t; /*%< Rate Limiter */ typedef struct isc_region isc_region_t; /*%< Region */ typedef uint64_t isc_resourcevalue_t; /*%< Resource Value */ typedef unsigned int isc_result_t; /*%< Result */ typedef struct isc_rwlock isc_rwlock_t; /*%< Read Write Lock */ typedef struct isc_sockaddr isc_sockaddr_t; /*%< Socket Address */ typedef ISC_LIST(isc_sockaddr_t) isc_sockaddrlist_t; /*%< Socket Address List */ typedef struct isc_socket isc_socket_t; /*%< Socket */ typedef struct isc_socketevent isc_socketevent_t; /*%< Socket Event */ typedef struct isc_socketmgr isc_socketmgr_t; /*%< Socket Manager */ typedef struct isc_stats isc_stats_t; /*%< Statistics */ #if defined(_WIN32) && !defined(_WIN64) typedef int_fast32_t isc_statscounter_t; /*%< Statistics Counter */ #else typedef int_fast64_t isc_statscounter_t; #endif typedef struct isc_symtab isc_symtab_t; /*%< Symbol Table */ typedef struct isc_task isc_task_t; /*%< Task */ typedef ISC_LIST(isc_task_t) isc_tasklist_t; /*%< Task List */ typedef struct isc_taskmgr isc_taskmgr_t; /*%< Task Manager */ typedef struct isc_textregion isc_textregion_t; /*%< Text Region */ typedef struct isc_time isc_time_t; /*%< Time */ typedef struct isc_timer isc_timer_t; /*%< Timer */ typedef struct isc_timermgr isc_timermgr_t; /*%< Timer Manager */ typedef isc_result_t (*isc_entropy_getdata_t)(void *, unsigned int, unsigned int *, unsigned int); typedef void (*isc_taskaction_t)(isc_task_t *, isc_event_t *); typedef int (*isc_sockfdwatch_t)(isc_task_t *, isc_socket_t *, void *, int); /* The following cannot be listed alphabetically due to forward reference */ typedef isc_result_t (isc_httpdaction_t)(const char *url, isc_httpdurl_t *urlinfo, const char *querystring, const char *headers, void *arg, unsigned int *retcode, const char **retmsg, const char **mimetype, isc_buffer_t *body, isc_httpdfree_t **freecb, void **freecb_args); typedef bool (isc_httpdclientok_t)(const isc_sockaddr_t *, void *); /*% Resource */ typedef enum { isc_resource_coresize = 1, isc_resource_cputime, isc_resource_datasize, isc_resource_filesize, isc_resource_lockedmemory, isc_resource_openfiles, isc_resource_processes, isc_resource_residentsize, isc_resource_stacksize } isc_resource_t; /*% Statistics formats (text file or XML) */ typedef enum { isc_statsformat_file, isc_statsformat_xml, isc_statsformat_json } isc_statsformat_t; #endif /* ISC_TYPES_H */ PKֺ1]D&&stat.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STAT_H #define ISC_STAT_H 1 /***** ***** Module Info *****/ /* * Portable support. * * This module is responsible for defining S_IS??? macros. * * MP: * No impact. * * Reliability: * No anticipated impact. * * Resources: * N/A. * * Security: * No anticipated impact. * */ /*** *** Imports. ***/ #include #include #endif /* ISC_STAT_H */ PKֺ1]mp) commandline.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_COMMANDLINE_H #define ISC_COMMANDLINE_H 1 /*! \file isc/commandline.h */ #include #include #include #include /*% Index into parent argv vector. */ LIBISC_EXTERNAL_DATA extern int isc_commandline_index; /*% Character checked for validity. */ LIBISC_EXTERNAL_DATA extern int isc_commandline_option; /*% Argument associated with option. */ LIBISC_EXTERNAL_DATA extern char *isc_commandline_argument; /*% For printing error messages. */ LIBISC_EXTERNAL_DATA extern char *isc_commandline_progname; /*% Print error message. */ LIBISC_EXTERNAL_DATA extern bool isc_commandline_errprint; /*% Reset getopt. */ LIBISC_EXTERNAL_DATA extern bool isc_commandline_reset; ISC_LANG_BEGINDECLS int isc_commandline_parse(int argc, char * const *argv, const char *options); /*%< * Parse a command line (similar to getopt()) */ isc_result_t isc_commandline_strtoargv(isc_mem_t *mctx, char *s, unsigned int *argcp, char ***argvp, unsigned int n); /*%< * Tokenize the string "s" into whitespace-separated words, * returning the number of words in '*argcp' and an array * of pointers to the words in '*argvp'. The caller * must free the array using isc_mem_free(). The string * is modified in-place. */ ISC_LANG_ENDDECLS #endif /* ISC_COMMANDLINE_H */ PKֺ1]magic.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_MAGIC_H #define ISC_MAGIC_H 1 #include /*! \file isc/magic.h */ typedef struct { unsigned int magic; } isc__magic_t; /*% * To use this macro the magic number MUST be the first thing in the * structure, and MUST be of type "unsigned int". * The intent of this is to allow magic numbers to be checked even though * the object is otherwise opaque. */ #define ISC_MAGIC_VALID(a,b) (ISC_LIKELY((a) != NULL) && \ ISC_LIKELY(((const isc__magic_t *)(a))->magic == (b))) #define ISC_MAGIC(a, b, c, d) ((a) << 24 | (b) << 16 | (c) << 8 | (d)) #endif /* ISC_MAGIC_H */ PKֺ1] 5?? resultclass.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_RESULTCLASS_H #define ISC_RESULTCLASS_H 1 /*! \file isc/resultclass.h * \brief Registry of Predefined Result Type Classes * * A result class number is an unsigned 16 bit number. Each class may * contain up to 65536 results. A result code is formed by adding the * result number within the class to the class number multiplied by 65536. * * Classes < 1024 are reserved for ISC use. * Result classes >= 1024 and <= 65535 are reserved for application use. */ #define ISC_RESULTCLASS_FROMNUM(num) ((num) << 16) #define ISC_RESULTCLASS_TONUM(rclass) ((rclass) >> 16) #define ISC_RESULTCLASS_SIZE 65536 #define ISC_RESULTCLASS_INCLASS(rclass, result) \ ((rclass) == ((result) & 0xFFFF0000)) #define ISC_RESULTCLASS_ISC ISC_RESULTCLASS_FROMNUM(0) #define ISC_RESULTCLASS_DNS ISC_RESULTCLASS_FROMNUM(1) #define ISC_RESULTCLASS_DST ISC_RESULTCLASS_FROMNUM(2) #define ISC_RESULTCLASS_DNSRCODE ISC_RESULTCLASS_FROMNUM(3) #define ISC_RESULTCLASS_OMAPI ISC_RESULTCLASS_FROMNUM(4) #define ISC_RESULTCLASS_ISCCC ISC_RESULTCLASS_FROMNUM(5) #define ISC_RESULTCLASS_DHCP ISC_RESULTCLASS_FROMNUM(6) #define ISC_RESULTCLASS_PK11 ISC_RESULTCLASS_FROMNUM(7) #endif /* ISC_RESULTCLASS_H */ PKֺ1])regex.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_REGEX_H #define ISC_REGEX_H 1 /*! \file isc/regex.h */ #include #include ISC_LANG_BEGINDECLS int isc_regex_validate(const char *expression); /*%< * Check a regular expression for syntactic correctness. * * Returns: *\li -1 on error. *\li the number of groups in the expression. */ ISC_LANG_ENDDECLS #endif /* ISC_REGEX_H */ PKֺ1]9   strerror.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STRERROR_H #define ISC_STRERROR_H /*! \file */ #include #include ISC_LANG_BEGINDECLS /*% String Error Size */ #define ISC_STRERRORSIZE 128 /*% * Provide a thread safe wrapper to strerror(). * * Requires: * 'buf' to be non NULL. */ void isc__strerror(int num, char *buf, size_t bufsize); ISC_LANG_ENDDECLS #endif /* ISC_STRERROR_H */ PKֺ1]region.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_REGION_H #define ISC_REGION_H 1 /*! \file isc/region.h */ #include #include struct isc_region { unsigned char * base; unsigned int length; }; struct isc_textregion { char * base; unsigned int length; }; /* XXXDCL questionable ... bears discussion. we have been putting off * discussing the region api. */ struct isc_constregion { const void * base; unsigned int length; }; struct isc_consttextregion { const char * base; unsigned int length; }; /*@{*/ /*! * The region structure is not opaque, and is usually directly manipulated. * Some macros are defined below for convenience. */ #define isc_region_consume(r,l) \ do { \ isc_region_t *_r = (r); \ unsigned int _l = (l); \ INSIST(_r->length >= _l); \ _r->base += _l; \ _r->length -= _l; \ } while (0) #define isc_textregion_consume(r,l) \ do { \ isc_textregion_t *_r = (r); \ unsigned int _l = (l); \ INSIST(_r->length >= _l); \ _r->base += _l; \ _r->length -= _l; \ } while (0) #define isc_constregion_consume(r,l) \ do { \ isc_constregion_t *_r = (r); \ unsigned int _l = (l); \ INSIST(_r->length >= _l); \ _r->base += _l; \ _r->length -= _l; \ } while (0) /*@}*/ ISC_LANG_BEGINDECLS int isc_region_compare(isc_region_t *r1, isc_region_t *r2); /*%< * Compares the contents of two regions * * Requires: *\li 'r1' is a valid region *\li 'r2' is a valid region * * Returns: *\li < 0 if r1 is lexicographically less than r2 *\li = 0 if r1 is lexicographically identical to r2 *\li > 0 if r1 is lexicographically greater than r2 */ ISC_LANG_ENDDECLS #endif /* ISC_REGION_H */ PKֺ1]o[[radix.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #include #include #include #include #include #include #include #ifndef _RADIX_H #define _RADIX_H #define NETADDR_TO_PREFIX_T(na,pt,bits,is_ecs) \ do { \ const void *p = na; \ memset(&(pt), 0, sizeof(pt)); \ if (p != NULL) { \ (pt).family = (na)->family; \ (pt).bitlen = (bits); \ if ((pt).family == AF_INET6) { \ memmove(&(pt).add.sin6, &(na)->type.in6, \ ((bits)+7)/8); \ } else \ memmove(&(pt).add.sin, &(na)->type.in, \ ((bits)+7)/8); \ } else { \ (pt).family = AF_UNSPEC; \ (pt).bitlen = 0; \ } \ (pt).ecs = is_ecs; \ isc_refcount_init(&(pt).refcount, 0); \ } while(0) typedef struct isc_prefix { isc_mem_t *mctx; unsigned int family; /* AF_INET | AF_INET6, or AF_UNSPEC for "any" */ unsigned int bitlen; /* 0 for "any" */ bool ecs; /* true for an EDNS client subnet address */ isc_refcount_t refcount; union { struct in_addr sin; struct in6_addr sin6; } add; } isc_prefix_t; typedef void (*isc_radix_destroyfunc_t)(void *); typedef void (*isc_radix_processfunc_t)(isc_prefix_t *, void **); #define isc_prefix_tochar(prefix) ((char *)&(prefix)->add.sin) #define isc_prefix_touchar(prefix) ((u_char *)&(prefix)->add.sin) /* * We need "first match" when we search the radix tree to preserve * compatibility with the existing ACL implementation. Radix trees * naturally lend themselves to "best match". In order to get "first match" * behavior, we keep track of the order in which entries are added to the * tree--and when a search is made, we find all matching entries, and * return the one that was added first. * * An IPv4 prefix and an IPv6 prefix may share a radix tree node if they * have the same length and bit pattern (e.g., 127/8 and 7f::/8). Also, * a node that matches a client address may also match an EDNS client * subnet address. To disambiguate between these, node_num and data * are four-element arrays; * * - node_num[0] and data[0] are used for IPv4 client addresses * - node_num[1] and data[1] for IPv4 client subnet addresses * - node_num[2] and data[2] are used for IPv6 client addresses * - node_num[3] and data[3] for IPv6 client subnet addresses * * A prefix of 0/0 (aka "any" or "none"), is always stored as IPv4, * but matches IPv6 addresses too, as well as all client subnet * addresses. */ #define RADIX_NOECS 0 #define RADIX_ECS 2 #define RADIX_V4 0 #define RADIX_V6 1 #define RADIX_V4_ECS 2 #define RADIX_V6_ECS 3 #define RADIX_FAMILIES 4 #define ISC_RADIX_FAMILY(p) \ ((((p)->family == AF_INET6) ? RADIX_V6 : RADIX_V4) + \ ((p)->ecs ? RADIX_ECS : RADIX_NOECS)) typedef struct isc_radix_node { isc_mem_t *mctx; uint32_t bit; /* bit length of the prefix */ isc_prefix_t *prefix; /* who we are in radix tree */ struct isc_radix_node *l, *r; /* left and right children */ struct isc_radix_node *parent; /* may be used */ void *data[RADIX_FAMILIES]; /* pointers to IPv4 and IPV6 data */ int node_num[RADIX_FAMILIES]; /* which node this was in the tree, or -1 for glue nodes */ } isc_radix_node_t; #define RADIX_TREE_MAGIC ISC_MAGIC('R','d','x','T'); #define RADIX_TREE_VALID(a) ISC_MAGIC_VALID(a, RADIX_TREE_MAGIC); typedef struct isc_radix_tree { unsigned int magic; isc_mem_t *mctx; isc_radix_node_t *head; uint32_t maxbits; /* for IP, 32 bit addresses */ int num_active_node; /* for debugging purposes */ int num_added_node; /* total number of nodes */ } isc_radix_tree_t; isc_result_t isc_radix_search(isc_radix_tree_t *radix, isc_radix_node_t **target, isc_prefix_t *prefix); /*%< * Search 'radix' for the best match to 'prefix'. * Return the node found in '*target'. * * Requires: * \li 'radix' to be valid. * \li 'target' is not NULL and "*target" is NULL. * \li 'prefix' to be valid. * * Returns: * \li ISC_R_NOTFOUND * \li ISC_R_SUCCESS */ isc_result_t isc_radix_insert(isc_radix_tree_t *radix, isc_radix_node_t **target, isc_radix_node_t *source, isc_prefix_t *prefix); /*%< * Insert 'source' or 'prefix' into the radix tree 'radix'. * Return the node added in 'target'. * * Requires: * \li 'radix' to be valid. * \li 'target' is not NULL and "*target" is NULL. * \li 'prefix' to be valid or 'source' to be non NULL and contain * a valid prefix. * * Returns: * \li ISC_R_NOMEMORY * \li ISC_R_SUCCESS */ void isc_radix_remove(isc_radix_tree_t *radix, isc_radix_node_t *node); /*%< * Remove the node 'node' from the radix tree 'radix'. * * Requires: * \li 'radix' to be valid. * \li 'node' to be valid. */ isc_result_t isc_radix_create(isc_mem_t *mctx, isc_radix_tree_t **target, int maxbits); /*%< * Create a radix tree with a maximum depth of 'maxbits'; * * Requires: * \li 'mctx' to be valid. * \li 'target' to be non NULL and '*target' to be NULL. * \li 'maxbits' to be less than or equal to RADIX_MAXBITS. * * Returns: * \li ISC_R_NOMEMORY * \li ISC_R_SUCCESS */ void isc_radix_destroy(isc_radix_tree_t *radix, isc_radix_destroyfunc_t func); /*%< * Destroy a radix tree optionally calling 'func' to clean up node data. * * Requires: * \li 'radix' to be valid. */ void isc_radix_process(isc_radix_tree_t *radix, isc_radix_processfunc_t func); /*%< * Walk a radix tree calling 'func' to process node data. * * Requires: * \li 'radix' to be valid. * \li 'func' to point to a function. */ #define RADIX_MAXBITS 128 #define RADIX_NBIT(x) (0x80 >> ((x) & 0x7f)) #define RADIX_NBYTE(x) ((x) >> 3) #define RADIX_WALK(Xhead, Xnode) \ do { \ isc_radix_node_t *Xstack[RADIX_MAXBITS+1]; \ isc_radix_node_t **Xsp = Xstack; \ isc_radix_node_t *Xrn = (Xhead); \ while ((Xnode = Xrn)) { \ if (Xnode->prefix) #define RADIX_WALK_END \ if (Xrn->l) { \ if (Xrn->r) { \ *Xsp++ = Xrn->r; \ } \ Xrn = Xrn->l; \ } else if (Xrn->r) { \ Xrn = Xrn->r; \ } else if (Xsp != Xstack) { \ Xrn = *(--Xsp); \ } else { \ Xrn = (isc_radix_node_t *) 0; \ } \ } \ } while (0) #endif /* _RADIX_H */ PKֺ1]˵~}}lang.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LANG_H #define ISC_LANG_H 1 /*! \file isc/lang.h */ #ifdef __cplusplus #define ISC_LANG_BEGINDECLS extern "C" { #define ISC_LANG_ENDDECLS } #else #define ISC_LANG_BEGINDECLS #define ISC_LANG_ENDDECLS #endif #endif /* ISC_LANG_H */ PKֺ1]"ā@@int.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #pragma once /*! \file */ #include typedef int8_t isc_int8_t; typedef uint8_t isc_uint8_t; typedef int16_t isc_int16_t; typedef uint16_t isc_uint16_t; typedef int32_t isc_int32_t; typedef uint32_t isc_uint32_t; typedef int64_t isc_int64_t; typedef uint64_t isc_uint64_t; #define ISC_INT8_MIN INT8_MIN #define ISC_INT8_MAX INT8_MAX #define ISC_UINT8_MAX UINT8_MAX #define ISC_INT16_MIN INT16_MIN #define ISC_INT16_MAX INT16_MAX #define ISC_UINT16_MAX UINT16_MAX #define ISC_INT32_MIN INT32_MIN #define ISC_INT32_MAX INT32_MAX #define ISC_UINT32_MAX UINT32_MAX #define ISC_INT64_MIN INT64_MIN #define ISC_INT64_MAX INT64_MAX #define ISC_UINT64_MAX UINT64_MAX PKֺ1]B)) stdtime.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_STDTIME_H #define ISC_STDTIME_H 1 /*! \file */ #include #include /*% * It's public information that 'isc_stdtime_t' is an unsigned integral type. * Applications that want maximum portability should not assume anything * about its size. */ typedef uint32_t isc_stdtime_t; ISC_LANG_BEGINDECLS /* */ void isc_stdtime_get(isc_stdtime_t *t); /*%< * Set 't' to the number of seconds since 00:00:00 UTC, January 1, 1970. * * Requires: * *\li 't' is a valid pointer. */ #define isc_stdtime_convert32(t, t32p) (*(t32p) = t) /* * Convert the standard time to its 32-bit version. */ ISC_LANG_ENDDECLS #endif /* ISC_STDTIME_H */ PKֺ1]33 backtrace.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ /*! \file isc/backtrace.h * \brief provide a back trace of the running process to help debug problems. * * This module tries to get a back trace of the process using some platform * dependent way when available. It also manages an internal symbol table * that maps function addresses used in the process to their textual symbols. * This module is expected to be used to help debug when some fatal error * happens. * * IMPORTANT NOTE: since the (major) intended use case of this module is * dumping a back trace on a fatal error, normally followed by self termination, * functions defined in this module generally doesn't employ assertion checks * (if it did, a program bug could cause infinite recursive calls to a * backtrace function). These functions still perform minimal checks and return * ISC_R_FAILURE if they detect an error, but the caller should therefore be * very careful about the use of these functions, and generally discouraged to * use them except in an exit path. The exception is * isc_backtrace_getsymbolfromindex(), which is expected to be used in a * non-error-handling context and validates arguments with assertion checks. */ #ifndef ISC_BACKTRACE_H #define ISC_BACKTRACE_H 1 /*** *** Imports ***/ #include /*** *** Types ***/ struct isc_backtrace_symmap { void *addr; const char *symbol; }; LIBISC_EXTERNAL_DATA extern const int isc__backtrace_nsymbols; LIBISC_EXTERNAL_DATA extern const isc_backtrace_symmap_t isc__backtrace_symtable[]; /*** *** Functions ***/ ISC_LANG_BEGINDECLS isc_result_t isc_backtrace_gettrace(void **addrs, int maxaddrs, int *nframes); /*%< * Get a back trace of the running process above this function itself. On * success, addrs[i] will store the address of the call point of the i-th * stack frame (addrs[0] is the caller of this function). *nframes will store * the total number of frames. * * Requires (note that these are not ensured by assertion checks, see above): * *\li 'addrs' is a valid array containing at least 'maxaddrs' void * entries. * *\li 'nframes' must be non NULL. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_FAILURE *\li #ISC_R_NOTFOUND *\li #ISC_R_NOTIMPLEMENTED */ isc_result_t isc_backtrace_getsymbolfromindex(int index, const void **addrp, const char **symbolp); /*%< * Returns the content of the internal symbol table of the given index. * On success, *addrsp and *symbolp point to the address and the symbol of * the 'index'th entry of the table, respectively. If 'index' is not in the * range of the symbol table, ISC_R_RANGE will be returned. * * Requires * *\li 'addrp' must be non NULL && '*addrp' == NULL. * *\li 'symbolp' must be non NULL && '*symbolp' == NULL. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_RANGE */ isc_result_t isc_backtrace_getsymbol(const void *addr, const char **symbolp, unsigned long *offsetp); /*%< * Searches the internal symbol table for the symbol that most matches the * given 'addr'. On success, '*symbolp' will point to the name of function * to which the address 'addr' belong, and '*offsetp' will store the offset * from the function's entry address to 'addr'. * * Requires (note that these are not ensured by assertion checks, see above): * *\li 'symbolp' must be non NULL && '*symbolp' == NULL. * *\li 'offsetp' must be non NULL. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_FAILURE *\li #ISC_R_NOTFOUND */ ISC_LANG_ENDDECLS #endif /* ISC_BACKTRACE_H */ PKֺ1]ώhash.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_HASH_H #define ISC_HASH_H 1 #include #include #include /***** ***** Module Info *****/ /*! \file isc/hash.h * * \brief The hash API * provides an unpredictable hash value for variable length data. * A hash object contains a random vector (which is hidden from clients * of this API) to make the actual hash value unpredictable. * * The algorithm used in the API guarantees the probability of hash * collision; in the current implementation, as long as the values stored * in the random vector are unpredictable, the probability of hash * collision between arbitrary two different values is at most 1/2^16. * * Although the API is generic about the hash keys, it mainly expects * DNS names (and sometimes IPv4/v6 addresses) as inputs. It has an * upper limit of the input length, and may run slow to calculate the * hash values for large inputs. * * This API is designed to be general so that it can provide multiple * different hash contexts that have different random vectors. However, * it should be typical to have a single context for an entire system. * To support such cases, the API also provides a single-context mode. * * \li MP: * The hash object is almost read-only. Once the internal random vector * is initialized, no write operation will occur, and there will be no * need to lock the object to calculate actual hash values. * * \li Reliability: * In some cases this module uses low-level data copy to initialize the * random vector. Errors in this part are likely to crash the server or * corrupt memory. * * \li Resources: * A buffer, used as a random vector for calculating hash values. * * \li Security: * This module intends to provide unpredictable hash values in * adversarial environments in order to avoid denial of service attacks * to hash buckets. * Its unpredictability relies on the quality of entropy to build the * random vector. * * \li Standards: * None. */ /*** *** Imports ***/ #include /*** *** Functions ***/ ISC_LANG_BEGINDECLS LIBISC_EXTERNAL_DATA extern isc_hash_t *isc_hashctx; isc_result_t isc_hash_ctxcreate(isc_mem_t *mctx, isc_entropy_t *entropy, size_t limit, isc_hash_t **hctx); isc_result_t isc_hash_create(isc_mem_t *mctx, isc_entropy_t *entropy, size_t limit); /*!< * \brief Create a new hash object. * * isc_hash_ctxcreate() creates a different object. * * isc_hash_create() creates a module-internal object to support the * single-context mode. It should be called only once. * * 'entropy' must be NULL or a valid entropy object. If 'entropy' is NULL, * pseudo random values will be used to build the random vector, which may * weaken security. * * 'limit' specifies the maximum number of hash keys. If it is too large, * these functions may fail. */ void isc_hash_ctxattach(isc_hash_t *hctx, isc_hash_t **hctxp) ISC_DEPRECATED; /*!< * \brief Attach to a hash object. * * This function is only necessary for the multiple-context mode. */ void isc_hash_ctxdetach(isc_hash_t **hctxp) ISC_DEPRECATED; /*!< * \brief Detach from a hash object. * * This function is for the multiple-context mode, and takes a valid * hash object as an argument. */ void isc_hash_destroy(void); /*!< * \brief This function is for the single-context mode, and is expected to be used * as a counterpart of isc_hash_create(). * * A valid module-internal hash object must have been created, and this * function should be called only once. */ /*@{*/ void isc_hash_ctxinit(isc_hash_t *hctx); void isc_hash_init(void); /*!< * \brief Initialize a hash object. * * It fills in the random vector with a proper * source of entropy, which is typically from the entropy object specified * at the creation. Thus, it is desirable to call these functions after * initializing the entropy object with some good entropy sources. * * These functions should be called before the first hash calculation. * * isc_hash_ctxinit() is for the multiple-context mode, and takes a valid hash * object as an argument. * * isc_hash_init() is for the single-context mode. A valid module-internal * hash object must have been created, and this function should be called only * once. */ /*@}*/ /*@{*/ unsigned int isc_hash_ctxcalc(isc_hash_t *hctx, const unsigned char *key, unsigned int keylen, bool case_sensitive) ISC_DEPRECATED; unsigned int isc_hash_calc(const unsigned char *key, unsigned int keylen, bool case_sensitive) ISC_DEPRECATED; /*!< * \brief Calculate a hash value. * * isc_hash_ctxinit() is for the multiple-context mode, and takes a valid hash * object as an argument. * * isc_hash_init() is for the single-context mode. A valid module-internal * hash object must have been created. * * 'key' is the hash key, which is a variable length buffer. * * 'keylen' specifies the key length, which must not be larger than the limit * specified for the corresponding hash object. * * 'case_sensitive' specifies whether the hash key should be treated as * case_sensitive values. It should typically be false if the hash key * is a DNS name. */ /*@}*/ void isc__hash_setvec(const uint16_t *vec) ISC_DEPRECATED; /*!< * \brief Set the contents of the random vector used in hashing. * * WARNING: This function is meant to be used only in testing code. It * must not be used anywhere in normally running code. * * The hash context must have been created beforehand, otherwise this * function is a nop. * * 'vec' is not documented here on purpose. You should know what you are * doing before using this function. */ const void * isc_hash_get_initializer(void); void isc_hash_set_initializer(const void *initializer); uint32_t isc_hash_function(const void *data, size_t length, bool case_sensitive, const uint32_t *previous_hashp); uint32_t isc_hash_function_reverse(const void *data, size_t length, bool case_sensitive, const uint32_t *previous_hashp); /*!< * \brief Calculate a hash over data. * * This hash function is useful for hashtables. The hash function is * opaque and not important to the caller. The returned hash values are * non-deterministic and will have different mapping every time a * process using this library is run, but will have uniform * distribution. * * isc_hash_function() calculates the hash from start to end over the * input data. isc_hash_function_reverse() calculates the hash from the * end to the start over the input data. The difference in order is * useful in incremental hashing; for example, a previously hashed * value for 'com' can be used as input when hashing 'example.com'. * * This is a new variant of isc_hash_calc() and will supersede * isc_hash_calc() eventually. * * 'data' is the data to be hashed. * * 'length' is the size of the data to be hashed. * * 'case_sensitive' specifies whether the hash key should be treated as * case_sensitive values. It should typically be false if the hash key * is a DNS name. * * 'previous_hashp' is a pointer to a previous hash value returned by * this function. It can be used to perform incremental hashing. NULL * must be passed during first calls. */ ISC_LANG_ENDDECLS #endif /* ISC_HASH_H */ PKֺ1]PA,,lib.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LIB_H #define ISC_LIB_H 1 /*! \file isc/lib.h */ #include #include ISC_LANG_BEGINDECLS LIBISC_EXTERNAL_DATA extern isc_msgcat_t *isc_msgcat; void isc_lib_initmsgcat(void); /*!< * \brief Initialize the ISC library's message catalog, isc_msgcat, if it * has not already been initialized. */ void isc_lib_register(void); /*!< * \brief Register the ISC library implementations for some base services * such as memory or event management and handling socket or timer events. * An external application that wants to use the ISC library must call this * function very early in main(). */ ISC_LANG_ENDDECLS #endif /* ISC_LIB_H */ PKֺ1]6gQ2%% platform.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_PLATFORM_H #define ISC_PLATFORM_H 1 /*! \file */ /***** ***** Platform-dependent defines. *****/ /*** *** Network. ***/ /*! \brief * Define if this system needs the header file included * for full IPv6 support (pretty much only UnixWare). */ #undef ISC_PLATFORM_NEEDNETINETIN6H /*! \brief * Define if this system needs the header file included * to support in6_pkinfo (pretty much only BSD/OS). */ #undef ISC_PLATFORM_NEEDNETINET6IN6H /*! \brief * If sockaddrs on this system have an sa_len field, ISC_PLATFORM_HAVESALEN * will be defined. */ #undef ISC_PLATFORM_HAVESALEN /*! \brief * If this system has the IPv6 structure definitions, ISC_PLATFORM_HAVEIPV6 * will be defined. */ #define ISC_PLATFORM_HAVEIPV6 1 /*! \brief * If this system is missing in6addr_any, ISC_PLATFORM_NEEDIN6ADDRANY will * be defined. */ #undef ISC_PLATFORM_NEEDIN6ADDRANY /*! \brief * If this system is missing in6addr_loopback, ISC_PLATFORM_NEEDIN6ADDRLOOPBACK * will be defined. */ #undef ISC_PLATFORM_NEEDIN6ADDRLOOPBACK /*! \brief * If this system has in6_pktinfo, ISC_PLATFORM_HAVEIN6PKTINFO will be * defined. */ #define ISC_PLATFORM_HAVEIN6PKTINFO 1 /*! \brief * If this system has in_addr6, rather than in6_addr, ISC_PLATFORM_HAVEINADDR6 * will be defined. */ #undef ISC_PLATFORM_HAVEINADDR6 /*! \brief * If this system has sin6_scope_id, ISC_PLATFORM_HAVESCOPEID will be defined. */ #define ISC_PLATFORM_HAVESCOPEID 1 /*! \brief * If this system needs inet_ntop(), ISC_PLATFORM_NEEDNTOP will be defined. */ #undef ISC_PLATFORM_NEEDNTOP /*! \brief * If this system needs inet_pton(), ISC_PLATFORM_NEEDPTON will be defined. */ #undef ISC_PLATFORM_NEEDPTON /*! \brief * If this system needs in_port_t, ISC_PLATFORM_NEEDPORTT will be defined. */ #undef ISC_PLATFORM_NEEDPORTT /*! \brief * Define if the system has struct lifconf which is a extended struct ifconf * for IPv6. */ #undef ISC_PLATFORM_HAVELIFCONF /*! \brief * Define if the system has struct if_laddrconf which is a extended struct * ifconf for IPv6. */ #undef ISC_PLATFORM_HAVEIF_LADDRCONF /*! \brief * Define if the system has struct if_laddrreq. */ #undef ISC_PLATFORM_HAVEIF_LADDRREQ /*! \brief * Define either ISC_PLATFORM_BSD44MSGHDR or ISC_PLATFORM_BSD43MSGHDR. */ #define ISC_NET_BSD44MSGHDR 1 /*! \brief * Define if the system supports if_nametoindex. */ #define ISC_PLATFORM_HAVEIFNAMETOINDEX 1 /*! \brief * Define on some UnixWare systems to fix erroneous definitions of various * IN6_IS_ADDR_* macros. */ #undef ISC_PLATFORM_FIXIN6ISADDR /*! \brief * Define if the system has struct sockaddr_storage. */ #define ISC_PLATFORM_HAVESOCKADDRSTORAGE 1 /*! \brief * Define if the system has TCP_FASTOPEN socket option. */ #define ISC_PLATFORM_HAVETFO 1 /*! \brief * Define if the system supports kqueue multiplexing */ #undef ISC_PLATFORM_HAVEKQUEUE /*! \brief * Define if the system supports epoll multiplexing */ #define ISC_PLATFORM_HAVEEPOLL 1 /*! \brief * Define if the system supports /dev/poll multiplexing */ #undef ISC_PLATFORM_HAVEDEVPOLL /*! \brief * Define if we want to log backtrace */ #define ISC_PLATFORM_USEBACKTRACE 1 /* *** Printing. ***/ /*! \brief * If this system needs vsnprintf() and snprintf(), ISC_PLATFORM_NEEDVSNPRINTF * will be defined. */ #undef ISC_PLATFORM_NEEDVSNPRINTF /*! \brief * If this system need a modern sprintf() that returns (int) not (char*). */ #undef ISC_PLATFORM_NEEDSPRINTF /*! \brief * If this system need a modern printf() that format size %z (size_t). */ #undef ISC_PLATFORM_NEEDPRINTF /*! \brief * If this system need a modern fprintf() that format size %z (size_t). */ #undef ISC_PLATFORM_NEEDFPRINTF /*** *** String functions. ***/ /* * If the system needs strsep(), ISC_PLATFORM_NEEDSTRSEP will be defined. */ #undef ISC_PLATFORM_NEEDSTRSEP /* * If the system needs strlcpy(), ISC_PLATFORM_NEEDSTRLCPY will be defined. */ #define ISC_PLATFORM_NEEDSTRLCPY 1 /* * If the system needs strlcat(), ISC_PLATFORM_NEEDSTRLCAT will be defined. */ #define ISC_PLATFORM_NEEDSTRLCAT 1 /* * Define if this system needs strtoul. */ #undef ISC_PLATFORM_NEEDSTRTOUL /* * Define if this system needs memmove. */ #undef ISC_PLATFORM_NEEDMEMMOVE /* * Define if this system needs strcasestr. */ #undef ISC_PLATFORM_NEEDSTRCASESTR /*** *** System limitations ***/ #include #ifndef NAME_MAX #define NAME_MAX 256 #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef IOV_MAX #define IOV_MAX 1024 #endif /*** *** Miscellaneous. ***/ /* * Defined if we are using threads. */ #define ISC_PLATFORM_USETHREADS 1 /* * Defined if unistd.h does not cause fd_set to be declared. */ #undef ISC_PLATFORM_NEEDSYSSELECTH /* * Defined to or for how to include * the GSSAPI header. */ #define ISC_PLATFORM_GSSAPIHEADER /* * Defined to or for how to * include the GSSAPI KRB5 header. */ #define ISC_PLATFORM_GSSAPI_KRB5_HEADER /* * Defined to or for how to include * the KRB5 header. */ #define ISC_PLATFORM_KRB5HEADER /* * Define if the system has nanosecond-level accuracy in file stats. */ #define ISC_PLATFORM_HAVESTATNSEC 1 /* * Type used for resource limits. */ #define ISC_PLATFORM_RLIMITTYPE rlim_t /* * Define if your compiler supports "long long int". */ #define ISC_PLATFORM_HAVELONGLONG 1 /* * Define if PTHREAD_ONCE_INIT should be surrounded by braces to * prevent compiler warnings (such as with gcc on Solaris 2.8). */ #undef ISC_PLATFORM_BRACEPTHREADONCEINIT /* * Used to control how extern data is linked; needed for Win32 platforms. */ #undef ISC_PLATFORM_USEDECLSPEC /* * Define if the platform has . */ #define ISC_PLATFORM_HAVESYSUNH 1 /* * If the "xadd" operation is available on this architecture, * ISC_PLATFORM_HAVEXADD will be defined. */ #define ISC_PLATFORM_HAVEXADD 1 /* * If the "xaddq" operation (64bit xadd) is available on this architecture, * ISC_PLATFORM_HAVEXADDQ will be defined. */ /* * If the 64-bit "atomic swap" operation is available on this * architecture, ISC_PLATFORM_HAVEATOMICSTOREQ" will be defined. */ #ifdef __x86_64__ #define ISC_PLATFORM_HAVEXADDQ 1 #define ISC_PLATFORM_HAVEATOMICSTOREQ 1 #else #undef ISC_PLATFORM_HAVEXADDQ #undef ISC_PLATFORM_HAVEATOMICSTOREQ #endif /* * If the 32-bit "atomic swap" operation is available on this * architecture, ISC_PLATFORM_HAVEATOMICSTORE" will be defined. */ #define ISC_PLATFORM_HAVEATOMICSTORE 1 /* * If the "compare-and-exchange" operation is available on this architecture, * ISC_PLATFORM_HAVECMPXCHG will be defined. */ #define ISC_PLATFORM_HAVECMPXCHG 1 /* * If is available on this architecture, * ISC_PLATFORM_HAVESTDATOMIC will be defined. */ #define ISC_PLATFORM_HAVESTDATOMIC 1 /* * Define if gcc ASM extension is available */ #define ISC_PLATFORM_USEGCCASM 1 /* * Define if Tru64 style ASM syntax must be used. */ #undef ISC_PLATFORM_USEOSFASM /* * Define if the standard __asm function must be used. */ #undef ISC_PLATFORM_USESTDASM /* * Define with the busy wait nop asm or function call. */ #define ISC_PLATFORM_BUSYWAITNOP asm("rep; nop") /* * Define if the platform has . */ #define ISC_PLATFORM_HAVESTRINGSH 1 /* * Define if the random functions are provided by crypto. */ #define ISC_PLATFORM_CRYPTORANDOM "openssl" /* * Define if the hash functions must be provided by OpenSSL. */ #define ISC_PLATFORM_OPENSSLHASH 1 /* * Define if AES support is wanted */ #define ISC_PLATFORM_WANTAES 1 /* * Defines for the noreturn attribute. */ #define ISC_PLATFORM_NORETURN_PRE #define ISC_PLATFORM_NORETURN_POST __attribute__((noreturn)) /*** *** Windows dll support. ***/ /* * Define if MacOS style of PPC assembly must be used. * e.g. "r6", not "6", for register six. */ #undef ISC_PLATFORM_USEMACASM #ifndef ISC_PLATFORM_USEDECLSPEC #define LIBISC_EXTERNAL_DATA #define LIBDNS_EXTERNAL_DATA #define LIBISCCC_EXTERNAL_DATA #define LIBISCCFG_EXTERNAL_DATA #define LIBBIND9_EXTERNAL_DATA #define LIBTESTS_EXTERNAL_DATA #else /*! \brief ISC_PLATFORM_USEDECLSPEC */ #ifdef LIBISC_EXPORTS #define LIBISC_EXTERNAL_DATA __declspec(dllexport) #else #define LIBISC_EXTERNAL_DATA __declspec(dllimport) #endif #ifdef LIBDNS_EXPORTS #define LIBDNS_EXTERNAL_DATA __declspec(dllexport) #else #define LIBDNS_EXTERNAL_DATA __declspec(dllimport) #endif #ifdef LIBISCCC_EXPORTS #define LIBISCCC_EXTERNAL_DATA __declspec(dllexport) #else #define LIBISCCC_EXTERNAL_DATA __declspec(dllimport) #endif #ifdef LIBISCCFG_EXPORTS #define LIBISCCFG_EXTERNAL_DATA __declspec(dllexport) #else #define LIBISCCFG_EXTERNAL_DATA __declspec(dllimport) #endif #ifdef LIBBIND9_EXPORTS #define LIBBIND9_EXTERNAL_DATA __declspec(dllexport) #else #define LIBBIND9_EXTERNAL_DATA __declspec(dllimport) #endif #ifdef LIBTESTS_EXPORTS #define LIBTESTS_EXTERNAL_DATA __declspec(dllexport) #else #define LIBTESTS_EXTERNAL_DATA __declspec(dllimport) #endif #endif /*! \brief ISC_PLATFORM_USEDECLSPEC */ /* * Tell emacs to use C mode for this file. * * Local Variables: * mode: c * End: */ #endif /* ISC_PLATFORM_H */ PKֺ1]"kB))))util.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_UTIL_H #define ISC_UTIL_H 1 #include /*! \file isc/util.h * NOTE: * * This file is not to be included from any (or other) library * files. * * \brief * Including this file puts several macros in your name space that are * not protected (as all the other ISC functions/macros do) by prepending * ISC_ or isc_ to the name. */ /*** *** General Macros. ***/ /*% * Use this to hide unused function arguments. * \code * int * foo(char *bar) * { * UNUSED(bar); * } * \endcode */ #define UNUSED(x) (void)(x) /*% * The opposite: silent warnings about stored values which are never read. */ #define POST(x) (void)(x) #define ISC_MAX(a, b) ((a) > (b) ? (a) : (b)) #define ISC_MIN(a, b) ((a) < (b) ? (a) : (b)) #define ISC_CLAMP(v, x, y) ((v) < (x) ? (x) : ((v) > (y) ? (y) : (v))) /*% * Use this to remove the const qualifier of a variable to assign it to * a non-const variable or pass it as a non-const function argument ... * but only when you are sure it won't then be changed! * This is necessary to sometimes shut up some compilers * (as with gcc -Wcast-qual) when there is just no other good way to avoid the * situation. */ #define DE_CONST(konst, var) \ do { \ union { const void *k; void *v; } _u; \ _u.k = konst; \ var = _u.v; \ } while (0) #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) /*% * Use this in translation units that would otherwise be empty, to * suppress compiler warnings. */ #define EMPTY_TRANSLATION_UNIT extern int isc__empty; /*% * We use macros instead of calling the routines directly because * the capital letters make the locking stand out. * We RUNTIME_CHECK for success since in general there's no way * for us to continue if they fail. */ #ifdef ISC_UTIL_TRACEON #define ISC_UTIL_TRACE(a) a #include /* Required for fprintf/stderr when tracing. */ #include /* Required for isc_msgcat when tracing. */ #else #define ISC_UTIL_TRACE(a) #endif #include /* Contractual promise. */ #define LOCK(lp) do { \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_LOCKING, "LOCKING"), \ (lp), __FILE__, __LINE__)); \ RUNTIME_CHECK(isc_mutex_lock((lp)) == ISC_R_SUCCESS); \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_LOCKED, "LOCKED"), \ (lp), __FILE__, __LINE__)); \ } while (0) #define UNLOCK(lp) do { \ RUNTIME_CHECK(isc_mutex_unlock((lp)) == ISC_R_SUCCESS); \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_UNLOCKED, "UNLOCKED"), \ (lp), __FILE__, __LINE__)); \ } while (0) #define DESTROYLOCK(lp) \ RUNTIME_CHECK(isc_mutex_destroy((lp)) == ISC_R_SUCCESS) #define BROADCAST(cvp) do { \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_BROADCAST, "BROADCAST"),\ (cvp), __FILE__, __LINE__)); \ RUNTIME_CHECK(isc_condition_broadcast((cvp)) == ISC_R_SUCCESS); \ } while (0) #define SIGNAL(cvp) do { \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_SIGNAL, "SIGNAL"), \ (cvp), __FILE__, __LINE__)); \ RUNTIME_CHECK(isc_condition_signal((cvp)) == ISC_R_SUCCESS); \ } while (0) #define WAIT(cvp, lp) do { \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_UTILWAIT, "WAIT"), \ (cvp), \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_LOCK, "LOCK"), \ (lp), __FILE__, __LINE__)); \ RUNTIME_CHECK(isc_condition_wait((cvp), (lp)) == ISC_R_SUCCESS); \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p %s %p %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_WAITED, "WAITED"), \ (cvp), \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_LOCKED, "LOCKED"), \ (lp), __FILE__, __LINE__)); \ } while (0) /* * isc_condition_waituntil can return ISC_R_TIMEDOUT, so we * don't RUNTIME_CHECK the result. * * XXX Also, can't really debug this then... */ #define WAITUNTIL(cvp, lp, tp) \ isc_condition_waituntil((cvp), (lp), (tp)) #define RWLOCK(lp, t) do { \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p, %d %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_RWLOCK, "RWLOCK"), \ (lp), (t), __FILE__, __LINE__)); \ RUNTIME_CHECK(isc_rwlock_lock((lp), (t)) == ISC_R_SUCCESS); \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p, %d %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_RWLOCKED, "RWLOCKED"), \ (lp), (t), __FILE__, __LINE__)); \ } while (0) #define RWUNLOCK(lp, t) do { \ ISC_UTIL_TRACE(fprintf(stderr, "%s %p, %d %s %d\n", \ isc_msgcat_get(isc_msgcat, ISC_MSGSET_UTIL, \ ISC_MSG_RWUNLOCK, "RWUNLOCK"), \ (lp), (t), __FILE__, __LINE__)); \ RUNTIME_CHECK(isc_rwlock_unlock((lp), (t)) == ISC_R_SUCCESS); \ } while (0) #define DESTROYMUTEXBLOCK(bp, n) \ RUNTIME_CHECK(isc_mutexblock_destroy((bp), (n)) == ISC_R_SUCCESS) /* * List Macros. */ #include /* Contractual promise. */ #define LIST(type) ISC_LIST(type) #define INIT_LIST(type) ISC_LIST_INIT(type) #define LINK(type) ISC_LINK(type) #define INIT_LINK(elt, link) ISC_LINK_INIT(elt, link) #define HEAD(list) ISC_LIST_HEAD(list) #define TAIL(list) ISC_LIST_TAIL(list) #define EMPTY(list) ISC_LIST_EMPTY(list) #define PREV(elt, link) ISC_LIST_PREV(elt, link) #define NEXT(elt, link) ISC_LIST_NEXT(elt, link) #define APPEND(list, elt, link) ISC_LIST_APPEND(list, elt, link) #define PREPEND(list, elt, link) ISC_LIST_PREPEND(list, elt, link) #define UNLINK(list, elt, link) ISC_LIST_UNLINK(list, elt, link) #define ENQUEUE(list, elt, link) ISC_LIST_APPEND(list, elt, link) #define DEQUEUE(list, elt, link) ISC_LIST_UNLINK(list, elt, link) #define INSERTBEFORE(li, b, e, ln) ISC_LIST_INSERTBEFORE(li, b, e, ln) #define INSERTAFTER(li, a, e, ln) ISC_LIST_INSERTAFTER(li, a, e, ln) #define APPENDLIST(list1, list2, link) ISC_LIST_APPENDLIST(list1, list2, link) /*% * Performance */ #include #ifdef HAVE_BUILTIN_UNREACHABLE #define ISC_UNREACHABLE() __builtin_unreachable(); #else #define ISC_UNREACHABLE() #endif #if !defined(__has_feature) #define __has_feature(x) 0 #endif /* GCC defines __SANITIZE_ADDRESS__, so reuse the macro for clang */ #if __has_feature(address_sanitizer) #define __SANITIZE_ADDRESS__ 1 #endif /* GCC defines __SANITIZE_THREAD__, so reuse the macro for clang */ #if __has_feature(thread_sanitizer) #define __SANITIZE_THREAD__ 1 #endif #if __SANITIZE_THREAD__ #define ISC_NO_SANITIZE_THREAD __attribute__((no_sanitize("thread"))) __attribute__((noinline)) #define ISC_NO_SANITIZE_INLINE #else /* if __SANITIZE_THREAD__ */ #define ISC_NO_SANITIZE_THREAD #define ISC_NO_SANITIZE_INLINE inline #endif /* if __SANITIZE_THREAD__ */ #ifdef UNIT_TESTING extern void mock_assert(const int result, const char* const expression, const char * const file, const int line); /* * Allow clang to determine that the following code is not reached * by calling abort() if the condition fails. The abort() will * never be executed as mock_assert() and _assert_true() longjmp * or exit if the condition is false. */ #define REQUIRE(expression) \ ((!(expression)) ? \ (mock_assert(0, #expression, __FILE__, __LINE__), abort()) : (void)0) #define ENSURE(expression) \ ((!(int)(expression)) ? \ (mock_assert(0, #expression, __FILE__, __LINE__), abort()) : (void)0) #define INSIST(expression) \ ((!(expression)) ? \ (mock_assert(0, #expression, __FILE__, __LINE__), abort()) : (void)0) #define INVARIANT(expression) \ ((!(expression)) ? \ (mock_assert(0, #expression, __FILE__, __LINE__), abort()) : (void)0) #define _assert_true(c, e, f, l) \ ((c) ? (void)0 : (_assert_true(0, e, f, l), abort())) #define _assert_int_equal(a, b, f, l) \ (((a) == (b)) ? (void)0 : (_assert_int_equal(a, b, f, l), abort())) #define _assert_int_not_equal(a, b, f, l) \ (((a) != (b)) ? (void)0 : (_assert_int_not_equal(a, b, f, l), abort())) #else /* UNIT_TESTING */ #ifndef CPPCHECK /* * Assertions */ #include /* Contractual promise. */ /*% Require Assertion */ #define REQUIRE(e) ISC_REQUIRE(e) /*% Ensure Assertion */ #define ENSURE(e) ISC_ENSURE(e) /*% Insist Assertion */ #define INSIST(e) ISC_INSIST(e) /*% Invariant Assertion */ #define INVARIANT(e) ISC_INVARIANT(e) #else /* CPPCHECK */ /*% Require Assertion */ #define REQUIRE(e) if (!(e)) abort() /*% Ensure Assertion */ #define ENSURE(e) if (!(e)) abort() /*% Insist Assertion */ #define INSIST(e) if (!(e)) abort() /*% Invariant Assertion */ #define INVARIANT(e) if (!(e)) abort() #endif /* CPPCHECK */ #endif /* UNIT_TESTING */ /* * Errors */ #include /* Contractual promise. */ /*% Unexpected Error */ #define UNEXPECTED_ERROR isc_error_unexpected /*% Fatal Error */ #define FATAL_ERROR isc_error_fatal #ifdef UNIT_TESTING #define RUNTIME_CHECK(expression) \ ((!(expression)) ? \ (mock_assert(0, #expression, __FILE__, __LINE__), abort()) : (void)0) #else /* UNIT_TESTING */ #ifndef CPPCHECK /*% Runtime Check */ #define RUNTIME_CHECK(cond) ISC_ERROR_RUNTIMECHECK(cond) #else #define RUNTIME_CHECK(e) if (!(e)) abort() #endif #endif /* UNIT_TESTING */ /*% * Time */ #define TIME_NOW(tp) RUNTIME_CHECK(isc_time_now((tp)) == ISC_R_SUCCESS) #ifdef CLOCK_BOOTTIME #define TIME_MONOTONIC(tp) RUNTIME_CHECK(isc_time_boottime((tp)) == ISC_R_SUCCESS) #endif /*% * Alignment */ #ifdef __GNUC__ #define ISC_ALIGN(x, a) (((x) + (a) - 1) & ~((typeof(x))(a) - 1)) #else #define ISC_ALIGN(x, a) (((x) + (a) - 1) & ~((uintmax_t)(a) - 1)) #endif /*% * Misc */ #include #endif /* ISC_UTIL_H */ PKֺ1]ʼΆ+&+&lex.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_LEX_H #define ISC_LEX_H 1 /***** ***** Module Info *****/ /*! \file isc/lex.h * \brief The "lex" module provides a lightweight tokenizer. It can operate * on files or buffers, and can handle "include". It is designed for * parsing of DNS master files and the BIND configuration file, but * should be general enough to tokenize other things, e.g. HTTP. * * \li MP: * No synchronization is provided. Clients must ensure exclusive * access. * * \li Reliability: * No anticipated impact. * * \li Resources: * TBS * * \li Security: * No anticipated impact. * * \li Standards: * None. */ /*** *** Imports ***/ #include #include #include #include #include ISC_LANG_BEGINDECLS /*** *** Options ***/ /*@{*/ /*! * Various options for isc_lex_gettoken(). */ #define ISC_LEXOPT_EOL 0x01 /*%< Want end-of-line token. */ #define ISC_LEXOPT_EOF 0x02 /*%< Want end-of-file token. */ #define ISC_LEXOPT_INITIALWS 0x04 /*%< Want initial whitespace. */ #define ISC_LEXOPT_NUMBER 0x08 /*%< Recognize numbers. */ #define ISC_LEXOPT_QSTRING 0x10 /*%< Recognize qstrings. */ /*@}*/ /*@{*/ /*! * The ISC_LEXOPT_DNSMULTILINE option handles the processing of '(' and ')' in * the DNS master file format. If this option is set, then the * ISC_LEXOPT_INITIALWS and ISC_LEXOPT_EOL options will be ignored when * the paren count is > 0. To use this option, '(' and ')' must be special * characters. */ #define ISC_LEXOPT_DNSMULTILINE 0x20 /*%< Handle '(' and ')'. */ #define ISC_LEXOPT_NOMORE 0x40 /*%< Want "no more" token. */ #define ISC_LEXOPT_CNUMBER 0x80 /*%< Recognize octal and hex. */ #define ISC_LEXOPT_ESCAPE 0x100 /*%< Recognize escapes. */ #define ISC_LEXOPT_QSTRINGMULTILINE 0x200 /*%< Allow multiline "" strings */ #define ISC_LEXOPT_OCTAL 0x400 /*%< Expect a octal number. */ #define ISC_LEXOPT_BTEXT 0x800 /*%< Bracketed text. */ /*@}*/ /*@{*/ /*! * Various commenting styles, which may be changed at any time with * isc_lex_setcomments(). */ #define ISC_LEXCOMMENT_C 0x01 #define ISC_LEXCOMMENT_CPLUSPLUS 0x02 #define ISC_LEXCOMMENT_SHELL 0x04 #define ISC_LEXCOMMENT_DNSMASTERFILE 0x08 /*@}*/ /*** *** Types ***/ /*! Lex */ typedef char isc_lexspecials_t[256]; /* Tokens */ typedef enum { isc_tokentype_unknown = 0, isc_tokentype_string = 1, isc_tokentype_number = 2, isc_tokentype_qstring = 3, isc_tokentype_eol = 4, isc_tokentype_eof = 5, isc_tokentype_initialws = 6, isc_tokentype_special = 7, isc_tokentype_nomore = 8, isc_tokentype_btext = 8 } isc_tokentype_t; typedef union { char as_char; unsigned long as_ulong; isc_region_t as_region; isc_textregion_t as_textregion; void * as_pointer; } isc_tokenvalue_t; typedef struct isc_token { isc_tokentype_t type; isc_tokenvalue_t value; } isc_token_t; /*** *** Functions ***/ isc_result_t isc_lex_create(isc_mem_t *mctx, size_t max_token, isc_lex_t **lexp); /*%< * Create a lexer. * * 'max_token' is a hint of the number of bytes in the largest token. * * Requires: *\li '*lexp' is a valid lexer. * * Ensures: *\li On success, *lexp is attached to the newly created lexer. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY */ void isc_lex_destroy(isc_lex_t **lexp); /*%< * Destroy the lexer. * * Requires: *\li '*lexp' is a valid lexer. * * Ensures: *\li *lexp == NULL */ unsigned int isc_lex_getcomments(isc_lex_t *lex); /*%< * Return the current lexer commenting styles. * * Requires: *\li 'lex' is a valid lexer. * * Returns: *\li The commenting styles which are currently allowed. */ void isc_lex_setcomments(isc_lex_t *lex, unsigned int comments); /*%< * Set allowed lexer commenting styles. * * Requires: *\li 'lex' is a valid lexer. * *\li 'comments' has meaningful values. */ void isc_lex_getspecials(isc_lex_t *lex, isc_lexspecials_t specials); /*%< * Put the current list of specials into 'specials'. * * Requires: *\li 'lex' is a valid lexer. */ void isc_lex_setspecials(isc_lex_t *lex, isc_lexspecials_t specials); /*!< * The characters in 'specials' are returned as tokens. Along with * whitespace, they delimit strings and numbers. * * Note: *\li Comment processing takes precedence over special character * recognition. * * Requires: *\li 'lex' is a valid lexer. */ isc_result_t isc_lex_openfile(isc_lex_t *lex, const char *filename); /*%< * Open 'filename' and make it the current input source for 'lex'. * * Requires: *\li 'lex' is a valid lexer. * *\li filename is a valid C string. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY Out of memory *\li #ISC_R_NOTFOUND File not found *\li #ISC_R_NOPERM No permission to open file *\li #ISC_R_FAILURE Couldn't open file, not sure why *\li #ISC_R_UNEXPECTED */ isc_result_t isc_lex_openstream(isc_lex_t *lex, FILE *stream); /*%< * Make 'stream' the current input source for 'lex'. * * Requires: *\li 'lex' is a valid lexer. * *\li 'stream' is a valid C stream. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY Out of memory */ isc_result_t isc_lex_openbuffer(isc_lex_t *lex, isc_buffer_t *buffer); /*%< * Make 'buffer' the current input source for 'lex'. * * Requires: *\li 'lex' is a valid lexer. * *\li 'buffer' is a valid buffer. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY Out of memory */ isc_result_t isc_lex_close(isc_lex_t *lex); /*%< * Close the most recently opened object (i.e. file or buffer). * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_NOMORE No more input sources */ isc_result_t isc_lex_gettoken(isc_lex_t *lex, unsigned int options, isc_token_t *tokenp); /*%< * Get the next token. * * Requires: *\li 'lex' is a valid lexer. * *\li 'lex' has an input source. * *\li 'options' contains valid options. * *\li '*tokenp' is a valid pointer. * * Returns: *\li #ISC_R_SUCCESS *\li #ISC_R_UNEXPECTEDEND *\li #ISC_R_NOMEMORY * * These two results are returned only if their corresponding lexer * options are not set. * *\li #ISC_R_EOF End of input source *\li #ISC_R_NOMORE No more input sources */ isc_result_t isc_lex_getmastertoken(isc_lex_t *lex, isc_token_t *token, isc_tokentype_t expect, bool eol); /*%< * Get the next token from a DNS master file type stream. This is a * convenience function that sets appropriate options and handles quoted * strings and end of line correctly for master files. It also ungets * unexpected tokens. If `eol` is set then expect end-of-line otherwise * eol is a error. * * Requires: *\li 'lex' is a valid lexer. * *\li 'token' is a valid pointer * * Returns: * * \li any return code from isc_lex_gettoken(). */ isc_result_t isc_lex_getoctaltoken(isc_lex_t *lex, isc_token_t *token, bool eol); /*%< * Get the next token from a DNS master file type stream. This is a * convenience function that sets appropriate options and handles end * of line correctly for master files. It also ungets unexpected tokens. * If `eol` is set then expect end-of-line otherwise eol is a error. * * Requires: *\li 'lex' is a valid lexer. * *\li 'token' is a valid pointer * * Returns: * * \li any return code from isc_lex_gettoken(). */ void isc_lex_ungettoken(isc_lex_t *lex, isc_token_t *tokenp); /*%< * Unget the current token. * * Requires: *\li 'lex' is a valid lexer. * *\li 'lex' has an input source. * *\li 'tokenp' points to a valid token. * *\li There is no ungotten token already. */ void isc_lex_getlasttokentext(isc_lex_t *lex, isc_token_t *tokenp, isc_region_t *r); /*%< * Returns a region containing the text of the last token returned. * * Requires: *\li 'lex' is a valid lexer. * *\li 'lex' has an input source. * *\li 'tokenp' points to a valid token. * *\li A token has been gotten and not ungotten. */ char * isc_lex_getsourcename(isc_lex_t *lex); /*%< * Return the input source name. * * Requires: *\li 'lex' is a valid lexer. * * Returns: * \li source name or NULL if no current source. *\li result valid while current input source exists. */ unsigned long isc_lex_getsourceline(isc_lex_t *lex); /*%< * Return the input source line number. * * Requires: *\li 'lex' is a valid lexer. * * Returns: *\li Current line number or 0 if no current source. */ isc_result_t isc_lex_setsourcename(isc_lex_t *lex, const char *name); /*%< * Assigns a new name to the input source. * * Requires: * * \li 'lex' is a valid lexer. * * Returns: * \li #ISC_R_SUCCESS * \li #ISC_R_NOMEMORY * \li #ISC_R_NOTFOUND - there are no sources. */ isc_result_t isc_lex_setsourceline(isc_lex_t *lex, unsigned long line); /*%< * Assigns a new line number to the input source. This can be used * when parsing a buffer that's been excerpted from the middle a file, * allowing logged messages to display the correct line number, * rather than the line number within the buffer. * * Requires: * * \li 'lex' is a valid lexer. * * Returns: * \li #ISC_R_SUCCESS * \li #ISC_R_NOTFOUND - there are no sources. */ bool isc_lex_isfile(isc_lex_t *lex); /*%< * Return whether the current input source is a file. * * Requires: *\li 'lex' is a valid lexer. * * Returns: * \li #true if the current input is a file, *\li #false otherwise. */ ISC_LANG_ENDDECLS #endif /* ISC_LEX_H */ PKֺ1]Bsymtab.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_SYMTAB_H #define ISC_SYMTAB_H 1 /***** ***** Module Info *****/ /*! \file isc/symtab.h * \brief Provides a simple memory-based symbol table. * * Keys are C strings, and key comparisons are case-insensitive. A type may * be specified when looking up, defining, or undefining. A type value of * 0 means "match any type"; any other value will only match the given * type. * * It's possible that a client will attempt to define a * tuple when a tuple with the given key and type already exists in the table. * What to do in this case is specified by the client. Possible policies are: * *\li #isc_symexists_reject Disallow the define, returning #ISC_R_EXISTS *\li #isc_symexists_replace Replace the old value with the new. The * undefine action (if provided) will be called * with the old tuple. *\li #isc_symexists_add Add the new tuple, leaving the old tuple in * the table. Subsequent lookups will retrieve * the most-recently-defined tuple. * * A lookup of a key using type 0 will return the most-recently defined * symbol with that key. An undefine of a key using type 0 will undefine the * most-recently defined symbol with that key. Trying to define a key with * type 0 is illegal. * * The symbol table library does not make a copy the key field, so the * caller must ensure that any key it passes to isc_symtab_define() will not * change until it calls isc_symtab_undefine() or isc_symtab_destroy(). * * A user-specified action will be called (if provided) when a symbol is * undefined. It can be used to free memory associated with keys and/or * values. * * A symbol table is implemented as a hash table of lists; the size of the * hash table is set by the 'size' parameter to isc_symtbl_create(). When * the number of entries in the symbol table reaches three quarters of this * value, the hash table is reallocated with size doubled, in order to * optimize lookup performance. This has a negative effect on insertion * performance, which can be mitigated by sizing the table appropriately * when creating it. * * \li MP: * The callers of this module must ensure any required synchronization. * * \li Reliability: * No anticipated impact. * * \li Resources: * TBS * * \li Security: * No anticipated impact. * * \li Standards: * None. */ /*** *** Imports. ***/ #include #include #include /* *** Symbol Tables. ***/ /*% Symbol table value. */ typedef union isc_symvalue { void * as_pointer; const void * as_cpointer; int as_integer; unsigned int as_uinteger; } isc_symvalue_t; typedef void (*isc_symtabaction_t)(char *key, unsigned int type, isc_symvalue_t value, void *userarg); /*% Symbol table exists. */ typedef enum { isc_symexists_reject = 0, /*%< Disallow the define */ isc_symexists_replace = 1, /*%< Replace the old value with the new */ isc_symexists_add = 2 /*%< Add the new tuple */ } isc_symexists_t; ISC_LANG_BEGINDECLS /*% Create a symbol table. */ isc_result_t isc_symtab_create(isc_mem_t *mctx, unsigned int size, isc_symtabaction_t undefine_action, void *undefine_arg, bool case_sensitive, isc_symtab_t **symtabp); /*% Destroy a symbol table. */ void isc_symtab_destroy(isc_symtab_t **symtabp); /*% Lookup a symbol table. */ isc_result_t isc_symtab_lookup(isc_symtab_t *symtab, const char *key, unsigned int type, isc_symvalue_t *value); /*% Define a symbol table. */ isc_result_t isc_symtab_define(isc_symtab_t *symtab, const char *key, unsigned int type, isc_symvalue_t value, isc_symexists_t exists_policy); /*% Undefine a symbol table. */ isc_result_t isc_symtab_undefine(isc_symtab_t *symtab, const char *key, unsigned int type); /*% Return the number of items in a symbol table. */ unsigned int isc_symtab_count(isc_symtab_t *symtab); ISC_LANG_ENDDECLS #endif /* ISC_SYMTAB_H */ PKֺ1]`;rwlock.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_RWLOCK_H #define ISC_RWLOCK_H 1 #include /*! \file isc/rwlock.h */ #include #include #include #include #if defined(ISC_PLATFORM_HAVESTDATOMIC) #if defined(__cplusplus) #include #else #include #endif #endif ISC_LANG_BEGINDECLS typedef enum { isc_rwlocktype_none = 0, isc_rwlocktype_read, isc_rwlocktype_write } isc_rwlocktype_t; #ifdef ISC_PLATFORM_USETHREADS # if defined(ISC_PLATFORM_HAVESTDATOMIC) # define ISC_RWLOCK_USEATOMIC 1 # define ISC_RWLOCK_USESTDATOMIC 1 # else /* defined(ISC_PLATFORM_HAVESTDATOMIC) */ # if defined(ISC_PLATFORM_HAVEXADD) && defined(ISC_PLATFORM_HAVECMPXCHG) # define ISC_RWLOCK_USEATOMIC 1 # endif # endif /* defined(ISC_PLATFORM_HAVESTDATOMIC) */ struct isc_rwlock { /* Unlocked. */ unsigned int magic; isc_mutex_t lock; #if defined(ISC_RWLOCK_USEATOMIC) /* * When some atomic instructions with hardware assistance are * available, rwlock will use those so that concurrent readers do not * interfere with each other through mutex as long as no writers * appear, massively reducing the lock overhead in the typical case. * * The basic algorithm of this approach is the "simple * writer-preference lock" shown in the following URL: * http://www.cs.rochester.edu/u/scott/synchronization/pseudocode/rw.html * but our implementation does not rely on the spin lock unlike the * original algorithm to be more portable as a user space application. */ /* Read or modified atomically. */ #if defined(ISC_RWLOCK_USESTDATOMIC) atomic_int_fast32_t spins; atomic_int_fast32_t write_requests; atomic_int_fast32_t write_completions; atomic_int_fast32_t cnt_and_flag; atomic_int_fast32_t write_granted; #else int32_t spins; int32_t write_requests; int32_t write_completions; int32_t cnt_and_flag; int32_t write_granted; #endif /* Locked by lock. */ isc_condition_t readable; isc_condition_t writeable; unsigned int readers_waiting; /* Unlocked. */ unsigned int write_quota; #else /* ISC_RWLOCK_USEATOMIC */ /*%< Locked by lock. */ isc_condition_t readable; isc_condition_t writeable; isc_rwlocktype_t type; /*% The number of threads that have the lock. */ unsigned int active; /*% * The number of lock grants made since the lock was last switched * from reading to writing or vice versa; used in determining * when the quota is reached and it is time to switch. */ unsigned int granted; unsigned int spins; unsigned int readers_waiting; unsigned int writers_waiting; unsigned int read_quota; unsigned int write_quota; isc_rwlocktype_t original; #endif /* ISC_RWLOCK_USEATOMIC */ }; #else /* ISC_PLATFORM_USETHREADS */ struct isc_rwlock { unsigned int magic; isc_rwlocktype_t type; unsigned int active; }; #endif /* ISC_PLATFORM_USETHREADS */ isc_result_t isc_rwlock_init(isc_rwlock_t *rwl, unsigned int read_quota, unsigned int write_quota); isc_result_t isc_rwlock_lock(isc_rwlock_t *rwl, isc_rwlocktype_t type); isc_result_t isc_rwlock_trylock(isc_rwlock_t *rwl, isc_rwlocktype_t type); isc_result_t isc_rwlock_unlock(isc_rwlock_t *rwl, isc_rwlocktype_t type); isc_result_t isc_rwlock_tryupgrade(isc_rwlock_t *rwl); void isc_rwlock_downgrade(isc_rwlock_t *rwl); void isc_rwlock_destroy(isc_rwlock_t *rwl); ISC_LANG_ENDDECLS #endif /* ISC_RWLOCK_H */ PKֺ1]-0 0 interfaceiter.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_INTERFACEITER_H #define ISC_INTERFACEITER_H 1 /***** ***** Module Info *****/ /*! \file isc/interfaceiter.h * \brief Iterates over the list of network interfaces. * * Interfaces whose address family is not supported are ignored and never * returned by the iterator. Interfaces whose netmask, interface flags, * or similar cannot be obtained are also ignored, and the failure is logged. * * Standards: * The API for scanning varies greatly among operating systems. * This module attempts to hide the differences. */ /*** *** Imports ***/ #include #include #include #include /*! * \brief Public structure describing a network interface. */ struct isc_interface { char name[32]; /*%< Interface name, null-terminated. */ unsigned int af; /*%< Address family. */ isc_netaddr_t address; /*%< Local address. */ isc_netaddr_t netmask; /*%< Network mask. */ isc_netaddr_t dstaddress; /*%< Destination address (point-to-point only). */ uint32_t flags; /*%< Flags; see INTERFACE flags. */ }; /*@{*/ /*! Interface flags. */ #define INTERFACE_F_UP 0x00000001U #define INTERFACE_F_POINTTOPOINT 0x00000002U #define INTERFACE_F_LOOPBACK 0x00000004U /*@}*/ /*** *** Functions ***/ ISC_LANG_BEGINDECLS isc_result_t isc_interfaceiter_create(isc_mem_t *mctx, isc_interfaceiter_t **iterp); /*!< * \brief Create an iterator for traversing the operating system's list * of network interfaces. * * Returns: *\li #ISC_R_SUCCESS * \li #ISC_R_NOMEMORY *\li Various network-related errors */ isc_result_t isc_interfaceiter_first(isc_interfaceiter_t *iter); /*!< * \brief Position the iterator on the first interface. * * Returns: *\li #ISC_R_SUCCESS Success. *\li #ISC_R_NOMORE There are no interfaces. */ isc_result_t isc_interfaceiter_current(isc_interfaceiter_t *iter, isc_interface_t *ifdata); /*!< * \brief Get information about the interface the iterator is currently * positioned at and store it at *ifdata. * * Requires: *\li The iterator has been successfully positioned using * isc_interface_iter_first() / isc_interface_iter_next(). * * Returns: *\li #ISC_R_SUCCESS Success. */ isc_result_t isc_interfaceiter_next(isc_interfaceiter_t *iter); /*!< * \brief Position the iterator on the next interface. * * Requires: * \li The iterator has been successfully positioned using * isc_interface_iter_first() / isc_interface_iter_next(). * * Returns: *\li #ISC_R_SUCCESS Success. *\li #ISC_R_NOMORE There are no more interfaces. */ void isc_interfaceiter_destroy(isc_interfaceiter_t **iterp); /*!< * \brief Destroy the iterator. */ ISC_LANG_ENDDECLS #endif /* ISC_INTERFACEITER_H */ PKֺ1]PB(T(Ttask.hnu[/* * Copyright (C) Internet Systems Consortium, Inc. ("ISC") * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at https://mozilla.org/MPL/2.0/. * * See the COPYRIGHT file distributed with this work for additional * information regarding copyright ownership. */ #ifndef ISC_TASK_H #define ISC_TASK_H 1 /***** ***** Module Info *****/ /*! \file isc/task.h * \brief The task system provides a lightweight execution context, which is * basically an event queue. * When a task's event queue is non-empty, the * task is runnable. A small work crew of threads, typically one per CPU, * execute runnable tasks by dispatching the events on the tasks' event * queues. Context switching between tasks is fast. * * \li MP: * The module ensures appropriate synchronization of data structures it * creates and manipulates. * The caller must ensure that isc_taskmgr_destroy() is called only * once for a given manager. * * \li Reliability: * No anticipated impact. * * \li Resources: * TBS * * \li Security: * No anticipated impact. * * \li Standards: * None. * * \section purge Purging and Unsending * * Events which have been queued for a task but not delivered may be removed * from the task's event queue by purging or unsending. * * With both types, the caller specifies a matching pattern that selects * events based upon their sender, type, and tag. * * Purging calls isc_event_free() on the matching events. * * Unsending returns a list of events that matched the pattern. * The caller is then responsible for them. * * Consumers of events should purge, not unsend. * * Producers of events often want to remove events when the caller indicates * it is no longer interested in the object, e.g. by canceling a timer. * Sometimes this can be done by purging, but for some event types, the * calls to isc_event_free() cause deadlock because the event free routine * wants to acquire a lock the caller is already holding. Unsending instead * of purging solves this problem. As a general rule, producers should only * unsend events which they have sent. */ /*** *** Imports. ***/ #include #include #include #include #include #include #include #define ISC_TASKEVENT_FIRSTEVENT (ISC_EVENTCLASS_TASK + 0) #define ISC_TASKEVENT_SHUTDOWN (ISC_EVENTCLASS_TASK + 1) #define ISC_TASKEVENT_TEST (ISC_EVENTCLASS_TASK + 1) #define ISC_TASKEVENT_LASTEVENT (ISC_EVENTCLASS_TASK + 65535) /***** ***** Tasks. *****/ ISC_LANG_BEGINDECLS /*** *** Types ***/ typedef enum { isc_taskqueue_normal = 0, isc_taskqueue_slow = 1, } isc_taskqueue_t; #define ISC_TASK_QUANTUM_SLOW 1024 typedef enum { isc_taskmgrmode_normal = 0, isc_taskmgrmode_privileged } isc_taskmgrmode_t; /*% Task and task manager methods */ typedef struct isc_taskmgrmethods { void (*destroy)(isc_taskmgr_t **managerp); void (*setmode)(isc_taskmgr_t *manager, isc_taskmgrmode_t mode); isc_taskmgrmode_t (*mode)(isc_taskmgr_t *manager); isc_result_t (*taskcreate)(isc_taskmgr_t *manager, unsigned int quantum, isc_task_t **taskp); void (*setexcltask)(isc_taskmgr_t *mgr, isc_task_t *task); isc_result_t (*excltask)(isc_taskmgr_t *mgr, isc_task_t **taskp); } isc_taskmgrmethods_t; typedef struct isc_taskmethods { void (*attach)(isc_task_t *source, isc_task_t **targetp); void (*detach)(isc_task_t **taskp); void (*destroy)(isc_task_t **taskp); void (*send)(isc_task_t *task, isc_event_t **eventp); void (*sendanddetach)(isc_task_t **taskp, isc_event_t **eventp); unsigned int (*unsend)(isc_task_t *task, void *sender, isc_eventtype_t type, void *tag, isc_eventlist_t *events); isc_result_t (*onshutdown)(isc_task_t *task, isc_taskaction_t action, void *arg); void (*shutdown)(isc_task_t *task); void (*setname)(isc_task_t *task, const char *name, void *tag); unsigned int (*purgeevents)(isc_task_t *task, void *sender, isc_eventtype_t type, void *tag); unsigned int (*purgerange)(isc_task_t *task, void *sender, isc_eventtype_t first, isc_eventtype_t last, void *tag); isc_result_t (*beginexclusive)(isc_task_t *task); void (*endexclusive)(isc_task_t *task); void (*setprivilege)(isc_task_t *task, bool priv); bool (*privilege)(isc_task_t *task); } isc_taskmethods_t; /*% * This structure is actually just the common prefix of a task manager * object implementation's version of an isc_taskmgr_t. * \brief * Direct use of this structure by clients is forbidden. task implementations * may change the structure. 'magic' must be ISCAPI_TASKMGR_MAGIC for any * of the isc_task_ routines to work. task implementations must maintain * all task invariants. */ struct isc_taskmgr { unsigned int impmagic; unsigned int magic; isc_taskmgrmethods_t *methods; }; #define ISCAPI_TASKMGR_MAGIC ISC_MAGIC('A','t','m','g') #define ISCAPI_TASKMGR_VALID(m) ((m) != NULL && \ (m)->magic == ISCAPI_TASKMGR_MAGIC) /*% * This is the common prefix of a task object. The same note as * that for the taskmgr structure applies. */ struct isc_task { unsigned int impmagic; unsigned int magic; isc_taskmethods_t *methods; }; #define ISCAPI_TASK_MAGIC ISC_MAGIC('A','t','s','t') #define ISCAPI_TASK_VALID(s) ((s) != NULL && \ (s)->magic == ISCAPI_TASK_MAGIC) isc_result_t isc_task_create(isc_taskmgr_t *manager, unsigned int quantum, isc_task_t **taskp); /*%< * Create a task. * * Notes: * *\li If 'quantum' is non-zero, then only that many events can be dispatched * before the task must yield to other tasks waiting to execute. If * quantum is zero, then the default quantum of the task manager will * be used. * *\li The 'quantum' option may be removed from isc_task_create() in the * future. If this happens, isc_task_getquantum() and * isc_task_setquantum() will be provided. * * Requires: * *\li 'manager' is a valid task manager. * *\li taskp != NULL && *taskp == NULL * * Ensures: * *\li On success, '*taskp' is bound to the new task. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_UNEXPECTED *\li #ISC_R_SHUTTINGDOWN */ void isc_task_attach(isc_task_t *source, isc_task_t **targetp); /*%< * Attach *targetp to source. * * Requires: * *\li 'source' is a valid task. * *\li 'targetp' points to a NULL isc_task_t *. * * Ensures: * *\li *targetp is attached to source. */ void isc_task_detach(isc_task_t **taskp); /*%< * Detach *taskp from its task. * * Requires: * *\li '*taskp' is a valid task. * * Ensures: * *\li *taskp is NULL. * *\li If '*taskp' is the last reference to the task, the task is idle (has * an empty event queue), and has not been shutdown, the task will be * shutdown. * *\li If '*taskp' is the last reference to the task and * the task has been shutdown, * all resources used by the task will be freed. */ void isc_task_send(isc_task_t *task, isc_event_t **eventp); /*%< * Send '*event' to 'task'. * * Requires: * *\li 'task' is a valid task. *\li eventp != NULL && *eventp != NULL. * * Ensures: * *\li *eventp == NULL. */ void isc_task_sendanddetach(isc_task_t **taskp, isc_event_t **eventp); /*%< * Send '*event' to '*taskp' and then detach '*taskp' from its * task. * * Requires: * *\li '*taskp' is a valid task. *\li eventp != NULL && *eventp != NULL. * * Ensures: * *\li *eventp == NULL. * *\li *taskp == NULL. * *\li If '*taskp' is the last reference to the task, the task is * idle (has an empty event queue), and has not been shutdown, * the task will be shutdown. * *\li If '*taskp' is the last reference to the task and * the task has been shutdown, * all resources used by the task will be freed. */ unsigned int isc_task_purgerange(isc_task_t *task, void *sender, isc_eventtype_t first, isc_eventtype_t last, void *tag); /*%< * Purge events from a task's event queue. * * Requires: * *\li 'task' is a valid task. * *\li last >= first * * Ensures: * *\li Events in the event queue of 'task' whose sender is 'sender', whose * type is >= first and <= last, and whose tag is 'tag' will be purged, * unless they are marked as unpurgable. * *\li A sender of NULL will match any sender. A NULL tag matches any * tag. * * Returns: * *\li The number of events purged. */ unsigned int isc_task_purge(isc_task_t *task, void *sender, isc_eventtype_t type, void *tag); /*%< * Purge events from a task's event queue. * * Notes: * *\li This function is equivalent to * *\code * isc_task_purgerange(task, sender, type, type, tag); *\endcode * * Requires: * *\li 'task' is a valid task. * * Ensures: * *\li Events in the event queue of 'task' whose sender is 'sender', whose * type is 'type', and whose tag is 'tag' will be purged, unless they * are marked as unpurgable. * *\li A sender of NULL will match any sender. A NULL tag matches any * tag. * * Returns: * *\li The number of events purged. */ bool isc_task_purgeevent(isc_task_t *task, isc_event_t *event); /*%< * Purge 'event' from a task's event queue. * * XXXRTH: WARNING: This method may be removed before beta. * * Notes: * *\li If 'event' is on the task's event queue, it will be purged, * unless it is marked as unpurgeable. 'event' does not have to be * on the task's event queue; in fact, it can even be an invalid * pointer. Purging only occurs if the event is actually on the task's * event queue. * * \li Purging never changes the state of the task. * * Requires: * *\li 'task' is a valid task. * * Ensures: * *\li 'event' is not in the event queue for 'task'. * * Returns: * *\li #true The event was purged. *\li #false The event was not in the event queue, * or was marked unpurgeable. */ unsigned int isc_task_unsendrange(isc_task_t *task, void *sender, isc_eventtype_t first, isc_eventtype_t last, void *tag, isc_eventlist_t *events); /*%< * Remove events from a task's event queue. * * Requires: * *\li 'task' is a valid task. * *\li last >= first. * *\li *events is a valid list. * * Ensures: * *\li Events in the event queue of 'task' whose sender is 'sender', whose * type is >= first and <= last, and whose tag is 'tag' will be dequeued * and appended to *events. * *\li A sender of NULL will match any sender. A NULL tag matches any * tag. * * Returns: * *\li The number of events unsent. */ unsigned int isc_task_unsend(isc_task_t *task, void *sender, isc_eventtype_t type, void *tag, isc_eventlist_t *events); /*%< * Remove events from a task's event queue. * * Notes: * *\li This function is equivalent to * *\code * isc_task_unsendrange(task, sender, type, type, tag, events); *\endcode * * Requires: * *\li 'task' is a valid task. * *\li *events is a valid list. * * Ensures: * *\li Events in the event queue of 'task' whose sender is 'sender', whose * type is 'type', and whose tag is 'tag' will be dequeued and appended * to *events. * * Returns: * *\li The number of events unsent. */ isc_result_t isc_task_onshutdown(isc_task_t *task, isc_taskaction_t action, void *arg); /*%< * Send a shutdown event with action 'action' and argument 'arg' when * 'task' is shutdown. * * Notes: * *\li Shutdown events are posted in LIFO order. * * Requires: * *\li 'task' is a valid task. * *\li 'action' is a valid task action. * * Ensures: * *\li When the task is shutdown, shutdown events requested with * isc_task_onshutdown() will be appended to the task's event queue. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_SHUTTINGDOWN Task is shutting down. */ void isc_task_shutdown(isc_task_t *task); /*%< * Shutdown 'task'. * * Notes: * *\li Shutting down a task causes any shutdown events requested with * isc_task_onshutdown() to be posted (in LIFO order). The task * moves into a "shutting down" mode which prevents further calls * to isc_task_onshutdown(). * *\li Trying to shutdown a task that has already been shutdown has no * effect. * * Requires: * *\li 'task' is a valid task. * * Ensures: * *\li Any shutdown events requested with isc_task_onshutdown() have been * posted (in LIFO order). */ void isc_task_destroy(isc_task_t **taskp); /*%< * Destroy '*taskp'. * * Notes: * *\li This call is equivalent to: * *\code * isc_task_shutdown(*taskp); * isc_task_detach(taskp); *\endcode * * Requires: * * '*taskp' is a valid task. * * Ensures: * *\li Any shutdown events requested with isc_task_onshutdown() have been * posted (in LIFO order). * *\li *taskp == NULL * *\li If '*taskp' is the last reference to the task, * all resources used by the task will be freed. */ void isc_task_setname(isc_task_t *task, const char *name, void *tag); /*%< * Name 'task'. * * Notes: * *\li Only the first 15 characters of 'name' will be copied. * *\li Naming a task is currently only useful for debugging purposes. * * Requires: * *\li 'task' is a valid task. */ const char * isc_task_getname(isc_task_t *task); /*%< * Get the name of 'task', as previously set using isc_task_setname(). * * Notes: *\li This function is for debugging purposes only. * * Requires: *\li 'task' is a valid task. * * Returns: *\li A non-NULL pointer to a null-terminated string. * If the task has not been named, the string is * empty. * */ void * isc_task_gettag(isc_task_t *task); /*%< * Get the tag value for 'task', as previously set using isc_task_settag(). * * Notes: *\li This function is for debugging purposes only. * * Requires: *\li 'task' is a valid task. */ isc_result_t isc_task_beginexclusive(isc_task_t *task); /*%< * Request exclusive access for 'task', which must be the calling * task. Waits for any other concurrently executing tasks to finish their * current event, and prevents any new events from executing in any of the * tasks sharing a task manager with 'task'. * * The exclusive access must be relinquished by calling * isc_task_endexclusive() before returning from the current event handler. * * Requires: *\li 'task' is the calling task. * * Returns: *\li #ISC_R_SUCCESS The current task now has exclusive access. *\li #ISC_R_LOCKBUSY Another task has already requested exclusive * access. */ void isc_task_endexclusive(isc_task_t *task); /*%< * Relinquish the exclusive access obtained by isc_task_beginexclusive(), * allowing other tasks to execute. * * Requires: *\li 'task' is the calling task, and has obtained * exclusive access by calling isc_task_spl(). */ void isc_task_getcurrenttime(isc_task_t *task, isc_stdtime_t *t); void isc_task_getcurrenttimex(isc_task_t *task, isc_time_t *t); /*%< * Provide the most recent timestamp on the task. The timestamp is considered * as the "current time". * * isc_task_getcurrentime() returns the time in one-second granularity; * isc_task_getcurrentimex() returns it in nanosecond granularity. * * Requires: *\li 'task' is a valid task. *\li 't' is a valid non NULL pointer. * * Ensures: *\li '*t' has the "current time". */ bool isc_task_exiting(isc_task_t *t); /*%< * Returns true if the task is in the process of shutting down, * false otherwise. * * Requires: *\li 'task' is a valid task. */ void isc_task_setprivilege(isc_task_t *task, bool priv); /*%< * Set or unset the task's "privileged" flag depending on the value of * 'priv'. * * Under normal circumstances this flag has no effect on the task behavior, * but when the task manager has been set to privileged execution mode via * isc_taskmgr_setmode(), only tasks with the flag set will be executed, * and all other tasks will wait until they're done. Once all privileged * tasks have finished executing, the task manager will automatically * return to normal execution mode and nonprivileged task can resume. * * Requires: *\li 'task' is a valid task. */ bool isc_task_privilege(isc_task_t *task); /*%< * Returns the current value of the task's privilege flag. * * Requires: *\li 'task' is a valid task. */ /***** ***** Task Manager. *****/ isc_result_t isc_taskmgr_createinctx(isc_mem_t *mctx, isc_appctx_t *actx, unsigned int workers, unsigned int default_quantum, isc_taskmgr_t **managerp); isc_result_t isc_taskmgr_create(isc_mem_t *mctx, unsigned int workers, unsigned int default_quantum, isc_taskmgr_t **managerp); /*%< * Create a new task manager. isc_taskmgr_createinctx() also associates * the new manager with the specified application context. * * Notes: * *\li 'workers' in the number of worker threads to create. In general, * the value should be close to the number of processors in the system. * The 'workers' value is advisory only. An attempt will be made to * create 'workers' threads, but if at least one thread creation * succeeds, isc_taskmgr_create() may return ISC_R_SUCCESS. * *\li If 'default_quantum' is non-zero, then it will be used as the default * quantum value when tasks are created. If zero, then an implementation * defined default quantum will be used. * * Requires: * *\li 'mctx' is a valid memory context. * *\li workers > 0 * *\li managerp != NULL && *managerp == NULL * *\li 'actx' is a valid application context (for createinctx()). * * Ensures: * *\li On success, '*managerp' will be attached to the newly created task * manager. * * Returns: * *\li #ISC_R_SUCCESS *\li #ISC_R_NOMEMORY *\li #ISC_R_NOTHREADS No threads could be created. *\li #ISC_R_UNEXPECTED An unexpected error occurred. *\li #ISC_R_SHUTTINGDOWN The non-threaded, shared, task * manager shutting down. */ void isc_taskmgr_setmode(isc_taskmgr_t *manager, isc_taskmgrmode_t mode); isc_taskmgrmode_t isc_taskmgr_mode(isc_taskmgr_t *manager); /*%< * Set/get the current operating mode of the task manager. Valid modes are: * *\li isc_taskmgrmode_normal *\li isc_taskmgrmode_privileged * * In privileged execution mode, only tasks that have had the "privilege" * flag set via isc_task_setprivilege() can be executed. When all such * tasks are complete, the manager automatically returns to normal mode * and proceeds with running non-privileged ready tasks. This means it is * necessary to have at least one privileged task waiting on the ready * queue *before* setting the manager into privileged execution mode, * which in turn means the task which calls this function should be in * task-exclusive mode when it does so. * * Requires: * *\li 'manager' is a valid task manager. */ void isc_taskmgr_destroy(isc_taskmgr_t **managerp); /*%< * Destroy '*managerp'. * * Notes: * *\li Calling isc_taskmgr_destroy() will shutdown all tasks managed by * *managerp that haven't already been shutdown. The call will block * until all tasks have entered the done state. * *\li isc_taskmgr_destroy() must not be called by a task event action, * because it would block forever waiting for the event action to * complete. An event action that wants to cause task manager shutdown * should request some non-event action thread of execution to do the * shutdown, e.g. by signaling a condition variable or using * isc_app_shutdown(). * *\li Task manager references are not reference counted, so the caller * must ensure that no attempt will be made to use the manager after * isc_taskmgr_destroy() returns. * * Requires: * *\li '*managerp' is a valid task manager. * *\li isc_taskmgr_destroy() has not be called previously on '*managerp'. * * Ensures: * *\li All resources used by the task manager, and any tasks it managed, * have been freed. */ void isc_taskmgr_setexcltask(isc_taskmgr_t *mgr, isc_task_t *task); /*%< * Set a task which will be used for all task-exclusive operations. * * Requires: *\li 'manager' is a valid task manager. * *\li 'task' is a valid task. */ isc_result_t isc_taskmgr_excltask(isc_taskmgr_t *mgr, isc_task_t **taskp); /*%< * Attach '*taskp' to the task set by isc_taskmgr_getexcltask(). * This task should be used whenever running in task-exclusive mode, * so as to prevent deadlock between two exclusive tasks. * * Requires: *\li 'manager' is a valid task manager. *\li taskp != NULL && *taskp == NULL */ #ifdef HAVE_LIBXML2 int isc_taskmgr_renderxml(isc_taskmgr_t *mgr, xmlTextWriterPtr writer); #endif #ifdef HAVE_JSON isc_result_t isc_taskmgr_renderjson(isc_taskmgr_t *mgr, json_object *tasksobj); #endif /*%< * See isc_taskmgr_create() above. */ typedef isc_result_t (*isc_taskmgrcreatefunc_t)(isc_mem_t *mctx, unsigned int workers, unsigned int default_quantum, isc_taskmgr_t **managerp); isc_result_t isc_task_register(isc_taskmgrcreatefunc_t createfunc); /*%< * Register a new task management implementation and add it to the list of * supported implementations. This function must be called when a different * event library is used than the one contained in the ISC library. */ isc_result_t isc__task_register(void); /*%< * A short cut function that specifies the task management module in the ISC * library for isc_task_register(). An application that uses the ISC library * usually do not have to care about this function: it would call * isc_lib_register(), which internally calls this function. */ ISC_LANG_ENDDECLS #endif /* ISC_TASK_H */ PK{ 1]T\kk keymgr.pynu[PK{ 1]'ס&& checkds.pynu[PK{ 1]׀} 5keyevent.pynu[PK{ 1]+V! ! J@keydict.pynu[PK{ 1]M2"" Kkeyseries.pynu[PK{ 1]LL'm__pycache__/policy.cpython-36.opt-1.pycnu[PK{ 1]LL!ٺ__pycache__/policy.cpython-36.pycnu[PK{ 1]T^X5X5'__pycache__/dnskey.cpython-36.opt-1.pycnu[PK{ 1]u*e(h=__pycache__/checkds.cpython-36.opt-1.pycnu[PK{ 1]~)zN__pycache__/__init__.cpython-36.opt-1.pycnu[PK{ 1]6_uu'P__pycache__/keymgr.cpython-36.opt-1.pycnu[PK{ 1]@9 "a__pycache__/keydict.cpython-36.pycnu[PK{ 1]%*k__pycache__/keyseries.cpython-36.opt-1.pycnu[PK{ 1]@9 (}__pycache__/keydict.cpython-36.opt-1.pycnu[PK{ 1]u*e"b__pycache__/checkds.cpython-36.pycnu[PK{ 1]6_uu!n__pycache__/keymgr.cpython-36.pycnu[PK{ 1]:]\ 4__pycache__/utils.cpython-36.pycnu[PK{ 1]q@@)H__pycache__/keyevent.cpython-36.opt-1.pycnu[PK{ 1]vPҔ#__pycache__/parsetab.cpython-36.pycnu[PK{ 1]s$__pycache__/eventlist.cpython-36.pycnu[PK{ 1]:]\&__pycache__/utils.cpython-36.opt-1.pycnu[PK{ 1]t}U# __pycache__/coverage.cpython-36.pycnu[PK{ 1]E3__pycache__/rndc.cpython-36.pycnu[PK{ 1]T^X5X5!__pycache__/dnskey.cpython-36.pycnu[PK{ 1]E%+I__pycache__/rndc.cpython-36.opt-1.pycnu[PK{ 1]%$]__pycache__/keyseries.cpython-36.pycnu[PK{ 1]vPҔ)o__pycache__/parsetab.cpython-36.opt-1.pycnu[PK{ 1]s*__pycache__/eventlist.cpython-36.opt-1.pycnu[PK{ 1]j(__pycache__/keyzone.cpython-36.opt-1.pycnu[PK{ 1]q@@#__pycache__/keyevent.cpython-36.pycnu[PK{ 1]j"__pycache__/keyzone.cpython-36.pycnu[PK{ 1]~#__pycache__/__init__.cpython-36.pycnu[PK{ 1]t}U)__pycache__/coverage.cpython-36.opt-1.pycnu[PK{ 1]5&& coverage.pynu[PK{ 1]=2g2g Wpolicy.pynu[PK{ 1]Snտ Ukeyzone.pynu[PK{ 1]A ]eventlist.pynu[PK{ 1]!tutils.pynu[PK{ 1]~Q3++}rndc.pynu[PK{ 1]oެX}}  parsetab.pynu[PK{ 1]WC @ @ ·dnskey.pynu[PK{ 1]`J __init__.pynu[PKֺ1]xUthread.hnu[PKֺ1]F'}}stats.hnu[PKֺ1]eHHsafe.hnu[PKֺ1]CKendian.hnu[PKֺ1]Ɉ>p>p-)log.hnu[PKֺ1]߾<: fsaccess.hnu[PKֺ1]ajson.hnu[PKֺ1]$>>ռdir.hnu[PKֺ1]ؕ2 2 Hbase64.hnu[PKֺ1]22likely.hnu[PKֺ1]9errno2result.hnu[PKֺ1]10""time.hnu[PKֺ1]; !F--file.hnu[PKֺ1]wee&sha2.hnu[PKֺ1]~[ &=stdatomic.hnu[PKֺ1]J RR Qboolean.hnu[PKֺ1]tnToffset.hnu[PKֺ1]hvvbWresult.hnu[PKֺ1]t.}} ktaskpool.hnu[PKֺ1]6{ ylfsr.hnu[PKֺ1]z9crc64.hnu[PKֺ1]   refcount.hnu[PKֺ1]}} formatcheck.hnu[PKֺ1][ [ assertions.hnu[PKֺ1]J< 4mutex.hnu[PKֺ1]˞ /netaddr.hnu[PKֺ1]-V(( Ventropy.hnu[PKֺ1]čO__netdb.hnu[PKֺ1]ไPTTqueue.hnu[PKֺ1]P r 5pool.hnu[PKֺ1]v} HH(atomic.hnu[PKֺ1]Ϳee 8eventclass.hnu[PKֺ1]Ϡ :>random.hnu[PKֺ1]-@!LLpLsyslog.hnu[PKֺ1]0] Osiphash.hnu[PKֺ1]Үd  Sondestroy.hnu[PKֺ1]9`]5^string.hnu[PKֺ1];a((uapp.hnu[PKֺ1]IE msgs.hnu[PKֺ1]'Q- /sockaddr.hnu[PKֺ1]:זheap.hnu[PKֺ1]xy  keyboard.hnu[PKֺ1]); print.hnu[PKֺ1]n//socket.hnu[PKֺ1]͓&errno.hnu[PKֺ1]Yerror.hnu[PKֺ1] ) parseint.hnu[PKֺ1]"l  httpd.hnu[PKֺ1]_@Bstdio.hnu[PKֺ1]~a&)&)tnet.hnu[PKֺ1]v!XXserial.hnu[PKֺ1]ǵ,,_ht.hnu[PKֺ1]Po( bufferlist.hnu[PKֺ1]1 meminfo.hnu[PKֺ1]W< portset.hnu[PKֺ1]s quota.hnu[PKֺ1]Gt} tm.hnu[PKֺ1]0 once.hnu[PKֺ1]z>>=bind9.hnu[PKֺ1]JvRvRmem.hnu[PKֺ1]E=]gstdlib.hnu[PKֺ1]"Ujos.hnu[PKֺ1] __ (mmutexblock.hnu[PKֺ1]Ќ. rhmacmd5.hnu[PKֺ1]& oo ydeprecated.hnu[PKֺ1]y |condition.hnu[PKֺ1]ׇL L md5.hnu[PKֺ1]5ee$base32.hnu[PKֺ1]K counter.hnu[PKֺ1]cYӱ version.hnu[PKֺ1]ß jhmacsha.hnu[PKֺ1]Տ%Bsha1.hnu[PKֺ1]a<5 msgcat.hnu[PKֺ1]I+ jevent.hnu[PKֺ1]6H ratelimiter.hnu[PKֺ1]hwwtlist.hnu[PKֺ1]pgg!cmocka.hnu[PKֺ1]0%+*+* timer.hnu[PKֺ1]36Ѡ", utf8.hnu[PKֺ1]~ۜff/ buffer.hnu[PKֺ1] ̖ netscope.hnu[PKֺ1]^P88͚ aes.hnu[PKֺ1]?.: iterated_hash.hnu[PKֺ1]w  hex.hnu[PKֺ1]|FF xml.hnu[PKֺ1]햄'. . 5 resource.hnu[PKֺ1]ryx types.hnu[PKֺ1]D&&h stat.hnu[PKֺ1]mp)  commandline.hnu[PKֺ1] magic.hnu[PKֺ1] 5??  resultclass.hnu[PKֺ1])G regex.hnu[PKֺ1]9   } strerror.hnu[PKֺ1] region.hnu[PKֺ1]o[[ radix.hnu[PKֺ1]˵~}}| lang.hnu[PKֺ1]"ā@@/ int.hnu[PKֺ1]B))  stdtime.hnu[PKֺ1]33  backtrace.hnu[PKֺ1]ώt- hash.hnu[PKֺ1]PA,,K lib.hnu[PKֺ1]6gQ2%% O platform.hnu[PKֺ1]"kB))))(v util.hnu[PKֺ1]ʼΆ+&+& lex.hnu[PKֺ1]B symtab.hnu[PKֺ1]`; rwlock.hnu[PKֺ1]-0 0  interfaceiter.hnu[PKֺ1]PB(T(T task.hnu[PKy-F