-
Notifications
You must be signed in to change notification settings - Fork 107
/
dispatcher.c
1800 lines (1636 loc) · 46.4 KB
/
dispatcher.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 2013-2024 Fabian Groffen
*
* 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.
*/
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "relay.h"
#include "router.h"
#include "server.h"
#include "collector.h"
#include "dispatcher.h"
#include "receptor.h"
#ifdef HAVE_GZIP
#include <zlib.h>
#endif
#ifdef HAVE_LZ4
#include <lz4.h>
#include <lz4frame.h>
#endif
#ifdef HAVE_SNAPPY
#include <snappy-c.h>
#endif
#ifdef HAVE_SSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif
#if defined(HAVE_DISPATCH_DISPATCH_H)
# include <dispatch/dispatch.h>
#elif defined(HAVE_SEMAPHORE_H)
# include <semaphore.h>
#else
# error "found no implementation for semaphores for your platform!"
#endif
enum conntype {
LISTENER,
CONNECTION
};
typedef struct _z_strm {
ssize_t (*strmread)(struct _z_strm *, void *, size_t); /* read func */
/* read from buffer only func, on error set errno to ENOMEM, EMSGSIZE or EBADMSG */
ssize_t (*strmreadbuf)(struct _z_strm *, void *, size_t, int, int);
int (*strmclose)(struct _z_strm *);
union {
#ifdef HAVE_GZIP
struct gz {
z_stream z;
int inflatemode;
} gz;
#endif
#ifdef HAVE_LZ4
struct lz4 {
LZ4F_decompressionContext_t lz;
size_t iloc; /* location for unprocessed input */
} lz4;
#endif
#ifdef HAVE_SSL
SSL *ssl;
#endif
int sock;
/* udp variant (in order to receive info about sender) */
struct udp_strm {
int sock;
struct sockaddr_in6 saddr;
char *srcaddr;
size_t srcaddrlen;
} udp;
} hdl;
#if defined(HAVE_GZIP) || defined(HAVE_LZ4) || defined(HAVE_SNAPPY)
char *ibuf;
size_t ipos;
size_t isize;
#endif
struct _z_strm *nextstrm;
} z_strm;
#define SOCKGROWSZ 32768
#define CONNGROWSZ 1024
#define MAX_LISTENERS 32 /* hopefully enough */
#define POLL_TIMEOUT 100
#define IDLE_DISCONNECT_TIME (10 * 60 * 1000 * 1000) /* 10 minutes */
/* connection takenby */
#define C_SETUP -2 /* being setup */
#define C_FREE -1 /* free */
#define C_IN 0 /* not taken */
/* > 0 taken by worker with id */
typedef struct _connection {
int sock;
z_strm *strm;
char takenby;
char srcaddr[24]; /* string representation of source address */
char buf[METRIC_BUFSIZ];
int buflen;
unsigned char needmore:1;
unsigned char noexpire:1;
unsigned char isaggr:1;
unsigned char isudp:1;
char datawaiting; /* full byte for atomic access */
char metric[METRIC_BUFSIZ];
destination dests[CONN_DESTS_SIZE];
size_t destlen;
struct timeval lastwork;
unsigned int maxsenddelay;
} connection;
struct _dispatcher {
pthread_t tid;
enum conntype type;
size_t metrics;
size_t blackholes;
size_t discards;
size_t ticks;
size_t sleeps;
size_t prevmetrics;
size_t prevblackholes;
size_t prevdiscards;
size_t prevticks;
size_t prevsleeps;
char id;
char keep_running; /* these all use a full byte for atomic access */
char route_refresh_pending;
char hold;
char tags_supported;
router *rtr;
router *pending_rtr;
char *allowed_chars;
int maxinplen;
int maxmetriclen;
};
static listener **listeners = NULL;
static connection *connections = NULL;
static size_t connectionslen = 0;
pthread_rwlock_t listenerslock = PTHREAD_RWLOCK_INITIALIZER;
pthread_rwlock_t connectionslock = PTHREAD_RWLOCK_INITIALIZER;
static size_t acceptedconnections = 0;
static size_t closedconnections = 0;
static unsigned int sockbufsize = 0;
/* connection specific readers and closers */
/* ordinary socket */
static inline ssize_t
sockread(z_strm *strm, void *buf, size_t sze)
{
return read(strm->hdl.sock, buf, sze);
}
static inline int
sockclose(z_strm *strm)
{
int ret = close(strm->hdl.sock);
free(strm);
return ret;
}
/* udp socket */
static inline ssize_t
udpsockread(z_strm *strm, void *buf, size_t sze)
{
ssize_t ret;
struct udp_strm *s = &strm->hdl.udp;
socklen_t slen = sizeof(s->saddr);
ret = recvfrom(s->sock, buf, sze, 0, (struct sockaddr *)&s->saddr, &slen);
if (ret <= 0)
return ret;
/* figure out who's calling */
s->srcaddr[0] = '\0';
switch (s->saddr.sin6_family) {
case PF_INET:
inet_ntop(s->saddr.sin6_family,
&((struct sockaddr_in *)&s->saddr)->sin_addr,
s->srcaddr, s->srcaddrlen);
break;
case PF_INET6:
inet_ntop(s->saddr.sin6_family, &s->saddr.sin6_addr,
s->srcaddr, s->srcaddrlen);
break;
}
return ret;
}
static inline int
udpsockclose(z_strm *strm)
{
int ret = close(strm->hdl.udp.sock);
free(strm);
return ret;
}
#ifdef HAVE_GZIP
/* gzip wrapped socket */
static inline ssize_t
gzipreadbuf(z_strm *strm, void *buf, size_t sze, int last_ret, int err);
static inline ssize_t
gzipread(z_strm *strm, void *buf, size_t sze)
{
z_stream *zstrm = &(strm->hdl.gz.z);
int ret;
if (zstrm->avail_in + 1 >= strm->isize) {
logerr("buffer overflow during read of gzip stream\n");
errno = EBADMSG;
return -1;
}
/* update ibuf */
if ((Bytef *)strm->ibuf != zstrm->next_in) {
memmove(strm->ibuf, zstrm->next_in, zstrm->avail_in);
zstrm->next_in = (Bytef *)strm->ibuf;
strm->ipos = zstrm->avail_in;
}
/* read any available data, if it fits */
ret = strm->nextstrm->strmread(strm->nextstrm,
strm->ibuf + strm->ipos,
strm->isize - strm->ipos);
if (ret > 0) {
zstrm->avail_in += ret;
strm->ipos += ret;
} else if (ret < 0) {
if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)
strm->hdl.gz.inflatemode = Z_FINISH;
} else {
/* ret == 0: EOF, which means we didn't read anything here, so
* calling inflate should be to flush whatever is in the zlib
* buffers, much like a read error.
* data in buffers may be exist, read with gzipreadbuf */
strm->hdl.gz.inflatemode = Z_FINISH;
return 0;
}
return gzipreadbuf(strm, buf, sze, ret, errno);
}
/* read data from buffer */
static inline ssize_t
gzipreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err)
{
z_stream *zstrm = &(strm->hdl.gz.z);
int iret;
zstrm->next_out = (Bytef *)buf;
zstrm->avail_out = (uInt)sze;
iret = inflate(zstrm, strm->hdl.gz.inflatemode);
switch (iret) {
case Z_OK: /* progress has been made */
/* calculate the "returned" bytes */
iret = sze - zstrm->avail_out;
break;
case Z_STREAM_END: /* everything uncompressed, nothing pending */
iret = sze - zstrm->avail_out;
break;
case Z_DATA_ERROR: /* corrupt input */
inflateSync(zstrm);
/* return isn't much of interest, we will call inflate next
* time and sync again if it still fails */
iret = -1;
break;
case Z_MEM_ERROR: /* out of memory */
logerr("out of memory during read of gzip stream\n");
errno = ENOMEM;
return -1;
break;
case Z_BUF_ERROR: /* output buffer full or nothing to read */
errno = EAGAIN;
break;
default:
iret = -1;
}
if (iret < 1) {
if (strm->ipos == strm->isize) {
logerr("buffer overflow during read of gzip stream\n");
errno = EBADMSG;
} else if (rval < 0)
errno = err ? err : EAGAIN;
}
return (ssize_t)iret;
}
static inline int
gzipclose(z_strm *strm)
{
int ret = strm->nextstrm->strmclose(strm->nextstrm);
inflateEnd(&(strm->hdl.gz.z));
free(strm->ibuf);
free(strm);
return ret;
}
#endif
#ifdef HAVE_LZ4
/* lz4 wrapped socket */
static inline ssize_t
lzreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err);
static inline ssize_t
lzreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err);
static inline ssize_t
lzread(z_strm *strm, void *buf, size_t sze)
{
int ret;
/* update ibuf */
if (strm->hdl.lz4.iloc > 0) {
memmove(strm->ibuf, strm->ibuf + strm->hdl.lz4.iloc, strm->ipos - strm->hdl.lz4.iloc);
strm->ipos -= strm->hdl.lz4.iloc;
strm->hdl.lz4.iloc = 0;
} else if (strm->ipos == strm->isize) {
logerr("buffer overflow during read of lz4 stream\n");
errno = EMSGSIZE;
return -1;
}
/* read any available data, if it fits */
ret = strm->nextstrm->strmread(strm->nextstrm,
strm->ibuf + strm->ipos, strm->isize - strm->ipos);
/* if EOF(0) or no-data(-1) then only get out now if the input
* buffer is empty because start of next frame may be waiting for us */
if (ret > 0) {
strm->ipos += ret;
} else if (ret < 0) {
if (strm->ipos == 0)
return -1;
} else {
/* ret == 0, a.k.a. EOF */
if (strm->ipos == 0)
return 0;
}
return lzreadbuf(strm, buf, sze, ret, errno);
}
static inline ssize_t
lzreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err)
{
/* attempt to decompress something from the (partial) frame that's
* arrived so far. srcsize is updated to the number of bytes
* consumed. likewise for destsize and bytes written */
size_t ret;
size_t srcsize;
size_t destsize;
srcsize = strm->ipos - strm->hdl.lz4.iloc;
if (srcsize == 0) /* input buffer decompressed */
return 0;
destsize = sze;
ret = LZ4F_decompress(strm->hdl.lz4.lz, buf, &destsize, strm->ibuf + strm->hdl.lz4.iloc, &srcsize, NULL);
/* check for error before doing anything else */
if (LZ4F_isError(ret)) {
/* need reset */
LZ4F_resetDecompressionContext(strm->hdl.lz4.lz);
/* liblz4 doesn't allow access to the error constants so have to
* return a generic code */
if (strm->hdl.lz4.iloc == 0 && strm->ipos == strm->isize) {
logerr("Error %s reading LZ4 compressed data, input buffer overflow\n", LZ4F_getErrorName(ret));
errno = EBADMSG;
} else if (rval == 0 ||
(rval == -1 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
logerr("Error %s reading LZ4 compressed data, lost %lu bytes in input buffer\n",
LZ4F_getErrorName(ret), strm->ipos - strm->hdl.lz4.iloc);
errno = EBADMSG;
} else
errno = err ? err : EAGAIN;
return -1;
}
strm->hdl.lz4.iloc += srcsize;
if (destsize == 0) {
tracef("No LZ4 data was produced\n");
errno = err ? err : EAGAIN;
return -1;
}
#ifdef ENABLE_TRACE
/* debug logging */
if (ret == 0)
tracef("LZ4 frame fully decoded\n");
#endif
return (ssize_t)destsize;
}
static inline int
lzclose(z_strm *strm)
{
int ret = strm->nextstrm->strmclose(strm->nextstrm);
LZ4F_freeDecompressionContext(strm->hdl.lz4.lz);
free(strm->ibuf);
free(strm);
return ret;
}
#endif
#ifdef HAVE_SNAPPY
/* snappy wrapped socket */
static inline ssize_t
snappyreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err);
static inline ssize_t
snappyreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err);
static inline ssize_t
snappyread(z_strm *strm, void *buf, size_t sze)
{
char *ibuf = strm->ibuf;
int ret;
size_t buflen = sze;
/* read any available data, if it fits */
ret = strm->nextstrm->strmread(strm->nextstrm,
ibuf + strm->ipos,
strm->isize - strm->ipos);
if (ret > 0) {
strm->ipos += ret;
} else if (ret < 0) {
return -1;
} else {
/* ret == 0, a.k.a. EOF */
return 0;
}
ret = snappy_uncompress(ibuf, strm->ipos, buf, &buflen);
/* if we decompressed something, update our ibuf */
if (ret == SNAPPY_OK) {
strm->ipos = strm->ipos - buflen;
memmove(ibuf, ibuf + buflen, strm->ipos);
} else if (ret == SNAPPY_BUFFER_TOO_SMALL) {
logerr("discarding snappy buffer: "
"the uncompressed block is too large\n");
strm->ipos = 0;
}
return (ssize_t)(ret == SNAPPY_OK ? buflen : -1);
}
static inline ssize_t
snappyreadbuf(z_strm *strm, void *buf, size_t sze, int rval, int err)
{
return 0;
}
static inline int
snappyclose(z_strm *strm)
{
int ret = strm->nextstrm->strmclose(strm->nextstrm);
free(strm->ibuf);
free(strm);
return ret;
}
#endif
#ifdef HAVE_SSL
/* (Open|Libre)SSL wrapped socket */
static inline ssize_t
sslread(z_strm *strm, void *buf, size_t sze)
{
return (ssize_t)SSL_read(strm->hdl.ssl, buf, (int)sze);
}
static inline int
sslclose(z_strm *strm)
{
int sock = SSL_get_fd(strm->hdl.ssl);
SSL_free(strm->hdl.ssl);
free(strm);
return close(sock);
}
#endif
/**
* Helper function to try and be helpful to the user. If errno
* indicates no new fds could be made, checks what the current max open
* files limit is, and if it's close to what we have in use now, write
* an informative message to stderr.
*/
void
dispatch_check_rlimit_and_warn(void)
{
if (errno == EISCONN || errno == EMFILE) {
struct rlimit ofiles;
/* rlimit can be changed for the running process (at least on
* Linux 2.6+) so refetch this value every time, should only
* occur on errors anyway */
if (getrlimit(RLIMIT_NOFILE, &ofiles) < 0)
ofiles.rlim_max = 0;
if (ofiles.rlim_max != RLIM_INFINITY && ofiles.rlim_max > 0)
logerr("process configured maximum connections = %d, "
"consider raising max open files/max descriptor limit\n",
(int)ofiles.rlim_max);
}
}
#define MAX_LISTENERS 32 /* hopefully enough */
/**
* Adds an (initial) listener socket to the chain of connections.
* Listener sockets are those which need to be accept()-ed on.
*/
int
dispatch_addlistener(listener *lsnr)
{
int c;
int *socks;
if (lsnr->ctype == CON_UDP) {
/* Adds a pseudo-listener for datagram (UDP) sockets, which is
* pseudo, for in fact it adds a new connection, but makes sure
* that connection won't be closed after being idle, and won't
* count that connection as an incoming connection either. */
for (socks = lsnr->socks; *socks != -1; socks++) {
c = dispatch_addconnection(*socks, lsnr);
if (c == -1)
return 1;
connections[c].noexpire = 1;
connections[c].isudp = 1;
acceptedconnections--;
}
return 0;
}
pthread_rwlock_wrlock(&listenerslock);
for (c = 0; c < MAX_LISTENERS; c++) {
if (listeners[c] == NULL) {
listeners[c] = lsnr;
for (socks = lsnr->socks; *socks != -1; socks++)
(void) fcntl(*socks, F_SETFL, O_NONBLOCK);
break;
}
}
if (c == MAX_LISTENERS) {
logerr("cannot add new listener: "
"no more free listener slots (max = %d)\n",
MAX_LISTENERS);
pthread_rwlock_unlock(&listenerslock);
return 1;
}
pthread_rwlock_unlock(&listenerslock);
return 0;
}
/**
* Remove listener from the listeners list. Each removal will incur a
* global lock. Frequent usage of this function is not anticipated.
*/
void
dispatch_removelistener(listener *lsnr)
{
int c;
if (lsnr->ctype != CON_UDP) {
pthread_rwlock_wrlock(&listenerslock);
/* find connection */
for (c = 0; c < MAX_LISTENERS; c++)
if (listeners[c] != NULL && listeners[c] == lsnr)
break;
if (c == MAX_LISTENERS) {
/* not found?!? */
logerr("dispatch: cannot find listener to remove!\n");
pthread_rwlock_unlock(&listenerslock);
return;
}
listeners[c] = NULL;
pthread_rwlock_unlock(&listenerslock);
}
/* acquire a write lock on connections, which is a bit wrong, but it
* ensures all dispatchers are stopped while we close the sockets,
* which avoids a race on the reading thereof if this is a UDP
* connection */
pthread_rwlock_wrlock(&connectionslock);
shutdownclose(lsnr);
pthread_rwlock_unlock(&connectionslock);
if (lsnr->saddrs) {
freeaddrinfo(lsnr->saddrs);
lsnr->saddrs = NULL;
}
}
/**
* Copy over all state related things from olsnr to nlsnr and ensure
* olsnr can be discarded (that is, thrown away without calling
* dispatch_removelistener).
*/
void
dispatch_transplantlistener(listener *olsnr, listener *nlsnr, router *r)
{
int c;
pthread_rwlock_wrlock(&listenerslock);
for (c = 0; c < MAX_LISTENERS; c++) {
if (listeners[c] == olsnr) {
router_transplant_listener_socks(r, olsnr, nlsnr);
#ifdef HAVE_SSL
if (nlsnr->transport & W_SSL)
nlsnr->ctx = olsnr->ctx;
#endif
if (olsnr->saddrs) {
freeaddrinfo(olsnr->saddrs);
olsnr->saddrs = NULL;
}
listeners[c] = nlsnr;
break; /* found and done */
}
}
pthread_rwlock_unlock(&listenerslock);
}
/**
* Adds a connection socket to the chain of connections.
* Connection sockets are those which need to be read from.
* Returns the connection id, or -1 if a failure occurred.
*/
int
dispatch_addconnection(int sock, listener *lsnr)
{
size_t c;
struct sockaddr_in6 saddr;
socklen_t saddr_len = sizeof(saddr);
#if defined(HAVE_GZIP) || defined(HAVE_LZ4) || defined(HAVE_SNAPPY)
int compress_type;
char *ibuf;
#endif
char checksize;
pthread_rwlock_rdlock(&connectionslock);
for (c = 0; c < connectionslen; c++)
if (__sync_bool_compare_and_swap(&(connections[c].takenby),
C_FREE, C_SETUP))
break;
checksize = c == connectionslen;
pthread_rwlock_unlock(&connectionslock);
if (checksize) {
connection *newlst;
size_t growlen;
pthread_rwlock_wrlock(&connectionslock);
if (connectionslen > c) {
/* another dispatcher just extended the list */
pthread_rwlock_unlock(&connectionslock);
return dispatch_addconnection(sock, lsnr);
}
/* take it slow with extending connections, because each
* connection struct is 65K, so use an exponential approach
* ceiled by CONNGROWSZ */
growlen = connectionslen * 5 / 10;
c = mode & MODE_SUBMISSION ? 2 : 10;
if (growlen < c)
growlen = c;
else if (growlen > CONNGROWSZ)
growlen = CONNGROWSZ;
newlst = realloc(connections,
sizeof(connection) * (connectionslen + growlen));
if (newlst == NULL) {
logerr("cannot add new connection: "
"out of memory allocating more slots (max = %zu)\n",
connectionslen);
pthread_rwlock_unlock(&connectionslock);
return -1;
} else if (newlst != connections) {
/* reset srcaddr after realloc due to issue 346 */
for (c = 0; c < connectionslen; c++) {
if (newlst[c].isudp) {
newlst[c].strm->hdl.udp.srcaddr = newlst[c].srcaddr;
newlst[c].strm->hdl.udp.srcaddrlen =
sizeof(newlst[c].srcaddr);
}
}
}
for (c = connectionslen; c < connectionslen + growlen; c++) {
memset(&newlst[c], '\0', sizeof(connection));
newlst[c].takenby = C_FREE;
}
connections = newlst;
c = connectionslen; /* for the setup code below */
newlst[c].takenby = C_SETUP;
connectionslen += growlen;
pthread_rwlock_unlock(&connectionslock);
}
/* figure out who's calling */
if (getpeername(sock, (struct sockaddr *)&saddr, &saddr_len) == 0) {
snprintf(connections[c].srcaddr, sizeof(connections[c].srcaddr),
"(unknown)");
switch (saddr.sin6_family) {
case PF_INET:
inet_ntop(saddr.sin6_family,
&((struct sockaddr_in *)&saddr)->sin_addr,
connections[c].srcaddr, sizeof(connections[c].srcaddr));
break;
case PF_INET6:
inet_ntop(saddr.sin6_family, &saddr.sin6_addr,
connections[c].srcaddr, sizeof(connections[c].srcaddr));
break;
}
}
(void) fcntl(sock, F_SETFL, O_NONBLOCK);
if (sockbufsize > 0) {
if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
&sockbufsize, sizeof(sockbufsize)) != 0)
;
}
connections[c].sock = sock;
connections[c].strm = malloc(sizeof(z_strm));
if (connections[c].strm == NULL) {
logerr("cannot add new connection: "
"out of memory allocating stream\n");
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
/* set socket or SSL connection */
connections[c].strm->nextstrm = NULL;
connections[c].strm->strmreadbuf = NULL;
if (lsnr == NULL || !(lsnr->transport & W_SSL)) {
if (lsnr == NULL || lsnr->ctype != CON_UDP) {
connections[c].strm->hdl.sock = sock;
connections[c].strm->strmread = &sockread;
connections[c].strm->strmclose = &sockclose;
} else {
connections[c].strm->hdl.udp.sock = sock;
connections[c].strm->hdl.udp.srcaddr =
connections[c].srcaddr;
connections[c].strm->hdl.udp.srcaddrlen =
sizeof(connections[c].srcaddr);
connections[c].strm->strmread = &udpsockread;
connections[c].strm->strmclose = &udpsockclose;
}
#ifdef HAVE_SSL
} else {
if ((connections[c].strm->hdl.ssl = SSL_new(lsnr->ctx)) == NULL) {
logerr("cannot add new connection: %s\n",
ERR_reason_error_string(ERR_get_error()));
free(connections[c].strm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
SSL_set_fd(connections[c].strm->hdl.ssl, sock);
SSL_set_accept_state(connections[c].strm->hdl.ssl);
if (lsnr->transport & W_MTLS) { /* issue #444 */
SSL_set_verify(connections[c].strm->hdl.ssl,
SSL_VERIFY_PEER |
SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
SSL_VERIFY_CLIENT_ONCE,
NULL);
}
connections[c].strm->strmread = &sslread;
connections[c].strm->strmclose = &sslclose;
#endif
}
#if defined(HAVE_GZIP) || defined(HAVE_LZ4) || defined(HAVE_SNAPPY)
if (lsnr == NULL)
compress_type = 0;
else
compress_type = lsnr->transport & 0xFFFF;
/* allocate input buffer */
if (
#ifdef HAVE_GZIP
compress_type == W_GZIP ||
#endif
#if HAVE_LZ4
compress_type == W_LZ4 ||
#endif
#ifdef HAVE_SNAPPY
compress_type == W_SNAPPY ||
#endif
0)
{
ibuf = malloc(METRIC_BUFSIZ);
if (ibuf == NULL) {
logerr("cannot add new connection: "
"out of memory allocating stream ibuf\n");
free(connections[c].strm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
} else
ibuf = NULL;
#endif
/* setup decompressor */
if (lsnr == NULL) {
/* do nothing, catch case only */
}
#ifdef HAVE_GZIP
else if (compress_type == W_GZIP) {
z_strm *zstrm = malloc(sizeof(z_strm));
if (zstrm == NULL) {
logerr("cannot add new connection: "
"out of memory allocating gzip stream\n");
free(ibuf);
free(connections[c].strm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
zstrm->ipos = 0;
zstrm->ibuf = ibuf;
zstrm->isize = METRIC_BUFSIZ;
memset(&zstrm->hdl.gz.z, 0, sizeof(zstrm->hdl.gz.z));
zstrm->hdl.gz.z.next_in = (Bytef *)zstrm->ibuf;
zstrm->hdl.gz.z.avail_in = 0;
zstrm->hdl.gz.z.zalloc = Z_NULL;
zstrm->hdl.gz.z.zfree = Z_NULL;
zstrm->hdl.gz.z.opaque = Z_NULL;
if (inflateInit2(&zstrm->hdl.gz.z, 15 + 16) != Z_OK)
{
logerr("cannot init gzip connection\n");
free(ibuf);
free(connections[c].strm);
free(zstrm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
zstrm->strmread = &gzipread;
zstrm->strmreadbuf = &gzipreadbuf;
zstrm->strmclose = &gzipclose;
zstrm->hdl.gz.inflatemode = Z_SYNC_FLUSH;
zstrm->nextstrm = connections[c].strm;
connections[c].strm = zstrm;
}
#endif
#ifdef HAVE_LZ4
else if (compress_type == W_LZ4) {
z_strm *lzstrm = malloc(sizeof(z_strm));
if (lzstrm == NULL) {
logerr("cannot add new connection: "
"out of memory allocating lz4 stream\n");
free(ibuf);
free(connections[c].strm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
if (LZ4F_isError(LZ4F_createDecompressionContext(
&lzstrm->hdl.lz4.lz, LZ4F_VERSION)))
{
logerr("Failed to create LZ4 decompression context\n");
free(ibuf);
free(connections[c].strm);
free(lzstrm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
lzstrm->ibuf = ibuf;
lzstrm->isize = METRIC_BUFSIZ;
lzstrm->ipos = 0;
lzstrm->hdl.lz4.iloc = 0;
lzstrm->strmread = &lzread;
lzstrm->strmreadbuf = &lzreadbuf;
lzstrm->strmclose = &lzclose;
lzstrm->nextstrm = connections[c].strm;
connections[c].strm = lzstrm;
}
#endif
#ifdef HAVE_SNAPPY
else if (compress_type == W_SNAPPY) {
z_strm *lzstrm = malloc(sizeof(z_strm));
if (lzstrm == NULL) {
logerr("cannot add new connection: "
"out of memory allocating snappy stream\n");
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
free(ibuf);
free(connections[c].strm);
__sync_bool_compare_and_swap(&(connections[c].takenby),
C_SETUP, C_FREE);
return -1;
}
lzstrm->ibuf = ibuf;
lzstrm->isize = METRIC_BUFSIZ;
lzstrm->ipos = 0;
lzstrm->strmread = &snappyread;
lzstrm->strmreadbuf = &snappyreadbuf;
lzstrm->strmclose = &snappyclose;
lzstrm->nextstrm = connections[c].strm;
connections[c].strm = lzstrm;
}
#endif
connections[c].buflen = 0;
connections[c].needmore = 0;
connections[c].noexpire = noexpire;
connections[c].isaggr = 0;
connections[c].isudp = 0;
connections[c].destlen = 0;
gettimeofday(&connections[c].lastwork, NULL);
connections[c].datawaiting = 0;
/* after this dispatchers will pick this connection up */
__sync_bool_compare_and_swap(&(connections[c].takenby), C_SETUP, C_IN);
__sync_add_and_fetch(&acceptedconnections, 1);
return c;
}
/**
* Adds a connection which we know is from an aggregator, so direct
* pipe. This is different from normal connections that we don't want
* to count them, never expire them, and want to recognise them when
* we're doing reloads.
*/
int
dispatch_addconnection_aggr(int sock)
{
int conn = dispatch_addconnection(sock, NULL);
if (conn == -1)
return 1;
connections[conn].noexpire = 1;
connections[conn].isaggr = 1;
acceptedconnections--;
return 0;
}
inline static char
dispatch_process_dests(connection *conn, dispatcher *self, struct timeval now)
{
int i;
char force;
if (conn->destlen > 0) {
if (conn->maxsenddelay == 0)
conn->maxsenddelay = ((rand() % 750) + 250) * 1000;
/* force when aggr (don't stall it) or after timeout */
force = conn->isaggr ? 1 :
timediff(conn->lastwork, now) > conn->maxsenddelay;
for (i = 0; i < conn->destlen; i++) {
tracef("dispatcher %d, connfd %d, metric %s, queueing to %s:%d\n",
self->id, conn->sock, conn->dests[i].metric,
server_ip(conn->dests[i].dest),
server_port(conn->dests[i].dest));
if (server_send(conn->dests[i].dest,