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