-
Notifications
You must be signed in to change notification settings - Fork 14
/
rmbtd.c
1820 lines (1532 loc) · 54.9 KB
/
rmbtd.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
/*******************************************************************************
* Copyright 2012-2014 alladin-IT GmbH
* Copyright 2014-2016 Thomas Schreiber
* Copyright 2017-2021 Rundfunk und Telekom Regulierungs-GmbH (RTR-GmbH)
*
* 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
*
* http://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 _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <regex.h>
#include <fcntl.h>
#include <signal.h>
#include <syslog.h>
#include <pwd.h>
#include <grp.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <time.h>
#include <pthread.h>
//#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
//#include <netdb.h>
#include <poll.h>
#include <arpa/inet.h>
#include "cwebsocket/websocket.h"
#include "config.h"
#define HAVE_SSL /* currently necessary! */
#ifdef HAVE_SSL
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#if !defined(OPENSSL_THREADS)
#error no thread support in openssl
#endif
#include <openssl/bio.h> // BIO objects for I/O
#include <openssl/crypto.h>
#include <openssl/ssl.h> // SSL and SSL_CTX for SSL connections
#include <openssl/err.h> // Error reporting
#include <openssl/hmac.h>
static pthread_mutex_t *lockarray;
SSL_CTX *ssl_ctx;
#define MY_SOCK BIO*
#define my_organic_write BIO_write
#define my_organic_read BIO_read
#else
#define MY_SOCK int
#define my_organic_write write
#define my_organic_read read
#endif
#define NEWLINE '\n'
#define CONNECTION_UPGRADE "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: RMBT\r\n\r\n"
#define GETTIME "GETTIME"
#define GETCHUNKS "GETCHUNKS"
#define PUT "PUT"
#define PUTNORESULT "PUTNORESULT"
#define PING "PING"
#define PONG_NL "PONG\n"
#define OK "OK"
#define OK_NL "OK\n"
#define ACCEPT_TOKEN_NL "ACCEPT TOKEN QUIT\n"
#define ACCEPT_GET_PUT_PING_NL "ACCEPT GETCHUNKS GETTIME PUT PUTNORESULT PING QUIT\n"
#define ERR_NL "ERR\n"
#define QUIT "QUIT"
#define BYE_NL "BYE\n"
#define MAX_SECRET_KEYS 128
#define MAX_SECRET_KEY_LINE_LENGTH 256
volatile int accept_queue[ACCEPT_QUEUE_MAX_SIZE];
volatile int accept_queue_listen_idx[ACCEPT_QUEUE_MAX_SIZE];
volatile int accept_queue_size, accept_queue_start = 0;
pthread_mutex_t accept_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t accept_queue_not_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t accept_queue_not_full = PTHREAD_COND_INITIALIZER;
volatile int do_shutdown = 0;
struct listen
{
struct sockaddr_in6 sockaddr;
int use_ssl;
int sock;
} *listens;
int num_listens;
struct thread_info
{
pthread_t thread_id;
int thread_num;
} *thread_infos;
// char *pidfile = NULL;
int num_threads = DEFAULT_NUM_THREADS;
char *total_random;
char secret_keys[MAX_SECRET_KEYS][MAX_SECRET_KEY_LINE_LENGTH];
char secret_keys_labels[MAX_SECRET_KEYS][MAX_SECRET_KEY_LINE_LENGTH];
int secret_keys_count=-1;
long random_size;
long page_size;
char use_http = 0;
int behave_as_version = 0; //MAYOR*1000 + MINOR
void print_help()
{
printf("==== rmbtd ====\n"
"command line arguments:\n\n"
" -l/-L listen on (IP and) port; -L for SSL;\n"
" examples: \"443\",\"1.2.3.4:1234\",\"[2001:1234::567A]:1234\"\n"
" maybe specified multiple times; at least once\n\n"
" -c path to SSL certificate in PEM format;\n"
" intermediate certificates following server cert in same file if needed\n"
" required\n\n"
" -k path to SSL key file in PEM format; required\n\n"
" -t number of worker threads to run for handling connections (default: %d)\n\n"
" -u drop root privileges and setuid to specified user; must be root\n\n"
" -d fork into background as daemon (no argument)\n\n"
" -D enable debug logging (no argument)\n\n"
" -w use as websocket server (no argument)\n\n"
" -v behave as version (v) for serving very old clients\n"
" example: \"0.3\"\n\n"
"Required are -c,-k and at least one -l/-L option\n",
DEFAULT_NUM_THREADS);
}
void syslog_and_print(int priority, const char *format, ...)
{
va_list args;
va_start(args,format);
size_t len = strlen(format);
char format_nl[len + 2];
memcpy(format_nl, format, len);
vfprintf(stderr, format_nl, args);
vsyslog(priority, format_nl, args);
va_end(args);
}
ssize_t my_write(MY_SOCK fd, const void *buf, size_t count, char use_websocket) {
if (use_websocket) {
char buffer[count + 14];
size_t out_len = count;
if (count < 2 || count > (CHUNK_SIZE-3)) {
wsMakeFrame((const uint8_t*) buf, count, (uint8_t*) buffer, &out_len, WS_BINARY_FRAME);
}
else {
wsMakeFrame((const uint8_t*) buf, count, (uint8_t*) buffer, &out_len, WS_TEXT_FRAME);
}
my_organic_write(fd,buffer,out_len); //@TODO: return real len of unmasked/unframed output
/**
* Activate if the amount of written bytes needs to be ever taken into account
* This is deactivated for now since openssl seems to handle that nicely by itself
*//*
ssize_t remaining = out_len;
do {
syslog(LOG_INFO, "remaining %d, arry: %p, starting position: %p", (int)remaining, (char*)buffer, &buffer[out_len - remaining]);
ssize_t cnt = my_organic_write(fd, &buffer[out_len - remaining], remaining); //@TODO: return real len of unmasked/unframed output
remaining -= cnt;
//break on error, signal error
if (cnt <= 0) {
long err = ERR_get_error();
syslog(LOG_INFO, "error: %ld %s - ",err,ERR_error_string(errno,NULL));
syslog(LOG_INFO, "error: %d %s\n",errno,strerror(errno));
break;
}
} while (remaining > 0);*/
return count;
}
else
{
return my_organic_write(fd,buf,count);
}
}
ssize_t my_read(MY_SOCK b, void *buf, size_t count, char use_websocket) {
if (use_websocket) {
//temporary buffer with enough space for the Frame
uint8_t tmpBuf[count+100];
uint8_t* data = buf;
char finFlagSet = 0;
ssize_t totalRead = 0;
//receive websocket frames, including continuation frames,
//reassemble these continuation frames
do {
ssize_t len = my_organic_read(b, tmpBuf, 14);
size_t in_len = 0;
if (len <= 0) {
return len;
}
enum wsFrameType t;
size_t payloadLength;
uint8_t payloadFieldExtraBytes;
payloadLength = getPayloadLength(tmpBuf, len, &payloadFieldExtraBytes, &t);
//read did not yet get the full tcp package
// -> read again until we got the full websocket frame
int remaining = (payloadLength + 6 + payloadFieldExtraBytes) - len;
//prevent possible buffer overflows
if (remaining > count) {
return 0;
}
//printf("payload length: %d, got %d, remaining: %d\n",(int) payloadLength, (int) len, remaining);
while (payloadLength != 0 && remaining > 0) {
int newLen = my_organic_read(b, &tmpBuf[len], remaining);
if (newLen == 0) {
break;
}
else if (newLen < 0) {
long err = ERR_get_error();
syslog(LOG_ERR, "error: %ld %s - ", err, ERR_error_string(errno, NULL));
syslog(LOG_ERR, "error: %d %s\n", errno, strerror(errno));
break;
}
remaining -= newLen;
len += newLen;
}
t = wsParseInputFrame((uint8_t *) tmpBuf, len, &data, &in_len);
//special frames: Closing frames
if (t == WS_CLOSING_FRAME ||
t == WS_ERROR_FRAME) {
return 0;
//close connection
}
finFlagSet = (tmpBuf[0] & 0x80) == 0x80;
//prevent buffer overflow
if ((totalRead + in_len) > count) {
syslog(LOG_DEBUG, "preventing possible buffer overflow with continuation frame %lu %ld %ld %d", totalRead, in_len, count, finFlagSet);
totalRead += in_len;
continue;
}
//move the gathered data to the buffer at the current position
memmove(buf + totalRead, data, in_len);
totalRead += in_len;
//syslog(LOG_INFO, "is finished: %d ; total read: %d (%d)", (int)isFinished, (int)in_len, tmpBuf[0]);
} while (!finFlagSet); //break, if a websocket frame has the FIN-flag set
//@TODO: Error frames
return totalRead;
}
else {
return my_organic_read(b,buf,count);
}
}
int my_readline(MY_SOCK sock, const char *buf, int size, char use_websocket)
{
const char *buf_ptr = buf;
int size_remain = size;
int r;
char *nl_ptr = NULL;
do
{
r = my_read(sock, (void*)buf_ptr, size_remain, use_websocket);
if (r > 0)
{
nl_ptr = memchr(buf_ptr, NEWLINE, r);
buf_ptr += r;
size_remain -= r;
}
}
while (r > 0 && nl_ptr == NULL && size_remain > 0);
if (size_remain <= 0)
return -1;
if (nl_ptr != NULL)
*nl_ptr = '\0';
return buf_ptr - buf;
}
void fill_ts(struct timespec *time_result)
{
int rc;
rc = clock_gettime(CLOCK_MONOTONIC, time_result);
if (rc == -1)
{
syslog(LOG_ERR, "error during clock_gettime: %m");
exit(EXIT_FAILURE);
}
}
long long ts_diff(struct timespec *start)
{
struct timespec end;
fill_ts(&end);
if ((end.tv_nsec-start->tv_nsec)<0)
{
start->tv_sec = end.tv_sec-start->tv_sec-1;
start->tv_nsec = 1000000000ull + end.tv_nsec-start->tv_nsec;
}
else
{
start->tv_sec = end.tv_sec-start->tv_sec;
start->tv_nsec = end.tv_nsec-start->tv_nsec;
}
return start->tv_nsec + (long long)start->tv_sec * 1000000000ull;
}
long long ts_diff_preserve(struct timespec *start)
{
struct timespec end;
fill_ts(&end);
if ((end.tv_nsec-start->tv_nsec)<0)
{
end.tv_sec = end.tv_sec-start->tv_sec-1;
end.tv_nsec = 1000000000ull + end.tv_nsec-start->tv_nsec;
}
else
{
end.tv_sec = end.tv_sec-start->tv_sec;
end.tv_nsec = end.tv_nsec-start->tv_nsec;
}
return end.tv_nsec + (long long)end.tv_sec * 1000000000ull;
}
void do_bind()
{
int true = 1;
int i;
for (i = 0; i < num_listens; i++)
{
if ((listens[i].sock = socket(AF_INET6, SOCK_STREAM, 0)) == -1)
{
syslog(LOG_ERR, "error during socket: %m");
exit(EXIT_FAILURE);
}
if (setsockopt(listens[i].sock, SOL_SOCKET, SO_REUSEADDR, &true, sizeof (int)) == -1)
{
syslog(LOG_ERR, "error during setsockopt SO_REUSEADDR: %m");
exit(EXIT_FAILURE);
}
if (setsockopt(listens[i].sock, IPPROTO_TCP, TCP_NODELAY , &true, sizeof (int)) == -1)
{
syslog(LOG_ERR, "error during setsockopt NODELAY: %m");
exit(EXIT_FAILURE);
}
/* set recieve timeout */
struct timeval timeout;
timeout.tv_sec = TIMEOUT;
timeout.tv_usec = 0;
if (setsockopt(listens[i].sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout)) == -1)
{
syslog(LOG_ERR, "error during setsockopt SO_RCVTIMEO: %m");
exit(EXIT_FAILURE);
}
/* set send timeout */
if (setsockopt(listens[i].sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof (timeout)) == -1)
{
syslog(LOG_ERR, "error during setsockopt SO_SNDTIMEO: %m");
exit(EXIT_FAILURE);
}
/*
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &true, sizeof (int)) == -1)
{
syslog(LOG_ERR, "error during setsockopt TCP_NODELAY: %m");
exit(1);
}
*/
char ip[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &listens[i].sockaddr.sin6_addr, ip, sizeof(ip));
if (bind(listens[i].sock, (const struct sockaddr *) &listens[i].sockaddr, sizeof(*listens)) == -1)
{
syslog(LOG_ERR, "error while binding on [%s]:%d: %m", ip, ntohs(listens[i].sockaddr.sin6_port));
exit(EXIT_FAILURE);
}
if (listen(listens[i].sock,LISTEN_BACKLOG) == -1)
{
syslog(LOG_ERR, "error during listen: %m");
exit(EXIT_FAILURE);
}
syslog(LOG_INFO, "listening on [%s]:%d (%s)", ip, ntohs(listens[i].sockaddr.sin6_port), listens[i].use_ssl ? "SSL" : "no ssl");
}
}
void unbind()
{
syslog(LOG_DEBUG, "closing sockets");
int i;
for (i = 0; i < num_listens; i++)
{
close(listens[i].sock);
}
}
void accept_loop()
{
struct pollfd poll_array[num_listens];
int i;
for (i = 0; i < num_listens; i++)
{
poll_array[i].fd = listens[i].sock;
poll_array[i].events = POLLIN;
}
syslog(LOG_INFO, "ready for connections");
/* accept loop */
while (! do_shutdown)
{
/* poll */
int r = poll(poll_array, num_listens, -1);
if (r == -1)
{
if (errno != EINTR)
syslog(LOG_ERR, "error during poll: %m");
continue;
}
for (i = 0; i < num_listens; i++)
{
if ((poll_array[i].revents & POLLIN) != 0)
{
/* accept */
int socket_descriptor = accept(listens[i].sock, NULL, NULL);
/* if valid socket descriptor */
if (socket_descriptor >= 0)
{
/* lock */
pthread_mutex_lock(&accept_queue_mutex);
/* wait until queue not full anymore */
while (! do_shutdown && accept_queue_size == ACCEPT_QUEUE_MAX_SIZE)
pthread_cond_wait(&accept_queue_not_full, &accept_queue_mutex);
if (do_shutdown)
return;
/* add socket descriptor to queue */
int idx = (accept_queue_start + accept_queue_size++) % ACCEPT_QUEUE_MAX_SIZE;
accept_queue[idx] = socket_descriptor;
accept_queue_listen_idx[idx] = i;
/* if queue was empty, signal a thread to start looking for the socket descriptor */
if (accept_queue_size > 0)
pthread_cond_signal(&accept_queue_not_empty);
/* unlock */
pthread_mutex_unlock(&accept_queue_mutex);
}
}
}
}
}
const char *base64(const char *input, int ilen, char *output, int *olen)
{
BIO *bmem, *b64;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, ilen);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
if (bptr->length > *olen)
{
BIO_free_all(b64);
return NULL;
}
else
{
memcpy((void *)output, bptr->data, bptr->length);
output[bptr->length - 1]='\0';
*olen = bptr->length;
BIO_free_all(b64);
return output;
}
}
int check_token_validity_using_key(int thread_num, const char *uuid, const char *start_time_str, const char *hmac, const int key_index)
{
unsigned char md_buf[EVP_MAX_MD_SIZE];
unsigned int md_size = sizeof(md_buf);
const char *key = secret_keys[key_index];
const char *key_label = secret_keys_labels[key_index];
unsigned char msg[128];
int r;
r = snprintf((char *)msg, sizeof(msg), "%s_%s", uuid, start_time_str);
if (r < 0)
return 0;
char base64_buf[64*2];
int base64_buf_size = sizeof(base64_buf);
unsigned char *md = HMAC(EVP_sha1(), key, strlen(key), msg, strnlen((char*)msg, sizeof(msg)), md_buf, &md_size);
if (md == NULL)
return -1;
base64((char*)md, md_size, base64_buf, &base64_buf_size);
int result = strncmp(base64_buf, hmac, base64_buf_size);
if (result == 0)
{
syslog(LOG_INFO, "[THR %d] Token was accepted by key %s", thread_num, key_label);
}
return result;
}
int check_token(int thread_num, const char *uuid, const char *start_time_str, const char *hmac)
{
int result = -1;
int i=0;
for (i=0;i<secret_keys_count;i++) {
int check = check_token_validity_using_key(thread_num, uuid, start_time_str, hmac, i);
if (check == 0) {
result = 0;
break;
}
}
if (result != 0)
{
syslog(LOG_ERR, "[THR %d] got illegal token: \"%s\"", thread_num, uuid);
}
else
{
/* check if client is allowed yet */
time_t now = time(NULL);
long int start_time = atoi(start_time_str);
// printf("now: %ld; start_time: %ld; MAX_ACCEPT_EARLY: %d, MAX_ACCEPT_LATE: %d\n", now, start_time, MAX_ACCEPT_EARLY, MAX_ACCEPT_LATE);
if (start_time - MAX_ACCEPT_EARLY > now || start_time + MAX_ACCEPT_LATE < now)
{
if (start_time - MAX_ACCEPT_EARLY > now)
syslog(LOG_ERR, "[THR %d] client is not allowed yet. %ld seconds to early", thread_num, start_time - now);
else
syslog(LOG_ERR, "[THR %d] client is %ld seconds too late", thread_num, now - start_time);
result = -1;
}
/* accept if a little bit too early, but let him wait */
if (result == 0 && start_time > now)
{
syslog(LOG_DEBUG, "[THR %d] client is %ld seconds too early. Let him wait", thread_num, start_time - now);
struct timespec sleep;
sleep.tv_sec = start_time - now;
sleep.tv_nsec = 0;
nanosleep(&sleep, NULL);
}
}
return result;
}
/*
void print_milsecs(unsigned long nsecs)
{
double milsecs = (double)nsecs/1e6;
//printf("time: %.6f milsec\n",milsecs);
}
void print_speed(unsigned long nsecs, unsigned long data_size)
{
double secs = (double)nsecs/1e9;
//printf("time: %.9f secs\n",secs);
//printf("MBit: %.4f\n",(double)data_size/secs*8.0/1e6);
}
*/
void write_err(MY_SOCK sock, char use_websocket)
{
my_write(sock, ERR_NL, sizeof(ERR_NL)-1, use_websocket);
//printf("sending ERR\n");
}
/**
* Change the buffers for storing chunks to the given chunk size
* @param new_chunk_size new chunk size the buffers should be resized to
* @param chunk_buffer_pointer pointer to the buffer pointer which can be NULL
* @param size_of_buffer reference to variable where to size of the buffer should be stored
* @return 0 in case of errors, the new chunk size otherwise
*/
uint32_t change_chunk_size(uint32_t new_chunk_size, char** chunk_buffer_pointer, uint32_t* size_of_buffer) {
//check if the chunk size is inside the set limitations
if (new_chunk_size <= 0 || new_chunk_size > MAX_CHUNK_SIZE || new_chunk_size < MIN_CHUNK_SIZE) {
//err
return 0;
}
//set new chunk size
*size_of_buffer = (new_chunk_size * sizeof (char));
char* chunk_buffer = *chunk_buffer_pointer;
char* tmp;
//try to reallocate the desired memory, fail if this is not possible
tmp = realloc(chunk_buffer, *size_of_buffer);
if (tmp != NULL) {
chunk_buffer = tmp;
}
else {
return 0;
}
//update the pointer to the new buffer location
*chunk_buffer_pointer = chunk_buffer;
return new_chunk_size;
}
/**
* See change_chunk_size
* @param size new size of the buffer, given as a String
*/
uint32_t parse_and_change_chunk_size(char* size, char** chunk_buffer_pointer, uint32_t* size_of_buffer) {
//get size from string, up to 9 chars (=1 GiB)
uint32_t new_chunk_size;
int r = sscanf((char*) size, "%9lu", (long unsigned int *) &new_chunk_size);
if (r > 0) {
return change_chunk_size(new_chunk_size, chunk_buffer_pointer, size_of_buffer);
}
else {
return 0;
}
}
/**
* Handle a single client connection
* @param thread_num number of the thread, only used for debug outputs
* @param sock socket to be used
* @param chunk_buffer_pointer pointer to the buffer pointer to be used and updated
*/
void handle_connection(int thread_num, MY_SOCK sock, char** chunk_buffer_pointer)
{
char use_websocket = 0;
/************************/
//buffers for parsing of the lines
char buf1[MAX_LINE_LENGTH];
char buf2[MAX_LINE_LENGTH];
char buf3[MAX_LINE_LENGTH];
char buf4[MAX_LINE_LENGTH];
//chunk buffer variables
char* chunk_buffer = NULL;
uint32_t chunk_size = -1;
uint32_t size_of_buffer = -1;
//initialize chunk buffer with default chunk size
chunk_size = change_chunk_size(CHUNK_SIZE, chunk_buffer_pointer, &size_of_buffer);
chunk_buffer = *chunk_buffer_pointer;
if (chunk_size <= 0) {
return;
}
int r, s;
if (use_http) {
int get;
r = my_organic_read(sock, buf1, MAX_LINE_LENGTH);
if (r <= 0) {
syslog(LOG_INFO, "initialization error: connection reset rmbtws: %d %d", r, (int) ERR_get_error());
ERR_print_errors_fp(stdout);
return;
}
//websocket handshake?
get = strncmp((char*) buf1, "GET ", 4);
if (get == 0) {
//use two different regular expressions, since handling with groups in C can be avoided
regex_t regex_ws, regex_rmbt;
int reti_ws, reti_rmbt;
/* Compile regular expression */
reti_ws = regcomp(®ex_ws, "^upgrade: websocket", REG_ICASE | REG_NEWLINE);
reti_rmbt = regcomp(®ex_rmbt, "^upgrade: rmbt", REG_ICASE | REG_NEWLINE);
if (reti_ws || reti_rmbt) {
syslog(LOG_ERR, "Could not compile regex\n");
return;
}
/* Execute regular expression */
reti_ws = regexec(®ex_ws, buf1, 0, NULL, 0);
reti_rmbt = regexec(®ex_rmbt, buf1, 0, NULL, 0);
regfree(®ex_ws); //free memory
regfree(®ex_rmbt);
if (reti_ws == REG_NOMATCH && reti_rmbt == REG_NOMATCH) { //No match -> No websocket
syslog(LOG_INFO, "[THR %d] No HTTP upgrade to websocket/rmbt", thread_num);
my_write(sock, GREETING, sizeof(GREETING)-1, use_websocket);
return;
} else if (reti_rmbt == 0) { //Match -> Websocket
syslog(LOG_DEBUG, "[THR %d] Upgrade to rmbt", thread_num);
//Send HTTP Upgrade command
my_write(sock, CONNECTION_UPGRADE, sizeof(CONNECTION_UPGRADE), use_websocket);
use_websocket=0;
} else if (reti_ws == 0) {
syslog(LOG_DEBUG, "[THR %d] Upgrade to websocket", thread_num);
struct handshake hs;
nullHandshake(&hs);
//try to parse handshake
enum wsFrameType handshake = wsParseHandshake((const uint8_t *) buf1, r, &hs);
if (handshake != WS_OPENING_FRAME) {
syslog(LOG_INFO, "[THR %d] invalid websocket handshake", thread_num);
return;
}
//generate and send the handshake response
size_t framesize = CHUNK_SIZE;
wsGetHandshakeAnswer(&hs, (uint8_t *) buf1, &framesize);
//syslog(LOG_INFO, "init Websocket handshake3 %d >> %s <<", (int) framesize, buf1);
//server response
my_organic_write(sock, buf1, framesize);
//syslog(LOG_INFO, "send answer");
use_websocket = 1;
} else {
syslog(LOG_INFO, "[THR %d] initialization error: upgrade-regex could not be evaluated: %d %d", thread_num, r, (int) ERR_get_error());
return;
}
}
else {
syslog(LOG_INFO, "[THR %d] initialization error: connection reset rmbt: %d %d", thread_num, r, (int) ERR_get_error());
return;
}
}
if (behave_as_version == 3)
my_write(sock, "RMBTv0.3\n", sizeof("RMBTv0.3\n")-1, use_websocket);
else
my_write(sock, GREETING, sizeof(GREETING)-1, use_websocket);
my_write(sock, ACCEPT_TOKEN_NL, sizeof(ACCEPT_TOKEN_NL)-1, use_websocket);
r = my_readline(sock, buf1, MAX_LINE_LENGTH, use_websocket);
if (r <= 0) {
if (use_websocket) {
syslog(LOG_INFO, "[THR %d] initialization error: client closed connection after handshake: %d %d",
thread_num, r, (int) ERR_get_error());
} else {
syslog(LOG_INFO, "[THR %d] initialization error: client closed connection after greeting: %d %d",
thread_num, r, (int) ERR_get_error());
}
ERR_print_errors_fp(stdout);
return;
}
r = sscanf((char*)buf1, "TOKEN %36[0-9a-f-]_%12[0-9]_%50[a-zA-Z0-9+/=]", buf2, buf3, buf4);
if (r != 3)
{
syslog(LOG_ERR, "[THR %d] syntax error on token: \"%s\"", thread_num, buf1);
return;
}
if (CHECK_TOKEN)
{
if (check_token(thread_num, buf2, buf3, buf4))
{
syslog(LOG_ERR, "[THR %d] token was not accepted", thread_num);
return;
}
syslog(LOG_INFO, "[THR %d] valid token; uuid: %s", thread_num, buf2);
}
else
syslog(LOG_INFO, "[THR %d] token NOT CHECKED; uuid: %s", thread_num, buf2);
my_write(sock, OK_NL, sizeof(OK_NL)-1, use_websocket);
//Send min and max chunksize
if (behave_as_version == 3)
r = snprintf(buf1, sizeof(buf1), "CHUNKSIZE %d\n", CHUNK_SIZE);
else
r = snprintf(buf1, sizeof(buf1), "CHUNKSIZE %d %d %d\n", CHUNK_SIZE, MIN_CHUNK_SIZE, MAX_CHUNK_SIZE);
if (r <= 0) return;
s = my_write(sock, buf1, r, use_websocket);
if (r != s) return;
for (;;)
{
my_write(sock, ACCEPT_GET_PUT_PING_NL, sizeof(ACCEPT_GET_PUT_PING_NL)-1, use_websocket);
int r = my_readline(sock, buf1, sizeof(buf1), use_websocket);
if (r <= 0)
return;
int parts = sscanf((char*)buf1, "%50s %12s %12s[^\n]", buf2, buf3, buf4);
/***** GETTIME *****/
if ((parts == 2 || parts == 3) && strncmp((char*)buf2, GETTIME, sizeof(GETTIME)) == 0)
{
//update chunk size
if (parts == 3) {
chunk_size = parse_and_change_chunk_size(buf4, chunk_buffer_pointer, &size_of_buffer);
if (chunk_size <= 0) {
return;
}
chunk_buffer = *chunk_buffer_pointer;
}
int seconds;
r = sscanf((char*)buf3, "%12d", &seconds);
if (r != 1 || seconds <=0 || seconds > MAX_SECONDS)
write_err(sock, use_websocket);
else
{
long long maxnsec = (long long)seconds * 1000000000ull;
/* start time measurement */
struct timespec timestamp;
fill_ts(×tamp);
/* TODO: start at random place? */
char *random_ptr = total_random;
//unsigned char null = 0x00;
//unsigned char ff = 0xff;
long long diffnsec;
unsigned long total_bytes = 0;
//char debugrandom[chunk];
//memset(debugrandom, 0, sizeof(debugrandom));
do
{
if (random_ptr + chunk_size >= (total_random + random_size))
random_ptr = total_random;
memcpy(chunk_buffer, random_ptr, chunk_size);
diffnsec = ts_diff_preserve(×tamp);
if (diffnsec >= maxnsec)
chunk_buffer[chunk_size - 1] = 0xff; // signal last package
else
chunk_buffer[chunk_size - 1] = 0x00;
r = my_write(sock, chunk_buffer, chunk_size, use_websocket);
total_bytes += r;
random_ptr += chunk_size;
}
while (diffnsec < maxnsec && r > 0);
//printf("TIME reached, %lu bytes sent.\n", total_bytes);
if (r <= 0)
write_err(sock, use_websocket);
else
{
int r = my_readline(sock, buf1, sizeof(buf1), use_websocket);
if (r <= 0)
return;
/* end time measurement */
long long nsecs_total = ts_diff(×tamp);
if (strncmp((char*)buf1, OK, sizeof(OK)) == 0)
{
//print_speed(nsecs_total, total_bytes);
r = snprintf((char*)buf3, sizeof(buf3), "TIME %lld\n", nsecs_total);
if (r <= 0) return;
s = my_write(sock, buf3, r, use_websocket);
if (r != s) return;
}
else
write_err(sock, use_websocket);
}
}
}
/***** GETCHUNKS *****/
else if ((parts == 2 || parts == 3) && strncmp((char*)buf2, GETCHUNKS, sizeof(GETCHUNKS)) == 0)
{
//update chunk size
if (parts == 3) {
chunk_size = parse_and_change_chunk_size(buf4, chunk_buffer_pointer, &size_of_buffer);
if (chunk_size <= 0) {
return;
}
chunk_buffer = *chunk_buffer_pointer;
}
int chunks;
r = sscanf((char*)buf3, "%12d", &chunks);
if (r != 1 || chunks <=0 || chunks > MAX_CHUNKS)
write_err(sock, use_websocket);
else
{
/* start time measurement */
struct timespec timestamp;
fill_ts(×tamp);
/* TODO: start at random place? */
char *random_ptr = total_random;
unsigned long total_bytes = 0;
int chunks_sent = 0;
//char debugrandom[chunk];
//memset(debugrandom, 0, sizeof(debugrandom));
do
{
if (random_ptr + chunk_size >= (total_random + random_size))
random_ptr = total_random;
memcpy(chunk_buffer, random_ptr, chunk_size);
if (++chunks_sent >= chunks) {
(chunk_buffer)[chunk_size - 1] = 0xff; // signal last package
}
else {
(chunk_buffer)[chunk_size - 1] = 0x00;
}
r = my_write(sock, chunk_buffer, chunk_size, use_websocket);
total_bytes += r;
random_ptr += chunk_size;
}
while (chunks_sent < chunks && r > 0);
if (r <= 0 || s <= 0)
write_err(sock, use_websocket);
else
{
int r = my_readline(sock, buf1, size_of_buffer, use_websocket);
if (r <= 0)
return;
/* end time measurement */
long long nsecs_total = ts_diff(×tamp);
if (strncmp((char*)buf1, OK, sizeof(OK)) == 0)
{
//print_speed(nsecs_total, total_bytes);
r = snprintf((char*)buf3, sizeof(buf3), "TIME %lld\n", nsecs_total);
if (r <= 0) return;
s = my_write(sock, buf3, r, use_websocket);
if (r != s) return;