2 * Copyright (C) <2005-2009> Wim Taymans <wim.taymans@gmail.com>
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
20 * Unless otherwise indicated, Source Code is licensed under MIT license.
21 * See further explanation attached in License Statement (distributed in the file
24 * Permission is hereby granted, free of charge, to any person obtaining a copy of
25 * this software and associated documentation files (the "Software"), to deal in
26 * the Software without restriction, including without limitation the rights to
27 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
28 * of the Software, and to permit persons to whom the Software is furnished to do
29 * so, subject to the following conditions:
31 * The above copyright notice and this permission notice shall be included in all
32 * copies or substantial portions of the Software.
34 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 * SECTION:gstrtspconnection
45 * @short_description: manage RTSP connections
46 * @see_also: gstrtspurl
48 * This object manages the RTSP connection to the server. It provides function
49 * to receive and send bytes and messages.
51 * Last reviewed on 2007-07-24 (0.10.14)
64 /* we include this here to get the G_OS_* defines */
68 #include "gstrtspconnection.h"
74 struct sockaddr_in sa_in;
75 struct sockaddr_in6 sa_in6;
76 struct sockaddr_storage sa_stor;
84 guchar out[3]; /* the size must be evenly divisible by 3 */
90 #define SEND_FLAGS MSG_NOSIGNAL
100 TUNNEL_STATE_COMPLETE
101 } GstRTSPTunnelState;
103 #define TUNNELID_LEN 24
105 struct _GstRTSPConnection
108 /* URL for the connection */
111 /* connection state */
112 GSocket *read_socket;
113 GSocket *write_socket;
114 gboolean manual_http;
115 GSocket *socket0, *socket1;
116 GCancellable *cancellable;
118 gchar tunnelid[TUNNELID_LEN];
120 GstRTSPTunnelState tstate;
126 gchar *initial_buffer;
127 gsize initial_buffer_offset;
130 gint cseq; /* sequence number */
131 gchar session_id[512]; /* session id */
132 gint timeout; /* session timeout in seconds */
133 GTimer *timer; /* timeout timer */
136 GstRTSPAuthMethod auth_method;
139 GHashTable *auth_params;
160 READ_AHEAD_EOH = -1, /* end of headers */
161 READ_AHEAD_CRLF = -2,
162 READ_AHEAD_CRLFCR = -3
165 /* a structure for constructing RTSPMessages */
169 GstRTSPResult status;
179 build_reset (GstRTSPBuilder * builder)
181 g_free (builder->body_data);
182 memset (builder, 0, sizeof (GstRTSPBuilder));
186 * gst_rtsp_connection_create:
187 * @url: a #GstRTSPUrl
188 * @conn: (out) (transfer full): storage for a #GstRTSPConnection
190 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
191 * The connection will not yet attempt to connect to @url, use
192 * gst_rtsp_connection_connect().
194 * A copy of @url will be made.
196 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
199 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
201 GstRTSPConnection *newconn;
203 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
205 newconn = g_new0 (GstRTSPConnection, 1);
207 newconn->cancellable = g_cancellable_new ();
209 newconn->url = gst_rtsp_url_copy (url);
210 newconn->timer = g_timer_new ();
211 newconn->timeout = 60;
214 newconn->auth_method = GST_RTSP_AUTH_NONE;
215 newconn->username = NULL;
216 newconn->passwd = NULL;
217 newconn->auth_params = NULL;
225 * gst_rtsp_connection_create_from_socket:
226 * @socket: a #GSocket
227 * @ip: the IP address of the other end
228 * @port: the port used by the other end
229 * @initial_buffer: data already read from @fd
230 * @conn: (out) (transfer full): storage for a #GstRTSPConnection
232 * Create a new #GstRTSPConnection for handling communication on the existing
233 * socket @socket. The @initial_buffer contains any data already read from
234 * @socket which should be used before starting to read new data.
236 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
239 gst_rtsp_connection_create_from_socket (GSocket * socket, const gchar * ip,
240 guint16 port, const gchar * initial_buffer, GstRTSPConnection ** conn)
242 GstRTSPConnection *newconn = NULL;
246 g_return_val_if_fail (G_IS_SOCKET (socket), GST_RTSP_EINVAL);
247 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
248 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
250 /* set to non-blocking mode so that we can cancel the communication */
251 g_socket_set_blocking (socket, FALSE);
253 /* create a url for the client address */
254 url = g_new0 (GstRTSPUrl, 1);
255 url->host = g_strdup (ip);
258 /* now create the connection object */
259 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
260 gst_rtsp_url_free (url);
262 /* both read and write initially */
263 newconn->socket0 = G_SOCKET (g_object_ref (socket));
264 newconn->socket1 = G_SOCKET (g_object_ref (socket));
265 newconn->write_socket = newconn->read_socket = newconn->socket0;
267 newconn->ip = g_strdup (ip);
269 newconn->initial_buffer = g_strdup (initial_buffer);
278 gst_rtsp_url_free (url);
284 * gst_rtsp_connection_accept:
286 * @conn: (out) (transfer full): storage for a #GstRTSPConnection
287 * @cancellable: a #GCancellable to cancel the operation
289 * Accept a new connection on @socket and create a new #GstRTSPConnection for
290 * handling communication on new socket.
292 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
295 gst_rtsp_connection_accept (GSocket * socket, GstRTSPConnection ** conn,
296 GCancellable * cancellable)
301 GSocket *client_sock;
302 GSocketAddress *addr;
305 g_return_val_if_fail (G_IS_SOCKET (socket), GST_RTSP_EINVAL);
306 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
308 client_sock = g_socket_accept (socket, cancellable, &err);
312 addr = g_socket_get_remote_address (client_sock, &err);
314 goto getnameinfo_failed;
316 ip = g_inet_address_to_string (g_inet_socket_address_get_address
317 (G_INET_SOCKET_ADDRESS (addr)));
318 port = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
319 g_object_unref (addr);
322 gst_rtsp_connection_create_from_socket (client_sock, ip, port, NULL,
324 g_object_unref (client_sock);
332 GST_DEBUG ("Accepting client failed: %s", err->message);
333 g_clear_error (&err);
334 return GST_RTSP_ESYS;
338 if (!g_socket_close (client_sock, &err)) {
339 GST_DEBUG ("Closing socket failed: %s", err->message);
340 g_clear_error (&err);
342 g_object_unref (client_sock);
343 return GST_RTSP_ERROR;
348 do_resolve (const gchar * host, GCancellable * cancellable)
355 addr = g_inet_address_new_from_string (host);
359 resolver = g_resolver_get_default ();
361 results = g_resolver_lookup_by_name (resolver, host, cancellable, &err);
365 for (l = results; l; l = l->next) {
366 GInetAddress *tmp = l->data;
368 if (g_inet_address_get_family (tmp) == G_SOCKET_FAMILY_IPV4 ||
369 g_inet_address_get_family (tmp) == G_SOCKET_FAMILY_IPV6) {
370 addr = G_INET_ADDRESS (g_object_ref (tmp));
375 g_resolver_free_addresses (results);
376 g_object_unref (resolver);
382 ip = g_inet_address_to_string (addr);
383 g_object_unref (addr);
390 GST_ERROR ("failed to resolve %s: %s", host, err->message);
391 g_clear_error (&err);
392 g_object_unref (resolver);
398 do_connect (const gchar * ip, guint16 port, GSocket ** socket_out,
399 GTimeVal * timeout, GCancellable * cancellable)
404 GSocketAddress *saddr;
407 addr = g_inet_address_new_from_string (ip);
409 saddr = g_inet_socket_address_new (addr, port);
410 g_object_unref (addr);
413 g_socket_new (g_socket_address_get_family (saddr), G_SOCKET_TYPE_STREAM,
414 G_SOCKET_PROTOCOL_TCP, &err);
418 /* set to non-blocking mode so that we can cancel the connect */
419 g_socket_set_blocking (socket, FALSE);
421 /* we are going to connect ASYNC now */
422 if (!g_socket_connect (socket, saddr, cancellable, &err)) {
423 if (!g_error_matches (err, G_IO_ERROR, G_IO_ERROR_PENDING))
425 g_clear_error (&err);
430 /* wait for connect to complete up to the specified timeout or until we got
432 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
434 g_socket_set_timeout (socket, (to + GST_SECOND - 1) / GST_SECOND);
435 if (!g_socket_condition_wait (socket, G_IO_OUT, cancellable, &err)) {
436 g_socket_set_timeout (socket, 0);
437 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT))
442 g_socket_set_timeout (socket, 0);
444 if (!g_socket_check_connect_result (socket, &err))
448 g_object_unref (saddr);
450 *socket_out = socket;
457 GST_ERROR ("no socket: %s", err->message);
458 g_clear_error (&err);
459 g_object_unref (saddr);
460 return GST_RTSP_ESYS;
464 GST_ERROR ("system error: %s", err->message);
465 g_clear_error (&err);
466 g_object_unref (saddr);
467 g_object_unref (socket);
468 return GST_RTSP_ESYS;
472 GST_ERROR ("timeout");
473 g_clear_error (&err);
474 g_object_unref (saddr);
475 g_object_unref (socket);
476 return GST_RTSP_ETIMEOUT;
481 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
488 guint16 port, url_port;
492 GstRTSPMessage response;
495 memset (&response, 0, sizeof (response));
496 gst_rtsp_message_init (&response);
498 /* create a random sessionid */
499 for (i = 0; i < TUNNELID_LEN; i++)
500 conn->tunnelid[i] = g_random_int_range ('a', 'z');
501 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
504 /* get the port from the url */
505 gst_rtsp_url_get_port (url, &url_port);
507 if (conn->proxy_host) {
508 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
509 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
510 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
511 ip = conn->proxy_host;
512 port = conn->proxy_port;
514 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
515 url->query ? url->query : "");
521 /* create the GET request for the read connection */
522 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
524 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
526 if (hostparam != NULL)
527 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
528 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
530 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
531 "application/x-rtsp-tunnelled");
532 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
533 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
535 /* we start by writing to this fd */
536 conn->write_socket = conn->socket0;
538 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
539 * request from being base64 encoded */
540 conn->tunneled = FALSE;
541 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
542 gst_rtsp_message_free (msg);
543 conn->tunneled = TRUE;
545 /* receive the response to the GET request */
546 /* we need to temporarily set manual_http to TRUE since
547 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
548 * failure otherwise */
549 old_http = conn->manual_http;
550 conn->manual_http = TRUE;
551 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
553 conn->manual_http = old_http;
555 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
556 response.type_data.response.code != GST_RTSP_STS_OK)
559 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
560 &value, 0) == GST_RTSP_OK) {
561 if (conn->proxy_host) {
562 /* if we use a proxy we need to change the destination url */
564 url->host = g_strdup (value);
566 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
568 /* and resolve the new ip address */
569 if (!(ip = do_resolve (value, conn->cancellable)))
576 /* connect to the host/port */
577 res = do_connect (ip, port, &conn->socket1, timeout, conn->cancellable);
578 if (res != GST_RTSP_OK)
581 /* this is now our writing socket */
582 conn->write_socket = conn->socket1;
584 /* create the POST request for the write connection */
585 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
587 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
589 if (hostparam != NULL)
590 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
591 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
593 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
594 "application/x-rtsp-tunnelled");
595 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
596 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
597 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
598 "Sun, 9 Jan 1972 00:00:00 GMT");
599 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
601 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
602 * request from being base64 encoded */
603 conn->tunneled = FALSE;
604 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
605 gst_rtsp_message_free (msg);
606 conn->tunneled = TRUE;
609 gst_rtsp_message_unset (&response);
618 GST_ERROR ("failed to create request (%d)", res);
623 GST_ERROR ("write failed (%d)", res);
624 gst_rtsp_message_free (msg);
625 conn->tunneled = TRUE;
630 GST_ERROR ("read failed (%d)", res);
631 conn->manual_http = FALSE;
636 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
637 response.type_data.response.reason);
638 res = GST_RTSP_ERROR;
643 GST_ERROR ("could not resolve %s", conn->ip);
649 GST_ERROR ("failed to connect");
655 * gst_rtsp_connection_connect:
656 * @conn: a #GstRTSPConnection
657 * @timeout: a #GTimeVal timeout
659 * Attempt to connect to the url of @conn made with
660 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
661 * forever. If @timeout contains a valid timeout, this function will return
662 * #GST_RTSP_ETIMEOUT after the timeout expired.
664 * This function can be cancelled with gst_rtsp_connection_flush().
666 * Returns: #GST_RTSP_OK when a connection could be made.
669 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
676 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
677 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
678 g_return_val_if_fail (conn->socket0 == NULL, GST_RTSP_EINVAL);
682 if (conn->proxy_host && conn->tunneled) {
683 if (!(ip = do_resolve (conn->proxy_host, conn->cancellable))) {
684 GST_ERROR ("could not resolve %s", conn->proxy_host);
687 port = conn->proxy_port;
688 g_free (conn->proxy_host);
689 conn->proxy_host = ip;
691 if (!(ip = do_resolve (url->host, conn->cancellable))) {
692 GST_ERROR ("could not resolve %s", url->host);
695 /* get the port from the url */
696 gst_rtsp_url_get_port (url, &port);
702 /* connect to the host/port */
703 res = do_connect (ip, port, &conn->socket0, timeout, conn->cancellable);
704 if (res != GST_RTSP_OK)
707 /* this is our read URL */
708 conn->read_socket = conn->socket0;
710 if (conn->tunneled) {
711 res = setup_tunneling (conn, timeout);
712 if (res != GST_RTSP_OK)
713 goto tunneling_failed;
715 conn->write_socket = conn->socket0;
722 return GST_RTSP_ENET;
726 GST_ERROR ("failed to connect");
731 GST_ERROR ("failed to setup tunneling");
737 auth_digest_compute_hex_urp (const gchar * username,
738 const gchar * realm, const gchar * password, gchar hex_urp[33])
740 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
741 const gchar *digest_string;
743 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
744 g_checksum_update (md5_context, (const guchar *) ":", 1);
745 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
746 g_checksum_update (md5_context, (const guchar *) ":", 1);
747 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
748 digest_string = g_checksum_get_string (md5_context);
750 memset (hex_urp, 0, 33);
751 memcpy (hex_urp, digest_string, strlen (digest_string));
753 g_checksum_free (md5_context);
757 auth_digest_compute_response (const gchar * method,
758 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
761 char hex_a2[33] = { 0, };
762 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
763 const gchar *digest_string;
766 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
767 g_checksum_update (md5_context, (const guchar *) ":", 1);
768 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
769 digest_string = g_checksum_get_string (md5_context);
770 memcpy (hex_a2, digest_string, strlen (digest_string));
773 g_checksum_reset (md5_context);
774 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
775 g_checksum_update (md5_context, (const guchar *) ":", 1);
776 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
777 g_checksum_update (md5_context, (const guchar *) ":", 1);
779 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
780 digest_string = g_checksum_get_string (md5_context);
781 memset (response, 0, 33);
782 memcpy (response, digest_string, strlen (digest_string));
784 g_checksum_free (md5_context);
788 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
790 switch (conn->auth_method) {
791 case GST_RTSP_AUTH_BASIC:{
796 if (conn->username == NULL || conn->passwd == NULL)
799 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
800 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
801 auth_string = g_strdup_printf ("Basic %s", user_pass64);
803 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
807 g_free (user_pass64);
810 case GST_RTSP_AUTH_DIGEST:{
811 gchar response[33], hex_urp[33];
812 gchar *auth_string, *auth_string2;
819 /* we need to have some params set */
820 if (conn->auth_params == NULL || conn->username == NULL ||
821 conn->passwd == NULL)
824 /* we need the realm and nonce */
825 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
826 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
827 if (realm == NULL || nonce == NULL)
830 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
833 method = gst_rtsp_method_as_text (message->type_data.request.method);
834 uri = message->type_data.request.uri;
836 /* Assume no qop, algorithm=md5, stale=false */
837 /* For algorithm MD5, a1 = urp. */
838 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
839 auth_string = g_strdup_printf ("Digest username=\"%s\", "
840 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
841 conn->username, realm, nonce, uri, response);
843 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
845 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
847 g_free (auth_string);
848 auth_string = auth_string2;
850 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
861 gen_date_string (gchar * date_string, guint len)
863 static const char wkdays[7][4] =
864 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
865 static const char months[12][4] =
866 { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
880 g_snprintf (date_string, len, "%s, %02d %s %04d %02d:%02d:%02d GMT",
881 wkdays[tm.tm_wday], tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900,
882 tm.tm_hour, tm.tm_min, tm.tm_sec);
886 write_bytes (GSocket * socket, const guint8 * buffer, guint * idx, guint size,
887 GCancellable * cancellable)
891 if (G_UNLIKELY (*idx > size))
892 return GST_RTSP_ERROR;
900 r = g_socket_send (socket, (gchar *) & buffer[*idx], left, cancellable,
902 if (G_UNLIKELY (r == 0)) {
903 return GST_RTSP_EINTR;
904 } else if (G_UNLIKELY (r < 0)) {
905 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
906 g_clear_error (&err);
907 return GST_RTSP_EINTR;
909 g_clear_error (&err);
910 return GST_RTSP_ESYS;
920 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size,
925 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
926 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
928 out = MIN (left, size);
929 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
931 if (left == (gsize) out) {
932 g_free (conn->initial_buffer);
933 conn->initial_buffer = NULL;
934 conn->initial_buffer_offset = 0;
936 conn->initial_buffer_offset += out;
939 if (G_LIKELY (size > (guint) out)) {
942 r = g_socket_receive (conn->read_socket, (gchar *) & buffer[out],
943 size - out, conn->cancellable, err);
955 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size,
958 DecodeCtx *ctx = conn->ctxp;
963 guint8 in[sizeof (ctx->out) * 4 / 3];
966 while (size > 0 && ctx->cout < ctx->coutl) {
967 /* we have some leftover bytes */
968 *buffer++ = ctx->out[ctx->cout++];
973 /* got what we needed? */
977 /* try to read more bytes */
978 r = fill_raw_bytes (conn, in, sizeof (in), err);
987 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
991 out = fill_raw_bytes (conn, buffer, size, err);
998 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1003 if (G_UNLIKELY (*idx > size))
1004 return GST_RTSP_ERROR;
1011 r = fill_bytes (conn, &buffer[*idx], left, &err);
1012 if (G_UNLIKELY (r == 0)) {
1013 return GST_RTSP_EEOF;
1014 } else if (G_UNLIKELY (r < 0)) {
1015 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1016 g_clear_error (&err);
1017 return GST_RTSP_EINTR;
1019 g_clear_error (&err);
1020 return GST_RTSP_ESYS;
1029 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1030 * end of a line. It even does its best to handle clients which mix them (even
1031 * though this is a really stupid idea (tm).) It also handles Line White Space
1032 * (LWS), where a line end followed by whitespace is considered LWS. This is
1033 * the method used in RTSP (and HTTP) to break long lines.
1035 static GstRTSPResult
1036 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1044 if (conn->read_ahead == READ_AHEAD_EOH) {
1045 /* the last call to read_line() already determined that we have reached
1046 * the end of the headers, so convey that information now */
1047 conn->read_ahead = 0;
1049 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1050 /* the last call to read_line() left off after having read \r\n */
1052 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1053 /* the last call to read_line() left off after having read \r\n\r */
1055 } else if (conn->read_ahead != 0) {
1056 /* the last call to read_line() left us with a character to start with */
1057 c = (guint8) conn->read_ahead;
1058 conn->read_ahead = 0;
1060 /* read the next character */
1061 r = fill_bytes (conn, &c, 1, &err);
1062 if (G_UNLIKELY (r == 0)) {
1063 return GST_RTSP_EEOF;
1064 } else if (G_UNLIKELY (r < 0)) {
1065 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1066 g_clear_error (&err);
1067 return GST_RTSP_EINTR;
1070 g_clear_error (&err);
1071 return GST_RTSP_ESYS;
1075 /* special treatment of line endings */
1076 if (c == '\r' || c == '\n') {
1080 /* need to read ahead one more character to know what to do... */
1081 r = fill_bytes (conn, &read_ahead, 1, &err);
1082 if (G_UNLIKELY (r == 0)) {
1083 return GST_RTSP_EEOF;
1084 } else if (G_UNLIKELY (r < 0)) {
1085 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1086 /* remember the original character we read and try again next time */
1087 if (conn->read_ahead == 0)
1088 conn->read_ahead = c;
1089 return GST_RTSP_EINTR;
1090 g_clear_error (&err);
1091 return GST_RTSP_EINTR;
1094 g_clear_error (&err);
1095 return GST_RTSP_ESYS;
1098 if (read_ahead == ' ' || read_ahead == '\t') {
1099 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1100 /* got \r\n\r followed by whitespace, treat it as a normal line
1101 * followed by one starting with LWS */
1102 conn->read_ahead = read_ahead;
1105 /* got LWS, change the line ending to a space and continue */
1107 conn->read_ahead = read_ahead;
1109 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1110 if (read_ahead == '\r' || read_ahead == '\n') {
1111 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1112 conn->read_ahead = READ_AHEAD_EOH;
1115 /* got \r\n\r followed by something else, this is not really
1116 * supported since we have probably just eaten the first character
1117 * of the body or the next message, so just ignore the second \r
1118 * and live with it... */
1119 conn->read_ahead = read_ahead;
1122 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1123 if (read_ahead == '\r') {
1124 /* got \r\n\r so far, need one more character... */
1125 conn->read_ahead = READ_AHEAD_CRLFCR;
1127 } else if (read_ahead == '\n') {
1128 /* got \r\n\n, treat it as the end of the headers */
1129 conn->read_ahead = READ_AHEAD_EOH;
1132 /* found the end of a line, keep read_ahead for the next line */
1133 conn->read_ahead = read_ahead;
1136 } else if (c == read_ahead) {
1137 /* got double \r or \n, treat it as the end of the headers */
1138 conn->read_ahead = READ_AHEAD_EOH;
1140 } else if (c == '\r' && read_ahead == '\n') {
1141 /* got \r\n so far, still need more to know what to do... */
1142 conn->read_ahead = READ_AHEAD_CRLF;
1145 /* found the end of a line, keep read_ahead for the next line */
1146 conn->read_ahead = read_ahead;
1151 if (G_LIKELY (*idx < size - 1))
1152 buffer[(*idx)++] = c;
1154 buffer[*idx] = '\0';
1160 * gst_rtsp_connection_write:
1161 * @conn: a #GstRTSPConnection
1162 * @data: the data to write
1163 * @size: the size of @data
1164 * @timeout: a timeout value or #NULL
1166 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1167 * the specified @timeout. @timeout can be #NULL, in which case this function
1168 * might block forever.
1170 * This function can be cancelled with gst_rtsp_connection_flush().
1172 * Returns: #GST_RTSP_OK on success.
1175 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1176 guint size, GTimeVal * timeout)
1183 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1184 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1185 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
1187 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1194 write_bytes (conn->write_socket, data, &offset, size,
1196 if (G_LIKELY (res == GST_RTSP_OK))
1198 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1201 /* not all is written, wait until we can write more */
1202 g_socket_set_timeout (conn->write_socket,
1203 (to + GST_SECOND - 1) / GST_SECOND);
1204 if (!g_socket_condition_wait (conn->write_socket,
1205 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable, &err)) {
1206 g_socket_set_timeout (conn->write_socket, 0);
1207 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1208 g_clear_error (&err);
1210 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1211 g_clear_error (&err);
1214 g_clear_error (&err);
1217 g_socket_set_timeout (conn->write_socket, 0);
1224 return GST_RTSP_ETIMEOUT;
1228 return GST_RTSP_ESYS;
1232 return GST_RTSP_EINTR;
1241 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1243 GString *str = NULL;
1245 str = g_string_new ("");
1247 switch (message->type) {
1248 case GST_RTSP_MESSAGE_REQUEST:
1249 /* create request string, add CSeq */
1250 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1252 gst_rtsp_method_as_text (message->type_data.request.method),
1253 message->type_data.request.uri, conn->cseq++);
1254 /* add session id if we have one */
1255 if (conn->session_id[0] != '\0') {
1256 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1257 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1260 /* add any authentication headers */
1261 add_auth_header (conn, message);
1263 case GST_RTSP_MESSAGE_RESPONSE:
1264 /* create response string */
1265 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1266 message->type_data.response.code, message->type_data.response.reason);
1268 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1269 /* create request string */
1270 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1271 gst_rtsp_method_as_text (message->type_data.request.method),
1272 message->type_data.request.uri,
1273 gst_rtsp_version_as_text (message->type_data.request.version));
1274 /* add any authentication headers */
1275 add_auth_header (conn, message);
1277 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1278 /* create response string */
1279 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1280 gst_rtsp_version_as_text (message->type_data.request.version),
1281 message->type_data.response.code, message->type_data.response.reason);
1283 case GST_RTSP_MESSAGE_DATA:
1285 guint8 data_header[4];
1287 /* prepare data header */
1288 data_header[0] = '$';
1289 data_header[1] = message->type_data.data.channel;
1290 data_header[2] = (message->body_size >> 8) & 0xff;
1291 data_header[3] = message->body_size & 0xff;
1293 /* create string with header and data */
1294 str = g_string_append_len (str, (gchar *) data_header, 4);
1296 g_string_append_len (str, (gchar *) message->body,
1297 message->body_size);
1301 g_string_free (str, TRUE);
1302 g_return_val_if_reached (NULL);
1306 /* append headers and body */
1307 if (message->type != GST_RTSP_MESSAGE_DATA) {
1308 gchar date_string[100];
1310 gen_date_string (date_string, sizeof (date_string));
1312 /* add date header */
1313 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1314 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1316 /* append headers */
1317 gst_rtsp_message_append_headers (message, str);
1319 /* append Content-Length and body if needed */
1320 if (message->body != NULL && message->body_size > 0) {
1323 len = g_strdup_printf ("%d", message->body_size);
1324 g_string_append_printf (str, "%s: %s\r\n",
1325 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1327 /* header ends here */
1328 g_string_append (str, "\r\n");
1330 g_string_append_len (str, (gchar *) message->body,
1331 message->body_size);
1333 /* just end headers */
1334 g_string_append (str, "\r\n");
1342 * gst_rtsp_connection_send:
1343 * @conn: a #GstRTSPConnection
1344 * @message: the message to send
1345 * @timeout: a timeout value or #NULL
1347 * Attempt to send @message to the connected @conn, blocking up to
1348 * the specified @timeout. @timeout can be #NULL, in which case this function
1349 * might block forever.
1351 * This function can be cancelled with gst_rtsp_connection_flush().
1353 * Returns: #GST_RTSP_OK on success.
1356 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1359 GString *string = NULL;
1364 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1365 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1367 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1370 if (conn->tunneled) {
1371 str = g_base64_encode ((const guchar *) string->str, string->len);
1372 g_string_free (string, TRUE);
1377 g_string_free (string, FALSE);
1381 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1389 g_warning ("Wrong message");
1390 return GST_RTSP_EINVAL;
1394 static GstRTSPResult
1395 parse_string (gchar * dest, gint size, gchar ** src)
1397 GstRTSPResult res = GST_RTSP_OK;
1402 while (g_ascii_isspace (**src))
1405 while (!g_ascii_isspace (**src) && **src != '\0') {
1407 dest[idx++] = **src;
1409 res = GST_RTSP_EPARSE;
1418 static GstRTSPResult
1419 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1420 GstRTSPVersion * version)
1422 GstRTSPResult res = GST_RTSP_OK;
1425 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1432 /* the version number must be formatted as X.Y with nothing following */
1433 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1434 res = GST_RTSP_EPARSE;
1436 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1437 if (major != 1 || minor != 0) {
1438 *version = GST_RTSP_VERSION_INVALID;
1439 res = GST_RTSP_ERROR;
1441 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1442 if (*type == GST_RTSP_MESSAGE_REQUEST)
1443 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1444 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1445 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1447 if (major == 1 && minor == 1) {
1448 *version = GST_RTSP_VERSION_1_1;
1449 } else if (major != 1 || minor != 0) {
1450 *version = GST_RTSP_VERSION_INVALID;
1451 res = GST_RTSP_ERROR;
1454 res = GST_RTSP_EPARSE;
1456 res = GST_RTSP_EPARSE;
1461 static GstRTSPResult
1462 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1464 GstRTSPResult res = GST_RTSP_OK;
1466 gchar versionstr[20];
1471 bptr = (gchar *) buffer;
1473 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1474 res = GST_RTSP_EPARSE;
1476 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1477 res = GST_RTSP_EPARSE;
1478 code = atoi (codestr);
1479 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1480 res = GST_RTSP_EPARSE;
1482 while (g_ascii_isspace (*bptr))
1485 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1486 NULL) != GST_RTSP_OK))
1487 res = GST_RTSP_EPARSE;
1489 res2 = parse_protocol_version (versionstr, &msg->type,
1490 &msg->type_data.response.version);
1491 if (G_LIKELY (res == GST_RTSP_OK))
1497 static GstRTSPResult
1498 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1500 GstRTSPResult res = GST_RTSP_OK;
1502 gchar versionstr[20];
1503 gchar methodstr[20];
1506 GstRTSPMethod method;
1508 bptr = (gchar *) buffer;
1510 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1511 res = GST_RTSP_EPARSE;
1512 method = gst_rtsp_find_method (methodstr);
1514 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1515 res = GST_RTSP_EPARSE;
1516 if (G_UNLIKELY (*urlstr == '\0'))
1517 res = GST_RTSP_EPARSE;
1519 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1520 res = GST_RTSP_EPARSE;
1522 if (G_UNLIKELY (*bptr != '\0'))
1523 res = GST_RTSP_EPARSE;
1525 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1526 urlstr) != GST_RTSP_OK))
1527 res = GST_RTSP_EPARSE;
1529 res2 = parse_protocol_version (versionstr, &msg->type,
1530 &msg->type_data.request.version);
1531 if (G_LIKELY (res == GST_RTSP_OK))
1534 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1535 /* GET and POST are not allowed as RTSP methods */
1536 if (msg->type_data.request.method == GST_RTSP_GET ||
1537 msg->type_data.request.method == GST_RTSP_POST) {
1538 msg->type_data.request.method = GST_RTSP_INVALID;
1539 if (res == GST_RTSP_OK)
1540 res = GST_RTSP_ERROR;
1542 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1543 /* only GET and POST are allowed as HTTP methods */
1544 if (msg->type_data.request.method != GST_RTSP_GET &&
1545 msg->type_data.request.method != GST_RTSP_POST) {
1546 msg->type_data.request.method = GST_RTSP_INVALID;
1547 if (res == GST_RTSP_OK)
1548 res = GST_RTSP_ERROR;
1555 /* parsing lines means reading a Key: Value pair */
1556 static GstRTSPResult
1557 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1559 GstRTSPHeaderField field;
1560 gchar *line = (gchar *) buffer;
1563 if ((value = strchr (line, ':')) == NULL || value == line)
1566 /* trim space before the colon */
1567 if (value[-1] == ' ')
1570 /* replace the colon with a NUL */
1573 /* find the header */
1574 field = gst_rtsp_find_header_field (line);
1575 if (field == GST_RTSP_HDR_INVALID)
1578 /* split up the value in multiple key:value pairs if it contains comma(s) */
1579 while (*value != '\0') {
1581 gchar *comma = NULL;
1582 gboolean quoted = FALSE;
1585 /* trim leading space */
1589 /* for headers which may not appear multiple times, and thus may not
1590 * contain multiple values on the same line, we can short-circuit the loop
1591 * below and the entire value results in just one key:value pair*/
1592 if (!gst_rtsp_header_allow_multiple (field))
1593 next_value = value + strlen (value);
1597 /* find the next value, taking special care of quotes and comments */
1598 while (*next_value != '\0') {
1599 if ((quoted || comment != 0) && *next_value == '\\' &&
1600 next_value[1] != '\0')
1602 else if (comment == 0 && *next_value == '"')
1604 else if (!quoted && *next_value == '(')
1606 else if (comment != 0 && *next_value == ')')
1608 else if (!quoted && comment == 0) {
1609 /* To quote RFC 2068: "User agents MUST take special care in parsing
1610 * the WWW-Authenticate field value if it contains more than one
1611 * challenge, or if more than one WWW-Authenticate header field is
1612 * provided, since the contents of a challenge may itself contain a
1613 * comma-separated list of authentication parameters."
1615 * What this means is that we cannot just look for an unquoted comma
1616 * when looking for multiple values in Proxy-Authenticate and
1617 * WWW-Authenticate headers. Instead we need to look for the sequence
1618 * "comma [space] token space token" before we can split after the
1621 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1622 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1623 if (*next_value == ',') {
1624 if (next_value[1] == ' ') {
1625 /* skip any space following the comma so we do not mistake it for
1626 * separating between two tokens */
1630 } else if (*next_value == ' ' && next_value[1] != ',' &&
1631 next_value[1] != '=' && comma != NULL) {
1636 } else if (*next_value == ',')
1644 if (value != next_value && next_value[-1] == ' ')
1645 next_value[-1] = '\0';
1647 if (*next_value != '\0')
1648 *next_value++ = '\0';
1650 /* add the key:value pair */
1652 gst_rtsp_message_add_header (msg, field, value);
1663 return GST_RTSP_EPARSE;
1667 /* convert all consecutive whitespace to a single space */
1669 normalize_line (guint8 * buffer)
1672 if (g_ascii_isspace (*buffer)) {
1676 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1679 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1687 * GST_RTSP_OK when a complete message was read.
1688 * GST_RTSP_EEOF: when the read socket is closed
1689 * GST_RTSP_EINTR: when more data is needed.
1690 * GST_RTSP_..: some other error occured.
1692 static GstRTSPResult
1693 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1694 GstRTSPConnection * conn)
1699 switch (builder->state) {
1704 builder->offset = 0;
1706 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1707 if (res != GST_RTSP_OK)
1710 c = builder->buffer[0];
1712 /* we have 1 bytes now and we can see if this is a data message or
1715 /* data message, prepare for the header */
1716 builder->state = STATE_DATA_HEADER;
1717 } else if (c == '\n' || c == '\r') {
1718 /* skip \n and \r */
1719 builder->offset = 0;
1722 builder->state = STATE_READ_LINES;
1726 case STATE_DATA_HEADER:
1729 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1730 if (res != GST_RTSP_OK)
1733 gst_rtsp_message_init_data (message, builder->buffer[1]);
1735 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1736 builder->body_data = g_malloc (builder->body_len + 1);
1737 builder->body_data[builder->body_len] = '\0';
1738 builder->offset = 0;
1739 builder->state = STATE_DATA_BODY;
1742 case STATE_DATA_BODY:
1745 read_bytes (conn, builder->body_data, &builder->offset,
1747 if (res != GST_RTSP_OK)
1750 /* we have the complete body now, store in the message adjusting the
1751 * length to include the trailing '\0' */
1752 gst_rtsp_message_take_body (message,
1753 (guint8 *) builder->body_data, builder->body_len + 1);
1754 builder->body_data = NULL;
1755 builder->body_len = 0;
1757 builder->state = STATE_END;
1760 case STATE_READ_LINES:
1762 res = read_line (conn, builder->buffer, &builder->offset,
1763 sizeof (builder->buffer));
1764 if (res != GST_RTSP_OK)
1767 /* we have a regular response */
1768 if (builder->buffer[0] == '\0') {
1771 /* empty line, end of message header */
1772 /* see if there is a Content-Length header, but ignore it if this
1773 * is a POST request with an x-sessioncookie header */
1774 if (gst_rtsp_message_get_header (message,
1775 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1776 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1777 message->type_data.request.method != GST_RTSP_POST ||
1778 gst_rtsp_message_get_header (message,
1779 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1780 /* there is, prepare to read the body */
1781 builder->body_len = atol (hdrval);
1782 builder->body_data = g_try_malloc (builder->body_len + 1);
1783 /* we can't do much here, we need the length to know how many bytes
1784 * we need to read next and when allocation fails, something is
1785 * probably wrong with the length. */
1786 if (builder->body_data == NULL)
1787 goto invalid_body_len;
1789 builder->body_data[builder->body_len] = '\0';
1790 builder->offset = 0;
1791 builder->state = STATE_DATA_BODY;
1793 builder->state = STATE_END;
1798 /* we have a line */
1799 normalize_line (builder->buffer);
1800 if (builder->line == 0) {
1801 /* first line, check for response status */
1802 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1803 memcmp (builder->buffer, "HTTP", 4) == 0) {
1804 builder->status = parse_response_status (builder->buffer, message);
1806 builder->status = parse_request_line (builder->buffer, message);
1809 /* else just parse the line */
1810 res = parse_line (builder->buffer, message);
1811 if (res != GST_RTSP_OK)
1812 builder->status = res;
1815 builder->offset = 0;
1820 gchar *session_cookie;
1823 if (message->type == GST_RTSP_MESSAGE_DATA) {
1824 /* data messages don't have headers */
1829 /* save the tunnel session in the connection */
1830 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1831 !conn->manual_http &&
1832 conn->tstate == TUNNEL_STATE_NONE &&
1833 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1834 &session_cookie, 0) == GST_RTSP_OK) {
1835 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1836 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1837 conn->tunneled = TRUE;
1840 /* save session id in the connection for further use */
1841 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1842 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1843 &session_id, 0) == GST_RTSP_OK) {
1846 maxlen = sizeof (conn->session_id) - 1;
1847 /* the sessionid can have attributes marked with ;
1848 * Make sure we strip them */
1849 for (i = 0; session_id[i] != '\0'; i++) {
1850 if (session_id[i] == ';') {
1855 } while (g_ascii_isspace (session_id[i]));
1856 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1859 /* if we parsed something valid, configure */
1860 if ((to = atoi (&session_id[i + 8])) > 0)
1867 /* make sure to not overflow */
1868 strncpy (conn->session_id, session_id, maxlen);
1869 conn->session_id[maxlen] = '\0';
1871 res = builder->status;
1875 res = GST_RTSP_ERROR;
1885 GST_DEBUG ("could not allocate body");
1886 return GST_RTSP_ERROR;
1891 * gst_rtsp_connection_read:
1892 * @conn: a #GstRTSPConnection
1893 * @data: the data to read
1894 * @size: the size of @data
1895 * @timeout: a timeout value or #NULL
1897 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1898 * the specified @timeout. @timeout can be #NULL, in which case this function
1899 * might block forever.
1901 * This function can be cancelled with gst_rtsp_connection_flush().
1903 * Returns: #GST_RTSP_OK on success.
1906 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1914 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1915 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1916 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
1918 if (G_UNLIKELY (size == 0))
1923 /* configure timeout if any */
1924 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1927 res = read_bytes (conn, data, &offset, size);
1928 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1930 if (G_LIKELY (res == GST_RTSP_OK))
1932 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1935 g_socket_set_timeout (conn->read_socket,
1936 (to + GST_SECOND - 1) / GST_SECOND);
1937 if (!g_socket_condition_wait (conn->read_socket,
1938 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
1940 g_socket_set_timeout (conn->read_socket, 0);
1941 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1942 g_clear_error (&err);
1944 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1945 g_clear_error (&err);
1946 goto select_timeout;
1948 g_clear_error (&err);
1951 g_socket_set_timeout (conn->read_socket, 0);
1958 return GST_RTSP_ESYS;
1962 return GST_RTSP_ETIMEOUT;
1966 return GST_RTSP_EINTR;
1970 return GST_RTSP_EEOF;
1978 static GstRTSPMessage *
1979 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
1980 const GstRTSPMessage * request)
1982 GstRTSPMessage *msg;
1985 if (gst_rtsp_status_as_text (code) == NULL)
1986 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1988 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
1991 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
1992 "GStreamer RTSP Server");
1993 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
1994 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
1995 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
1997 if (code == GST_RTSP_STS_OK) {
1999 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2001 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2002 "application/x-rtsp-tunnelled");
2015 * gst_rtsp_connection_receive:
2016 * @conn: a #GstRTSPConnection
2017 * @message: the message to read
2018 * @timeout: a timeout value or #NULL
2020 * Attempt to read into @message from the connected @conn, blocking up to
2021 * the specified @timeout. @timeout can be #NULL, in which case this function
2022 * might block forever.
2024 * This function can be cancelled with gst_rtsp_connection_flush().
2026 * Returns: #GST_RTSP_OK on success.
2029 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2033 GstRTSPBuilder builder;
2037 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2038 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2039 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2041 /* configure timeout if any */
2042 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2044 memset (&builder, 0, sizeof (GstRTSPBuilder));
2046 res = build_next (&builder, message, conn);
2047 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2049 else if (G_LIKELY (res == GST_RTSP_OK)) {
2050 if (!conn->manual_http) {
2051 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2052 if (conn->tstate == TUNNEL_STATE_NONE &&
2053 message->type_data.request.method == GST_RTSP_GET) {
2054 GstRTSPMessage *response;
2056 conn->tstate = TUNNEL_STATE_GET;
2058 /* tunnel GET request, we can reply now */
2059 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2060 res = gst_rtsp_connection_send (conn, response, timeout);
2061 gst_rtsp_message_free (response);
2062 if (res == GST_RTSP_OK)
2063 res = GST_RTSP_ETGET;
2065 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2066 message->type_data.request.method == GST_RTSP_POST) {
2067 conn->tstate = TUNNEL_STATE_POST;
2069 /* tunnel POST request, the caller now has to link the two
2071 res = GST_RTSP_ETPOST;
2074 res = GST_RTSP_EPARSE;
2077 } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2078 res = GST_RTSP_EPARSE;
2084 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2087 g_socket_set_timeout (conn->read_socket,
2088 (to + GST_SECOND - 1) / GST_SECOND);
2089 if (!g_socket_condition_wait (conn->read_socket,
2090 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
2092 g_socket_set_timeout (conn->read_socket, 0);
2093 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
2094 g_clear_error (&err);
2096 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
2097 g_clear_error (&err);
2098 goto select_timeout;
2100 g_clear_error (&err);
2103 g_socket_set_timeout (conn->read_socket, 0);
2106 /* we have a message here */
2107 build_reset (&builder);
2114 res = GST_RTSP_ESYS;
2119 res = GST_RTSP_ETIMEOUT;
2124 res = GST_RTSP_EINTR;
2129 res = GST_RTSP_EEOF;
2135 build_reset (&builder);
2136 gst_rtsp_message_unset (message);
2142 * gst_rtsp_connection_close:
2143 * @conn: a #GstRTSPConnection
2145 * Close the connected @conn. After this call, the connection is in the same
2146 * state as when it was first created.
2148 * Returns: #GST_RTSP_OK on success.
2151 gst_rtsp_connection_close (GstRTSPConnection * conn)
2153 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2155 /* last unref closes the connection we don't want to explicitly close here
2156 * because these sockets might have been provided at construction */
2157 if (conn->socket0) {
2158 g_object_unref (conn->socket0);
2159 conn->socket0 = NULL;
2161 if (conn->socket1) {
2162 g_object_unref (conn->socket1);
2163 conn->socket1 = NULL;
2169 conn->read_ahead = 0;
2171 g_free (conn->initial_buffer);
2172 conn->initial_buffer = NULL;
2173 conn->initial_buffer_offset = 0;
2175 conn->write_socket = NULL;
2176 conn->read_socket = NULL;
2177 conn->tunneled = FALSE;
2178 conn->tstate = TUNNEL_STATE_NONE;
2180 g_free (conn->username);
2181 conn->username = NULL;
2182 g_free (conn->passwd);
2183 conn->passwd = NULL;
2184 gst_rtsp_connection_clear_auth_params (conn);
2187 conn->session_id[0] = '\0';
2193 * gst_rtsp_connection_free:
2194 * @conn: a #GstRTSPConnection
2196 * Close and free @conn.
2198 * Returns: #GST_RTSP_OK on success.
2201 gst_rtsp_connection_free (GstRTSPConnection * conn)
2205 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2207 res = gst_rtsp_connection_close (conn);
2209 if (conn->cancellable)
2210 g_object_unref (conn->cancellable);
2212 g_timer_destroy (conn->timer);
2213 gst_rtsp_url_free (conn->url);
2214 g_free (conn->proxy_host);
2221 * gst_rtsp_connection_poll:
2222 * @conn: a #GstRTSPConnection
2223 * @events: a bitmask of #GstRTSPEvent flags to check
2224 * @revents: location for result flags
2225 * @timeout: a timeout
2227 * Wait up to the specified @timeout for the connection to become available for
2228 * at least one of the operations specified in @events. When the function returns
2229 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2232 * @timeout can be #NULL, in which case this function might block forever.
2234 * This function can be cancelled with gst_rtsp_connection_flush().
2236 * Returns: #GST_RTSP_OK on success.
2239 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2240 GstRTSPEvent * revents, GTimeVal * timeout)
2244 GSource *rs, *ws, *ts;
2245 GIOCondition condition;
2247 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2248 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2249 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2250 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2251 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2253 ctx = g_main_context_new ();
2255 /* configure timeout if any */
2256 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2259 ts = g_timeout_source_new (to / GST_MSECOND);
2260 g_source_set_dummy_callback (ts);
2261 g_source_attach (ts, ctx);
2262 g_source_unref (ts);
2265 rs = g_socket_create_source (conn->read_socket,
2266 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable);
2267 g_source_set_dummy_callback (rs);
2268 g_source_attach (rs, ctx);
2269 g_source_unref (rs);
2271 ws = g_socket_create_source (conn->write_socket,
2272 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable);
2273 g_source_set_dummy_callback (ws);
2274 g_source_attach (ws, ctx);
2275 g_source_unref (ws);
2277 /* Returns after handling all pending events */
2278 g_main_context_iteration (ctx, TRUE);
2280 g_main_context_unref (ctx);
2283 g_socket_condition_check (conn->read_socket,
2284 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP);
2286 g_socket_condition_check (conn->write_socket,
2287 G_IO_OUT | G_IO_ERR | G_IO_HUP);
2290 if (events & GST_RTSP_EV_READ) {
2291 if ((condition & G_IO_IN) || (condition & G_IO_PRI))
2292 *revents |= GST_RTSP_EV_READ;
2294 if (events & GST_RTSP_EV_WRITE) {
2295 if ((condition & G_IO_OUT))
2296 *revents |= GST_RTSP_EV_WRITE;
2300 return GST_RTSP_ETIMEOUT;
2306 * gst_rtsp_connection_next_timeout:
2307 * @conn: a #GstRTSPConnection
2308 * @timeout: a timeout
2310 * Calculate the next timeout for @conn, storing the result in @timeout.
2312 * Returns: #GST_RTSP_OK.
2315 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2322 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2323 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2325 ctimeout = conn->timeout;
2326 if (ctimeout >= 20) {
2327 /* Because we should act before the timeout we timeout 5
2328 * seconds in advance. */
2330 } else if (ctimeout >= 5) {
2331 /* else timeout 20% earlier */
2332 ctimeout -= ctimeout / 5;
2333 } else if (ctimeout >= 1) {
2334 /* else timeout 1 second earlier */
2338 elapsed = g_timer_elapsed (conn->timer, &usec);
2339 if (elapsed >= ctimeout) {
2343 sec = ctimeout - elapsed;
2344 if (usec <= G_USEC_PER_SEC)
2345 usec = G_USEC_PER_SEC - usec;
2350 timeout->tv_sec = sec;
2351 timeout->tv_usec = usec;
2357 * gst_rtsp_connection_reset_timeout:
2358 * @conn: a #GstRTSPConnection
2360 * Reset the timeout of @conn.
2362 * Returns: #GST_RTSP_OK.
2365 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2367 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2369 g_timer_start (conn->timer);
2375 * gst_rtsp_connection_flush:
2376 * @conn: a #GstRTSPConnection
2377 * @flush: start or stop the flush
2379 * Start or stop the flushing action on @conn. When flushing, all current
2380 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2381 * is set to non-flushing mode again.
2383 * Returns: #GST_RTSP_OK.
2386 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2388 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2391 g_cancellable_cancel (conn->cancellable);
2393 g_cancellable_reset (conn->cancellable);
2399 * gst_rtsp_connection_set_proxy:
2400 * @conn: a #GstRTSPConnection
2401 * @host: the proxy host
2402 * @port: the proxy port
2404 * Set the proxy host and port.
2406 * Returns: #GST_RTSP_OK.
2409 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2410 const gchar * host, guint port)
2412 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2414 g_free (conn->proxy_host);
2415 conn->proxy_host = g_strdup (host);
2416 conn->proxy_port = port;
2422 * gst_rtsp_connection_set_auth:
2423 * @conn: a #GstRTSPConnection
2424 * @method: authentication method
2426 * @pass: the password
2428 * Configure @conn for authentication mode @method with @user and @pass as the
2429 * user and password respectively.
2431 * Returns: #GST_RTSP_OK.
2434 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2435 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2437 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2439 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2440 || g_strrstr (user, ":") != NULL))
2441 return GST_RTSP_EINVAL;
2443 /* Make sure the username and passwd are being set for authentication */
2444 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2445 return GST_RTSP_EINVAL;
2447 /* ":" chars are not allowed in usernames for basic auth */
2448 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2449 return GST_RTSP_EINVAL;
2451 g_free (conn->username);
2452 g_free (conn->passwd);
2454 conn->auth_method = method;
2455 conn->username = g_strdup (user);
2456 conn->passwd = g_strdup (pass);
2463 * @key: ASCII string to hash
2465 * Hashes @key in a case-insensitive manner.
2467 * Returns: the hash code.
2470 str_case_hash (gconstpointer key)
2472 const char *p = key;
2473 guint h = g_ascii_toupper (*p);
2476 for (p += 1; *p != '\0'; p++)
2477 h = (h << 5) - h + g_ascii_toupper (*p);
2484 * @v1: an ASCII string
2485 * @v2: another ASCII string
2487 * Compares @v1 and @v2 in a case-insensitive manner
2489 * Returns: %TRUE if they are equal (modulo case)
2492 str_case_equal (gconstpointer v1, gconstpointer v2)
2494 const char *string1 = v1;
2495 const char *string2 = v2;
2497 return g_ascii_strcasecmp (string1, string2) == 0;
2501 * gst_rtsp_connection_set_auth_param:
2502 * @conn: a #GstRTSPConnection
2503 * @param: authentication directive
2506 * Setup @conn with authentication directives. This is not necesary for
2507 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2508 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2509 * in the WWW-Authenticate response header and can include realm, domain,
2510 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2513 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2514 const gchar * param, const gchar * value)
2516 g_return_if_fail (conn != NULL);
2517 g_return_if_fail (param != NULL);
2519 if (conn->auth_params == NULL) {
2521 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2523 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2527 * gst_rtsp_connection_clear_auth_params:
2528 * @conn: a #GstRTSPConnection
2530 * Clear the list of authentication directives stored in @conn.
2533 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2535 g_return_if_fail (conn != NULL);
2537 if (conn->auth_params != NULL) {
2538 g_hash_table_destroy (conn->auth_params);
2539 conn->auth_params = NULL;
2543 static GstRTSPResult
2544 set_qos_dscp (GSocket * socket, guint qos_dscp)
2550 union gst_sockaddr sa;
2551 socklen_t slen = sizeof (sa);
2558 fd = g_socket_get_fd (socket);
2559 if (getsockname (fd, &sa.sa, &slen) < 0)
2560 goto no_getsockname;
2562 af = sa.sa.sa_family;
2564 /* if this is an IPv4-mapped address then do IPv4 QoS */
2565 if (af == AF_INET6) {
2566 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2570 /* extract and shift 6 bits of the DSCP */
2571 tos = (qos_dscp & 0x3f) << 2;
2575 if (setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2580 if (setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2594 return GST_RTSP_ESYS;
2598 return GST_RTSP_ERROR;
2604 * gst_rtsp_connection_set_qos_dscp:
2605 * @conn: a #GstRTSPConnection
2606 * @qos_dscp: DSCP value
2608 * Configure @conn to use the specified DSCP value.
2610 * Returns: #GST_RTSP_OK on success.
2613 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2617 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2618 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2619 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2621 res = set_qos_dscp (conn->socket0, qos_dscp);
2622 if (res == GST_RTSP_OK)
2623 res = set_qos_dscp (conn->socket1, qos_dscp);
2630 * gst_rtsp_connection_get_url:
2631 * @conn: a #GstRTSPConnection
2633 * Retrieve the URL of the other end of @conn.
2635 * Returns: The URL. This value remains valid until the
2636 * connection is freed.
2639 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2641 g_return_val_if_fail (conn != NULL, NULL);
2647 * gst_rtsp_connection_get_ip:
2648 * @conn: a #GstRTSPConnection
2650 * Retrieve the IP address of the other end of @conn.
2652 * Returns: The IP address as a string. this value remains valid until the
2653 * connection is closed.
2656 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2658 g_return_val_if_fail (conn != NULL, NULL);
2664 * gst_rtsp_connection_set_ip:
2665 * @conn: a #GstRTSPConnection
2666 * @ip: an ip address
2668 * Set the IP address of the server.
2671 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2673 g_return_if_fail (conn != NULL);
2676 conn->ip = g_strdup (ip);
2680 * gst_rtsp_connection_get_readfd:
2681 * @conn: a #GstRTSPConnection
2683 * Get the file descriptor for reading.
2685 * Returns: the file descriptor used for reading or %NULL on error. The file
2686 * descriptor remains valid until the connection is closed.
2689 gst_rtsp_connection_get_read_socket (const GstRTSPConnection * conn)
2691 g_return_val_if_fail (conn != NULL, NULL);
2692 g_return_val_if_fail (conn->read_socket != NULL, NULL);
2694 return conn->read_socket;
2698 * gst_rtsp_connection_get_write_socket:
2699 * @conn: a #GstRTSPConnection
2701 * Get the file descriptor for writing.
2703 * Returns: the file descriptor used for writing or NULL on error. The file
2704 * descriptor remains valid until the connection is closed.
2707 gst_rtsp_connection_get_write_socket (const GstRTSPConnection * conn)
2709 g_return_val_if_fail (conn != NULL, NULL);
2710 g_return_val_if_fail (conn->write_socket != NULL, NULL);
2712 return conn->write_socket;
2716 * gst_rtsp_connection_set_http_mode:
2717 * @conn: a #GstRTSPConnection
2718 * @enable: %TRUE to enable manual HTTP mode
2720 * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2721 * messages in addition to the RTSP messages. It will also disable the
2722 * automatic handling of setting up an HTTP tunnel.
2725 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2727 g_return_if_fail (conn != NULL);
2729 conn->manual_http = enable;
2733 * gst_rtsp_connection_set_tunneled:
2734 * @conn: a #GstRTSPConnection
2735 * @tunneled: the new state
2737 * Set the HTTP tunneling state of the connection. This must be configured before
2738 * the @conn is connected.
2741 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2743 g_return_if_fail (conn != NULL);
2744 g_return_if_fail (conn->read_socket == NULL);
2745 g_return_if_fail (conn->write_socket == NULL);
2747 conn->tunneled = tunneled;
2751 * gst_rtsp_connection_is_tunneled:
2752 * @conn: a #GstRTSPConnection
2754 * Get the tunneling state of the connection.
2756 * Returns: if @conn is using HTTP tunneling.
2759 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2761 g_return_val_if_fail (conn != NULL, FALSE);
2763 return conn->tunneled;
2767 * gst_rtsp_connection_get_tunnelid:
2768 * @conn: a #GstRTSPConnection
2770 * Get the tunnel session id the connection.
2772 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2775 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2777 g_return_val_if_fail (conn != NULL, NULL);
2779 if (!conn->tunneled)
2782 return conn->tunnelid;
2786 * gst_rtsp_connection_do_tunnel:
2787 * @conn: a #GstRTSPConnection
2788 * @conn2: a #GstRTSPConnection or %NULL
2790 * If @conn received the first tunnel connection and @conn2 received
2791 * the second tunnel connection, link the two connections together so that
2792 * @conn manages the tunneled connection.
2794 * After this call, @conn2 cannot be used anymore and must be freed with
2795 * gst_rtsp_connection_free().
2797 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2800 * Returns: return GST_RTSP_OK on success.
2803 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2804 GstRTSPConnection * conn2)
2806 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2808 if (conn2 != NULL) {
2809 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2810 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2811 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2812 TUNNELID_LEN), GST_RTSP_EINVAL);
2814 /* both connections have socket0 as the read/write socket. start by taking the
2815 * socket from conn2 and set it as the socket in conn */
2816 conn->socket1 = conn2->socket0;
2818 /* clean up some of the state of conn2 */
2819 g_cancellable_cancel (conn2->cancellable);
2821 g_object_unref (conn2->socket1);
2822 conn2->socket1 = NULL;
2823 conn2->write_socket = conn2->read_socket = NULL;
2824 g_cancellable_reset (conn2->cancellable);
2826 /* We make socket0 the write socket and socket1 the read socket. */
2827 conn->write_socket = conn->socket0;
2828 conn->read_socket = conn->socket1;
2830 conn->tstate = TUNNEL_STATE_COMPLETE;
2832 g_free (conn->initial_buffer);
2833 conn->initial_buffer = conn2->initial_buffer;
2834 conn2->initial_buffer = NULL;
2835 conn->initial_buffer_offset = conn2->initial_buffer_offset;
2838 /* we need base64 decoding for the readfd */
2839 conn->ctx.state = 0;
2842 conn->ctx.coutl = 0;
2843 conn->ctxp = &conn->ctx;
2848 #define READ_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2849 #define READ_COND (G_IO_IN | READ_ERR)
2850 #define WRITE_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2851 #define WRITE_COND (G_IO_OUT | WRITE_ERR)
2860 /* async functions */
2861 struct _GstRTSPWatch
2865 GstRTSPConnection *conn;
2867 GstRTSPBuilder builder;
2868 GstRTSPMessage message;
2873 /* queued message for transmission */
2882 GstRTSPWatchFuncs funcs;
2885 GDestroyNotify notify;
2889 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2891 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2893 if (watch->conn->initial_buffer != NULL)
2896 *timeout = (watch->conn->timeout * 1000);
2902 gst_rtsp_source_check (GSource * source)
2904 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2906 if (watch->readfd.revents & READ_COND)
2909 if (watch->writefd.revents & WRITE_COND)
2916 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2917 gpointer user_data G_GNUC_UNUSED)
2919 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2920 GstRTSPResult res = GST_RTSP_ERROR;
2921 gboolean keep_running = TRUE;
2923 /* first read as much as we can */
2924 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2926 if (watch->readfd.revents & READ_ERR)
2929 res = build_next (&watch->builder, &watch->message, watch->conn);
2930 if (res == GST_RTSP_EINTR)
2932 else if (G_UNLIKELY (res == GST_RTSP_EEOF)) {
2933 watch->readfd.events = 0;
2934 watch->readfd.revents = 0;
2935 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2936 /* When we are in tunnelled mode, the read socket can be closed and we
2937 * should be prepared for a new POST method to reopen it */
2938 if (watch->conn->tstate == TUNNEL_STATE_COMPLETE) {
2939 /* remove the read connection for the tunnel */
2940 /* we accept a new POST request */
2941 watch->conn->tstate = TUNNEL_STATE_GET;
2942 /* and signal that we lost our tunnel */
2943 if (watch->funcs.tunnel_lost)
2944 res = watch->funcs.tunnel_lost (watch, watch->user_data);
2948 } else if (G_LIKELY (res == GST_RTSP_OK)) {
2949 if (!watch->conn->manual_http &&
2950 watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2951 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2952 watch->message.type_data.request.method == GST_RTSP_GET) {
2953 GstRTSPMessage *response;
2954 GstRTSPStatusCode code;
2956 watch->conn->tstate = TUNNEL_STATE_GET;
2958 if (watch->funcs.tunnel_start)
2959 code = watch->funcs.tunnel_start (watch, watch->user_data);
2961 code = GST_RTSP_STS_OK;
2963 /* queue the response */
2964 response = gen_tunnel_reply (watch->conn, code, &watch->message);
2965 gst_rtsp_watch_send_message (watch, response, NULL);
2966 gst_rtsp_message_free (response);
2968 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2969 watch->message.type_data.request.method == GST_RTSP_POST) {
2970 watch->conn->tstate = TUNNEL_STATE_POST;
2972 /* in the callback the connection should be tunneled with the
2974 if (watch->funcs.tunnel_complete) {
2975 watch->funcs.tunnel_complete (watch, watch->user_data);
2976 keep_running = !(watch->conn->read_socket == NULL &&
2977 watch->conn->write_socket == NULL);
2986 if (!watch->conn->manual_http) {
2987 /* if manual HTTP support is not enabled, then restore the message to
2988 * what it would have looked like without the support for parsing HTTP
2989 * messages being present */
2990 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2991 watch->message.type = GST_RTSP_MESSAGE_REQUEST;
2992 watch->message.type_data.request.method = GST_RTSP_INVALID;
2993 if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
2994 watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
2995 res = GST_RTSP_EPARSE;
2996 } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2997 watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
2998 if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
2999 watch->message.type_data.response.version =
3000 GST_RTSP_VERSION_INVALID;
3001 res = GST_RTSP_EPARSE;
3005 if (G_LIKELY (res == GST_RTSP_OK)) {
3006 if (watch->funcs.message_received)
3007 watch->funcs.message_received (watch, &watch->message,
3014 gst_rtsp_message_unset (&watch->message);
3015 build_reset (&watch->builder);
3019 if (watch->writefd.revents & WRITE_COND) {
3020 if (watch->writefd.revents & WRITE_ERR)
3023 g_mutex_lock (&watch->mutex);
3025 if (watch->write_data == NULL) {
3028 /* get a new message from the queue */
3029 rec = g_queue_pop_tail (watch->messages);
3033 watch->write_off = 0;
3034 watch->write_data = rec->data;
3035 watch->write_size = rec->size;
3036 watch->write_id = rec->id;
3038 g_slice_free (GstRTSPRec, rec);
3041 res = write_bytes (watch->conn->write_socket, watch->write_data,
3042 &watch->write_off, watch->write_size, watch->conn->cancellable);
3043 g_mutex_unlock (&watch->mutex);
3045 if (res == GST_RTSP_EINTR)
3047 else if (G_LIKELY (res == GST_RTSP_OK)) {
3048 if (watch->funcs.message_sent)
3049 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3053 g_mutex_lock (&watch->mutex);
3055 g_free (watch->write_data);
3056 watch->write_data = NULL;
3059 watch->writefd.events = WRITE_ERR;
3061 g_mutex_unlock (&watch->mutex);
3066 return keep_running;
3071 if (watch->funcs.closed)
3072 watch->funcs.closed (watch, watch->user_data);
3074 /* always stop when the readfd returns EOF in non-tunneled mode */
3079 watch->readfd.events = 0;
3080 watch->readfd.revents = 0;
3081 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3082 keep_running = (watch->writefd.events != 0);
3085 if (watch->funcs.error_full)
3086 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3087 0, watch->user_data), error);
3095 watch->writefd.events = 0;
3096 watch->writefd.revents = 0;
3097 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3098 keep_running = (watch->readfd.events != 0);
3101 if (watch->funcs.error_full)
3102 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3103 watch->write_id, watch->user_data), error);
3111 if (watch->funcs.error)
3112 watch->funcs.error (watch, res, watch->user_data);
3114 return keep_running;
3119 gst_rtsp_rec_free (gpointer data)
3121 GstRTSPRec *rec = data;
3124 g_slice_free (GstRTSPRec, rec);
3128 gst_rtsp_source_finalize (GSource * source)
3130 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3132 build_reset (&watch->builder);
3133 gst_rtsp_message_unset (&watch->message);
3135 g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3136 g_queue_free (watch->messages);
3137 watch->messages = NULL;
3138 g_free (watch->write_data);
3140 g_mutex_clear (&watch->mutex);
3143 watch->notify (watch->user_data);
3146 static GSourceFuncs gst_rtsp_source_funcs = {
3147 gst_rtsp_source_prepare,
3148 gst_rtsp_source_check,
3149 gst_rtsp_source_dispatch,
3150 gst_rtsp_source_finalize,
3156 * gst_rtsp_watch_new:
3157 * @conn: a #GstRTSPConnection
3158 * @funcs: watch functions
3159 * @user_data: user data to pass to @funcs
3160 * @notify: notify when @user_data is not referenced anymore
3162 * Create a watch object for @conn. The functions provided in @funcs will be
3163 * called with @user_data when activity happened on the watch.
3165 * The new watch is usually created so that it can be attached to a
3166 * maincontext with gst_rtsp_watch_attach().
3168 * @conn must exist for the entire lifetime of the watch.
3170 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3171 * communication. Free with gst_rtsp_watch_unref () after usage.
3174 gst_rtsp_watch_new (GstRTSPConnection * conn,
3175 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3177 GstRTSPWatch *result;
3179 g_return_val_if_fail (conn != NULL, NULL);
3180 g_return_val_if_fail (funcs != NULL, NULL);
3181 g_return_val_if_fail (conn->read_socket != NULL, NULL);
3182 g_return_val_if_fail (conn->write_socket != NULL, NULL);
3184 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3185 sizeof (GstRTSPWatch));
3187 result->conn = conn;
3188 result->builder.state = STATE_START;
3190 g_mutex_init (&result->mutex);
3191 result->messages = g_queue_new ();
3193 result->readfd.fd = -1;
3194 result->writefd.fd = -1;
3196 gst_rtsp_watch_reset (result);
3198 result->funcs = *funcs;
3199 result->user_data = user_data;
3200 result->notify = notify;
3206 * gst_rtsp_watch_reset:
3207 * @watch: a #GstRTSPWatch
3209 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3210 * when the file descriptors of the connection might have changed.
3213 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3215 if (watch->readfd.fd != -1)
3216 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3217 if (watch->writefd.fd != -1)
3218 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3220 watch->readfd.fd = g_socket_get_fd (watch->conn->read_socket);
3221 watch->readfd.events = READ_COND;
3222 watch->readfd.revents = 0;
3224 watch->writefd.fd = g_socket_get_fd (watch->conn->write_socket);
3225 watch->writefd.events = WRITE_ERR;
3226 watch->writefd.revents = 0;
3228 if (watch->readfd.fd != -1)
3229 g_source_add_poll ((GSource *) watch, &watch->readfd);
3230 if (watch->writefd.fd != -1)
3231 g_source_add_poll ((GSource *) watch, &watch->writefd);
3235 * gst_rtsp_watch_attach:
3236 * @watch: a #GstRTSPWatch
3237 * @context: a GMainContext (if NULL, the default context will be used)
3239 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3241 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3244 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3246 g_return_val_if_fail (watch != NULL, 0);
3248 return g_source_attach ((GSource *) watch, context);
3252 * gst_rtsp_watch_unref:
3253 * @watch: a #GstRTSPWatch
3255 * Decreases the reference count of @watch by one. If the resulting reference
3256 * count is zero the watch and associated memory will be destroyed.
3259 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3261 g_return_if_fail (watch != NULL);
3263 g_source_unref ((GSource *) watch);
3267 * gst_rtsp_watch_write_data:
3268 * @watch: a #GstRTSPWatch
3269 * @data: the data to queue
3270 * @size: the size of @data
3271 * @id: (out) (allow-none): location for a message ID or %NULL
3273 * Write @data using the connection of the @watch. If it cannot be sent
3274 * immediately, it will be queued for transmission in @watch. The contents of
3275 * @message will then be serialized and transmitted when the connection of the
3276 * @watch becomes writable. In case the @message is queued, the ID returned in
3277 * @id will be non-zero and used as the ID argument in the message_sent
3280 * This function will take ownership of @data and g_free() it after use.
3282 * Returns: #GST_RTSP_OK on success.
3285 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3286 guint size, guint * id)
3291 GMainContext *context = NULL;
3293 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3294 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3295 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3297 g_mutex_lock (&watch->mutex);
3299 /* try to send the message synchronously first */
3300 if (watch->messages->length == 0 && watch->write_data == NULL) {
3302 write_bytes (watch->conn->write_socket, data, &off, size,
3303 watch->conn->cancellable);
3304 if (res != GST_RTSP_EINTR) {
3307 g_free ((gpointer) data);
3312 /* make a record with the data and id for sending async */
3313 rec = g_slice_new (GstRTSPRec);
3315 rec->data = (guint8 *) data;
3318 rec->data = g_memdup (data + off, size - off);
3319 rec->size = size - off;
3320 g_free ((gpointer) data);
3324 /* make sure rec->id is never 0 */
3325 rec->id = ++watch->id;
3326 } while (G_UNLIKELY (rec->id == 0));
3328 /* add the record to a queue. FIXME we would like to have an upper limit here */
3329 g_queue_push_head (watch->messages, rec);
3331 /* make sure the main context will now also check for writability on the
3333 if (watch->writefd.events != WRITE_COND) {
3334 watch->writefd.events = WRITE_COND;
3335 context = ((GSource *) watch)->context;
3343 g_mutex_unlock (&watch->mutex);
3346 g_main_context_wakeup (context);
3352 * gst_rtsp_watch_send_message:
3353 * @watch: a #GstRTSPWatch
3354 * @message: a #GstRTSPMessage
3355 * @id: (out) (allow-none): location for a message ID or %NULL
3357 * Send a @message using the connection of the @watch. If it cannot be sent
3358 * immediately, it will be queued for transmission in @watch. The contents of
3359 * @message will then be serialized and transmitted when the connection of the
3360 * @watch becomes writable. In case the @message is queued, the ID returned in
3361 * @id will be non-zero and used as the ID argument in the message_sent
3364 * Returns: #GST_RTSP_OK on success.
3367 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3373 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3374 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3376 /* make a record with the message as a string and id */
3377 str = message_to_string (watch->conn, message);
3379 return gst_rtsp_watch_write_data (watch,
3380 (guint8 *) g_string_free (str, FALSE), size, id);