]> git.lizzy.rs Git - dragonfireclient.git/blob - src/rollback.cpp
Fix possible unreliable behavior due to uninitialized variables
[dragonfireclient.git] / src / rollback.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "rollback.h"
21 #include <fstream>
22 #include <list>
23 #include <sstream>
24 #include "log.h"
25 #include "mapnode.h"
26 #include "gamedef.h"
27 #include "nodedef.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "util/numeric.h"
31 #include "inventorymanager.h" // deserializing InventoryLocations
32 #include "sqlite3.h"
33 #include "filesys.h"
34
35 #define POINTS_PER_NODE (16.0)
36
37 #define SQLRES(f, good) \
38         if ((f) != (good)) {\
39                 throw FileNotGoodException(std::string("RollbackManager: " \
40                         "SQLite3 error (" __FILE__ ":" TOSTRING(__LINE__) \
41                         "): ") + sqlite3_errmsg(db)); \
42         }
43 #define SQLOK(f) SQLRES(f, SQLITE_OK)
44
45 #define SQLOK_ERRSTREAM(s, m)                             \
46         if ((s) != SQLITE_OK) {                               \
47                 errorstream << "RollbackManager: " << (m) << ": " \
48                         << sqlite3_errmsg(db) << std::endl;           \
49         }
50
51 #define FINALIZE_STATEMENT(statement) \
52         SQLOK_ERRSTREAM(sqlite3_finalize(statement), "Failed to finalize " #statement)
53
54 class ItemStackRow : public ItemStack {
55 public:
56         ItemStackRow & operator = (const ItemStack & other)
57         {
58                 *static_cast<ItemStack *>(this) = other;
59                 return *this;
60         }
61
62         int id;
63 };
64
65 struct ActionRow {
66         int          id;
67         int          actor;
68         time_t       timestamp;
69         int          type;
70         std::string  location, list;
71         int          index, add;
72         ItemStackRow stack;
73         int          nodeMeta;
74         int          x, y, z;
75         int          oldNode;
76         int          oldParam1, oldParam2;
77         std::string  oldMeta;
78         int          newNode;
79         int          newParam1, newParam2;
80         std::string  newMeta;
81         int          guessed;
82 };
83
84
85 struct Entity {
86         int         id;
87         std::string name;
88 };
89
90
91
92 RollbackManager::RollbackManager(const std::string & world_path,
93                 IGameDef * gamedef_) :
94         gamedef(gamedef_)
95 {
96         verbosestream << "RollbackManager::RollbackManager(" << world_path
97                 << ")" << std::endl;
98
99         std::string txt_filename = world_path + DIR_DELIM "rollback.txt";
100         std::string migrating_flag = txt_filename + ".migrating";
101         database_path = world_path + DIR_DELIM "rollback.sqlite";
102
103         bool created = initDatabase();
104
105         if (fs::PathExists(txt_filename) && (created ||
106                         fs::PathExists(migrating_flag))) {
107                 std::ofstream of(migrating_flag.c_str());
108                 of.close();
109                 migrate(txt_filename);
110                 fs::DeleteSingleFileOrEmptyDirectory(migrating_flag);
111         }
112 }
113
114
115 RollbackManager::~RollbackManager()
116 {
117         flush();
118
119         FINALIZE_STATEMENT(stmt_insert);
120         FINALIZE_STATEMENT(stmt_replace);
121         FINALIZE_STATEMENT(stmt_select);
122         FINALIZE_STATEMENT(stmt_select_range);
123         FINALIZE_STATEMENT(stmt_select_withActor);
124         FINALIZE_STATEMENT(stmt_knownActor_select);
125         FINALIZE_STATEMENT(stmt_knownActor_insert);
126         FINALIZE_STATEMENT(stmt_knownNode_select);
127         FINALIZE_STATEMENT(stmt_knownNode_insert);
128
129         SQLOK_ERRSTREAM(sqlite3_close(db), "Could not close db");
130 }
131
132
133 void RollbackManager::registerNewActor(const int id, const std::string &name)
134 {
135         Entity actor = {id, name};
136         knownActors.push_back(actor);
137 }
138
139
140 void RollbackManager::registerNewNode(const int id, const std::string &name)
141 {
142         Entity node = {id, name};
143         knownNodes.push_back(node);
144 }
145
146
147 int RollbackManager::getActorId(const std::string &name)
148 {
149         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
150                         iter != knownActors.end(); ++iter) {
151                 if (iter->name == name) {
152                         return iter->id;
153                 }
154         }
155
156         SQLOK(sqlite3_bind_text(stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL));
157         SQLRES(sqlite3_step(stmt_knownActor_insert), SQLITE_DONE);
158         SQLOK(sqlite3_reset(stmt_knownActor_insert));
159
160         int id = sqlite3_last_insert_rowid(db);
161         registerNewActor(id, name);
162
163         return id;
164 }
165
166
167 int RollbackManager::getNodeId(const std::string &name)
168 {
169         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
170                         iter != knownNodes.end(); ++iter) {
171                 if (iter->name == name) {
172                         return iter->id;
173                 }
174         }
175
176         SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL));
177         SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE);
178         SQLOK(sqlite3_reset(stmt_knownNode_insert));
179
180         int id = sqlite3_last_insert_rowid(db);
181         registerNewNode(id, name);
182
183         return id;
184 }
185
186
187 const char * RollbackManager::getActorName(const int id)
188 {
189         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
190                         iter != knownActors.end(); ++iter) {
191                 if (iter->id == id) {
192                         return iter->name.c_str();
193                 }
194         }
195
196         return "";
197 }
198
199
200 const char * RollbackManager::getNodeName(const int id)
201 {
202         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
203                         iter != knownNodes.end(); ++iter) {
204                 if (iter->id == id) {
205                         return iter->name.c_str();
206                 }
207         }
208
209         return "";
210 }
211
212
213 bool RollbackManager::createTables()
214 {
215         SQLOK(sqlite3_exec(db,
216                 "CREATE TABLE IF NOT EXISTS `actor` (\n"
217                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
218                 "       `name` TEXT NOT NULL\n"
219                 ");\n"
220                 "CREATE TABLE IF NOT EXISTS `node` (\n"
221                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
222                 "       `name` TEXT NOT NULL\n"
223                 ");\n"
224                 "CREATE TABLE IF NOT EXISTS `action` (\n"
225                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n"
226                 "       `actor` INTEGER NOT NULL,\n"
227                 "       `timestamp` TIMESTAMP NOT NULL,\n"
228                 "       `type` INTEGER NOT NULL,\n"
229                 "       `list` TEXT,\n"
230                 "       `index` INTEGER,\n"
231                 "       `add` INTEGER,\n"
232                 "       `stackNode` INTEGER,\n"
233                 "       `stackQuantity` INTEGER,\n"
234                 "       `nodeMeta` INTEGER,\n"
235                 "       `x` INT,\n"
236                 "       `y` INT,\n"
237                 "       `z` INT,\n"
238                 "       `oldNode` INTEGER,\n"
239                 "       `oldParam1` INTEGER,\n"
240                 "       `oldParam2` INTEGER,\n"
241                 "       `oldMeta` TEXT,\n"
242                 "       `newNode` INTEGER,\n"
243                 "       `newParam1` INTEGER,\n"
244                 "       `newParam2` INTEGER,\n"
245                 "       `newMeta` TEXT,\n"
246                 "       `guessedActor` INTEGER,\n"
247                 "       FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n"
248                 "       FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n"
249                 "       FOREIGN KEY (`oldNode`)   REFERENCES `node`(`id`),\n"
250                 "       FOREIGN KEY (`newNode`)   REFERENCES `node`(`id`)\n"
251                 ");\n"
252                 "CREATE INDEX IF NOT EXISTS `actionIndex` ON `action`(`x`,`y`,`z`,`timestamp`,`actor`);\n",
253                 NULL, NULL, NULL));
254         verbosestream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
255
256         return true;
257 }
258
259
260 bool RollbackManager::initDatabase()
261 {
262         verbosestream << "RollbackManager: Database connection setup" << std::endl;
263
264         bool needs_create = !fs::PathExists(database_path);
265         SQLOK(sqlite3_open_v2(database_path.c_str(), &db,
266                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL));
267
268         if (needs_create) {
269                 createTables();
270         }
271
272         SQLOK(sqlite3_prepare_v2(db,
273                 "INSERT INTO `action` (\n"
274                 "       `actor`, `timestamp`, `type`,\n"
275                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
276                 "       `x`, `y`, `z`,\n"
277                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
278                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
279                 "       `guessedActor`\n"
280                 ") VALUES (\n"
281                 "       ?, ?, ?,\n"
282                 "       ?, ?, ?, ?, ?, ?,\n"
283                 "       ?, ?, ?,\n"
284                 "       ?, ?, ?, ?,\n"
285                 "       ?, ?, ?, ?,\n"
286                 "       ?"
287                 ");",
288                 -1, &stmt_insert, NULL));
289
290         SQLOK(sqlite3_prepare_v2(db,
291                 "REPLACE INTO `action` (\n"
292                 "       `actor`, `timestamp`, `type`,\n"
293                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
294                 "       `x`, `y`, `z`,\n"
295                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
296                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
297                 "       `guessedActor`, `id`\n"
298                 ") VALUES (\n"
299                 "       ?, ?, ?,\n"
300                 "       ?, ?, ?, ?, ?, ?,\n"
301                 "       ?, ?, ?,\n"
302                 "       ?, ?, ?, ?,\n"
303                 "       ?, ?, ?, ?,\n"
304                 "       ?, ?\n"
305                 ");",
306                 -1, &stmt_replace, NULL));
307
308         SQLOK(sqlite3_prepare_v2(db,
309                 "SELECT\n"
310                 "       `actor`, `timestamp`, `type`,\n"
311                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
312                 "       `x`, `y`, `z`,\n"
313                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
314                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
315                 "       `guessedActor`\n"
316                 " FROM `action`\n"
317                 " WHERE `timestamp` >= ?\n"
318                 " ORDER BY `timestamp` DESC, `id` DESC",
319                 -1, &stmt_select, NULL));
320
321         SQLOK(sqlite3_prepare_v2(db,
322                 "SELECT\n"
323                 "       `actor`, `timestamp`, `type`,\n"
324                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
325                 "       `x`, `y`, `z`,\n"
326                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
327                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
328                 "       `guessedActor`\n"
329                 "FROM `action`\n"
330                 "WHERE `timestamp` >= ?\n"
331                 "       AND `x` IS NOT NULL\n"
332                 "       AND `y` IS NOT NULL\n"
333                 "       AND `z` IS NOT NULL\n"
334                 "       AND `x` BETWEEN ? AND ?\n"
335                 "       AND `y` BETWEEN ? AND ?\n"
336                 "       AND `z` BETWEEN ? AND ?\n"
337                 "ORDER BY `timestamp` DESC, `id` DESC\n"
338                 "LIMIT 0,?",
339                 -1, &stmt_select_range, NULL));
340
341         SQLOK(sqlite3_prepare_v2(db,
342                 "SELECT\n"
343                 "       `actor`, `timestamp`, `type`,\n"
344                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
345                 "       `x`, `y`, `z`,\n"
346                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
347                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
348                 "       `guessedActor`\n"
349                 "FROM `action`\n"
350                 "WHERE `timestamp` >= ?\n"
351                 "       AND `actor` = ?\n"
352                 "ORDER BY `timestamp` DESC, `id` DESC\n",
353                 -1, &stmt_select_withActor, NULL));
354
355         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`",
356                         -1, &stmt_knownActor_select, NULL));
357
358         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)",
359                         -1, &stmt_knownActor_insert, NULL));
360
361         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`",
362                         -1, &stmt_knownNode_select, NULL));
363
364         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)",
365                         -1, &stmt_knownNode_insert, NULL));
366
367         verbosestream << "SQL prepared statements setup correctly" << std::endl;
368
369         while (sqlite3_step(stmt_knownActor_select) == SQLITE_ROW) {
370                 registerNewActor(
371                         sqlite3_column_int(stmt_knownActor_select, 0),
372                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownActor_select, 1))
373                 );
374         }
375         SQLOK(sqlite3_reset(stmt_knownActor_select));
376
377         while (sqlite3_step(stmt_knownNode_select) == SQLITE_ROW) {
378                 registerNewNode(
379                         sqlite3_column_int(stmt_knownNode_select, 0),
380                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownNode_select, 1))
381                 );
382         }
383         SQLOK(sqlite3_reset(stmt_knownNode_select));
384
385         return needs_create;
386 }
387
388
389 bool RollbackManager::registerRow(const ActionRow & row)
390 {
391         sqlite3_stmt * stmt_do = (row.id) ? stmt_replace : stmt_insert;
392
393         bool nodeMeta = false;
394
395         SQLOK(sqlite3_bind_int  (stmt_do, 1, row.actor));
396         SQLOK(sqlite3_bind_int64(stmt_do, 2, row.timestamp));
397         SQLOK(sqlite3_bind_int  (stmt_do, 3, row.type));
398
399         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
400                 const std::string & loc = row.location;
401                 nodeMeta = (loc.substr(0, 9) == "nodemeta:");
402
403                 SQLOK(sqlite3_bind_text(stmt_do, 4, row.list.c_str(), row.list.size(), NULL));
404                 SQLOK(sqlite3_bind_int (stmt_do, 5, row.index));
405                 SQLOK(sqlite3_bind_int (stmt_do, 6, row.add));
406                 SQLOK(sqlite3_bind_int (stmt_do, 7, row.stack.id));
407                 SQLOK(sqlite3_bind_int (stmt_do, 8, row.stack.count));
408                 SQLOK(sqlite3_bind_int (stmt_do, 9, (int) nodeMeta));
409
410                 if (nodeMeta) {
411                         std::string::size_type p1, p2;
412                         p1 = loc.find(':') + 1;
413                         p2 = loc.find(',');
414                         std::string x = loc.substr(p1, p2 - p1);
415                         p1 = p2 + 1;
416                         p2 = loc.find(',', p1);
417                         std::string y = loc.substr(p1, p2 - p1);
418                         std::string z = loc.substr(p2 + 1);
419                         SQLOK(sqlite3_bind_int(stmt_do, 10, atoi(x.c_str())));
420                         SQLOK(sqlite3_bind_int(stmt_do, 11, atoi(y.c_str())));
421                         SQLOK(sqlite3_bind_int(stmt_do, 12, atoi(z.c_str())));
422                 }
423         } else {
424                 SQLOK(sqlite3_bind_null(stmt_do, 4));
425                 SQLOK(sqlite3_bind_null(stmt_do, 5));
426                 SQLOK(sqlite3_bind_null(stmt_do, 6));
427                 SQLOK(sqlite3_bind_null(stmt_do, 7));
428                 SQLOK(sqlite3_bind_null(stmt_do, 8));
429                 SQLOK(sqlite3_bind_null(stmt_do, 9));
430         }
431
432         if (row.type == RollbackAction::TYPE_SET_NODE) {
433                 SQLOK(sqlite3_bind_int (stmt_do, 10, row.x));
434                 SQLOK(sqlite3_bind_int (stmt_do, 11, row.y));
435                 SQLOK(sqlite3_bind_int (stmt_do, 12, row.z));
436                 SQLOK(sqlite3_bind_int (stmt_do, 13, row.oldNode));
437                 SQLOK(sqlite3_bind_int (stmt_do, 14, row.oldParam1));
438                 SQLOK(sqlite3_bind_int (stmt_do, 15, row.oldParam2));
439                 SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL));
440                 SQLOK(sqlite3_bind_int (stmt_do, 17, row.newNode));
441                 SQLOK(sqlite3_bind_int (stmt_do, 18, row.newParam1));
442                 SQLOK(sqlite3_bind_int (stmt_do, 19, row.newParam2));
443                 SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL));
444                 SQLOK(sqlite3_bind_int (stmt_do, 21, row.guessed ? 1 : 0));
445         } else {
446                 if (!nodeMeta) {
447                         SQLOK(sqlite3_bind_null(stmt_do, 10));
448                         SQLOK(sqlite3_bind_null(stmt_do, 11));
449                         SQLOK(sqlite3_bind_null(stmt_do, 12));
450                 }
451                 SQLOK(sqlite3_bind_null(stmt_do, 13));
452                 SQLOK(sqlite3_bind_null(stmt_do, 14));
453                 SQLOK(sqlite3_bind_null(stmt_do, 15));
454                 SQLOK(sqlite3_bind_null(stmt_do, 16));
455                 SQLOK(sqlite3_bind_null(stmt_do, 17));
456                 SQLOK(sqlite3_bind_null(stmt_do, 18));
457                 SQLOK(sqlite3_bind_null(stmt_do, 19));
458                 SQLOK(sqlite3_bind_null(stmt_do, 20));
459                 SQLOK(sqlite3_bind_null(stmt_do, 21));
460         }
461
462         if (row.id) {
463                 SQLOK(sqlite3_bind_int(stmt_do, 22, row.id));
464         }
465
466         int written = sqlite3_step(stmt_do);
467
468         SQLOK(sqlite3_reset(stmt_do));
469
470         return written == SQLITE_DONE;
471 }
472
473
474 const std::list<ActionRow> RollbackManager::actionRowsFromSelect(sqlite3_stmt* stmt)
475 {
476         std::list<ActionRow> rows;
477         const unsigned char * text;
478         size_t size;
479
480         while (sqlite3_step(stmt) == SQLITE_ROW) {
481                 ActionRow row;
482
483                 row.actor     = sqlite3_column_int  (stmt, 0);
484                 row.timestamp = sqlite3_column_int64(stmt, 1);
485                 row.type      = sqlite3_column_int  (stmt, 2);
486                 row.nodeMeta  = 0;
487
488                 if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
489                         text = sqlite3_column_text (stmt, 3);
490                         size = sqlite3_column_bytes(stmt, 3);
491                         row.list        = std::string(reinterpret_cast<const char*>(text), size);
492                         row.index       = sqlite3_column_int(stmt, 4);
493                         row.add         = sqlite3_column_int(stmt, 5);
494                         row.stack.id    = sqlite3_column_int(stmt, 6);
495                         row.stack.count = sqlite3_column_int(stmt, 7);
496                         row.nodeMeta    = sqlite3_column_int(stmt, 8);
497                 }
498
499                 if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta) {
500                         row.x = sqlite3_column_int(stmt,  9);
501                         row.y = sqlite3_column_int(stmt, 10);
502                         row.z = sqlite3_column_int(stmt, 11);
503                 }
504
505                 if (row.type == RollbackAction::TYPE_SET_NODE) {
506                         row.oldNode   = sqlite3_column_int(stmt, 12);
507                         row.oldParam1 = sqlite3_column_int(stmt, 13);
508                         row.oldParam2 = sqlite3_column_int(stmt, 14);
509                         text = sqlite3_column_text (stmt, 15);
510                         size = sqlite3_column_bytes(stmt, 15);
511                         row.oldMeta   = std::string(reinterpret_cast<const char*>(text), size);
512                         row.newNode   = sqlite3_column_int(stmt, 16);
513                         row.newParam1 = sqlite3_column_int(stmt, 17);
514                         row.newParam2 = sqlite3_column_int(stmt, 18);
515                         text = sqlite3_column_text(stmt, 19);
516                         size = sqlite3_column_bytes(stmt, 19);
517                         row.newMeta   = std::string(reinterpret_cast<const char*>(text), size);
518                         row.guessed   = sqlite3_column_int(stmt, 20);
519                 }
520
521                 if (row.nodeMeta) {
522                         row.location = "nodemeta:";
523                         row.location += itos(row.x);
524                         row.location += ',';
525                         row.location += itos(row.y);
526                         row.location += ',';
527                         row.location += itos(row.z);
528                 } else {
529                         row.location = getActorName(row.actor);
530                 }
531
532                 rows.push_back(row);
533         }
534
535         SQLOK(sqlite3_reset(stmt));
536
537         return rows;
538 }
539
540
541 ActionRow RollbackManager::actionRowFromRollbackAction(const RollbackAction & action)
542 {
543         ActionRow row;
544
545         row.id        = 0;
546         row.actor     = getActorId(action.actor);
547         row.timestamp = action.unix_time;
548         row.type      = action.type;
549
550         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
551                 row.location = action.inventory_location;
552                 row.list     = action.inventory_list;
553                 row.index    = action.inventory_index;
554                 row.add      = action.inventory_add;
555                 row.stack    = action.inventory_stack;
556                 row.stack.id = getNodeId(row.stack.name);
557         } else {
558                 row.x         = action.p.X;
559                 row.y         = action.p.Y;
560                 row.z         = action.p.Z;
561                 row.oldNode   = getNodeId(action.n_old.name);
562                 row.oldParam1 = action.n_old.param1;
563                 row.oldParam2 = action.n_old.param2;
564                 row.oldMeta   = action.n_old.meta;
565                 row.newNode   = getNodeId(action.n_new.name);
566                 row.newParam1 = action.n_new.param1;
567                 row.newParam2 = action.n_new.param2;
568                 row.newMeta   = action.n_new.meta;
569                 row.guessed   = action.actor_is_guess;
570         }
571
572         return row;
573 }
574
575
576 const std::list<RollbackAction> RollbackManager::rollbackActionsFromActionRows(
577                 const std::list<ActionRow> & rows)
578 {
579         std::list<RollbackAction> actions;
580
581         for (const ActionRow &row : rows) {
582                 RollbackAction action;
583                 action.actor     = (row.actor) ? getActorName(row.actor) : "";
584                 action.unix_time = row.timestamp;
585                 action.type      = static_cast<RollbackAction::Type>(row.type);
586
587                 switch (action.type) {
588                 case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:
589                         action.inventory_location = row.location;
590                         action.inventory_list     = row.list;
591                         action.inventory_index    = row.index;
592                         action.inventory_add      = row.add;
593                         action.inventory_stack    = row.stack;
594                         if (action.inventory_stack.name.empty()) {
595                                 action.inventory_stack.name = getNodeName(row.stack.id);
596                         }
597                         break;
598
599                 case RollbackAction::TYPE_SET_NODE:
600                         action.p            = v3s16(row.x, row.y, row.z);
601                         action.n_old.name   = getNodeName(row.oldNode);
602                         action.n_old.param1 = row.oldParam1;
603                         action.n_old.param2 = row.oldParam2;
604                         action.n_old.meta   = row.oldMeta;
605                         action.n_new.name   = getNodeName(row.newNode);
606                         action.n_new.param1 = row.newParam1;
607                         action.n_new.param2 = row.newParam2;
608                         action.n_new.meta   = row.newMeta;
609                         break;
610
611                 default:
612                         throw ("W.T.F.");
613                         break;
614                 }
615
616                 actions.push_back(action);
617         }
618
619         return actions;
620 }
621
622
623 const std::list<ActionRow> RollbackManager::getRowsSince(time_t firstTime, const std::string & actor)
624 {
625         sqlite3_stmt *stmt_stmt = actor.empty() ? stmt_select : stmt_select_withActor;
626         sqlite3_bind_int64(stmt_stmt, 1, firstTime);
627
628         if (!actor.empty()) {
629                 sqlite3_bind_int(stmt_stmt, 2, getActorId(actor));
630         }
631
632         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_stmt);
633         sqlite3_reset(stmt_stmt);
634
635         return rows;
636 }
637
638
639 const std::list<ActionRow> RollbackManager::getRowsSince_range(
640                 time_t start_time, v3s16 p, int range, int limit)
641 {
642
643         sqlite3_bind_int64(stmt_select_range, 1, start_time);
644         sqlite3_bind_int  (stmt_select_range, 2, static_cast<int>(p.X - range));
645         sqlite3_bind_int  (stmt_select_range, 3, static_cast<int>(p.X + range));
646         sqlite3_bind_int  (stmt_select_range, 4, static_cast<int>(p.Y - range));
647         sqlite3_bind_int  (stmt_select_range, 5, static_cast<int>(p.Y + range));
648         sqlite3_bind_int  (stmt_select_range, 6, static_cast<int>(p.Z - range));
649         sqlite3_bind_int  (stmt_select_range, 7, static_cast<int>(p.Z + range));
650         sqlite3_bind_int  (stmt_select_range, 8, limit);
651
652         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_select_range);
653         sqlite3_reset(stmt_select_range);
654
655         return rows;
656 }
657
658
659 const std::list<RollbackAction> RollbackManager::getActionsSince_range(
660                 time_t start_time, v3s16 p, int range, int limit)
661 {
662         return rollbackActionsFromActionRows(getRowsSince_range(start_time, p, range, limit));
663 }
664
665
666 const std::list<RollbackAction> RollbackManager::getActionsSince(
667                 time_t start_time, const std::string & actor)
668 {
669         return rollbackActionsFromActionRows(getRowsSince(start_time, actor));
670 }
671
672
673 void RollbackManager::migrate(const std::string & file_path)
674 {
675         std::cout << "Migrating from rollback.txt to rollback.sqlite." << std::endl;
676
677         std::ifstream fh(file_path.c_str(), std::ios::in | std::ios::ate);
678         if (!fh.good()) {
679                 throw FileNotGoodException("Unable to open rollback.txt");
680         }
681
682         std::streampos file_size = fh.tellg();
683
684         if (file_size < 10) {
685                 errorstream << "Empty rollback log." << std::endl;
686                 return;
687         }
688
689         fh.seekg(0);
690
691         sqlite3_stmt *stmt_begin;
692         sqlite3_stmt *stmt_commit;
693         SQLOK(sqlite3_prepare_v2(db, "BEGIN", -1, &stmt_begin, NULL));
694         SQLOK(sqlite3_prepare_v2(db, "COMMIT", -1, &stmt_commit, NULL));
695
696         std::string bit;
697         int i = 0;
698         time_t start = time(0);
699         time_t t = start;
700         SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
701         sqlite3_reset(stmt_begin);
702         do {
703                 ActionRow row;
704                 row.id = 0;
705
706                 // Get the timestamp
707                 std::getline(fh, bit, ' ');
708                 bit = trim(bit);
709                 if (!atoi(bit.c_str())) {
710                         std::getline(fh, bit);
711                         continue;
712                 }
713                 row.timestamp = atoi(bit.c_str());
714
715                 // Get the actor
716                 row.actor = getActorId(deSerializeJsonString(fh));
717
718                 // Get the action type
719                 std::getline(fh, bit, '[');
720                 std::getline(fh, bit, ' ');
721
722                 if (bit == "modify_inventory_stack") {
723                         row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK;
724                         row.location = trim(deSerializeJsonString(fh));
725                         std::getline(fh, bit, ' ');
726                         row.list     = trim(deSerializeJsonString(fh));
727                         std::getline(fh, bit, ' ');
728                         std::getline(fh, bit, ' ');
729                         row.index    = atoi(trim(bit).c_str());
730                         std::getline(fh, bit, ' ');
731                         row.add      = (int)(trim(bit) == "add");
732                         row.stack.deSerialize(deSerializeJsonString(fh));
733                         row.stack.id = getNodeId(row.stack.name);
734                         std::getline(fh, bit);
735                 } else if (bit == "set_node") {
736                         row.type = RollbackAction::TYPE_SET_NODE;
737                         std::getline(fh, bit, '(');
738                         std::getline(fh, bit, ',');
739                         row.x       = atoi(trim(bit).c_str());
740                         std::getline(fh, bit, ',');
741                         row.y       = atoi(trim(bit).c_str());
742                         std::getline(fh, bit, ')');
743                         row.z       = atoi(trim(bit).c_str());
744                         std::getline(fh, bit, ' ');
745                         row.oldNode = getNodeId(trim(deSerializeJsonString(fh)));
746                         std::getline(fh, bit, ' ');
747                         std::getline(fh, bit, ' ');
748                         row.oldParam1 = atoi(trim(bit).c_str());
749                         std::getline(fh, bit, ' ');
750                         row.oldParam2 = atoi(trim(bit).c_str());
751                         row.oldMeta   = trim(deSerializeJsonString(fh));
752                         std::getline(fh, bit, ' ');
753                         row.newNode   = getNodeId(trim(deSerializeJsonString(fh)));
754                         std::getline(fh, bit, ' ');
755                         std::getline(fh, bit, ' ');
756                         row.newParam1 = atoi(trim(bit).c_str());
757                         std::getline(fh, bit, ' ');
758                         row.newParam2 = atoi(trim(bit).c_str());
759                         row.newMeta   = trim(deSerializeJsonString(fh));
760                         std::getline(fh, bit, ' ');
761                         std::getline(fh, bit, ' ');
762                         std::getline(fh, bit);
763                         row.guessed = (int)(trim(bit) == "actor_is_guess");
764                 } else {
765                         errorstream << "Unrecognized rollback action type \""
766                                 << bit << "\"!" << std::endl;
767                         continue;
768                 }
769
770                 registerRow(row);
771                 ++i;
772
773                 if (time(0) - t >= 1) {
774                         SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
775                         sqlite3_reset(stmt_commit);
776                         t = time(0);
777                         std::cout
778                                 << " Done: " << static_cast<int>((static_cast<float>(fh.tellg()) / static_cast<float>(file_size)) * 100) << "%"
779                                 << " Speed: " << i / (t - start) << "/second     \r" << std::flush;
780                         SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
781                         sqlite3_reset(stmt_begin);
782                 }
783         } while (fh.good());
784         SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
785         sqlite3_reset(stmt_commit);
786
787         SQLOK(sqlite3_finalize(stmt_begin));
788         SQLOK(sqlite3_finalize(stmt_commit));
789
790         std::cout
791                 << " Done: 100%                                  " << std::endl
792                 << "Now you can delete the old rollback.txt file." << std::endl;
793 }
794
795
796 // Get nearness factor for subject's action for this action
797 // Return value: 0 = impossible, >0 = factor
798 float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p,
799                 time_t suspect_t, v3s16 action_p, time_t action_t)
800 {
801         // Suspect cannot cause things in the past
802         if (action_t < suspect_t) {
803                 return 0;        // 0 = cannot be
804         }
805         // Start from 100
806         int f = 100;
807         // Distance (1 node = -x points)
808         f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
809         // Time (1 second = -x points)
810         f -= 1 * (action_t - suspect_t);
811         // If is a guess, halve the points
812         if (is_guess) {
813                 f *= 0.5;
814         }
815         // Limit to 0
816         if (f < 0) {
817                 f = 0;
818         }
819         return f;
820 }
821
822
823 void RollbackManager::reportAction(const RollbackAction &action_)
824 {
825         // Ignore if not important
826         if (!action_.isImportant(gamedef)) {
827                 return;
828         }
829
830         RollbackAction action = action_;
831         action.unix_time = time(0);
832
833         // Figure out actor
834         action.actor = current_actor;
835         action.actor_is_guess = current_actor_is_guess;
836
837         if (action.actor.empty()) { // If actor is not known, find out suspect or cancel
838                 v3s16 p;
839                 if (!action.getPosition(&p)) {
840                         return;
841                 }
842
843                 action.actor = getSuspect(p, 83, 1);
844                 if (action.actor.empty()) {
845                         return;
846                 }
847
848                 action.actor_is_guess = true;
849         }
850
851         addAction(action);
852 }
853
854 std::string RollbackManager::getActor()
855 {
856         return current_actor;
857 }
858
859 bool RollbackManager::isActorGuess()
860 {
861         return current_actor_is_guess;
862 }
863
864 void RollbackManager::setActor(const std::string & actor, bool is_guess)
865 {
866         current_actor = actor;
867         current_actor_is_guess = is_guess;
868 }
869
870 std::string RollbackManager::getSuspect(v3s16 p, float nearness_shortcut,
871                 float min_nearness)
872 {
873         if (!current_actor.empty()) {
874                 return current_actor;
875         }
876         int cur_time = time(0);
877         time_t first_time = cur_time - (100 - min_nearness);
878         RollbackAction likely_suspect;
879         float likely_suspect_nearness = 0;
880         for (std::list<RollbackAction>::const_reverse_iterator
881              i = action_latest_buffer.rbegin();
882              i != action_latest_buffer.rend(); ++i) {
883                 if (i->unix_time < first_time) {
884                         break;
885                 }
886                 if (i->actor.empty()) {
887                         continue;
888                 }
889                 // Find position of suspect or continue
890                 v3s16 suspect_p;
891                 if (!i->getPosition(&suspect_p)) {
892                         continue;
893                 }
894                 float f = getSuspectNearness(i->actor_is_guess, suspect_p,
895                                              i->unix_time, p, cur_time);
896                 if (f >= min_nearness && f > likely_suspect_nearness) {
897                         likely_suspect_nearness = f;
898                         likely_suspect = *i;
899                         if (likely_suspect_nearness >= nearness_shortcut) {
900                                 break;
901                         }
902                 }
903         }
904         // No likely suspect was found
905         if (likely_suspect_nearness == 0) {
906                 return "";
907         }
908         // Likely suspect was found
909         return likely_suspect.actor;
910 }
911
912
913 void RollbackManager::flush()
914 {
915         sqlite3_exec(db, "BEGIN", NULL, NULL, NULL);
916
917         std::list<RollbackAction>::const_iterator iter;
918
919         for (iter  = action_todisk_buffer.begin();
920                         iter != action_todisk_buffer.end();
921                         ++iter) {
922                 if (iter->actor.empty()) {
923                         continue;
924                 }
925
926                 registerRow(actionRowFromRollbackAction(*iter));
927         }
928
929         sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
930         action_todisk_buffer.clear();
931 }
932
933
934 void RollbackManager::addAction(const RollbackAction & action)
935 {
936         action_todisk_buffer.push_back(action);
937         action_latest_buffer.push_back(action);
938
939         // Flush to disk sometimes
940         if (action_todisk_buffer.size() >= 500) {
941                 flush();
942         }
943 }
944
945 std::list<RollbackAction> RollbackManager::getNodeActors(v3s16 pos, int range,
946                 time_t seconds, int limit)
947 {
948         flush();
949         time_t cur_time = time(0);
950         time_t first_time = cur_time - seconds;
951
952         return getActionsSince_range(first_time, pos, range, limit);
953 }
954
955 std::list<RollbackAction> RollbackManager::getRevertActions(
956                 const std::string &actor_filter,
957                 time_t seconds)
958 {
959         time_t cur_time = time(0);
960         time_t first_time = cur_time - seconds;
961
962         flush();
963
964         return getActionsSince(first_time, actor_filter);
965 }
966