2
* Copyright (C) 2010 Julien BLACHE <jb@jblache.org>
3
* Based on evhttp from libevent 1.4.x
5
* Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
8
* Redistribution and use in source and binary forms, with or without
9
* modification, are permitted provided that the following conditions
11
* 1. Redistributions of source code must retain the above copyright
12
* notice, this list of conditions and the following disclaimer.
13
* 2. Redistributions in binary form must reproduce the above copyright
14
* notice, this list of conditions and the following disclaimer in the
15
* documentation and/or other materials provided with the distribution.
16
* 3. The name of the author may not be used to endorse or promote products
17
* derived from this software without specific prior written permission.
19
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
#ifdef _EVENT_HAVE_SYS_PARAM_H
34
#include <sys/param.h>
36
#ifdef _EVENT_HAVE_SYS_TYPES_H
37
#include <sys/types.h>
40
#ifdef _EVENT_HAVE_SYS_TIME_H
43
#ifdef _EVENT_HAVE_SYS_IOCCOM_H
44
#include <sys/ioccom.h>
48
#include <sys/resource.h>
49
#include <sys/socket.h>
54
#include <sys/queue.h>
57
#include <netinet/in.h>
59
#include <arpa/inet.h>
77
#ifdef _EVENT_HAVE_UNISTD_H
80
#ifdef _EVENT_HAVE_FCNTL_H
84
#undef timeout_pending
85
#undef timeout_initialized
88
/* #define USE_DEBUG */
90
#include "rtsp-internal.h"
93
#define strcasecmp _stricmp
94
#define strncasecmp _strnicmp
95
#define strdup _strdup
98
#ifndef _EVENT_HAVE_GETNAMEINFO
100
#define NI_MAXHOST 1025
102
#define NI_NUMERICHOST 1
103
#define NI_NUMERICSERV 2
106
fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
107
size_t hostlen, char *serv, size_t servlen, int flags)
109
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
114
evutil_snprintf(tmpserv, sizeof(tmpserv),
115
"%d", ntohs(sin->sin_port));
116
ret = evutil_snprintf(serv, servlen, "%s", tmpserv);
117
if ((ret < 0) || (ret >= servlen))
122
if (flags & NI_NUMERICHOST) {
123
ret = evutil_snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
124
if ((ret < 0) || (ret >= hostlen))
130
hp = gethostbyaddr((char *)&sin->sin_addr,
131
sizeof(struct in_addr), AF_INET);
135
ret = evutil_snprintf(host, hostlen, "%s", hp->h_name);
136
if ((ret < 0) || (ret >= hostlen))
147
#ifndef _EVENT_HAVE_GETADDRINFO
153
struct sockaddr *ai_addr;
154
struct addrinfo *ai_next;
157
fake_getaddrinfo(const char *hostname, struct addrinfo *ai)
159
struct hostent *he = NULL;
160
struct sockaddr_in *sa;
162
he = gethostbyname(hostname);
166
ai->ai_family = he ? he->h_addrtype : AF_INET;
167
ai->ai_socktype = SOCK_STREAM;
169
ai->ai_addrlen = sizeof(struct sockaddr_in);
170
if (NULL == (ai->ai_addr = malloc(ai->ai_addrlen)))
172
sa = (struct sockaddr_in*)ai->ai_addr;
173
memset(sa, 0, ai->ai_addrlen);
175
sa->sin_family = he->h_addrtype;
176
memcpy(&sa->sin_addr, he->h_addr_list[0], he->h_length);
178
sa->sin_family = AF_INET;
179
sa->sin_addr.s_addr = INADDR_ANY;
185
fake_freeaddrinfo(struct addrinfo *ai)
192
#define MIN(a,b) (((a)<(b))?(a):(b))
195
/* wrapper for setting the base from the rtsp server */
196
#define EVRTSP_BASE_SET(x, y) do { \
197
if ((x)->base != NULL) event_base_set((x)->base, y); \
202
static int socket_connect(int fd, const char *address, unsigned short port);
203
static int bind_socket_ai(int family, struct addrinfo *, int reuse);
204
static int bind_socket(int family, const char *, u_short, int reuse);
205
static void name_from_addr(struct sockaddr *, socklen_t, char **, char **);
206
static void evrtsp_connection_start_detectclose(
207
struct evrtsp_connection *evcon);
208
static void evrtsp_connection_stop_detectclose(
209
struct evrtsp_connection *evcon);
210
static void evrtsp_request_dispatch(struct evrtsp_connection* evcon);
211
static void evrtsp_read_firstline(struct evrtsp_connection *evcon,
212
struct evrtsp_request *req);
213
static void evrtsp_read_header(struct evrtsp_connection *evcon,
214
struct evrtsp_request *req);
215
static int evrtsp_add_header_internal(struct evkeyvalq *headers,
216
const char *key, const char *value);
218
void evrtsp_read(int, short, void *);
219
void evrtsp_write(int, short, void *);
221
#ifndef _EVENT_HAVE_STRSEP
222
/* strsep replacement for platforms that lack it. Only works if
223
* del is one character long. */
225
strsep(char **s, const char *del)
228
assert(strlen(del) == 1);
232
d = strstr(tok, del);
243
evrtsp_method(enum evrtsp_cmd_type type)
248
case EVRTSP_REQ_ANNOUNCE:
252
case EVRTSP_REQ_OPTIONS:
256
case EVRTSP_REQ_SETUP:
260
case EVRTSP_REQ_RECORD:
264
case EVRTSP_REQ_PAUSE:
268
case EVRTSP_REQ_GET_PARAMETER:
269
method = "GET_PARAMETER";
272
case EVRTSP_REQ_SET_PARAMETER:
273
method = "SET_PARAMETER";
276
case EVRTSP_REQ_FLUSH:
280
case EVRTSP_REQ_TEARDOWN:
293
evrtsp_add_event(struct event *ev, int timeout, int default_timeout)
298
evutil_timerclear(&tv);
299
tv.tv_sec = timeout != -1 ? timeout : default_timeout;
307
evrtsp_write_buffer(struct evrtsp_connection *evcon,
308
void (*cb)(struct evrtsp_connection *, void *), void *arg)
310
event_debug(("%s: preparing to write buffer\n", __func__));
316
/* check if the event is already pending */
317
if (event_pending(&evcon->ev, EV_WRITE|EV_TIMEOUT, NULL))
318
event_del(&evcon->ev);
320
event_assign(&evcon->ev, evcon->base, evcon->fd, EV_WRITE, evrtsp_write, evcon);
321
evrtsp_add_event(&evcon->ev, evcon->timeout, RTSP_WRITE_TIMEOUT);
325
evrtsp_connected(struct evrtsp_connection *evcon)
327
switch (evcon->state) {
328
case EVCON_DISCONNECTED:
329
case EVCON_CONNECTING:
332
case EVCON_READING_FIRSTLINE:
333
case EVCON_READING_HEADERS:
334
case EVCON_READING_BODY:
335
case EVCON_READING_TRAILER:
343
* Create the headers needed for an RTSP request
346
evrtsp_make_header_request(struct evrtsp_connection *evcon,
347
struct evrtsp_request *req)
351
/* Generate request line */
352
method = evrtsp_method(req->type);
353
evbuffer_add_printf(evcon->output_buffer, "%s %s RTSP/%d.%d\r\n",
354
method, req->uri, req->major, req->minor);
356
/* Content-Length is mandatory, absent means 0 */
357
if ((evbuffer_get_length(req->output_buffer) > 0)
358
&& (evrtsp_find_header(req->output_headers, "Content-Length") == NULL))
361
evutil_snprintf(size, sizeof(size), "%ld",
362
(long)evbuffer_get_length(req->output_buffer));
363
evrtsp_add_header(req->output_headers, "Content-Length", size);
368
evrtsp_make_header(struct evrtsp_connection *evcon, struct evrtsp_request *req)
370
struct evkeyval *header;
372
evrtsp_make_header_request(evcon, req);
374
TAILQ_FOREACH(header, req->output_headers, next) {
375
evbuffer_add_printf(evcon->output_buffer, "%s: %s\r\n",
376
header->key, header->value);
378
evbuffer_add(evcon->output_buffer, "\r\n", 2);
380
if (evbuffer_get_length(req->output_buffer) > 0) {
381
evbuffer_add_buffer(evcon->output_buffer, req->output_buffer);
385
/* Separated host, port and file from URI */
387
int /* FIXME: needed? */
388
evrtsp_hostportfile(char *url, char **phost, u_short *pport, char **pfile)
390
/* XXX not threadsafe. */
391
static char host[1024];
392
static char file[1024];
399
len = strlen(RTSP_PREFIX);
400
if (strncasecmp(url, RTSP_PREFIX, len))
405
/* We might overrun */
406
ret = evutil_snprintf(host, sizeof(host), "%s", url);
407
if ((ret < 0) || (ret >= sizeof(host)))
410
p = strchr(host, '/');
418
/* Generate request file */
421
evutil_snprintf(file, sizeof(file), "/%s", p2);
424
p = strchr(host, ':');
445
evrtsp_connection_fail(struct evrtsp_connection *evcon,
446
enum evrtsp_connection_error error)
448
struct evrtsp_request* req = TAILQ_FIRST(&evcon->requests);
449
void (*cb)(struct evrtsp_request *, void *);
453
/* save the callback for later; the cb might free our object */
455
cb_arg = req->cb_arg;
457
TAILQ_REMOVE(&evcon->requests, req, next);
458
evrtsp_request_free(req);
460
/* xxx: maybe we should fail all requests??? */
462
/* reset the connection */
463
evrtsp_connection_reset(evcon);
465
/* We are trying the next request that was queued on us */
466
if (TAILQ_FIRST(&evcon->requests) != NULL)
467
evrtsp_connection_connect(evcon);
469
/* inform the user */
475
evrtsp_write(int fd, short what, void *arg)
477
struct evrtsp_connection *evcon = arg;
480
if (what == EV_TIMEOUT) {
481
evrtsp_connection_fail(evcon, EVCON_RTSP_TIMEOUT);
485
n = evbuffer_write(evcon->output_buffer, fd);
487
event_debug(("%s: evbuffer_write", __func__));
488
evrtsp_connection_fail(evcon, EVCON_RTSP_EOF);
493
event_debug(("%s: write nothing", __func__));
494
evrtsp_connection_fail(evcon, EVCON_RTSP_EOF);
498
if (evbuffer_get_length(evcon->output_buffer) != 0) {
499
evrtsp_add_event(&evcon->ev,
500
evcon->timeout, RTSP_WRITE_TIMEOUT);
504
/* Activate our call back */
505
if (evcon->cb != NULL)
506
(*evcon->cb)(evcon, evcon->cb_arg);
510
* Advance the connection state.
511
* - If this is an outgoing connection, we've just processed the response;
512
* idle or close the connection.
515
evrtsp_connection_done(struct evrtsp_connection *evcon)
517
struct evrtsp_request *req = TAILQ_FIRST(&evcon->requests);
519
/* idle or close the connection */
520
TAILQ_REMOVE(&evcon->requests, req, next);
523
evcon->state = EVCON_IDLE;
525
if (TAILQ_FIRST(&evcon->requests) != NULL) {
527
* We have more requests; reset the connection
528
* and deal with the next request.
530
if (!evrtsp_connected(evcon))
531
evrtsp_connection_connect(evcon);
533
evrtsp_request_dispatch(evcon);
536
* The connection is going to be persistent, but we
537
* need to detect if the other side closes it.
539
evrtsp_connection_start_detectclose(evcon);
542
/* notify the user of the request */
543
(*req->cb)(req, req->cb_arg);
545
evrtsp_request_free(req);
548
static void /* FIXME: needed? */
549
evrtsp_read_trailer(struct evrtsp_connection *evcon, struct evrtsp_request *req)
551
struct evbuffer *buf = evcon->input_buffer;
553
switch (evrtsp_parse_headers(req, buf)) {
555
evrtsp_connection_fail(evcon, EVCON_RTSP_INVALID_HEADER);
558
event_del(&evcon->ev);
559
evrtsp_connection_done(evcon);
561
case MORE_DATA_EXPECTED:
563
evrtsp_add_event(&evcon->ev, evcon->timeout,
570
evrtsp_read_body(struct evrtsp_connection *evcon, struct evrtsp_request *req)
572
struct evbuffer *buf = evcon->input_buffer;
574
if (req->ntoread < 0) {
575
/* Read until connection close. */
576
evbuffer_add_buffer(req->input_buffer, buf);
577
} else if (evbuffer_get_length(buf) >= req->ntoread) {
578
/* Completed content length */
579
evbuffer_add(req->input_buffer, evbuffer_pullup(buf,-1),
580
(size_t)req->ntoread);
581
evbuffer_drain(buf, (size_t)req->ntoread);
583
evrtsp_connection_done(evcon);
587
event_assign(&evcon->ev, evcon->base, evcon->fd, EV_READ, evrtsp_read, evcon);
588
evrtsp_add_event(&evcon->ev, evcon->timeout, RTSP_READ_TIMEOUT);
592
* Reads data into a buffer structure until no more data
593
* can be read on the file descriptor or we have read all
594
* the data that we wanted to read.
595
* Execute callback when done.
599
evrtsp_read(int fd, short what, void *arg)
601
struct evrtsp_connection *evcon = arg;
602
struct evrtsp_request *req = TAILQ_FIRST(&evcon->requests);
603
struct evbuffer *buf = evcon->input_buffer;
606
if (what == EV_TIMEOUT) {
607
evrtsp_connection_fail(evcon, EVCON_RTSP_TIMEOUT);
610
n = evbuffer_read(buf, fd, -1);
611
event_debug(("%s: got %d on %d\n", __func__, n, fd));
614
if (errno != EINTR && errno != EAGAIN) {
615
event_debug(("%s: evbuffer_read", __func__));
616
evrtsp_connection_fail(evcon, EVCON_RTSP_EOF);
618
evrtsp_add_event(&evcon->ev, evcon->timeout,
623
/* Connection closed */
624
evcon->state = EVCON_DISCONNECTED;
625
evrtsp_connection_done(evcon);
629
switch (evcon->state) {
630
case EVCON_READING_FIRSTLINE:
631
evrtsp_read_firstline(evcon, req);
633
case EVCON_READING_HEADERS:
634
evrtsp_read_header(evcon, req);
636
case EVCON_READING_BODY:
637
evrtsp_read_body(evcon, req);
639
case EVCON_READING_TRAILER:
640
evrtsp_read_trailer(evcon, req);
642
case EVCON_DISCONNECTED:
643
case EVCON_CONNECTING:
647
event_errx(1, "%s: illegal connection state %d",
648
__func__, evcon->state);
653
evrtsp_write_connectioncb(struct evrtsp_connection *evcon, void *arg)
655
/* This is after writing the request to the server */
656
struct evrtsp_request *req = TAILQ_FIRST(&evcon->requests);
659
assert(evcon->state == EVCON_WRITING);
661
/* We are done writing our header and are now expecting the response */
662
req->kind = EVRTSP_RESPONSE;
664
evrtsp_start_read(evcon);
670
* Clean up a connection object
674
evrtsp_connection_free(struct evrtsp_connection *evcon)
676
struct evrtsp_request *req;
678
/* notify interested parties that this connection is going down */
679
if (evcon->fd != -1) {
680
if (evrtsp_connected(evcon) && evcon->closecb != NULL)
681
(*evcon->closecb)(evcon, evcon->closecb_arg);
684
/* remove all requests that might be queued on this connection */
685
while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
686
TAILQ_REMOVE(&evcon->requests, req, next);
687
evrtsp_request_free(req);
690
if (event_initialized(&evcon->close_ev))
691
event_del(&evcon->close_ev);
693
if (event_initialized(&evcon->ev))
694
event_del(&evcon->ev);
697
EVUTIL_CLOSESOCKET(evcon->fd);
699
if (evcon->bind_address != NULL)
700
free(evcon->bind_address);
702
if (evcon->address != NULL)
703
free(evcon->address);
705
if (evcon->input_buffer != NULL)
706
evbuffer_free(evcon->input_buffer);
708
if (evcon->output_buffer != NULL)
709
evbuffer_free(evcon->output_buffer);
715
evrtsp_request_dispatch(struct evrtsp_connection* evcon)
717
struct evrtsp_request *req = TAILQ_FIRST(&evcon->requests);
719
/* this should not usually happy but it's possible */
723
/* delete possible close detection events */
724
evrtsp_connection_stop_detectclose(evcon);
726
/* we assume that the connection is connected already */
727
assert(evcon->state == EVCON_IDLE);
729
evcon->state = EVCON_WRITING;
731
/* Create the header from the store arguments */
732
evrtsp_make_header(evcon, req);
734
evrtsp_write_buffer(evcon, evrtsp_write_connectioncb, NULL);
737
/* Reset our connection state */
739
evrtsp_connection_reset(struct evrtsp_connection *evcon)
741
if (event_initialized(&evcon->ev))
742
event_del(&evcon->ev);
744
if (evcon->fd != -1) {
745
/* inform interested parties about connection close */
746
if (evrtsp_connected(evcon) && evcon->closecb != NULL)
747
(*evcon->closecb)(evcon, evcon->closecb_arg);
749
EVUTIL_CLOSESOCKET(evcon->fd);
752
evcon->state = EVCON_DISCONNECTED;
754
evbuffer_drain(evcon->input_buffer,
755
evbuffer_get_length(evcon->input_buffer));
756
evbuffer_drain(evcon->output_buffer,
757
evbuffer_get_length(evcon->output_buffer));
761
evrtsp_detect_close_cb(int fd, short what, void *arg)
763
struct evrtsp_connection *evcon = arg;
765
evrtsp_connection_reset(evcon);
769
evrtsp_connection_start_detectclose(struct evrtsp_connection *evcon)
771
evcon->flags |= EVRTSP_CON_CLOSEDETECT;
773
if (event_initialized(&evcon->close_ev))
774
event_del(&evcon->close_ev);
775
event_assign(&evcon->close_ev, evcon->base, evcon->fd, EV_READ,
776
evrtsp_detect_close_cb, evcon);
777
event_add(&evcon->close_ev, NULL);
781
evrtsp_connection_stop_detectclose(struct evrtsp_connection *evcon)
783
evcon->flags &= ~EVRTSP_CON_CLOSEDETECT;
784
event_del(&evcon->close_ev);
788
* Call back for asynchronous connection attempt.
792
evrtsp_connectioncb(int fd, short what, void *arg)
794
struct evrtsp_connection *evcon = arg;
796
socklen_t errsz = sizeof(error);
798
if (what == EV_TIMEOUT) {
799
event_debug(("%s: connection timeout for \"%s:%d\" on %d",
800
__func__, evcon->address, evcon->port, evcon->fd));
804
/* Check if the connection completed */
805
if (getsockopt(evcon->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
807
event_debug(("%s: getsockopt for \"%s:%d\" on %d",
808
__func__, evcon->address, evcon->port, evcon->fd));
813
event_debug(("%s: connect failed for \"%s:%d\" on %d: %s",
814
__func__, evcon->address, evcon->port, evcon->fd,
819
/* We are connected to the server now */
820
event_debug(("%s: connected to \"%s:%d\" on %d\n",
821
__func__, evcon->address, evcon->port, evcon->fd));
823
evcon->state = EVCON_IDLE;
825
/* try to start requests that have queued up on this connection */
826
evrtsp_request_dispatch(evcon);
830
evrtsp_connection_reset(evcon);
832
/* for now, we just signal all requests by executing their callbacks */
833
while (TAILQ_FIRST(&evcon->requests) != NULL) {
834
struct evrtsp_request *request = TAILQ_FIRST(&evcon->requests);
835
TAILQ_REMOVE(&evcon->requests, request, next);
836
request->evcon = NULL;
838
/* we might want to set an error here */
839
request->cb(request, request->cb_arg);
840
evrtsp_request_free(request);
845
* Check if we got a valid response code.
849
evrtsp_valid_response_code(int code)
857
/* Parses the status line of an RTSP server */
860
evrtsp_parse_response_line(struct evrtsp_request *req, char *line)
864
const char *readable = "";
866
protocol = strsep(&line, " ");
869
number = strsep(&line, " ");
873
if (strcmp(protocol, "RTSP/1.0") == 0) {
876
} else if (strcmp(protocol, "RTSP/1.1") == 0) {
880
event_debug(("%s: bad protocol \"%s\"",
881
__func__, protocol));
885
req->response_code = atoi(number);
886
if (!evrtsp_valid_response_code(req->response_code)) {
887
event_debug(("%s: bad response code \"%s\"",
892
if ((req->response_code_line = strdup(readable)) == NULL)
893
event_err(1, "%s: strdup", __func__);
899
evrtsp_find_header(const struct evkeyvalq *headers, const char *key)
901
struct evkeyval *header;
903
TAILQ_FOREACH(header, headers, next) {
904
if (strcasecmp(header->key, key) == 0)
905
return (header->value);
912
evrtsp_clear_headers(struct evkeyvalq *headers)
914
struct evkeyval *header;
916
for (header = TAILQ_FIRST(headers);
918
header = TAILQ_FIRST(headers)) {
919
TAILQ_REMOVE(headers, header, next);
927
* Returns 0, if the header was successfully removed.
928
* Returns -1, if the header could not be found.
932
evrtsp_remove_header(struct evkeyvalq *headers, const char *key)
934
struct evkeyval *header;
936
TAILQ_FOREACH(header, headers, next) {
937
if (strcasecmp(header->key, key) == 0)
944
/* Free and remove the header that we found */
945
TAILQ_REMOVE(headers, header, next);
954
evrtsp_header_is_valid_value(const char *value)
956
const char *p = value;
958
while ((p = strpbrk(p, "\r\n")) != NULL) {
959
/* we really expect only one new line */
960
p += strspn(p, "\r\n");
961
/* we expect a space or tab for continuation */
962
if (*p != ' ' && *p != '\t')
969
evrtsp_add_header(struct evkeyvalq *headers,
970
const char *key, const char *value)
972
event_debug(("%s: key: %s val: %s\n", __func__, key, value));
974
if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
975
/* drop illegal headers */
976
event_debug(("%s: dropping illegal header key\n", __func__));
980
if (!evrtsp_header_is_valid_value(value)) {
981
event_debug(("%s: dropping illegal header value\n", __func__));
985
return (evrtsp_add_header_internal(headers, key, value));
989
evrtsp_add_header_internal(struct evkeyvalq *headers,
990
const char *key, const char *value)
992
struct evkeyval *header = calloc(1, sizeof(struct evkeyval));
994
if (header == NULL) {
995
event_warn("%s: calloc", __func__);
998
if ((header->key = strdup(key)) == NULL) {
1000
event_warn("%s: strdup", __func__);
1003
if ((header->value = strdup(value)) == NULL) {
1006
event_warn("%s: strdup", __func__);
1010
TAILQ_INSERT_TAIL(headers, header, next);
1016
* Parses header lines from a request or a response into the specified
1017
* request object given an event buffer.
1020
* DATA_CORRUPTED on error
1021
* MORE_DATA_EXPECTED when we need to read more headers
1022
* ALL_DATA_READ when all headers have been read.
1025
enum message_read_status
1026
evrtsp_parse_firstline(struct evrtsp_request *req, struct evbuffer *buffer)
1029
enum message_read_status status = ALL_DATA_READ;
1031
line = evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY);
1033
return (MORE_DATA_EXPECTED);
1035
switch (req->kind) {
1036
case EVRTSP_RESPONSE:
1037
if (evrtsp_parse_response_line(req, line) == -1)
1038
status = DATA_CORRUPTED;
1041
status = DATA_CORRUPTED;
1049
evrtsp_append_to_last_header(struct evkeyvalq *headers, const char *line)
1051
struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
1053
size_t old_len, line_len;
1058
old_len = strlen(header->value);
1059
line_len = strlen(line);
1061
newval = realloc(header->value, old_len + line_len + 1);
1065
memcpy(newval + old_len, line, line_len + 1);
1066
header->value = newval;
1071
enum message_read_status
1072
evrtsp_parse_headers(struct evrtsp_request *req, struct evbuffer *buffer)
1075
enum message_read_status status = MORE_DATA_EXPECTED;
1077
struct evkeyvalq *headers = req->input_headers;
1078
while ((line = evbuffer_readln(buffer, NULL, EVBUFFER_EOL_CRLF))
1080
char *skey, *svalue;
1082
if (*line == '\0') { /* Last header - Done */
1083
status = ALL_DATA_READ;
1088
/* Check if this is a continuation line */
1089
if (*line == ' ' || *line == '\t') {
1090
if (evrtsp_append_to_last_header(headers, line) == -1)
1096
/* Processing of header lines */
1098
skey = strsep(&svalue, ":");
1102
svalue += strspn(svalue, " ");
1104
if (evrtsp_add_header(headers, skey, svalue) == -1)
1114
return (DATA_CORRUPTED);
1118
evrtsp_get_body_length(struct evrtsp_request *req)
1120
struct evkeyvalq *headers = req->input_headers;
1121
const char *content_length;
1123
content_length = evrtsp_find_header(headers, "Content-Length");
1125
if (content_length == NULL) {
1126
/* If there is no Content-Length: header, a value of 0 is assumed, per spec. */
1130
ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
1131
if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
1132
event_debug(("%s: illegal content length: %s",
1133
__func__, content_length));
1136
req->ntoread = ntoread;
1139
event_debug(("%s: bytes to read: %lld (in buffer %ld)\n",
1140
__func__, req->ntoread,
1141
evbuffer_get_length(req->evcon->input_buffer)));
1147
evrtsp_get_body(struct evrtsp_connection *evcon, struct evrtsp_request *req)
1149
evcon->state = EVCON_READING_BODY;
1150
if (evrtsp_get_body_length(req) == -1) {
1151
evrtsp_connection_fail(evcon, EVCON_RTSP_INVALID_HEADER);
1155
evrtsp_read_body(evcon, req);
1159
evrtsp_read_firstline(struct evrtsp_connection *evcon,
1160
struct evrtsp_request *req)
1162
enum message_read_status res;
1164
res = evrtsp_parse_firstline(req, evcon->input_buffer);
1165
if (res == DATA_CORRUPTED) {
1166
/* Error while reading, terminate */
1167
event_debug(("%s: bad header lines on %d\n",
1168
__func__, evcon->fd));
1169
evrtsp_connection_fail(evcon, EVCON_RTSP_INVALID_HEADER);
1171
} else if (res == MORE_DATA_EXPECTED) {
1172
/* Need more header lines */
1173
evrtsp_add_event(&evcon->ev,
1174
evcon->timeout, RTSP_READ_TIMEOUT);
1178
evcon->state = EVCON_READING_HEADERS;
1179
evrtsp_read_header(evcon, req);
1183
evrtsp_read_header(struct evrtsp_connection *evcon, struct evrtsp_request *req)
1185
enum message_read_status res;
1188
res = evrtsp_parse_headers(req, evcon->input_buffer);
1189
if (res == DATA_CORRUPTED) {
1190
/* Error while reading, terminate */
1191
event_debug(("%s: bad header lines on %d\n", __func__, fd));
1192
evrtsp_connection_fail(evcon, EVCON_RTSP_INVALID_HEADER);
1194
} else if (res == MORE_DATA_EXPECTED) {
1195
/* Need more header lines */
1196
evrtsp_add_event(&evcon->ev,
1197
evcon->timeout, RTSP_READ_TIMEOUT);
1201
/* Done reading headers, do the real work */
1202
switch (req->kind) {
1203
case EVRTSP_RESPONSE:
1204
event_debug(("%s: start of read body on %d\n",
1206
evrtsp_get_body(evcon, req);
1210
event_warnx("%s: bad header on %d", __func__, fd);
1211
evrtsp_connection_fail(evcon, EVCON_RTSP_INVALID_HEADER);
1217
* Creates a TCP connection to the specified port and executes a callback
1218
* when finished. Failure or sucess is indicate by the passed connection
1221
* Although this interface accepts a hostname, it is intended to take
1222
* only numeric hostnames so that non-blocking DNS resolution can
1226
struct evrtsp_connection *
1227
evrtsp_connection_new(const char *address, unsigned short port)
1229
struct evrtsp_connection *evcon = NULL;
1232
unsigned char scratch[16];
1235
if ((addr = strdup(address)) == NULL) {
1236
event_warn("%s: strdup failed", __func__);
1240
intf = strchr(addr, '%');
1244
if (inet_pton(AF_INET6, addr, scratch) == 1)
1246
else if (inet_pton(AF_INET, addr, scratch) == 1)
1250
event_warn("%s: address is neither IPv6 nor IPv4", __func__);
1257
event_debug(("Attempting connection to %s:%d\n", address, port));
1259
if ((evcon = calloc(1, sizeof(struct evrtsp_connection))) == NULL) {
1261
event_warn("%s: calloc failed", __func__);
1268
evcon->timeout = -1;
1272
evcon->family = family;
1273
evcon->address = addr;
1275
if ((evcon->input_buffer = evbuffer_new()) == NULL) {
1276
event_warn("%s: evbuffer_new failed", __func__);
1280
if ((evcon->output_buffer = evbuffer_new()) == NULL) {
1281
event_warn("%s: evbuffer_new failed", __func__);
1285
evcon->state = EVCON_DISCONNECTED;
1286
TAILQ_INIT(&evcon->requests);
1292
evrtsp_connection_free(evcon);
1296
void evrtsp_connection_set_base(struct evrtsp_connection *evcon,
1297
struct event_base *base)
1299
assert(evcon->base == NULL);
1300
assert(evcon->state == EVCON_DISCONNECTED);
1305
evrtsp_connection_set_timeout(struct evrtsp_connection *evcon,
1306
int timeout_in_secs)
1308
evcon->timeout = timeout_in_secs;
1312
evrtsp_connection_set_closecb(struct evrtsp_connection *evcon,
1313
void (*cb)(struct evrtsp_connection *, void *), void *cbarg)
1315
evcon->closecb = cb;
1316
evcon->closecb_arg = cbarg;
1320
evrtsp_connection_get_local_address(struct evrtsp_connection *evcon,
1321
char **address, u_short *port)
1324
struct sockaddr_storage ss;
1326
struct sockaddr_in sin;
1327
struct sockaddr_in6 sin6;
1335
if (!evrtsp_connected(evcon))
1338
slen = sizeof(struct sockaddr_storage);
1339
ret = getsockname(evcon->fd, &addr.sa, &slen);
1343
name_from_addr(&addr.sa, slen, address, NULL);
1348
switch (addr.ss.ss_family)
1351
*port = ntohs(addr.sin.sin_port);
1356
*port = ntohs(addr.sin6.sin6_port);
1364
event_err(1, "%s: unhandled address family\n", __func__);
1370
evrtsp_connection_get_peer(struct evrtsp_connection *evcon,
1371
char **address, u_short *port)
1373
*address = evcon->address;
1374
*port = evcon->port;
1378
evrtsp_connection_connect(struct evrtsp_connection *evcon)
1380
if (evcon->state == EVCON_CONNECTING)
1383
evrtsp_connection_reset(evcon);
1385
evcon->fd = bind_socket(evcon->family,
1386
evcon->bind_address, evcon->bind_port, 0 /*reuse*/);
1387
if (evcon->fd == -1) {
1388
event_debug(("%s: failed to bind to \"%s\"",
1389
__func__, evcon->bind_address));
1393
if (socket_connect(evcon->fd, evcon->address, evcon->port) == -1) {
1394
EVUTIL_CLOSESOCKET(evcon->fd); evcon->fd = -1;
1398
/* Set up a callback for successful connection setup */
1399
event_assign(&evcon->ev, evcon->base, evcon->fd, EV_WRITE, evrtsp_connectioncb, evcon);
1400
evrtsp_add_event(&evcon->ev, evcon->timeout, RTSP_CONNECT_TIMEOUT);
1402
evcon->state = EVCON_CONNECTING;
1408
* Starts an RTSP request on the provided evrtsp_connection object.
1409
* If the connection object is not connected to the server already,
1410
* this will start the connection.
1414
evrtsp_make_request(struct evrtsp_connection *evcon,
1415
struct evrtsp_request *req,
1416
enum evrtsp_cmd_type type, const char *uri)
1418
/* We are making a request */
1419
req->kind = EVRTSP_REQUEST;
1421
if (req->uri != NULL)
1423
if ((req->uri = strdup(uri)) == NULL)
1424
event_err(1, "%s: strdup", __func__);
1426
/* Set the protocol version if it is not supplied */
1427
if (!req->major && !req->minor) {
1432
assert(req->evcon == NULL);
1434
assert(!(req->flags & EVRTSP_REQ_OWN_CONNECTION));
1436
TAILQ_INSERT_TAIL(&evcon->requests, req, next);
1438
/* If the connection object is not connected; make it so */
1439
if (!evrtsp_connected(evcon))
1440
return (evrtsp_connection_connect(evcon));
1443
* If it's connected already and we are the first in the queue,
1444
* then we can dispatch this request immediately. Otherwise, it
1445
* will be dispatched once the pending requests are completed.
1447
if (TAILQ_FIRST(&evcon->requests) == req)
1448
evrtsp_request_dispatch(evcon);
1454
* Reads data from file descriptor into request structure
1455
* Request structure needs to be set up correctly.
1459
evrtsp_start_read(struct evrtsp_connection *evcon)
1461
/* Set up an event to read the headers */
1462
if (event_initialized(&evcon->ev))
1463
event_del(&evcon->ev);
1464
event_assign(&evcon->ev, evcon->base, evcon->fd, EV_READ, evrtsp_read, evcon);
1465
evrtsp_add_event(&evcon->ev, evcon->timeout, RTSP_READ_TIMEOUT);
1466
evcon->state = EVCON_READING_FIRSTLINE;
1470
evrtsp_send_done(struct evrtsp_connection *evcon, void *arg)
1472
struct evrtsp_request *req = TAILQ_FIRST(&evcon->requests);
1473
TAILQ_REMOVE(&evcon->requests, req, next);
1475
/* delete possible close detection events */
1476
evrtsp_connection_stop_detectclose(evcon);
1478
assert(req->flags & EVRTSP_REQ_OWN_CONNECTION);
1479
evrtsp_request_free(req);
1482
/* Requires that headers and response code are already set up */
1485
evrtsp_send(struct evrtsp_request *req, struct evbuffer *databuf)
1487
struct evrtsp_connection *evcon = req->evcon;
1489
if (evcon == NULL) {
1490
evrtsp_request_free(req);
1494
assert(TAILQ_FIRST(&evcon->requests) == req);
1496
/* xxx: not sure if we really should expose the data buffer this way */
1497
if (databuf != NULL)
1498
evbuffer_add_buffer(req->output_buffer, databuf);
1500
/* Adds headers to the response */
1501
evrtsp_make_header(evcon, req);
1503
evrtsp_write_buffer(evcon, evrtsp_send_done, NULL);
1507
* Request related functions
1510
struct evrtsp_request *
1511
evrtsp_request_new(void (*cb)(struct evrtsp_request *, void *), void *arg)
1513
struct evrtsp_request *req = NULL;
1515
/* Allocate request structure */
1516
if ((req = calloc(1, sizeof(struct evrtsp_request))) == NULL) {
1517
event_warn("%s: calloc", __func__);
1521
req->kind = EVRTSP_RESPONSE;
1522
req->input_headers = calloc(1, sizeof(struct evkeyvalq));
1523
if (req->input_headers == NULL) {
1524
event_warn("%s: calloc", __func__);
1527
TAILQ_INIT(req->input_headers);
1529
req->output_headers = calloc(1, sizeof(struct evkeyvalq));
1530
if (req->output_headers == NULL) {
1531
event_warn("%s: calloc", __func__);
1534
TAILQ_INIT(req->output_headers);
1536
if ((req->input_buffer = evbuffer_new()) == NULL) {
1537
event_warn("%s: evbuffer_new", __func__);
1541
if ((req->output_buffer = evbuffer_new()) == NULL) {
1542
event_warn("%s: evbuffer_new", __func__);
1553
evrtsp_request_free(req);
1558
evrtsp_request_free(struct evrtsp_request *req)
1560
if (req->uri != NULL)
1562
if (req->response_code_line != NULL)
1563
free(req->response_code_line);
1565
evrtsp_clear_headers(req->input_headers);
1566
free(req->input_headers);
1568
evrtsp_clear_headers(req->output_headers);
1569
free(req->output_headers);
1571
if (req->input_buffer != NULL)
1572
evbuffer_free(req->input_buffer);
1574
if (req->output_buffer != NULL)
1575
evbuffer_free(req->output_buffer);
1581
* Allows for inspection of the request URI
1585
evrtsp_request_uri(struct evrtsp_request *req) {
1586
if (req->uri == NULL)
1587
event_debug(("%s: request %p has no uri\n", __func__, req));
1592
* Network helper functions that we do not want to export to the rest of
1596
static struct addrinfo *
1597
addr_from_name(char *address)
1599
#ifdef _EVENT_HAVE_GETADDRINFO
1600
struct addrinfo ai, *aitop;
1603
memset(&ai, 0, sizeof(ai));
1604
ai.ai_family = AF_INET;
1605
ai.ai_socktype = SOCK_RAW;
1607
if ((ai_result = getaddrinfo(address, NULL, &ai, &aitop)) != 0) {
1608
if ( ai_result == EAI_SYSTEM )
1609
event_warn("getaddrinfo");
1611
event_warnx("getaddrinfo: %s", gai_strerror(ai_result));
1617
return NULL; /* XXXXX Use gethostbyname, if this function is ever used. */
1623
name_from_addr(struct sockaddr *sa, socklen_t salen,
1624
char **phost, char **pport)
1626
char ntop[NI_MAXHOST];
1627
char strport[NI_MAXSERV];
1630
#ifdef _EVENT_HAVE_GETNAMEINFO
1631
ni_result = getnameinfo(sa, salen,
1632
ntop, sizeof(ntop), strport, sizeof(strport),
1633
NI_NUMERICHOST|NI_NUMERICSERV);
1635
if (ni_result != 0) {
1636
if (ni_result == EAI_SYSTEM)
1637
event_err(1, "getnameinfo failed");
1639
event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
1643
ni_result = fake_getnameinfo(sa, salen,
1644
ntop, sizeof(ntop), strport, sizeof(strport),
1645
NI_NUMERICHOST|NI_NUMERICSERV);
1650
*phost = strdup(ntop);
1652
*pport = strdup(strport);
1655
/* Create a non-blocking socket and bind it */
1656
/* todo: rename this function */
1658
bind_socket_ai(int family, struct addrinfo *ai, int reuse)
1664
family = ai->ai_family;
1666
/* Create listen socket */
1667
fd = socket(family, SOCK_STREAM, 0);
1669
event_warn("socket");
1673
if (evutil_make_socket_nonblocking(fd) < 0)
1677
if (fcntl(fd, F_SETFD, 1) == -1) {
1678
event_warn("fcntl(F_SETFD)");
1683
if (family == AF_INET6)
1684
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1686
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1688
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1689
(void *)&on, sizeof(on));
1693
r = bind(fd, ai->ai_addr, ai->ai_addrlen);
1701
serrno = EVUTIL_SOCKET_ERROR();
1702
EVUTIL_CLOSESOCKET(fd);
1703
EVUTIL_SET_SOCKET_ERROR(serrno);
1707
static struct addrinfo *
1708
make_addrinfo(const char *address, u_short port)
1710
struct addrinfo *aitop = NULL;
1712
#ifdef _EVENT_HAVE_GETADDRINFO
1714
char strport[NI_MAXSERV];
1717
memset(&ai, 0, sizeof(ai));
1718
ai.ai_family = AF_UNSPEC;
1719
ai.ai_socktype = SOCK_STREAM;
1720
ai.ai_flags = AI_PASSIVE; /* turn NULL host name into INADDR_ANY */
1721
evutil_snprintf(strport, sizeof(strport), "%d", port);
1722
if ((ai_result = getaddrinfo(address, strport, &ai, &aitop)) != 0) {
1723
if ( ai_result == EAI_SYSTEM )
1724
event_warn("getaddrinfo");
1726
event_warnx("getaddrinfo: %s", gai_strerror(ai_result));
1731
static struct addrinfo ai[2]; /* We will be returning the address of some of this memory so it has to last even after this call. */
1732
if (++cur == 2) cur = 0; /* allow calling this function twice */
1734
if (fake_getaddrinfo(address, &ai[cur]) < 0) {
1735
event_warn("fake_getaddrinfo");
1739
((struct sockaddr_in *) aitop->ai_addr)->sin_port = htons(port);
1746
bind_socket(int family, const char *address, u_short port, int reuse)
1749
struct addrinfo *aitop = NULL;
1751
/* just create an unbound socket */
1752
if (address == NULL && port == 0)
1753
return bind_socket_ai(family, NULL, 0);
1755
aitop = make_addrinfo(address, port);
1760
fd = bind_socket_ai(family, aitop, reuse);
1762
#ifdef _EVENT_HAVE_GETADDRINFO
1763
freeaddrinfo(aitop);
1765
fake_freeaddrinfo(aitop);
1772
socket_connect(int fd, const char *address, unsigned short port)
1774
struct addrinfo *ai = make_addrinfo(address, port);
1778
event_debug(("%s: make_addrinfo: \"%s:%d\"",
1779
__func__, address, port));
1783
if (connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
1785
int tmp_error = WSAGetLastError();
1786
if (tmp_error != WSAEWOULDBLOCK && tmp_error != WSAEINVAL &&
1787
tmp_error != WSAEINPROGRESS) {
1791
if (errno != EINPROGRESS) {
1797
/* everything is fine */
1801
#ifdef _EVENT_HAVE_GETADDRINFO
1804
fake_freeaddrinfo(ai);