sqlite3_ds.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # Copyright (C) 2010 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. # $Id$
  16. import sqlite3, re, random
  17. import isc
  18. #define the index of different part of one record
  19. RR_TYPE_INDEX = 5
  20. RR_NAME_INDEX = 2
  21. RR_TTL_INDEX = 4
  22. RR_RDATA_INDEX = 7
  23. #########################################################################
  24. # define exceptions
  25. #########################################################################
  26. class Sqlite3DSError(Exception):
  27. pass
  28. #########################################################################
  29. # create: set up schema for a newly created zones/records database
  30. #########################################################################
  31. def create(cur):
  32. """Create new zone database"""
  33. cur.execute("CREATE TABLE schema_version (version INTEGER NOT NULL)")
  34. cur.execute("INSERT INTO schema_version VALUES (1)")
  35. cur.execute("""CREATE TABLE zones (id INTEGER PRIMARY KEY,
  36. name STRING NOT NULL COLLATE NOCASE,
  37. rdclass STRING NOT NULL COLLATE NOCASE DEFAULT 'IN',
  38. dnssec BOOLEAN NOT NULL DEFAULT 0)""")
  39. cur.execute("CREATE INDEX zones_byname ON zones (name)")
  40. cur.execute("""CREATE TABLE records (id INTEGER PRIMARY KEY,
  41. zone_id INTEGER NOT NULL,
  42. name STRING NOT NULL COLLATE NOCASE,
  43. rname STRING NOT NULL COLLATE NOCASE,
  44. ttl INTEGER NOT NULL,
  45. rdtype STRING NOT NULL COLLATE NOCASE,
  46. sigtype STRING COLLATE NOCASE,
  47. rdata STRING NOT NULL)""")
  48. cur.execute("CREATE INDEX records_byname ON records (name)")
  49. cur.execute("CREATE INDEX records_byrname ON records (rname)")
  50. cur.execute("""CREATE TABLE nsec3 (id INTEGER PRIMARY KEY,
  51. zone_id INTEGER NOT NULL,
  52. hash STRING NOT NULL COLLATE NOCASE,
  53. owner STRING NOT NULL COLLATE NOCASE,
  54. ttl INTEGER NOT NULL,
  55. rdtype STRING NOT NULL COLLATE NOCASE,
  56. rdata STRING NOT NULL)""")
  57. cur.execute("CREATE INDEX nsec3_byhash ON nsec3 (hash)")
  58. #########################################################################
  59. # open: open a database. if the database is not yet set up,
  60. # call create to do so.
  61. # input:
  62. # dbfile - the filename for the sqlite3 database
  63. # returns:
  64. # sqlite3 connection, sqlite3 cursor
  65. #########################################################################
  66. def open(dbfile):
  67. """Open the database file. If necessary, set it up"""
  68. try:
  69. conn = sqlite3.connect(dbfile)
  70. cur = conn.cursor()
  71. except Exception as e:
  72. fail = "Failed to open " + dbfile + ": " + e.args[0]
  73. raise Sqlite3DSError(fail)
  74. # Does the database exist yet? If not, create it.
  75. try:
  76. cur.execute("SELECT version FROM schema_version")
  77. row = cur.fetchone()
  78. except:
  79. create(cur)
  80. conn.commit()
  81. row = [1]
  82. if row == None or row[0] != 1:
  83. raise Sqlite3DSError("Bad database schema version")
  84. return conn, cur
  85. #########################################################################
  86. # get_zone_datas
  87. # a generator function producing an iterable set of
  88. # the records in the zone with the given zone name.
  89. #########################################################################
  90. def get_zone_datas(zonename, dbfile):
  91. conn, cur = open(dbfile)
  92. zone_id = get_zoneid(zonename, cur)
  93. cur.execute("SELECT * FROM records WHERE zone_id = ?", [zone_id])
  94. record = cur.fetchone()
  95. while record:
  96. yield record
  97. record = cur.fetchone()
  98. cur.close()
  99. conn.close()
  100. #########################################################################
  101. # get_zone_soa
  102. # returns the soa record of the zone with the given zone name.
  103. # If the zone doesn't exist, return None.
  104. #########################################################################
  105. def get_zone_soa(zonename, dbfile):
  106. conn, cur = open(dbfile)
  107. id = get_zoneid(zonename, cur)
  108. cur.execute("SELECT * FROM records WHERE zone_id = ? and rdtype = ?", [id, 'SOA'])
  109. datas = cur.fetchone()
  110. cur.close()
  111. conn.close()
  112. return datas
  113. #########################################################################
  114. # get_zone_rrset
  115. # returns the rrset of the zone with the given zone name, rrset name
  116. # and given rd type.
  117. # If the zone doesn't exist or rd type doesn't exist, return an empty list.
  118. #########################################################################
  119. def get_zone_rrset(zonename, rr_name, rdtype, dbfile):
  120. conn, cur = open(dbfile)
  121. id = get_zoneid(zonename, cur)
  122. cur.execute("SELECT * FROM records WHERE name = ? and zone_id = ? and rdtype = ?",
  123. [rr_name, id, rdtype])
  124. datas = cur.fetchall()
  125. cur.close()
  126. conn.close()
  127. return datas
  128. #########################################################################
  129. # get_zones_info:
  130. # returns all the zones' information.
  131. #########################################################################
  132. def get_zones_info(db_file):
  133. conn, cur = open(db_file)
  134. cur.execute("SELECT name, rdclass FROM zones")
  135. info = cur.fetchone()
  136. while info:
  137. yield info
  138. info = cur.fetchone()
  139. cur.close()
  140. conn.close()
  141. #########################################################################
  142. # get_zoneid:
  143. # returns the zone_id for a given zone name, or an empty
  144. # string if the zone is not found
  145. #########################################################################
  146. def get_zoneid(zone, cur):
  147. cur.execute("SELECT id FROM zones WHERE name = ?", [zone])
  148. row = cur.fetchone()
  149. if row:
  150. return row[0]
  151. else:
  152. return ''
  153. #########################################################################
  154. # reverse_name:
  155. # reverse the labels of a DNS name. (for example,
  156. # "bind10.isc.org." would become "org.isc.bind10.")
  157. #########################################################################
  158. def reverse_name(name):
  159. """Reverse the labels of a domain name; for example,
  160. given 'www.isc.org.', return 'org.isc.www.' This is needed
  161. for DNSSEC sort order."""
  162. new = name.split('.')
  163. new.reverse()
  164. if new[0] == '':
  165. new.pop(0)
  166. return '.'.join(new)+'.'
  167. #########################################################################
  168. # load:
  169. # load a zone into the SQL database.
  170. # input:
  171. # dbfile: the sqlite3 database fileanme
  172. # zone: the zone origin
  173. # reader: a generator function producing an iterable set of
  174. # name/ttl/class/rrtype/rdata-text tuples
  175. #########################################################################
  176. def load(dbfile, zone, reader):
  177. # if the zone name doesn't contain the trailing dot, automatically add it.
  178. if zone[-1] != '.':
  179. zone += '.'
  180. conn, cur = open(dbfile)
  181. old_zone_id = get_zoneid(zone, cur)
  182. temp = str(random.randrange(100000))
  183. cur.execute("INSERT INTO zones (name, rdclass) VALUES (?, 'IN')", [temp])
  184. new_zone_id = cur.lastrowid
  185. try:
  186. for name, ttl, rdclass, rdtype, rdata in reader():
  187. sigtype = ''
  188. if rdtype.lower() == 'rrsig':
  189. sigtype = rdata.split()[0]
  190. if rdtype.lower() == 'nsec3' or sigtype.lower() == 'nsec3':
  191. hash = name.split('.')[0]
  192. cur.execute("""INSERT INTO nsec3
  193. (zone_id, hash, owner, ttl, rdtype, rdata)
  194. VALUES (?, ?, ?, ?, ?, ?)""",
  195. [new_zone_id, hash, name, ttl, rdtype, rdata])
  196. elif rdtype.lower() == 'rrsig':
  197. cur.execute("""INSERT INTO records
  198. (zone_id, name, rname, ttl,
  199. rdtype, sigtype, rdata)
  200. VALUES (?, ?, ?, ?, ?, ?, ?)""",
  201. [new_zone_id, name, reverse_name(name), ttl,
  202. rdtype, sigtype, rdata])
  203. else:
  204. cur.execute("""INSERT INTO records
  205. (zone_id, name, rname, ttl, rdtype, rdata)
  206. VALUES (?, ?, ?, ?, ?, ?)""",
  207. [new_zone_id, name, reverse_name(name), ttl,
  208. rdtype, rdata])
  209. except Exception as e:
  210. fail = "Error while loading " + zone + ": " + e.args[0]
  211. raise Sqlite3DSError(fail)
  212. if old_zone_id:
  213. cur.execute("DELETE FROM zones WHERE id=?", [old_zone_id])
  214. cur.execute("UPDATE zones SET name=? WHERE id=?", [zone, new_zone_id])
  215. conn.commit()
  216. cur.execute("DELETE FROM records WHERE zone_id=?", [old_zone_id])
  217. cur.execute("DELETE FROM nsec3 WHERE zone_id=?", [old_zone_id])
  218. conn.commit()
  219. else:
  220. cur.execute("UPDATE zones SET name=? WHERE id=?", [zone, new_zone_id])
  221. conn.commit()
  222. cur.close()
  223. conn.close()