-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmultizorkd.c
2783 lines (2441 loc) · 118 KB
/
multizorkd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MojoZork; a simple, just-for-fun implementation of Infocom's Z-Machine.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <unistd.h>
#include <signal.h>
#include <poll.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <fcntl.h>
#include <setjmp.h>
#include <assert.h>
#include "sqlite3.h"
#define MULTIZORK 1
#include "mojozork.c"
#define MULTIZORKD_VERSION "0.0.8"
#define MULTIZORKD_DEFAULT_PORT 23 /* telnet! */
#define MULTIZORKD_DEFAULT_BACKLOG 64
#define MULTIZORKD_DEFAULT_EGID 0
#define MULTIZORKD_DEFAULT_EUID 0
#define MULTIZORK_TRANSCRIPT_BASEURL "https://multizork.icculus.org"
#define MULTIZORK_BLOCKED_TIMEOUT (60 * 60 * 24) /* 24 hours in seconds */
#define MULTIZORK_AUTOSAVE_EVERY_X_MOVES 30
typedef unsigned int uint; // for cleaner printf casting.
// the "_t" drives me nuts. :/
typedef uint8_t uint8;
typedef int8_t sint8;
typedef uint16_t uint16;
typedef int16_t sint16;
typedef uint32_t uint32;
typedef int32_t sint32;
typedef uint64_t uint64;
typedef int64_t sint64;
typedef size_t uintptr;
#define ARRAYSIZE(x) ( (sizeof (x)) / (sizeof ((x)[0])) )
static time_t GNow = 0;
static const char *GOriginalStoryName = NULL;
static uint8 *GOriginalStory = NULL;
static uint32 GOriginalStoryLen = 0;
static void loginfo(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf("multizorkd: ");
vprintf(fmt, ap);
va_end(ap);
printf("\n");
}
#if defined(__GNUC__) || defined(__clang__)
static void panic(const char *fmt, ...) __attribute__((noreturn));
#endif
static void panic(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf("multizorkd: ");
vprintf(fmt, ap);
va_end(ap);
printf("\n");
fflush(stdout);
exit(1);
}
typedef struct Connection Connection;
typedef enum ConnectionState
{
CONNSTATE_READY,
CONNSTATE_DRAINING,
CONNSTATE_CLOSING,
// never happens, we destroy the object once we hit this state. CONNSTATE_DISCONNECTED
} ConnectionState;
#define MULTIPLAYER_PROP_DATALEN 32 // ZORK 1 SPECIFIC MAGIC: other games (or longer player names) might need more.
typedef struct Player
{
Connection *connection; // null if user is disconnected; player lives on.
sqlite3_int64 dbid;
char username[16];
char hash[8];
uint32 next_logical_pc; // next step_instance() should run this player from this z-machine program counter.
uint32 next_logical_sp; // next step_instance() should run this player from this z-machine stack pointer.
uint16 next_logical_bp; // next step_instance() should run this player from this z-machine base pointer.
uint16 stack[2048]; // Copy of the stack to restore for next step_instance() // !!! FIXME: make this dynamic?
uint8 *next_inputbuf; // where to write the next input for this player.
uint8 next_inputbuflen;
uint16 next_operands[2]; // to save off the READ operands for later.
char againbuf[128];
uint8 object_table_data[9];
uint8 property_table_data[MULTIPLAYER_PROP_DATALEN];
// ZORK 1 SPECIFIC MAGIC: track the TOUCHBIT for each room per-player, so they all get descriptions on their first visit.
uint8 touchbits[32];
// ZORK 1 SPECIFIC MAGIC: these are player-specific globals we need to manage.
uint16 gvar_location;
uint16 gvar_coffin_held;
uint16 gvar_dead;
uint16 gvar_deaths;
uint16 gvar_lit;
uint16 gvar_alwayslit;
uint16 gvar_verbose;
uint16 gvar_superbrief;
uint16 gvar_lucky;
uint16 gvar_loadallowed;
// !!! FIXME: several more, probably.
int game_over;
} Player;
typedef struct Instance
{
ZMachineState zmachine_state;
sqlite3_int64 dbid;
int started;
char hash[8];
Player players[4];
int num_players;
int current_player; // the player we're currently running the z-machine for.
time_t savetime;
int moves_since_last_save;
sqlite3_int64 crashed;
jmp_buf jmpbuf;
} Instance;
typedef void (*InputFn)(Connection *conn, const char *str);
struct Connection
{
int sock;
ConnectionState state;
InputFn inputfn;
Instance *instance;
char address[64];
char username[16];
char inputbuf[128];
uint32 inputbuf_used;
int overlong_input;
char *outputbuf;
uint32 outputbuf_len;
uint32 outputbuf_used;
time_t last_activity;
int blocked;
};
static Connection **connections = NULL;
static size_t num_connections = 0;
#define MULTIZORK_DATABASE_PATH "multizork.sqlite3"
#define SQL_CREATE_TABLES \
"create table if not exists instances (" \
" id integer primary key," \
" hashid text not null unique," \
" num_players integer unsigned not null," \
" starttime integer unsigned not null," \
" savetime integer unsigned not null," \
" instructions_run integer unsigned not null," \
" dynamic_memory blob not null," \
" story_filename text not null," \
" crashed integer not null default 0" \
");" \
" " \
"create index if not exists instance_index on instances (hashid);" \
" " \
"create table if not exists players (" \
" id integer primary key," \
" hashid text not null unique," \
" instance integer not null," \
" username text not null," \
" next_logical_pc integer unsigned not null," \
" next_logical_sp integer unsigned not null," \
" next_logical_bp integer unsigned not null," \
" next_logical_inputbuf integer unsigned not null," \
" next_logical_inputbuflen integer unsigned not null," \
" next_operands_1 integer unsigned not null," \
" next_operands_2 integer unsigned not null," \
" againbuf text not null," \
" stack blob not null," \
" object_table_data blob not null," \
" property_table_data blob not null," \
" touchbits blob not null," \
" gvar_location integer unsigned not null," \
" gvar_coffin_held integer unsigned not null," \
" gvar_dead integer unsigned not null," \
" gvar_deaths integer unsigned not null," \
" gvar_lit integer unsigned not null," \
" gvar_alwayslit integer unsigned not null," \
" gvar_verbose integer unsigned not null," \
" gvar_superbrief integer unsigned not null," \
" gvar_lucky integer unsigned not null," \
" gvar_loadallowed integer unsigned not null," \
/* !!! FIXME: several more, probably. */ \
" game_over integer not null default 0" \
");" \
" " \
"create index if not exists players_index on players (hashid);" \
" " \
"create table if not exists transcripts (" \
" id integer primary key," \
" timestamp integer unsigned not null," \
" player integer not null," \
" texttype integer not null," \
" content text not null" \
");" \
" " \
"create index if not exists transcript_index on transcripts (player);" \
" " \
"create table if not exists used_hashes (" \
" hashid text not null unique" \
");" \
" " \
"create index if not exists used_hashes_index on used_hashes (hashid);" \
" " \
"create table if not exists crashes (" \
" id integer primary key," \
" instance integer not null," \
" timestamp integer unsigned not null," \
" current_player integer unsigned not null," \
" logical_pc integer unsigned not null," \
" errstr text not null" \
");" \
" " \
"create table if not exists blocked (" \
" id integer primary key," \
" address text not null," \
" timestamp integer unsigned not null" \
");" \
" " \
"create index if not exists blocked_index on blocked (address);" \
#define SQL_TRANSCRIPT_INSERT \
"insert into transcripts (timestamp, player, texttype, content) values ($timestamp, $player, $texttype, $content);"
#define SQL_USED_HASH_INSERT \
"insert into used_hashes (hashid) values ($hashid);"
#define SQL_INSTANCE_INSERT \
"insert into instances (hashid, num_players, starttime, savetime, instructions_run, dynamic_memory, story_filename)" \
" values ($hashid, $num_players, $starttime, $savetime, $instructions_run, $dynamic_memory, $story_filename);"
#define SQL_INSTANCE_UPDATE \
"update instances set savetime=$savetime, instructions_run=$instructions_run, crashed=$crashed, dynamic_memory=$dynamic_memory where id=$id limit 1;"
#define SQL_INSTANCE_SELECT \
"select * from instances where id=$id limit 1;"
#define SQL_PLAYER_INSERT \
"insert into players (hashid, instance, username, next_logical_pc, next_logical_sp, next_logical_bp," \
" next_logical_inputbuf, next_logical_inputbuflen, next_operands_1, next_operands_2, againbuf, stack," \
" object_table_data, property_table_data, touchbits, gvar_location, gvar_coffin_held, gvar_dead, gvar_deaths," \
" gvar_lit, gvar_alwayslit, gvar_verbose, gvar_superbrief, gvar_lucky, gvar_loadallowed, game_over" \
") values ($hashid, $instance, $username, $next_logical_pc, $next_logical_sp, $next_logical_bp," \
" $next_logical_inputbuf, $next_logical_inputbuflen, $next_operands_1, $next_operands_2, $againbuf, $stack," \
" $object_table_data, $property_table_data, $touchbits, $gvar_location, $gvar_coffin_held, $gvar_dead, $gvar_deaths," \
" $gvar_lit, $gvar_alwayslit, $gvar_verbose, $gvar_superbrief, $gvar_lucky, $gvar_loadallowed, $game_over);"
#define SQL_PLAYER_UPDATE \
"update players set" \
" next_logical_pc = $next_logical_pc, next_logical_sp = $next_logical_sp, next_logical_bp = $next_logical_bp," \
" next_logical_inputbuf = $next_logical_inputbuf, next_logical_inputbuflen = $next_logical_inputbuflen," \
" next_operands_1 = $next_operands_1, next_operands_2 = $next_operands_2, againbuf = $againbuf, stack = $stack," \
" object_table_data = $object_table_data, property_table_data = $property_table_data, touchbits = $touchbits," \
" gvar_location = $gvar_location, gvar_coffin_held = $gvar_coffin_held, gvar_dead = $gvar_dead," \
" gvar_deaths = $gvar_deaths, gvar_lit = $gvar_lit, gvar_alwayslit = $gvar_alwayslit, gvar_verbose = $gvar_verbose," \
" gvar_superbrief = $gvar_superbrief, gvar_lucky = $gvar_lucky, gvar_loadallowed = $gvar_loadallowed, game_over = $game_over" \
" where id=$id limit 1;"
#define SQL_FIND_INSTANCE_BY_PLAYER_HASH \
"select instance from players where hashid=$hashid limit 1;"
#define SQL_PLAYERS_SELECT \
"select * from players where instance=$instance order by id limit $limit;"
#define SQL_RECAP_SELECT \
"select content from (select id, content from transcripts where player=$player order by id desc limit $limit) order by id;"
#define SQL_CRASH_INSERT \
"insert into crashes (instance, timestamp, current_player, logical_pc, errstr)" \
" values ($instance, $timestamp, $current_player, $logical_pc, $errstr);"
#define SQL_BLOCKED_INSERT \
"insert into blocked (address, timestamp) values ($address, $timestamp);"
#define SQL_BLOCKED_SELECT \
"select timestamp from blocked where address = $address order by id desc limit 1;"
#define SQL_RECAP_TRIM \
"delete from transcripts where player = $player and timestamp > $savetime;"
static sqlite3 *GDatabase = NULL;
static sqlite3_stmt *GStmtBegin = NULL;
static sqlite3_stmt *GStmtCommit = NULL;
static sqlite3_stmt *GStmtTranscriptInsert = NULL;
static sqlite3_stmt *GStmtUsedHashInsert = NULL;
static sqlite3_stmt *GStmtInstanceInsert = NULL;
static sqlite3_stmt *GStmtInstanceUpdate = NULL;
static sqlite3_stmt *GStmtInstanceSelect = NULL;
static sqlite3_stmt *GStmtPlayerInsert = NULL;
static sqlite3_stmt *GStmtPlayerUpdate = NULL;
static sqlite3_stmt *GStmtFindInstanceByPlayerHash = NULL;
static sqlite3_stmt *GStmtPlayersSelect = NULL;
static sqlite3_stmt *GStmtRecapSelect = NULL;
static sqlite3_stmt *GStmtCrashInsert = NULL;
static sqlite3_stmt *GStmtBlockedInsert = NULL;
static sqlite3_stmt *GStmtBlockedSelect = NULL;
static sqlite3_stmt *GStmtRecapTrim = NULL;
static void db_log_error(const char *what)
{
loginfo("DBERROR: failed to %s! (%s)", what, sqlite3_errmsg(GDatabase));
}
static int db_set_transaction(sqlite3_stmt *stmt, const char *what)
{
if ((sqlite3_reset(stmt) != SQLITE_OK) || (sqlite3_step(stmt) != SQLITE_DONE)) {
db_log_error(what);
return 0;
}
return 1;
}
static unsigned int db_transaction_count = 0;
static int db_begin_transaction(void)
{
db_transaction_count++;
if (db_transaction_count > 1) {
return 1;
}
return db_set_transaction(GStmtBegin, "begin sqlite3 transaction");
}
static int db_end_transaction(void)
{
assert(db_transaction_count > 0);
db_transaction_count--;
if (db_transaction_count > 0) {
return 1;
}
return db_set_transaction(GStmtCommit, "commit sqlite3 transaction");
}
static int find_sql_column_by_name(sqlite3_stmt *stmt, const char *name)
{
const int total = sqlite3_column_count(stmt);
for (int i = 0; i < total; i++) {
const char *colname = sqlite3_column_name(stmt, i);
if (strcasecmp(colname, name) == 0) {
return i;
}
}
panic("Asked for unknown column '%s' in SQL statement '%s'!", name, sqlite3_sql(stmt));
return -1;
}
static int find_sql_bind_by_name(sqlite3_stmt *stmt, const char *name)
{
char dollarname[64];
snprintf(dollarname, sizeof (dollarname), "$%s", name);
const int retval = sqlite3_bind_parameter_index(stmt, dollarname);
if (retval) {
return retval;
}
panic("Asked for unknown bind '%s' in SQL statement '%s'!", name, sqlite3_sql(stmt));
return 0;
}
#define SQLBINDINT(stmt, name, val) (sqlite3_bind_int((stmt), find_sql_bind_by_name((stmt), (name)), (val)))
#define SQLBINDINT64(stmt, name, val) (sqlite3_bind_int64((stmt), find_sql_bind_by_name((stmt), (name)), (val)))
#define SQLBINDTEXT(stmt, name, val) (sqlite3_bind_text((stmt), find_sql_bind_by_name((stmt), (name)), (val), -1, SQLITE_TRANSIENT))
#define SQLBINDBLOB(stmt, name, val, len) (sqlite3_bind_blob((stmt), find_sql_bind_by_name((stmt), (name)), (val), len, SQLITE_TRANSIENT))
#define SQLCOLUMN(typ, stmt, name) (sqlite3_column_##typ((stmt), find_sql_column_by_name((stmt), (name))))
typedef enum TranscriptTextType
{
TT_GAME_OUTPUT = 0,
TT_PLAYER_INPUT,
TT_SYSTEM_MESSAGE
} TranscriptTextType;
static sqlite3_int64 db_insert_transcript(const sqlite3_int64 player_dbid, const TranscriptTextType texttype, const char *content)
{
//"insert into transcripts (timestamp, player, texttype, content) values ($timestamp, $player, $texttype, $content);"
const sqlite3_int64 retval =
( (sqlite3_reset(GStmtTranscriptInsert) == SQLITE_OK) &&
(SQLBINDINT64(GStmtTranscriptInsert, "timestamp", (sqlite3_int64) GNow) == SQLITE_OK) &&
(SQLBINDINT64(GStmtTranscriptInsert, "player", player_dbid) == SQLITE_OK) &&
(SQLBINDINT(GStmtTranscriptInsert, "texttype", (int) texttype) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtTranscriptInsert, "content", content) == SQLITE_OK) &&
(sqlite3_step(GStmtTranscriptInsert) == SQLITE_DONE) ) ? sqlite3_last_insert_rowid(GDatabase) : 0;
if (!retval) { db_log_error("insert transcript"); }
return retval;
}
static sqlite3_int64 db_insert_used_hash(const char *hashid, int *_notunique)
{
//"insert into used_hashes (hashid) values ($hashid);"
int rc = SQLITE_DONE;
const sqlite3_int64 retval =
( (sqlite3_reset(GStmtUsedHashInsert) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtUsedHashInsert, "hashid", hashid) == SQLITE_OK) &&
((rc = sqlite3_step(GStmtUsedHashInsert)) == SQLITE_DONE) ) ? sqlite3_last_insert_rowid(GDatabase) : 0;
*_notunique = (rc == SQLITE_CONSTRAINT);
if ((!retval) && (!*_notunique)) {
db_log_error("insert used hash");
}
return retval;
}
static sqlite3_int64 db_insert_instance(const Instance *inst)
{
//"insert into instances (hashid, num_players, starttime, savetime, instructions_run, dynamic_memory, story_filename)"
//" values ($hashid, $num_players, $starttime, $savetime, $instructions_run, $dynamic_memory, $story_filename);"
const sqlite3_int64 retval =
( (sqlite3_reset(GStmtInstanceInsert) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtInstanceInsert, "hashid", inst->hash) == SQLITE_OK) &&
(SQLBINDINT(GStmtInstanceInsert, "num_players", inst->num_players) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceInsert, "starttime", (sqlite3_int64) GNow) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceInsert, "savetime", (sqlite3_int64) GNow) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceInsert, "instructions_run", (sqlite3_int64) inst->zmachine_state.instructions_run) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtInstanceInsert, "dynamic_memory", inst->zmachine_state.story, inst->zmachine_state.header.staticmem_addr) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtInstanceInsert, "story_filename", inst->zmachine_state.story_filename) == SQLITE_OK) &&
(sqlite3_step(GStmtInstanceInsert) == SQLITE_DONE) ) ? sqlite3_last_insert_rowid(GDatabase) : 0;
if (!retval) { db_log_error("insert instance"); }
return retval;
}
static int db_update_instance(const Instance *inst)
{
//"update instances set savetime=$savetime, instructions_run=$instructions_run, crashed=$crashed, dynamic_memory=$dynamic_memory where id=$id limit 1;"
assert(inst->dbid != 0);
const int retval =
( (sqlite3_reset(GStmtInstanceUpdate) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceUpdate, "savetime", (sqlite3_int64) GNow) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceUpdate, "instructions_run", (sqlite3_int64) inst->zmachine_state.instructions_run) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtInstanceUpdate, "dynamic_memory", inst->zmachine_state.story, inst->zmachine_state.header.staticmem_addr) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceUpdate, "crashed", inst->crashed) == SQLITE_OK) &&
(SQLBINDINT64(GStmtInstanceUpdate, "id", (sqlite3_int64) inst->dbid) == SQLITE_OK) &&
(sqlite3_step(GStmtInstanceUpdate) == SQLITE_DONE) ) ? 1 : 0;
if (!retval) { db_log_error("update instance"); }
return retval;
}
static sqlite3_int64 db_insert_player(const Instance *inst, const int playernum)
{
//"insert into players (hashid, instance, username, next_logical_pc, next_logical_sp, next_logical_bp,"
//" next_logical_inputbuf, next_logical_inputbuflen, next_operands_1, next_operands_2, againbuf, stack,"
//" object_table_data, property_table_data, touchbits, gvar_location, gvar_coffin_held, gvar_dead, gvar_deaths,"
//" gvar_lit, gvar_alwayslit, gvar_verbose, gvar_superbrief, gvar_lucky, gvar_loadallowed, game_over"
//") values ($hashid, $instance, $username, $next_logical_pc, $next_logical_sp, $next_logical_bp,"
//" $next_logical_inputbuf, $next_logical_inputbuflen, $next_operands_1, $next_operands_2, $againbuf, $stack,"
//" $object_table_data, $property_table_data, $touchbits, $gvar_location, $gvar_coffin_held, $gvar_dead, $gvar_deaths,"
//" $gvar_lit, $gvar_alwayslit, $gvar_verbose, $gvar_superbrief, $gvar_lucky, $gvar_loadallowed, $game_over);"
const Player *player = &inst->players[playernum];
assert(player->dbid == 0);
const sqlite3_int64 retval =
( (sqlite3_reset(GStmtPlayerInsert) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtPlayerInsert, "hashid", player->hash) == SQLITE_OK) &&
(SQLBINDINT64(GStmtPlayerInsert, "instance", inst->dbid) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtPlayerInsert, "username", player->username) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_logical_pc", (int) player->next_logical_pc) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_logical_sp", (int) player->next_logical_sp) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_logical_bp", (int) player->next_logical_bp) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_logical_inputbuf", player->next_inputbuf ? ((int) (player->next_inputbuf - inst->zmachine_state.story)) : 0) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_logical_inputbuflen", player->next_inputbuflen) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_operands_1", (int) player->next_operands[0]) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "next_operands_2", (int) player->next_operands[1]) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtPlayerInsert, "againbuf", player->againbuf) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerInsert, "stack", player->stack, player->next_logical_sp * 2) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerInsert, "object_table_data", player->object_table_data, sizeof (player->object_table_data)) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerInsert, "property_table_data", player->property_table_data, sizeof (player->property_table_data)) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerInsert, "touchbits", player->touchbits, sizeof (player->touchbits)) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_location", (int) player->gvar_location) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_coffin_held", (int) player->gvar_coffin_held) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_dead", (int) player->gvar_dead) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_deaths", (int) player->gvar_deaths) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_lit", (int) player->gvar_lit) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_alwayslit", (int) player->gvar_alwayslit) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_verbose", (int) player->gvar_verbose) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_superbrief", (int) player->gvar_superbrief) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_lucky", (int) player->gvar_lucky) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "gvar_loadallowed", (int) player->gvar_loadallowed) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerInsert, "game_over", player->game_over) == SQLITE_OK) &&
(sqlite3_step(GStmtPlayerInsert) == SQLITE_DONE) ) ? sqlite3_last_insert_rowid(GDatabase) : 0;
if (!retval) { db_log_error("insert player"); }
return retval;
}
static int db_update_player(const Instance *inst, const int playernum)
{
//"update players set"
//" next_logical_pc = $next_logical_pc, next_logical_sp = $next_logical_sp, next_logical_bp = $next_logical_bp,"
//" next_logical_inputbuf = $next_logical_inputbuf, next_logical_inputbuflen = $next_logical_inputbuflen,"
//" next_operands_1 = $next_operands_1, next_operands_2 = $next_operands_2, againbuf = $againbuf, stack = $stack,"
//" object_table_data = $object_table_data, property_table_data = $property_table_data, touchbits = $touchbits,"
//" gvar_location = $gvar_location, gvar_coffin_held = $gvar_coffin_held, gvar_dead = $gvar_dead,"
//" gvar_deaths = $gvar_deaths, gvar_lit = $gvar_lit, gvar_alwayslit = $gvar_alwayslit, gvar_verbose = $gvar_verbose,"
//" gvar_superbrief = $gvar_superbrief, gvar_lucky = $gvar_lucky, gvar_loadallowed = $gvar_loadallowed, game_over = $game_over"
//" where id=$id limit 1;"
const Player *player = &inst->players[playernum];
assert(player->dbid != 0);
const int retval =
( (sqlite3_reset(GStmtPlayerUpdate) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_logical_pc", (int) player->next_logical_pc) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_logical_sp", (int) player->next_logical_sp) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_logical_bp", (int) player->next_logical_bp) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_logical_inputbuf", player->next_inputbuf ? ((int) (player->next_inputbuf - inst->zmachine_state.story)) : 0) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_logical_inputbuflen", player->next_inputbuflen) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_operands_1", (int) player->next_operands[0]) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "next_operands_2", (int) player->next_operands[1]) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtPlayerUpdate, "againbuf", player->againbuf) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerUpdate, "stack", player->stack, player->next_logical_sp * 2) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerUpdate, "object_table_data", player->object_table_data, sizeof (player->object_table_data)) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerUpdate, "property_table_data", player->property_table_data, sizeof (player->property_table_data)) == SQLITE_OK) &&
(SQLBINDBLOB(GStmtPlayerUpdate, "touchbits", player->touchbits, sizeof (player->touchbits)) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "gvar_location", (int) player->gvar_location) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "gvar_coffin_held", (int) player->gvar_coffin_held) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "gvar_dead", (int) player->gvar_dead) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "gvar_deaths", (int) player->gvar_deaths) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "gvar_lit", (int) player->gvar_lit) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "gvar_alwayslit", (int) player->gvar_alwayslit) == SQLITE_OK) &&
(SQLBINDINT64(GStmtPlayerUpdate, "gvar_verbose", (int) player->gvar_verbose) == SQLITE_OK) &&
(SQLBINDINT64(GStmtPlayerUpdate, "gvar_superbrief", (int) player->gvar_superbrief) == SQLITE_OK) &&
(SQLBINDINT64(GStmtPlayerUpdate, "gvar_lucky", (int) player->gvar_lucky) == SQLITE_OK) &&
(SQLBINDINT64(GStmtPlayerUpdate, "gvar_loadallowed", (int) player->gvar_loadallowed) == SQLITE_OK) &&
(SQLBINDINT(GStmtPlayerUpdate, "game_over", (int) player->game_over) == SQLITE_OK) &&
(SQLBINDINT64(GStmtPlayerUpdate, "id", player->dbid) == SQLITE_OK) &&
(sqlite3_step(GStmtPlayerUpdate) == SQLITE_DONE) ) ? 1 : 0;
if (!retval) { db_log_error("update player"); }
return retval;
}
static sqlite3_int64 db_find_instance_by_player_hash(const char *hashid)
{
//"select instance from players where hashid=$hashid limit 1;"
int rc = SQLITE_ERROR;
if ( (sqlite3_reset(GStmtFindInstanceByPlayerHash) != SQLITE_OK) ||
(SQLBINDTEXT(GStmtFindInstanceByPlayerHash, "hashid", hashid) != SQLITE_OK) ||
((rc = sqlite3_step(GStmtFindInstanceByPlayerHash)) != SQLITE_ROW) ) {
if (rc != SQLITE_DONE) { db_log_error("select instance by player hash"); }
return 0; // error or not found.
}
return SQLCOLUMN(int64, GStmtFindInstanceByPlayerHash, "instance");
}
static int db_select_instance(Instance *inst, const sqlite3_int64 dbid)
{
// this should be a fresh object returned create_instance() that we will update with database info.
assert(!inst->started);
assert(!inst->dbid);
//"select * from instances where id=$id limit 1;"
int rc = SQLITE_ERROR;
if ( (sqlite3_reset(GStmtInstanceSelect) != SQLITE_OK) ||
(SQLBINDINT64(GStmtInstanceSelect, "id", dbid) != SQLITE_OK) ||
((rc = sqlite3_step(GStmtInstanceSelect)) != SQLITE_ROW) ) {
if (rc != SQLITE_DONE) { db_log_error("select instance"); }
return 0; // error or not found.
}
inst->dbid = dbid;
snprintf(inst->hash, sizeof (inst->hash), "%s", SQLCOLUMN(text, GStmtInstanceSelect, "hashid"));
inst->num_players = SQLCOLUMN(int, GStmtInstanceSelect, "num_players");
inst->savetime = (time_t) SQLCOLUMN(int64, GStmtInstanceSelect, "savetime");
inst->crashed = SQLCOLUMN(int64, GStmtInstanceSelect, "crashed");
inst->zmachine_state.instructions_run = (uint32) SQLCOLUMN(int64, GStmtInstanceSelect, "instructions_run");
const void *dynmem = SQLCOLUMN(blob, GStmtInstanceSelect, "dynamic_memory");
size_t dynmemlen = SQLCOLUMN(bytes, GStmtInstanceSelect, "dynamic_memory");
assert(dynmemlen == ((size_t) inst->zmachine_state.header.staticmem_addr));
if ( ((size_t) inst->zmachine_state.header.staticmem_addr) < dynmemlen ) {
dynmemlen = (size_t) inst->zmachine_state.header.staticmem_addr;
}
memcpy(inst->zmachine_state.story, dynmem, dynmemlen);
sqlite3_reset(GStmtInstanceSelect);
//"select * from players where instance=$instance order by id limit $limit;"
if ( (sqlite3_reset(GStmtPlayersSelect) != SQLITE_OK) ||
(SQLBINDINT64(GStmtPlayersSelect, "instance", dbid) != SQLITE_OK) ||
(SQLBINDINT(GStmtPlayersSelect, "limit", inst->num_players) != SQLITE_OK) ) {
db_log_error("select players");
return 0;
}
int num_players = 0;
while (sqlite3_step(GStmtPlayersSelect) == SQLITE_ROW) {
assert(num_players < inst->num_players);
Player *player = &inst->players[num_players];
player->connection = NULL;
player->dbid = SQLCOLUMN(int, GStmtPlayersSelect, "id");
snprintf(player->hash, sizeof (player->hash), "%s", SQLCOLUMN(text, GStmtPlayersSelect, "hashid"));
snprintf(player->username, sizeof (player->username), "%s", SQLCOLUMN(text, GStmtPlayersSelect, "username"));
player->next_logical_pc = (uint32) SQLCOLUMN(int, GStmtPlayersSelect, "next_logical_pc");
player->next_logical_sp = (uint32) SQLCOLUMN(int, GStmtPlayersSelect, "next_logical_sp");
player->next_logical_bp = (uint32) SQLCOLUMN(int, GStmtPlayersSelect, "next_logical_bp");
player->next_inputbuf = inst->zmachine_state.story + ((size_t) SQLCOLUMN(int, GStmtPlayersSelect, "next_logical_inputbuf"));
player->next_inputbuflen = (uint8) SQLCOLUMN(int, GStmtPlayersSelect, "next_logical_inputbuflen");
player->next_operands[0] = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "next_operands_1");
player->next_operands[1] = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "next_operands_2");
snprintf(player->againbuf, sizeof (player->againbuf), "%s", SQLCOLUMN(text, GStmtPlayersSelect, "againbuf"));
memcpy(player->stack, SQLCOLUMN(blob, GStmtPlayersSelect, "stack"), player->next_logical_sp * 2);
memcpy(player->object_table_data, SQLCOLUMN(blob, GStmtPlayersSelect, "object_table_data"), sizeof (player->object_table_data));
memcpy(player->property_table_data, SQLCOLUMN(blob, GStmtPlayersSelect, "property_table_data"), sizeof (player->property_table_data));
memcpy(player->touchbits, SQLCOLUMN(blob, GStmtPlayersSelect, "touchbits"), sizeof (player->touchbits));
player->gvar_location = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_location");
player->gvar_coffin_held = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_coffin_held");
player->gvar_dead = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_dead");
player->gvar_deaths = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_deaths");
player->gvar_lit = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_lit");
player->gvar_alwayslit = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_alwayslit");
player->gvar_verbose = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_verbose");
player->gvar_superbrief = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_superbrief");
player->gvar_lucky = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_lucky");
player->gvar_loadallowed = (uint16) SQLCOLUMN(int, GStmtPlayersSelect, "gvar_loadallowed");
player->game_over = SQLCOLUMN(int, GStmtPlayersSelect, "game_over");
num_players++;
}
sqlite3_reset(GStmtPlayersSelect);
if (num_players != inst->num_players) {
loginfo("Uhoh, instance '%s' has %d players in the database, should be %d!", inst->hash, num_players, inst->num_players);
return 0;
}
return 1;
}
static void write_to_connection(Connection *conn, const char *str);
static int db_select_recap(Player *player, const int rows_of_recap)
{
Connection *conn = player->connection;
if (!conn) {
return 0;
}
//"select content from (select id, content from transcripts where player=$player order by id desc limit $limit) order by id;"
if ( (sqlite3_reset(GStmtRecapSelect) != SQLITE_OK) ||
(SQLBINDINT64(GStmtRecapSelect, "player", player->dbid) != SQLITE_OK) ||
(SQLBINDINT(GStmtRecapSelect, "limit", rows_of_recap) != SQLITE_OK) ) {
db_log_error("select recap");
return 0;
}
while (sqlite3_step(GStmtRecapSelect) == SQLITE_ROW) {
write_to_connection(conn, (const char *) SQLCOLUMN(text, GStmtRecapSelect, "content"));
}
sqlite3_reset(GStmtRecapSelect);
return 1;
}
static sqlite3_int64 db_insert_crash(const char *errstr)
{
Instance *inst = (Instance *) GState; // this works because zmachine_state is the first field in Instance.
if (!inst) {
return 0;
}
//"insert into crashes (instance, timestamp, current_player, logical_pc, errstr)"
//" values ($instance, $timestamp, $current_player, $logical_pc, $errstr);"
const sqlite3_int64 retval =
( (sqlite3_reset(GStmtCrashInsert) == SQLITE_OK) &&
(SQLBINDINT64(GStmtCrashInsert, "instance", inst->dbid) == SQLITE_OK) &&
(SQLBINDINT64(GStmtCrashInsert, "timestamp", (sqlite3_int64) GNow) == SQLITE_OK) &&
(SQLBINDINT(GStmtCrashInsert, "logical_pc", GState->logical_pc) == SQLITE_OK) &&
(SQLBINDINT(GStmtCrashInsert, "current_player", inst->current_player) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtCrashInsert, "errstr", errstr) == SQLITE_OK) &&
(sqlite3_step(GStmtCrashInsert) == SQLITE_DONE) ) ? sqlite3_last_insert_rowid(GDatabase) : 0;
if (!retval) { db_log_error("insert crash"); }
return retval;
}
static sqlite3_int64 db_insert_blocked(const char *address)
{
//"insert into blocked (address, timestamp) values ($address, $timestamp);"
const sqlite3_int64 retval =
( (sqlite3_reset(GStmtBlockedInsert) == SQLITE_OK) &&
(SQLBINDTEXT(GStmtBlockedInsert, "address", address) == SQLITE_OK) &&
(SQLBINDINT64(GStmtBlockedInsert, "timestamp", (sqlite3_int64) GNow) == SQLITE_OK) &&
(sqlite3_step(GStmtBlockedInsert) == SQLITE_DONE) ) ? sqlite3_last_insert_rowid(GDatabase) : 0;
if (!retval) { db_log_error("insert blocked"); }
return retval;
}
static sqlite3_int64 db_select_blocked(const char *address)
{
//"select timestamp from blocked where address = $address order by id desc limit 1;"
int rc = SQLITE_ERROR;
if ( (sqlite3_reset(GStmtBlockedSelect) != SQLITE_OK) ||
(SQLBINDTEXT(GStmtBlockedSelect, "address", address) != SQLITE_OK) ||
((rc = sqlite3_step(GStmtBlockedSelect)) != SQLITE_ROW) ) {
if (rc != SQLITE_DONE) { // DONE == address was never blocked (no results).
db_log_error("select blocked");
}
return 0; // let it through even if an error.
}
const sqlite3_int64 retval = SQLCOLUMN(int64, GStmtBlockedSelect, "timestamp");
sqlite3_reset(GStmtRecapSelect);
return retval;
}
static void db_trim_recap(Instance *inst)
{
//"delete from transcripts where player = $player and timestamp > $savetime;"
for (int i = 0; i < inst->num_players; i++) {
if ( (sqlite3_reset(GStmtRecapTrim) != SQLITE_OK) ||
(SQLBINDINT64(GStmtRecapTrim, "player", inst->players[i].dbid) != SQLITE_OK) ||
(SQLBINDINT64(GStmtRecapTrim, "savetime", (sqlite3_int64) inst->savetime) != SQLITE_OK) ||
(sqlite3_step(GStmtRecapTrim) != SQLITE_DONE) ) {
db_log_error("trim recap");
}
}
}
static void db_init(void)
{
char *errmsg = NULL;
if (sqlite3_initialize() != SQLITE_OK) {
panic("sqlite3_initialize failed!");
}
if (sqlite3_open(MULTIZORK_DATABASE_PATH, &GDatabase) != SQLITE_OK) {
panic("Couldn't open '%s'!", MULTIZORK_DATABASE_PATH);
}
if (sqlite3_exec(GDatabase, SQL_CREATE_TABLES, NULL, NULL, &errmsg) != SQLITE_OK) {
panic("Couldn't create database tables! %s", errmsg);
}
if (sqlite3_prepare_v2(GDatabase, "begin transaction;", -1, &GStmtBegin, NULL) != SQLITE_OK) {
panic("Failed to create BEGIN TRANSACTION SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, "end transaction;", -1, &GStmtCommit, NULL) != SQLITE_OK) {
panic("Failed to create END TRANSACTION SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_TRANSCRIPT_INSERT, -1, &GStmtTranscriptInsert, NULL) != SQLITE_OK) {
panic("Failed to create transcript insert SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_USED_HASH_INSERT, -1, &GStmtUsedHashInsert, NULL) != SQLITE_OK) {
panic("Failed to create used hash insert SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_INSTANCE_INSERT, -1, &GStmtInstanceInsert, NULL) != SQLITE_OK) {
panic("Failed to create instance insert SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_INSTANCE_UPDATE, -1, &GStmtInstanceUpdate, NULL) != SQLITE_OK) {
panic("Failed to create instance update SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_INSTANCE_SELECT, -1, &GStmtInstanceSelect, NULL) != SQLITE_OK) {
panic("Failed to create instance select SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_PLAYER_INSERT, -1, &GStmtPlayerInsert, NULL) != SQLITE_OK) {
panic("Failed to create player insert SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_PLAYER_UPDATE, -1, &GStmtPlayerUpdate, NULL) != SQLITE_OK) {
panic("Failed to create player update SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_FIND_INSTANCE_BY_PLAYER_HASH, -1, &GStmtFindInstanceByPlayerHash, NULL) != SQLITE_OK) {
panic("Failed to create find-instance-by-player-hash SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_PLAYERS_SELECT, -1, &GStmtPlayersSelect, NULL) != SQLITE_OK) {
panic("Failed to create select players SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_RECAP_SELECT, -1, &GStmtRecapSelect, NULL) != SQLITE_OK) {
panic("Failed to create select recap SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_CRASH_INSERT, -1, &GStmtCrashInsert, NULL) != SQLITE_OK) {
panic("Failed to create crash insert SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_BLOCKED_INSERT, -1, &GStmtBlockedInsert, NULL) != SQLITE_OK) {
panic("Failed to create blocked insert SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_BLOCKED_SELECT, -1, &GStmtBlockedSelect, NULL) != SQLITE_OK) {
panic("Failed to create blocked select SQL statement! %s", sqlite3_errmsg(GDatabase));
}
if (sqlite3_prepare_v2(GDatabase, SQL_RECAP_TRIM, -1, &GStmtRecapTrim, NULL) != SQLITE_OK) {
panic("Failed to create recap trim SQL statement! %s", sqlite3_errmsg(GDatabase));
}
}
static void db_quit(void)
{
#define FINALIZE_DB_STMT(x) if (x) { sqlite3_finalize(x); x = NULL; }
FINALIZE_DB_STMT(GStmtBegin);
FINALIZE_DB_STMT(GStmtCommit);
FINALIZE_DB_STMT(GStmtTranscriptInsert);
FINALIZE_DB_STMT(GStmtUsedHashInsert);
FINALIZE_DB_STMT(GStmtInstanceInsert);
FINALIZE_DB_STMT(GStmtInstanceUpdate);
FINALIZE_DB_STMT(GStmtInstanceSelect);
FINALIZE_DB_STMT(GStmtPlayerInsert);
FINALIZE_DB_STMT(GStmtPlayerUpdate);
FINALIZE_DB_STMT(GStmtPlayersSelect);
FINALIZE_DB_STMT(GStmtFindInstanceByPlayerHash);
FINALIZE_DB_STMT(GStmtRecapSelect);
FINALIZE_DB_STMT(GStmtCrashInsert);
FINALIZE_DB_STMT(GStmtBlockedInsert);
FINALIZE_DB_STMT(GStmtBlockedSelect);
FINALIZE_DB_STMT(GStmtRecapTrim);
#undef FINALIZE_DB_STMT
if (GDatabase) {
sqlite3_close(GDatabase);
GDatabase = NULL;
}
sqlite3_shutdown();
}
static int generate_unique_hash(char *hash) // `hash` points to up to 8 bytes of space.
{
// this is kinda cheesy, but it's good enough.
static const char chartable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
int notunique = 0;
do {
for (size_t i = 0; i < 6; i++) {
hash[i] = chartable[((size_t) random()) % (sizeof (chartable)-1)];
}
hash[6] = '\0';
const int rc = db_insert_used_hash(hash, ¬unique);
if (!rc && !notunique) {
return 0; // database problem
}
} while (notunique); // not unique? Try again.
return 1; // we're good.
}
static size_t count_newlines(const char *str, const uintptr slen)
{
size_t retval = 0;
for (size_t i = 0; i < slen; i++) {
if (str[i] == '\n') {
retval++;
}
}
return retval;
}
// This queues a string for sending over the connection's socket when possible.
static void write_to_connection_slen(Connection *conn, const char *str, const uintptr slen)
{
if (!conn || (conn->state != CONNSTATE_READY)) {
return;
}
const size_t needed_space = slen + count_newlines(str, slen);
const size_t avail = conn->outputbuf_len - conn->outputbuf_used;
if (avail < needed_space) {
void *ptr = realloc(conn->outputbuf, conn->outputbuf_len + needed_space + 1);
if (!ptr) {
panic("Uhoh, out of memory in write_to_connection"); // !!! FIXME: we could handle this more gracefully.
}
conn->outputbuf = (char *) ptr;
conn->outputbuf_len += needed_space;
}
// replace "\n" with "\r\n" because telnet is terrible.
for (size_t i = 0; i < slen; i++) {
const char ch = str[i];
if ( (ch == '\n') && ((i == 0) || (str[i-1] != '\r')) ) {
conn->outputbuf[conn->outputbuf_used++] = '\r';
conn->outputbuf[conn->outputbuf_used++] = '\n';
} else {
conn->outputbuf[conn->outputbuf_used++] = ch;
}
}
conn->outputbuf[conn->outputbuf_used] = '\0'; // make sure we're always null-terminated.
}
static void write_to_connection(Connection *conn, const char *str)
{
write_to_connection_slen(conn, str, strlen(str));
}
static void free_instance(Instance *inst);
static void drop_connection(Connection *conn)
{
if (conn->state != CONNSTATE_READY) {
return; // already dropping.
}
loginfo("Starting drop of connection for socket %d", conn->sock);
write_to_connection(conn, "\n\n"); // make sure we are a new line.
conn->state = CONNSTATE_DRAINING; // flush any pending output to the socket first.
Instance *inst = conn->instance;
int players_still_connected = 0;
if (inst != NULL) {
char msg[128];
snprintf(msg, sizeof (msg), "\n\n*** %s has disconnected. If they come back, we'll let you know. ***\n\n\n>", conn->username);
for (size_t i = 0; i < ARRAYSIZE(inst->players); i++) {
Connection *c = inst->players[i].connection;
if (c == conn) {
inst->players[i].connection = NULL; // no longer connected to this instance.
} else if (c != NULL) {
players_still_connected++;
write_to_connection(c, msg);
}
}
conn->instance = NULL; // no longer part of an instance.
if (!players_still_connected) {
free_instance(inst); // no one's still connected? Archive and free the instance.
}
}
}
static void broadcast_to_instance(Instance *inst, const char *str)
{
if (inst) {
for (size_t i = 0; i < ARRAYSIZE(inst->players); i++) {
Player *player = &inst->players[i];
write_to_connection(player->connection, str);
if (i != inst->current_player) { // these will transcribe with rest of buffer generated during inpfn_ingame.
db_insert_transcript(player->dbid, TT_SYSTEM_MESSAGE, str);
}
}
}
}
static void broadcast_to_room(Instance *inst, const uint16 room, const char *str)
{
if (inst) {
for (size_t i = 0; i < ARRAYSIZE(inst->players); i++) {
Player *player = &inst->players[i];
if (player->gvar_location == room) {
write_to_connection(player->connection, str);
if (i != inst->current_player) { // these will transcribe with rest of buffer generated during inpfn_ingame.
db_insert_transcript(player->dbid, TT_SYSTEM_MESSAGE, str);
}
}
}
}
}
static Player *get_current_player(Instance *inst)
{
assert(inst->current_player >= 0);
assert(inst->current_player < ARRAYSIZE(inst->players));
return &inst->players[inst->current_player];
}
// MojoZork Z-Machine overrides...
// ZORK 1 SPECIFIC MAGIC:
// Z-Machine version 3 (what Zork 1 uses) refers to objects by an 8-bit index,
// with 0 being a "null" object, so you can address 255 objects. Zork 1
// uses 250, so we have slots for adding players, but the object table has
// space for _exactly_ 250 objects, with the property data starting in the
// next byte. Since the object table is in dynamic memory, generally we
// can't just move things around and it's legal for a Z-Machine program to
// edit the object table directly by poking dynamic memory if it wants.
// Fortunately, Zork 1 doesn't do this; it only uses the official opcodes