connection.c 24.9 KB
Newer Older
Jack Moffitt's avatar
Jack Moffitt committed
1 2 3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
4
#include <time.h>
Jack Moffitt's avatar
Jack Moffitt committed
5
#include <sys/types.h>
6
#include <sys/stat.h>
7 8 9

#ifndef _WIN32
#include <sys/time.h>
Jack Moffitt's avatar
Jack Moffitt committed
10 11
#include <sys/socket.h>
#include <netinet/in.h>
12
#else
13
#include <winsock2.h>
14 15
#define snprintf _snprintf
#define strcasecmp stricmp
16
#define strncasecmp strnicmp
17
#endif
Jack Moffitt's avatar
Jack Moffitt committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

#include "os.h"

#include "thread.h"
#include "avl.h"
#include "sock.h"
#include "log.h"
#include "httpp.h"

#include "config.h"
#include "global.h"
#include "util.h"
#include "connection.h"
#include "refbuf.h"
#include "client.h"
#include "stats.h"
#include "logging.h"
35
#include "xslt.h"
36
#include "fserve.h"
37 38

#include "yp.h"
Jack Moffitt's avatar
Jack Moffitt committed
39
#include "source.h"
40
#include "geturl.h"
41
#include "format.h"
42
#include "format_mp3.h"
43
#include "event.h"
Jack Moffitt's avatar
Jack Moffitt committed
44 45 46 47 48 49 50 51 52

#define CATMODULE "connection"

typedef struct con_queue_tag {
	connection_t *con;
	struct con_queue_tag *next;
} con_queue_t;

typedef struct _thread_queue_tag {
53
	thread_type *thread_id;
Jack Moffitt's avatar
Jack Moffitt committed
54 55 56 57 58 59 60 61 62 63 64 65 66
	struct _thread_queue_tag *next;
} thread_queue_t;

static mutex_t _connection_mutex;
static unsigned long _current_id = 0;
static int _initialized = 0;
static cond_t _pool_cond;

static con_queue_t *_queue = NULL;
static mutex_t _queue_mutex;

static thread_queue_t *_conhands = NULL;

67
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
68 69 70 71 72 73 74 75 76 77 78

static void *_handle_connection(void *arg);

void connection_initialize(void)
{
	if (_initialized) return;
	
	thread_mutex_create(&_connection_mutex);
	thread_mutex_create(&_queue_mutex);
	thread_rwlock_create(&_source_shutdown_rwlock);
	thread_cond_create(&_pool_cond);
79
    thread_cond_create(&global.shutdown_cond);
Jack Moffitt's avatar
Jack Moffitt committed
80 81 82 83 84 85 86 87

	_initialized = 1;
}

void connection_shutdown(void)
{
	if (!_initialized) return;
	
88
    thread_cond_destroy(&global.shutdown_cond);
Jack Moffitt's avatar
Jack Moffitt committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
	thread_cond_destroy(&_pool_cond);
	thread_rwlock_destroy(&_source_shutdown_rwlock);
	thread_mutex_destroy(&_queue_mutex);
	thread_mutex_destroy(&_connection_mutex);

	_initialized = 0;
}

static unsigned long _next_connection_id(void)
{
	unsigned long id;

	thread_mutex_lock(&_connection_mutex);
	id = _current_id++;
	thread_mutex_unlock(&_connection_mutex);

	return id;
}

108 109 110 111 112 113 114 115
connection_t *create_connection(sock_t sock, char *ip) {
	connection_t *con;
	con = (connection_t *)malloc(sizeof(connection_t));
	memset(con, 0, sizeof(connection_t));
	con->sock = sock;
	con->con_time = time(NULL);
	con->id = _next_connection_id();
	con->ip = ip;
116 117 118 119

    con->event_number = EVENT_NO_EVENT;
    con->event = NULL;

120 121 122
	return con;
}

Jack Moffitt's avatar
Jack Moffitt committed
123 124 125 126 127 128
static connection_t *_accept_connection(void)
{
	int sock;
	connection_t *con;
	char *ip;

129
    if (util_timed_wait_for_fd(global.serversock, 100) <= 0) {
Jack Moffitt's avatar
Jack Moffitt committed
130 131 132
		return NULL;
	}

133
	/* malloc enough room for a full IP address (including ipv6) */
134
	ip = (char *)malloc(MAX_ADDR_LEN);
Jack Moffitt's avatar
Jack Moffitt committed
135

136
	sock = sock_accept(global.serversock, ip, MAX_ADDR_LEN);
Jack Moffitt's avatar
Jack Moffitt committed
137
	if (sock >= 0) {
138
		con = create_connection(sock, ip);
Jack Moffitt's avatar
Jack Moffitt committed
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

		return con;
	}

	if (!sock_recoverable(sock_error()))
		WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
	
	free(ip);

	return NULL;
}

static void _add_connection(connection_t *con)
{
	con_queue_t *node;

	node = (con_queue_t *)malloc(sizeof(con_queue_t));
	
	thread_mutex_lock(&_queue_mutex);
	node->con = con;
	node->next = _queue;
	_queue = node;
	thread_mutex_unlock(&_queue_mutex);

}

static void _signal_pool(void)
{
	thread_cond_signal(&_pool_cond);
}

170
static void _push_thread(thread_queue_t **queue, thread_type *thread_id)
Jack Moffitt's avatar
Jack Moffitt committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
{
	/* create item */
	thread_queue_t *item = (thread_queue_t *)malloc(sizeof(thread_queue_t));
	item->thread_id = thread_id;
	item->next = NULL;


	thread_mutex_lock(&_queue_mutex);
	if (*queue == NULL) {
		*queue = item;
	} else {
		item->next = *queue;
		*queue = item;
	}
	thread_mutex_unlock(&_queue_mutex);
}

188
static thread_type *_pop_thread(thread_queue_t **queue)
Jack Moffitt's avatar
Jack Moffitt committed
189
{
190
	thread_type *id;
Jack Moffitt's avatar
Jack Moffitt committed
191 192 193 194 195 196 197
	thread_queue_t *item;

	thread_mutex_lock(&_queue_mutex);

	item = *queue;
	if (item == NULL) {
		thread_mutex_unlock(&_queue_mutex);
Michael Smith's avatar
Michael Smith committed
198
		return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	}

	*queue = item->next;
	item->next = NULL;
	id = item->thread_id;
	free(item);

	thread_mutex_unlock(&_queue_mutex);

	return id;
}

static void _build_pool(void)
{
	ice_config_t *config;
Michael Smith's avatar
Michael Smith committed
214
	int i;
215
    thread_type *tid;
Jack Moffitt's avatar
Jack Moffitt committed
216
	char buff[64];
217
    int threadpool_size;
Jack Moffitt's avatar
Jack Moffitt committed
218 219

	config = config_get_config();
220 221
    threadpool_size = config->threadpool_size;
    config_release_config();
Jack Moffitt's avatar
Jack Moffitt committed
222

223
	for (i = 0; i < threadpool_size; i++) {
Jack Moffitt's avatar
Jack Moffitt committed
224
		snprintf(buff, 64, "Connection Thread #%d", i);
225
		tid = thread_create(buff, _handle_connection, NULL, THREAD_ATTACHED);
Jack Moffitt's avatar
Jack Moffitt committed
226 227 228 229 230 231
		_push_thread(&_conhands, tid);
	}
}

static void _destroy_pool(void)
{
232
	thread_type *id;
Jack Moffitt's avatar
Jack Moffitt committed
233 234 235 236 237 238
	int i;

	i = 0;

	thread_cond_broadcast(&_pool_cond);
	id = _pop_thread(&_conhands);
Michael Smith's avatar
Michael Smith committed
239
	while (id != NULL) {
Jack Moffitt's avatar
Jack Moffitt committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
		thread_join(id);
		_signal_pool();
		id = _pop_thread(&_conhands);
	}
}

void connection_accept_loop(void)
{
	connection_t *con;

	_build_pool();

	while (global.running == ICE_RUNNING) {
		con = _accept_connection();

		if (con) {
			_add_connection(con);
			_signal_pool();
		}
	}

261 262 263
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

Jack Moffitt's avatar
Jack Moffitt committed
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
	_destroy_pool();

	/* wait for all the sources to shutdown */
	thread_rwlock_wlock(&_source_shutdown_rwlock);
	thread_rwlock_unlock(&_source_shutdown_rwlock);
}

static connection_t *_get_connection(void)
{
	con_queue_t *node = NULL;
	con_queue_t *oldnode = NULL;
	connection_t *con = NULL;

	thread_mutex_lock(&_queue_mutex);
	if (_queue) {
		node = _queue;
		while (node->next) {
			oldnode = node;
			node = node->next;
		}
		
		/* node is now the last node
		** and oldnode is the previous one, or NULL
		*/
		if (oldnode) oldnode->next = NULL;
		else (_queue) = NULL;
	}
	thread_mutex_unlock(&_queue_mutex);

	if (node) {
		con = node->con;
		free(node);
	}

	return con;
}

301 302 303 304 305 306 307 308 309 310
void connection_inject_event(int eventnum, void *event_data) {
    connection_t *con = calloc(1, sizeof(connection_t));

    con->event_number = eventnum;
    con->event = event_data;

    _add_connection(con);
    _signal_pool();
}

311 312 313
/* TODO: Make this return an appropriate error code so that we can use HTTP
 * codes where appropriate
 */
314
int connection_create_source(client_t *client, connection_t *con, http_parser_t *parser, char *mount) {
315 316
	source_t *source;
	char *contenttype;
Michael Smith's avatar
Michael Smith committed
317
    mount_proxy *mountproxy, *mountinfo = NULL;
318 319 320 321 322 323
    int source_limit;
    ice_config_t *config;

    config = config_get_config();
    source_limit = config->source_limit;
    config_release_config();
324

325 326 327 328
	/* check to make sure this source wouldn't
	** be over the limit
	*/
	global_lock();
329
	if (global.sources >= source_limit) {
330 331 332 333 334 335
		INFO1("Source (%s) logged in, but there are too many sources", mount);
		global_unlock();
		return 0;
	}
	global.sources++;
	global_unlock();
336

337
	stats_event_inc(NULL, "sources");
Michael Smith's avatar
Michael Smith committed
338
    
339 340 341 342 343
    config = config_get_config();
    mountproxy = config->mounts;
    thread_mutex_lock(&(config_locks()->mounts_lock));
    config_release_config();

Michael Smith's avatar
Michael Smith committed
344 345 346 347 348 349 350
    while(mountproxy) {
        if(!strcmp(mountproxy->mountname, mount)) {
            mountinfo = mountproxy;
            break;
        }
        mountproxy = mountproxy->next;
    }
351 352 353 354 355

	contenttype = httpp_getvar(parser, "content-type");

	if (contenttype != NULL) {
		format_type_t format = format_get_type(contenttype);
356
		if (format == FORMAT_ERROR) {
357
			WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
358
            thread_mutex_unlock(&(config_locks()->mounts_lock));
359
            goto fail;
360
		} else {
Michael Smith's avatar
Michael Smith committed
361 362
			source = source_create(client, con, parser, mount, 
                    format, mountinfo);
363
            thread_mutex_unlock(&(config_locks()->mounts_lock));
364 365
		}
	} else {
366
        format_type_t format = FORMAT_TYPE_MP3;
367
		ERROR0("No content-type header, falling back to backwards compatibility mode for icecast 1.x relays. Assuming content is mp3.");
Michael Smith's avatar
Michael Smith committed
368
        source = source_create(client, con, parser, mount, format, mountinfo);
369
        thread_mutex_unlock(&(config_locks()->mounts_lock));
370
	}
371

372
    source->send_return = 1;
373 374 375 376
	source->shutdown_rwlock = &_source_shutdown_rwlock;
	sock_set_blocking(con->sock, SOCK_NONBLOCK);
	thread_create("Source Thread", source_main, (void *)source, THREAD_DETACHED);
	return 1;
377 378 379 380 381 382 383 384

fail:
    global_lock();
    global.sources--;
    global_unlock();

    stats_event_dec(NULL, "sources");
    return 0;
385 386
}

387 388
static int _check_pass_http(http_parser_t *parser, 
        char *correctuser, char *correctpass)
389 390 391 392 393 394 395 396 397 398 399 400 401
{
    /* This will look something like "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" */
    char *header = httpp_getvar(parser, "authorization");
    char *userpass, *tmp;
    char *username, *password;

    if(header == NULL)
        return 0;

    if(strncmp(header, "Basic ", 6))
        return 0;

    userpass = util_base64_decode(header+6);
402 403 404
    if(userpass == NULL) {
        WARN1("Base64 decode of Authorization header \"%s\" failed",
                header+6);
405
        return 0;
406
    }
407 408 409 410 411 412 413 414 415 416

    tmp = strchr(userpass, ':');
    if(!tmp) {
        free(userpass);
        return 0;
    }
    *tmp = 0;
    username = userpass;
    password = tmp+1;

417
    if(strcmp(username, correctuser) || strcmp(password, correctpass)) {
418 419 420
        free(userpass);
        return 0;
    }
421
    free(userpass);
422 423 424 425

    return 1;
}

426
static int _check_pass_ice(http_parser_t *parser, char *correctpass)
427
{
428
    char *password;
429 430 431 432 433 434 435 436 437 438 439

    password = httpp_getvar(parser, "ice-password");
    if(!password)
        password = "";

	if (strcmp(password, correctpass))
        return 0;
    else
        return 1;
}

440
static int _check_relay_pass(http_parser_t *parser)
441
{
442 443
    ice_config_t *config = config_get_config();
    char *pass = config->relay_password;
444
    if(!pass)
445 446
        pass = config->source_password;
    config_release_config();
447 448 449 450

    return _check_pass_http(parser, "relay", pass);
}

451 452
static int _check_admin_pass(http_parser_t *parser)
{
453 454 455 456 457
    ice_config_t *config = config_get_config();
    char *pass = config->admin_password;
    char *user = config->admin_username;
    config_release_config();

458 459 460 461 462 463 464
    if(!pass || !user)
        return 0;

    return _check_pass_http(parser, "admin", pass);
}

static int _check_source_pass(http_parser_t *parser, char *mount)
465
{
466 467
    ice_config_t *config = config_get_config();
    char *pass = config->source_password;
468
    char *user = "source";
469
    int ret;
470 471 472 473 474
    int ice_login = config->ice_login;

    mount_proxy *mountinfo = config->mounts;
    thread_mutex_lock(&(config_locks()->mounts_lock));
    config_release_config();
475

476 477
    while(mountinfo) {
        if(!strcmp(mountinfo->mountname, mount)) {
478 479 480 481
            if(mountinfo->password)
                pass = mountinfo->password;
            if(mountinfo->username)
                user = mountinfo->username;
482 483
            break;
        }
484
        mountinfo = mountinfo->next;
485 486
    }

487 488
    thread_mutex_unlock(&(config_locks()->mounts_lock));

489 490 491 492 493 494
    if(!pass) {
        WARN0("No source password set, rejecting source");
        return 0;
    }

    ret = _check_pass_http(parser, user, pass);
495
    if(!ret && ice_login)
496 497 498 499 500 501 502
    {
        ret = _check_pass_ice(parser, pass);
        if(ret)
            WARN0("Source is using deprecated icecast login");
    }

    return ret;
503 504
}

Michael Smith's avatar
Michael Smith committed
505 506 507 508 509 510
static void handle_fallback_request(client_t *client)
{
    source_t *source;
    char *mount, *value, *old;
    int bytes;

511 512 513 514
    mount = httpp_get_query_param(client->parser, "mount");
    value = httpp_get_query_param(client->parser, "fallback");

    if(!_check_source_pass(client->parser, mount)) {
Michael Smith's avatar
Michael Smith committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528
		INFO0("Bad or missing password on fallback configuration request");
        client_send_401(client);
        return;
    }

    if(value == NULL || mount == NULL) {
        client_send_400(client, "Missing parameter");
        return;
    }

    avl_tree_rlock(global.source_tree);
    source = source_find_mount(mount);
    avl_tree_unlock(global.source_tree);

529 530 531 532 533
    if(source == NULL) {
        client_send_400(client, "Current source not found");
        return;
    }

Michael Smith's avatar
Michael Smith committed
534 535 536 537 538 539 540 541 542 543 544 545
    old = source->fallback_mount;
    source->fallback_mount = strdup(value);
    free(old);

    client->respcode = 200;
	bytes = sock_write(client->con->sock, 
            "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"
            "Fallback configured");
    if(bytes > 0) client->con->sent_bytes = bytes;
    client_destroy(client);
}

546 547 548 549 550 551 552 553 554
static void handle_metadata_request(client_t *client)
{
    source_t *source;
    char *action;
    char *mount;
    char *value;
    mp3_state *state;
    int bytes;

555 556 557 558 559
    action = httpp_get_query_param(client->parser, "mode");
    mount = httpp_get_query_param(client->parser, "mount");
    value = httpp_get_query_param(client->parser, "song");

    if(!_check_source_pass(client->parser, mount)) {
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
		INFO0("Metadata request with wrong or missing password");
        client_send_401(client);
        return;
    }

    if(value == NULL || action == NULL || mount == NULL) {
        client_send_400(client, "Missing parameter");
        return;
    }

    avl_tree_rlock(global.source_tree);
    source = source_find_mount(mount);
    avl_tree_unlock(global.source_tree);

    if(source == NULL) {
        client_send_400(client, "No such mountpoint");
        return;
    }

    if(source->format->type != FORMAT_TYPE_MP3) {
        client_send_400(client, "Not mp3, cannot update metadata");
        return;
    }

    if(strcmp(action, "updinfo") != 0) {
        client_send_400(client, "No such action");
        return;
    }

    state = source->format->_state;
    thread_mutex_lock(&(state->lock));
    free(state->metadata);
    state->metadata = strdup(value);
    state->metadata_age++;
594
    state->metadata_raw = 0;
595 596 597
    thread_mutex_unlock(&(state->lock));

    DEBUG2("Metadata on mountpoint %s changed to \"%s\"", mount, value);
598
    stats_event(mount, "title", value);
599 600 601 602 603 604 605 606
    client->respcode = 200;
	bytes = sock_write(client->con->sock, 
            "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"
            "Update successful");
    if(bytes > 0) client->con->sent_bytes = bytes;
    client_destroy(client);
}

607 608 609
static void _handle_source_request(connection_t *con, 
        http_parser_t *parser, char *uri)
{
610 611 612 613
    client_t *client;

	client = client_create(con, parser);

614 615 616
    INFO1("Source logging in at mountpoint \"%s\"", uri);
    stats_event_inc(NULL, "source_connections");
				
617
	if (!_check_source_pass(parser, uri)) {
618
		INFO1("Source (%s) attempted to login with invalid or missing password", uri);
619
        client_send_401(client);
620 621 622 623 624 625 626 627 628
        return;
	}

	/* check to make sure this source has
	** a unique mountpoint
	*/

	avl_tree_rlock(global.source_tree);
	if (source_find_mount(uri) != NULL) {
629
		avl_tree_unlock(global.source_tree);
630
		INFO1("Source tried to log in as %s, but mountpoint is already used", uri);
631
        client_send_404(client, "Mountpoint in use");
632 633 634 635
		return;
	}
	avl_tree_unlock(global.source_tree);

636
	if (!connection_create_source(client, con, parser, uri)) {
637
        client_send_404(client, "Mountpoint in use");
638 639 640 641 642
	}
}

static void _handle_stats_request(connection_t *con, 
        http_parser_t *parser, char *uri)
Jack Moffitt's avatar
Jack Moffitt committed
643 644
{
	stats_connection_t *stats;
645 646 647

	stats_event_inc(NULL, "stats_connections");
				
648
	if (!_check_admin_pass(parser)) {
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        ERROR0("Bad password for stats connection");
		connection_close(con);
		httpp_destroy(parser);
        return;
	}
					
	stats_event_inc(NULL, "stats");
					
	/* create stats connection and create stats handler thread */
	stats = (stats_connection_t *)malloc(sizeof(stats_connection_t));
	stats->parser = parser;
	stats->con = con;
					
	thread_create("Stats Connection", stats_connection, (void *)stats, THREAD_DETACHED);
}

static void _handle_get_request(connection_t *con,
        http_parser_t *parser, char *uri)
{
    char *fullpath;
	client_t *client;
    int bytes;
671
	struct stat statbuf;
672
	source_t *source;
673 674 675 676 677 678 679 680 681 682 683 684 685
    int fileserve;
    char *host;
    int port;
    ice_config_t *config;
    int client_limit;

    config = config_get_config();
    fileserve = config->fileserve;
    host = config->hostname;
    port = config->port;
    client_limit = config->client_limit;
    config_release_config();

686 687 688 689 690 691 692 693 694

    DEBUG0("Client connected");

	/* make a client */
	client = client_create(con, parser);
	stats_event_inc(NULL, "client_connections");
					
	/* there are several types of HTTP GET clients
	** media clients, which are looking for a source (eg, URI = /stream.ogg)
695
	** stats clients, which are looking for /admin/stats.xml
696 697 698 699 700 701
	** and director server authorizers, which are looking for /GUID-xxxxxxxx 
    ** (where xxxxxx is the GUID in question) - this isn't implemented yet.
	** we need to handle the latter two before the former, as the latter two
	** aren't subject to the limits.
	*/
	/* TODO: add GUID-xxxxxx */
702
	if (strcmp(uri, "/admin/stats.xml") == 0) {
703
	    if (!_check_admin_pass(parser)) {
704
		    INFO0("Request for /admin/stats.xml with incorrect or no password");
705 706 707
            client_send_401(client);
            return;
    	}
708 709 710 711 712 713
        DEBUG0("Stats request, sending xml stats");
		stats_sendxml(client);
        client_destroy(client);
        return;
    }

714 715 716 717 718 719
    if(strcmp(uri, "/admin/metadata") == 0) {
        DEBUG0("Got metadata update request");
        handle_metadata_request(client);
        return;
    }

Michael Smith's avatar
Michael Smith committed
720 721 722 723 724 725
    if(strcmp(uri, "/admin/fallbacks") == 0) {
        DEBUG0("Got fallback request");
        handle_fallback_request(client);
        return;
    }

726 727 728 729 730 731 732 733 734
	/* Here we are parsing the URI request to see
	** if the extension is .xsl, if so, then process
	** this request as an XSLT request
	*/
    fullpath = util_get_path_from_normalised_uri(uri);
    if (util_check_valid_extension(fullpath) == XSLT_CONTENT) {
    	/* If the file exists, then transform it, otherwise, write a 404 */
    	if (stat(fullpath, &statbuf) == 0) {
            DEBUG0("Stats request, sending XSL transformed stats");
735
            client->respcode = 200;
736 737 738 739 740 741 742 743 744 745 746 747
		    bytes = sock_write(client->con->sock, 
                    "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n");
            if(bytes > 0) client->con->sent_bytes = bytes;
            stats_transform_xslt(client, fullpath);
		    client_destroy(client);
    	}
	    else {
            client_send_404(client, "The file you requested could not be found");
    	}
        free(fullpath);
        return;
	}
748 749
    else if(fileserve && stat(fullpath, &statbuf) == 0) 
    {
750
        fserve_client_create(client, fullpath);
751 752 753
        free(fullpath);
        return;
    }
754 755 756 757 758 759 760 761 762 763 764 765 766 767
    free(fullpath);

    if(strcmp(util_get_extension(uri), "m3u") == 0) {
        char *sourceuri = strdup(uri);
        char *dot = strrchr(sourceuri, '.');
        *dot = 0;
	    avl_tree_rlock(global.source_tree);
    	source = source_find_mount(sourceuri);
	   	if (source) {
            client->respcode = 200;
            bytes = sock_write(client->con->sock,
                    "HTTP/1.0 200 OK\r\n"
                    "Content-Type: audio/x-mpegurl\r\n\r\n"
                    "http://%s:%d%s", 
768 769
                    host, 
                    port,
770 771 772 773 774
                    sourceuri
                    );
            if(bytes > 0) client->con->sent_bytes = bytes;
    	    client_destroy(client);
        }
775
        else if(fileserve) {
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
            fullpath = util_get_path_from_normalised_uri(sourceuri);
            if(stat(fullpath, &statbuf) == 0) {
                fserve_client_create(client, fullpath);
                free(fullpath);
            }
            else {
                free(fullpath);
                fullpath = util_get_path_from_normalised_uri(uri);
                if(stat(fullpath, &statbuf) == 0) {
                    fserve_client_create(client, fullpath);
                    free(fullpath);
                }
                else {
                    free(fullpath);
                    client_send_404(client, 
                            "The file you requested could not be found");
                }
            }
        }
795 796 797 798 799 800 801 802
        else {
            client_send_404(client, "The file you requested could not be found");
        }
		avl_tree_unlock(global.source_tree);
        free(sourceuri);
        return;
    }

803
	if (strcmp(uri, "/admin/streamlist") == 0) {
804
		if (!_check_relay_pass(parser)) {
805
			INFO0("Client attempted to fetch /admin/streamlist with bad password");
806
            client_send_401(client);
807
		} else {
808 809 810
			avl_node *node;
			source_t *s;

811 812 813 814 815
            client->respcode = 200;
            bytes = sock_write(client->con->sock,
                    "HTTP/1.0 200 OK\r\n\r\n");
            if(bytes > 0) client->con->sent_bytes = bytes;

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
			avl_tree_rlock(global.source_tree);
			node = avl_get_first(global.source_tree);
			while (node) {
				s = (source_t *)node->key;
				bytes = sock_write(client->con->sock, "%s\r\n", s->mount);
                if(bytes > 0) client->con->sent_bytes += bytes;
                else break;

				node = avl_get_next(node);
			}
			avl_tree_unlock(global.source_tree);
		    client_destroy(client);
		}
        return;
	}
				
	global_lock();
833
	if (global.clients >= client_limit) {
Michael Smith's avatar
Michael Smith committed
834 835
        client_send_504(client,
                "The server is already full. Try again later.");
836 837 838 839 840 841 842 843 844 845 846
		global_unlock();
        return;
	}
	global_unlock();
					
	avl_tree_rlock(global.source_tree);
	source = source_find_mount(uri);
	if (source) {
        DEBUG0("Source found for client");
						
		global_lock();
847
		if (global.clients >= client_limit) {
Michael Smith's avatar
Michael Smith committed
848 849
            client_send_504(client, 
                    "The server is already full. Try again later.");
850 851 852 853
			global_unlock();
            avl_tree_unlock(global.source_tree);
            return;
		}
Michael Smith's avatar
Michael Smith committed
854 855 856 857 858 859 860 861 862
        else if(source->max_listeners != -1 && 
                source->listeners >= source->max_listeners) 
        {
            client_send_504(client, 
                    "Too many clients on this mountpoint. Try again later.");
			global_unlock();
            avl_tree_unlock(global.source_tree);
            return;
        }
863 864 865
		global.clients++;
		global_unlock();
						
866 867 868 869
        client->format_data = source->format->create_client_data(
                source->format, source, client);

        source->format->client_send_headers(source->format, source, client);
870 871 872 873 874
						
		bytes = sock_write(client->con->sock, "\r\n");
        if(bytes > 0) client->con->sent_bytes += bytes;
							
    	sock_set_blocking(client->con->sock, SOCK_NONBLOCK);
875
        sock_set_nodelay(client->con->sock);
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
						
		avl_tree_wlock(source->pending_tree);
		avl_insert(source->pending_tree, (void *)client);
		avl_tree_unlock(source->pending_tree);
	}
					
	avl_tree_unlock(global.source_tree);
					
	if (!source) {
        DEBUG0("Source not found for client");
        client_send_404(client, "The source you requested could not be found.");
	}
}

static void *_handle_connection(void *arg)
{
	char header[4096];
	connection_t *con;
	http_parser_t *parser;
895
    char *rawuri, *uri;
896
	client_t *client;
Jack Moffitt's avatar
Jack Moffitt committed
897 898 899 900 901 902 903 904

	while (global.running == ICE_RUNNING) {
		memset(header, 0, 4096);

		thread_cond_wait(&_pool_cond);
		if (global.running != ICE_RUNNING) break;

		/* grab a connection and set the socket to blocking */
905
		while ((con = _get_connection())) {
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

            /* Handle meta-connections */
            if(con->event_number > 0) {
                switch(con->event_number) {
                    case EVENT_CONFIG_READ:
                        event_config_read(con->event);
                        break;
                    default:
                        ERROR1("Unknown event number: %d", con->event_number);
                        break;
                }
                free(con);
                continue;
            }

921
			stats_event_inc(NULL, "connections");
Jack Moffitt's avatar
Jack Moffitt committed
922

923
			sock_set_blocking(con->sock, SOCK_BLOCK);
Jack Moffitt's avatar
Jack Moffitt committed
924

925 926 927
			/* fill header with the http header */
			if (util_read_header(con->sock, header, 4096) == 0) {
				/* either we didn't get a complete header, or we timed out */
Jack Moffitt's avatar
Jack Moffitt committed
928 929 930 931
				connection_close(con);
				continue;
			}

932 933 934 935
			parser = httpp_create_parser();
			httpp_initialize(parser, NULL);
			if (httpp_parse(parser, header, strlen(header))) {
				/* handle the connection or something */
Jack Moffitt's avatar
Jack Moffitt committed
936
				
937 938
				if (strcmp("ICE",  httpp_getvar(parser, HTTPP_VAR_PROTOCOL)) &&
                    strcmp("HTTP", httpp_getvar(parser, HTTPP_VAR_PROTOCOL))) {
939
                    ERROR0("Bad HTTP protocol detected");
Jack Moffitt's avatar
Jack Moffitt committed
940 941 942 943 944
					connection_close(con);
					httpp_destroy(parser);
					continue;
				}

945 946 947 948 949
                rawuri = httpp_getvar(parser, HTTPP_VAR_URI);
                uri = util_normalise_uri(rawuri);

                if(!uri) {
					client = client_create(con, parser);
950
                    client_send_404(client, "The path you requested was invalid");
951 952
                    continue;
                }
953

954
				if (parser->req_type == httpp_req_source) {
955 956 957 958 959 960 961 962 963
                    _handle_source_request(con, parser, uri);
                }
                else if (parser->req_type == httpp_req_stats) {
                    _handle_stats_request(con, parser, uri);
                }
                else if (parser->req_type == httpp_req_get) {
                    _handle_get_request(con, parser, uri);
                }
                else {
964
                    ERROR0("Wrong request type from client");
965 966
					connection_close(con);
					httpp_destroy(parser);
967 968 969
                }

                free(uri);
Jack Moffitt's avatar
Jack Moffitt committed
970
			} else {
971
                ERROR0("HTTP request parsing failed");
Jack Moffitt's avatar
Jack Moffitt committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
				connection_close(con);
				httpp_destroy(parser);
				continue;
			}
		}
	}

	thread_exit(0);

	return NULL;
}

void connection_close(connection_t *con)
{
	sock_close(con->sock);
	if (con->ip) free(con->ip);
	if (con->host) free(con->host);
	free(con);
}