convertdb.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. # ============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it 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) 2013 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. from __future__ import print_function
  20. import os
  21. import shutil
  22. import time
  23. from pwman.util.crypto import CryptoEngine
  24. import pwman.data.factory
  25. from pwman.util.callback import CLICallback
  26. from pwman.data.nodes import NewNode
  27. from pwman.data.tags import Tag
  28. from pwman.data.database import Database, DatabaseException
  29. import sqlite3 as sqlite
  30. import pwman.util.config as config
  31. import cPickle
  32. _NEWVERSION = 0.4
  33. class SQLiteDatabaseReader(Database):
  34. """SQLite Database implementation"""
  35. def __init__(self, filename=None):
  36. """Initialise SQLitePwmanDatabase instance."""
  37. Database.__init__(self)
  38. try:
  39. self._filename = config.get_value('Database', 'filename')
  40. except KeyError as e:
  41. raise DatabaseException(
  42. "SQLite: missing config parameter [%s]" % (e))
  43. def _open(self):
  44. try:
  45. self._con = sqlite.connect(self._filename)
  46. self._cur = self._con.cursor()
  47. self._checktables()
  48. except sqlite.DatabaseError as e:
  49. raise DatabaseException("SQLite: %s" % (e))
  50. def close(self):
  51. self._cur.close()
  52. self._con.close()
  53. def getnodes(self, ids):
  54. nodes = []
  55. for i in ids:
  56. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  57. try:
  58. self._cur.execute(sql, [i])
  59. row = self._cur.fetchone()
  60. if row is not None:
  61. node = cPickle.loads(str(row[0]))
  62. node.set_id(i)
  63. nodes.append(node)
  64. except sqlite.DatabaseError as e:
  65. raise DatabaseException("SQLite: %s" % (e))
  66. return nodes
  67. def listnodes(self):
  68. sql = ''
  69. params = []
  70. if len(self._filtertags) == 0:
  71. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  72. else:
  73. first = True
  74. for t in self._filtertags:
  75. if not first:
  76. sql += " INTERSECT "
  77. else:
  78. first = False
  79. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS "
  80. " ON TAG = TAGS.ID"
  81. " WHERE TAGS.DATA = ? ")
  82. params.append(cPickle.dumps(t))
  83. try:
  84. self._cur.execute(sql, params)
  85. ids = []
  86. row = self._cur.fetchone()
  87. while (row is not None):
  88. ids.append(row[0])
  89. row = self._cur.fetchone()
  90. return ids
  91. except sqlite.DatabaseError as e:
  92. raise DatabaseException("SQLite: %s" % (e))
  93. def _commit(self):
  94. try:
  95. self._con.commit()
  96. except sqlite.DatabaseError as e:
  97. self._con.rollback()
  98. raise DatabaseException(
  99. "SQLite: Error commiting data to db [%s]" % (e))
  100. def _tagids(self, tags):
  101. ids = []
  102. for t in tags:
  103. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  104. if not isinstance(t, Tag):
  105. raise DatabaseException(
  106. "Tried to insert foreign object into database [%s]", t)
  107. data = cPickle.dumps(t)
  108. try:
  109. self._cur.execute(sql, [data])
  110. row = self._cur.fetchone()
  111. if (row is not None):
  112. ids.append(row[0])
  113. else:
  114. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  115. self._cur.execute(sql, [data])
  116. ids.append(self._cur.lastrowid)
  117. except sqlite.DatabaseError as e:
  118. raise DatabaseException("SQLite: %s" % (e))
  119. return ids
  120. def _checktables(self):
  121. """ Check if the Pwman tables exist """
  122. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  123. if (self._cur.fetchone() is None):
  124. # table doesn't exist, create it
  125. # SQLite does have constraints implemented at the moment
  126. # so datatype will just be a string
  127. self._cur.execute("CREATE TABLE NODES "
  128. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  129. "DATA BLOB NOT NULL)")
  130. self._cur.execute("CREATE TABLE TAGS "
  131. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  132. "DATA BLOB NOT NULL UNIQUE)")
  133. self._cur.execute("CREATE TABLE LOOKUP "
  134. "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  135. " PRIMARY KEY(NODE, TAG))")
  136. self._cur.execute("CREATE TABLE KEY "
  137. + "(THEKEY TEXT NOT NULL DEFAULT '')")
  138. self._cur.execute("INSERT INTO KEY VALUES('')")
  139. try:
  140. self._con.commit()
  141. except DatabaseException as e:
  142. self._con.rollback()
  143. raise e
  144. def loadkey(self):
  145. """
  146. fetch the key to database. the key is also stored
  147. encrypted.
  148. """
  149. self._cur.execute("SELECT THEKEY FROM KEY")
  150. keyrow = self._cur.fetchone()
  151. if (keyrow[0] == ''):
  152. return None
  153. else:
  154. return keyrow[0]
  155. class DBConverter(object):
  156. """
  157. A general class to provide a base template for converting a database
  158. from one version to another
  159. """
  160. def __init__(self, args, config):
  161. self.dbname = config.get_value('Database', 'filename')
  162. self.dbtype = config.get_value("Database", "type")
  163. if not args.output:
  164. self.newdb_name = self.dbname
  165. else:
  166. self.newdb_name = '.new-%s'.join(os.path.splitext(self.dbname))
  167. @staticmethod
  168. def detect_db_version(self, filename):
  169. """
  170. This method should accept a pwman db file name, and it should try to
  171. detect which database version it is.
  172. """
  173. pass
  174. @staticmethod
  175. def invoke_converter(dbversion, future_version):
  176. """
  177. this method should accept the two parameters and according to them
  178. invoke the right converter
  179. """
  180. pass
  181. def backup_old_db(self):
  182. print("Will convert the following Database: %s " % self.dbname)
  183. if os.path.exists(config.get_value("Database", "filename")):
  184. dbver = pwman.data.factory.check_db_version(self.dbtype)
  185. self.dbver = float(dbver)
  186. backup = '.backup-%s'.join(os.path.splitext(self.dbname)) % \
  187. time.strftime(
  188. '%Y-%m-%d-%H:%M')
  189. shutil.copy(self.dbname, backup)
  190. print("backup created in ", backup)
  191. def read_old_db(self):
  192. raise Exception("This methodod should be overriden")
  193. def create_new_db(self, new_version=_NEWVERSION):
  194. if os.path.exists(self.newdb_name):
  195. os.remove(self.newdb_name)
  196. self.newdb = pwman.data.factory.create(self.dbtype, new_version,
  197. self.newdb_name)
  198. self.newdb._open()
  199. def convert_nodes(self):
  200. raise Exception("This methodod should be overriden")
  201. def save_new_nodes_to_db(self):
  202. self.newdb.addnodes(self.NewNodes)
  203. self.newdb._commit()
  204. def save_old_key(self):
  205. raise Exception("This methodod should be overriden")
  206. def print_success(self):
  207. print("pwman successfully converted the old database to the new "
  208. "format.\nPlease run `pwman3 -d %s` to make sure your password "
  209. "and data are still correct. If you found errors, please "
  210. "report a bug in Pwman homepage in github. " % self.newdb_name)
  211. def run(self):
  212. self.backup_old_db()
  213. self.read_old_db()
  214. self.create_new_db()
  215. self.convert_nodes()
  216. self.save_new_nodes_to_db()
  217. self.save_old_key()
  218. self.print_success()
  219. class PwmanConvertDB(DBConverter):
  220. """
  221. Class to migrate from DB in version 0.3 to
  222. DB used in version 0.4 to 0.5.
  223. """
  224. def read_old_db(self):
  225. "read the old db and get all nodes"
  226. self.db = SQLiteDatabaseReader()
  227. enc = CryptoEngine.get()
  228. enc.set_callback(CLICallback())
  229. self.db.open()
  230. self.oldnodes = self.db.listnodes()
  231. self.oldnodes = self.db.getnodes(self.oldnodes)
  232. def save_old_key(self):
  233. enc = CryptoEngine.get()
  234. self.oldkey = enc.get_cryptedkey()
  235. self.newdb.savekey(self.oldkey)
  236. def convert_nodes(self):
  237. """convert old nodes instances to new format"""
  238. self.NewNodes = []
  239. for node in self.oldnodes:
  240. username = node.get_username()
  241. password = node.get_password()
  242. url = node.get_url()
  243. notes = node.get_notes()
  244. tags = node.get_tags()
  245. tags_strings = [tag._name for tag in tags]
  246. newNode = NewNode()
  247. newNode.username = username
  248. newNode.password = password
  249. newNode.url = url
  250. newNode.notes = notes
  251. newNode.tags = tags_strings
  252. self.NewNodes.append(newNode)
  253. class PwmanConvertKey(DBConverter):
  254. def read_old_db(self):
  255. enc = CryptoEngine.get()
  256. enc.set_callback(CLICallback())
  257. self.db.open()
  258. self.oldnodes = self.db.listnodes()
  259. self.oldnodes = self.db.getnodes(self.oldnodes)
  260. def save_old_key(self):
  261. CryptoEngine._instance = None
  262. enc = CryptoEngine.get(0.5)
  263. self.oldkey = enc.get_cryptedkey()
  264. self.newdb.savekey(self.oldkey)