#include <err.h>
#include <errno.h>
#include <endian.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <term.h>
#include <unistd.h>
#include "pathnames.h"
#include "screen.h"
#include "scores.h"
#include "tetris.h"
#ifndef RESCUEDIR
#define ALLOW_SCORE_UPDATES
#endif
#define NUMSPOTS (MAXHISCORES + 1)
#define NLEVELS (MAXLEVEL + 1)
static time_t now;
static int nscores;
static int gotscores;
static struct highscore scores[NUMSPOTS];
static int checkscores(struct highscore *, int);
static int cmpscores(const void *, const void *);
static void getscores(int *);
static void printem(int, int, struct highscore *, int, const char *);
static char *thisuser(void);
static const char hsh_magic_val[HSH_MAGIC_SIZE] = "//:\0\0://";
#define HSH_ENDIAN_NATIVE 0x12345678
#define HSH_ENDIAN_OPP 0x78563412
#define HSH_VERSION 1
#define SCOREFILE_ERROR (-1)
#define SCOREFILE_CURRENT 0
#define SCOREFILE_CURRENT_OPP 1
#define SCOREFILE_599 2
#define SCOREFILE_599_OPP 3
#define SCOREFILE_50 4
#define SCOREFILE_50_OPP 5
static int
scorefile_probe(int sd)
{
struct stat st;
int t1, t2, t3, tx;
ssize_t result;
uint32_t numbers[3], offset56, offset60, offset64;
if (fstat(sd, &st) < 0) {
warn("Score file %s: fstat", _PATH_SCOREFILE);
return -1;
}
t1 = st.st_size % sizeof(struct highscore_ondisk) == 0;
t2 = st.st_size % sizeof(struct highscore_ondisk_599) == 0;
t3 = st.st_size % sizeof(struct highscore_ondisk_50) == 0;
tx = t1 + t2 + t3;
if (tx == 1) {
if (t1) {
return SCOREFILE_CURRENT;
} else if (t2) {
return SCOREFILE_599;
} else {
return SCOREFILE_50;
}
} else if (tx == 0) {
goto wildguess;
}
if (lseek(sd, 56, SEEK_SET) < 0) {
warn("Score file %s: lseek", _PATH_SCOREFILE);
return -1;
}
result = read(sd, &numbers, sizeof(numbers));
if (result < 0) {
warn("Score file %s: read", _PATH_SCOREFILE);
return -1;
}
if ((size_t)result != sizeof(numbers)) {
warnx("Score file %s: Unexpected EOF", _PATH_SCOREFILE);
return -1;
}
offset56 = numbers[0];
offset60 = numbers[1];
offset64 = numbers[2];
if (offset64 >= MINLEVEL && offset64 <= MAXLEVEL) {
return SCOREFILE_CURRENT;
} else if (offset60 >= MINLEVEL && offset60 <= MAXLEVEL) {
return SCOREFILE_599;
} else if (offset56 >= MINLEVEL && offset56 <= MAXLEVEL) {
return SCOREFILE_50;
}
offset64 = bswap32(offset64);
offset60 = bswap32(offset60);
offset56 = bswap32(offset56);
if (offset64 >= MINLEVEL && offset64 <= MAXLEVEL) {
return SCOREFILE_CURRENT_OPP;
} else if (offset60 >= MINLEVEL && offset60 <= MAXLEVEL) {
return SCOREFILE_599_OPP;
} else if (offset56 >= MINLEVEL && offset56 <= MAXLEVEL) {
return SCOREFILE_50_OPP;
}
wildguess:
warnx("Score file %s is likely corrupt", _PATH_SCOREFILE);
if (sizeof(void *) == 8 && sizeof(time_t) == 8) {
return SCOREFILE_CURRENT;
} else if (sizeof(time_t) == 8) {
return SCOREFILE_599;
} else {
return SCOREFILE_50;
}
}
static void
readname(char *to, size_t maxto, const char *from, size_t maxfrom)
{
size_t amt;
amt = maxto < maxfrom ? maxto : maxfrom;
memcpy(to, from, amt);
to[maxto-1] = '\0';
}
static int32_t
read32(int32_t val, int doflip)
{
if (doflip) {
val = bswap32(val);
}
return val;
}
static int64_t
read64(int64_t val, int doflip)
{
if (doflip) {
val = bswap64(val);
}
return val;
}
static int
readscores(int sd, int doflip)
{
struct highscore_ondisk buf[MAXHISCORES];
ssize_t result;
int i;
result = read(sd, buf, sizeof(buf));
if (result < 0) {
warn("Score file %s: read", _PATH_SCOREFILE);
return -1;
}
nscores = result / sizeof(buf[0]);
for (i=0; i<nscores; i++) {
readname(scores[i].hs_name, sizeof(scores[i].hs_name),
buf[i].hso_name, sizeof(buf[i].hso_name));
scores[i].hs_score = read32(buf[i].hso_score, doflip);
scores[i].hs_level = read32(buf[i].hso_level, doflip);
scores[i].hs_time = read64(buf[i].hso_time, doflip);
}
return 0;
}
static int
readscores599(int sd, int doflip)
{
struct highscore_ondisk_599 buf[MAXHISCORES];
ssize_t result;
int i;
result = read(sd, buf, sizeof(buf));
if (result < 0) {
warn("Score file %s: read", _PATH_SCOREFILE);
return -1;
}
nscores = result / sizeof(buf[0]);
for (i=0; i<nscores; i++) {
readname(scores[i].hs_name, sizeof(scores[i].hs_name),
buf[i].hso599_name, sizeof(buf[i].hso599_name));
scores[i].hs_score = read32(buf[i].hso599_score, doflip);
scores[i].hs_level = read32(buf[i].hso599_level, doflip);
scores[i].hs_time =
read32(buf[i].hso599_time[buf[i].hso599_time[0] == 0],
doflip);
}
return 0;
}
static int
readscores50(int sd, int doflip)
{
struct highscore_ondisk_50 buf[MAXHISCORES];
ssize_t result;
int i;
result = read(sd, buf, sizeof(buf));
if (result < 0) {
warn("Score file %s: read", _PATH_SCOREFILE);
return -1;
}
nscores = result / sizeof(buf[0]);
for (i=0; i<nscores; i++) {
readname(scores[i].hs_name, sizeof(scores[i].hs_name),
buf[i].hso50_name, sizeof(buf[i].hso50_name));
scores[i].hs_score = read32(buf[i].hso50_score, doflip);
scores[i].hs_level = read32(buf[i].hso50_level, doflip);
scores[i].hs_time = read32(buf[i].hso50_time, doflip);
}
return 0;
}
static void
getscores(int *fdp)
{
struct highscore_header header;
int sd, mint, lck;
mode_t mask;
const char *human;
int doflip;
int serrno;
ssize_t result;
#ifdef ALLOW_SCORE_UPDATES
if (fdp != NULL) {
mint = O_RDWR | O_CREAT;
human = "read/write";
lck = LOCK_EX;
} else
#endif
{
mint = O_RDONLY;
human = "reading";
lck = LOCK_SH;
}
setegid(egid);
mask = umask(S_IWOTH);
sd = open(_PATH_SCOREFILE, mint, 0666);
serrno = errno;
(void)umask(mask);
setegid(gid);
if (sd < 0) {
errno = serrno;
if (fdp != NULL || errno != ENOENT) {
warn("Cannot open %s for %s", _PATH_SCOREFILE, human);
}
goto fail;
}
if (flock(sd, lck))
warn("warning: score file %s cannot be locked",
_PATH_SCOREFILE);
result = read(sd, &header, sizeof(header));
if (result < 0) {
warn("Score file %s: read", _PATH_SCOREFILE);
goto sdfail;
}
if (result != 0 && (size_t)result != sizeof(header)) {
warnx("Score file %s: read: unexpected EOF", _PATH_SCOREFILE);
if (lseek(sd, 0, SEEK_SET) < 0) {
warn("Score file %s: lseek", _PATH_SCOREFILE);
goto sdfail;
}
if (ftruncate(sd, 0) == 0) {
result = 0;
} else {
goto sdfail;
}
}
if (result == 0) {
nscores = 0;
} else {
if (!memcmp(header.hsh_magic, hsh_magic_val, HSH_MAGIC_SIZE)) {
if (header.hsh_endiantag == HSH_ENDIAN_NATIVE) {
doflip = 0;
} else if (header.hsh_endiantag == HSH_ENDIAN_OPP) {
doflip = 1;
} else {
warnx("Score file %s: Unknown endian tag %u",
_PATH_SCOREFILE, header.hsh_endiantag);
goto sdfail;
}
if (header.hsh_version != HSH_VERSION) {
warnx("Score file %s: Unknown version code %u",
_PATH_SCOREFILE, header.hsh_version);
goto sdfail;
}
if (readscores(sd, doflip) < 0) {
goto sdfail;
}
} else {
result = scorefile_probe(sd);
if (lseek(sd, 0, SEEK_SET) < 0) {
warn("Score file %s: lseek", _PATH_SCOREFILE);
goto sdfail;
}
switch (result) {
case SCOREFILE_CURRENT:
result = readscores(sd, 0 );
break;
case SCOREFILE_CURRENT_OPP:
result = readscores(sd, 1 );
break;
case SCOREFILE_599:
result = readscores599(sd, 0 );
break;
case SCOREFILE_599_OPP:
result = readscores599(sd, 1 );
break;
case SCOREFILE_50:
result = readscores50(sd, 0 );
break;
case SCOREFILE_50_OPP:
result = readscores50(sd, 1 );
break;
default:
goto sdfail;
}
if (result < 0) {
goto sdfail;
}
}
}
if (fdp)
*fdp = sd;
else
close(sd);
return;
sdfail:
close(sd);
fail:
if (fdp != NULL) {
*fdp = -1;
}
nscores = 0;
}
#ifdef ALLOW_SCORE_UPDATES
static int
dowrite(int sd, const void *vbuf, size_t len)
{
const char *buf = vbuf;
ssize_t result;
size_t done = 0;
while (done < len) {
result = write(sd, buf+done, len-done);
if (result < 0) {
if (errno == EINTR) {
continue;
}
return -1;
}
done += result;
}
return 0;
}
#endif
static void
putscores(int sd)
{
#ifdef ALLOW_SCORE_UPDATES
struct highscore_header header;
struct highscore_ondisk buf[MAXHISCORES] = {0};
int i;
if (sd == -1) {
return;
}
memcpy(header.hsh_magic, hsh_magic_val, HSH_MAGIC_SIZE);
header.hsh_endiantag = HSH_ENDIAN_NATIVE;
header.hsh_version = HSH_VERSION;
for (i=0; i<nscores; i++) {
memcpy(buf[i].hso_name, scores[i].hs_name,
sizeof(buf[i].hso_name));
buf[i].hso_score = scores[i].hs_score;
buf[i].hso_level = scores[i].hs_level;
buf[i].hso_pad = 0xbaadf00d;
buf[i].hso_time = scores[i].hs_time;
}
if (lseek(sd, 0, SEEK_SET) < 0) {
warn("Score file %s: lseek", _PATH_SCOREFILE);
goto fail;
}
if (dowrite(sd, &header, sizeof(header)) < 0 ||
dowrite(sd, buf, sizeof(buf[0]) * nscores) < 0) {
warn("Score file %s: write", _PATH_SCOREFILE);
goto fail;
}
return;
fail:
warnx("high scores may be damaged");
#else
(void)sd;
#endif
}
static void
closescores(int sd)
{
flock(sd, LOCK_UN);
close(sd);
}
void
savescore(int level)
{
struct highscore *sp;
int i;
int change;
int sd;
const char *me;
getscores(&sd);
gotscores = 1;
(void)time(&now);
change = 0;
me = thisuser();
for (i = 0, sp = &scores[0]; i < nscores; i++, sp++) {
if (sp->hs_level != level || strcmp(sp->hs_name, me) != 0)
continue;
if (score > sp->hs_score) {
(void)printf("%s bettered %s %d score of %d!\n",
"\nYou", "your old level", level,
sp->hs_score * sp->hs_level);
sp->hs_score = score;
sp->hs_time = now;
change = 1;
} else if (score == sp->hs_score) {
(void)printf("%s tied %s %d high score.\n",
"\nYou", "your old level", level);
sp->hs_time = now;
change = 1;
}
break;
}
if (i >= nscores) {
strcpy(sp->hs_name, me);
sp->hs_level = level;
sp->hs_score = score;
sp->hs_time = now;
nscores++;
change = 1;
}
if (change) {
nscores = checkscores(scores, nscores);
putscores(sd);
}
closescores(sd);
}
static char *
thisuser(void)
{
const char *p;
struct passwd *pw;
size_t l;
static char u[sizeof(scores[0].hs_name)];
if (u[0])
return (u);
p = getlogin();
if (p == NULL || *p == '\0') {
pw = getpwuid(getuid());
if (pw != NULL)
p = pw->pw_name;
else
p = " ???";
}
l = strlen(p);
if (l >= sizeof(u))
l = sizeof(u) - 1;
memcpy(u, p, l);
u[l] = '\0';
return (u);
}
static int
cmpscores(const void *x, const void *y)
{
const struct highscore *a, *b;
long l;
a = x;
b = y;
l = (long)b->hs_level * b->hs_score - (long)a->hs_level * a->hs_score;
if (l < 0)
return (-1);
if (l > 0)
return (1);
if (a->hs_time < b->hs_time)
return (-1);
if (a->hs_time > b->hs_time)
return (1);
return (0);
}
static int
checkscores(struct highscore *hs, int num)
{
struct highscore *sp;
int i, j, k, numnames;
int levelfound[NLEVELS];
struct peruser {
char *name;
int times;
} count[NUMSPOTS];
struct peruser *pu;
qsort((void *)hs, nscores, sizeof(*hs), cmpscores);
for (i = MINLEVEL; i < NLEVELS; i++)
levelfound[i] = 0;
numnames = 0;
for (i = 0, sp = hs; i < num;) {
for (j = 0, pu = count; j < numnames; j++, pu++)
if (strcmp(sp->hs_name, pu->name) == 0)
break;
if (j == numnames) {
pu->name = sp->hs_name;
pu->times = 1;
numnames++;
} else {
if ((pu->times < MAXSCORES &&
getpwnam(sp->hs_name) != NULL &&
sp->hs_time + EXPIRATION >= now) ||
levelfound[sp->hs_level] == 0)
pu->times++;
else {
num--;
for (k = i; k < num; k++)
hs[k] = hs[k + 1];
continue;
}
}
if (sp->hs_level < NLEVELS && sp->hs_level >= 0)
levelfound[sp->hs_level] = 1;
i++, sp++;
}
return (num > MAXHISCORES ? MAXHISCORES : num);
}
void
showscores(int level)
{
struct highscore *sp;
int i, n, c;
const char *me;
int levelfound[NLEVELS];
if (!gotscores)
getscores(NULL);
(void)printf("\n\t\t\t Tetris High Scores\n");
me = level && enter_standout_mode ? thisuser() : NULL;
for (i = MINLEVEL; i < NLEVELS; i++)
levelfound[i] = 0;
for (i = 0, sp = scores; i < nscores; i++, sp++) {
if (sp->hs_level < NLEVELS && sp->hs_level >= 0) {
if (levelfound[sp->hs_level])
sp->hs_time = 0;
else {
sp->hs_time = 1;
levelfound[sp->hs_level] = 1;
}
}
}
for (i = 0, sp = scores; i < nscores; sp += n) {
n = 40;
if (i + n > nscores)
n = nscores - i;
printem(level, i + 1, sp, n, me);
if ((i += n) < nscores) {
(void)printf("\nHit RETURN to continue.");
(void)fflush(stdout);
while ((c = getchar()) != '\n')
if (c == EOF)
break;
(void)printf("\n");
}
}
}
static void
printem(int level, int offset, struct highscore *hs, int n, const char *me)
{
struct highscore *sp;
int nrows, row, col, item, i, highlight;
char buf[100];
#define TITLE "Rank Score Name (points/level)"
printf("%s %s\n", TITLE, n > 1 ? TITLE : "");
highlight = 0;
nrows = (n + 1) / 2;
for (row = 0; row < nrows; row++) {
for (col = 0; col < 2; col++) {
item = col * nrows + row;
if (item >= n) {
(void)putchar('\n');
continue;
}
sp = &hs[item];
(void)snprintf(buf, sizeof(buf),
"%3d%c %6d %-11s (%6d on %d)",
item + offset, sp->hs_time ? '*' : ' ',
sp->hs_score * sp->hs_level,
sp->hs_name, sp->hs_score, sp->hs_level);
if (me != NULL &&
sp->hs_level == level &&
sp->hs_score == score &&
strcmp(sp->hs_name, me) == 0) {
putpad(enter_standout_mode);
highlight = 1;
}
(void)printf("%s", buf);
if (highlight) {
putpad(exit_standout_mode);
highlight = 0;
}
if (col == 0)
for (i = 40 - strlen(buf); --i >= 0;)
(void)putchar(' ');
else
(void)putchar('\n');
}
}
}