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