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., 51 Franklin St, Fifth Floor,
17 * Boston, MA 02110-1301, 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 zero terminated data already
234 * read from @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 g_clear_error (&err);
1090 return GST_RTSP_EINTR;
1093 g_clear_error (&err);
1094 return GST_RTSP_ESYS;
1097 if (read_ahead == ' ' || read_ahead == '\t') {
1098 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1099 /* got \r\n\r followed by whitespace, treat it as a normal line
1100 * followed by one starting with LWS */
1101 conn->read_ahead = read_ahead;
1104 /* got LWS, change the line ending to a space and continue */
1106 conn->read_ahead = read_ahead;
1108 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1109 if (read_ahead == '\r' || read_ahead == '\n') {
1110 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1111 conn->read_ahead = READ_AHEAD_EOH;
1114 /* got \r\n\r followed by something else, this is not really
1115 * supported since we have probably just eaten the first character
1116 * of the body or the next message, so just ignore the second \r
1117 * and live with it... */
1118 conn->read_ahead = read_ahead;
1121 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1122 if (read_ahead == '\r') {
1123 /* got \r\n\r so far, need one more character... */
1124 conn->read_ahead = READ_AHEAD_CRLFCR;
1126 } else if (read_ahead == '\n') {
1127 /* got \r\n\n, treat it as the end of the headers */
1128 conn->read_ahead = READ_AHEAD_EOH;
1131 /* found the end of a line, keep read_ahead for the next line */
1132 conn->read_ahead = read_ahead;
1135 } else if (c == read_ahead) {
1136 /* got double \r or \n, treat it as the end of the headers */
1137 conn->read_ahead = READ_AHEAD_EOH;
1139 } else if (c == '\r' && read_ahead == '\n') {
1140 /* got \r\n so far, still need more to know what to do... */
1141 conn->read_ahead = READ_AHEAD_CRLF;
1144 /* found the end of a line, keep read_ahead for the next line */
1145 conn->read_ahead = read_ahead;
1150 if (G_LIKELY (*idx < size - 1))
1151 buffer[(*idx)++] = c;
1153 buffer[*idx] = '\0';
1159 * gst_rtsp_connection_write:
1160 * @conn: a #GstRTSPConnection
1161 * @data: the data to write
1162 * @size: the size of @data
1163 * @timeout: a timeout value or #NULL
1165 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1166 * the specified @timeout. @timeout can be #NULL, in which case this function
1167 * might block forever.
1169 * This function can be cancelled with gst_rtsp_connection_flush().
1171 * Returns: #GST_RTSP_OK on success.
1174 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1175 guint size, GTimeVal * timeout)
1182 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1183 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1184 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
1186 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1193 write_bytes (conn->write_socket, data, &offset, size,
1195 if (G_LIKELY (res == GST_RTSP_OK))
1197 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1200 /* not all is written, wait until we can write more */
1201 g_socket_set_timeout (conn->write_socket,
1202 (to + GST_SECOND - 1) / GST_SECOND);
1203 if (!g_socket_condition_wait (conn->write_socket,
1204 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable, &err)) {
1205 g_socket_set_timeout (conn->write_socket, 0);
1206 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1207 g_clear_error (&err);
1209 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1210 g_clear_error (&err);
1213 g_clear_error (&err);
1216 g_socket_set_timeout (conn->write_socket, 0);
1223 return GST_RTSP_ETIMEOUT;
1227 return GST_RTSP_ESYS;
1231 return GST_RTSP_EINTR;
1240 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1242 GString *str = NULL;
1244 str = g_string_new ("");
1246 switch (message->type) {
1247 case GST_RTSP_MESSAGE_REQUEST:
1248 /* create request string, add CSeq */
1249 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1251 gst_rtsp_method_as_text (message->type_data.request.method),
1252 message->type_data.request.uri, conn->cseq++);
1253 /* add session id if we have one */
1254 if (conn->session_id[0] != '\0') {
1255 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1256 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1259 /* add any authentication headers */
1260 add_auth_header (conn, message);
1262 case GST_RTSP_MESSAGE_RESPONSE:
1263 /* create response string */
1264 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1265 message->type_data.response.code, message->type_data.response.reason);
1267 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1268 /* create request string */
1269 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1270 gst_rtsp_method_as_text (message->type_data.request.method),
1271 message->type_data.request.uri,
1272 gst_rtsp_version_as_text (message->type_data.request.version));
1273 /* add any authentication headers */
1274 add_auth_header (conn, message);
1276 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1277 /* create response string */
1278 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1279 gst_rtsp_version_as_text (message->type_data.request.version),
1280 message->type_data.response.code, message->type_data.response.reason);
1282 case GST_RTSP_MESSAGE_DATA:
1284 guint8 data_header[4];
1286 /* prepare data header */
1287 data_header[0] = '$';
1288 data_header[1] = message->type_data.data.channel;
1289 data_header[2] = (message->body_size >> 8) & 0xff;
1290 data_header[3] = message->body_size & 0xff;
1292 /* create string with header and data */
1293 str = g_string_append_len (str, (gchar *) data_header, 4);
1295 g_string_append_len (str, (gchar *) message->body,
1296 message->body_size);
1300 g_string_free (str, TRUE);
1301 g_return_val_if_reached (NULL);
1305 /* append headers and body */
1306 if (message->type != GST_RTSP_MESSAGE_DATA) {
1307 gchar date_string[100];
1309 gen_date_string (date_string, sizeof (date_string));
1311 /* add date header */
1312 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1313 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1315 /* append headers */
1316 gst_rtsp_message_append_headers (message, str);
1318 /* append Content-Length and body if needed */
1319 if (message->body != NULL && message->body_size > 0) {
1322 len = g_strdup_printf ("%d", message->body_size);
1323 g_string_append_printf (str, "%s: %s\r\n",
1324 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1326 /* header ends here */
1327 g_string_append (str, "\r\n");
1329 g_string_append_len (str, (gchar *) message->body,
1330 message->body_size);
1332 /* just end headers */
1333 g_string_append (str, "\r\n");
1341 * gst_rtsp_connection_send:
1342 * @conn: a #GstRTSPConnection
1343 * @message: the message to send
1344 * @timeout: a timeout value or #NULL
1346 * Attempt to send @message to the connected @conn, blocking up to
1347 * the specified @timeout. @timeout can be #NULL, in which case this function
1348 * might block forever.
1350 * This function can be cancelled with gst_rtsp_connection_flush().
1352 * Returns: #GST_RTSP_OK on success.
1355 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1358 GString *string = NULL;
1363 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1364 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1366 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1369 if (conn->tunneled) {
1370 str = g_base64_encode ((const guchar *) string->str, string->len);
1371 g_string_free (string, TRUE);
1376 g_string_free (string, FALSE);
1380 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1388 g_warning ("Wrong message");
1389 return GST_RTSP_EINVAL;
1393 static GstRTSPResult
1394 parse_string (gchar * dest, gint size, gchar ** src)
1396 GstRTSPResult res = GST_RTSP_OK;
1401 while (g_ascii_isspace (**src))
1404 while (!g_ascii_isspace (**src) && **src != '\0') {
1406 dest[idx++] = **src;
1408 res = GST_RTSP_EPARSE;
1417 static GstRTSPResult
1418 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1419 GstRTSPVersion * version)
1421 GstRTSPResult res = GST_RTSP_OK;
1424 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1431 /* the version number must be formatted as X.Y with nothing following */
1432 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1433 res = GST_RTSP_EPARSE;
1435 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1436 if (major != 1 || minor != 0) {
1437 *version = GST_RTSP_VERSION_INVALID;
1438 res = GST_RTSP_ERROR;
1440 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1441 if (*type == GST_RTSP_MESSAGE_REQUEST)
1442 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1443 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1444 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1446 if (major == 1 && minor == 1) {
1447 *version = GST_RTSP_VERSION_1_1;
1448 } else if (major != 1 || minor != 0) {
1449 *version = GST_RTSP_VERSION_INVALID;
1450 res = GST_RTSP_ERROR;
1453 res = GST_RTSP_EPARSE;
1455 res = GST_RTSP_EPARSE;
1460 static GstRTSPResult
1461 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1463 GstRTSPResult res = GST_RTSP_OK;
1465 gchar versionstr[20];
1470 bptr = (gchar *) buffer;
1472 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1473 res = GST_RTSP_EPARSE;
1475 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1476 res = GST_RTSP_EPARSE;
1477 code = atoi (codestr);
1478 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1479 res = GST_RTSP_EPARSE;
1481 while (g_ascii_isspace (*bptr))
1484 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1485 NULL) != GST_RTSP_OK))
1486 res = GST_RTSP_EPARSE;
1488 res2 = parse_protocol_version (versionstr, &msg->type,
1489 &msg->type_data.response.version);
1490 if (G_LIKELY (res == GST_RTSP_OK))
1496 static GstRTSPResult
1497 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1499 GstRTSPResult res = GST_RTSP_OK;
1501 gchar versionstr[20];
1502 gchar methodstr[20];
1505 GstRTSPMethod method;
1507 bptr = (gchar *) buffer;
1509 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1510 res = GST_RTSP_EPARSE;
1511 method = gst_rtsp_find_method (methodstr);
1513 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1514 res = GST_RTSP_EPARSE;
1515 if (G_UNLIKELY (*urlstr == '\0'))
1516 res = GST_RTSP_EPARSE;
1518 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1519 res = GST_RTSP_EPARSE;
1521 if (G_UNLIKELY (*bptr != '\0'))
1522 res = GST_RTSP_EPARSE;
1524 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1525 urlstr) != GST_RTSP_OK))
1526 res = GST_RTSP_EPARSE;
1528 res2 = parse_protocol_version (versionstr, &msg->type,
1529 &msg->type_data.request.version);
1530 if (G_LIKELY (res == GST_RTSP_OK))
1533 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1534 /* GET and POST are not allowed as RTSP methods */
1535 if (msg->type_data.request.method == GST_RTSP_GET ||
1536 msg->type_data.request.method == GST_RTSP_POST) {
1537 msg->type_data.request.method = GST_RTSP_INVALID;
1538 if (res == GST_RTSP_OK)
1539 res = GST_RTSP_ERROR;
1541 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1542 /* only GET and POST are allowed as HTTP methods */
1543 if (msg->type_data.request.method != GST_RTSP_GET &&
1544 msg->type_data.request.method != GST_RTSP_POST) {
1545 msg->type_data.request.method = GST_RTSP_INVALID;
1546 if (res == GST_RTSP_OK)
1547 res = GST_RTSP_ERROR;
1554 /* parsing lines means reading a Key: Value pair */
1555 static GstRTSPResult
1556 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1558 GstRTSPHeaderField field;
1559 gchar *line = (gchar *) buffer;
1562 if ((value = strchr (line, ':')) == NULL || value == line)
1565 /* trim space before the colon */
1566 if (value[-1] == ' ')
1569 /* replace the colon with a NUL */
1572 /* find the header */
1573 field = gst_rtsp_find_header_field (line);
1574 if (field == GST_RTSP_HDR_INVALID)
1577 /* split up the value in multiple key:value pairs if it contains comma(s) */
1578 while (*value != '\0') {
1580 gchar *comma = NULL;
1581 gboolean quoted = FALSE;
1584 /* trim leading space */
1588 /* for headers which may not appear multiple times, and thus may not
1589 * contain multiple values on the same line, we can short-circuit the loop
1590 * below and the entire value results in just one key:value pair*/
1591 if (!gst_rtsp_header_allow_multiple (field))
1592 next_value = value + strlen (value);
1596 /* find the next value, taking special care of quotes and comments */
1597 while (*next_value != '\0') {
1598 if ((quoted || comment != 0) && *next_value == '\\' &&
1599 next_value[1] != '\0')
1601 else if (comment == 0 && *next_value == '"')
1603 else if (!quoted && *next_value == '(')
1605 else if (comment != 0 && *next_value == ')')
1607 else if (!quoted && comment == 0) {
1608 /* To quote RFC 2068: "User agents MUST take special care in parsing
1609 * the WWW-Authenticate field value if it contains more than one
1610 * challenge, or if more than one WWW-Authenticate header field is
1611 * provided, since the contents of a challenge may itself contain a
1612 * comma-separated list of authentication parameters."
1614 * What this means is that we cannot just look for an unquoted comma
1615 * when looking for multiple values in Proxy-Authenticate and
1616 * WWW-Authenticate headers. Instead we need to look for the sequence
1617 * "comma [space] token space token" before we can split after the
1620 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1621 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1622 if (*next_value == ',') {
1623 if (next_value[1] == ' ') {
1624 /* skip any space following the comma so we do not mistake it for
1625 * separating between two tokens */
1629 } else if (*next_value == ' ' && next_value[1] != ',' &&
1630 next_value[1] != '=' && comma != NULL) {
1635 } else if (*next_value == ',')
1643 if (value != next_value && next_value[-1] == ' ')
1644 next_value[-1] = '\0';
1646 if (*next_value != '\0')
1647 *next_value++ = '\0';
1649 /* add the key:value pair */
1651 gst_rtsp_message_add_header (msg, field, value);
1662 return GST_RTSP_EPARSE;
1666 /* convert all consecutive whitespace to a single space */
1668 normalize_line (guint8 * buffer)
1671 if (g_ascii_isspace (*buffer)) {
1675 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1678 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1686 * GST_RTSP_OK when a complete message was read.
1687 * GST_RTSP_EEOF: when the read socket is closed
1688 * GST_RTSP_EINTR: when more data is needed.
1689 * GST_RTSP_..: some other error occured.
1691 static GstRTSPResult
1692 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1693 GstRTSPConnection * conn)
1698 switch (builder->state) {
1703 builder->offset = 0;
1705 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1706 if (res != GST_RTSP_OK)
1709 c = builder->buffer[0];
1711 /* we have 1 bytes now and we can see if this is a data message or
1714 /* data message, prepare for the header */
1715 builder->state = STATE_DATA_HEADER;
1716 } else if (c == '\n' || c == '\r') {
1717 /* skip \n and \r */
1718 builder->offset = 0;
1721 builder->state = STATE_READ_LINES;
1725 case STATE_DATA_HEADER:
1728 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1729 if (res != GST_RTSP_OK)
1732 gst_rtsp_message_init_data (message, builder->buffer[1]);
1734 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1735 builder->body_data = g_malloc (builder->body_len + 1);
1736 builder->body_data[builder->body_len] = '\0';
1737 builder->offset = 0;
1738 builder->state = STATE_DATA_BODY;
1741 case STATE_DATA_BODY:
1744 read_bytes (conn, builder->body_data, &builder->offset,
1746 if (res != GST_RTSP_OK)
1749 /* we have the complete body now, store in the message adjusting the
1750 * length to include the trailing '\0' */
1751 gst_rtsp_message_take_body (message,
1752 (guint8 *) builder->body_data, builder->body_len + 1);
1753 builder->body_data = NULL;
1754 builder->body_len = 0;
1756 builder->state = STATE_END;
1759 case STATE_READ_LINES:
1761 res = read_line (conn, builder->buffer, &builder->offset,
1762 sizeof (builder->buffer));
1763 if (res != GST_RTSP_OK)
1766 /* we have a regular response */
1767 if (builder->buffer[0] == '\0') {
1770 /* empty line, end of message header */
1771 /* see if there is a Content-Length header, but ignore it if this
1772 * is a POST request with an x-sessioncookie header */
1773 if (gst_rtsp_message_get_header (message,
1774 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1775 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1776 message->type_data.request.method != GST_RTSP_POST ||
1777 gst_rtsp_message_get_header (message,
1778 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1779 /* there is, prepare to read the body */
1780 builder->body_len = atol (hdrval);
1781 builder->body_data = g_try_malloc (builder->body_len + 1);
1782 /* we can't do much here, we need the length to know how many bytes
1783 * we need to read next and when allocation fails, something is
1784 * probably wrong with the length. */
1785 if (builder->body_data == NULL)
1786 goto invalid_body_len;
1788 builder->body_data[builder->body_len] = '\0';
1789 builder->offset = 0;
1790 builder->state = STATE_DATA_BODY;
1792 builder->state = STATE_END;
1797 /* we have a line */
1798 normalize_line (builder->buffer);
1799 if (builder->line == 0) {
1800 /* first line, check for response status */
1801 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1802 memcmp (builder->buffer, "HTTP", 4) == 0) {
1803 builder->status = parse_response_status (builder->buffer, message);
1805 builder->status = parse_request_line (builder->buffer, message);
1808 /* else just parse the line */
1809 res = parse_line (builder->buffer, message);
1810 if (res != GST_RTSP_OK)
1811 builder->status = res;
1814 builder->offset = 0;
1819 gchar *session_cookie;
1822 if (message->type == GST_RTSP_MESSAGE_DATA) {
1823 /* data messages don't have headers */
1828 /* save the tunnel session in the connection */
1829 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1830 !conn->manual_http &&
1831 conn->tstate == TUNNEL_STATE_NONE &&
1832 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1833 &session_cookie, 0) == GST_RTSP_OK) {
1834 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1835 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1836 conn->tunneled = TRUE;
1839 /* save session id in the connection for further use */
1840 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1841 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1842 &session_id, 0) == GST_RTSP_OK) {
1845 maxlen = sizeof (conn->session_id) - 1;
1846 /* the sessionid can have attributes marked with ;
1847 * Make sure we strip them */
1848 for (i = 0; session_id[i] != '\0'; i++) {
1849 if (session_id[i] == ';') {
1854 } while (g_ascii_isspace (session_id[i]));
1855 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1858 /* if we parsed something valid, configure */
1859 if ((to = atoi (&session_id[i + 8])) > 0)
1866 /* make sure to not overflow */
1867 strncpy (conn->session_id, session_id, maxlen);
1868 conn->session_id[maxlen] = '\0';
1870 res = builder->status;
1874 res = GST_RTSP_ERROR;
1884 GST_DEBUG ("could not allocate body");
1885 return GST_RTSP_ERROR;
1890 * gst_rtsp_connection_read:
1891 * @conn: a #GstRTSPConnection
1892 * @data: the data to read
1893 * @size: the size of @data
1894 * @timeout: a timeout value or #NULL
1896 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1897 * the specified @timeout. @timeout can be #NULL, in which case this function
1898 * might block forever.
1900 * This function can be cancelled with gst_rtsp_connection_flush().
1902 * Returns: #GST_RTSP_OK on success.
1905 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1913 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1914 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1915 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
1917 if (G_UNLIKELY (size == 0))
1922 /* configure timeout if any */
1923 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1926 res = read_bytes (conn, data, &offset, size);
1927 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1929 if (G_LIKELY (res == GST_RTSP_OK))
1931 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1934 g_socket_set_timeout (conn->read_socket,
1935 (to + GST_SECOND - 1) / GST_SECOND);
1936 if (!g_socket_condition_wait (conn->read_socket,
1937 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
1939 g_socket_set_timeout (conn->read_socket, 0);
1940 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1941 g_clear_error (&err);
1943 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1944 g_clear_error (&err);
1945 goto select_timeout;
1947 g_clear_error (&err);
1950 g_socket_set_timeout (conn->read_socket, 0);
1957 return GST_RTSP_ESYS;
1961 return GST_RTSP_ETIMEOUT;
1965 return GST_RTSP_EINTR;
1969 return GST_RTSP_EEOF;
1977 static GstRTSPMessage *
1978 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
1979 const GstRTSPMessage * request)
1981 GstRTSPMessage *msg;
1984 if (gst_rtsp_status_as_text (code) == NULL)
1985 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1987 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
1990 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
1991 "GStreamer RTSP Server");
1992 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
1993 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
1994 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
1996 if (code == GST_RTSP_STS_OK) {
1998 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2000 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2001 "application/x-rtsp-tunnelled");
2014 * gst_rtsp_connection_receive:
2015 * @conn: a #GstRTSPConnection
2016 * @message: the message to read
2017 * @timeout: a timeout value or #NULL
2019 * Attempt to read into @message from the connected @conn, blocking up to
2020 * the specified @timeout. @timeout can be #NULL, in which case this function
2021 * might block forever.
2023 * This function can be cancelled with gst_rtsp_connection_flush().
2025 * Returns: #GST_RTSP_OK on success.
2028 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2032 GstRTSPBuilder builder;
2036 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2037 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2038 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2040 /* configure timeout if any */
2041 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2043 memset (&builder, 0, sizeof (GstRTSPBuilder));
2045 res = build_next (&builder, message, conn);
2046 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2048 else if (G_LIKELY (res == GST_RTSP_OK)) {
2049 if (!conn->manual_http) {
2050 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2051 if (conn->tstate == TUNNEL_STATE_NONE &&
2052 message->type_data.request.method == GST_RTSP_GET) {
2053 GstRTSPMessage *response;
2055 conn->tstate = TUNNEL_STATE_GET;
2057 /* tunnel GET request, we can reply now */
2058 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2059 res = gst_rtsp_connection_send (conn, response, timeout);
2060 gst_rtsp_message_free (response);
2061 if (res == GST_RTSP_OK)
2062 res = GST_RTSP_ETGET;
2064 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2065 message->type_data.request.method == GST_RTSP_POST) {
2066 conn->tstate = TUNNEL_STATE_POST;
2068 /* tunnel POST request, the caller now has to link the two
2070 res = GST_RTSP_ETPOST;
2073 res = GST_RTSP_EPARSE;
2076 } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2077 res = GST_RTSP_EPARSE;
2083 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2086 g_socket_set_timeout (conn->read_socket,
2087 (to + GST_SECOND - 1) / GST_SECOND);
2088 if (!g_socket_condition_wait (conn->read_socket,
2089 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
2091 g_socket_set_timeout (conn->read_socket, 0);
2092 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
2093 g_clear_error (&err);
2095 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
2096 g_clear_error (&err);
2097 goto select_timeout;
2099 g_clear_error (&err);
2102 g_socket_set_timeout (conn->read_socket, 0);
2105 /* we have a message here */
2106 build_reset (&builder);
2113 res = GST_RTSP_ESYS;
2118 res = GST_RTSP_ETIMEOUT;
2123 res = GST_RTSP_EINTR;
2128 res = GST_RTSP_EEOF;
2134 build_reset (&builder);
2135 gst_rtsp_message_unset (message);
2141 * gst_rtsp_connection_close:
2142 * @conn: a #GstRTSPConnection
2144 * Close the connected @conn. After this call, the connection is in the same
2145 * state as when it was first created.
2147 * Returns: #GST_RTSP_OK on success.
2150 gst_rtsp_connection_close (GstRTSPConnection * conn)
2152 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2154 /* last unref closes the connection we don't want to explicitly close here
2155 * because these sockets might have been provided at construction */
2156 if (conn->socket0) {
2157 g_object_unref (conn->socket0);
2158 conn->socket0 = NULL;
2160 if (conn->socket1) {
2161 g_object_unref (conn->socket1);
2162 conn->socket1 = NULL;
2168 conn->read_ahead = 0;
2170 g_free (conn->initial_buffer);
2171 conn->initial_buffer = NULL;
2172 conn->initial_buffer_offset = 0;
2174 conn->write_socket = NULL;
2175 conn->read_socket = NULL;
2176 conn->tunneled = FALSE;
2177 conn->tstate = TUNNEL_STATE_NONE;
2179 g_free (conn->username);
2180 conn->username = NULL;
2181 g_free (conn->passwd);
2182 conn->passwd = NULL;
2183 gst_rtsp_connection_clear_auth_params (conn);
2186 conn->session_id[0] = '\0';
2192 * gst_rtsp_connection_free:
2193 * @conn: a #GstRTSPConnection
2195 * Close and free @conn.
2197 * Returns: #GST_RTSP_OK on success.
2200 gst_rtsp_connection_free (GstRTSPConnection * conn)
2204 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2206 res = gst_rtsp_connection_close (conn);
2208 if (conn->cancellable)
2209 g_object_unref (conn->cancellable);
2211 g_timer_destroy (conn->timer);
2212 gst_rtsp_url_free (conn->url);
2213 g_free (conn->proxy_host);
2220 * gst_rtsp_connection_poll:
2221 * @conn: a #GstRTSPConnection
2222 * @events: a bitmask of #GstRTSPEvent flags to check
2223 * @revents: location for result flags
2224 * @timeout: a timeout
2226 * Wait up to the specified @timeout for the connection to become available for
2227 * at least one of the operations specified in @events. When the function returns
2228 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2231 * @timeout can be #NULL, in which case this function might block forever.
2233 * This function can be cancelled with gst_rtsp_connection_flush().
2235 * Returns: #GST_RTSP_OK on success.
2238 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2239 GstRTSPEvent * revents, GTimeVal * timeout)
2243 GSource *rs, *ws, *ts;
2244 GIOCondition condition;
2246 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2247 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2248 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2249 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2250 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2252 ctx = g_main_context_new ();
2254 /* configure timeout if any */
2255 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2258 ts = g_timeout_source_new (to / GST_MSECOND);
2259 g_source_set_dummy_callback (ts);
2260 g_source_attach (ts, ctx);
2261 g_source_unref (ts);
2264 rs = g_socket_create_source (conn->read_socket,
2265 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable);
2266 g_source_set_dummy_callback (rs);
2267 g_source_attach (rs, ctx);
2268 g_source_unref (rs);
2270 ws = g_socket_create_source (conn->write_socket,
2271 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable);
2272 g_source_set_dummy_callback (ws);
2273 g_source_attach (ws, ctx);
2274 g_source_unref (ws);
2276 /* Returns after handling all pending events */
2277 g_main_context_iteration (ctx, TRUE);
2279 g_main_context_unref (ctx);
2282 g_socket_condition_check (conn->read_socket,
2283 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP);
2285 g_socket_condition_check (conn->write_socket,
2286 G_IO_OUT | G_IO_ERR | G_IO_HUP);
2289 if (events & GST_RTSP_EV_READ) {
2290 if ((condition & G_IO_IN) || (condition & G_IO_PRI))
2291 *revents |= GST_RTSP_EV_READ;
2293 if (events & GST_RTSP_EV_WRITE) {
2294 if ((condition & G_IO_OUT))
2295 *revents |= GST_RTSP_EV_WRITE;
2299 return GST_RTSP_ETIMEOUT;
2305 * gst_rtsp_connection_next_timeout:
2306 * @conn: a #GstRTSPConnection
2307 * @timeout: a timeout
2309 * Calculate the next timeout for @conn, storing the result in @timeout.
2311 * Returns: #GST_RTSP_OK.
2314 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2321 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2322 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2324 ctimeout = conn->timeout;
2325 if (ctimeout >= 20) {
2326 /* Because we should act before the timeout we timeout 5
2327 * seconds in advance. */
2329 } else if (ctimeout >= 5) {
2330 /* else timeout 20% earlier */
2331 ctimeout -= ctimeout / 5;
2332 } else if (ctimeout >= 1) {
2333 /* else timeout 1 second earlier */
2337 elapsed = g_timer_elapsed (conn->timer, &usec);
2338 if (elapsed >= ctimeout) {
2342 sec = ctimeout - elapsed;
2343 if (usec <= G_USEC_PER_SEC)
2344 usec = G_USEC_PER_SEC - usec;
2349 timeout->tv_sec = sec;
2350 timeout->tv_usec = usec;
2356 * gst_rtsp_connection_reset_timeout:
2357 * @conn: a #GstRTSPConnection
2359 * Reset the timeout of @conn.
2361 * Returns: #GST_RTSP_OK.
2364 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2366 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2368 g_timer_start (conn->timer);
2374 * gst_rtsp_connection_flush:
2375 * @conn: a #GstRTSPConnection
2376 * @flush: start or stop the flush
2378 * Start or stop the flushing action on @conn. When flushing, all current
2379 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2380 * is set to non-flushing mode again.
2382 * Returns: #GST_RTSP_OK.
2385 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2387 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2390 g_cancellable_cancel (conn->cancellable);
2392 g_cancellable_reset (conn->cancellable);
2398 * gst_rtsp_connection_set_proxy:
2399 * @conn: a #GstRTSPConnection
2400 * @host: the proxy host
2401 * @port: the proxy port
2403 * Set the proxy host and port.
2405 * Returns: #GST_RTSP_OK.
2408 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2409 const gchar * host, guint port)
2411 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2413 g_free (conn->proxy_host);
2414 conn->proxy_host = g_strdup (host);
2415 conn->proxy_port = port;
2421 * gst_rtsp_connection_set_auth:
2422 * @conn: a #GstRTSPConnection
2423 * @method: authentication method
2425 * @pass: the password
2427 * Configure @conn for authentication mode @method with @user and @pass as the
2428 * user and password respectively.
2430 * Returns: #GST_RTSP_OK.
2433 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2434 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2436 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2438 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2439 || g_strrstr (user, ":") != NULL))
2440 return GST_RTSP_EINVAL;
2442 /* Make sure the username and passwd are being set for authentication */
2443 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2444 return GST_RTSP_EINVAL;
2446 /* ":" chars are not allowed in usernames for basic auth */
2447 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2448 return GST_RTSP_EINVAL;
2450 g_free (conn->username);
2451 g_free (conn->passwd);
2453 conn->auth_method = method;
2454 conn->username = g_strdup (user);
2455 conn->passwd = g_strdup (pass);
2462 * @key: ASCII string to hash
2464 * Hashes @key in a case-insensitive manner.
2466 * Returns: the hash code.
2469 str_case_hash (gconstpointer key)
2471 const char *p = key;
2472 guint h = g_ascii_toupper (*p);
2475 for (p += 1; *p != '\0'; p++)
2476 h = (h << 5) - h + g_ascii_toupper (*p);
2483 * @v1: an ASCII string
2484 * @v2: another ASCII string
2486 * Compares @v1 and @v2 in a case-insensitive manner
2488 * Returns: %TRUE if they are equal (modulo case)
2491 str_case_equal (gconstpointer v1, gconstpointer v2)
2493 const char *string1 = v1;
2494 const char *string2 = v2;
2496 return g_ascii_strcasecmp (string1, string2) == 0;
2500 * gst_rtsp_connection_set_auth_param:
2501 * @conn: a #GstRTSPConnection
2502 * @param: authentication directive
2505 * Setup @conn with authentication directives. This is not necesary for
2506 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2507 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2508 * in the WWW-Authenticate response header and can include realm, domain,
2509 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2512 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2513 const gchar * param, const gchar * value)
2515 g_return_if_fail (conn != NULL);
2516 g_return_if_fail (param != NULL);
2518 if (conn->auth_params == NULL) {
2520 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2522 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2526 * gst_rtsp_connection_clear_auth_params:
2527 * @conn: a #GstRTSPConnection
2529 * Clear the list of authentication directives stored in @conn.
2532 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2534 g_return_if_fail (conn != NULL);
2536 if (conn->auth_params != NULL) {
2537 g_hash_table_destroy (conn->auth_params);
2538 conn->auth_params = NULL;
2542 static GstRTSPResult
2543 set_qos_dscp (GSocket * socket, guint qos_dscp)
2549 union gst_sockaddr sa;
2550 socklen_t slen = sizeof (sa);
2557 fd = g_socket_get_fd (socket);
2558 if (getsockname (fd, &sa.sa, &slen) < 0)
2559 goto no_getsockname;
2561 af = sa.sa.sa_family;
2563 /* if this is an IPv4-mapped address then do IPv4 QoS */
2564 if (af == AF_INET6) {
2565 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2569 /* extract and shift 6 bits of the DSCP */
2570 tos = (qos_dscp & 0x3f) << 2;
2574 if (setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2579 if (setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2593 return GST_RTSP_ESYS;
2597 return GST_RTSP_ERROR;
2603 * gst_rtsp_connection_set_qos_dscp:
2604 * @conn: a #GstRTSPConnection
2605 * @qos_dscp: DSCP value
2607 * Configure @conn to use the specified DSCP value.
2609 * Returns: #GST_RTSP_OK on success.
2612 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2616 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2617 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2618 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2620 res = set_qos_dscp (conn->socket0, qos_dscp);
2621 if (res == GST_RTSP_OK)
2622 res = set_qos_dscp (conn->socket1, qos_dscp);
2629 * gst_rtsp_connection_get_url:
2630 * @conn: a #GstRTSPConnection
2632 * Retrieve the URL of the other end of @conn.
2634 * Returns: The URL. This value remains valid until the
2635 * connection is freed.
2638 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2640 g_return_val_if_fail (conn != NULL, NULL);
2646 * gst_rtsp_connection_get_ip:
2647 * @conn: a #GstRTSPConnection
2649 * Retrieve the IP address of the other end of @conn.
2651 * Returns: The IP address as a string. this value remains valid until the
2652 * connection is closed.
2655 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2657 g_return_val_if_fail (conn != NULL, NULL);
2663 * gst_rtsp_connection_set_ip:
2664 * @conn: a #GstRTSPConnection
2665 * @ip: an ip address
2667 * Set the IP address of the server.
2670 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2672 g_return_if_fail (conn != NULL);
2675 conn->ip = g_strdup (ip);
2679 * gst_rtsp_connection_get_readfd:
2680 * @conn: a #GstRTSPConnection
2682 * Get the file descriptor for reading.
2684 * Returns: the file descriptor used for reading or %NULL on error. The file
2685 * descriptor remains valid until the connection is closed.
2688 gst_rtsp_connection_get_read_socket (const GstRTSPConnection * conn)
2690 g_return_val_if_fail (conn != NULL, NULL);
2691 g_return_val_if_fail (conn->read_socket != NULL, NULL);
2693 return conn->read_socket;
2697 * gst_rtsp_connection_get_write_socket:
2698 * @conn: a #GstRTSPConnection
2700 * Get the file descriptor for writing.
2702 * Returns: the file descriptor used for writing or NULL on error. The file
2703 * descriptor remains valid until the connection is closed.
2706 gst_rtsp_connection_get_write_socket (const GstRTSPConnection * conn)
2708 g_return_val_if_fail (conn != NULL, NULL);
2709 g_return_val_if_fail (conn->write_socket != NULL, NULL);
2711 return conn->write_socket;
2715 * gst_rtsp_connection_set_http_mode:
2716 * @conn: a #GstRTSPConnection
2717 * @enable: %TRUE to enable manual HTTP mode
2719 * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2720 * messages in addition to the RTSP messages. It will also disable the
2721 * automatic handling of setting up an HTTP tunnel.
2724 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2726 g_return_if_fail (conn != NULL);
2728 conn->manual_http = enable;
2732 * gst_rtsp_connection_set_tunneled:
2733 * @conn: a #GstRTSPConnection
2734 * @tunneled: the new state
2736 * Set the HTTP tunneling state of the connection. This must be configured before
2737 * the @conn is connected.
2740 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2742 g_return_if_fail (conn != NULL);
2743 g_return_if_fail (conn->read_socket == NULL);
2744 g_return_if_fail (conn->write_socket == NULL);
2746 conn->tunneled = tunneled;
2750 * gst_rtsp_connection_is_tunneled:
2751 * @conn: a #GstRTSPConnection
2753 * Get the tunneling state of the connection.
2755 * Returns: if @conn is using HTTP tunneling.
2758 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2760 g_return_val_if_fail (conn != NULL, FALSE);
2762 return conn->tunneled;
2766 * gst_rtsp_connection_get_tunnelid:
2767 * @conn: a #GstRTSPConnection
2769 * Get the tunnel session id the connection.
2771 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2774 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2776 g_return_val_if_fail (conn != NULL, NULL);
2778 if (!conn->tunneled)
2781 return conn->tunnelid;
2785 * gst_rtsp_connection_do_tunnel:
2786 * @conn: a #GstRTSPConnection
2787 * @conn2: a #GstRTSPConnection or %NULL
2789 * If @conn received the first tunnel connection and @conn2 received
2790 * the second tunnel connection, link the two connections together so that
2791 * @conn manages the tunneled connection.
2793 * After this call, @conn2 cannot be used anymore and must be freed with
2794 * gst_rtsp_connection_free().
2796 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2799 * Returns: return GST_RTSP_OK on success.
2802 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2803 GstRTSPConnection * conn2)
2805 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2807 if (conn2 != NULL) {
2808 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2809 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2810 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2811 TUNNELID_LEN), GST_RTSP_EINVAL);
2813 /* both connections have socket0 as the read/write socket. start by taking the
2814 * socket from conn2 and set it as the socket in conn */
2815 conn->socket1 = conn2->socket0;
2817 /* clean up some of the state of conn2 */
2818 g_cancellable_cancel (conn2->cancellable);
2820 g_object_unref (conn2->socket1);
2821 conn2->socket1 = NULL;
2822 conn2->write_socket = conn2->read_socket = NULL;
2823 g_cancellable_reset (conn2->cancellable);
2825 /* We make socket0 the write socket and socket1 the read socket. */
2826 conn->write_socket = conn->socket0;
2827 conn->read_socket = conn->socket1;
2829 conn->tstate = TUNNEL_STATE_COMPLETE;
2831 g_free (conn->initial_buffer);
2832 conn->initial_buffer = conn2->initial_buffer;
2833 conn2->initial_buffer = NULL;
2834 conn->initial_buffer_offset = conn2->initial_buffer_offset;
2837 /* we need base64 decoding for the readfd */
2838 conn->ctx.state = 0;
2841 conn->ctx.coutl = 0;
2842 conn->ctxp = &conn->ctx;
2847 #define READ_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2848 #define READ_COND (G_IO_IN | READ_ERR)
2849 #define WRITE_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2850 #define WRITE_COND (G_IO_OUT | WRITE_ERR)
2859 /* async functions */
2860 struct _GstRTSPWatch
2864 GstRTSPConnection *conn;
2866 GstRTSPBuilder builder;
2867 GstRTSPMessage message;
2872 /* queued message for transmission */
2881 GstRTSPWatchFuncs funcs;
2884 GDestroyNotify notify;
2888 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2890 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2892 if (watch->conn->initial_buffer != NULL)
2895 *timeout = (watch->conn->timeout * 1000);
2901 gst_rtsp_source_check (GSource * source)
2903 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2905 if (watch->readfd.revents & READ_COND)
2908 if (watch->writefd.revents & WRITE_COND)
2915 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2916 gpointer user_data G_GNUC_UNUSED)
2918 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2919 GstRTSPResult res = GST_RTSP_ERROR;
2920 gboolean keep_running = TRUE;
2922 /* first read as much as we can */
2923 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2925 if (watch->readfd.revents & READ_ERR)
2928 res = build_next (&watch->builder, &watch->message, watch->conn);
2929 if (res == GST_RTSP_EINTR)
2931 else if (G_UNLIKELY (res == GST_RTSP_EEOF)) {
2932 watch->readfd.events = 0;
2933 watch->readfd.revents = 0;
2934 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2935 /* When we are in tunnelled mode, the read socket can be closed and we
2936 * should be prepared for a new POST method to reopen it */
2937 if (watch->conn->tstate == TUNNEL_STATE_COMPLETE) {
2938 /* remove the read connection for the tunnel */
2939 /* we accept a new POST request */
2940 watch->conn->tstate = TUNNEL_STATE_GET;
2941 /* and signal that we lost our tunnel */
2942 if (watch->funcs.tunnel_lost)
2943 res = watch->funcs.tunnel_lost (watch, watch->user_data);
2947 } else if (G_LIKELY (res == GST_RTSP_OK)) {
2948 if (!watch->conn->manual_http &&
2949 watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2950 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2951 watch->message.type_data.request.method == GST_RTSP_GET) {
2952 GstRTSPMessage *response;
2953 GstRTSPStatusCode code;
2955 watch->conn->tstate = TUNNEL_STATE_GET;
2957 if (watch->funcs.tunnel_start)
2958 code = watch->funcs.tunnel_start (watch, watch->user_data);
2960 code = GST_RTSP_STS_OK;
2962 /* queue the response */
2963 response = gen_tunnel_reply (watch->conn, code, &watch->message);
2964 gst_rtsp_watch_send_message (watch, response, NULL);
2965 gst_rtsp_message_free (response);
2967 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2968 watch->message.type_data.request.method == GST_RTSP_POST) {
2969 watch->conn->tstate = TUNNEL_STATE_POST;
2971 /* in the callback the connection should be tunneled with the
2973 if (watch->funcs.tunnel_complete) {
2974 watch->funcs.tunnel_complete (watch, watch->user_data);
2975 keep_running = !(watch->conn->read_socket == NULL &&
2976 watch->conn->write_socket == NULL);
2985 if (!watch->conn->manual_http) {
2986 /* if manual HTTP support is not enabled, then restore the message to
2987 * what it would have looked like without the support for parsing HTTP
2988 * messages being present */
2989 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2990 watch->message.type = GST_RTSP_MESSAGE_REQUEST;
2991 watch->message.type_data.request.method = GST_RTSP_INVALID;
2992 if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
2993 watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
2994 res = GST_RTSP_EPARSE;
2995 } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2996 watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
2997 if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
2998 watch->message.type_data.response.version =
2999 GST_RTSP_VERSION_INVALID;
3000 res = GST_RTSP_EPARSE;
3004 if (G_LIKELY (res == GST_RTSP_OK)) {
3005 if (watch->funcs.message_received)
3006 watch->funcs.message_received (watch, &watch->message,
3013 gst_rtsp_message_unset (&watch->message);
3014 build_reset (&watch->builder);
3018 if (watch->writefd.revents & WRITE_COND) {
3019 if (watch->writefd.revents & WRITE_ERR)
3022 g_mutex_lock (&watch->mutex);
3024 if (watch->write_data == NULL) {
3027 /* get a new message from the queue */
3028 rec = g_queue_pop_tail (watch->messages);
3032 watch->write_off = 0;
3033 watch->write_data = rec->data;
3034 watch->write_size = rec->size;
3035 watch->write_id = rec->id;
3037 g_slice_free (GstRTSPRec, rec);
3040 res = write_bytes (watch->conn->write_socket, watch->write_data,
3041 &watch->write_off, watch->write_size, watch->conn->cancellable);
3042 g_mutex_unlock (&watch->mutex);
3044 if (res == GST_RTSP_EINTR)
3046 else if (G_LIKELY (res == GST_RTSP_OK)) {
3047 if (watch->funcs.message_sent)
3048 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3052 g_mutex_lock (&watch->mutex);
3054 g_free (watch->write_data);
3055 watch->write_data = NULL;
3058 watch->writefd.events = WRITE_ERR;
3060 g_mutex_unlock (&watch->mutex);
3065 return keep_running;
3070 if (watch->funcs.closed)
3071 watch->funcs.closed (watch, watch->user_data);
3073 /* always stop when the readfd returns EOF in non-tunneled mode */
3078 watch->readfd.events = 0;
3079 watch->readfd.revents = 0;
3080 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3081 keep_running = (watch->writefd.events != 0);
3084 if (watch->funcs.error_full)
3085 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3086 0, watch->user_data), error);
3094 watch->writefd.events = 0;
3095 watch->writefd.revents = 0;
3096 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3097 keep_running = (watch->readfd.events != 0);
3100 if (watch->funcs.error_full)
3101 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3102 watch->write_id, watch->user_data), error);
3110 if (watch->funcs.error)
3111 watch->funcs.error (watch, res, watch->user_data);
3113 return keep_running;
3118 gst_rtsp_rec_free (gpointer data)
3120 GstRTSPRec *rec = data;
3123 g_slice_free (GstRTSPRec, rec);
3127 gst_rtsp_source_finalize (GSource * source)
3129 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3131 build_reset (&watch->builder);
3132 gst_rtsp_message_unset (&watch->message);
3134 g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3135 g_queue_free (watch->messages);
3136 watch->messages = NULL;
3137 g_free (watch->write_data);
3139 g_mutex_clear (&watch->mutex);
3142 watch->notify (watch->user_data);
3145 static GSourceFuncs gst_rtsp_source_funcs = {
3146 gst_rtsp_source_prepare,
3147 gst_rtsp_source_check,
3148 gst_rtsp_source_dispatch,
3149 gst_rtsp_source_finalize,
3155 * gst_rtsp_watch_new:
3156 * @conn: a #GstRTSPConnection
3157 * @funcs: watch functions
3158 * @user_data: user data to pass to @funcs
3159 * @notify: notify when @user_data is not referenced anymore
3161 * Create a watch object for @conn. The functions provided in @funcs will be
3162 * called with @user_data when activity happened on the watch.
3164 * The new watch is usually created so that it can be attached to a
3165 * maincontext with gst_rtsp_watch_attach().
3167 * @conn must exist for the entire lifetime of the watch.
3169 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3170 * communication. Free with gst_rtsp_watch_unref () after usage.
3173 gst_rtsp_watch_new (GstRTSPConnection * conn,
3174 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3176 GstRTSPWatch *result;
3178 g_return_val_if_fail (conn != NULL, NULL);
3179 g_return_val_if_fail (funcs != NULL, NULL);
3180 g_return_val_if_fail (conn->read_socket != NULL, NULL);
3181 g_return_val_if_fail (conn->write_socket != NULL, NULL);
3183 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3184 sizeof (GstRTSPWatch));
3186 result->conn = conn;
3187 result->builder.state = STATE_START;
3189 g_mutex_init (&result->mutex);
3190 result->messages = g_queue_new ();
3192 result->readfd.fd = -1;
3193 result->writefd.fd = -1;
3195 gst_rtsp_watch_reset (result);
3197 result->funcs = *funcs;
3198 result->user_data = user_data;
3199 result->notify = notify;
3205 * gst_rtsp_watch_reset:
3206 * @watch: a #GstRTSPWatch
3208 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3209 * when the file descriptors of the connection might have changed.
3212 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3214 if (watch->readfd.fd != -1)
3215 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3216 if (watch->writefd.fd != -1)
3217 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3219 watch->readfd.fd = g_socket_get_fd (watch->conn->read_socket);
3220 watch->readfd.events = READ_COND;
3221 watch->readfd.revents = 0;
3223 watch->writefd.fd = g_socket_get_fd (watch->conn->write_socket);
3224 watch->writefd.events = WRITE_ERR;
3225 watch->writefd.revents = 0;
3227 if (watch->readfd.fd != -1)
3228 g_source_add_poll ((GSource *) watch, &watch->readfd);
3229 if (watch->writefd.fd != -1)
3230 g_source_add_poll ((GSource *) watch, &watch->writefd);
3234 * gst_rtsp_watch_attach:
3235 * @watch: a #GstRTSPWatch
3236 * @context: a GMainContext (if NULL, the default context will be used)
3238 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3240 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3243 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3245 g_return_val_if_fail (watch != NULL, 0);
3247 return g_source_attach ((GSource *) watch, context);
3251 * gst_rtsp_watch_unref:
3252 * @watch: a #GstRTSPWatch
3254 * Decreases the reference count of @watch by one. If the resulting reference
3255 * count is zero the watch and associated memory will be destroyed.
3258 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3260 g_return_if_fail (watch != NULL);
3262 g_source_unref ((GSource *) watch);
3266 * gst_rtsp_watch_write_data:
3267 * @watch: a #GstRTSPWatch
3268 * @data: the data to queue
3269 * @size: the size of @data
3270 * @id: (out) (allow-none): location for a message ID or %NULL
3272 * Write @data using the connection of the @watch. If it cannot be sent
3273 * immediately, it will be queued for transmission in @watch. The contents of
3274 * @message will then be serialized and transmitted when the connection of the
3275 * @watch becomes writable. In case the @message is queued, the ID returned in
3276 * @id will be non-zero and used as the ID argument in the message_sent
3279 * This function will take ownership of @data and g_free() it after use.
3281 * Returns: #GST_RTSP_OK on success.
3284 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3285 guint size, guint * id)
3290 GMainContext *context = NULL;
3292 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3293 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3294 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3296 g_mutex_lock (&watch->mutex);
3298 /* try to send the message synchronously first */
3299 if (watch->messages->length == 0 && watch->write_data == NULL) {
3301 write_bytes (watch->conn->write_socket, data, &off, size,
3302 watch->conn->cancellable);
3303 if (res != GST_RTSP_EINTR) {
3306 g_free ((gpointer) data);
3311 /* make a record with the data and id for sending async */
3312 rec = g_slice_new (GstRTSPRec);
3314 rec->data = (guint8 *) data;
3317 rec->data = g_memdup (data + off, size - off);
3318 rec->size = size - off;
3319 g_free ((gpointer) data);
3323 /* make sure rec->id is never 0 */
3324 rec->id = ++watch->id;
3325 } while (G_UNLIKELY (rec->id == 0));
3327 /* add the record to a queue. FIXME we would like to have an upper limit here */
3328 g_queue_push_head (watch->messages, rec);
3330 /* make sure the main context will now also check for writability on the
3332 if (watch->writefd.events != WRITE_COND) {
3333 watch->writefd.events = WRITE_COND;
3334 context = ((GSource *) watch)->context;
3342 g_mutex_unlock (&watch->mutex);
3345 g_main_context_wakeup (context);
3351 * gst_rtsp_watch_send_message:
3352 * @watch: a #GstRTSPWatch
3353 * @message: a #GstRTSPMessage
3354 * @id: (out) (allow-none): location for a message ID or %NULL
3356 * Send a @message using the connection of the @watch. If it cannot be sent
3357 * immediately, it will be queued for transmission in @watch. The contents of
3358 * @message will then be serialized and transmitted when the connection of the
3359 * @watch becomes writable. In case the @message is queued, the ID returned in
3360 * @id will be non-zero and used as the ID argument in the message_sent
3363 * Returns: #GST_RTSP_OK on success.
3366 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3372 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3373 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3375 /* make a record with the message as a string and id */
3376 str = message_to_string (watch->conn, message);
3378 return gst_rtsp_watch_write_data (watch,
3379 (guint8 *) g_string_free (str, FALSE), size, id);