-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathconnection.c
2113 lines (1868 loc) · 61.9 KB
/
connection.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
/* Icecast
*
* This program is distributed under the GNU General Public License, version 2.
* A copy of this license is included with this source.
*
* Copyright 2010-2022, Karl Heyes <[email protected]>
* Copyright 2000-2004, Jack Moffitt <[email protected]>,
* Michael Smith <[email protected]>,
* oddsock <[email protected]>,
* Karl Heyes <[email protected]>
* and others (see AUTHORS for details).
*/
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <fnmatch.h>
#ifdef _MSC_VER
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_SIGNALFD
#include <sys/signalfd.h>
#include <signal.h>
#endif
#include "compat.h"
#include "thread/thread.h"
#include "avl/avl.h"
#include "net/sock.h"
#include "httpp/httpp.h"
#include "timing/timing.h"
#include "cfgfile.h"
#include "global.h"
#include "util.h"
#include "connection.h"
#include "refbuf.h"
#include "client.h"
#include "stats.h"
#include "logging.h"
#include "xslt.h"
#include "fserve.h"
#include "sighandler.h"
#include "slave.h"
#include "yp.h"
#include "source.h"
#include "format.h"
#include "format_mp3.h"
#include "event.h"
#include "admin.h"
#include "auth.h"
#define CATMODULE "connection"
/* Two different major types of source authentication.
Shoutcast style is used only by the Shoutcast DSP
and is a crazy version of HTTP. It looks like :
Source Client -> Connects to port + 1
Source Client -> sends encoder password (plaintext)\r\n
Icecast -> reads encoder password, if ok, sends OK2\r\n, else disconnects
Source Client -> reads OK2\r\n, then sends http-type request headers
that contain the stream details (icy-name, etc..)
Icecast -> reads headers, stores them
Source Client -> starts sending MP3 data
Source Client -> periodically updates metadata via admin.cgi call
Icecast auth style uses HTTP and Basic Authorization.
*/
static int shoutcast_source_client (client_t *client);
static int http_client_request (client_t *client);
static int _handle_get_request (client_t *client);
static int _handle_source_request (client_t *client);
static int _handle_stats_request (client_t *client);
static mutex_t _connection_lock;
static uint64_t _current_id = 0;
thread_type *conn_tid;
int sigfd;
static int ssl_ok;
#ifdef HAVE_OPENSSL
#ifndef SSL_OP_NO_COMPRESSION
#define SSL_OP_NO_COMPRESSION 0
#endif
static SSL_CTX *ssl_ctx;
static mutex_t *ssl_mutexes = NULL;
#if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
static unsigned long ssl_id_function (void);
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
static void ssl_locking_function (int mode, int n, const char *file, int line);
#endif
#endif
int header_timeout;
struct _client_functions shoutcast_source_ops =
{
shoutcast_source_client,
client_destroy
};
struct _client_functions http_request_ops =
{
http_client_request,
client_destroy
};
struct _client_functions http_req_get_ops =
{
_handle_get_request,
client_destroy
};
struct _client_functions http_req_source_ops =
{
_handle_source_request,
client_destroy
};
struct _client_functions http_req_stats_ops =
{
_handle_stats_request,
client_destroy
};
/* filtering client connection based on IP */
cache_file_contents banned_ip, allowed_ip;
/* filtering listener connection based on useragent */
cache_file_contents useragents;
volatile sig_atomic_t connection_running = 0;
// Generated using `openssl dhparam -C -2 2048`
// BEGIN DH CODE
#ifdef HAVE_OPENSSL
#include <openssl/dh.h>
#if !defined(SSL_CTX_set_dh_auto)
static DH *get_dh2048()
{
static unsigned char dh2048_p[]={
0xF7,0x5F,0x18,0x4E,0xA4,0x66,0xC5,0xAE,0xE1,0x3C,0x52,0x75,
0xEC,0x81,0x79,0x52,0xA9,0x9E,0xEA,0x0A,0xD5,0x2C,0x58,0xC0,
0xE4,0x87,0x5A,0x62,0x46,0xEF,0xE7,0x3E,0xCD,0xD9,0xDE,0xE2,
0xF7,0xD4,0xA5,0x1D,0x3D,0x5C,0xFD,0xE1,0x25,0xBB,0xA9,0x33,
0x4F,0x5F,0x5F,0xF6,0x30,0x65,0x33,0xF6,0x15,0x96,0xE7,0x62,
0xF6,0xB2,0xC3,0x66,0xC0,0x10,0x6A,0x77,0xA2,0xB7,0x87,0x9F,
0x5F,0x48,0x3B,0x4A,0x11,0x4E,0xAC,0x15,0xAA,0xCE,0x10,0xF7,
0xA3,0x6D,0x93,0x80,0xA7,0x71,0x53,0x8C,0x40,0xD5,0x73,0x91,
0x50,0xFD,0x77,0xEC,0xD6,0x41,0x61,0x4E,0x5E,0xF7,0x00,0xE2,
0x63,0x74,0xA0,0xE2,0xF0,0x9C,0x80,0x4F,0x02,0xEB,0xEF,0xE4,
0x1E,0xF4,0x49,0x6D,0xCF,0x5B,0x09,0xE3,0xDC,0x4C,0x66,0x04,
0xE4,0xB3,0x94,0x7D,0xAF,0xB6,0xE8,0x15,0x65,0x2C,0xE6,0x41,
0x18,0x98,0xF7,0x80,0x5B,0x2C,0x00,0x78,0x5A,0xCB,0x20,0x4C,
0x63,0x71,0xE2,0xF6,0xAE,0x73,0x89,0x05,0xD2,0x44,0x2C,0x77,
0x73,0x03,0x19,0x0C,0xAD,0x2F,0x2F,0xDD,0xAB,0x85,0x67,0x43,
0x09,0xFC,0xDF,0x02,0xB6,0xD3,0xCE,0xAA,0x68,0xFF,0xA3,0x94,
0x4C,0xFD,0x2F,0x5C,0xE4,0x1A,0xF4,0x0C,0x58,0x5A,0x3D,0xDC,
0xEF,0x64,0x2B,0xA4,0xCF,0xF5,0xFF,0x6C,0x37,0xE9,0x0E,0xAE,
0x3D,0x84,0x61,0x91,0xFE,0x09,0x4B,0xF6,0x68,0xCB,0xC6,0x42,
0xE8,0x03,0xAC,0xA2,0x5D,0x49,0x2A,0xC7,0xF1,0xA5,0x7A,0x61,
0xC2,0x30,0xA4,0x3D,0xD9,0x2D,0xBC,0x6F,0xE6,0xE1,0xDE,0xD2,
0x98,0xE6,0x46,0x7B,
};
static unsigned char dh2048_g[]={
0x02,
};
DH *dh;
BIGNUM *p, *g;
if ((dh=DH_new()) == NULL) return NULL;
p = BN_bin2bn (dh2048_p, sizeof(dh2048_p), NULL);
g = BN_bin2bn (dh2048_g, sizeof(dh2048_g), NULL);
if ((p == NULL) || (g == NULL))
{
BN_free (p);
BN_free (g);
DH_free (dh);
return NULL;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100005L
DH_set0_pqg(dh, p, NULL, g);
#else
dh->p = p;
dh->g = g;
#endif
return dh;
}
#endif
#endif // END DH CODE
static int compare_banned_ip (void *arg, void *a, void *b)
{
struct node_IP_time *this = (struct node_IP_time *)a;
struct node_IP_time *that = (struct node_IP_time *)b;
int ret = strcmp (&this->ip[0], &that->ip[0]);
if (ret && that->a.timeout)
{
cache_file_contents *c = arg;
time_t threshold = c->file_recheck - 60;
if (c->deletions_count < 9 && that->a.timeout < threshold)
{
c->deletions [c->deletions_count] = that;
c->deletions_count++;
}
}
return ret;
}
void connection_initialize(void)
{
thread_mutex_create (&_connection_lock);
memset (&banned_ip, 0, sizeof (banned_ip));
memset (&allowed_ip, 0, sizeof (allowed_ip));
memset (&useragents, 0, sizeof (useragents));
conn_tid = NULL;
connection_running = 0;
#ifdef HAVE_OPENSSL
ssl_ctx = NULL;
#if OPENSSL_API_COMPAT < 0x10100000L
SSL_load_error_strings(); /* readable error messages */
#endif
SSL_library_init(); /* initialize library */
ssl_mutexes = calloc(CRYPTO_num_locks(), sizeof(mutex_t));
if (ssl_mutexes)
{
int i;
for (i=0; i < CRYPTO_num_locks(); i++)
thread_mutex_create (&ssl_mutexes[i]);
#if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
CRYPTO_set_id_callback (ssl_id_function);
#endif
CRYPTO_set_locking_callback (ssl_locking_function);
}
else
WARN0("unable to set up internal locking for SSL, memory problem");
#endif
}
void connection_shutdown(void)
{
connection_listen_sockets_close (NULL, 1);
thread_mutex_destroy (&_connection_lock);
#ifdef HAVE_OPENSSL
SSL_CTX_free (ssl_ctx);
#if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
CRYPTO_set_id_callback(NULL);
#endif
CRYPTO_set_locking_callback(NULL);
#if OPENSSL_API_COMPAT < 0x10100000L
ERR_free_strings ();
#endif
if (ssl_mutexes)
{
int i;
for(i = 0; i < CRYPTO_num_locks(); i++)
thread_mutex_destroy (&ssl_mutexes[i]);
free (ssl_mutexes);
ssl_mutexes = NULL;
}
#endif
}
static uint64_t _next_connection_id(void)
{
uint64_t id;
thread_mutex_lock (&_connection_lock);
id = _current_id++;
thread_mutex_unlock (&_connection_lock);
return id;
}
#ifdef HAVE_OPENSSL
#if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
static unsigned long ssl_id_function (void)
{
return (unsigned long)thread_self();
}
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
static void ssl_locking_function (int mode, int n, const char *file, int line)
{
if (mode & CRYPTO_LOCK)
thread_mutex_lock_c (&ssl_mutexes[n], line, file);
else
thread_mutex_unlock_c (&ssl_mutexes[n], line, file);
}
#endif
static void get_ssl_certificate (ice_config_t *config)
{
ssl_ok = 0;
SSL_CTX *new_ssl_ctx = NULL;
do
{
long ssl_opts;
if (config->cert_file == NULL)
break;
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
new_ssl_ctx = SSL_CTX_new (TLS_method());
#else
new_ssl_ctx = SSL_CTX_new (SSLv23_method());
#endif
ssl_opts = SSL_CTX_get_options (new_ssl_ctx);
SSL_CTX_set_options (new_ssl_ctx, ssl_opts|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION|SSL_OP_CIPHER_SERVER_PREFERENCE|SSL_OP_ALL);
// Enable DH and ECDH
// See: https://john.nachtimwald.com/2014/10/01/enable-dh-and-ecdh-in-openssl-server/
#if defined(SSL_CTX_set_ecdh_auto)
SSL_CTX_set_ecdh_auto (new_ssl_ctx, 1);
#else
EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if ( (NULL == ecdh) || 1 != SSL_CTX_set_tmp_ecdh (new_ssl_ctx, ecdh) )
{
WARN0 ("Cannot setup Elliptic curve Diffie–Hellman parameters");
}
EC_KEY_free (ecdh);
#endif
#if defined(SSL_CTX_set_dh_auto)
SSL_CTX_set_dh_auto (new_ssl_ctx, 1);
#else
DH *dh = get_dh2048 ();
if ( (NULL == dh) || (1 != SSL_CTX_set_tmp_dh (new_ssl_ctx, dh)) )
{
WARN0 ("Cannot setup Diffie-Hellman parameters");
}
DH_free (dh);
#endif
if (SSL_CTX_use_certificate_chain_file (new_ssl_ctx, config->cert_file) <= 0)
{
WARN2 ("Invalid cert file %s (%s)", config->cert_file, ERR_reason_error_string (ERR_peek_last_error()));
break;
}
if (SSL_CTX_use_PrivateKey_file (new_ssl_ctx, config->key_file, SSL_FILETYPE_PEM) <= 0)
{
WARN2 ("Invalid private key file %s (%s)", config->key_file, ERR_reason_error_string (ERR_peek_last_error()));
break;
}
if (config->ca_file && SSL_CTX_load_verify_locations (new_ssl_ctx, config->ca_file, NULL) != 0)
{
WARN2 ("Invalid CA file %s (%s)", config->ca_file, ERR_reason_error_string (ERR_peek_last_error()));
break;
}
SSL_CTX_set_verify_depth (new_ssl_ctx,1);
if (!SSL_CTX_check_private_key (new_ssl_ctx))
{
ERROR2 ("Invalid %s - Private key does not match cert public key (%s)", config->key_file, ERR_reason_error_string (ERR_peek_last_error()));
break;
}
if (SSL_CTX_set_cipher_list (new_ssl_ctx, config->cipher_list) <= 0)
{
WARN1 ("Invalid cipher list: %s", config->cipher_list);
}
ssl_ok = 1;
INFO1 ("SSL certificate found at %s", config->cert_file);
if (strcmp (config->cert_file, config->key_file) != 0)
INFO1 ("SSL private key found at %s", config->key_file);
if (config->ca_file)
INFO1 ("SSL certificate chain found at %s", config->ca_file);
INFO1 ("SSL using ciphers %s", config->cipher_list);
if (ssl_ctx)
SSL_CTX_free (ssl_ctx);
ssl_ctx = new_ssl_ctx;
return;
} while (0);
if (new_ssl_ctx)
SSL_CTX_free (new_ssl_ctx);
if (ssl_ctx)
{ // use the existing certificate details
ssl_ok = 1;
INFO0 ("SSL not reloaded, will keep using previous certificate/key");
}
else
INFO0 ("No SSL capability on any configured ports");
}
/* handlers for reading and writing a connection_t when there is ssl
* configured on the listening port
*/
int connection_read_ssl (connection_t *con, void *buf, size_t len)
{
ERR_clear_error();
int bytes = SSL_read (con->ssl, buf, len);
int code = SSL_get_error (con->ssl, bytes);
char err[128];
switch (code)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_SSL:
case SSL_ERROR_SYSCALL: // avoid the ssl shutdown
con->flags |= CONN_FLG_SSL;
// fallthru
case SSL_ERROR_ZERO_RETURN:
con->error = 1;
// fallthru
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return -1;
default: // the rest are retryable
ERR_error_string (ERR_get_error(), err);
DEBUG2("error %d, %s", code, err);
return -1;
}
return bytes;
}
int connection_send_ssl (connection_t *con, const void *buf, size_t len)
{
ERR_clear_error();
int bytes = SSL_write (con->ssl, buf, len);
int code = SSL_get_error (con->ssl, bytes);
char err[128];
switch (code)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_SYSCALL: // avoid the ssl shutdown
// DEBUG3("syscall error %d, on %s (%" PRIu64 ")", sock_error(), &con->ip[0], con->id);
case SSL_ERROR_SSL:
con->flags |= CONN_FLG_SSL;
// fallthru
case SSL_ERROR_ZERO_RETURN:
con->error = 1;
// fallthru
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return -1;
default:
ERR_error_string (ERR_get_error(), err);
DEBUG2("error %d, %s", code, err);
}
if (bytes > 0)
con->sent_bytes += bytes;
return bytes;
}
#else
/* SSL not compiled in, so at least log it */
static void get_ssl_certificate (ice_config_t *config)
{
ssl_ok = 0;
INFO0 ("No SSL capability");
}
#endif /* HAVE_OPENSSL */
int connection_unreadable (connection_t *con)
{
if (((++con->readchk) & 15) == 15)
{
int r = sock_active (con->sock);
if (r == 0)
{
con->error = 1;
return -1;
}
}
return 0;
}
/* handlers (default) for reading and writing a connection_t, no encrpytion
* used just straight access to the socket
*/
int connection_read (connection_t *con, void *buf, size_t len)
{
int bytes = sock_read_bytes (con->sock, buf, len);
if (bytes == 0)
con->error = 1;
if (bytes == -1 && !sock_recoverable (sock_error()))
con->error = 1;
return bytes;
}
int connection_send (connection_t *con, const void *buf, size_t len)
{
if (connection_unreadable (con))
return -1;
if ((con->flags & CONN_FLG_DISCON) && con->discon.sent > 0)
{
if (con->sent_bytes + len > con->discon.sent)
len = con->discon.sent - con->sent_bytes;
}
int bytes = 0;
if (len > 0)
bytes = sock_write_bytes (con->sock, buf, len);
if (bytes < 0)
{
if (!sock_recoverable (sock_error()))
con->error = 1;
}
else
{
con->sent_bytes += bytes;
if ((con->flags & CONN_FLG_DISCON) && con->sent_bytes >= con->discon.sent)
con->error = CONN_ERR_FINI;
}
return bytes;
}
void connection_bufs_init (struct connection_bufs *v, short start)
{
memset (v, 0, sizeof (struct connection_bufs));
if (start && start < 500)
{
v->block = calloc (start, sizeof (IOVEC));
v->max = start;
}
}
void connection_bufs_release (struct connection_bufs *v)
{
free (v->block);
memset (v, 0, sizeof (struct connection_bufs));
}
void connection_bufs_flush (struct connection_bufs *v)
{
v->count = 0;
v->total = 0;
}
int connection_bufs_append (struct connection_bufs *v, void *buf, unsigned int len)
{
if (len > 0xFFFFFF)
{
ERROR1 ("Sanity check failed, len is %u", len);
abort();
}
if (v->count >= v->max)
{
int len = v->max + 16;
IOVEC *arr = realloc (v->block, (len*sizeof(IOVEC)));
v->max = len;
v->block = arr;
}
IO_VECTOR_BASE (v->block + v->count) = buf;
IO_VECTOR_LEN (v->block + v->count) = len;
v->count++;
v->total += len;
return v->total;
}
static int connbufs_locate_start (struct connection_bufs *vects, int skip, IOVEC *old_value, int *offp)
{
int sum = 0, i = vects->count;
IOVEC *p = vects->block;
if (skip < vects->total)
{
for (; i; i--)
{
if (sum + IO_VECTOR_LEN(p) > skip)
{
int offset = skip - sum;
if (offset)
{
*old_value = *p;
IO_VECTOR_BASE(p) += offset;
IO_VECTOR_LEN(p) -= offset;
}
*offp = offset;
return p - vects->block;
}
sum += IO_VECTOR_LEN(p);
p++;
}
}
return -1;
}
int connection_bufs_send (connection_t *con, struct connection_bufs *vectors, int skip)
{
IOVEC *p = vectors->block, old_vals;
int i = vectors->count, offset = 0, ret = -1;
if (skip > vectors->total) abort();
i = connbufs_locate_start (vectors, skip, &old_vals, &offset);
p = vectors->block + i;
if (i >= 0)
{
if (not_ssl_connection (con))
{
if (connection_unreadable (con))
return -1;
ret = sock_writev (con->sock, p, vectors->count - i);
if (ret < 0 && !sock_recoverable (sock_error()))
con->error = 1;
}
#ifdef HAVE_OPENSSL
else
{
IOVEC *io = p;
int bytes = 0;
for (; i < vectors->count; i++, io++)
{
int v = connection_send_ssl (con, IO_VECTOR_BASE(io), IO_VECTOR_LEN(io));
if (v > 0) bytes += v;
if (v < 0 || v < IO_VECTOR_LEN(io)) break;
}
if (bytes > 0) ret = bytes;
}
#endif
if (offset)
*p = old_vals;
if (ret > 0)
con->sent_bytes += ret;
}
return ret;
}
int connection_chunk_start (connection_t *con, struct connection_bufs *bufs, char *chunk_hdr, unsigned chunk_sz)
{
int chunk_hdrlen = snprintf (chunk_hdr, CHUNK_HDR_SZ, "%x\r\n", chunk_sz);
return connection_bufs_append (bufs, chunk_hdr, chunk_hdrlen);
}
int connection_chunk_end (connection_t *con, struct connection_bufs *bufs, char *chunk_hdr, unsigned chunk_sz)
{
char *p = strchr (chunk_hdr, '\r');
if (p && p[1] == '\n')
return connection_bufs_append (bufs, p, 2);
ERROR0 ("chunk has no EOL");
abort();
}
static void add_banned_ip (cache_file_contents *c, const void *e, time_t now)
{
if (c)
{
struct node_IP_time *banned;
const char *ip = e;
#ifdef HAVE_FNMATCH_H
if (ip [strcspn (ip, "*?[")]) // if wildcard present
{
struct cache_list_node *entry = calloc (1, sizeof (*entry));
entry->content = strdup (ip);
entry->next = c->extra;
c->extra = entry;
DEBUG1 ("Adding wildcard entry \"%.30s\"", ip);
return;
}
#endif
banned = calloc (1, sizeof (struct node_IP_time));
snprintf (&banned->ip[0], sizeof (banned->ip), "%s", ip);
banned->a.timeout = now;
DEBUG1 ("Adding literal entry \"%.30s\"", ip);
avl_insert (c->contents, banned);
}
}
void connection_add_banned_ip (const char *ip, int duration)
{
time_t timeout = 0;
if (duration > 0)
timeout = time(NULL) + duration;
if (banned_ip.contents)
{
global_lock();
add_banned_ip (&banned_ip, ip, timeout);
global_unlock();
}
else
INFO0 ("No ban-file set up, missing tag in xml or no file referenced");
}
void connection_release_banned_ip (const char *ip)
{
if (banned_ip.contents)
{
global_lock();
avl_delete (banned_ip.contents, (void*)ip, cached_treenode_free);
global_unlock();
}
}
void connection_stats (void)
{
long banned_IPs = 0;
if (banned_ip.contents)
banned_IPs = (long)banned_ip.contents->length;
stats_event_args (NULL, "banned_IPs", "%ld", banned_IPs);
}
time_t cachefile_timecheck = (time_t)0;
/* check specified ip against internal set of banned IPs
* return -1 for no data, 0 for no match and 1 for match
*/
static int search_banned_ip_locked (char *ip)
{
int ret = 0;
if (banned_ip.extra)
{
struct cache_list_node *entry = banned_ip.extra;
while (entry)
{
if (cached_pattern_compare (ip, entry->content) == 0)
return 1;
entry = entry->next;
}
}
if (banned_ip.contents)
{
int i;
void *result;
banned_ip.deletions_count = 0;
if (avl_get_by_key (banned_ip.contents, ip, &result) == 0)
{
struct node_IP_time *match = result;
if (match->a.timeout == 0 || match->a.timeout > cachefile_timecheck)
{
if (match->a.timeout && cachefile_timecheck + 300 > match->a.timeout)
match->a.timeout = cachefile_timecheck + 300;
ret = 1;
}
else
avl_delete (banned_ip.contents, ip, cached_treenode_free);
}
/* we may of seen others to remove */
for (i = 0; i < banned_ip.deletions_count; ++i)
{
struct node_IP_time *to_go = banned_ip.deletions[i];
INFO1 ("removing %s from ban list for now", &(to_go->ip[0]));
avl_delete (banned_ip.contents, &(to_go->ip[0]), cached_treenode_free);
}
banned_ip.deletions_count = 0;
}
return ret;
}
static int search_banned_ip (char *ip)
{
int ret;
thread_mutex_lock (&_connection_lock);
time_t t = cachefile_timecheck;
thread_mutex_unlock (&_connection_lock);
cached_file_recheck (&banned_ip, t);
global_lock();
ret = search_banned_ip_locked (ip);
global_unlock();
return ret;
}
/* return 0 if the passed ip address is not to be handled by icecast, non-zero otherwise */
static int accept_ip_address (char *ip)
{
time_t t = time (NULL);
thread_mutex_lock (&_connection_lock);
cachefile_timecheck = t;
thread_mutex_unlock (&_connection_lock);
if (search_banned_ip (ip) > 0)
{
DEBUG1 ("%s banned", ip);
return 0;
}
if (cached_pattern_search (&allowed_ip, ip, t) == 0)
{
DEBUG1 ("%s is not allowed", ip);
return 0;
}
return 1;
}
static struct xforward_entry *_find_xforward_addr (ice_config_t *config, char *ip)
{
struct xforward_entry *xforward = config->xforward;
while (xforward)
{
if (fnmatch (xforward->ip, ip, 0) == 0)
break;
xforward = xforward->next;
}
return xforward;
}
static int _set_connection_peer (connection_t *con, sock_t sock)
{
struct sockaddr_storage sa;
socklen_t slen = sizeof (sa);
if (getpeername (sock, (struct sockaddr *)&sa, &slen) == 0)
{
char *ip;
#ifdef HAVE_GETNAMEINFO
char buffer [200] = "unknown";
getnameinfo ((struct sockaddr *)&sa, slen, buffer, 200, NULL, 0, NI_NUMERICHOST);
if (strncmp (buffer, "::ffff:", 7) == 0)
ip = strdup (buffer+7);
else
ip = strdup (buffer);
#else
int len = 30;
ip = malloc (len);
strncpy (ip, inet_ntoa (((struct sockaddr_in*)&sa)->sin_addr), len);
#endif
free (con->ip);
if (accept_ip_address (ip))
{
con->ip = ip;
return 0;
}
con->ip = NULL;
free (ip);
}
return -1;
}
int connection_init (connection_t *con, sock_t sock, const char *addr)
{
if (con)
{
con->sock = sock;
if (sock == SOCK_ERROR)
return -1;
con->id = _next_connection_id();
if (addr)
{
free (con->ip);
con->ip = strdup (addr + (strncmp (addr, "::ffff:", 7) == 0 ? 7: 0));
return 0;
}
if (_set_connection_peer (con, sock) == 0)
return 0;
free (con->ip);
memset (con, 0, sizeof (connection_t));
con->sock = SOCK_ERROR;
}
return -1;
}
/* prepare connection for interacting over a SSL connection
*/
int connection_uses_ssl (connection_t *con, int accept_state)
{
#ifdef HAVE_OPENSSL
int ret;
if (ssl_ctx == NULL)
{
DEBUG1 ("Detected SSL on connection from %s, but SSL not defined", con->ip);
con->error = 1;
return -1;
}
con->ssl = SSL_new (ssl_ctx);
ret = SSL_set_fd (con->ssl, con->sock);
if (accept_state)
SSL_set_accept_state (con->ssl);
else
SSL_set_connect_state (con->ssl);
SSL_set_mode (con->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|SSL_MODE_ENABLE_PARTIAL_WRITE);
return ret > 0 ? 0 : -1;
#else
return -1;
#endif
}
int connection_peek (connection_t *con)
{
if (ssl_ok && not_ssl_connection (con)) // if set then ssl is already determined, so skip this
{
unsigned char arr[12];
int r = sock_peek (con->sock, (char*)arr, sizeof (arr));
if (r > 5)
{
if (arr[0] == 0x16 && arr[1] == 0x3 && arr[5] == 0x1)
{
sock_set_cork (con->sock, 0); // make sure this is off, leave curl to decide
sock_set_nodelay (con->sock);
if (connection_uses_ssl (con, 1) == 0)
DEBUG1 ("Detected SSL on connection from %s", con->ip);
}
else if (sock_set_cork (con->sock, 1) < 0)
sock_set_nodelay (con->sock);
return 1;
}
if (r < 0)
return -1;
con->error = 1; // closed socket
}
else if (sock_set_cork (con->sock, 1) < 0)
sock_set_nodelay (con->sock);
return 0;
}
#ifdef HAVE_SIGNALFD
void connection_close_sigfd (void)
{
if (sigfd >= 0)
close (sigfd);
sigfd = -1;
}
#else
#define connection_close_sigfd() do {}while(0);
#endif
static sock_t wait_for_serversock (void)
{
#ifdef HAVE_POLL
int i, ret;
struct pollfd ufds [global.server_sockets + 1];
for(i=0; i < global.server_sockets; i++) {
ufds[i].fd = global.serversock[i];
ufds[i].events = POLLIN;
ufds[i].revents = 0;
}
#ifdef HAVE_SIGNALFD
ufds[i].revents = 0;
if (sigfd >= 0)
{
ufds[i].fd = sigfd;
ufds[i].events = POLLIN;
ret = poll(ufds, i+1, 4000);
}
else
ret = poll(ufds, i, 4000);
#else
ret = poll(ufds, global.server_sockets, 333);