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
|
/*
* util.c -- Utilities.
*
* This file is donated to the Tox Project.
* Copyright 2013 plutooo
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <time.h>
/* for CLIENT_ID_SIZE */
#include "DHT.h"
#include "util.h"
uint64_t now()
{
return time(NULL);
}
uint64_t random_64b()
{
uint64_t r;
// This is probably not random enough?
r = random_int();
r <<= 32;
r |= random_int();
return r;
}
bool id_eq(uint8_t *dest, uint8_t *src)
{
return memcmp(dest, src, CLIENT_ID_SIZE) == 0;
}
void id_cpy(uint8_t *dest, uint8_t *src)
{
memcpy(dest, src, CLIENT_ID_SIZE);
}
int load_state(load_state_callback_func load_state_callback, void *outer,
uint8_t *data, uint32_t length, uint16_t cookie_inner)
{
if (!load_state_callback || !data) {
#ifdef DEBUG
fprintf(stderr, "load_state() called with invalid args.\n");
#endif
return -1;
}
uint16_t type;
uint32_t length_sub, cookie_type;
uint32_t size32 = sizeof(uint32_t), size_head = size32 * 2;
while (length >= size_head) {
length_sub = *(uint32_t *)data;
cookie_type = *(uint32_t *)(data + size32);
data += size_head;
length -= size_head;
if (length < length_sub) {
/* file truncated */
#ifdef DEBUG
fprintf(stderr, "state file too short: %u < %u\n", length, length_sub);
#endif
return -1;
}
if ((cookie_type >> 16) != cookie_inner) {
/* something is not matching up in a bad way, give up */
#ifdef DEBUG
fprintf(stderr, "state file garbeled: %04hx != %04hx\n", (cookie_type >> 16), cookie_inner);
#endif
return -1;
}
type = cookie_type & 0xFFFF;
if (-1 == load_state_callback(outer, data, length_sub, type))
return -1;
data += length_sub;
length -= length_sub;
}
return length == 0 ? 0 : -1;
};
#ifdef LOGGING
time_t starttime = 0;
char logbuffer[512];
static FILE *logfile = NULL;
void loginit(uint16_t port)
{
if (logfile)
fclose(logfile);
sprintf(logbuffer, "%u-%u.log", ntohs(port), (uint32_t)now());
logfile = fopen(logbuffer, "w");
starttime = now();
};
void loglog(char *text)
{
if (logfile) {
fprintf(logfile, "%4u ", (uint32_t)(now() - starttime));
fprintf(logfile, text);
fflush(logfile);
}
};
void logexit()
{
if (logfile) {
fclose(logfile);
logfile = NULL;
}
};
#endif
|