tap.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # -*- test-case-name: twisted.names.test.test_tap -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Domain Name Server
  6. """
  7. import os, traceback
  8. from twisted.python import usage
  9. from twisted.names import dns
  10. from twisted.application import internet, service
  11. from twisted.names import server
  12. from twisted.names import authority
  13. from twisted.names import secondary
  14. class Options(usage.Options):
  15. optParameters = [
  16. ["interface", "i", "", "The interface to which to bind"],
  17. ["port", "p", "53", "The port on which to listen"],
  18. ["resolv-conf", None, None,
  19. "Override location of resolv.conf (implies --recursive)"],
  20. ["hosts-file", None, None, "Perform lookups with a hosts file"],
  21. ]
  22. optFlags = [
  23. ["cache", "c", "Enable record caching"],
  24. ["recursive", "r", "Perform recursive lookups"],
  25. ["verbose", "v", "Log verbosely"],
  26. ]
  27. compData = usage.Completions(
  28. optActions={"interface" : usage.CompleteNetInterfaces()}
  29. )
  30. zones = None
  31. zonefiles = None
  32. def __init__(self):
  33. usage.Options.__init__(self)
  34. self['verbose'] = 0
  35. self.bindfiles = []
  36. self.zonefiles = []
  37. self.secondaries = []
  38. def opt_pyzone(self, filename):
  39. """Specify the filename of a Python syntax zone definition"""
  40. if not os.path.exists(filename):
  41. raise usage.UsageError(filename + ": No such file")
  42. self.zonefiles.append(filename)
  43. def opt_bindzone(self, filename):
  44. """Specify the filename of a BIND9 syntax zone definition"""
  45. if not os.path.exists(filename):
  46. raise usage.UsageError(filename + ": No such file")
  47. self.bindfiles.append(filename)
  48. def opt_secondary(self, ip_domain):
  49. """Act as secondary for the specified domain, performing
  50. zone transfers from the specified IP (IP/domain)
  51. """
  52. args = ip_domain.split('/', 1)
  53. if len(args) != 2:
  54. raise usage.UsageError("Argument must be of the form IP[:port]/domain")
  55. address = args[0].split(':')
  56. if len(address) == 1:
  57. address = (address[0], dns.PORT)
  58. else:
  59. try:
  60. port = int(address[1])
  61. except ValueError:
  62. raise usage.UsageError(
  63. "Specify an integer port number, not %r" % (address[1],))
  64. address = (address[0], port)
  65. self.secondaries.append((address, [args[1]]))
  66. def opt_verbose(self):
  67. """Increment verbosity level"""
  68. self['verbose'] += 1
  69. def postOptions(self):
  70. if self['resolv-conf']:
  71. self['recursive'] = True
  72. self.svcs = []
  73. self.zones = []
  74. for f in self.zonefiles:
  75. try:
  76. self.zones.append(authority.PySourceAuthority(f))
  77. except Exception:
  78. traceback.print_exc()
  79. raise usage.UsageError("Invalid syntax in " + f)
  80. for f in self.bindfiles:
  81. try:
  82. self.zones.append(authority.BindAuthority(f))
  83. except Exception:
  84. traceback.print_exc()
  85. raise usage.UsageError("Invalid syntax in " + f)
  86. for f in self.secondaries:
  87. svc = secondary.SecondaryAuthorityService.fromServerAddressAndDomains(*f)
  88. self.svcs.append(svc)
  89. self.zones.append(self.svcs[-1].getAuthority())
  90. try:
  91. self['port'] = int(self['port'])
  92. except ValueError:
  93. raise usage.UsageError("Invalid port: %r" % (self['port'],))
  94. def _buildResolvers(config):
  95. """
  96. Build DNS resolver instances in an order which leaves recursive
  97. resolving as a last resort.
  98. @type config: L{Options} instance
  99. @param config: Parsed command-line configuration
  100. @return: Two-item tuple of a list of cache resovers and a list of client
  101. resolvers
  102. """
  103. from twisted.names import client, cache, hosts
  104. ca, cl = [], []
  105. if config['cache']:
  106. ca.append(cache.CacheResolver(verbose=config['verbose']))
  107. if config['hosts-file']:
  108. cl.append(hosts.Resolver(file=config['hosts-file']))
  109. if config['recursive']:
  110. cl.append(client.createResolver(resolvconf=config['resolv-conf']))
  111. return ca, cl
  112. def makeService(config):
  113. ca, cl = _buildResolvers(config)
  114. f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
  115. p = dns.DNSDatagramProtocol(f)
  116. f.noisy = 0
  117. ret = service.MultiService()
  118. for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
  119. s = klass(config['port'], arg, interface=config['interface'])
  120. s.setServiceParent(ret)
  121. for svc in config.svcs:
  122. svc.setServiceParent(ret)
  123. return ret