1 /* Icecast
2  *
3  * This program is distributed under the GNU General Public License, version 2.
4  * A copy of this license is included with this source.
5  *
6  * Copyright 2000-2004, Jack Moffitt <jack@xiph.org>,
7  *                      Michael Smith <msmith@xiph.org>,
8  *                      oddsock <oddsock@xiph.org>,
9  *                      Karl Heyes <karl@xiph.org>
10  *                      and others (see AUTHORS for details).
11  * Copyright 2000-2017, Karl Heyes <karl@kheyes.plus.com>
12  */
13 
14 /* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- */
15 #ifdef HAVE_CONFIG_H
16 #include <config.h>
17 #endif
18 
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <string.h>
23 #ifdef HAVE_POLL
24 #include <sys/poll.h>
25 #endif
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fnmatch.h>
29 
30 #ifdef _MSC_VER
31  #include <winsock2.h>
32  #include <ws2tcpip.h>
33 #endif
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37 #ifdef HAVE_NETINET_IN_H
38 #include <netinet/in.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
42 #endif
43 #ifdef HAVE_NETDB_H
44 #include <netdb.h>
45 #endif
46 
47 #ifdef HAVE_SIGNALFD
48 #include <sys/signalfd.h>
49 #include <signal.h>
50 #endif
51 
52 #include "compat.h"
53 
54 #include "thread/thread.h"
55 #include "avl/avl.h"
56 #include "net/sock.h"
57 #include "httpp/httpp.h"
58 #include "timing/timing.h"
59 
60 #include "cfgfile.h"
61 #include "global.h"
62 #include "util.h"
63 #include "connection.h"
64 #include "refbuf.h"
65 #include "client.h"
66 #include "stats.h"
67 #include "logging.h"
68 #include "xslt.h"
69 #include "fserve.h"
70 #include "sighandler.h"
71 #include "slave.h"
72 
73 #include "yp.h"
74 #include "source.h"
75 #include "format.h"
76 #include "format_mp3.h"
77 #include "event.h"
78 #include "admin.h"
79 #include "auth.h"
80 
81 #define CATMODULE "connection"
82 
83 /* Two different major types of source authentication.
84    Shoutcast style is used only by the Shoutcast DSP
85    and is a crazy version of HTTP.  It looks like :
86      Source Client -> Connects to port + 1
87      Source Client -> sends encoder password (plaintext)\r\n
88      Icecast -> reads encoder password, if ok, sends OK2\r\n, else disconnects
89      Source Client -> reads OK2\r\n, then sends http-type request headers
90                       that contain the stream details (icy-name, etc..)
91      Icecast -> reads headers, stores them
92      Source Client -> starts sending MP3 data
93      Source Client -> periodically updates metadata via admin.cgi call
94 
95    Icecast auth style uses HTTP and Basic Authorization.
96 */
97 
98 static int  shoutcast_source_client (client_t *client);
99 static int  http_client_request (client_t *client);
100 static int  _handle_get_request (client_t *client);
101 static int  _handle_source_request (client_t *client);
102 static int  _handle_stats_request (client_t *client);
103 
104 static spin_t _connection_lock;
105 static uint64_t _current_id = 0;
106 thread_type *conn_tid;
107 int sigfd;
108 
109 static int ssl_ok;
110 #ifdef HAVE_OPENSSL
111 #ifndef SSL_OP_NO_COMPRESSION
112 #define SSL_OP_NO_COMPRESSION 0
113 #endif
114 static SSL_CTX *ssl_ctx;
115 static mutex_t *ssl_mutexes = NULL;
116 #if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
117 static unsigned long ssl_id_function (void);
118 #endif
119 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
120 static void ssl_locking_function (int mode, int n, const char *file, int line);
121 #endif
122 #endif
123 
124 int header_timeout;
125 
126 struct _client_functions shoutcast_source_ops =
127 {
128     shoutcast_source_client,
129     client_destroy
130 };
131 
132 struct _client_functions http_request_ops =
133 {
134     http_client_request,
135     client_destroy
136 };
137 
138 struct _client_functions http_req_get_ops =
139 {
140     _handle_get_request,
141     client_destroy
142 };
143 struct _client_functions http_req_source_ops =
144 {
145     _handle_source_request,
146     client_destroy
147 };
148 
149 struct _client_functions http_req_stats_ops =
150 {
151     _handle_stats_request,
152     client_destroy
153 };
154 
155 /* filtering client connection based on IP */
156 cache_file_contents banned_ip, allowed_ip;
157 
158 /* filtering listener connection based on useragent */
159 cache_file_contents useragents;
160 
161 int connection_running = 0;
162 
163 
164 // Generated using `openssl dhparam -C -2 2048`
165 // BEGIN DH CODE
166 #ifdef HAVE_OPENSSL
167 #include <openssl/dh.h>
168 
169 #if !defined(SSL_CTX_set_dh_auto)
get_dh2048()170 static DH *get_dh2048()
171 {
172     static unsigned char dh2048_p[]={
173         0xF7,0x5F,0x18,0x4E,0xA4,0x66,0xC5,0xAE,0xE1,0x3C,0x52,0x75,
174         0xEC,0x81,0x79,0x52,0xA9,0x9E,0xEA,0x0A,0xD5,0x2C,0x58,0xC0,
175         0xE4,0x87,0x5A,0x62,0x46,0xEF,0xE7,0x3E,0xCD,0xD9,0xDE,0xE2,
176         0xF7,0xD4,0xA5,0x1D,0x3D,0x5C,0xFD,0xE1,0x25,0xBB,0xA9,0x33,
177         0x4F,0x5F,0x5F,0xF6,0x30,0x65,0x33,0xF6,0x15,0x96,0xE7,0x62,
178         0xF6,0xB2,0xC3,0x66,0xC0,0x10,0x6A,0x77,0xA2,0xB7,0x87,0x9F,
179         0x5F,0x48,0x3B,0x4A,0x11,0x4E,0xAC,0x15,0xAA,0xCE,0x10,0xF7,
180         0xA3,0x6D,0x93,0x80,0xA7,0x71,0x53,0x8C,0x40,0xD5,0x73,0x91,
181         0x50,0xFD,0x77,0xEC,0xD6,0x41,0x61,0x4E,0x5E,0xF7,0x00,0xE2,
182         0x63,0x74,0xA0,0xE2,0xF0,0x9C,0x80,0x4F,0x02,0xEB,0xEF,0xE4,
183         0x1E,0xF4,0x49,0x6D,0xCF,0x5B,0x09,0xE3,0xDC,0x4C,0x66,0x04,
184         0xE4,0xB3,0x94,0x7D,0xAF,0xB6,0xE8,0x15,0x65,0x2C,0xE6,0x41,
185         0x18,0x98,0xF7,0x80,0x5B,0x2C,0x00,0x78,0x5A,0xCB,0x20,0x4C,
186         0x63,0x71,0xE2,0xF6,0xAE,0x73,0x89,0x05,0xD2,0x44,0x2C,0x77,
187         0x73,0x03,0x19,0x0C,0xAD,0x2F,0x2F,0xDD,0xAB,0x85,0x67,0x43,
188         0x09,0xFC,0xDF,0x02,0xB6,0xD3,0xCE,0xAA,0x68,0xFF,0xA3,0x94,
189         0x4C,0xFD,0x2F,0x5C,0xE4,0x1A,0xF4,0x0C,0x58,0x5A,0x3D,0xDC,
190         0xEF,0x64,0x2B,0xA4,0xCF,0xF5,0xFF,0x6C,0x37,0xE9,0x0E,0xAE,
191         0x3D,0x84,0x61,0x91,0xFE,0x09,0x4B,0xF6,0x68,0xCB,0xC6,0x42,
192         0xE8,0x03,0xAC,0xA2,0x5D,0x49,0x2A,0xC7,0xF1,0xA5,0x7A,0x61,
193         0xC2,0x30,0xA4,0x3D,0xD9,0x2D,0xBC,0x6F,0xE6,0xE1,0xDE,0xD2,
194         0x98,0xE6,0x46,0x7B,
195     };
196     static unsigned char dh2048_g[]={
197         0x02,
198     };
199     DH *dh;
200     BIGNUM *p, *g;
201 
202     if ((dh=DH_new()) == NULL) return NULL;
203     p = BN_bin2bn (dh2048_p, sizeof(dh2048_p), NULL);
204     g = BN_bin2bn (dh2048_g, sizeof(dh2048_g), NULL);
205     if ((p == NULL) || (g == NULL))
206     {
207         BN_free (p);
208         BN_free (g);
209         DH_free (dh);
210         return NULL;
211     }
212 #if OPENSSL_VERSION_NUMBER >= 0x10100005L
213     DH_set0_pqg(dh, p, NULL, g);
214 #else
215     dh->p = p;
216     dh->g = g;
217 #endif
218     return dh;
219 }
220 #endif
221 #endif  // END DH CODE
222 
223 
compare_banned_ip(void * arg,void * a,void * b)224 static int compare_banned_ip (void *arg, void *a, void *b)
225 {
226     struct node_IP_time *this = (struct node_IP_time *)a;
227     struct node_IP_time *that = (struct node_IP_time *)b;
228     int ret = strcmp (&this->ip[0], &that->ip[0]);
229 
230     if (ret && that->a.timeout)
231     {
232         cache_file_contents *c = arg;
233         time_t threshold = c->file_recheck - 60;
234 
235         if (c->deletions_count < 9 && that->a.timeout < threshold)
236         {
237             c->deletions [c->deletions_count] = that;
238             c->deletions_count++;
239         }
240     }
241     return ret;
242 }
243 
244 
connection_initialize(void)245 void connection_initialize(void)
246 {
247     thread_spin_create (&_connection_lock);
248 
249     memset (&banned_ip, 0, sizeof (banned_ip));
250     memset (&allowed_ip, 0, sizeof (allowed_ip));
251     memset (&useragents, 0, sizeof (useragents));
252 
253     conn_tid = NULL;
254     connection_running = 0;
255 #ifdef HAVE_OPENSSL
256     ssl_ctx = NULL;
257 #if OPENSSL_API_COMPAT < 0x10100000L
258     SSL_load_error_strings();                /* readable error messages */
259 #endif
260     SSL_library_init();                      /* initialize library */
261     ssl_mutexes = malloc(CRYPTO_num_locks() * sizeof(mutex_t));
262     if (ssl_mutexes)
263     {
264         int i;
265         for (i=0; i < CRYPTO_num_locks();  i++)
266             thread_mutex_create (&ssl_mutexes[i]);
267 #if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
268         CRYPTO_set_id_callback (ssl_id_function);
269 #endif
270         CRYPTO_set_locking_callback (ssl_locking_function);
271     }
272     else
273         WARN0("unable to set up internal locking for SSL, memory problem");
274 #endif
275 }
276 
connection_shutdown(void)277 void connection_shutdown(void)
278 {
279     connection_listen_sockets_close (NULL, 1);
280     thread_spin_destroy (&_connection_lock);
281 #ifdef HAVE_OPENSSL
282     SSL_CTX_free (ssl_ctx);
283 #if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
284     CRYPTO_set_id_callback(NULL);
285 #endif
286     CRYPTO_set_locking_callback(NULL);
287 #if OPENSSL_API_COMPAT < 0x10100000L
288     ERR_free_strings ();
289 #endif
290     if (ssl_mutexes)
291     {
292         int i;
293         for(i = 0; i < CRYPTO_num_locks(); i++)
294             thread_mutex_destroy (&ssl_mutexes[i]);
295         free (ssl_mutexes);
296         ssl_mutexes = NULL;
297     }
298 #endif
299 }
300 
_next_connection_id(void)301 static uint64_t _next_connection_id(void)
302 {
303     uint64_t id;
304 
305     thread_spin_lock (&_connection_lock);
306     id = _current_id++;
307     thread_spin_unlock (&_connection_lock);
308 
309     return id;
310 }
311 
312 
313 #ifdef HAVE_OPENSSL
314 #if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000
ssl_id_function(void)315 static unsigned long ssl_id_function (void)
316 {
317     return (unsigned long)thread_self();
318 }
319 #endif
320 
321 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
ssl_locking_function(int mode,int n,const char * file,int line)322 static void ssl_locking_function (int mode, int n, const char *file, int line)
323 {
324     if (mode & CRYPTO_LOCK)
325         thread_mutex_lock_c (&ssl_mutexes[n], line, file);
326     else
327         thread_mutex_unlock_c (&ssl_mutexes[n], line, file);
328 }
329 #endif
330 
331 
get_ssl_certificate(ice_config_t * config)332 static void get_ssl_certificate (ice_config_t *config)
333 {
334     ssl_ok = 0;
335     SSL_CTX *new_ssl_ctx = NULL;
336 
337     do
338     {
339         long ssl_opts;
340 
341         if (config->cert_file == NULL)
342             break;
343 
344 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
345         new_ssl_ctx = SSL_CTX_new (TLS_server_method());
346 #else
347         new_ssl_ctx = SSL_CTX_new (SSLv23_server_method());
348 #endif
349         ssl_opts = SSL_CTX_get_options (new_ssl_ctx);
350         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);
351 
352         // Enable DH and ECDH
353         // See: https://john.nachtimwald.com/2014/10/01/enable-dh-and-ecdh-in-openssl-server/
354 #if defined(SSL_CTX_set_ecdh_auto)
355         SSL_CTX_set_ecdh_auto (new_ssl_ctx, 1);
356 #else
357         EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
358         if ( (NULL == ecdh) || 1 != SSL_CTX_set_tmp_ecdh (new_ssl_ctx, ecdh) )
359         {
360             WARN0 ("Cannot setup Elliptic curve Diffie–Hellman parameters");
361         }
362         EC_KEY_free (ecdh);
363 #endif
364 
365 #if defined(SSL_CTX_set_dh_auto)
366         SSL_CTX_set_dh_auto (new_ssl_ctx, 1);
367 #else
368         DH *dh = get_dh2048 ();
369         if ( (NULL == dh) || (1 != SSL_CTX_set_tmp_dh (new_ssl_ctx, dh)) )
370         {
371             WARN0 ("Cannot setup Diffie-Hellman parameters");
372         }
373         DH_free (dh);
374 #endif
375         if (SSL_CTX_use_certificate_chain_file (new_ssl_ctx, config->cert_file) <= 0)
376         {
377             WARN2 ("Invalid cert file %s (%s)", config->cert_file, ERR_reason_error_string (ERR_peek_last_error()));
378             break;
379         }
380         if (SSL_CTX_use_PrivateKey_file (new_ssl_ctx, config->key_file, SSL_FILETYPE_PEM) <= 0)
381         {
382             WARN2 ("Invalid private key file %s (%s)", config->key_file, ERR_reason_error_string (ERR_peek_last_error()));
383             break;
384         }
385         if (config->ca_file && SSL_CTX_load_verify_locations (new_ssl_ctx, config->ca_file, NULL) != 0)
386         {
387             WARN2 ("Invalid CA file %s (%s)", config->ca_file, ERR_reason_error_string (ERR_peek_last_error()));
388             break;
389         }
390         SSL_CTX_set_verify_depth (new_ssl_ctx,1);
391 
392         if (!SSL_CTX_check_private_key (new_ssl_ctx))
393         {
394             ERROR2 ("Invalid %s - Private key does not match cert public key (%s)", config->key_file, ERR_reason_error_string (ERR_peek_last_error()));
395             break;
396         }
397         if (SSL_CTX_set_cipher_list (new_ssl_ctx, config->cipher_list) <= 0)
398         {
399             WARN1 ("Invalid cipher list: %s", config->cipher_list);
400         }
401         ssl_ok = 1;
402         INFO1 ("SSL certificate found at %s", config->cert_file);
403         if (strcmp (config->cert_file, config->key_file) != 0)
404             INFO1 ("SSL private key found at %s", config->key_file);
405         if (config->ca_file)
406             INFO1 ("SSL certificate chain found at %s", config->ca_file);
407 
408         INFO1 ("SSL using ciphers %s", config->cipher_list);
409         if (ssl_ctx)
410             SSL_CTX_free (ssl_ctx);
411         ssl_ctx = new_ssl_ctx;
412         return;
413     } while (0);
414 
415     if (new_ssl_ctx)
416         SSL_CTX_free (new_ssl_ctx);
417 
418     if (ssl_ctx)
419         INFO0 ("SSL not reloaded, will keep using previous certificate/key");
420     else
421         INFO0 ("No SSL capability on any configured ports");
422 }
423 
424 
425 /* handlers for reading and writing a connection_t when there is ssl
426  * configured on the listening port
427  */
connection_read_ssl(connection_t * con,void * buf,size_t len)428 int connection_read_ssl (connection_t *con, void *buf, size_t len)
429 {
430     ERR_clear_error();
431     int bytes = SSL_read (con->ssl, buf, len);
432     int code = SSL_get_error (con->ssl, bytes);
433     char err[128];
434 
435     switch (code)
436     {
437         case SSL_ERROR_NONE:
438             break;
439         case SSL_ERROR_SSL:
440         case SSL_ERROR_SYSCALL:     // avoid the ssl shutdown
441             con->sslflags |= 1;
442             // fallthru
443         case SSL_ERROR_ZERO_RETURN:
444             con->error = 1;
445             // fallthru
446         case SSL_ERROR_WANT_READ:
447         case SSL_ERROR_WANT_WRITE:
448             return -1;
449         default:    // the rest are retryable
450             ERR_error_string (ERR_get_error(), err);
451             DEBUG2("error %d, %s", code, err);
452             return -1;
453     }
454     return bytes;
455 }
456 
connection_send_ssl(connection_t * con,const void * buf,size_t len)457 int connection_send_ssl (connection_t *con, const void *buf, size_t len)
458 {
459     ERR_clear_error();
460     int bytes = SSL_write (con->ssl, buf, len);
461     int code = SSL_get_error (con->ssl, bytes);
462     char err[128];
463 
464     switch (code)
465     {
466         case SSL_ERROR_NONE:
467             break;
468         case SSL_ERROR_SYSCALL: // avoid the ssl shutdown
469             // DEBUG3("syscall error %d, on %s (%" PRIu64 ")", sock_error(), &con->ip[0], con->id);
470         case SSL_ERROR_SSL:
471             con->sslflags |= 1;
472             // fallthru
473         case SSL_ERROR_ZERO_RETURN:
474             con->error = 1;
475             // fallthru
476         case SSL_ERROR_WANT_READ:
477         case SSL_ERROR_WANT_WRITE:
478             return -1;
479         default:
480             ERR_error_string (ERR_get_error(), err);
481             DEBUG2("error %d, %s", code, err);
482     }
483     if (bytes > 0)
484         con->sent_bytes += bytes;
485     return bytes;
486 }
487 #else
488 
489 /* SSL not compiled in, so at least log it */
get_ssl_certificate(ice_config_t * config)490 static void get_ssl_certificate (ice_config_t *config)
491 {
492     ssl_ok = 0;
493     INFO0 ("No SSL capability");
494 }
495 #endif /* HAVE_OPENSSL */
496 
connection_unreadable(connection_t * con)497 int connection_unreadable (connection_t *con)
498 {
499     if (((++con->readchk) & 15) == 15)
500     {
501         int r = sock_active (con->sock);
502         if (r == 0)
503         {
504             con->error = 1;
505             return -1;
506         }
507     }
508     return 0;
509 }
510 
511 /* handlers (default) for reading and writing a connection_t, no encrpytion
512  * used just straight access to the socket
513  */
connection_read(connection_t * con,void * buf,size_t len)514 int connection_read (connection_t *con, void *buf, size_t len)
515 {
516     int bytes = sock_read_bytes (con->sock, buf, len);
517     if (bytes == 0)
518         con->error = 1;
519     if (bytes == -1 && !sock_recoverable (sock_error()))
520         con->error = 1;
521     return bytes;
522 }
523 
connection_send(connection_t * con,const void * buf,size_t len)524 int connection_send (connection_t *con, const void *buf, size_t len)
525 {
526     if (connection_unreadable (con))
527         return -1;
528     int bytes = sock_write_bytes (con->sock, buf, len);
529     if (bytes < 0)
530     {
531         if (!sock_recoverable (sock_error()))
532             con->error = 1;
533     }
534     else
535         con->sent_bytes += bytes;
536     return bytes;
537 }
538 
539 
connection_bufs_init(struct connection_bufs * v,short start)540 void connection_bufs_init (struct connection_bufs *v, short start)
541 {
542     memset (v, 0, sizeof (struct connection_bufs));
543     if (start && start < 500)
544     {
545         v->block = calloc (start, sizeof (IOVEC));
546         v->max = start;
547     }
548 }
549 
550 
connection_bufs_release(struct connection_bufs * v)551 void connection_bufs_release (struct connection_bufs *v)
552 {
553     free (v->block);
554     memset (v, 0, sizeof (struct connection_bufs));
555 }
556 
557 
connection_bufs_flush(struct connection_bufs * v)558 void connection_bufs_flush (struct connection_bufs *v)
559 {
560     v->count = 0;
561     v->total = 0;
562 }
563 
564 
connection_bufs_append(struct connection_bufs * v,void * buf,unsigned int len)565 int connection_bufs_append (struct connection_bufs *v, void *buf, unsigned int len)
566 {
567     if (len > 0xFFFFFF)
568     {
569         ERROR1 ("Sanity check failed, len is %u", len);
570         abort();
571     }
572     if (v->count >= v->max)
573     {
574        int len = v->max + 16;
575        IOVEC *arr = realloc (v->block, (len*sizeof(IOVEC)));
576        v->max = len;
577        v->block = arr;
578     }
579     IO_VECTOR_BASE (v->block + v->count) = buf;
580     IO_VECTOR_LEN (v->block + v->count) = len;
581     v->count++;
582     v->total += len;
583     return v->total;
584 
585 }
586 
587 
connbufs_locate_start(struct connection_bufs * vects,int skip,IOVEC * old_value,int * offp)588 static int connbufs_locate_start (struct connection_bufs *vects, int skip, IOVEC *old_value, int *offp)
589 {
590     int sum = 0, i = vects->count;
591     IOVEC *p = vects->block;
592 
593     if (skip < vects->total)
594     {
595         for (; i; i--)
596         {
597             if (sum + IO_VECTOR_LEN(p) > skip)
598             {
599                 int offset = skip - sum;
600                 if (offset)
601                 {
602                     *old_value = *p;
603                     IO_VECTOR_BASE(p) += offset;
604                     IO_VECTOR_LEN(p) -= offset;
605                 }
606                 *offp = offset;
607                 return p - vects->block;
608             }
609             sum += IO_VECTOR_LEN(p);
610             p++;
611         }
612     }
613     return -1;
614 }
615 
616 
connection_bufs_send(connection_t * con,struct connection_bufs * vectors,int skip)617 int connection_bufs_send (connection_t *con, struct connection_bufs *vectors, int skip)
618 {
619     IOVEC *p = vectors->block, old_vals;
620     int i = vectors->count,  offset = 0, ret = -1;
621 
622     if (skip > vectors->total) abort();
623     i = connbufs_locate_start (vectors, skip, &old_vals, &offset);
624     p = vectors->block + i;
625 
626     if (i >= 0)
627     {
628         if (not_ssl_connection (con))
629         {
630             if (connection_unreadable (con))
631                 return -1;
632             ret = sock_writev (con->sock, p, vectors->count - i);
633             if (ret < 0 && !sock_recoverable (sock_error()))
634                 con->error = 1;
635         }
636 #ifdef HAVE_OPENSSL
637         else
638         {
639             IOVEC *io = p;
640             int bytes = 0;
641             for (; i < vectors->count; i++, io++)
642             {
643                int v = connection_send_ssl (con, IO_VECTOR_BASE(io), IO_VECTOR_LEN(io));
644                if (v > 0) bytes += v;
645                if (v < 0 || v < IO_VECTOR_LEN(io)) break;
646             }
647             if (bytes > 0)  ret = bytes;
648         }
649 #endif
650         if (offset)
651             *p = old_vals;
652         if (ret > 0)
653             con->sent_bytes += ret;
654     }
655     return ret;
656 }
657 
658 
connection_chunk_start(connection_t * con,struct connection_bufs * bufs,char * chunk_hdr,unsigned chunk_sz)659 int connection_chunk_start (connection_t *con, struct connection_bufs *bufs, char *chunk_hdr, unsigned chunk_sz)
660 {
661     int chunk_hdrlen = snprintf (chunk_hdr, CHUNK_HDR_SZ, "%x\r\n", chunk_sz);
662 
663     return connection_bufs_append (bufs, chunk_hdr, chunk_hdrlen);
664 }
665 
666 
connection_chunk_end(connection_t * con,struct connection_bufs * bufs,char * chunk_hdr,unsigned chunk_sz)667 int connection_chunk_end (connection_t *con, struct connection_bufs *bufs, char *chunk_hdr, unsigned chunk_sz)
668 {
669     char *p = strchr (chunk_hdr, '\r');
670     if (p && p[1] == '\n')
671         return connection_bufs_append (bufs, p, 2);
672     ERROR0 ("chunk has no EOL");
673     abort();
674 }
675 
676 
677 
add_banned_ip(cache_file_contents * c,const void * e,time_t now)678 static void add_banned_ip (cache_file_contents *c, const void *e, time_t now)
679 {
680     if (c)
681     {
682         struct node_IP_time *banned;
683         const char *ip = e;
684 #ifdef HAVE_FNMATCH_H
685         if (ip [strcspn (ip, "*?[")]) // if wildcard present
686         {
687             struct cache_list_node *entry = calloc (1, sizeof (*entry));
688             entry->content = strdup (ip);
689             entry->next = c->extra;
690             c->extra = entry;
691             DEBUG1 ("Adding wildcard entry \"%.30s\"", ip);
692             return;
693         }
694 #endif
695         banned = calloc (1, sizeof (struct node_IP_time));
696         snprintf (&banned->ip[0], sizeof (banned->ip), "%s", ip);
697         banned->a.timeout = now;
698         DEBUG1 ("Adding literal entry \"%.30s\"", ip);
699         avl_insert (c->contents, banned);
700     }
701 }
702 
connection_add_banned_ip(const char * ip,int duration)703 void connection_add_banned_ip (const char *ip, int duration)
704 {
705     time_t timeout = 0;
706     if (duration > 0)
707         timeout = time(NULL) + duration;
708 
709     if (banned_ip.contents)
710     {
711         global_lock();
712         add_banned_ip (&banned_ip, ip, timeout);
713         global_unlock();
714     }
715     else
716         INFO0 ("No ban-file set up, missing tag in xml or no file referenced");
717 }
718 
connection_release_banned_ip(const char * ip)719 void connection_release_banned_ip (const char *ip)
720 {
721     if (banned_ip.contents)
722     {
723         global_lock();
724         avl_delete (banned_ip.contents, (void*)ip, cached_treenode_free);
725         global_unlock();
726     }
727 }
728 
connection_stats(void)729 void connection_stats (void)
730 {
731     long banned_IPs = 0;
732     if (banned_ip.contents)
733         banned_IPs = (long)banned_ip.contents->length;
734     stats_event_args (NULL, "banned_IPs", "%ld", banned_IPs);
735 }
736 
737 
738 time_t cachefile_timecheck = (time_t)0;
739 
740 /* check specified ip against internal set of banned IPs
741  * return -1 for no data, 0 for no match and 1 for match
742  */
search_banned_ip_locked(char * ip)743 static int search_banned_ip_locked (char *ip)
744 {
745     int ret = 0;
746     if (banned_ip.extra)
747     {
748         struct cache_list_node *entry = banned_ip.extra;
749         while (entry)
750         {
751             if (cached_pattern_compare (ip, entry->content) == 0)
752                 return 1;
753             entry = entry->next;
754         }
755     }
756     if (banned_ip.contents)
757     {
758         int i;
759         void *result;
760 
761         banned_ip.deletions_count = 0;
762         if (avl_get_by_key (banned_ip.contents, ip, &result) == 0)
763         {
764             struct node_IP_time *match = result;
765             if (match->a.timeout == 0 || match->a.timeout > cachefile_timecheck)
766             {
767                 if (match->a.timeout && cachefile_timecheck + 300 > match->a.timeout)
768                     match->a.timeout = cachefile_timecheck + 300;
769                 ret = 1;
770             }
771             else
772                 avl_delete (banned_ip.contents, ip, cached_treenode_free);
773         }
774         /* we may of seen others to remove */
775         for (i = 0; i < banned_ip.deletions_count; ++i)
776         {
777             struct node_IP_time *to_go = banned_ip.deletions[i];
778             INFO1 ("removing %s from ban list for now", &(to_go->ip[0]));
779             avl_delete (banned_ip.contents, &(to_go->ip[0]), cached_treenode_free);
780         }
781         banned_ip.deletions_count = 0;
782     }
783     return ret;
784 }
785 
786 
search_banned_ip(char * ip)787 static int search_banned_ip (char *ip)
788 {
789     int ret;
790     cached_file_recheck (&banned_ip, cachefile_timecheck);
791     global_lock();
792     ret = search_banned_ip_locked (ip);
793     global_unlock();
794     return ret;
795 }
796 
797 
798 /* return 0 if the passed ip address is not to be handled by icecast, non-zero otherwise */
accept_ip_address(char * ip)799 static int accept_ip_address (char *ip)
800 {
801     cachefile_timecheck = time (NULL);
802 
803     if (search_banned_ip (ip) > 0)
804     {
805         DEBUG1 ("%s banned", ip);
806         return 0;
807     }
808     if (cached_pattern_search (&allowed_ip, ip, cachefile_timecheck) == 0)
809     {
810         DEBUG1 ("%s is not allowed", ip);
811         return 0;
812     }
813     return 1;
814 }
815 
816 
_find_xforward_addr(ice_config_t * config,char * ip)817 static struct xforward_entry *_find_xforward_addr (ice_config_t *config, char *ip)
818 {
819     struct xforward_entry *xforward = config->xforward;
820     while (xforward)
821     {
822         if (fnmatch (xforward->ip, ip, 0) == 0)
823             break;
824         xforward = xforward->next;
825     }
826     return xforward;
827 }
828 
829 
connection_init(connection_t * con,sock_t sock,const char * addr)830 int connection_init (connection_t *con, sock_t sock, const char *addr)
831 {
832     if (con)
833     {
834         struct sockaddr_storage sa;
835         socklen_t slen = sizeof (sa);
836 
837         con->sock = sock;
838         if (sock == SOCK_ERROR)
839             return -1;
840         con->id = _next_connection_id();
841         if (addr)
842         {
843             con->ip = strdup (addr + (strncmp (addr, "::ffff:", 7) == 0 ? 7: 0));
844             return 0;
845         }
846         if (getpeername (sock, (struct sockaddr *)&sa, &slen) == 0)
847         {
848             char *ip;
849 #ifdef HAVE_GETNAMEINFO
850             char buffer [200] = "unknown";
851             getnameinfo ((struct sockaddr *)&sa, slen, buffer, 200, NULL, 0, NI_NUMERICHOST);
852             if (strncmp (buffer, "::ffff:", 7) == 0)
853                 ip = strdup (buffer+7);
854             else
855                 ip = strdup (buffer);
856 #else
857             int len = 30;
858             ip = malloc (len);
859             strncpy (ip, inet_ntoa (((struct sockaddr_in*)&sa)->sin_addr), len);
860 #endif
861             if (accept_ip_address (ip))
862             {
863                 con->ip = ip;
864                 return 0;
865             }
866             free (ip);
867         }
868         memset (con, 0, sizeof (connection_t));
869         con->sock = SOCK_ERROR;
870     }
871     return -1;
872 }
873 
874 
875 /* prepare connection for interacting over a SSL connection
876  */
connection_uses_ssl(connection_t * con)877 void connection_uses_ssl (connection_t *con)
878 {
879 #ifdef HAVE_OPENSSL
880     if (ssl_ctx == NULL)
881     {
882         DEBUG1 ("Detected SSL on connection from %s, but SSL not defined", con->ip);
883         con->error = 1;
884         return;
885     }
886     con->ssl = SSL_new (ssl_ctx);
887     SSL_set_accept_state (con->ssl);
888     SSL_set_fd (con->ssl, con->sock);
889     SSL_set_mode (con->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|SSL_MODE_ENABLE_PARTIAL_WRITE);
890     DEBUG1 ("Detected SSL on connection from %s", con->ip);
891 #endif
892 }
893 
894 
connection_peek(connection_t * con)895 int connection_peek (connection_t *con)
896 {
897 #ifdef HAVE_OPENSSL
898     if (con->ssl == NULL)   // if set then ssl is already determined, so skip this
899     {
900         unsigned char arr[20];
901         int r = sock_peek (con->sock, (char*)arr, sizeof (arr));
902         if (r > 0)
903         {
904             if (r > 5 && arr[0] == 0x16 && arr[1] == 0x3 && arr[5] == 0x1)
905             {
906                 connection_uses_ssl (con);
907                 return 1;
908             }
909             return r < 10 ? 0 : 1;
910         }
911         if (r < 0)
912             return -1;
913         con->error = 1;
914     }
915 #endif
916     return 0;
917 }
918 
919 
920 #ifdef HAVE_SIGNALFD
connection_close_sigfd(void)921 void connection_close_sigfd (void)
922 {
923     if (sigfd >= 0)
924         close (sigfd);
925     sigfd = -1;
926 }
927 #else
928 #define connection_close_sigfd()    do {}while(0);
929 #endif
930 
931 
wait_for_serversock(void)932 static sock_t wait_for_serversock (void)
933 {
934 #ifdef HAVE_POLL
935     int i, ret;
936     struct pollfd ufds [global.server_sockets + 1];
937 
938     for(i=0; i < global.server_sockets; i++) {
939         ufds[i].fd = global.serversock[i];
940         ufds[i].events = POLLIN;
941         ufds[i].revents = 0;
942     }
943 #ifdef HAVE_SIGNALFD
944     ufds[i].revents = 0;
945     if (sigfd >= 0)
946     {
947         ufds[i].fd = sigfd;
948         ufds[i].events = POLLIN;
949         ret = poll(ufds, i+1, 4000);
950     }
951     else
952         ret = poll(ufds, i, 4000);
953 #else
954     ret = poll(ufds, global.server_sockets, 333);
955 #endif
956 
957     if (ret <= 0)
958         return SOCK_ERROR;
959     else {
960         int dst;
961 #ifdef HAVE_SIGNALFD
962         if (ufds[i].revents & POLLIN)
963         {
964             struct signalfd_siginfo fdsi;
965             int ret  = read (sigfd, &fdsi, sizeof(struct signalfd_siginfo));
966             if (ret == sizeof(struct signalfd_siginfo))
967             {
968                 switch (fdsi.ssi_signo)
969                 {
970                     case SIGINT:
971                     case SIGTERM:
972                         DEBUG0 ("signalfd received a termination");
973                         global_lock();
974                         global.running = ICE_HALTING;
975                         global_unlock();
976                         thread_spin_lock (&_connection_lock);
977                         connection_running = 0;
978                         thread_spin_unlock (&_connection_lock);
979                         break;
980                     case SIGHUP:
981                         INFO0 ("HUP received, reread scheduled");
982                         global_lock();
983                         global.schedule_config_reread = 1;
984                         global_unlock();
985                         break;
986                     default:
987                         WARN1 ("unexpected signal (%d)", fdsi.ssi_signo);
988                 }
989             }
990         }
991         if (ufds[i].revents & (POLLNVAL|POLLERR))
992         {
993             ERROR0 ("signalfd descriptor became invalid, doing thread restart");
994             slave_restart(); // something odd happened
995             thread_sleep (250000);
996         }
997 #endif
998         for(i=0; i < global.server_sockets; i++) {
999             if(ufds[i].revents & POLLIN)
1000                 return ufds[i].fd;
1001             if(ufds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
1002             {
1003                 if (ufds[i].revents & (POLLHUP|POLLERR))
1004                 {
1005                     sock_close (global.serversock[i]);
1006                 }
1007                 listener_t *l = global.server_conn[i];
1008                 WARN2("Had to remove a listening socket on port %d (%s)", l->port, l->bind_address ? l->bind_address : "default");
1009                 global.serversock[i] = SOCK_ERROR;
1010             }
1011         }
1012         /* remove any closed sockets */
1013         for(i=0, dst=0; i < global.server_sockets; i++)
1014         {
1015             if (global.serversock[i] == SOCK_ERROR)
1016                 continue;
1017             if (i!=dst)
1018                 global.serversock[dst] = global.serversock[i];
1019             dst++;
1020         }
1021         global.server_sockets = dst;
1022         return SOCK_ERROR;
1023     }
1024 #else
1025     fd_set rfds;
1026     struct timeval tv;
1027     int i, ret;
1028     sock_t max = SOCK_ERROR;
1029 
1030     FD_ZERO(&rfds);
1031 
1032     for(i=0; i < global.server_sockets; i++) {
1033         FD_SET(global.serversock[i], &rfds);
1034         if (max == SOCK_ERROR || global.serversock[i] > max)
1035             max = global.serversock[i];
1036     }
1037 
1038     tv.tv_sec = 0;
1039     tv.tv_usec = 333000;
1040 
1041     ret = select(max+1, &rfds, NULL, NULL, &tv);
1042     if(ret < 0) {
1043         return SOCK_ERROR;
1044     }
1045     else if(ret == 0) {
1046         return SOCK_ERROR;
1047     }
1048     else {
1049         for(i=0; i < global.server_sockets; i++) {
1050             if(FD_ISSET(global.serversock[i], &rfds))
1051                 return global.serversock[i];
1052         }
1053         return SOCK_ERROR; /* Should be impossible, stop compiler warnings */
1054     }
1055 #endif
1056 }
1057 
1058 
accept_client(void)1059 static client_t *accept_client (void)
1060 {
1061     sock_t sock, serversock = wait_for_serversock ();
1062     listener_t *server_conn = NULL;
1063     char addr [200];
1064 
1065     if (serversock == SOCK_ERROR)
1066         return NULL;
1067 
1068     sock = sock_accept (serversock, addr, 200);
1069     if (sock == SOCK_ERROR)
1070     {
1071         if (sock_recoverable (sock_error()))
1072             return NULL;
1073         WARN2 ("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
1074         thread_sleep (500000);
1075         return NULL;
1076     }
1077     do
1078     {
1079         int i;
1080         refbuf_t *r;
1081 
1082         if (accept_ip_address (addr) == 0)
1083             break;
1084         if (sock_set_blocking (sock, 0) || (sock_set_cork (sock, 1) < 0 && sock_set_nodelay (sock)))
1085         {
1086             WARN0 ("failed to set tcp options on client connection, dropping");
1087             break;
1088         }
1089         global_lock ();
1090         for (i=0; i < global.server_sockets; i++)
1091         {
1092             if (global.serversock[i] == serversock)
1093             {
1094                 server_conn = global.server_conn[i];
1095                 server_conn->refcount++;
1096                 break;
1097             }
1098         }
1099         global_unlock ();
1100         if (server_conn)
1101         {
1102             client_t *client = NULL;
1103             int not_using_ssl = 1;
1104 
1105             if (ssl_ok && server_conn->ssl)
1106                 not_using_ssl = 0;
1107             if (not_using_ssl)
1108             {
1109                 if (sock_set_blocking (sock, 0) || (sock_set_cork (sock, 1) < 0 && sock_set_nodelay (sock)))
1110                 {
1111                     WARN1 ("failed to set tcp options on incoming client connection %s, dropping", addr);
1112                     break;
1113                 }
1114             }
1115             client = calloc (1, sizeof (client_t));
1116             if (client == NULL || connection_init (&client->connection, sock, addr) < 0)
1117             {
1118                 free (client);
1119                 break;
1120             }
1121 
1122             client->shared_data = r = refbuf_new (PER_CLIENT_REFBUF_SIZE);
1123             r->len = 0; // for building up the request coming in
1124 
1125             global_lock ();
1126             client_register (client);
1127             global_unlock ();
1128 
1129             if (not_using_ssl == 0)
1130                 connection_uses_ssl (&client->connection);
1131 
1132             if (server_conn->shoutcast_compat)
1133                 client->ops = &shoutcast_source_ops;
1134             else
1135                 client->ops = &http_request_ops;
1136             client->server_conn = server_conn;
1137             client->flags |= CLIENT_ACTIVE;
1138 
1139             return client;
1140         }
1141     } while (0);
1142 
1143     if (server_conn)
1144     {
1145         global_lock ();
1146         server_conn->refcount--;
1147         global_unlock ();
1148     }
1149     sock_close (sock);
1150     return NULL;
1151 }
1152 
1153 
1154 /* shoutcast source clients are handled specially because the protocol is limited. It is
1155  * essentially a password followed by a series of headers, each on a separate line.  In here
1156  * we get the password and build a http request like a native source client would do
1157  */
shoutcast_source_client(client_t * client)1158 static int shoutcast_source_client (client_t *client)
1159 {
1160     do
1161     {
1162         connection_t *con = &client->connection;
1163         if (con->error || con->discon.time <= client->worker->current_time.tv_sec)
1164             break;
1165 
1166         if (client->shared_data)  /* need to get password first */
1167         {
1168             refbuf_t *refbuf = client->shared_data;
1169             int remaining = PER_CLIENT_REFBUF_SIZE - 2 - refbuf->len, ret, len;
1170             char *buf = refbuf->data + refbuf->len;
1171             char *esc_header;
1172             refbuf_t *r, *resp;
1173             char header [128];
1174 
1175             if (remaining == 0)
1176                 break;
1177 
1178             ret = client_read_bytes (client, buf, remaining);
1179             if (ret == 0 || con->error || global.running != ICE_RUNNING)
1180                 break;
1181             if (ret < 0)
1182                 return 0;
1183 
1184             refbuf->len += ret;
1185             buf [ret] = '\0';
1186             len = strcspn (refbuf->data, "\r\n");
1187             if (refbuf->data [len] == '\0')  /* no EOL yet */
1188                 return 0;
1189 
1190             refbuf->data [len] = '\0';  // password
1191 
1192             // is mountpoint embedded in the password
1193             const char *mount = client->server_conn->shoutcast_mount, *pw = refbuf->data;
1194             char *sep = strchr (refbuf->data, ':');
1195             if (sep && *pw == '/')
1196             {
1197                 pw = sep + 1;
1198                 *sep = '\0';
1199                 mount = refbuf->data;
1200             }
1201             // DEBUG2 ("Using mount %s and pass %s", mount, pw);
1202             snprintf (header, sizeof(header), "source:%s", pw);
1203             esc_header = util_base64_encode (header);
1204 
1205             len += 1 + strspn (refbuf->data+len+1, "\r\n");
1206             r = refbuf_new (PER_CLIENT_REFBUF_SIZE);
1207             snprintf (r->data, PER_CLIENT_REFBUF_SIZE,
1208                     "SOURCE %s HTTP/1.0\r\n" "Authorization: Basic %s\r\n%s",
1209                     mount, esc_header, refbuf->data+len);
1210             r->len = strlen (r->data);
1211             free (esc_header);
1212             client->respcode = 200;
1213             resp = refbuf_new (30);
1214             snprintf (resp->data, 30, "OK2\r\nicy-caps:11\r\n\r\n");
1215             resp->len = strlen (resp->data);
1216             resp->associated = r;
1217             client->refbuf = resp;
1218             refbuf_release (refbuf);
1219             client->shared_data = NULL;
1220             INFO1 ("emulation on %s", client->server_conn->shoutcast_mount);
1221         }
1222         format_generic_write_to_client (client);
1223         if (client->pos == client->refbuf->len)
1224         {
1225             refbuf_t *r = client->refbuf;
1226             client->shared_data = r->associated;
1227             client->refbuf = NULL;
1228             r->associated = NULL;
1229             refbuf_release (r);
1230             client->ops = &http_request_ops;
1231             client->pos = 0;
1232         }
1233         client->schedule_ms = client->worker->time_ms + 100;
1234         return 0;
1235     } while (0);
1236 
1237     refbuf_release (client->shared_data);
1238     client->shared_data = NULL;
1239     return -1;
1240 }
1241 
1242 
1243 // NOTE: stream data may be in the block after headers
1244 //
setup_source_client_callback(client_t * client)1245 int setup_source_client_callback (client_t *client)
1246 {
1247     refbuf_t *buf = client->refbuf;
1248 
1249     if (client->format_data == NULL)
1250     {
1251         const char *expect = httpp_getvar (client->parser, "expect");
1252         int len = buf->len - client->pos;
1253 
1254         if (len)
1255         {
1256             refbuf_t *stream = refbuf_new (len);
1257             memcpy (stream->data, buf->data+client->pos, len);
1258             buf->associated = stream;
1259             buf->len -= len;
1260             DEBUG1 ("found %d bytes of stream data after headers", len);
1261         }
1262         if (expect)
1263         {
1264            if (strcasecmp (expect, "100-continue") == 0)
1265            {
1266                DEBUG0 ("client expects 100 continue");
1267                snprintf (buf->data, PER_CLIENT_REFBUF_SIZE, "HTTP/1.1 100 Continue\r\n\r\n");
1268                buf->len = strlen (buf->data);
1269                client->format_data = buf;
1270                client->pos = 0;
1271                client_send_buffer_callback (client, setup_source_client_callback);
1272                return 0;  // need to send this straight away
1273            }
1274            INFO1 ("Received Expect header: %s", expect);
1275         }
1276     }
1277     buf = buf->associated;
1278     client->refbuf->associated = NULL;
1279     refbuf_release (client->refbuf);
1280     client->refbuf = buf;
1281     client->pos = 0;
1282     client->format_data = NULL;
1283     client->ops = &http_req_source_ops;
1284     return 0;
1285 }
1286 
1287 
http_client_request(client_t * client)1288 static int http_client_request (client_t *client)
1289 {
1290     refbuf_t *refbuf = client->shared_data;
1291     int remaining, ret = -1;
1292 
1293     if (global.running != ICE_RUNNING)
1294         return -1;
1295     if (refbuf == NULL)
1296     {
1297         client->shared_data = refbuf = refbuf_new (PER_CLIENT_REFBUF_SIZE);
1298         refbuf->len = 0; // for building up the request coming in
1299     }
1300     remaining = PER_CLIENT_REFBUF_SIZE - 1 - refbuf->len;
1301 
1302     if (remaining && client->connection.discon.time > client->worker->current_time.tv_sec)
1303     {
1304         char *buf = refbuf->data + refbuf->len;
1305 
1306         if (refbuf->len == 0)
1307         {
1308             if (connection_peek (&client->connection) < 0)
1309             {
1310                 client->schedule_ms = client->worker->time_ms + (not_ssl_connection (&client->connection) ? 90 : 133);
1311                 return 0;
1312             }
1313         }
1314         ret = client_read_bytes (client, buf, remaining);
1315         if (ret > 0)
1316         {
1317             char *ptr;
1318 
1319             buf [ret] = '\0';
1320             refbuf->len += ret;
1321             if (memcmp (refbuf->data, "<policy-file-request/>", 23) == 0)
1322             {
1323                 fbinfo fb;
1324                 memset (&fb, 0, sizeof(fb));
1325                 fb.mount = "/flashpolicy";
1326                 fb.flags = FS_USE_ADMIN;
1327                 fb.type = FORMAT_TYPE_UNDEFINED;
1328                 client->respcode = 200;
1329                 refbuf_release (refbuf);
1330                 client->shared_data = NULL;
1331                 client->check_buffer = format_generic_write_to_client;
1332                 return fserve_setup_client_fb (client, &fb);
1333             }
1334             /* find a blank line */
1335             do
1336             {
1337                 buf = refbuf->data;
1338                 ptr = strstr (buf, "\r\n\r\n");
1339                 if (ptr)
1340                 {
1341                     ptr += 4;
1342                     break;
1343                 }
1344                 ptr = strstr (buf, "\n\n");
1345                 if (ptr)
1346                 {
1347                     ptr += 2;
1348                     break;
1349                 }
1350                 ptr = strstr (buf, "\r\r\n\r\r\n");
1351                 if (ptr)
1352                 {
1353                     ptr += 6;
1354                     break;
1355                 }
1356                 client->schedule_ms = client->worker->time_ms + 100;
1357                 return 0;
1358             } while (0);
1359             client->refbuf = client->shared_data;
1360             client->shared_data = NULL;
1361             client->connection.discon.time = 0;
1362             client->parser = httpp_create_parser();
1363             httpp_initialize (client->parser, NULL);
1364             if (httpp_parse (client->parser, refbuf->data, refbuf->len))
1365             {
1366                 const char *str;
1367 
1368                 str = httpp_getvar (client->parser, "x-forwarded-for");
1369                 if (str)
1370                 {
1371                     if (_find_xforward_addr (config_get_config(), client->connection.ip) != NULL)
1372                     {
1373                         config_release_config();
1374                         int len = strcspn (str, ",") + 1;
1375                         int drop_it = 0;
1376                         char *ip = malloc (len);
1377                         snprintf (ip, len, "%s",  str);
1378 
1379                         if (accept_ip_address (ip) == 0)
1380                         {
1381                             DEBUG2 ("Dropping client at %s via %s", ip, client->connection.ip);
1382                             drop_it = 1;
1383                         }
1384                         else
1385                             DEBUG2 ("x-forwarded-for match for %s, using %s instead", client->connection.ip, ip);
1386                         free (client->connection.ip);
1387                         client->connection.ip = ip;
1388                         if (drop_it)
1389                             return -1;
1390                     }
1391                     else
1392                         config_release_config();
1393                 }
1394 
1395                 if (useragents.filename)
1396                 {
1397                     const char *agent = httpp_getvar (client->parser, "user-agent");
1398 
1399                     if (agent && cached_pattern_search (&useragents, agent, client->worker->current_time.tv_sec) > 0)
1400                     {
1401                         INFO2 ("dropping client at %s because useragent is %.70s",
1402                                 client->connection.ip, agent);
1403                         return -1;
1404                     }
1405                 }
1406 
1407                 /* headers now parsed, make sure any sent content is next */
1408                 str = httpp_getvar (client->parser, HTTPP_VAR_PROTOCOL);
1409                 if (strcmp("ICE", str) && strcmp("HTTP", str))
1410                 {
1411                     ERROR2("Bad protocol (%.15s) detected from %s", str, &client->connection.ip[0]);
1412                     return -1;
1413                 }
1414                 str = httpp_getvar (client->parser, HTTPP_VAR_VERSION);
1415                 if (str && strcmp (str, "1.1") == 0)
1416                     client->flags |= CLIENT_KEEPALIVE;  // make default for 1.1
1417 
1418                 str = httpp_getvar (client->parser, "connection");
1419                 if (str)
1420                 {
1421                     if (strcasecmp (str, "keep-alive") == 0)
1422                         client->flags |= CLIENT_KEEPALIVE;
1423                     else
1424                         client->flags &= ~CLIENT_KEEPALIVE;
1425                 }
1426 
1427                 auth_check_http (client);
1428                 switch (client->parser->req_type)
1429                 {
1430                     case httpp_req_head:
1431                     case httpp_req_get:
1432                         refbuf->len = PER_CLIENT_REFBUF_SIZE;
1433                         client->ops = &http_req_get_ops;
1434                         break;
1435                     case httpp_req_source:
1436                     case httpp_req_put:
1437                         client->pos = ptr - refbuf->data;
1438                         setup_source_client_callback (client);
1439                         break;
1440                     case httpp_req_stats:
1441                         refbuf->len = PER_CLIENT_REFBUF_SIZE;
1442                         client->ops = &http_req_stats_ops;
1443                         break;
1444                     case httpp_req_options:
1445                         return client_send_options (client);
1446                     default:
1447                         WARN1("unhandled request type from %s", client->connection.ip);
1448                         return client_send_501 (client);
1449                 }
1450                 client->counter = 0;
1451                 return client->ops->process(client);
1452             }
1453             /* invalid http request */
1454             return -1;
1455         }
1456         if (ret && client->connection.error == 0)
1457         {
1458             /* scale up the retry time, very short initially, usual case */
1459             uint64_t diff = client->worker->time_ms - client->counter;
1460             diff >>= 1;
1461             if (diff > 200)
1462                 diff = 200;
1463             client->schedule_ms = client->worker->time_ms + 6 + diff;
1464             return 0;
1465         }
1466     }
1467     refbuf_release (refbuf);
1468     client->shared_data = NULL;
1469     return -1;
1470 }
1471 
1472 
connection_thread(void * arg)1473 static void *connection_thread (void *arg)
1474 {
1475     ice_config_t *config;
1476 
1477 #ifdef HAVE_SIGNALFD
1478     sigset_t mask;
1479     sigemptyset(&mask);
1480     sigaddset(&mask, SIGINT);
1481     sigaddset(&mask, SIGHUP);
1482     sigaddset(&mask, SIGTERM);
1483     sigfd = signalfd(-1, &mask, 0);
1484 #endif
1485 
1486     config = config_get_config ();
1487     /* setup the banned/allowed IP filenames from the xml */
1488     cached_file_init (&banned_ip,  config->banfile,   add_banned_ip, compare_banned_ip);
1489     cached_file_init (&allowed_ip, config->allowfile, NULL, NULL);
1490     cached_file_init (&useragents, config->agentfile, NULL, NULL);
1491 
1492     connection_setup_sockets (config);
1493     header_timeout = config->header_timeout;
1494     config_release_config ();
1495 
1496     INFO0 ("connection thread started");
1497 
1498     thread_spin_lock (&_connection_lock);
1499     connection_running = 1;
1500     while (connection_running)
1501     {
1502         thread_spin_unlock (&_connection_lock);
1503         client_t *client = accept_client ();
1504         if (client)
1505         {
1506             /* do a small delay here so the client has chance to send the request after
1507              * getting a connect. */
1508             client->counter = client->schedule_ms = timing_get_time();
1509             client->connection.con_time = client->schedule_ms/1000;
1510             client->connection.discon.time = client->connection.con_time + header_timeout;
1511             client->schedule_ms += 30;
1512             client_add_incoming (client);
1513             stats_event_inc (NULL, "connections");
1514         }
1515         if (global.new_connections_slowdown)
1516             thread_sleep (global.new_connections_slowdown * 5000);
1517         thread_spin_lock (&_connection_lock);
1518     }
1519     connection_running = 0;
1520     thread_spin_unlock (&_connection_lock);
1521 
1522     global_lock();
1523     cached_file_clear (&banned_ip);
1524     cached_file_clear (&allowed_ip);
1525     cached_file_clear (&useragents);
1526     global_unlock();
1527     connection_close_sigfd ();
1528 
1529     INFO0 ("connection thread finished");
1530 
1531     return NULL;
1532 }
1533 
1534 
connection_thread_startup()1535 void connection_thread_startup ()
1536 {
1537 #ifdef HAVE_SIGNALFD
1538     sigset_t mask;
1539     sigfillset(&mask);
1540     pthread_sigmask (SIG_SETMASK, &mask, NULL);
1541 #endif
1542     if (conn_tid)
1543         WARN0("id for connection thread still set");
1544 
1545     conn_tid = thread_create ("connection", connection_thread, NULL, THREAD_ATTACHED);
1546 }
1547 
1548 
connection_thread_shutdown()1549 void connection_thread_shutdown ()
1550 {
1551     if (conn_tid)
1552     {
1553         thread_spin_lock (&_connection_lock);
1554         connection_running = 0;
1555         thread_spin_unlock (&_connection_lock);
1556         INFO0("shutting down connection thread");
1557         thread_join (conn_tid);
1558         conn_tid = NULL;
1559     }
1560 }
1561 
1562 
_check_pass_http(http_parser_t * parser,const char * correctuser,const char * correctpass)1563 static int _check_pass_http(http_parser_t *parser,
1564         const char *correctuser, const char *correctpass)
1565 {
1566     /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
1567     const char *header = httpp_getvar(parser, "authorization");
1568     char *userpass, *tmp;
1569     char *username, *password;
1570 
1571     if(header == NULL)
1572         return 0;
1573 
1574     if(strncmp(header, "Basic ", 6))
1575         return 0;
1576 
1577     userpass = util_base64_decode(header+6);
1578     if(userpass == NULL) {
1579         WARN1("Base64 decode of Authorization header \"%s\" failed",
1580                 header+6);
1581         return 0;
1582     }
1583 
1584     tmp = strchr(userpass, ':');
1585     if(!tmp) {
1586         free(userpass);
1587         return 0;
1588     }
1589     *tmp = 0;
1590     username = userpass;
1591     password = tmp+1;
1592 
1593     if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
1594         free(userpass);
1595         return 0;
1596     }
1597     free(userpass);
1598 
1599     return 1;
1600 }
1601 
_check_pass_icy(http_parser_t * parser,const char * correctpass)1602 static int _check_pass_icy(http_parser_t *parser, const char *correctpass)
1603 {
1604     const char *password;
1605 
1606     password = httpp_getvar(parser, HTTPP_VAR_ICYPASSWORD);
1607     if(!password)
1608         return 0;
1609 
1610     if (strcmp(password, correctpass))
1611         return 0;
1612     else
1613         return 1;
1614 }
1615 
_check_pass_ice(http_parser_t * parser,const char * correctpass)1616 static int _check_pass_ice(http_parser_t *parser, const char *correctpass)
1617 {
1618     const char *password;
1619 
1620     password = httpp_getvar(parser, "ice-password");
1621     if(!password)
1622         password = "";
1623 
1624     if (strcmp(password, correctpass))
1625         return 0;
1626     else
1627         return 1;
1628 }
1629 
connection_check_admin_pass(http_parser_t * parser)1630 int connection_check_admin_pass(http_parser_t *parser)
1631 {
1632     int ret;
1633     ice_config_t *config = config_get_config();
1634     char *pass = config->admin_password;
1635     char *user = config->admin_username;
1636     const char *protocol;
1637 
1638     if(!pass || !user) {
1639         config_release_config();
1640         return 0;
1641     }
1642 
1643     protocol = httpp_getvar (parser, HTTPP_VAR_PROTOCOL);
1644     if (protocol && strcmp (protocol, "ICY") == 0)
1645         ret = _check_pass_icy (parser, pass);
1646     else
1647         ret = _check_pass_http (parser, user, pass);
1648     config_release_config();
1649     return ret;
1650 }
1651 
connection_check_relay_pass(http_parser_t * parser)1652 int connection_check_relay_pass(http_parser_t *parser)
1653 {
1654     int ret;
1655     ice_config_t *config = config_get_config();
1656     char *pass = config->relay_password;
1657     char *user = config->relay_username;
1658 
1659     if(!pass || !user) {
1660         config_release_config();
1661         return 0;
1662     }
1663 
1664     ret = _check_pass_http(parser, user, pass);
1665     config_release_config();
1666     return ret;
1667 }
1668 
1669 
1670 /* return 0 for failed, 1 for ok
1671  */
connection_check_pass(http_parser_t * parser,const char * user,const char * pass)1672 int connection_check_pass (http_parser_t *parser, const char *user, const char *pass)
1673 {
1674     int ret;
1675     const char *protocol;
1676 
1677     if(!pass) {
1678         WARN0("No source password set, rejecting source");
1679         return -1;
1680     }
1681 
1682     protocol = httpp_getvar(parser, HTTPP_VAR_PROTOCOL);
1683     if(protocol != NULL && !strcmp(protocol, "ICY")) {
1684         ret = _check_pass_icy(parser, pass);
1685     }
1686     else {
1687         ret = _check_pass_http(parser, user, pass);
1688         if (!ret)
1689         {
1690             ice_config_t *config = config_get_config_unlocked();
1691             if (config->ice_login)
1692             {
1693                 ret = _check_pass_ice(parser, pass);
1694                 if(ret)
1695                     WARN0("Source is using deprecated icecast login");
1696             }
1697         }
1698     }
1699     return ret;
1700 }
1701 
1702 
_handle_source_request(client_t * client)1703 static int _handle_source_request (client_t *client)
1704 {
1705     const char *uri = httpp_getvar (client->parser, HTTPP_VAR_URI);
1706 
1707     INFO1("Source logging in at mountpoint \"%s\"", uri);
1708 
1709     client->flags &= ~CLIENT_KEEPALIVE;
1710 
1711     if (uri[0] != '/')
1712     {
1713         WARN0 ("source mountpoint not starting with /");
1714         return client_send_401 (client, NULL);
1715     }
1716     switch (auth_check_source (client, uri))
1717     {
1718         case 0:         /* authenticated from config file */
1719             return source_startup (client, uri);
1720         case 1:         /* auth pending */
1721             break;
1722         default:        /* failed */
1723             INFO1("Source (%s) attempted to login with invalid or missing password", uri);
1724             return client_send_401 (client, NULL);
1725     }
1726 
1727     return 0;
1728 }
1729 
1730 
_handle_stats_request(client_t * client)1731 static int _handle_stats_request (client_t *client)
1732 {
1733     if (connection_check_admin_pass (client->parser))
1734         stats_add_listener (client, STATS_ALL);
1735     else
1736     {
1737         const char *uri = httpp_getvar (client->parser, HTTPP_VAR_URI);
1738 
1739         if (strcmp (uri, "/admin/streams") == 0 && connection_check_relay_pass (client->parser))
1740             stats_add_listener (client, STATS_SLAVE|STATS_GENERAL);
1741         else
1742             return auth_add_listener (uri, client);
1743     }
1744     return 0;
1745 }
1746 
1747 
check_for_filtering(ice_config_t * config,client_t * client,char * uri)1748 static void check_for_filtering (ice_config_t *config, client_t *client, char *uri)
1749 {
1750     char *pattern = config->access_log.exclude_ext;
1751     char *extension = strrchr (uri, '.');
1752     const char *type = httpp_get_query_param (client->parser, "type");
1753 
1754     if ((extension && strcmp (extension+1, "flv") == 0) ||
1755         (type && (strcmp (type, ".flv") == 0 || strcmp (type, ".fla") == 0)))
1756     {
1757         client->flags |= CLIENT_WANTS_FLV;
1758         client->flags &= ~CLIENT_KEEPALIVE;
1759         DEBUG1 ("listener at %s has requested FLV", &client->connection.ip[0]);
1760     }
1761     if (extension == NULL || uri == NULL)
1762         return;
1763 
1764     extension++;
1765     if (pattern == NULL)
1766         return;
1767     while (*pattern)
1768     {
1769         int len = strcspn (pattern, " ");
1770         if (strncmp (extension, pattern, len) == 0 && extension[len] == '\0')
1771         {
1772             client->flags |= CLIENT_SKIP_ACCESSLOG;
1773             return;
1774         }
1775         pattern += len;
1776         len = strspn (pattern, " "); /* find next pattern */
1777         pattern += len;
1778     }
1779 }
1780 
1781 
_handle_get_request(client_t * client)1782 static int _handle_get_request (client_t *client)
1783 {
1784     char *serverhost = NULL;
1785     int serverport = 0, ret = 0;
1786     aliases *alias;
1787     ice_config_t *config;
1788     char *uri = util_normalise_uri (httpp_getvar (client->parser, HTTPP_VAR_URI));
1789     int client_limit_reached = 0;
1790 
1791     if (uri == NULL)
1792         return client_send_400 (client, "invalid request URI");
1793 
1794     DEBUG1 ("start with %s", uri);
1795     config = config_get_config();
1796     check_for_filtering (config, client, uri);
1797     if (client->server_conn)
1798     {
1799         serverhost = client->server_conn->bind_address;
1800         serverport = client->server_conn->port;
1801     }
1802 
1803     alias = config->aliases;
1804 
1805     /* there are several types of HTTP GET clients
1806     ** media clients, which are looking for a source (eg, URI = /stream.ogg)
1807     ** stats clients, which are looking for /admin/stats.xml
1808     ** and directory server authorizers, which are looking for /GUID-xxxxxxxx
1809     ** (where xxxxxx is the GUID in question) - this isn't implemented yet.
1810     ** we need to handle the latter two before the former, as the latter two
1811     ** aren't subject to the limits.
1812     */
1813     /* TODO: add GUID-xxxxxx */
1814 
1815     /* Handle aliases */
1816     while(alias) {
1817         if(strcmp(uri, alias->source) == 0 && (alias->port == -1 || alias->port == serverport) && (alias->bind_address == NULL || (serverhost != NULL && strcmp(alias->bind_address, serverhost) == 0))) {
1818             char *newuri = strdup (alias->destination);
1819             DEBUG2 ("alias has made %s into %s", uri, newuri);
1820             free (uri);
1821             uri = newuri;
1822             break;
1823         }
1824         alias = alias->next;
1825     }
1826     int client_limit = config->client_limit;
1827     config_release_config();
1828 
1829     global_lock();
1830     if (global.clients > config->client_limit)
1831     {
1832         client_limit_reached = 1;
1833         WARN3 ("server client limit reached (%d/%d) for %s", client_limit, global.clients, client->connection.ip);
1834     }
1835     global_unlock();
1836 
1837     stats_event_inc(NULL, "client_connections");
1838 
1839     if (strcmp (uri, "/admin.cgi") == 0 || strncmp("/admin/", uri, 7) == 0)
1840         ret = admin_handle_request (client, uri);
1841     else
1842     {
1843         /* drop non-admin GET requests here if clients limit reached */
1844         if (client_limit_reached)
1845             ret = client_send_403 (client, "Too many clients connected");
1846         else
1847             ret = auth_add_listener (uri, client);
1848     }
1849     free (uri);
1850     return ret;
1851 }
1852 
1853 
1854 /* close any open listening sockets
1855  */
connection_listen_sockets_close(ice_config_t * config,int all_sockets)1856 void connection_listen_sockets_close (ice_config_t *config, int all_sockets)
1857 {
1858     if (global.serversock)
1859     {
1860         int old = 0, new = 0, cur = global.server_sockets;
1861         for (; old < cur; old++)
1862         {
1863             // close all listening sockets unless privileged ones are to stay open
1864             // and it is still present in the config.
1865             if (config && all_sockets == 0 && global.server_conn [old]->port < 1024)
1866             {
1867                 listener_t *listener = config->listen_sock;
1868                 while (listener)
1869                 {
1870                     if (listener->port == global.server_conn [old]->port)
1871                     {
1872                         const char *new_bind = listener->bind_address ? listener->bind_address : "",
1873                               *old_bind = global.server_conn[old]->bind_address ? global.server_conn[old]->bind_address :  "";
1874 
1875                         if (strcmp (new_bind, old_bind) == 0)
1876                             break;
1877                     }
1878                     listener = listener->next;
1879                 }
1880                 if (listener)
1881                 {
1882                     INFO2 ("Leaving port %d (%s) open", listener->port,
1883                             listener->bind_address ? listener->bind_address : "");
1884                     // update the following attributes of existing socket
1885                     sock_listen (global.serversock [old], listener->qlen);
1886                     if (listener->so_sndbuf)
1887                         sock_set_send_buffer (global.serversock [old], listener->so_sndbuf);
1888                     if (listener->so_mss)
1889                         sock_set_mss (global.serversock [old], listener->so_mss);
1890                     if (new < old)
1891                     {
1892                         global.server_conn [new] = global.server_conn [old];
1893                         global.serversock [new] = global.serversock [old];
1894                     }
1895                     new++;
1896                     continue;
1897                 }
1898             }
1899             if (global.server_conn [old]->bind_address)
1900                 INFO2 ("Closing port %d on %s", global.server_conn [old]->port, global.server_conn [old]->bind_address);
1901             else
1902                 INFO1 ("Closing port %d", global.server_conn [old]->port);
1903             sock_close (global.serversock [old]);
1904             global.serversock [old] = SOCK_ERROR;
1905             config_clear_listener (global.server_conn [old]);
1906             global.server_sockets--;
1907         }
1908         if (global.server_sockets == 0)
1909         {
1910             free (global.serversock);
1911             global.serversock = NULL;
1912             free (global.server_conn);
1913             global.server_conn = NULL;
1914         }
1915     }
1916 }
1917 
1918 
connection_setup_sockets(ice_config_t * config)1919 int connection_setup_sockets (ice_config_t *config)
1920 {
1921     static int sockets_setup = 2;
1922     int count = 0, socket_count = 0, socket_attempt = 0, arr_size;
1923     listener_t *listener, **prev;
1924 
1925     global_lock();
1926 
1927     listener = config->listen_sock;
1928     prev = &config->listen_sock;
1929     arr_size = count = global.server_sockets;
1930     if (sockets_setup == 1)
1931     {
1932         // in case of changowner, run through the first time as root, but reject the second run through as that will
1933         // be as a user (initial startup of listening thread). after that it's fine.
1934         sockets_setup--;
1935         global_unlock();
1936         return 0;
1937     }
1938     if (sockets_setup > 0)
1939         sockets_setup--;
1940     get_ssl_certificate (config);
1941     if (count)
1942         INFO1 ("%d listening sockets already open", count);
1943     while (listener)
1944     {
1945         socket_count = 0;
1946         socket_attempt = 0;
1947 
1948         sock_server_t sockets = sock_get_server_sockets (listener->port, listener->bind_address);
1949 
1950         do
1951         {
1952             sock_t sock = SOCK_ERROR;
1953             if (sock_get_next_server_socket (sockets, &sock) < 0)
1954                 break;   // end of any available sockets
1955             socket_attempt++;
1956             if (sock == SOCK_ERROR)
1957                 continue;
1958             /* some win32 setups do not do TCP win scaling well, so allow an override */
1959             if (listener->so_sndbuf)
1960                 sock_set_send_buffer (sock, listener->so_sndbuf);
1961             if (listener->so_mss)
1962                 sock_set_mss (sock, listener->so_mss);
1963             if (sock_listen (sock, listener->qlen) == SOCK_ERROR)
1964             {
1965                 sock_close (sock);
1966                 continue;
1967             }
1968             if (count >= arr_size) // need to resize arrays?
1969             {
1970                 void *tmp;
1971                 arr_size += 10;
1972                 tmp = realloc (global.serversock, (arr_size*sizeof (sock_t)));
1973                 if (tmp) global.serversock = tmp;
1974 
1975                 tmp = realloc (global.server_conn, (arr_size*sizeof (listener_t*)));
1976                 if (tmp) global.server_conn = tmp;
1977             }
1978 
1979             sock_set_blocking (sock, 0);
1980             global.serversock [count] = sock;
1981             global.server_conn [count] = listener;
1982             listener->refcount++;
1983             socket_count++;
1984             count++;
1985         } while(1);
1986 
1987         sock_free_server_sockets (sockets);
1988         if (socket_count != socket_attempt)
1989         {
1990             if (socket_count == 0)
1991             {
1992                 if (listener->bind_address)
1993                     ERROR2 ("Could not create listener socket on port %d bind %s",
1994                             listener->port, listener->bind_address);
1995                 else
1996                     ERROR1 ("Could not create listener socket on port %d", listener->port);
1997             }
1998             if (sockets_setup)
1999             {
2000                 global_unlock();
2001                 ERROR0 ("unable to setup all listening sockets");
2002                 return 0;
2003             }
2004             /* remove failed connection */
2005             *prev = config_clear_listener (listener);
2006             listener = *prev;
2007             continue;
2008         }
2009         if (listener->bind_address)
2010             INFO3 ("%d listener socket(s) for port %d address %s", socket_count, listener->port, listener->bind_address);
2011         else
2012             INFO2 ("%d listener socket(s) for port %d", socket_count, listener->port);
2013 
2014         prev = &listener->next;
2015         listener = listener->next;
2016     }
2017     global.server_sockets = count;
2018     global_unlock();
2019 
2020     if (count)
2021         INFO1 ("%d listening sockets setup complete", count);
2022     else
2023         ERROR0 ("No listening sockets established");
2024     return count;
2025 }
2026 
2027 
connection_reset(connection_t * con,uint64_t time_ms)2028 void connection_reset (connection_t *con, uint64_t time_ms)
2029 {
2030     con->con_time = time_ms/1000;
2031     con->discon.time = con->con_time + 7;
2032     con->sent_bytes = 0;
2033 #ifdef HAVE_OPENSSL
2034     if (con->ssl) { SSL_shutdown (con->ssl); SSL_free (con->ssl); con->ssl = NULL; }
2035 #endif
2036 }
2037 
connection_close(connection_t * con)2038 void connection_close(connection_t *con)
2039 {
2040 #ifdef HAVE_OPENSSL
2041     if (con->ssl) { if ((con->sslflags & 1) == 0) SSL_shutdown (con->ssl); SSL_free (con->ssl); }
2042 #endif
2043     if (con->sock != SOCK_ERROR)
2044         sock_close (con->sock);
2045     free (con->ip);
2046     memset (con, 0, sizeof (connection_t));
2047     con->sock = SOCK_ERROR;
2048 }
2049 
2050