blob: 7f3d8298626c4b0b735c4c0113c56e8cf4ee26c1 [file] [log] [blame]
Alexander Afanasyev71b43e72012-12-27 01:03:43 -08001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2012 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
19 * Zhenkai Zhu <zhenkai@cs.ucla.edu>
20 */
21
22#include "sqlite-helper.h"
23// #include "sync-log.h"
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080024#include "hash-string-converter.h"
Alexander Afanasyev71b43e72012-12-27 01:03:43 -080025
26// Other options: VP_md2, EVP_md5, EVP_sha, EVP_sha1, EVP_sha256, EVP_dss, EVP_dss1, EVP_mdc2, EVP_ripemd160
27#define HASH_FUNCTION EVP_sha256
28
29#include <boost/throw_exception.hpp>
30typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
31// typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int;
32
33
34const std::string INIT_DATABASE = "\
35CREATE TABLE \
36 SyncNodes( \
37 device_id INTEGER PRIMARY KEY AUTOINCREMENT, \
38 device_name TEXT NOT NULL, \
39 description TEXT, \
40 seq_no INTEGER NOT NULL, \
41 last_known_tdi TEXT, \
42 last_update TIMESTAMP \
43 ); \
44 \
45CREATE INDEX SyncNodes_device_name ON SyncNodes (device_name); \
46 \
47CREATE TABLE SyncLog( \
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080048 state_id INTEGER PRIMARY KEY AUTOINCREMENT, \
49 state_hash BLOB NOT NULL UNIQUE, \
Alexander Afanasyev71b43e72012-12-27 01:03:43 -080050 last_update TIMESTAMP NOT NULL \
51 ); \
52 \
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080053CREATE TABLE \
54 SyncStateNodes( \
55 id INTEGER PRIMARY KEY AUTOINCREMENT, \
56 state_id INTEGER NOT NULL \
57 REFERENCES SyncLog (state_id) ON UPDATE CASCADE ON DELETE CASCADE, \
Alexander Afanasyev71b43e72012-12-27 01:03:43 -080058 device_id INTEGER NOT NULL \
59 REFERENCES SyncNodes (device_id) ON UPDATE CASCADE ON DELETE CASCADE, \
60 seq_no INTEGER NOT NULL \
61 ); \
62 \
63CREATE INDEX SyncStateNodes_device_id ON SyncStateNodes (device_id); \
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080064CREATE INDEX SyncStateNodes_state_id ON SyncStateNodes (state_id); \
65CREATE INDEX SyncStateNodes_seq_no ON SyncStateNodes (seq_no); \
Alexander Afanasyev71b43e72012-12-27 01:03:43 -080066 \
67CREATE TRIGGER SyncLogGuard_trigger \
68 BEFORE INSERT ON SyncLog \
69 FOR EACH ROW \
70 WHEN (SELECT state_hash \
71 FROM SyncLog \
72 WHERE state_hash=NEW.state_hash) \
73 IS NOT NULL \
74 BEGIN \
75 DELETE FROM SyncLog WHERE state_hash=NEW.state_hash; \
76 END; \
77";
78
79DbHelper::DbHelper (const std::string &path)
80{
81 int res = sqlite3_open((path+"chronoshare.db").c_str (), &m_db);
82 if (res != SQLITE_OK)
83 {
84 BOOST_THROW_EXCEPTION (Error::Db ()
85 << errmsg_info_str ("Cannot open/create dabatabase: [" + path + "chronoshare.db" + "]"));
86 }
87
88 res = sqlite3_create_function (m_db, "hash", 2, SQLITE_ANY, 0, 0,
89 DbHelper::hash_xStep, DbHelper::hash_xFinal);
90 if (res != SQLITE_OK)
91 {
92 BOOST_THROW_EXCEPTION (Error::Db ()
93 << errmsg_info_str ("Cannot create function ``hash''"));
94 }
95
96 // Alex: determine if tables initialized. if not, initialize... not sure what is the best way to go...
97 // for now, just attempt to create everything
98
99 char *errmsg = 0;
100 res = sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, &errmsg);
Alexander Afanasyev71b43e72012-12-27 01:03:43 -0800101 if (res != SQLITE_OK && errmsg != 0)
102 {
103 std::cerr << "DEBUG: " << errmsg << std::endl;
104 sqlite3_free (errmsg);
105 }
106}
107
108DbHelper::~DbHelper ()
109{
110 int res = sqlite3_close (m_db);
111 if (res != SQLITE_OK)
112 {
113 // complain
114 }
115}
116
117void
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -0800118DbHelper::rememberStateInStateLog ()
119{
120 char *errmsg = 0;
121 int res = sqlite3_exec (m_db, " \
122BEGIN TRANSACTION; \
123INSERT INTO SyncLog \
124 (state_hash, last_update) \
125 SELECT \
126 hash(device_name, seq_no), datetime('now') \
127 FROM SyncNodes \
128 ORDER BY device_name; \
129 \
130INSERT INTO SyncStateNodes \
131 (state_id, device_id, seq_no) \
132 SELECT last_insert_rowid(), device_id, seq_no \
133 FROM SyncNodes; \
134COMMIT; \
135",
136 NULL, NULL, &errmsg);
137 if (res != SQLITE_OK && errmsg != 0)
138 {
139 std::cerr << "DEBUG: " << errmsg << std::endl;
140 sqlite3_free (errmsg);
141 }
142}
143
144
145void
Alexander Afanasyev71b43e72012-12-27 01:03:43 -0800146DbHelper::hash_xStep (sqlite3_context *context, int argc, sqlite3_value **argv)
147{
148 if (argc != 2)
149 {
150 // _LOG_ERROR ("Wrong arguments are supplied for ``hash'' function");
151 sqlite3_result_error (context, "Wrong arguments are supplied for ``hash'' function", -1);
152 return;
153 }
154 if (sqlite3_value_type (argv[0]) != SQLITE_TEXT ||
155 sqlite3_value_type (argv[1]) != SQLITE_INTEGER)
156 {
157 // _LOG_ERROR ("Hash expects (text,integer) parameters");
158 sqlite3_result_error (context, "Hash expects (text,integer) parameters", -1);
159 return;
160 }
161
162 EVP_MD_CTX **hash_context = reinterpret_cast<EVP_MD_CTX **> (sqlite3_aggregate_context (context, sizeof (EVP_MD_CTX *)));
163
164 if (hash_context == 0)
165 {
166 sqlite3_result_error_nomem (context);
167 return;
168 }
169
170 if (*hash_context == 0)
171 {
172 *hash_context = EVP_MD_CTX_create ();
173 EVP_DigestInit_ex (*hash_context, HASH_FUNCTION (), 0);
174 }
175
176 int nameBytes = sqlite3_value_bytes (argv[0]);
177 const unsigned char *name = sqlite3_value_text (argv[0]);
178 sqlite3_int64 seqno = sqlite3_value_int64 (argv[1]);
179
180 EVP_DigestUpdate (*hash_context, name, nameBytes);
181 EVP_DigestUpdate (*hash_context, &seqno, sizeof(sqlite3_int64));
182}
183
184void
185DbHelper::hash_xFinal (sqlite3_context *context)
186{
187 EVP_MD_CTX **hash_context = reinterpret_cast<EVP_MD_CTX **> (sqlite3_aggregate_context (context, sizeof (EVP_MD_CTX *)));
188
189 if (hash_context == 0)
190 {
191 sqlite3_result_error_nomem (context);
192 return;
193 }
194
195 if (*hash_context == 0) // no rows
196 {
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -0800197 char charNullResult = 0;
198 sqlite3_result_blob (context, &charNullResult, 1, SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
Alexander Afanasyev71b43e72012-12-27 01:03:43 -0800199 return;
200 }
201
202 unsigned char *hash = new unsigned char [EVP_MAX_MD_SIZE];
203 unsigned int hashLength = 0;
204
205 int ok = EVP_DigestFinal_ex (*hash_context,
206 hash, &hashLength);
207
208 sqlite3_result_blob (context, hash, hashLength, SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
209 delete [] hash;
210
211 EVP_MD_CTX_destroy (*hash_context);
212}
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -0800213
214void
215DbHelper::hash2str_Func (sqlite3_context *context, int argc, sqlite3_value **argv)
216{
217 if (argc != 1 || sqlite3_value_type (argv[0]) != SQLITE_BLOB)
218 {
219 sqlite3_result_error (context, "Wrong arguments are supplied for ``hash2str'' function", -1);
220 return;
221 }
222
223 int hashBytes = sqlite3_value_bytes (argv[0]);
224 const void *hash = sqlite3_value_blob (argv[0]);
225
226 std::ostringstream os;
227 os << Hash (hash, hashBytes);
228 sqlite3_result_text (context, os.str ().c_str (), -1, SQLITE_TRANSIENT);
229}
230
231void
232DbHelper::str2hash_Func (sqlite3_context *context, int argc, sqlite3_value **argv)
233{
234 if (argc != 1 || sqlite3_value_type (argv[0]) != SQLITE_TEXT)
235 {
236 sqlite3_result_error (context, "Wrong arguments are supplied for ``str2hash'' function", -1);
237 return;
238 }
239
240 size_t hashTextBytes = sqlite3_value_bytes (argv[0]);
241 const unsigned char *hashText = sqlite3_value_text (argv[0]);
242
243 Hash hash (std::string (reinterpret_cast<const char*> (hashText), hashTextBytes));
244 sqlite3_result_blob (context, hash.GetHash (), hash.GetHashBytes (), SQLITE_TRANSIENT);
245}
246