hosts.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # -*- test-case-name: twisted.names.test.test_hosts -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. hosts(5) support.
  6. """
  7. from __future__ import division, absolute_import
  8. from twisted.python.compat import nativeString
  9. from twisted.names import dns
  10. from twisted.python import failure
  11. from twisted.python.filepath import FilePath
  12. from twisted.internet import defer
  13. from twisted.internet.abstract import isIPAddress
  14. from twisted.names import common
  15. def searchFileForAll(hostsFile, name):
  16. """
  17. Search the given file, which is in hosts(5) standard format, for an address
  18. entry with a given name.
  19. @param hostsFile: The name of the hosts(5)-format file to search.
  20. @type hostsFile: L{FilePath}
  21. @param name: The name to search for.
  22. @type name: C{bytes}
  23. @return: L{None} if the name is not found in the file, otherwise a
  24. C{str} giving the address in the file associated with the name.
  25. """
  26. results = []
  27. try:
  28. lines = hostsFile.getContent().splitlines()
  29. except:
  30. return results
  31. name = name.lower()
  32. for line in lines:
  33. idx = line.find(b'#')
  34. if idx != -1:
  35. line = line[:idx]
  36. if not line:
  37. continue
  38. parts = line.split()
  39. if name.lower() in [s.lower() for s in parts[1:]]:
  40. results.append(nativeString(parts[0]))
  41. return results
  42. def searchFileFor(file, name):
  43. """
  44. Grep given file, which is in hosts(5) standard format, for an address
  45. entry with a given name.
  46. @param file: The name of the hosts(5)-format file to search.
  47. @type file: C{str} or C{bytes}
  48. @param name: The name to search for.
  49. @type name: C{bytes}
  50. @return: L{None} if the name is not found in the file, otherwise a
  51. C{str} giving the first address in the file associated with
  52. the name.
  53. """
  54. addresses = searchFileForAll(FilePath(file), name)
  55. if addresses:
  56. return addresses[0]
  57. return None
  58. class Resolver(common.ResolverBase):
  59. """
  60. A resolver that services hosts(5) format files.
  61. """
  62. def __init__(self, file=b'/etc/hosts', ttl = 60 * 60):
  63. common.ResolverBase.__init__(self)
  64. self.file = file
  65. self.ttl = ttl
  66. def _aRecords(self, name):
  67. """
  68. Return a tuple of L{dns.RRHeader} instances for all of the IPv4
  69. addresses in the hosts file.
  70. """
  71. return tuple([
  72. dns.RRHeader(name, dns.A, dns.IN, self.ttl,
  73. dns.Record_A(addr, self.ttl))
  74. for addr
  75. in searchFileForAll(FilePath(self.file), name)
  76. if isIPAddress(addr)])
  77. def _aaaaRecords(self, name):
  78. """
  79. Return a tuple of L{dns.RRHeader} instances for all of the IPv6
  80. addresses in the hosts file.
  81. """
  82. return tuple([
  83. dns.RRHeader(name, dns.AAAA, dns.IN, self.ttl,
  84. dns.Record_AAAA(addr, self.ttl))
  85. for addr
  86. in searchFileForAll(FilePath(self.file), name)
  87. if not isIPAddress(addr)])
  88. def _respond(self, name, records):
  89. """
  90. Generate a response for the given name containing the given result
  91. records, or a failure if there are no result records.
  92. @param name: The DNS name the response is for.
  93. @type name: C{str}
  94. @param records: A tuple of L{dns.RRHeader} instances giving the results
  95. that will go into the response.
  96. @return: A L{Deferred} which will fire with a three-tuple of result
  97. records, authority records, and additional records, or which will
  98. fail with L{dns.DomainError} if there are no result records.
  99. """
  100. if records:
  101. return defer.succeed((records, (), ()))
  102. return defer.fail(failure.Failure(dns.DomainError(name)))
  103. def lookupAddress(self, name, timeout=None):
  104. """
  105. Read any IPv4 addresses from C{self.file} and return them as
  106. L{Record_A} instances.
  107. """
  108. name = dns.domainString(name)
  109. return self._respond(name, self._aRecords(name))
  110. def lookupIPV6Address(self, name, timeout=None):
  111. """
  112. Read any IPv6 addresses from C{self.file} and return them as
  113. L{Record_AAAA} instances.
  114. """
  115. name = dns.domainString(name)
  116. return self._respond(name, self._aaaaRecords(name))
  117. # Someday this should include IPv6 addresses too, but that will cause
  118. # problems if users of the API (mainly via getHostByName) aren't updated to
  119. # know about IPv6 first.
  120. lookupAllRecords = lookupAddress