[Branch ~piorun/piorun/devel] Rev 65: certificates storing in database instead of files

5 views
Skip to first unread message

nor...@launchpad.net

unread,
Dec 31, 2007, 9:10:11 PM12/31/07
to piorun...@googlegroups.com
------------------------------------------------------------
revno: 65
committer: doza <doza@orkan>
branch nick: devel
timestamp: Tue 2008-01-01 03:09:47 +0100
message:
certificates storing in database instead of files
modified:
res/ui.xml
src/Chat.boo
src/Database.boo
src/Piorun.boo
src/Tls.boo
src/actions/EditActions.boo

=== modified file 'res/ui.xml'
--- a/res/ui.xml 2007-12-30 22:30:41 +0000
+++ b/res/ui.xml 2008-01-01 02:09:47 +0000
@@ -47,7 +47,8 @@
<menuitem action="ChatHistory" />
<menuitem action="ChatSearch" />
<separator />
- <menuitem action="EditClearChat" />
+ <menuitem action="ChatClear" />
+ <menuitem action="ChatEnd" />
</menu>
<menu action="ContactMenu">
<menuitem action="ContactAdd" />
@@ -106,7 +107,7 @@
<separator />
<toolitem action="ChatHistory" />
<toolitem action="ChatSearch" />
- <toolitem action="EditClearChat" />
+ <toolitem action="ChatEnd" />
</toolbar>
<popup name="ContactPopup">
<menuitem action="ContactVCard" />

=== modified file 'src/Chat.boo'
--- a/src/Chat.boo 2007-12-30 22:30:41 +0000
+++ b/src/Chat.boo 2008-01-01 02:09:47 +0000
@@ -366,6 +366,9 @@
Timestamps:
get:
return timestamps
+ [getter(End)] end as Action
+ clear as Action
+

def constructor(session as Session):
super('Contact')
@@ -403,6 +406,17 @@
App.Conf.ShowTimestamps.Changed += do:
timestamps.Active = App.Conf.ShowTimestamps.Value

+ end = Action('ChatEnd', _('_End conversation'), null, Gtk.Stock.Close)
+ Add(end)
+# end.Activated += session.Chat.OnChatHistory
+# AccelMap.AddEntry('<piorun>/chat/history', cast(uint,Gdk.Key.h), ctrl)
+ end.AccelPath = '<piorun>/chat/end'
+
+ clear = Action("ChatClear", _('_Clear chat'), null, Gtk.Stock.Clear)
+ Add(clear)
+ clear.Activated += { session.Chat.ChatView.Clear(self, null) }
+
+
def Init():
App.Conf.UseSpellchecking.Changed += do:
spellchecking.Active = App.Conf.UseSpellchecking.Value

=== modified file 'src/Database.boo'
--- a/src/Database.boo 2007-12-30 22:30:41 +0000
+++ b/src/Database.boo 2008-01-01 02:09:47 +0000
@@ -16,8 +16,6 @@
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.

-
-
namespace Piorun

import Gtk
@@ -26,6 +24,7 @@
import Piorun.Xmpp
import System
import System.Collections
+import System.Collections.Generic
import System.Collections.Specialized
import System.Data
import System.Diagnostics
@@ -35,15 +34,20 @@
class Database:

# 0 means uni
- db_version as int
+
+ Version = 1

newFile as bool
connection as IDbConnection
+
+ upgraders = (UpgradeTo1,)
+

def constructor():
pass

- def InitDB(filename as string):
+ def Init(filename as string):
+ # connect
newFile = not File.Exists(filename)
connection = SqliteConnection("URI=file:" + filename)
if not connection:
@@ -52,12 +56,46 @@
connection.Open()
except e:
raise ApplicationException('Error opening database file '+filename+':\n'+e.Message)
- version = GetDBVersion()
- debug version
- version = 0 # force scheme creation
- if version == 0:
- debug 'rrr'
- CreateScheme()
+
+ # check version and run upgraders chain if needed
+ prevVersion = GetVersion()
+# prevVersion = 0 # force scheme creation
+ debug prevVersion
+ try:
+ for upgrade in upgraders[prevVersion:Version]:
+ upgrade()
+ debug 'UPGRADE'
+ except e:
+ raise ApplicationException('Error upgrading database '+filename+':\n'+e.Message)
+
+
+ def UpgradeTo1():
+ q = """
+ drop table if exists info;
+ create table info(db_version integer);
+ insert into info(db_version) values(1);
+
+ drop table if exists entry;
+ create table entry(
+ id_entry integer primary key,
+ timestamp datetime,
+ id_conversation integer,
+ xml text,
+ nick_from text);
+
+ drop table if exists conversation;
+ create table conversation(
+ id_conversation integer primary key,
+ start_time datetime);
+
+ drop table if exists certificate;
+ create table certificate(
+ id_certificate integer primary key,
+ hash text,
+ raw blob);
+ """
+ debug q
+ ExecuteQuery(q)

def Esc(s as string) as string:
return s.Replace("'", "''")
@@ -67,12 +105,27 @@

def AddEntry(entry as HistoryEntry) as int:
q = """
- insert into entry(xml)
+ insert into entry(xml, timestamp)
values('${Esc(entry.Xml)}, ${entry.Timestamp.ToFileTime()}');
"""
debug q
return ExecuteQuery(q)
-
+
+ def GetHistoryDates() as (DateTime):
+ # suboptimal - maybe we should store date without time in separate field?
+ q = 'SELECT timestamp from entry'
+ reader = Read(q)
+ dates = (List of DateTime)()
+ d as DateTime
+ while reader.Read():
+ d = DateTime.FromFileTime(reader.GetInt32(0))
+ d = d.Date
+ if not dates.Contains(d):
+ dates.Add(d)
+ dates.Sort()
+ return dates.ToArray()
+
+
/*
def GetEntries() as List:
q = "SELECT Name, Owner, Contact, Comment, Version FROM DBInfo"
@@ -94,131 +147,76 @@
return []
*/

+
+ def AddCertificate(hash as string, raw as (byte)):
+ if not HasCertificate(hash):
+ using cmd = connection.CreateCommand():
+ cmd.CommandText = 'INSERT INTO certificate(hash, raw) VALUES(?, ?)'
+ phash = cmd.CreateParameter()
+ praw = cmd.CreateParameter()
+ cmd.Parameters.Add(phash)
+ cmd.Parameters.Add(praw)
+ phash.Value = hash
+ praw.Value = raw
+ cmd.ExecuteNonQuery()
+
+ def DelCertificate(hash as string):
+ using cmd = connection.CreateCommand():
+ cmd.CommandText = 'DELETE FROM certificate WHERE hash=?'
+ phash = cmd.CreateParameter()
+ cmd.Parameters.Add(phash)
+ phash.Value = hash
+ cmd.ExecuteNonQuery()
+
+ def HasCertificate(hash as string) as bool:
+ using cmd = connection.CreateCommand():
+ cmd.CommandText = 'SELECT id_certificate FROM certificate WHERE hash=?'
+ phash = cmd.CreateParameter()
+ cmd.Parameters.Add(phash)
+ phash.Value = hash
+ using reader = cmd.ExecuteReader() as SqliteDataReader:
+ return reader.Read()
+
+ def GetCertificate(hash as string) as (byte):
+ using cmd = connection.CreateCommand():
+ cmd.CommandText = 'SELECT raw FROM certificate where hash=?'
+ phash = SqliteParameter()
+ cmd.Parameters.Add(phash)
+ phash.Value = hash
+ using reader = cmd.ExecuteReader() as SqliteDataReader:
+ if reader.Read():
+ return reader.GetValue(0) as (byte)
+ else:
+ return null
+
+ def GetCertificates() as ((byte)):
+ certificates = (List of (byte))()
+ using cmd = connection.CreateCommand():
+ cmd.CommandText = 'SELECT raw FROM certificate'
+ using reader = cmd.ExecuteReader() as SqliteDataReader:
+ while reader.Read():
+ certificates.Add(reader.GetValue(0) as (byte))
+ return certificates.ToArray()
+
def ExecuteQuery(q as string) as int:
""" Execute a Query without any return results """
- cmd = connection.CreateCommand() as SqliteCommand
- cmd.CommandText = q
- cmd.ExecuteNonQuery()
- return cmd.LastInsertRowID()
+ using cmd = connection.CreateCommand() as SqliteCommand:
+ cmd.CommandText = q
+ cmd.ExecuteNonQuery()
+ return cmd.LastInsertRowID()

def Read(q as string) as IDataReader:
- cmd = connection.CreateCommand() as SqliteCommand
- cmd.CommandText = q
- return cmd.ExecuteReader()
+ using cmd = connection.CreateCommand() as SqliteCommand:
+ cmd.CommandText = q
+ return cmd.ExecuteReader()

- def GetDBVersion() as int:
+ private def GetVersion() as int:
+ """ For empty database returns 0 """
q = "select db_version from info"
using cmd = connection.CreateCommand():
cmd.CommandText = q
- try:
- using reader = cmd.ExecuteReader():
- if reader.FieldCount == 0:
- raise Exception("Can't find database information! Aborting...")
+ using reader = cmd.ExecuteReader():
+ if reader.Read():
return reader.GetInt32(0)
- except:
- return 0
-
-
- def CreateScheme():
- q = """
- drop table if exists info;
- create table info(db_version integer);
- insert into info(db_version) values(1);
-
- drop table if exists entry;
- create table entry(
- id_entry integer primary key,
- timestamp datetime,
- id_conversation integer,
- xml text,
- nick_from text);
-
- drop table if exists conversation;
- create table conversation(
- id_conversation integer primary key,
- start_time datetime);
- """
- debug q
- ExecuteQuery(q)
-/*
- if not FreshDatabase:
-
- # We need to upgrade...
- __DBInfo as DBInfo = null;
- try:
- __DBInfo = GetDBInfo();
- except:
- if not __DBInfo:
- __DBInfo = DBInfo();
- # Assuming version without DBInfo (1)
- __DBInfo.Version = -1
-
- Debug.Message("MovieDatabase.dll", "MovieDB", String.Format("Database version is {0}", __DBInfo.Version));
-/*
- // -1 to 0
- if (__DBInfo.Version < 0) {
- Console.WriteLine("Upgrading database to version 0...");
- Upgrades.UpgradeTo0();
- }
-
- // 0 to 3
- if (__DBInfo.Version < 3) {
- Console.WriteLine("Upgrading database to version 3...");
- Upgrades.UpgradeTo3();
- }
-
- // 3 to 4
- if (__DBInfo.Version < 4) {
- Console.WriteLine("Upgrading database to version 4...");
- Upgrades.UpgradeTo4();
- }
-
- // 3 to 4
- if (__DBInfo.Version < 5) {
- Console.WriteLine("Upgrading database to version 5...");
- Upgrades.UpgradeTo5();
- }
-
- else:
- // Create database
- CreateDatabase();
-*/
-
- /* Returns true if fresh database was created */
- def CreateDatabase() as bool:
- // Create table string
- string __MoviesQuery = "CREATE TABLE Movies (ID INTEGER PRIMARY KEY,";
- foreach (DataField __Field in Fields)
- {
- if (__Field.Name != "ID" )
- if (__Field.Type != DataFieldType.NUMBER) __MoviesQuery += __Field.SqlName + " TEXT,";
- else __MoviesQuery += __Field.SqlName + " INT,";
- }
-
- __MoviesQuery = __MoviesQuery.TrimEnd(',');
- __MoviesQuery += ")";
-
- // Create DBINfo query
- string __DBInfoQuery = "CREATE TABLE DBInfo (Name TEXT, Owner TEXT, Contact TEXT, Comment TEXT, Version TEXT)";
- string __DBInfoInsert = "INSERT INTO DBInfo (Name, Owner, Contact, Comment, Version) VALUES ('your database name', 'database owner' , 'e-mail or phone', 'additional notes' , '5')";
-
-
- try:
- Debug.Message("MovieDatabase.dll", "MovieDB", "Creating Movies table, QUERY=" + __MoviesQuery);
- ExecuteQuery(__MoviesQuery);
- Console.WriteLine("Creating fresh database, version {0}", "5")
- except:
- return false
-
- // If we managed to create the Movies table, we HAVE TO manage to create the rest
-
- try:
- ExecuteQuery(__DBInfoQuery);
- ExecuteQuery(__DBInfoInsert);
- except _Excp:
- raise Exception("Error during fresh database creation!", _Excp)
- return true
-
-*/
-
-
+ else:
+ return 0

=== modified file 'src/Piorun.boo'
--- a/src/Piorun.boo 2007-12-03 17:58:19 +0000
+++ b/src/Piorun.boo 2008-01-01 02:09:47 +0000
@@ -134,7 +134,7 @@
Conf.ShowTimestamps.Changed += { Tags.TimestampsVisible = Conf.ShowTimestamps.Value }

database = Database()
- database.InitDB(ConfigDirName + Sep + "data.sqlite")
+ database.Init(ConfigDirName + Sep + "data.sqlite")
history = History()

# display main window

=== modified file 'src/Tls.boo'
--- a/src/Tls.boo 2007-11-25 22:25:46 +0000
+++ b/src/Tls.boo 2008-01-01 02:09:47 +0000
@@ -111,8 +111,8 @@
[property(Cert)]
cert as X509.X509Certificate

- [property(FileName)]
- fileName as string
+ [property(Hash)]
+ hash as string

commonName as string

@@ -128,7 +128,7 @@

session as Session
[Widget("CertListDialog")]
- _dialog as Gtk.Dialog
+ _dialog as Gtk.Dialog

[Widget("DetailsButton")]
_detailsButton as Button
@@ -163,14 +163,13 @@
node as CertNode
parts as (string)
p as (string)
- for s in Directory.GetFiles(session.CertMgr.CertPath, "*.cert"):
+ for b in App.Database.GetCertificates():
node = CertNode()
- node.FileName = s
- debug node.FileName
try:
- node.Cert = X509.X509Certificate.CreateFromCertFile(node.FileName)
+ node.Cert = X509.X509Certificate(b)
+ node.Hash = node.Cert.GetCertHashString()
except e:
- print "Error while loading certificate file", node.FileName
+ print "Error while loading certificate"
print e
continue
parts = node.Cert.Subject.Split(char(','))
@@ -195,7 +194,7 @@
def OnDelete(o, args as System.EventArgs):
node = _nodeView.NodeSelection.SelectedNode as CertNode
try:
- File.Delete(node.FileName)
+ App.Database.DelCertificate(node.Hash)
except e:
return
_nodeStore.RemoveNode(node)
@@ -231,18 +230,17 @@

def constructor(session as Session):
self.session = session
- _certPath = App.ConfigDirName + App.Sep + "certificates"
- Directory.CreateDirectory(CertPath)

def Validate(cert as X509.X509Certificate, errors as (int)) as bool:
result = false
assert cert
lastCert = cert
- path = CertPath + App.Sep + cert.GetCertHashString() + ".cert"
+ hash = cert.GetCertHashString()
try:
# check if the certificate was already accepted
- if File.Exists(path):
- if cert.Equals(X509.X509Certificate.CreateFromCertFile(path)):
+ b = App.Database.GetCertificate(hash)
+ if b:
+ if cert.Equals(X509.X509Certificate(b)):
SafeConnection = true
return true
except e:
@@ -256,14 +254,11 @@
if result:
# add to known certificates
try:
- fs = System.IO.FileStream(path, FileMode.Create, FileAccess.Write)
b = cert.GetRawCertData()
- fs.Write(b, 0, b.Length)
+ App.Database.AddCertificate(hash, b)
except e:
print "ERROR: Could not save certificate"
print e
- ensure:
- fs.Close()
SafeConnection = result
return result

@@ -323,31 +318,27 @@
else:
certValDialog.Hide()

-
private def GetCertificateError(error as int) as string:
m as string = null
if error == -2146762490: # "CERT_E_PURPOSE 0x800B0106"
- m = "Certificate is being used for a purpose other than "+\
- "that for which it is permitted"
+ m = _('Certificate is being used for a purpose other than that for which it is permitted')
elif error == -2146762481: # "CERT_E_CN_NO_MATCH 0x800B010F";
- m = "Certificate's CN name does not match the passed value";
+ m = _("Certificate's CN name does not match the passed value")
elif error == -2146869223: # "TRUST_E_BASIC_CONSTRAINTS 0x80096019"
- m = "Cerficates basic constraints are invalid or missing"
- elif error == -2146869232: # "TRUST_E_BAD_DIGEST 0x80096010";
- m = "Objects digest did not verify"
+ m = _('Cerficates basic constraints are invalid or missing')
+ elif error == -2146869232: # "TRUST_E_BAD_DIGEST 0x80096010';
+ m = _('Objects digest did not verify')
elif error == -2146762494: # "CERT_E_VALIDITYPERIODNESTING 0x800B0102";
- m = "The validity periods of the certification chain do "+\
- "not nest correctly"
+ m = _('The validity periods of the certification chain do not nest correctly')
elif error == -2146762495: # "CERT_E_EXPIRED 0x800B0101"
- m = "Required certificate is not within its validity period"
+ m = _('Required certificate is not within its validity period')
elif error == -2146762486: # "CERT_E_CHAINING 0x800B010A";
- m = "A chain of certs did not chain as they should "+\
- "in a certain application of chaining."
+ m = _('A chain of certs did not chain as they should in a certain application of chaining.')
elif error == -2146762487: # "CERT_E_UNTRUSTEDROOT 0x800B0109"
- m = "A certification chain processed correctly, "+\
- "but terminated in a root certificate which is not "+\
- "trusted by the trust provider."
+ m = _('A certification chain processed correctly, ')+\
+ _('but terminated in a root certificate which is not trusted by the trust provider.')
else:
- m = " unknown"
+ m = ' unknown'
return "${m} (error #${error})"
+

\ No newline at end of file

=== modified file 'src/actions/EditActions.boo'
--- a/src/actions/EditActions.boo 2007-12-30 22:30:41 +0000
+++ b/src/actions/EditActions.boo 2008-01-01 02:09:47 +0000
@@ -29,7 +29,6 @@
session as Session

editMenu as Action
- editClearChat as Action
editCertificates as Action
editCut as Action
editCopy as Action
@@ -61,11 +60,6 @@
Add(editDelete)
# editClearChat.Activated += { session.Chat.ChatView.Clear(self, null) }

-
- editClearChat = Action("EditClearChat", _('_Clear chat'), null, Gtk.Stock.Clear)
- Add(editClearChat)
- editClearChat.Activated += { session.Chat.ChatView.Clear(self, null) }
-
editCertificates = Action("EditCertificates", _("_Certificates"), null, null)
Add(editCertificates)
editCertificates.Activated += do:

--

https://code.launchpad.net/~piorun/piorun/devel

You are receiving this branch notification because you are subscribed to it.

Reply all
Reply to author
Forward
0 new messages