sqlite.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # ============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute iut and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. # ============================================================================
  17. # Copyright (C) 2012, 2013, 2014 Oz Nahum Tiram <nahumoz@gmail.com>
  18. # ============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. # ============================================================================
  21. """SQLite Database implementation."""
  22. from pwman.data.database import Database, DatabaseException
  23. from pwman.data.database import __DB_FORMAT__
  24. import sqlite3 as sqlite
  25. class SQLite(Database):
  26. @classmethod
  27. def check_db_version(cls, fname):
  28. """
  29. check the database version.
  30. """
  31. con = sqlite.connect(fname)
  32. cur = con.cursor()
  33. cur.execute("PRAGMA TABLE_INFO(DBVERSION)")
  34. row = cur.fetchone()
  35. try:
  36. return row[-2]
  37. except IndexError: # pragma: no cover
  38. raise DatabaseException("Something seems fishy with the DB")
  39. def __init__(self, filename, dbformat=__DB_FORMAT__):
  40. """Initialise SQLitePwmanDatabase instance."""
  41. self._filename = filename
  42. self.dbformat = dbformat
  43. def _open(self):
  44. self._con = sqlite.connect(self._filename)
  45. self._cur = self._con.cursor()
  46. self._create_tables()
  47. def listnodes(self, filter=None):
  48. """return a list of node ids"""
  49. if not filter:
  50. sql_all = "SELECT ID FROM NODE"
  51. self._cur.execute(sql_all)
  52. ids = self._cur.fetchall()
  53. return [id[0] for id in ids]
  54. else:
  55. tagid = self._get_tag(filter)
  56. if not tagid:
  57. return []
  58. sql_filter = "SELECT NODEID FROM LOOKUP WHERE TAGID = ? "
  59. self._cur.execute(sql_filter, (tagid))
  60. ids = self._cur.fetchall()
  61. return [id[0] for id in ids]
  62. def listtags(self):
  63. self._clean_orphands()
  64. get_tags = "select data from tag"
  65. self._cur.execute(get_tags)
  66. tags = self._cur.fetchall()
  67. if tags:
  68. return [t[0] for t in tags]
  69. return []
  70. def _create_tables(self):
  71. self._cur.execute("PRAGMA TABLE_INFO(NODE)")
  72. if self._cur.fetchone() is not None:
  73. return
  74. self._cur.execute("CREATE TABLE NODE (ID INTEGER PRIMARY KEY "
  75. "AUTOINCREMENT, "
  76. "USER TEXT NOT NULL, "
  77. "PASSWORD TEXT NOT NULL, "
  78. "URL TEXT NOT NULL,"
  79. "NOTES TEXT NOT NULL)")
  80. self._cur.execute("CREATE TABLE TAG"
  81. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  82. "DATA BLOB NOT NULL UNIQUE)")
  83. self._cur.execute("CREATE TABLE LOOKUP ("
  84. "nodeid INTEGER NOT NULL, "
  85. "tagid INTEGER NOT NULL, "
  86. "FOREIGN KEY(nodeid) REFERENCES NODE(ID),"
  87. "FOREIGN KEY(tagid) REFERENCES TAG(ID))")
  88. self._cur.execute("CREATE TABLE CRYPTO"
  89. "(SEED TEXT,"
  90. " DIGEST TEXT)")
  91. # create a table to hold DB version info
  92. self._cur.execute("CREATE TABLE DBVERSION"
  93. "(VERSION TEXT NOT NULL DEFAULT '%s')" %
  94. self.dbformat)
  95. self._cur.execute("INSERT INTO DBVERSION VALUES('%s')" %
  96. self.dbformat)
  97. try:
  98. self._con.commit()
  99. except DatabaseException as e: # pragma: no cover
  100. self._con.rollback()
  101. raise e
  102. def fetch_crypto_info(self):
  103. self._cur.execute("SELECT * FROM CRYPTO")
  104. keyrow = self._cur.fetchone()
  105. return keyrow
  106. def save_crypto_info(self, seed, digest):
  107. """save the random seed and the digested key"""
  108. self._cur.execute("DELETE FROM CRYPTO")
  109. self._cur.execute("INSERT INTO CRYPTO VALUES(?, ?)", [seed, digest])
  110. self._con.commit()
  111. def add_node(self, node):
  112. sql = ("INSERT INTO NODE(USER, PASSWORD, URL, NOTES)"
  113. "VALUES(?, ?, ?, ?)")
  114. node_tags = list(node)
  115. node, tags = node_tags[:4], node_tags[-1]
  116. self._cur.execute(sql, (node))
  117. self._setnodetags(self._cur.lastrowid, tags)
  118. self._con.commit()
  119. def _get_tag(self, tagcipher):
  120. sql_search = "SELECT ID FROM TAG WHERE DATA = ?"
  121. self._cur.execute(sql_search, ([tagcipher]))
  122. rv = self._cur.fetchone()
  123. return rv
  124. def _get_or_create_tag(self, tagcipher):
  125. rv = self._get_tag(tagcipher)
  126. if rv:
  127. return rv[0]
  128. else:
  129. sql_insert = "INSERT INTO TAG(DATA) VALUES(?)"
  130. self._cur.execute(sql_insert, ([tagcipher]))
  131. return self._cur.lastrowid
  132. def _update_tag_lookup(self, nodeid, tid):
  133. sql_lookup = "INSERT INTO LOOKUP(nodeid, tagid) VALUES(?,?)"
  134. self._cur.execute(sql_lookup, (nodeid, tid))
  135. self._con.commit()
  136. def _setnodetags(self, nodeid, tags):
  137. for tag in tags:
  138. tid = self._get_or_create_tag(tag)
  139. self._update_tag_lookup(nodeid, tid)
  140. def _get_node_tags(self, node):
  141. sql = "SELECT tagid FROM LOOKUP WHERE NODEID = ?"
  142. tagids = self._cur.execute(sql, (str(node[0]),)).fetchall()
  143. sql = ("SELECT DATA FROM TAG WHERE ID IN (%s)"
  144. "" % ','.join('?'*len(tagids)))
  145. tagids = [str(id[0]) for id in tagids]
  146. self._cur.execute(sql, (tagids))
  147. tags = self._cur.fetchall()
  148. for t in tags:
  149. yield t[0]
  150. def getnodes(self, ids):
  151. """
  152. get nodes as raw ciphertext
  153. """
  154. sql = "SELECT * FROM NODE WHERE ID IN (%s)" % ','.join('?'*len(ids))
  155. self._cur.execute(sql, (ids))
  156. nodes = self._cur.fetchall()
  157. nodes_w_tags = []
  158. for node in nodes:
  159. tags = list(self._get_node_tags(node))
  160. nodes_w_tags.append(list(node) + tags)
  161. return nodes_w_tags
  162. def editnode(self, nid, **kwargs):
  163. tags = kwargs.pop('tags', None)
  164. sql = ("UPDATE NODE SET %s WHERE ID = ? "
  165. "" % ','.join('%s=?' % k for k in list(kwargs)))
  166. self._cur.execute(sql, (list(kwargs.values()) + [nid]))
  167. if tags:
  168. # update all old node entries in lookup
  169. # create new entries
  170. # clean all old tags
  171. sql_clean = "DELETE FROM LOOKUP WHERE NODEID=?"
  172. self._cur.execute(sql_clean, (str(nid),))
  173. self._setnodetags(nid, tags)
  174. self._con.commit()
  175. def removenodes(self, nids):
  176. sql_rm = "delete from node where id in (%s)" % ','.join('?'*len(nids))
  177. self._cur.execute(sql_rm, (nids))
  178. self._con.commit()
  179. def _clean_orphands(self):
  180. clean = ("delete from tag where not exists "
  181. "(select 'x' from lookup l where l.tagid = tag.id)")
  182. self._cur.execute(clean)
  183. self._con.commit()
  184. def savekey(self, key):
  185. salt, digest = key.split('$6$')
  186. sql = "INSERT INTO CRYPTO(SEED, DIGEST) VALUES(?,?)"
  187. self._cur.execute("DELETE FROM CRYPTO")
  188. self._cur.execute(sql, (salt, digest))
  189. self._digest = digest.encode('utf-8')
  190. self._salt = salt.encode('utf-8')
  191. self._con.commit()
  192. def loadkey(self):
  193. # TODO: rename this method!
  194. """
  195. return _keycrypted
  196. """
  197. sql = "SELECT * FROM CRYPTO"
  198. try:
  199. seed, digest = self._cur.execute(sql).fetchone()
  200. return seed + u'$6$' + digest
  201. except TypeError:
  202. return None
  203. def close(self):
  204. self._clean_orphands()
  205. self._cur.close()
  206. self._con.close()