connection.c 17.5 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
35

#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 "format.h"
#include "logging.h"
36
#include "xslt.h"
Jack Moffitt's avatar
Jack Moffitt committed
37
38
39
40
41
42
43
44
45
46
47

#include "source.h"

#define CATMODULE "connection"

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

typedef struct _thread_queue_tag {
Michael Smith's avatar
Michael Smith committed
48
	thread_t *thread_id;
Jack Moffitt's avatar
Jack Moffitt committed
49
50
51
52
53
54
55
56
57
58
59
60
61
	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;

62
rwlock_t _source_shutdown_rwlock;
Jack Moffitt's avatar
Jack Moffitt committed
63
64
65
66
67
68
69
70
71
72
73

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);
74
    thread_cond_create(&global.shutdown_cond);
Jack Moffitt's avatar
Jack Moffitt committed
75
76
77
78
79
80
81
82

	_initialized = 1;
}

void connection_shutdown(void)
{
	if (!_initialized) return;
	
83
    thread_cond_destroy(&global.shutdown_cond);
Jack Moffitt's avatar
Jack Moffitt committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
	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;
}

103
104
105
106
107
108
109
110
111
112
113
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;
	return con;
}

Jack Moffitt's avatar
Jack Moffitt committed
114
115
116
117
118
119
static connection_t *_accept_connection(void)
{
	int sock;
	connection_t *con;
	char *ip;

120
    if (util_timed_wait_for_fd(global.serversock, 30) <= 0) {
Jack Moffitt's avatar
Jack Moffitt committed
121
122
123
124
125
126
127
128
		return NULL;
	}

	/* malloc enough room for 123.123.123.123\0 */
	ip = (char *)malloc(16);

	sock = sock_accept(global.serversock, ip, 16);
	if (sock >= 0) {
129
		con = create_connection(sock, ip);
Jack Moffitt's avatar
Jack Moffitt committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

		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);
}

Michael Smith's avatar
Michael Smith committed
161
static void _push_thread(thread_queue_t **queue, thread_t *thread_id)
Jack Moffitt's avatar
Jack Moffitt committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
{
	/* 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);
}

Michael Smith's avatar
Michael Smith committed
179
static thread_t *_pop_thread(thread_queue_t **queue)
Jack Moffitt's avatar
Jack Moffitt committed
180
{
Michael Smith's avatar
Michael Smith committed
181
	thread_t *id;
Jack Moffitt's avatar
Jack Moffitt committed
182
183
184
185
186
187
188
	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
189
		return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
	}

	*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
205
206
	int i;
    thread_t *tid;
Jack Moffitt's avatar
Jack Moffitt committed
207
208
209
210
211
212
	char buff[64];

	config = config_get_config();

	for (i = 0; i < config->threadpool_size; i++) {
		snprintf(buff, 64, "Connection Thread #%d", i);
213
		tid = thread_create(buff, _handle_connection, NULL, THREAD_ATTACHED);
Jack Moffitt's avatar
Jack Moffitt committed
214
215
216
217
218
219
		_push_thread(&_conhands, tid);
	}
}

static void _destroy_pool(void)
{
Michael Smith's avatar
Michael Smith committed
220
	thread_t *id;
Jack Moffitt's avatar
Jack Moffitt committed
221
222
223
224
225
226
	int i;

	i = 0;

	thread_cond_broadcast(&_pool_cond);
	id = _pop_thread(&_conhands);
Michael Smith's avatar
Michael Smith committed
227
	while (id != NULL) {
Jack Moffitt's avatar
Jack Moffitt committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
		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();
		}
	}

249
250
251
    /* Give all the other threads notification to shut down */
    thread_cond_broadcast(&global.shutdown_cond);

Jack Moffitt's avatar
Jack Moffitt committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
	_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;
}

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
int connection_create_source(connection_t *con, http_parser_t *parser, char *mount) {
	source_t *source;
	char *contenttype;
	/* check to make sure this source wouldn't
	** be over the limit
	*/
	global_lock();
	if (global.sources >= config_get_config()->source_limit) {
		INFO1("Source (%s) logged in, but there are too many sources", mount);
		global_unlock();
		return 0;
	}
	global.sources++;
	global_unlock();
	
	stats_event_inc(NULL, "sources");

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

	if (contenttype != NULL) {
		format_type_t format = format_get_type(contenttype);
		if (format < 0) {
			WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
312
            goto fail;
313
314
315
316
317
		} else {
			source = source_create(con, parser, mount, format);
		}
	} else {
		WARN0("No content-type header, cannot handle source");
318
        goto fail;
319
320
321
322
323
	}
	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;
324
325
326
327
328
329
330
331

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

    stats_event_dec(NULL, "sources");
    return 0;
332
333
}

Jack Moffitt's avatar
Jack Moffitt committed
334
335
336
337
338
339
340
341
342
343
344
static void *_handle_connection(void *arg)
{
	char header[4096];
	connection_t *con;
	http_parser_t *parser;
	source_t *source;
	stats_connection_t *stats;
	avl_node *node;
	http_var_t *var;
	client_t *client;
	int bytes;
345
	struct stat statbuf;
346
	char *fullpath;
347
    char *uri;
Jack Moffitt's avatar
Jack Moffitt committed
348
349
350
351
352
353
354
355

	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 */
356
		while ((con = _get_connection())) {
357
			stats_event_inc(NULL, "connections");
Jack Moffitt's avatar
Jack Moffitt committed
358

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

361
362
363
			/* 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
364
365
366
367
				connection_close(con);
				continue;
			}

368
369
370
371
			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
372
				
373
				if (strcmp("ICE", httpp_getvar(parser, HTTPP_VAR_PROTOCOL)) != 0 && strcmp("HTTP", httpp_getvar(parser, HTTPP_VAR_PROTOCOL)) != 0) {
374
                    ERROR0("Bad HTTP protocol detected");
Jack Moffitt's avatar
Jack Moffitt committed
375
376
377
378
379
					connection_close(con);
					httpp_destroy(parser);
					continue;
				}

380
381
                uri = httpp_getvar(parser, HTTPP_VAR_URI);

382
				if (parser->req_type == httpp_req_source) {
383
                    INFO1("Source logging in at mountpoint \"%s\"", uri);
384
					stats_event_inc(NULL, "source_connections");
Jack Moffitt's avatar
Jack Moffitt committed
385
				
386
					if (strcmp((httpp_getvar(parser, "ice-password") != NULL) ? httpp_getvar(parser, "ice-password") : "", (config_get_config()->source_password != NULL) ? config_get_config()->source_password : "") != 0) {
387
						INFO1("Source (%s) attempted to login with bad password", uri);
388
389
390
391
						connection_close(con);
						httpp_destroy(parser);
						continue;
					}
Jack Moffitt's avatar
Jack Moffitt committed
392

393
394
395
396
397
					/* check to make sure this source has
					** a unique mountpoint
					*/

					avl_tree_rlock(global.source_tree);
398
399
					if (source_find_mount(uri) != NULL) {
						INFO1("Source tried to log in as %s, but is already used", uri);
400
401
402
403
404
405
						connection_close(con);
						httpp_destroy(parser);
						avl_tree_unlock(global.source_tree);
						continue;
					}
					avl_tree_unlock(global.source_tree);
Jack Moffitt's avatar
Jack Moffitt committed
406

407
					if (!connection_create_source(con, parser, uri)) {
408
409
410
411
						connection_close(con);
						httpp_destroy(parser);
					}

Jack Moffitt's avatar
Jack Moffitt committed
412
					continue;
413
414
415
416
				} else if (parser->req_type == httpp_req_stats) {
					stats_event_inc(NULL, "stats_connections");
					
					if (strcmp((httpp_getvar(parser, "ice-password") != NULL) ? httpp_getvar(parser, "ice-password") : "", (config_get_config()->source_password != NULL) ? config_get_config()->source_password : "") != 0) {
417
                        ERROR0("Bad password for stats connection");
418
419
420
						connection_close(con);
						httpp_destroy(parser);
						continue;
Jack Moffitt's avatar
Jack Moffitt committed
421
					}
422
423
424
425
426
427
428
429
430
431
					
					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);
					
Jack Moffitt's avatar
Jack Moffitt committed
432
					continue;
433
				} else if (parser->req_type == httpp_req_play || parser->req_type == httpp_req_get) {
434
                    DEBUG0("Client connected");
435
436
437
438
439
440
441
442
443
444
445
446
447

					/* 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)
					** stats clients, which are looking for /stats.xml
					** and director server authorizers, which are looking for /GUID-xxxxxxxx (where xxxxxx is the GUID in question
					** we need to handle the latter two before the former, as the latter two
					** aren't subject to the limits.
					*/
					// TODO: add GUID-xxxxxx
448
					if (strcmp(uri, "/stats.xml") == 0) {
449
                        DEBUG0("Stats request, sending xml stats");
450
						stats_sendxml(client);
451
452
453
454
455
456
457
458
                        client_destroy(client);
						continue;
					}

					/* Here we are parsing the URI request to see
					** if the extension is .xsl, if so, then process
					** this request as an XSLT request
					*/
459
460
                    fullpath = util_get_path_from_uri(uri);
					if (fullpath && util_check_valid_extension(fullpath) == XSLT_CONTENT) {
461
						/* If the file exists, then transform it, otherwise, write a 404 error */
462
						if (stat(fullpath, &statbuf) == 0) {
463
                            DEBUG0("Stats request, sending XSL transformed stats");
464
465
							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;
466
                            stats_transform_xslt(client, fullpath);
467
468
						}
						else {
469
							bytes = sock_write(client->con->sock, "HTTP/1.0 404 File Not Found\r\nContent-Type: text/html\r\n\r\n"\
470
								   "<b>The file you requested could not be found.</b>\r\n");
471
                            if(bytes > 0) client->con->sent_bytes = bytes;
472
473
						}
						client_destroy(client);
474
475
						continue;
					}
476

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
                    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\nContent-Type: audio/x-mpegurl\r\n\r\nhttp://%s:%d%s", 
                                    config_get_config()->hostname, 
                                    config_get_config()->port,
                                    sourceuri
                                    );
                        }
                        else {
                            client->respcode = 404;
                            bytes = sock_write(client->con->sock,
                                    "HTTP/1.0 404 Not Found\r\nContent-Type: text/html\r\n<b>The file you requested could not be found</b>\r\n");
                        }
						avl_tree_unlock(global.source_tree);
                        if(bytes > 0) client->con->sent_bytes = bytes;
						client_destroy(client);
						continue;
                    }

					if (strcmp(uri, "/allstreams.txt") == 0) {
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
						if (strcmp((httpp_getvar(parser, "ice-password") != NULL) ? httpp_getvar(parser, "ice-password") : "", (config_get_config()->source_password != NULL) ? config_get_config()->source_password : "") != 0) {
							INFO0("Client attempted to fetch allstreams.txt with bad password");
							if (parser->req_type == httpp_req_get) {
								client->respcode = 404;
								bytes = sock_write(client->con->sock, "HTTP/1.0 404 Source Not Found\r\nContent-Type: text/html\r\n\r\n"\
										   "<b>The source you requested could not be found.</b>\r\n");
								if (bytes > 0) client->con->sent_bytes = bytes;
							}
						} else {
							avl_node *node;
							source_t *s;
							avl_tree_rlock(global.source_tree);
							node = avl_get_first(global.source_tree);
							while (node) {
								s = (source_t *)node->key;
519
520
521
522
523
524
								bytes = sock_write(client->con->sock, "%s\r\n", s->mount);
                                if(bytes > 0) 
                                    client->con->sent_bytes += bytes;
                                else 
                                    break;

525
526
527
528
529
530
531
								node = avl_get_next(node);
							}
							avl_tree_unlock(global.source_tree);
						}
						client_destroy(client);
						continue;
					}
532
					
Jack Moffitt's avatar
Jack Moffitt committed
533
534
535
536
537
538
539
540
541
542
543
544
545
					global_lock();
					if (global.clients >= config_get_config()->client_limit) {
						if (parser->req_type == httpp_req_get) {
							client->respcode = 504;
							bytes = sock_write(client->con->sock, "HTTP/1.0 504 Server Full\r\nContent-Type: text/html\r\n\r\n"\
									   "<b>The server is already full.  Try again later.</b>\r\n");
							if (bytes > 0) client->con->sent_bytes = bytes;
						}
						client_destroy(client);
						global_unlock();
						continue;
					}
					global_unlock();
546
547
					
					avl_tree_rlock(global.source_tree);
548
					source = source_find_mount(uri);
549
					if (source) {
550
                        DEBUG0("Source found for client");
551
552
553
554
555
556
557
558
						
						global_lock();
						if (global.clients >= config_get_config()->client_limit) {
							if (parser->req_type == httpp_req_get) {
								client->respcode = 504;
								bytes = sock_write(client->con->sock, "HTTP/1.0 504 Server Full\r\nContent-Type: text/html\r\n\r\n"\
										   "<b>The server is already full.  Try again later.</b>\r\n");
								if (bytes > 0) client->con->sent_bytes = bytes;
Jack Moffitt's avatar
Jack Moffitt committed
559
							}
560
561
562
							client_destroy(client);
							global_unlock();
							continue;
Jack Moffitt's avatar
Jack Moffitt committed
563
						}
564
565
						global.clients++;
						global_unlock();
Jack Moffitt's avatar
Jack Moffitt committed
566
						
567
568
						if (parser->req_type == httpp_req_get) {
							client->respcode = 200;
569
570
							bytes = sock_write(client->con->sock, "HTTP/1.0 200 OK\r\nContent-Type: %s\r\n", format_get_mimetype(source->format->type));
                            if(bytes > 0) client->con->sent_bytes += bytes;
571
572
573
574
575
576
							/* iterate through source http headers and send to client */
							avl_tree_rlock(source->parser->vars);
							node = avl_get_first(source->parser->vars);
							while (node) {
								var = (http_var_t *)node->key;
								if (strcasecmp(var->name, "ice-password") && !strncasecmp("ice-", var->name, 4)) {
577
578
									bytes = sock_write(client->con->sock, "%s: %s\r\n", var->name, var->value);
                                    if(bytes > 0) client->con->sent_bytes += bytes;
579
580
581
582
583
								}
								node = avl_get_next(node);
							}
							avl_tree_unlock(source->parser->vars);
							
584
585
							bytes = sock_write(client->con->sock, "\r\n");
                            if(bytes > 0) client->con->sent_bytes += bytes;
586
587
588
589
590
591
592
							
							sock_set_blocking(client->con->sock, SOCK_NONBLOCK);
						}
						
						avl_tree_wlock(source->pending_tree);
						avl_insert(source->pending_tree, (void *)client);
						avl_tree_unlock(source->pending_tree);
Jack Moffitt's avatar
Jack Moffitt committed
593
					}
594
595
596
597
					
					avl_tree_unlock(global.source_tree);
					
					if (!source) {
598
                        DEBUG0("Source not found for client");
599
600
601
602
603
604
605
						if (parser->req_type == httpp_req_get) {
							client->respcode = 404;
							bytes = sock_write(client->con->sock, "HTTP/1.0 404 Source Not Found\r\nContent-Type: text/html\r\n\r\n"\
									   "<b>The source you requested could not be found.</b>\r\n");
							if (bytes > 0) client->con->sent_bytes = bytes;
						}
						client_destroy(client);
Jack Moffitt's avatar
Jack Moffitt committed
606
					}
607
608
609
					
					continue;
				} else {
610
                    ERROR0("Wrong request type from client");
611
612
613
					connection_close(con);
					httpp_destroy(parser);
					continue;
Jack Moffitt's avatar
Jack Moffitt committed
614
615
				}
			} else {
616
                ERROR0("HTTP request parsing failed");
Jack Moffitt's avatar
Jack Moffitt committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
				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);
}