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
|
/*
* grvscored.c
*
* Simple highscore server -- run this from (x)inetd on ports
* 22392 with option -s and 22393 with option -r
*/
#include <inttypes.h>
#include <limits.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include "highscore.h"
int score_send(const char *file)
{
FILE *f = fopen(file, "r");
if ( !f )
exit(1);
flock(fileno(f), LOCK_SH);
alarm(120); /* Make sure we have a sane timeout */
highscore_parse(f, fgets);
fclose(f);
return highscore_write(stdout, fputs) ? 1 : 0;
}
int score_recv(const char *file)
{
FILE *f = fopen(file, "r+");
FILE *t;
char *tp;
if ( !f || !(tp = alloca(strlen(file)+5)) )
exit(1);
sprintf(tp, "%s.tmp", file);
if ( !(t = fopen(tp, "w")) )
exit(1);
flock(fileno(f), LOCK_EX);
alarm(120); /* Make sure we have a sane timeout */
highscore_parse(f, fgets);
rewind(f);
highscore_parse(stdin, fgets);
if ( highscore_write(t, fputs) ) {
unlink(tp);
fclose(f);
return 1;
} else {
rename(tp, file);
fclose(f);
return 0;
}
}
int main(int argc, char *argv[])
{
if ( argc != 3 ) {
fprintf(stderr, "Usage: %s -s|r file\n", argv[0]);
exit(1);
}
highscore_init();
if ( argv[1][0] == '-' && argv[1][1] == 's' ) {
return score_send(argv[2]);
} else if ( argv[1][0] == '-' && argv[1][1] == 'r' ) {
return score_recv(argv[2]);
}
exit(1);
}
|