forked from googleprojectzero/Jackalope
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.cpp
706 lines (565 loc) · 17.3 KB
/
server.cpp
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
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#define _CRT_SECURE_NO_WARNINGS
#include "server.h"
#include "directory.h"
#include "common.h"
#include "thread.h"
int ServerCommon::Read(socket_type sock, void *buf, size_t size) {
int ret;
size_t to_read = size;
char *p = (char *)buf;
//printf("starting read\n");
while (to_read) {
int read_chunk;
if (to_read > 0x100000) {
read_chunk = 0x100000;
} else {
read_chunk = (int)to_read;
}
ret = recv(sock, p, read_chunk, 0);
//printf("read returned %ld\n", ret);
if (ret > 0) {
to_read -= ret;
p += ret;
} else {
return 0;
}
}
return 1;
}
int ServerCommon::Write(socket_type sock, const char *buf, size_t size) {
int ret;
size_t to_write = size;
const char *p = (char *)buf;
while (to_write) {
int write_chunk;
if (to_write > 0x100000) {
write_chunk = 0x100000;
} else {
write_chunk = (int)to_write;
}
ret = send(sock, p, write_chunk, 0);
//printf("read returned %ld\n", ret);
if (ret > 0) {
to_write -= ret;
p += ret;
} else {
return 0;
}
}
return 1;
}
int ServerCommon::SendSample(socket_type sock, Sample &sample) {
uint64_t sample_size = sample.size;
Write(sock, (const char *)(&sample_size), sizeof(sample_size));
Write(sock, sample.bytes, sample.size);
return 1;
}
int ServerCommon::RecvSample(socket_type sock, Sample &sample) {
uint64_t sample_size;
if (!Read(sock, &sample_size, sizeof(sample_size))) {
return 0;
}
char *new_bytes = (char*)malloc(sample_size);
if (!new_bytes) return 0;
if (!Read(sock, new_bytes, sample_size)) {
free(new_bytes);
return 0;
}
sample.Init(new_bytes, (size_t)sample_size);
free(new_bytes);
return 1;
}
int ServerCommon::SendString(socket_type sock, std::string &str) {
uint64_t size = str.size();
Write(sock, (const char *)(&size), sizeof(size));
Write(sock, str.data(), size);
return 1;
}
int ServerCommon::RecvString(socket_type sock, std::string &str) {
uint64_t size;
if (!Read(sock, &size, sizeof(size))) {
return 0;
}
char *tmp_data = (char *)malloc(size);
if (!tmp_data) return 0;
if (!Read(sock, tmp_data, size)) {
free(tmp_data);
return 0;
}
str = std::string(tmp_data, size);
free(tmp_data);
return 1;
}
int ServerCommon::SendCoverage(socket_type sock, Coverage &coverage) {
for (auto iter = coverage.begin(); iter != coverage.end(); iter++) {
uint64_t num_offsets = iter->offsets.size();
uint64_t *offsets = (uint64_t *)malloc(num_offsets * sizeof(uint64_t));
size_t i = 0;
for (auto iter2 = iter->offsets.begin(); iter2 != iter->offsets.end(); iter2++) {
offsets[i] = *iter2;
i++;
}
send(sock, "C", 1, 0);
SendString(sock, iter->module_name);
send(sock, (char *)&num_offsets, sizeof(num_offsets), 0);
send(sock, (char *)offsets, (int)(num_offsets * sizeof(uint64_t)), 0);
free(offsets);
}
send(sock, "N", 1, 0);
return 1;
}
int ServerCommon::RecvCoverage(socket_type sock, Coverage &coverage) {
char command;
std::string module_name;
uint64_t num_offsets;
uint64_t *offsets;
while (1) {
if (!Read(sock, &command, 1)) {
return 0;
}
if (command == 'N') break;
if (command != 'C') return 0;
if (!RecvString(sock, module_name)) {
return 0;
}
ModuleCoverage *module_coverage = GetModuleCoverage(coverage, module_name);
if(!module_coverage) {
coverage.push_back({ module_name, {} });
module_coverage = GetModuleCoverage(coverage, module_name);
}
if (!Read(sock, &num_offsets, sizeof(num_offsets))) {
return 0;
}
if (num_offsets > SIZE_MAX / sizeof(uint64_t)) {
return 0;
}
offsets = (uint64_t *)malloc(num_offsets * sizeof(uint64_t));
if (!offsets) return 0;
if (!Read(sock, offsets, (int)(num_offsets * sizeof(uint64_t)))) {
free(offsets);
return 0;
}
for (size_t i = 0; i < num_offsets; i++) {
module_coverage->offsets.insert(offsets[i]);
}
}
return 1;
}
uint64_t CoverageServer::GetIndex(std::vector<TimestampIndex> ×tamps, uint64_t timestamp, uint64_t last_index) {
if (timestamp == 0) return 0;
if (timestamps.empty()) return 0;
if (timestamp >= timestamps[timestamps.size() - 1].timestamp) return last_index;
int64_t l = 0;
int64_t r = timestamps.size() - 1;
int64_t m;
while (l <= r) {
m = (l + r) / 2;
if (timestamps[m].timestamp < timestamp) {
l = m + 1;
} else if (timestamps[m].timestamp > timestamp) {
r = m - 1;
} else {
break;
}
}
if (timestamps[m].timestamp > timestamp) {
while ((m > 0) && (timestamps[m - 1].timestamp > timestamp)) m--;
} else {
while ((m < (int64_t)(timestamps.size() - 1)) && (timestamps[m].timestamp <= timestamp)) m++;
}
if (timestamps[m].timestamp <= timestamp) {
FATAL("Error in GetIndex");
}
return timestamps[m].index;
}
int CoverageServer::ServeUpdates(socket_type sock) {
uint64_t timestamp;
uint64_t client_id, client_execs;
if (!Read(sock, &client_id, sizeof(client_id))) {
return 0;
}
if (!Read(sock, &client_execs, sizeof(client_execs))) {
return 0;
}
printf("Client %016llx reported %llu total execs\n", client_id, client_execs);
if (!Read(sock, ×tamp, sizeof(timestamp))) {
return 0;
}
mutex.LockRead();
Write(sock, (const char *)(&server_timestamp), sizeof(server_timestamp));
if (timestamp >= server_timestamp) {
send(sock, "N", 1, 0);
mutex.UnlockRead();
return 1;
}
uint64_t first_index = GetIndex(corpus.timestamps, timestamp, corpus.samples.size());
if (first_index >= corpus.samples.size()) {
send(sock, "N", 1, 0);
mutex.UnlockRead();
return 1;
}
for (size_t i = first_index; i < corpus.samples.size(); i++) {
Sample &sample = corpus.samples[i];
send(sock, "S", 1, 0);
if (!SendSample(sock, sample)) {
mutex.UnlockRead();
return 0;
}
}
send(sock, "N", 1, 0);
mutex.UnlockRead();
return 1;
}
bool CoverageServer::HasNewCoverage(Coverage *client_coverage, Coverage *new_coverage) {
CoverageDifference(total_coverage, *client_coverage, *new_coverage);
return (!new_coverage->empty());
}
bool CoverageServer::OnNewCoverage(Coverage *client_coverage) {
Coverage new_client_coverage;
CoverageDifference(total_coverage, *client_coverage, new_client_coverage);
if (new_client_coverage.empty()) {
return false;
}
server_timestamp++;
MergeCoverage(total_coverage, new_client_coverage);
return true;
}
int CoverageServer::ReportNewCoverage(socket_type sock) {
char command;
Coverage client_coverage;
Coverage new_client_coverage;
if(!RecvCoverage(sock, client_coverage)) {
return 0;
}
mutex.LockRead();
if (!HasNewCoverage(&client_coverage, &new_client_coverage)) {
mutex.UnlockRead();
send(sock, "N", 1, 0);
return 1;
}
mutex.UnlockRead();
send(sock, "Y", 1, 0);
std::list<Sample> new_samples;
// read samples
while (1) {
if (!Read(sock, &command, 1)) {
return 0;
}
if (command == 'N') break;
if (command != 'S') return 0;
Sample sample;
if (!RecvSample(sock, sample)) {
return 0;
}
new_samples.push_back(sample);
}
mutex.LockWrite();
// we need to check coverage twice as another thread could have
// updated it just before lock
if (!OnNewCoverage(&new_client_coverage)) {
mutex.UnlockWrite();
return 1;
}
if (!new_samples.empty()) {
corpus.timestamps.push_back({ server_timestamp, corpus.samples.size() });
}
for(auto iter = new_samples.begin(); iter != new_samples.end(); iter++) {
char fileindex[20];
sprintf(fileindex, "%05zu", corpus.samples.size());
std::string sample_file = DirJoin(sample_dir, std::string("sample_") + fileindex);
iter->Save(sample_file.c_str());
corpus.samples.push_back(*iter);
}
num_samples = corpus.samples.size();
mutex.UnlockWrite();
return 1;
}
bool CoverageServer::CheckFilename(std::string& filename) {
size_t len = filename.length();
for (size_t i = 0; i < len; i++) {
char c = filename[i];
if ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c == '-') ||
(c == '_'))
{
continue;
} else {
return false;
}
}
return true;
}
int CoverageServer::ReportCrash(socket_type sock) {
char command;
while (1) {
if (!Read(sock, &command, 1)) {
return 0;
}
if (command == 'N') break;
if (command != 'S') return 0;
Sample sample;
if (!RecvSample(sock, sample)) {
return 0;
}
std::string crash_desc;
if (!RecvString(sock, crash_desc)) {
return 0;
}
if (!CheckFilename(crash_desc)) {
WARN("Invalid characters in crash filename");
continue;
}
bool should_save_crash = false;
int duplicates = 0;
crash_mutex.Lock();
num_crashes++;
auto crash_it = unique_crashes.find(crash_desc);
if(crash_it == unique_crashes.end()) {
should_save_crash = true;
duplicates = 1;
unique_crashes[crash_desc] = 1;
num_unique_crashes++;
} else {
if(crash_it->second < MAX_SERVER_IDENTICAL_CRASHES) {
should_save_crash = true;
crash_it->second++;
duplicates = crash_it->second;
}
}
if(should_save_crash) {
std::string crash_filename = crash_desc + "_" + std::to_string(duplicates);
std::string outfile = DirJoin(crash_dir, crash_filename);
sample.Save(outfile.c_str());
}
crash_mutex.Unlock();
}
return 1;
}
void CoverageServer::SaveState() {
mutex.LockRead();
std::string out_file = DirJoin(out_dir, std::string("server_state.dat"));
FILE *fp = fopen(out_file.c_str(), "wb");
if (!fp) {
FATAL("Error saving server state");
}
fwrite(&num_samples, sizeof(num_samples), 1, fp);
fwrite(&server_timestamp, sizeof(server_timestamp), 1, fp);
WriteCoverageBinary(total_coverage, fp);
uint64_t size;
// write corpus
size = corpus.samples.size();
fwrite(&size, sizeof(size), 1, fp);
//corpus timestamps
size = corpus.timestamps.size();
fwrite(&size, sizeof(size), 1, fp);
if(size) fwrite(&corpus.timestamps[0], sizeof(corpus.timestamps[0]), size, fp);
fclose(fp);
mutex.UnlockRead();
}
void CoverageServer::RestoreState() {
mutex.LockWrite();
std::string out_file = DirJoin(out_dir, std::string("server_state.dat"));
FILE *fp = fopen(out_file.c_str(), "rb");
if (!fp) {
FATAL("Error reading server state");
}
fread(&num_samples, sizeof(num_samples), 1, fp);
fread(&server_timestamp, sizeof(server_timestamp), 1, fp);
ReadCoverageBinary(total_coverage, fp);
uint64_t size;
// read corpus
fread(&size, sizeof(size), 1, fp);
for (size_t i = 0; i < size; i++) {
Sample sample;
char fileindex[20];
sprintf(fileindex, "%05zu", i);
std::string sample_file = DirJoin(sample_dir, std::string("sample_") + fileindex);
sample.Load(sample_file.c_str());
corpus.samples.push_back(sample);
}
//corpus timestamps
fread(&size, sizeof(size), 1, fp);
corpus.timestamps.resize(size);
fread(&corpus.timestamps[0], sizeof(corpus.timestamps[0]), size, fp);
fclose(fp);
mutex.UnlockWrite();
}
int CoverageServer::HandleConnection(socket_type sock) {
int ret = 1;
char command;
if (!Read(sock, &command, 1)) {
return 0;
}
size_t cur_n_connections;
connection_mutex.Lock();
num_connections++;
cur_n_connections = num_connections;
connection_mutex.Unlock();
if (cur_n_connections > MAX_CONNECTIONS) {
// tell the client to wait and retry
send(sock, "W", 1, 0);
} else {
send(sock, "K", 1, 0);
if (command == 'X') {
ret = ReportCrash(sock);
} else if (command == 'S') {
ret = ReportNewCoverage(sock);
} else if (command == 'U') {
ret = ServeUpdates(sock);
} else {
ret = 0;
}
}
connection_mutex.Lock();
num_connections--;
connection_mutex.Unlock();
return ret;
}
void CoverageServer::StatusThread() {
int seconds_since_last_save = 0;
while (1) {
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
Sleep(10000);
#else
usleep(10000000);
#endif
seconds_since_last_save += 10;
printf("Num connections: %zu\n", num_connections);
printf("Num samples: %zu\n", num_samples);
printf("Num crashes: %zu (%zu unique)\n", num_crashes, num_unique_crashes);
printf("\n");
if (seconds_since_last_save > SERVER_SAVE_INERVAL) {
SaveState();
seconds_since_last_save = 0;
}
}
}
void *StartServerThread(void *arg) {
ClientSocket *client_info = (ClientSocket *)arg;
client_info->server->HandleConnection(client_info->client_socket);
closesocket(client_info->client_socket);
delete client_info;
return NULL;
}
void *StartStatusThread(void *arg) {
CoverageServer *server = (CoverageServer *)arg;
server->StatusThread();
return NULL;
}
void CoverageServer::Init(int argc, char **argv) {
char *option;
option = GetOption("-out", argc, argv);
if (!option) FATAL("No server output dir specified");
out_dir = option;
option = GetOption("-start_server", argc, argv);
if (!option) FATAL("No server output dir specified");
std::string host_port = option;
// extract server host and port
size_t delimiter = host_port.rfind(":");
if (delimiter == std::string::npos) {
// consider ip only, use the default port
server_ip = host_port;
} else {
server_ip = host_port.substr(0, delimiter);
server_port = atoi(host_port.c_str() + delimiter + 1);
}
SetupDirectories();
if (GetBinaryOption("-restore", argc, argv, false) ||
GetBinaryOption("-resume", argc, argv, false))
{
RestoreState();
}
}
void CoverageServer::SetupDirectories() {
//create output directories
CreateDirectory(out_dir);
crash_dir = DirJoin(out_dir, "server_crashes");
CreateDirectory(crash_dir);
sample_dir = DirJoin(out_dir, "server_samples");
CreateDirectory(sample_dir);
}
void CoverageServer::RunServer() {
num_connections = 0;
socket_type listen_socket, client_socket;
struct sockaddr_in serv_addr;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
FATAL("WSAStartup failed");
}
#endif
listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket == INVALID_SOCKET) {
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSACleanup();
#endif
FATAL("socket failed");
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
serv_addr.sin_port = htons(server_port);
if (bind(listen_socket, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
closesocket(listen_socket);
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSACleanup();
#endif
FATAL("bind failed");
}
if (listen(listen_socket, 10)) {
closesocket(listen_socket);
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSACleanup();
#endif
FATAL("listen failed");
}
CreateThread(StartStatusThread, this);
while (1)
{
client_socket = accept(listen_socket, NULL, NULL);
if (client_socket == INVALID_SOCKET) {
closesocket(listen_socket);
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSACleanup();
#endif
FATAL("accept failed");
}
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
DWORD timeout = 10000;
if (setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout))) {
#else
struct timeval tv;
tv.tv_sec = 10000; // 10 Secs Timeout
tv.tv_usec = 0;
if (setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(struct timeval))) {
#endif
closesocket(client_socket);
closesocket(listen_socket);
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSACleanup();
#endif
FATAL("setsockopt failed");
}
ClientSocket *client_info = new ClientSocket();
client_info->client_socket = client_socket;
client_info->server = this;
CreateThread(StartServerThread, client_info);
}
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
WSACleanup();
#endif
}