convertdb.py 9.3 KB

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