Fix -Wterminate warnings in rollback.cpp as well
[oweals/minetest.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         current_actor_is_guess(false)
96 {
97         verbosestream << "RollbackManager::RollbackManager(" << world_path
98                 << ")" << std::endl;
99
100         std::string txt_filename = world_path + DIR_DELIM "rollback.txt";
101         std::string migrating_flag = txt_filename + ".migrating";
102         database_path = world_path + DIR_DELIM "rollback.sqlite";
103
104         bool created = initDatabase();
105
106         if (fs::PathExists(txt_filename) && (created ||
107                         fs::PathExists(migrating_flag))) {
108                 std::ofstream of(migrating_flag.c_str());
109                 of.close();
110                 migrate(txt_filename);
111                 fs::DeleteSingleFileOrEmptyDirectory(migrating_flag);
112         }
113 }
114
115
116 RollbackManager::~RollbackManager()
117 {
118         flush();
119
120         FINALIZE_STATEMENT(stmt_insert);
121         FINALIZE_STATEMENT(stmt_replace);
122         FINALIZE_STATEMENT(stmt_select);
123         FINALIZE_STATEMENT(stmt_select_range);
124         FINALIZE_STATEMENT(stmt_select_withActor);
125         FINALIZE_STATEMENT(stmt_knownActor_select);
126         FINALIZE_STATEMENT(stmt_knownActor_insert);
127         FINALIZE_STATEMENT(stmt_knownNode_select);
128         FINALIZE_STATEMENT(stmt_knownNode_insert);
129
130         SQLOK_ERRSTREAM(sqlite3_close(db), "Could not close db");
131 }
132
133
134 void RollbackManager::registerNewActor(const int id, const std::string &name)
135 {
136         Entity actor = {id, name};
137         knownActors.push_back(actor);
138 }
139
140
141 void RollbackManager::registerNewNode(const int id, const std::string &name)
142 {
143         Entity node = {id, name};
144         knownNodes.push_back(node);
145 }
146
147
148 int RollbackManager::getActorId(const std::string &name)
149 {
150         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
151                         iter != knownActors.end(); ++iter) {
152                 if (iter->name == name) {
153                         return iter->id;
154                 }
155         }
156
157         SQLOK(sqlite3_bind_text(stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL));
158         SQLRES(sqlite3_step(stmt_knownActor_insert), SQLITE_DONE);
159         SQLOK(sqlite3_reset(stmt_knownActor_insert));
160
161         int id = sqlite3_last_insert_rowid(db);
162         registerNewActor(id, name);
163
164         return id;
165 }
166
167
168 int RollbackManager::getNodeId(const std::string &name)
169 {
170         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
171                         iter != knownNodes.end(); ++iter) {
172                 if (iter->name == name) {
173                         return iter->id;
174                 }
175         }
176
177         SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL));
178         SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE);
179         SQLOK(sqlite3_reset(stmt_knownNode_insert));
180
181         int id = sqlite3_last_insert_rowid(db);
182         registerNewNode(id, name);
183
184         return id;
185 }
186
187
188 const char * RollbackManager::getActorName(const int id)
189 {
190         for (std::vector<Entity>::const_iterator iter = knownActors.begin();
191                         iter != knownActors.end(); ++iter) {
192                 if (iter->id == id) {
193                         return iter->name.c_str();
194                 }
195         }
196
197         return "";
198 }
199
200
201 const char * RollbackManager::getNodeName(const int id)
202 {
203         for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
204                         iter != knownNodes.end(); ++iter) {
205                 if (iter->id == id) {
206                         return iter->name.c_str();
207                 }
208         }
209
210         return "";
211 }
212
213
214 bool RollbackManager::createTables()
215 {
216         SQLOK(sqlite3_exec(db,
217                 "CREATE TABLE IF NOT EXISTS `actor` (\n"
218                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
219                 "       `name` TEXT NOT NULL\n"
220                 ");\n"
221                 "CREATE TABLE IF NOT EXISTS `node` (\n"
222                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
223                 "       `name` TEXT NOT NULL\n"
224                 ");\n"
225                 "CREATE TABLE IF NOT EXISTS `action` (\n"
226                 "       `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n"
227                 "       `actor` INTEGER NOT NULL,\n"
228                 "       `timestamp` TIMESTAMP NOT NULL,\n"
229                 "       `type` INTEGER NOT NULL,\n"
230                 "       `list` TEXT,\n"
231                 "       `index` INTEGER,\n"
232                 "       `add` INTEGER,\n"
233                 "       `stackNode` INTEGER,\n"
234                 "       `stackQuantity` INTEGER,\n"
235                 "       `nodeMeta` INTEGER,\n"
236                 "       `x` INT,\n"
237                 "       `y` INT,\n"
238                 "       `z` INT,\n"
239                 "       `oldNode` INTEGER,\n"
240                 "       `oldParam1` INTEGER,\n"
241                 "       `oldParam2` INTEGER,\n"
242                 "       `oldMeta` TEXT,\n"
243                 "       `newNode` INTEGER,\n"
244                 "       `newParam1` INTEGER,\n"
245                 "       `newParam2` INTEGER,\n"
246                 "       `newMeta` TEXT,\n"
247                 "       `guessedActor` INTEGER,\n"
248                 "       FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n"
249                 "       FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n"
250                 "       FOREIGN KEY (`oldNode`)   REFERENCES `node`(`id`),\n"
251                 "       FOREIGN KEY (`newNode`)   REFERENCES `node`(`id`)\n"
252                 ");\n"
253                 "CREATE INDEX IF NOT EXISTS `actionIndex` ON `action`(`x`,`y`,`z`,`timestamp`,`actor`);\n",
254                 NULL, NULL, NULL));
255         verbosestream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
256
257         return true;
258 }
259
260
261 bool RollbackManager::initDatabase()
262 {
263         verbosestream << "RollbackManager: Database connection setup" << std::endl;
264
265         bool needs_create = !fs::PathExists(database_path);
266         SQLOK(sqlite3_open_v2(database_path.c_str(), &db,
267                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL));
268
269         if (needs_create) {
270                 createTables();
271         }
272
273         SQLOK(sqlite3_prepare_v2(db,
274                 "INSERT INTO `action` (\n"
275                 "       `actor`, `timestamp`, `type`,\n"
276                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
277                 "       `x`, `y`, `z`,\n"
278                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
279                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
280                 "       `guessedActor`\n"
281                 ") VALUES (\n"
282                 "       ?, ?, ?,\n"
283                 "       ?, ?, ?, ?, ?, ?,\n"
284                 "       ?, ?, ?,\n"
285                 "       ?, ?, ?, ?,\n"
286                 "       ?, ?, ?, ?,\n"
287                 "       ?"
288                 ");",
289                 -1, &stmt_insert, NULL));
290
291         SQLOK(sqlite3_prepare_v2(db,
292                 "REPLACE INTO `action` (\n"
293                 "       `actor`, `timestamp`, `type`,\n"
294                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
295                 "       `x`, `y`, `z`,\n"
296                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
297                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
298                 "       `guessedActor`, `id`\n"
299                 ") VALUES (\n"
300                 "       ?, ?, ?,\n"
301                 "       ?, ?, ?, ?, ?, ?,\n"
302                 "       ?, ?, ?,\n"
303                 "       ?, ?, ?, ?,\n"
304                 "       ?, ?, ?, ?,\n"
305                 "       ?, ?\n"
306                 ");",
307                 -1, &stmt_replace, NULL));
308
309         SQLOK(sqlite3_prepare_v2(db,
310                 "SELECT\n"
311                 "       `actor`, `timestamp`, `type`,\n"
312                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
313                 "       `x`, `y`, `z`,\n"
314                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
315                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
316                 "       `guessedActor`\n"
317                 " FROM `action`\n"
318                 " WHERE `timestamp` >= ?\n"
319                 " ORDER BY `timestamp` DESC, `id` DESC",
320                 -1, &stmt_select, NULL));
321
322         SQLOK(sqlite3_prepare_v2(db,
323                 "SELECT\n"
324                 "       `actor`, `timestamp`, `type`,\n"
325                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
326                 "       `x`, `y`, `z`,\n"
327                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
328                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
329                 "       `guessedActor`\n"
330                 "FROM `action`\n"
331                 "WHERE `timestamp` >= ?\n"
332                 "       AND `x` IS NOT NULL\n"
333                 "       AND `y` IS NOT NULL\n"
334                 "       AND `z` IS NOT NULL\n"
335                 "       AND `x` BETWEEN ? AND ?\n"
336                 "       AND `y` BETWEEN ? AND ?\n"
337                 "       AND `z` BETWEEN ? AND ?\n"
338                 "ORDER BY `timestamp` DESC, `id` DESC\n"
339                 "LIMIT 0,?",
340                 -1, &stmt_select_range, NULL));
341
342         SQLOK(sqlite3_prepare_v2(db,
343                 "SELECT\n"
344                 "       `actor`, `timestamp`, `type`,\n"
345                 "       `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
346                 "       `x`, `y`, `z`,\n"
347                 "       `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
348                 "       `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
349                 "       `guessedActor`\n"
350                 "FROM `action`\n"
351                 "WHERE `timestamp` >= ?\n"
352                 "       AND `actor` = ?\n"
353                 "ORDER BY `timestamp` DESC, `id` DESC\n",
354                 -1, &stmt_select_withActor, NULL));
355
356         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`",
357                         -1, &stmt_knownActor_select, NULL));
358
359         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)",
360                         -1, &stmt_knownActor_insert, NULL));
361
362         SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`",
363                         -1, &stmt_knownNode_select, NULL));
364
365         SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)",
366                         -1, &stmt_knownNode_insert, NULL));
367
368         verbosestream << "SQL prepared statements setup correctly" << std::endl;
369
370         while (sqlite3_step(stmt_knownActor_select) == SQLITE_ROW) {
371                 registerNewActor(
372                         sqlite3_column_int(stmt_knownActor_select, 0),
373                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownActor_select, 1))
374                 );
375         }
376         SQLOK(sqlite3_reset(stmt_knownActor_select));
377
378         while (sqlite3_step(stmt_knownNode_select) == SQLITE_ROW) {
379                 registerNewNode(
380                         sqlite3_column_int(stmt_knownNode_select, 0),
381                         reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownNode_select, 1))
382                 );
383         }
384         SQLOK(sqlite3_reset(stmt_knownNode_select));
385
386         return needs_create;
387 }
388
389
390 bool RollbackManager::registerRow(const ActionRow & row)
391 {
392         sqlite3_stmt * stmt_do = (row.id) ? stmt_replace : stmt_insert;
393
394         bool nodeMeta = false;
395
396         SQLOK(sqlite3_bind_int  (stmt_do, 1, row.actor));
397         SQLOK(sqlite3_bind_int64(stmt_do, 2, row.timestamp));
398         SQLOK(sqlite3_bind_int  (stmt_do, 3, row.type));
399
400         if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
401                 const std::string & loc = row.location;
402                 nodeMeta = (loc.substr(0, 9) == "nodemeta:");
403
404                 SQLOK(sqlite3_bind_text(stmt_do, 4, row.list.c_str(), row.list.size(), NULL));
405                 SQLOK(sqlite3_bind_int (stmt_do, 5, row.index));
406                 SQLOK(sqlite3_bind_int (stmt_do, 6, row.add));
407                 SQLOK(sqlite3_bind_int (stmt_do, 7, row.stack.id));
408                 SQLOK(sqlite3_bind_int (stmt_do, 8, row.stack.count));
409                 SQLOK(sqlite3_bind_int (stmt_do, 9, (int) nodeMeta));
410
411                 if (nodeMeta) {
412                         std::string::size_type p1, p2;
413                         p1 = loc.find(':') + 1;
414                         p2 = loc.find(',');
415                         std::string x = loc.substr(p1, p2 - p1);
416                         p1 = p2 + 1;
417                         p2 = loc.find(',', p1);
418                         std::string y = loc.substr(p1, p2 - p1);
419                         std::string z = loc.substr(p2 + 1);
420                         SQLOK(sqlite3_bind_int(stmt_do, 10, atoi(x.c_str())));
421                         SQLOK(sqlite3_bind_int(stmt_do, 11, atoi(y.c_str())));
422                         SQLOK(sqlite3_bind_int(stmt_do, 12, atoi(z.c_str())));
423                 }
424         } else {
425                 SQLOK(sqlite3_bind_null(stmt_do, 4));
426                 SQLOK(sqlite3_bind_null(stmt_do, 5));
427                 SQLOK(sqlite3_bind_null(stmt_do, 6));
428                 SQLOK(sqlite3_bind_null(stmt_do, 7));
429                 SQLOK(sqlite3_bind_null(stmt_do, 8));
430                 SQLOK(sqlite3_bind_null(stmt_do, 9));
431         }
432
433         if (row.type == RollbackAction::TYPE_SET_NODE) {
434                 SQLOK(sqlite3_bind_int (stmt_do, 10, row.x));
435                 SQLOK(sqlite3_bind_int (stmt_do, 11, row.y));
436                 SQLOK(sqlite3_bind_int (stmt_do, 12, row.z));
437                 SQLOK(sqlite3_bind_int (stmt_do, 13, row.oldNode));
438                 SQLOK(sqlite3_bind_int (stmt_do, 14, row.oldParam1));
439                 SQLOK(sqlite3_bind_int (stmt_do, 15, row.oldParam2));
440                 SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL));
441                 SQLOK(sqlite3_bind_int (stmt_do, 17, row.newNode));
442                 SQLOK(sqlite3_bind_int (stmt_do, 18, row.newParam1));
443                 SQLOK(sqlite3_bind_int (stmt_do, 19, row.newParam2));
444                 SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL));
445                 SQLOK(sqlite3_bind_int (stmt_do, 21, row.guessed ? 1 : 0));
446         } else {
447                 if (!nodeMeta) {
448                         SQLOK(sqlite3_bind_null(stmt_do, 10));
449                         SQLOK(sqlite3_bind_null(stmt_do, 11));
450                         SQLOK(sqlite3_bind_null(stmt_do, 12));
451                 }
452                 SQLOK(sqlite3_bind_null(stmt_do, 13));
453                 SQLOK(sqlite3_bind_null(stmt_do, 14));
454                 SQLOK(sqlite3_bind_null(stmt_do, 15));
455                 SQLOK(sqlite3_bind_null(stmt_do, 16));
456                 SQLOK(sqlite3_bind_null(stmt_do, 17));
457                 SQLOK(sqlite3_bind_null(stmt_do, 18));
458                 SQLOK(sqlite3_bind_null(stmt_do, 19));
459                 SQLOK(sqlite3_bind_null(stmt_do, 20));
460                 SQLOK(sqlite3_bind_null(stmt_do, 21));
461         }
462
463         if (row.id) {
464                 SQLOK(sqlite3_bind_int(stmt_do, 22, row.id));
465         }
466
467         int written = sqlite3_step(stmt_do);
468
469         SQLOK(sqlite3_reset(stmt_do));
470
471         return written == SQLITE_DONE;
472 }
473
474
475 const std::list<ActionRow> RollbackManager::actionRowsFromSelect(sqlite3_stmt* stmt)
476 {
477         std::list<ActionRow> rows;
478         const unsigned char * text;
479         size_t size;
480
481         while (sqlite3_step(stmt) == SQLITE_ROW) {
482                 ActionRow row;
483
484                 row.actor     = sqlite3_column_int  (stmt, 0);
485                 row.timestamp = sqlite3_column_int64(stmt, 1);
486                 row.type      = sqlite3_column_int  (stmt, 2);
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 (std::list<ActionRow>::const_iterator it = rows.begin();
582                         it != rows.end(); ++it) {
583                 RollbackAction action;
584                 action.actor     = (it->actor) ? getActorName(it->actor) : "";
585                 action.unix_time = it->timestamp;
586                 action.type      = static_cast<RollbackAction::Type>(it->type);
587
588                 switch (action.type) {
589                 case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:
590                         action.inventory_location = it->location.c_str();
591                         action.inventory_list     = it->list;
592                         action.inventory_index    = it->index;
593                         action.inventory_add      = it->add;
594                         action.inventory_stack    = it->stack;
595                         if (action.inventory_stack.name.empty()) {
596                                 action.inventory_stack.name = getNodeName(it->stack.id);
597                         }
598                         break;
599
600                 case RollbackAction::TYPE_SET_NODE:
601                         action.p            = v3s16(it->x, it->y, it->z);
602                         action.n_old.name   = getNodeName(it->oldNode);
603                         action.n_old.param1 = it->oldParam1;
604                         action.n_old.param2 = it->oldParam2;
605                         action.n_old.meta   = it->oldMeta;
606                         action.n_new.name   = getNodeName(it->newNode);
607                         action.n_new.param1 = it->newParam1;
608                         action.n_new.param2 = it->newParam2;
609                         action.n_new.meta   = it->newMeta;
610                         break;
611
612                 default:
613                         throw ("W.T.F.");
614                         break;
615                 }
616
617                 actions.push_back(action);
618         }
619
620         return actions;
621 }
622
623
624 const std::list<ActionRow> RollbackManager::getRowsSince(time_t firstTime, const std::string & actor)
625 {
626         sqlite3_stmt *stmt_stmt = actor.empty() ? stmt_select : stmt_select_withActor;
627         sqlite3_bind_int64(stmt_stmt, 1, firstTime);
628
629         if (!actor.empty()) {
630                 sqlite3_bind_int(stmt_stmt, 2, getActorId(actor));
631         }
632
633         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_stmt);
634         sqlite3_reset(stmt_stmt);
635
636         return rows;
637 }
638
639
640 const std::list<ActionRow> RollbackManager::getRowsSince_range(
641                 time_t start_time, v3s16 p, int range, int limit)
642 {
643
644         sqlite3_bind_int64(stmt_select_range, 1, start_time);
645         sqlite3_bind_int  (stmt_select_range, 2, static_cast<int>(p.X - range));
646         sqlite3_bind_int  (stmt_select_range, 3, static_cast<int>(p.X + range));
647         sqlite3_bind_int  (stmt_select_range, 4, static_cast<int>(p.Y - range));
648         sqlite3_bind_int  (stmt_select_range, 5, static_cast<int>(p.Y + range));
649         sqlite3_bind_int  (stmt_select_range, 6, static_cast<int>(p.Z - range));
650         sqlite3_bind_int  (stmt_select_range, 7, static_cast<int>(p.Z + range));
651         sqlite3_bind_int  (stmt_select_range, 8, limit);
652
653         const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_select_range);
654         sqlite3_reset(stmt_select_range);
655
656         return rows;
657 }
658
659
660 const std::list<RollbackAction> RollbackManager::getActionsSince_range(
661                 time_t start_time, v3s16 p, int range, int limit)
662 {
663         return rollbackActionsFromActionRows(getRowsSince_range(start_time, p, range, limit));
664 }
665
666
667 const std::list<RollbackAction> RollbackManager::getActionsSince(
668                 time_t start_time, const std::string & actor)
669 {
670         return rollbackActionsFromActionRows(getRowsSince(start_time, actor));
671 }
672
673
674 void RollbackManager::migrate(const std::string & file_path)
675 {
676         std::cout << "Migrating from rollback.txt to rollback.sqlite." << std::endl;
677
678         std::ifstream fh(file_path.c_str(), std::ios::in | std::ios::ate);
679         if (!fh.good()) {
680                 throw FileNotGoodException("Unable to open rollback.txt");
681         }
682
683         std::streampos file_size = fh.tellg();
684
685         if (file_size < 10) {
686                 errorstream << "Empty rollback log." << std::endl;
687                 return;
688         }
689
690         fh.seekg(0);
691
692         sqlite3_stmt *stmt_begin;
693         sqlite3_stmt *stmt_commit;
694         SQLOK(sqlite3_prepare_v2(db, "BEGIN", -1, &stmt_begin, NULL));
695         SQLOK(sqlite3_prepare_v2(db, "COMMIT", -1, &stmt_commit, NULL));
696
697         std::string bit;
698         int i = 0;
699         time_t start = time(0);
700         time_t t = start;
701         SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
702         sqlite3_reset(stmt_begin);
703         do {
704                 ActionRow row;
705                 row.id = 0;
706
707                 // Get the timestamp
708                 std::getline(fh, bit, ' ');
709                 bit = trim(bit);
710                 if (!atoi(bit.c_str())) {
711                         std::getline(fh, bit);
712                         continue;
713                 }
714                 row.timestamp = atoi(bit.c_str());
715
716                 // Get the actor
717                 row.actor = getActorId(deSerializeJsonString(fh));
718
719                 // Get the action type
720                 std::getline(fh, bit, '[');
721                 std::getline(fh, bit, ' ');
722
723                 if (bit == "modify_inventory_stack") {
724                         row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK;
725                         row.location = trim(deSerializeJsonString(fh));
726                         std::getline(fh, bit, ' ');
727                         row.list     = trim(deSerializeJsonString(fh));
728                         std::getline(fh, bit, ' ');
729                         std::getline(fh, bit, ' ');
730                         row.index    = atoi(trim(bit).c_str());
731                         std::getline(fh, bit, ' ');
732                         row.add      = (int)(trim(bit) == "add");
733                         row.stack.deSerialize(deSerializeJsonString(fh));
734                         row.stack.id = getNodeId(row.stack.name);
735                         std::getline(fh, bit);
736                 } else if (bit == "set_node") {
737                         row.type = RollbackAction::TYPE_SET_NODE;
738                         std::getline(fh, bit, '(');
739                         std::getline(fh, bit, ',');
740                         row.x       = atoi(trim(bit).c_str());
741                         std::getline(fh, bit, ',');
742                         row.y       = atoi(trim(bit).c_str());
743                         std::getline(fh, bit, ')');
744                         row.z       = atoi(trim(bit).c_str());
745                         std::getline(fh, bit, ' ');
746                         row.oldNode = getNodeId(trim(deSerializeJsonString(fh)));
747                         std::getline(fh, bit, ' ');
748                         std::getline(fh, bit, ' ');
749                         row.oldParam1 = atoi(trim(bit).c_str());
750                         std::getline(fh, bit, ' ');
751                         row.oldParam2 = atoi(trim(bit).c_str());
752                         row.oldMeta   = trim(deSerializeJsonString(fh));
753                         std::getline(fh, bit, ' ');
754                         row.newNode   = getNodeId(trim(deSerializeJsonString(fh)));
755                         std::getline(fh, bit, ' ');
756                         std::getline(fh, bit, ' ');
757                         row.newParam1 = atoi(trim(bit).c_str());
758                         std::getline(fh, bit, ' ');
759                         row.newParam2 = atoi(trim(bit).c_str());
760                         row.newMeta   = trim(deSerializeJsonString(fh));
761                         std::getline(fh, bit, ' ');
762                         std::getline(fh, bit, ' ');
763                         std::getline(fh, bit);
764                         row.guessed = (int)(trim(bit) == "actor_is_guess");
765                 } else {
766                         errorstream << "Unrecognized rollback action type \""
767                                 << bit << "\"!" << std::endl;
768                         continue;
769                 }
770
771                 registerRow(row);
772                 ++i;
773
774                 if (time(0) - t >= 1) {
775                         SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
776                         sqlite3_reset(stmt_commit);
777                         t = time(0);
778                         std::cout
779                                 << " Done: " << static_cast<int>((static_cast<float>(fh.tellg()) / static_cast<float>(file_size)) * 100) << "%"
780                                 << " Speed: " << i / (t - start) << "/second     \r" << std::flush;
781                         SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
782                         sqlite3_reset(stmt_begin);
783                 }
784         } while (fh.good());
785         SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
786         sqlite3_reset(stmt_commit);
787
788         SQLOK(sqlite3_finalize(stmt_begin));
789         SQLOK(sqlite3_finalize(stmt_commit));
790
791         std::cout
792                 << " Done: 100%                                  " << std::endl
793                 << "Now you can delete the old rollback.txt file." << std::endl;
794 }
795
796
797 // Get nearness factor for subject's action for this action
798 // Return value: 0 = impossible, >0 = factor
799 float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p,
800                 time_t suspect_t, v3s16 action_p, time_t action_t)
801 {
802         // Suspect cannot cause things in the past
803         if (action_t < suspect_t) {
804                 return 0;        // 0 = cannot be
805         }
806         // Start from 100
807         int f = 100;
808         // Distance (1 node = -x points)
809         f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
810         // Time (1 second = -x points)
811         f -= 1 * (action_t - suspect_t);
812         // If is a guess, halve the points
813         if (is_guess) {
814                 f *= 0.5;
815         }
816         // Limit to 0
817         if (f < 0) {
818                 f = 0;
819         }
820         return f;
821 }
822
823
824 void RollbackManager::reportAction(const RollbackAction &action_)
825 {
826         // Ignore if not important
827         if (!action_.isImportant(gamedef)) {
828                 return;
829         }
830
831         RollbackAction action = action_;
832         action.unix_time = time(0);
833
834         // Figure out actor
835         action.actor = current_actor;
836         action.actor_is_guess = current_actor_is_guess;
837
838         if (action.actor.empty()) { // If actor is not known, find out suspect or cancel
839                 v3s16 p;
840                 if (!action.getPosition(&p)) {
841                         return;
842                 }
843
844                 action.actor = getSuspect(p, 83, 1);
845                 if (action.actor.empty()) {
846                         return;
847                 }
848
849                 action.actor_is_guess = true;
850         }
851
852         addAction(action);
853 }
854
855 std::string RollbackManager::getActor()
856 {
857         return current_actor;
858 }
859
860 bool RollbackManager::isActorGuess()
861 {
862         return current_actor_is_guess;
863 }
864
865 void RollbackManager::setActor(const std::string & actor, bool is_guess)
866 {
867         current_actor = actor;
868         current_actor_is_guess = is_guess;
869 }
870
871 std::string RollbackManager::getSuspect(v3s16 p, float nearness_shortcut,
872                 float min_nearness)
873 {
874         if (current_actor != "") {
875                 return current_actor;
876         }
877         int cur_time = time(0);
878         time_t first_time = cur_time - (100 - min_nearness);
879         RollbackAction likely_suspect;
880         float likely_suspect_nearness = 0;
881         for (std::list<RollbackAction>::const_reverse_iterator
882              i = action_latest_buffer.rbegin();
883              i != action_latest_buffer.rend(); ++i) {
884                 if (i->unix_time < first_time) {
885                         break;
886                 }
887                 if (i->actor == "") {
888                         continue;
889                 }
890                 // Find position of suspect or continue
891                 v3s16 suspect_p;
892                 if (!i->getPosition(&suspect_p)) {
893                         continue;
894                 }
895                 float f = getSuspectNearness(i->actor_is_guess, suspect_p,
896                                              i->unix_time, p, cur_time);
897                 if (f >= min_nearness && f > likely_suspect_nearness) {
898                         likely_suspect_nearness = f;
899                         likely_suspect = *i;
900                         if (likely_suspect_nearness >= nearness_shortcut) {
901                                 break;
902                         }
903                 }
904         }
905         // No likely suspect was found
906         if (likely_suspect_nearness == 0) {
907                 return "";
908         }
909         // Likely suspect was found
910         return likely_suspect.actor;
911 }
912
913
914 void RollbackManager::flush()
915 {
916         sqlite3_exec(db, "BEGIN", NULL, NULL, NULL);
917
918         std::list<RollbackAction>::const_iterator iter;
919
920         for (iter  = action_todisk_buffer.begin();
921                         iter != action_todisk_buffer.end();
922                         ++iter) {
923                 if (iter->actor == "") {
924                         continue;
925                 }
926
927                 registerRow(actionRowFromRollbackAction(*iter));
928         }
929
930         sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
931         action_todisk_buffer.clear();
932 }
933
934
935 void RollbackManager::addAction(const RollbackAction & action)
936 {
937         action_todisk_buffer.push_back(action);
938         action_latest_buffer.push_back(action);
939
940         // Flush to disk sometimes
941         if (action_todisk_buffer.size() >= 500) {
942                 flush();
943         }
944 }
945
946 std::list<RollbackAction> RollbackManager::getEntriesSince(time_t first_time)
947 {
948         flush();
949         return getActionsSince(first_time);
950 }
951
952 std::list<RollbackAction> RollbackManager::getNodeActors(v3s16 pos, int range,
953                 time_t seconds, int limit)
954 {
955         flush();
956         time_t cur_time = time(0);
957         time_t first_time = cur_time - seconds;
958
959         return getActionsSince_range(first_time, pos, range, limit);
960 }
961
962 std::list<RollbackAction> RollbackManager::getRevertActions(
963                 const std::string &actor_filter,
964                 time_t seconds)
965 {
966         time_t cur_time = time(0);
967         time_t first_time = cur_time - seconds;
968
969         flush();
970
971         return getActionsSince(first_time, actor_filter);
972 }
973