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"
70 #include "gst/glib-compat-private.h"
76 struct sockaddr_in sa_in;
77 struct sockaddr_in6 sa_in6;
78 struct sockaddr_storage sa_stor;
86 guchar out[3]; /* the size must be evenly divisible by 3 */
92 #define SEND_FLAGS MSG_NOSIGNAL
102 TUNNEL_STATE_COMPLETE
103 } GstRTSPTunnelState;
105 #define TUNNELID_LEN 24
107 struct _GstRTSPConnection
110 /* URL for the connection */
113 /* connection state */
114 GSocket *read_socket;
115 GSocket *write_socket;
116 gboolean manual_http;
117 GSocket *socket0, *socket1;
118 GCancellable *cancellable;
120 gchar tunnelid[TUNNELID_LEN];
122 GstRTSPTunnelState tstate;
128 gchar *initial_buffer;
129 gsize initial_buffer_offset;
132 gint cseq; /* sequence number */
133 gchar session_id[512]; /* session id */
134 gint timeout; /* session timeout in seconds */
135 GTimer *timer; /* timeout timer */
138 GstRTSPAuthMethod auth_method;
141 GHashTable *auth_params;
162 READ_AHEAD_EOH = -1, /* end of headers */
163 READ_AHEAD_CRLF = -2,
164 READ_AHEAD_CRLFCR = -3
167 /* a structure for constructing RTSPMessages */
171 GstRTSPResult status;
181 build_reset (GstRTSPBuilder * builder)
183 g_free (builder->body_data);
184 memset (builder, 0, sizeof (GstRTSPBuilder));
188 * gst_rtsp_connection_create:
189 * @url: a #GstRTSPUrl
190 * @conn: storage for a #GstRTSPConnection
192 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
193 * The connection will not yet attempt to connect to @url, use
194 * gst_rtsp_connection_connect().
196 * A copy of @url will be made.
198 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
201 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
203 GstRTSPConnection *newconn;
205 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
207 newconn = g_new0 (GstRTSPConnection, 1);
209 newconn->cancellable = g_cancellable_new ();
211 newconn->url = gst_rtsp_url_copy (url);
212 newconn->timer = g_timer_new ();
213 newconn->timeout = 60;
216 newconn->auth_method = GST_RTSP_AUTH_NONE;
217 newconn->username = NULL;
218 newconn->passwd = NULL;
219 newconn->auth_params = NULL;
227 * gst_rtsp_connection_create_from_socket:
228 * @socket: a #GSocket
229 * @ip: the IP address of the other end
230 * @port: the port used by the other end
231 * @initial_buffer: data already read from @fd
232 * @conn: storage for a #GstRTSPConnection
234 * Create a new #GstRTSPConnection for handling communication on the existing
235 * socket @socket. The @initial_buffer contains any data already read from
236 * @socket which should be used before starting to read new data.
238 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
243 gst_rtsp_connection_create_from_socket (GSocket * socket, const gchar * ip,
244 guint16 port, const gchar * initial_buffer, GstRTSPConnection ** conn)
246 GstRTSPConnection *newconn = NULL;
250 g_return_val_if_fail (G_IS_SOCKET (socket), GST_RTSP_EINVAL);
251 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
252 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
254 /* set to non-blocking mode so that we can cancel the communication */
255 g_socket_set_blocking (socket, FALSE);
257 /* create a url for the client address */
258 url = g_new0 (GstRTSPUrl, 1);
259 url->host = g_strdup (ip);
262 /* now create the connection object */
263 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
264 gst_rtsp_url_free (url);
266 /* both read and write initially */
267 newconn->socket0 = G_SOCKET (g_object_ref (socket));
268 newconn->socket1 = G_SOCKET (g_object_ref (socket));
269 newconn->write_socket = newconn->read_socket = newconn->socket0;
271 newconn->ip = g_strdup (ip);
273 newconn->initial_buffer = g_strdup (initial_buffer);
282 gst_rtsp_url_free (url);
288 * gst_rtsp_connection_accept:
290 * @conn: storage for a #GstRTSPConnection
291 * @cancellable: a #GCancellable to cancel the operation
293 * Accept a new connection on @socket and create a new #GstRTSPConnection for
294 * handling communication on new socket.
296 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
301 gst_rtsp_connection_accept (GSocket * socket, GstRTSPConnection ** conn,
302 GCancellable * cancellable)
307 GSocket *client_sock;
308 GSocketAddress *addr;
311 g_return_val_if_fail (G_IS_SOCKET (socket), GST_RTSP_EINVAL);
312 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
314 client_sock = g_socket_accept (socket, cancellable, &err);
318 addr = g_socket_get_remote_address (client_sock, &err);
320 goto getnameinfo_failed;
322 ip = g_inet_address_to_string (g_inet_socket_address_get_address
323 (G_INET_SOCKET_ADDRESS (addr)));
324 port = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
325 g_object_unref (addr);
328 gst_rtsp_connection_create_from_socket (client_sock, ip, port, NULL,
330 g_object_unref (client_sock);
338 GST_DEBUG ("Accepting client failed: %s", err->message);
339 g_clear_error (&err);
340 return GST_RTSP_ESYS;
344 if (!g_socket_close (client_sock, &err)) {
345 GST_DEBUG ("Closing socket failed: %s", err->message);
346 g_clear_error (&err);
348 g_object_unref (client_sock);
349 return GST_RTSP_ERROR;
354 do_resolve (const gchar * host, GCancellable * cancellable)
361 addr = g_inet_address_new_from_string (host);
365 resolver = g_resolver_get_default ();
367 results = g_resolver_lookup_by_name (resolver, host, cancellable, &err);
371 for (l = results; l; l = l->next) {
372 GInetAddress *tmp = l->data;
374 if (g_inet_address_get_family (tmp) == G_SOCKET_FAMILY_IPV4 ||
375 g_inet_address_get_family (tmp) == G_SOCKET_FAMILY_IPV6) {
376 addr = G_INET_ADDRESS (g_object_ref (tmp));
381 g_resolver_free_addresses (results);
382 g_object_unref (resolver);
388 ip = g_inet_address_to_string (addr);
389 g_object_unref (addr);
396 GST_ERROR ("failed to resolve %s: %s", host, err->message);
397 g_clear_error (&err);
398 g_object_unref (resolver);
404 do_connect (const gchar * ip, guint16 port, GSocket ** socket_out,
405 GTimeVal * timeout, GCancellable * cancellable)
410 GSocketAddress *saddr;
413 addr = g_inet_address_new_from_string (ip);
415 saddr = g_inet_socket_address_new (addr, port);
416 g_object_unref (addr);
419 g_socket_new (g_socket_address_get_family (saddr), G_SOCKET_TYPE_STREAM,
420 G_SOCKET_PROTOCOL_TCP, &err);
424 /* set to non-blocking mode so that we can cancel the connect */
425 g_socket_set_blocking (socket, FALSE);
427 /* we are going to connect ASYNC now */
428 if (!g_socket_connect (socket, saddr, cancellable, &err)) {
429 if (!g_error_matches (err, G_IO_ERROR, G_IO_ERROR_PENDING))
431 g_clear_error (&err);
436 /* wait for connect to complete up to the specified timeout or until we got
438 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
440 g_socket_set_timeout (socket, (to + GST_SECOND - 1) / GST_SECOND);
441 if (!g_socket_condition_wait (socket, G_IO_OUT, cancellable, &err)) {
442 g_socket_set_timeout (socket, 0);
443 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT))
448 g_socket_set_timeout (socket, 0);
450 if (!g_socket_check_connect_result (socket, &err))
454 g_object_unref (saddr);
456 *socket_out = socket;
463 GST_ERROR ("no socket: %s", err->message);
464 g_clear_error (&err);
465 g_object_unref (saddr);
466 return GST_RTSP_ESYS;
470 GST_ERROR ("system error: %s", err->message);
471 g_clear_error (&err);
472 g_object_unref (saddr);
473 g_object_unref (socket);
474 return GST_RTSP_ESYS;
478 GST_ERROR ("timeout");
479 g_clear_error (&err);
480 g_object_unref (saddr);
481 g_object_unref (socket);
482 return GST_RTSP_ETIMEOUT;
487 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
494 guint16 port, url_port;
498 GstRTSPMessage response;
501 memset (&response, 0, sizeof (response));
502 gst_rtsp_message_init (&response);
504 /* create a random sessionid */
505 for (i = 0; i < TUNNELID_LEN; i++)
506 conn->tunnelid[i] = g_random_int_range ('a', 'z');
507 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
510 /* get the port from the url */
511 gst_rtsp_url_get_port (url, &url_port);
513 if (conn->proxy_host) {
514 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
515 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
516 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
517 ip = conn->proxy_host;
518 port = conn->proxy_port;
520 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
521 url->query ? url->query : "");
527 /* create the GET request for the read connection */
528 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
530 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
532 if (hostparam != NULL)
533 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
534 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
536 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
537 "application/x-rtsp-tunnelled");
538 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
539 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
541 /* we start by writing to this fd */
542 conn->write_socket = conn->socket0;
544 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
545 * request from being base64 encoded */
546 conn->tunneled = FALSE;
547 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
548 gst_rtsp_message_free (msg);
549 conn->tunneled = TRUE;
551 /* receive the response to the GET request */
552 /* we need to temporarily set manual_http to TRUE since
553 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
554 * failure otherwise */
555 old_http = conn->manual_http;
556 conn->manual_http = TRUE;
557 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
559 conn->manual_http = old_http;
561 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
562 response.type_data.response.code != GST_RTSP_STS_OK)
565 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
566 &value, 0) == GST_RTSP_OK) {
567 if (conn->proxy_host) {
568 /* if we use a proxy we need to change the destination url */
570 url->host = g_strdup (value);
572 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
574 /* and resolve the new ip address */
575 if (!(ip = do_resolve (value, conn->cancellable)))
582 /* connect to the host/port */
583 res = do_connect (ip, port, &conn->socket1, timeout, conn->cancellable);
584 if (res != GST_RTSP_OK)
587 /* this is now our writing socket */
588 conn->write_socket = conn->socket1;
590 /* create the POST request for the write connection */
591 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
593 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
595 if (hostparam != NULL)
596 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
597 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
599 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
600 "application/x-rtsp-tunnelled");
601 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
602 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
603 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
604 "Sun, 9 Jan 1972 00:00:00 GMT");
605 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
607 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
608 * request from being base64 encoded */
609 conn->tunneled = FALSE;
610 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
611 gst_rtsp_message_free (msg);
612 conn->tunneled = TRUE;
615 gst_rtsp_message_unset (&response);
624 GST_ERROR ("failed to create request (%d)", res);
629 GST_ERROR ("write failed (%d)", res);
630 gst_rtsp_message_free (msg);
631 conn->tunneled = TRUE;
636 GST_ERROR ("read failed (%d)", res);
637 conn->manual_http = FALSE;
642 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
643 response.type_data.response.reason);
644 res = GST_RTSP_ERROR;
649 GST_ERROR ("could not resolve %s", conn->ip);
655 GST_ERROR ("failed to connect");
661 * gst_rtsp_connection_connect:
662 * @conn: a #GstRTSPConnection
663 * @timeout: a #GTimeVal timeout
665 * Attempt to connect to the url of @conn made with
666 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
667 * forever. If @timeout contains a valid timeout, this function will return
668 * #GST_RTSP_ETIMEOUT after the timeout expired.
670 * This function can be cancelled with gst_rtsp_connection_flush().
672 * Returns: #GST_RTSP_OK when a connection could be made.
675 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
682 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
683 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
684 g_return_val_if_fail (conn->socket0 == NULL, GST_RTSP_EINVAL);
688 if (conn->proxy_host && conn->tunneled) {
689 if (!(ip = do_resolve (conn->proxy_host, conn->cancellable))) {
690 GST_ERROR ("could not resolve %s", conn->proxy_host);
693 port = conn->proxy_port;
694 g_free (conn->proxy_host);
695 conn->proxy_host = ip;
697 if (!(ip = do_resolve (url->host, conn->cancellable))) {
698 GST_ERROR ("could not resolve %s", url->host);
701 /* get the port from the url */
702 gst_rtsp_url_get_port (url, &port);
708 /* connect to the host/port */
709 res = do_connect (ip, port, &conn->socket0, timeout, conn->cancellable);
710 if (res != GST_RTSP_OK)
713 /* this is our read URL */
714 conn->read_socket = conn->socket0;
716 if (conn->tunneled) {
717 res = setup_tunneling (conn, timeout);
718 if (res != GST_RTSP_OK)
719 goto tunneling_failed;
721 conn->write_socket = conn->socket0;
728 return GST_RTSP_ENET;
732 GST_ERROR ("failed to connect");
737 GST_ERROR ("failed to setup tunneling");
743 auth_digest_compute_hex_urp (const gchar * username,
744 const gchar * realm, const gchar * password, gchar hex_urp[33])
746 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
747 const gchar *digest_string;
749 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
750 g_checksum_update (md5_context, (const guchar *) ":", 1);
751 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
752 g_checksum_update (md5_context, (const guchar *) ":", 1);
753 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
754 digest_string = g_checksum_get_string (md5_context);
756 memset (hex_urp, 0, 33);
757 memcpy (hex_urp, digest_string, strlen (digest_string));
759 g_checksum_free (md5_context);
763 auth_digest_compute_response (const gchar * method,
764 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
767 char hex_a2[33] = { 0, };
768 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
769 const gchar *digest_string;
772 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
773 g_checksum_update (md5_context, (const guchar *) ":", 1);
774 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
775 digest_string = g_checksum_get_string (md5_context);
776 memcpy (hex_a2, digest_string, strlen (digest_string));
779 g_checksum_reset (md5_context);
780 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
781 g_checksum_update (md5_context, (const guchar *) ":", 1);
782 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
783 g_checksum_update (md5_context, (const guchar *) ":", 1);
785 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
786 digest_string = g_checksum_get_string (md5_context);
787 memset (response, 0, 33);
788 memcpy (response, digest_string, strlen (digest_string));
790 g_checksum_free (md5_context);
794 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
796 switch (conn->auth_method) {
797 case GST_RTSP_AUTH_BASIC:{
802 if (conn->username == NULL || conn->passwd == NULL)
805 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
806 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
807 auth_string = g_strdup_printf ("Basic %s", user_pass64);
809 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
813 g_free (user_pass64);
816 case GST_RTSP_AUTH_DIGEST:{
817 gchar response[33], hex_urp[33];
818 gchar *auth_string, *auth_string2;
825 /* we need to have some params set */
826 if (conn->auth_params == NULL || conn->username == NULL ||
827 conn->passwd == NULL)
830 /* we need the realm and nonce */
831 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
832 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
833 if (realm == NULL || nonce == NULL)
836 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
839 method = gst_rtsp_method_as_text (message->type_data.request.method);
840 uri = message->type_data.request.uri;
842 /* Assume no qop, algorithm=md5, stale=false */
843 /* For algorithm MD5, a1 = urp. */
844 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
845 auth_string = g_strdup_printf ("Digest username=\"%s\", "
846 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
847 conn->username, realm, nonce, uri, response);
849 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
851 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
853 g_free (auth_string);
854 auth_string = auth_string2;
856 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
867 gen_date_string (gchar * date_string, guint len)
869 static const char wkdays[7][4] =
870 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
871 static const char months[12][4] =
872 { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
886 g_snprintf (date_string, len, "%s, %02d %s %04d %02d:%02d:%02d GMT",
887 wkdays[tm.tm_wday], tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900,
888 tm.tm_hour, tm.tm_min, tm.tm_sec);
892 write_bytes (GSocket * socket, const guint8 * buffer, guint * idx, guint size,
893 GCancellable * cancellable)
897 if (G_UNLIKELY (*idx > size))
898 return GST_RTSP_ERROR;
906 r = g_socket_send (socket, (gchar *) & buffer[*idx], left, cancellable,
908 if (G_UNLIKELY (r == 0)) {
909 return GST_RTSP_EINTR;
910 } else if (G_UNLIKELY (r < 0)) {
911 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
912 g_clear_error (&err);
913 return GST_RTSP_EINTR;
915 g_clear_error (&err);
916 return GST_RTSP_ESYS;
926 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size,
931 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
932 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
934 out = MIN (left, size);
935 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
937 if (left == (gsize) out) {
938 g_free (conn->initial_buffer);
939 conn->initial_buffer = NULL;
940 conn->initial_buffer_offset = 0;
942 conn->initial_buffer_offset += out;
945 if (G_LIKELY (size > (guint) out)) {
948 r = g_socket_receive (conn->read_socket, (gchar *) & buffer[out],
949 size - out, conn->cancellable, err);
961 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size,
964 DecodeCtx *ctx = conn->ctxp;
969 guint8 in[sizeof (ctx->out) * 4 / 3];
972 while (size > 0 && ctx->cout < ctx->coutl) {
973 /* we have some leftover bytes */
974 *buffer++ = ctx->out[ctx->cout++];
979 /* got what we needed? */
983 /* try to read more bytes */
984 r = fill_raw_bytes (conn, in, sizeof (in), err);
993 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
997 out = fill_raw_bytes (conn, buffer, size, err);
1003 static GstRTSPResult
1004 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1009 if (G_UNLIKELY (*idx > size))
1010 return GST_RTSP_ERROR;
1017 r = fill_bytes (conn, &buffer[*idx], left, &err);
1018 if (G_UNLIKELY (r == 0)) {
1019 return GST_RTSP_EEOF;
1020 } else if (G_UNLIKELY (r < 0)) {
1021 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1022 g_clear_error (&err);
1023 return GST_RTSP_EINTR;
1025 g_clear_error (&err);
1026 return GST_RTSP_ESYS;
1035 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1036 * end of a line. It even does its best to handle clients which mix them (even
1037 * though this is a really stupid idea (tm).) It also handles Line White Space
1038 * (LWS), where a line end followed by whitespace is considered LWS. This is
1039 * the method used in RTSP (and HTTP) to break long lines.
1041 static GstRTSPResult
1042 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1050 if (conn->read_ahead == READ_AHEAD_EOH) {
1051 /* the last call to read_line() already determined that we have reached
1052 * the end of the headers, so convey that information now */
1053 conn->read_ahead = 0;
1055 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1056 /* the last call to read_line() left off after having read \r\n */
1058 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1059 /* the last call to read_line() left off after having read \r\n\r */
1061 } else if (conn->read_ahead != 0) {
1062 /* the last call to read_line() left us with a character to start with */
1063 c = (guint8) conn->read_ahead;
1064 conn->read_ahead = 0;
1066 /* read the next character */
1067 r = fill_bytes (conn, &c, 1, &err);
1068 if (G_UNLIKELY (r == 0)) {
1069 return GST_RTSP_EEOF;
1070 } else if (G_UNLIKELY (r < 0)) {
1071 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1072 g_clear_error (&err);
1073 return GST_RTSP_EINTR;
1076 g_clear_error (&err);
1077 return GST_RTSP_ESYS;
1081 /* special treatment of line endings */
1082 if (c == '\r' || c == '\n') {
1086 /* need to read ahead one more character to know what to do... */
1087 r = fill_bytes (conn, &read_ahead, 1, &err);
1088 if (G_UNLIKELY (r == 0)) {
1089 return GST_RTSP_EEOF;
1090 } else if (G_UNLIKELY (r < 0)) {
1091 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1092 /* remember the original character we read and try again next time */
1093 if (conn->read_ahead == 0)
1094 conn->read_ahead = c;
1095 return GST_RTSP_EINTR;
1096 g_clear_error (&err);
1097 return GST_RTSP_EINTR;
1100 g_clear_error (&err);
1101 return GST_RTSP_ESYS;
1104 if (read_ahead == ' ' || read_ahead == '\t') {
1105 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1106 /* got \r\n\r followed by whitespace, treat it as a normal line
1107 * followed by one starting with LWS */
1108 conn->read_ahead = read_ahead;
1111 /* got LWS, change the line ending to a space and continue */
1113 conn->read_ahead = read_ahead;
1115 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1116 if (read_ahead == '\r' || read_ahead == '\n') {
1117 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1118 conn->read_ahead = READ_AHEAD_EOH;
1121 /* got \r\n\r followed by something else, this is not really
1122 * supported since we have probably just eaten the first character
1123 * of the body or the next message, so just ignore the second \r
1124 * and live with it... */
1125 conn->read_ahead = read_ahead;
1128 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1129 if (read_ahead == '\r') {
1130 /* got \r\n\r so far, need one more character... */
1131 conn->read_ahead = READ_AHEAD_CRLFCR;
1133 } else if (read_ahead == '\n') {
1134 /* got \r\n\n, treat it as the end of the headers */
1135 conn->read_ahead = READ_AHEAD_EOH;
1138 /* found the end of a line, keep read_ahead for the next line */
1139 conn->read_ahead = read_ahead;
1142 } else if (c == read_ahead) {
1143 /* got double \r or \n, treat it as the end of the headers */
1144 conn->read_ahead = READ_AHEAD_EOH;
1146 } else if (c == '\r' && read_ahead == '\n') {
1147 /* got \r\n so far, still need more to know what to do... */
1148 conn->read_ahead = READ_AHEAD_CRLF;
1151 /* found the end of a line, keep read_ahead for the next line */
1152 conn->read_ahead = read_ahead;
1157 if (G_LIKELY (*idx < size - 1))
1158 buffer[(*idx)++] = c;
1160 buffer[*idx] = '\0';
1166 * gst_rtsp_connection_write:
1167 * @conn: a #GstRTSPConnection
1168 * @data: the data to write
1169 * @size: the size of @data
1170 * @timeout: a timeout value or #NULL
1172 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1173 * the specified @timeout. @timeout can be #NULL, in which case this function
1174 * might block forever.
1176 * This function can be cancelled with gst_rtsp_connection_flush().
1178 * Returns: #GST_RTSP_OK on success.
1181 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1182 guint size, GTimeVal * timeout)
1189 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1190 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1191 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
1193 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1200 write_bytes (conn->write_socket, data, &offset, size,
1202 if (G_LIKELY (res == GST_RTSP_OK))
1204 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1207 /* not all is written, wait until we can write more */
1208 g_socket_set_timeout (conn->write_socket,
1209 (to + GST_SECOND - 1) / GST_SECOND);
1210 if (!g_socket_condition_wait (conn->write_socket,
1211 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable, &err)) {
1212 g_socket_set_timeout (conn->write_socket, 0);
1213 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1214 g_clear_error (&err);
1216 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1217 g_clear_error (&err);
1220 g_clear_error (&err);
1223 g_socket_set_timeout (conn->write_socket, 0);
1230 return GST_RTSP_ETIMEOUT;
1234 return GST_RTSP_ESYS;
1238 return GST_RTSP_EINTR;
1247 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1249 GString *str = NULL;
1251 str = g_string_new ("");
1253 switch (message->type) {
1254 case GST_RTSP_MESSAGE_REQUEST:
1255 /* create request string, add CSeq */
1256 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1258 gst_rtsp_method_as_text (message->type_data.request.method),
1259 message->type_data.request.uri, conn->cseq++);
1260 /* add session id if we have one */
1261 if (conn->session_id[0] != '\0') {
1262 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1263 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1266 /* add any authentication headers */
1267 add_auth_header (conn, message);
1269 case GST_RTSP_MESSAGE_RESPONSE:
1270 /* create response string */
1271 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1272 message->type_data.response.code, message->type_data.response.reason);
1274 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1275 /* create request string */
1276 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1277 gst_rtsp_method_as_text (message->type_data.request.method),
1278 message->type_data.request.uri,
1279 gst_rtsp_version_as_text (message->type_data.request.version));
1280 /* add any authentication headers */
1281 add_auth_header (conn, message);
1283 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1284 /* create response string */
1285 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1286 gst_rtsp_version_as_text (message->type_data.request.version),
1287 message->type_data.response.code, message->type_data.response.reason);
1289 case GST_RTSP_MESSAGE_DATA:
1291 guint8 data_header[4];
1293 /* prepare data header */
1294 data_header[0] = '$';
1295 data_header[1] = message->type_data.data.channel;
1296 data_header[2] = (message->body_size >> 8) & 0xff;
1297 data_header[3] = message->body_size & 0xff;
1299 /* create string with header and data */
1300 str = g_string_append_len (str, (gchar *) data_header, 4);
1302 g_string_append_len (str, (gchar *) message->body,
1303 message->body_size);
1307 g_string_free (str, TRUE);
1308 g_return_val_if_reached (NULL);
1312 /* append headers and body */
1313 if (message->type != GST_RTSP_MESSAGE_DATA) {
1314 gchar date_string[100];
1316 gen_date_string (date_string, sizeof (date_string));
1318 /* add date header */
1319 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1320 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1322 /* append headers */
1323 gst_rtsp_message_append_headers (message, str);
1325 /* append Content-Length and body if needed */
1326 if (message->body != NULL && message->body_size > 0) {
1329 len = g_strdup_printf ("%d", message->body_size);
1330 g_string_append_printf (str, "%s: %s\r\n",
1331 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1333 /* header ends here */
1334 g_string_append (str, "\r\n");
1336 g_string_append_len (str, (gchar *) message->body,
1337 message->body_size);
1339 /* just end headers */
1340 g_string_append (str, "\r\n");
1348 * gst_rtsp_connection_send:
1349 * @conn: a #GstRTSPConnection
1350 * @message: the message to send
1351 * @timeout: a timeout value or #NULL
1353 * Attempt to send @message to the connected @conn, blocking up to
1354 * the specified @timeout. @timeout can be #NULL, in which case this function
1355 * might block forever.
1357 * This function can be cancelled with gst_rtsp_connection_flush().
1359 * Returns: #GST_RTSP_OK on success.
1362 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1365 GString *string = NULL;
1370 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1371 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1373 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1376 if (conn->tunneled) {
1377 str = g_base64_encode ((const guchar *) string->str, string->len);
1378 g_string_free (string, TRUE);
1383 g_string_free (string, FALSE);
1387 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1395 g_warning ("Wrong message");
1396 return GST_RTSP_EINVAL;
1400 static GstRTSPResult
1401 parse_string (gchar * dest, gint size, gchar ** src)
1403 GstRTSPResult res = GST_RTSP_OK;
1408 while (g_ascii_isspace (**src))
1411 while (!g_ascii_isspace (**src) && **src != '\0') {
1413 dest[idx++] = **src;
1415 res = GST_RTSP_EPARSE;
1424 static GstRTSPResult
1425 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1426 GstRTSPVersion * version)
1428 GstRTSPResult res = GST_RTSP_OK;
1431 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1438 /* the version number must be formatted as X.Y with nothing following */
1439 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1440 res = GST_RTSP_EPARSE;
1442 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1443 if (major != 1 || minor != 0) {
1444 *version = GST_RTSP_VERSION_INVALID;
1445 res = GST_RTSP_ERROR;
1447 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1448 if (*type == GST_RTSP_MESSAGE_REQUEST)
1449 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1450 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1451 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1453 if (major == 1 && minor == 1) {
1454 *version = GST_RTSP_VERSION_1_1;
1455 } else if (major != 1 || minor != 0) {
1456 *version = GST_RTSP_VERSION_INVALID;
1457 res = GST_RTSP_ERROR;
1460 res = GST_RTSP_EPARSE;
1462 res = GST_RTSP_EPARSE;
1467 static GstRTSPResult
1468 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1470 GstRTSPResult res = GST_RTSP_OK;
1472 gchar versionstr[20];
1477 bptr = (gchar *) buffer;
1479 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1480 res = GST_RTSP_EPARSE;
1482 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1483 res = GST_RTSP_EPARSE;
1484 code = atoi (codestr);
1485 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1486 res = GST_RTSP_EPARSE;
1488 while (g_ascii_isspace (*bptr))
1491 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1492 NULL) != GST_RTSP_OK))
1493 res = GST_RTSP_EPARSE;
1495 res2 = parse_protocol_version (versionstr, &msg->type,
1496 &msg->type_data.response.version);
1497 if (G_LIKELY (res == GST_RTSP_OK))
1503 static GstRTSPResult
1504 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1506 GstRTSPResult res = GST_RTSP_OK;
1508 gchar versionstr[20];
1509 gchar methodstr[20];
1512 GstRTSPMethod method;
1514 bptr = (gchar *) buffer;
1516 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1517 res = GST_RTSP_EPARSE;
1518 method = gst_rtsp_find_method (methodstr);
1520 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1521 res = GST_RTSP_EPARSE;
1522 if (G_UNLIKELY (*urlstr == '\0'))
1523 res = GST_RTSP_EPARSE;
1525 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1526 res = GST_RTSP_EPARSE;
1528 if (G_UNLIKELY (*bptr != '\0'))
1529 res = GST_RTSP_EPARSE;
1531 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1532 urlstr) != GST_RTSP_OK))
1533 res = GST_RTSP_EPARSE;
1535 res2 = parse_protocol_version (versionstr, &msg->type,
1536 &msg->type_data.request.version);
1537 if (G_LIKELY (res == GST_RTSP_OK))
1540 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1541 /* GET and POST are not allowed as RTSP methods */
1542 if (msg->type_data.request.method == GST_RTSP_GET ||
1543 msg->type_data.request.method == GST_RTSP_POST) {
1544 msg->type_data.request.method = GST_RTSP_INVALID;
1545 if (res == GST_RTSP_OK)
1546 res = GST_RTSP_ERROR;
1548 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1549 /* only GET and POST are allowed as HTTP methods */
1550 if (msg->type_data.request.method != GST_RTSP_GET &&
1551 msg->type_data.request.method != GST_RTSP_POST) {
1552 msg->type_data.request.method = GST_RTSP_INVALID;
1553 if (res == GST_RTSP_OK)
1554 res = GST_RTSP_ERROR;
1561 /* parsing lines means reading a Key: Value pair */
1562 static GstRTSPResult
1563 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1565 GstRTSPHeaderField field;
1566 gchar *line = (gchar *) buffer;
1569 if ((value = strchr (line, ':')) == NULL || value == line)
1572 /* trim space before the colon */
1573 if (value[-1] == ' ')
1576 /* replace the colon with a NUL */
1579 /* find the header */
1580 field = gst_rtsp_find_header_field (line);
1581 if (field == GST_RTSP_HDR_INVALID)
1584 /* split up the value in multiple key:value pairs if it contains comma(s) */
1585 while (*value != '\0') {
1587 gchar *comma = NULL;
1588 gboolean quoted = FALSE;
1591 /* trim leading space */
1595 /* for headers which may not appear multiple times, and thus may not
1596 * contain multiple values on the same line, we can short-circuit the loop
1597 * below and the entire value results in just one key:value pair*/
1598 if (!gst_rtsp_header_allow_multiple (field))
1599 next_value = value + strlen (value);
1603 /* find the next value, taking special care of quotes and comments */
1604 while (*next_value != '\0') {
1605 if ((quoted || comment != 0) && *next_value == '\\' &&
1606 next_value[1] != '\0')
1608 else if (comment == 0 && *next_value == '"')
1610 else if (!quoted && *next_value == '(')
1612 else if (comment != 0 && *next_value == ')')
1614 else if (!quoted && comment == 0) {
1615 /* To quote RFC 2068: "User agents MUST take special care in parsing
1616 * the WWW-Authenticate field value if it contains more than one
1617 * challenge, or if more than one WWW-Authenticate header field is
1618 * provided, since the contents of a challenge may itself contain a
1619 * comma-separated list of authentication parameters."
1621 * What this means is that we cannot just look for an unquoted comma
1622 * when looking for multiple values in Proxy-Authenticate and
1623 * WWW-Authenticate headers. Instead we need to look for the sequence
1624 * "comma [space] token space token" before we can split after the
1627 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1628 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1629 if (*next_value == ',') {
1630 if (next_value[1] == ' ') {
1631 /* skip any space following the comma so we do not mistake it for
1632 * separating between two tokens */
1636 } else if (*next_value == ' ' && next_value[1] != ',' &&
1637 next_value[1] != '=' && comma != NULL) {
1642 } else if (*next_value == ',')
1650 if (value != next_value && next_value[-1] == ' ')
1651 next_value[-1] = '\0';
1653 if (*next_value != '\0')
1654 *next_value++ = '\0';
1656 /* add the key:value pair */
1658 gst_rtsp_message_add_header (msg, field, value);
1669 return GST_RTSP_EPARSE;
1673 /* convert all consecutive whitespace to a single space */
1675 normalize_line (guint8 * buffer)
1678 if (g_ascii_isspace (*buffer)) {
1682 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1685 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1693 * GST_RTSP_OK when a complete message was read.
1694 * GST_RTSP_EEOF: when the read socket is closed
1695 * GST_RTSP_EINTR: when more data is needed.
1696 * GST_RTSP_..: some other error occured.
1698 static GstRTSPResult
1699 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1700 GstRTSPConnection * conn)
1705 switch (builder->state) {
1710 builder->offset = 0;
1712 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1713 if (res != GST_RTSP_OK)
1716 c = builder->buffer[0];
1718 /* we have 1 bytes now and we can see if this is a data message or
1721 /* data message, prepare for the header */
1722 builder->state = STATE_DATA_HEADER;
1723 } else if (c == '\n' || c == '\r') {
1724 /* skip \n and \r */
1725 builder->offset = 0;
1728 builder->state = STATE_READ_LINES;
1732 case STATE_DATA_HEADER:
1735 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1736 if (res != GST_RTSP_OK)
1739 gst_rtsp_message_init_data (message, builder->buffer[1]);
1741 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1742 builder->body_data = g_malloc (builder->body_len + 1);
1743 builder->body_data[builder->body_len] = '\0';
1744 builder->offset = 0;
1745 builder->state = STATE_DATA_BODY;
1748 case STATE_DATA_BODY:
1751 read_bytes (conn, builder->body_data, &builder->offset,
1753 if (res != GST_RTSP_OK)
1756 /* we have the complete body now, store in the message adjusting the
1757 * length to include the trailing '\0' */
1758 gst_rtsp_message_take_body (message,
1759 (guint8 *) builder->body_data, builder->body_len + 1);
1760 builder->body_data = NULL;
1761 builder->body_len = 0;
1763 builder->state = STATE_END;
1766 case STATE_READ_LINES:
1768 res = read_line (conn, builder->buffer, &builder->offset,
1769 sizeof (builder->buffer));
1770 if (res != GST_RTSP_OK)
1773 /* we have a regular response */
1774 if (builder->buffer[0] == '\0') {
1777 /* empty line, end of message header */
1778 /* see if there is a Content-Length header, but ignore it if this
1779 * is a POST request with an x-sessioncookie header */
1780 if (gst_rtsp_message_get_header (message,
1781 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1782 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1783 message->type_data.request.method != GST_RTSP_POST ||
1784 gst_rtsp_message_get_header (message,
1785 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1786 /* there is, prepare to read the body */
1787 builder->body_len = atol (hdrval);
1788 builder->body_data = g_try_malloc (builder->body_len + 1);
1789 /* we can't do much here, we need the length to know how many bytes
1790 * we need to read next and when allocation fails, something is
1791 * probably wrong with the length. */
1792 if (builder->body_data == NULL)
1793 goto invalid_body_len;
1795 builder->body_data[builder->body_len] = '\0';
1796 builder->offset = 0;
1797 builder->state = STATE_DATA_BODY;
1799 builder->state = STATE_END;
1804 /* we have a line */
1805 normalize_line (builder->buffer);
1806 if (builder->line == 0) {
1807 /* first line, check for response status */
1808 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1809 memcmp (builder->buffer, "HTTP", 4) == 0) {
1810 builder->status = parse_response_status (builder->buffer, message);
1812 builder->status = parse_request_line (builder->buffer, message);
1815 /* else just parse the line */
1816 res = parse_line (builder->buffer, message);
1817 if (res != GST_RTSP_OK)
1818 builder->status = res;
1821 builder->offset = 0;
1826 gchar *session_cookie;
1829 if (message->type == GST_RTSP_MESSAGE_DATA) {
1830 /* data messages don't have headers */
1835 /* save the tunnel session in the connection */
1836 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1837 !conn->manual_http &&
1838 conn->tstate == TUNNEL_STATE_NONE &&
1839 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1840 &session_cookie, 0) == GST_RTSP_OK) {
1841 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1842 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1843 conn->tunneled = TRUE;
1846 /* save session id in the connection for further use */
1847 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1848 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1849 &session_id, 0) == GST_RTSP_OK) {
1852 maxlen = sizeof (conn->session_id) - 1;
1853 /* the sessionid can have attributes marked with ;
1854 * Make sure we strip them */
1855 for (i = 0; session_id[i] != '\0'; i++) {
1856 if (session_id[i] == ';') {
1861 } while (g_ascii_isspace (session_id[i]));
1862 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1865 /* if we parsed something valid, configure */
1866 if ((to = atoi (&session_id[i + 8])) > 0)
1873 /* make sure to not overflow */
1874 strncpy (conn->session_id, session_id, maxlen);
1875 conn->session_id[maxlen] = '\0';
1877 res = builder->status;
1881 res = GST_RTSP_ERROR;
1891 GST_DEBUG ("could not allocate body");
1892 return GST_RTSP_ERROR;
1897 * gst_rtsp_connection_read:
1898 * @conn: a #GstRTSPConnection
1899 * @data: the data to read
1900 * @size: the size of @data
1901 * @timeout: a timeout value or #NULL
1903 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1904 * the specified @timeout. @timeout can be #NULL, in which case this function
1905 * might block forever.
1907 * This function can be cancelled with gst_rtsp_connection_flush().
1909 * Returns: #GST_RTSP_OK on success.
1912 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1920 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1921 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1922 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
1924 if (G_UNLIKELY (size == 0))
1929 /* configure timeout if any */
1930 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1933 res = read_bytes (conn, data, &offset, size);
1934 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1936 if (G_LIKELY (res == GST_RTSP_OK))
1938 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1941 g_socket_set_timeout (conn->read_socket,
1942 (to + GST_SECOND - 1) / GST_SECOND);
1943 if (!g_socket_condition_wait (conn->read_socket,
1944 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
1946 g_socket_set_timeout (conn->read_socket, 0);
1947 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1948 g_clear_error (&err);
1950 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1951 g_clear_error (&err);
1952 goto select_timeout;
1954 g_clear_error (&err);
1957 g_socket_set_timeout (conn->read_socket, 0);
1964 return GST_RTSP_ESYS;
1968 return GST_RTSP_ETIMEOUT;
1972 return GST_RTSP_EINTR;
1976 return GST_RTSP_EEOF;
1984 static GstRTSPMessage *
1985 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
1986 const GstRTSPMessage * request)
1988 GstRTSPMessage *msg;
1991 if (gst_rtsp_status_as_text (code) == NULL)
1992 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1994 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
1997 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
1998 "GStreamer RTSP Server");
1999 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2000 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2001 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2003 if (code == GST_RTSP_STS_OK) {
2005 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2007 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2008 "application/x-rtsp-tunnelled");
2021 * gst_rtsp_connection_receive:
2022 * @conn: a #GstRTSPConnection
2023 * @message: the message to read
2024 * @timeout: a timeout value or #NULL
2026 * Attempt to read into @message from the connected @conn, blocking up to
2027 * the specified @timeout. @timeout can be #NULL, in which case this function
2028 * might block forever.
2030 * This function can be cancelled with gst_rtsp_connection_flush().
2032 * Returns: #GST_RTSP_OK on success.
2035 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2039 GstRTSPBuilder builder;
2043 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2044 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2045 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2047 /* configure timeout if any */
2048 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2050 memset (&builder, 0, sizeof (GstRTSPBuilder));
2052 res = build_next (&builder, message, conn);
2053 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2055 else if (G_LIKELY (res == GST_RTSP_OK)) {
2056 if (!conn->manual_http) {
2057 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2058 if (conn->tstate == TUNNEL_STATE_NONE &&
2059 message->type_data.request.method == GST_RTSP_GET) {
2060 GstRTSPMessage *response;
2062 conn->tstate = TUNNEL_STATE_GET;
2064 /* tunnel GET request, we can reply now */
2065 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2066 res = gst_rtsp_connection_send (conn, response, timeout);
2067 gst_rtsp_message_free (response);
2068 if (res == GST_RTSP_OK)
2069 res = GST_RTSP_ETGET;
2071 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2072 message->type_data.request.method == GST_RTSP_POST) {
2073 conn->tstate = TUNNEL_STATE_POST;
2075 /* tunnel POST request, the caller now has to link the two
2077 res = GST_RTSP_ETPOST;
2080 res = GST_RTSP_EPARSE;
2083 } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2084 res = GST_RTSP_EPARSE;
2090 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2093 g_socket_set_timeout (conn->read_socket,
2094 (to + GST_SECOND - 1) / GST_SECOND);
2095 if (!g_socket_condition_wait (conn->read_socket,
2096 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
2098 g_socket_set_timeout (conn->read_socket, 0);
2099 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
2100 g_clear_error (&err);
2102 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
2103 g_clear_error (&err);
2104 goto select_timeout;
2106 g_clear_error (&err);
2109 g_socket_set_timeout (conn->read_socket, 0);
2112 /* we have a message here */
2113 build_reset (&builder);
2120 res = GST_RTSP_ESYS;
2125 res = GST_RTSP_ETIMEOUT;
2130 res = GST_RTSP_EINTR;
2135 res = GST_RTSP_EEOF;
2141 build_reset (&builder);
2142 gst_rtsp_message_unset (message);
2148 * gst_rtsp_connection_close:
2149 * @conn: a #GstRTSPConnection
2151 * Close the connected @conn. After this call, the connection is in the same
2152 * state as when it was first created.
2154 * Returns: #GST_RTSP_OK on success.
2157 gst_rtsp_connection_close (GstRTSPConnection * conn)
2159 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2161 /* last unref closes the connection we don't want to explicitly close here
2162 * because these sockets might have been provided at construction */
2163 if (conn->socket0) {
2164 g_object_unref (conn->socket0);
2165 conn->socket0 = NULL;
2167 if (conn->socket1) {
2168 g_object_unref (conn->socket1);
2169 conn->socket1 = NULL;
2175 conn->read_ahead = 0;
2177 g_free (conn->initial_buffer);
2178 conn->initial_buffer = NULL;
2179 conn->initial_buffer_offset = 0;
2181 conn->write_socket = NULL;
2182 conn->read_socket = NULL;
2183 conn->tunneled = FALSE;
2184 conn->tstate = TUNNEL_STATE_NONE;
2186 g_free (conn->username);
2187 conn->username = NULL;
2188 g_free (conn->passwd);
2189 conn->passwd = NULL;
2190 gst_rtsp_connection_clear_auth_params (conn);
2193 conn->session_id[0] = '\0';
2199 * gst_rtsp_connection_free:
2200 * @conn: a #GstRTSPConnection
2202 * Close and free @conn.
2204 * Returns: #GST_RTSP_OK on success.
2207 gst_rtsp_connection_free (GstRTSPConnection * conn)
2211 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2213 res = gst_rtsp_connection_close (conn);
2215 if (conn->cancellable)
2216 g_object_unref (conn->cancellable);
2218 g_timer_destroy (conn->timer);
2219 gst_rtsp_url_free (conn->url);
2220 g_free (conn->proxy_host);
2227 * gst_rtsp_connection_poll:
2228 * @conn: a #GstRTSPConnection
2229 * @events: a bitmask of #GstRTSPEvent flags to check
2230 * @revents: location for result flags
2231 * @timeout: a timeout
2233 * Wait up to the specified @timeout for the connection to become available for
2234 * at least one of the operations specified in @events. When the function returns
2235 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2238 * @timeout can be #NULL, in which case this function might block forever.
2240 * This function can be cancelled with gst_rtsp_connection_flush().
2242 * Returns: #GST_RTSP_OK on success.
2247 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2248 GstRTSPEvent * revents, GTimeVal * timeout)
2252 GSource *rs, *ws, *ts;
2253 GIOCondition condition;
2255 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2256 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2257 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2258 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2259 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2261 ctx = g_main_context_new ();
2263 /* configure timeout if any */
2264 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2267 ts = g_timeout_source_new (to / GST_MSECOND);
2268 g_source_set_dummy_callback (ts);
2269 g_source_attach (ts, ctx);
2270 g_source_unref (ts);
2273 rs = g_socket_create_source (conn->read_socket,
2274 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable);
2275 g_source_set_dummy_callback (rs);
2276 g_source_attach (rs, ctx);
2277 g_source_unref (rs);
2279 ws = g_socket_create_source (conn->write_socket,
2280 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable);
2281 g_source_set_dummy_callback (ws);
2282 g_source_attach (ws, ctx);
2283 g_source_unref (ws);
2285 /* Returns after handling all pending events */
2286 g_main_context_iteration (ctx, TRUE);
2288 g_main_context_unref (ctx);
2291 g_socket_condition_check (conn->read_socket,
2292 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP);
2294 g_socket_condition_check (conn->write_socket,
2295 G_IO_OUT | G_IO_ERR | G_IO_HUP);
2298 if (events & GST_RTSP_EV_READ) {
2299 if ((condition & G_IO_IN) || (condition & G_IO_PRI))
2300 *revents |= GST_RTSP_EV_READ;
2302 if (events & GST_RTSP_EV_WRITE) {
2303 if ((condition & G_IO_OUT))
2304 *revents |= GST_RTSP_EV_WRITE;
2308 return GST_RTSP_ETIMEOUT;
2314 * gst_rtsp_connection_next_timeout:
2315 * @conn: a #GstRTSPConnection
2316 * @timeout: a timeout
2318 * Calculate the next timeout for @conn, storing the result in @timeout.
2320 * Returns: #GST_RTSP_OK.
2323 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2330 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2331 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2333 ctimeout = conn->timeout;
2334 if (ctimeout >= 20) {
2335 /* Because we should act before the timeout we timeout 5
2336 * seconds in advance. */
2338 } else if (ctimeout >= 5) {
2339 /* else timeout 20% earlier */
2340 ctimeout -= ctimeout / 5;
2341 } else if (ctimeout >= 1) {
2342 /* else timeout 1 second earlier */
2346 elapsed = g_timer_elapsed (conn->timer, &usec);
2347 if (elapsed >= ctimeout) {
2351 sec = ctimeout - elapsed;
2352 if (usec <= G_USEC_PER_SEC)
2353 usec = G_USEC_PER_SEC - usec;
2358 timeout->tv_sec = sec;
2359 timeout->tv_usec = usec;
2365 * gst_rtsp_connection_reset_timeout:
2366 * @conn: a #GstRTSPConnection
2368 * Reset the timeout of @conn.
2370 * Returns: #GST_RTSP_OK.
2373 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2375 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2377 g_timer_start (conn->timer);
2383 * gst_rtsp_connection_flush:
2384 * @conn: a #GstRTSPConnection
2385 * @flush: start or stop the flush
2387 * Start or stop the flushing action on @conn. When flushing, all current
2388 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2389 * is set to non-flushing mode again.
2391 * Returns: #GST_RTSP_OK.
2394 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2396 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2399 g_cancellable_cancel (conn->cancellable);
2401 g_cancellable_reset (conn->cancellable);
2407 * gst_rtsp_connection_set_proxy:
2408 * @conn: a #GstRTSPConnection
2409 * @host: the proxy host
2410 * @port: the proxy port
2412 * Set the proxy host and port.
2414 * Returns: #GST_RTSP_OK.
2419 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2420 const gchar * host, guint port)
2422 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2424 g_free (conn->proxy_host);
2425 conn->proxy_host = g_strdup (host);
2426 conn->proxy_port = port;
2432 * gst_rtsp_connection_set_auth:
2433 * @conn: a #GstRTSPConnection
2434 * @method: authentication method
2436 * @pass: the password
2438 * Configure @conn for authentication mode @method with @user and @pass as the
2439 * user and password respectively.
2441 * Returns: #GST_RTSP_OK.
2444 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2445 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2447 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2449 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2450 || g_strrstr (user, ":") != NULL))
2451 return GST_RTSP_EINVAL;
2453 /* Make sure the username and passwd are being set for authentication */
2454 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2455 return GST_RTSP_EINVAL;
2457 /* ":" chars are not allowed in usernames for basic auth */
2458 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2459 return GST_RTSP_EINVAL;
2461 g_free (conn->username);
2462 g_free (conn->passwd);
2464 conn->auth_method = method;
2465 conn->username = g_strdup (user);
2466 conn->passwd = g_strdup (pass);
2473 * @key: ASCII string to hash
2475 * Hashes @key in a case-insensitive manner.
2477 * Returns: the hash code.
2480 str_case_hash (gconstpointer key)
2482 const char *p = key;
2483 guint h = g_ascii_toupper (*p);
2486 for (p += 1; *p != '\0'; p++)
2487 h = (h << 5) - h + g_ascii_toupper (*p);
2494 * @v1: an ASCII string
2495 * @v2: another ASCII string
2497 * Compares @v1 and @v2 in a case-insensitive manner
2499 * Returns: %TRUE if they are equal (modulo case)
2502 str_case_equal (gconstpointer v1, gconstpointer v2)
2504 const char *string1 = v1;
2505 const char *string2 = v2;
2507 return g_ascii_strcasecmp (string1, string2) == 0;
2511 * gst_rtsp_connection_set_auth_param:
2512 * @conn: a #GstRTSPConnection
2513 * @param: authentication directive
2516 * Setup @conn with authentication directives. This is not necesary for
2517 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2518 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2519 * in the WWW-Authenticate response header and can include realm, domain,
2520 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2525 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2526 const gchar * param, const gchar * value)
2528 g_return_if_fail (conn != NULL);
2529 g_return_if_fail (param != NULL);
2531 if (conn->auth_params == NULL) {
2533 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2535 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2539 * gst_rtsp_connection_clear_auth_params:
2540 * @conn: a #GstRTSPConnection
2542 * Clear the list of authentication directives stored in @conn.
2547 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2549 g_return_if_fail (conn != NULL);
2551 if (conn->auth_params != NULL) {
2552 g_hash_table_destroy (conn->auth_params);
2553 conn->auth_params = NULL;
2557 static GstRTSPResult
2558 set_qos_dscp (GSocket * socket, guint qos_dscp)
2564 union gst_sockaddr sa;
2565 socklen_t slen = sizeof (sa);
2572 fd = g_socket_get_fd (socket);
2573 if (getsockname (fd, &sa.sa, &slen) < 0)
2574 goto no_getsockname;
2576 af = sa.sa.sa_family;
2578 /* if this is an IPv4-mapped address then do IPv4 QoS */
2579 if (af == AF_INET6) {
2580 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2584 /* extract and shift 6 bits of the DSCP */
2585 tos = (qos_dscp & 0x3f) << 2;
2589 if (setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2594 if (setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2608 return GST_RTSP_ESYS;
2612 return GST_RTSP_ERROR;
2618 * gst_rtsp_connection_set_qos_dscp:
2619 * @conn: a #GstRTSPConnection
2620 * @qos_dscp: DSCP value
2622 * Configure @conn to use the specified DSCP value.
2624 * Returns: #GST_RTSP_OK on success.
2629 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2633 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2634 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2635 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2637 res = set_qos_dscp (conn->socket0, qos_dscp);
2638 if (res == GST_RTSP_OK)
2639 res = set_qos_dscp (conn->socket1, qos_dscp);
2646 * gst_rtsp_connection_get_url:
2647 * @conn: a #GstRTSPConnection
2649 * Retrieve the URL of the other end of @conn.
2651 * Returns: The URL. This value remains valid until the
2652 * connection is freed.
2657 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2659 g_return_val_if_fail (conn != NULL, NULL);
2665 * gst_rtsp_connection_get_ip:
2666 * @conn: a #GstRTSPConnection
2668 * Retrieve the IP address of the other end of @conn.
2670 * Returns: The IP address as a string. this value remains valid until the
2671 * connection is closed.
2676 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2678 g_return_val_if_fail (conn != NULL, NULL);
2684 * gst_rtsp_connection_set_ip:
2685 * @conn: a #GstRTSPConnection
2686 * @ip: an ip address
2688 * Set the IP address of the server.
2693 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2695 g_return_if_fail (conn != NULL);
2698 conn->ip = g_strdup (ip);
2702 * gst_rtsp_connection_get_readfd:
2703 * @conn: a #GstRTSPConnection
2705 * Get the file descriptor for reading.
2707 * Returns: the file descriptor used for reading or %NULL on error. The file
2708 * descriptor remains valid until the connection is closed.
2713 gst_rtsp_connection_get_read_socket (const GstRTSPConnection * conn)
2715 g_return_val_if_fail (conn != NULL, NULL);
2716 g_return_val_if_fail (conn->read_socket != NULL, NULL);
2718 return conn->read_socket;
2722 * gst_rtsp_connection_get_write_socket:
2723 * @conn: a #GstRTSPConnection
2725 * Get the file descriptor for writing.
2727 * Returns: the file descriptor used for writing or NULL on error. The file
2728 * descriptor remains valid until the connection is closed.
2733 gst_rtsp_connection_get_write_socket (const GstRTSPConnection * conn)
2735 g_return_val_if_fail (conn != NULL, NULL);
2736 g_return_val_if_fail (conn->write_socket != NULL, NULL);
2738 return conn->write_socket;
2742 * gst_rtsp_connection_set_http_mode:
2743 * @conn: a #GstRTSPConnection
2744 * @enable: %TRUE to enable manual HTTP mode
2746 * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2747 * messages in addition to the RTSP messages. It will also disable the
2748 * automatic handling of setting up an HTTP tunnel.
2753 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2755 g_return_if_fail (conn != NULL);
2757 conn->manual_http = enable;
2761 * gst_rtsp_connection_set_tunneled:
2762 * @conn: a #GstRTSPConnection
2763 * @tunneled: the new state
2765 * Set the HTTP tunneling state of the connection. This must be configured before
2766 * the @conn is connected.
2771 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2773 g_return_if_fail (conn != NULL);
2774 g_return_if_fail (conn->read_socket == NULL);
2775 g_return_if_fail (conn->write_socket == NULL);
2777 conn->tunneled = tunneled;
2781 * gst_rtsp_connection_is_tunneled:
2782 * @conn: a #GstRTSPConnection
2784 * Get the tunneling state of the connection.
2786 * Returns: if @conn is using HTTP tunneling.
2791 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2793 g_return_val_if_fail (conn != NULL, FALSE);
2795 return conn->tunneled;
2799 * gst_rtsp_connection_get_tunnelid:
2800 * @conn: a #GstRTSPConnection
2802 * Get the tunnel session id the connection.
2804 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2809 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2811 g_return_val_if_fail (conn != NULL, NULL);
2813 if (!conn->tunneled)
2816 return conn->tunnelid;
2820 * gst_rtsp_connection_do_tunnel:
2821 * @conn: a #GstRTSPConnection
2822 * @conn2: a #GstRTSPConnection or %NULL
2824 * If @conn received the first tunnel connection and @conn2 received
2825 * the second tunnel connection, link the two connections together so that
2826 * @conn manages the tunneled connection.
2828 * After this call, @conn2 cannot be used anymore and must be freed with
2829 * gst_rtsp_connection_free().
2831 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2834 * Returns: return GST_RTSP_OK on success.
2839 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2840 GstRTSPConnection * conn2)
2842 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2844 if (conn2 != NULL) {
2845 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2846 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2847 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2848 TUNNELID_LEN), GST_RTSP_EINVAL);
2850 /* both connections have socket0 as the read/write socket. start by taking the
2851 * socket from conn2 and set it as the socket in conn */
2852 conn->socket1 = conn2->socket0;
2854 /* clean up some of the state of conn2 */
2855 g_cancellable_cancel (conn2->cancellable);
2857 g_object_unref (conn2->socket1);
2858 conn2->socket1 = NULL;
2859 conn2->write_socket = conn2->read_socket = NULL;
2860 g_cancellable_reset (conn2->cancellable);
2862 /* We make socket0 the write socket and socket1 the read socket. */
2863 conn->write_socket = conn->socket0;
2864 conn->read_socket = conn->socket1;
2866 conn->tstate = TUNNEL_STATE_COMPLETE;
2868 g_free (conn->initial_buffer);
2869 conn->initial_buffer = conn2->initial_buffer;
2870 conn2->initial_buffer = NULL;
2871 conn->initial_buffer_offset = conn2->initial_buffer_offset;
2874 /* we need base64 decoding for the readfd */
2875 conn->ctx.state = 0;
2878 conn->ctx.coutl = 0;
2879 conn->ctxp = &conn->ctx;
2884 #define READ_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2885 #define READ_COND (G_IO_IN | READ_ERR)
2886 #define WRITE_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2887 #define WRITE_COND (G_IO_OUT | WRITE_ERR)
2896 /* async functions */
2897 struct _GstRTSPWatch
2901 GstRTSPConnection *conn;
2903 GstRTSPBuilder builder;
2904 GstRTSPMessage message;
2909 /* queued message for transmission */
2918 GstRTSPWatchFuncs funcs;
2921 GDestroyNotify notify;
2925 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2927 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2929 if (watch->conn->initial_buffer != NULL)
2932 *timeout = (watch->conn->timeout * 1000);
2938 gst_rtsp_source_check (GSource * source)
2940 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2942 if (watch->readfd.revents & READ_COND)
2945 if (watch->writefd.revents & WRITE_COND)
2952 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2953 gpointer user_data G_GNUC_UNUSED)
2955 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2956 GstRTSPResult res = GST_RTSP_ERROR;
2957 gboolean keep_running = TRUE;
2959 /* first read as much as we can */
2960 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2962 if (watch->readfd.revents & READ_ERR)
2965 res = build_next (&watch->builder, &watch->message, watch->conn);
2966 if (res == GST_RTSP_EINTR)
2968 else if (G_UNLIKELY (res == GST_RTSP_EEOF)) {
2969 watch->readfd.events = 0;
2970 watch->readfd.revents = 0;
2971 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2972 /* When we are in tunnelled mode, the read socket can be closed and we
2973 * should be prepared for a new POST method to reopen it */
2974 if (watch->conn->tstate == TUNNEL_STATE_COMPLETE) {
2975 /* remove the read connection for the tunnel */
2976 /* we accept a new POST request */
2977 watch->conn->tstate = TUNNEL_STATE_GET;
2978 /* and signal that we lost our tunnel */
2979 if (watch->funcs.tunnel_lost)
2980 res = watch->funcs.tunnel_lost (watch, watch->user_data);
2984 } else if (G_LIKELY (res == GST_RTSP_OK)) {
2985 if (!watch->conn->manual_http &&
2986 watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2987 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2988 watch->message.type_data.request.method == GST_RTSP_GET) {
2989 GstRTSPMessage *response;
2990 GstRTSPStatusCode code;
2992 watch->conn->tstate = TUNNEL_STATE_GET;
2994 if (watch->funcs.tunnel_start)
2995 code = watch->funcs.tunnel_start (watch, watch->user_data);
2997 code = GST_RTSP_STS_OK;
2999 /* queue the response */
3000 response = gen_tunnel_reply (watch->conn, code, &watch->message);
3001 gst_rtsp_watch_send_message (watch, response, NULL);
3002 gst_rtsp_message_free (response);
3004 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3005 watch->message.type_data.request.method == GST_RTSP_POST) {
3006 watch->conn->tstate = TUNNEL_STATE_POST;
3008 /* in the callback the connection should be tunneled with the
3010 if (watch->funcs.tunnel_complete)
3011 watch->funcs.tunnel_complete (watch, watch->user_data);
3017 if (!watch->conn->manual_http) {
3018 /* if manual HTTP support is not enabled, then restore the message to
3019 * what it would have looked like without the support for parsing HTTP
3020 * messages being present */
3021 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3022 watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3023 watch->message.type_data.request.method = GST_RTSP_INVALID;
3024 if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3025 watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3026 res = GST_RTSP_EPARSE;
3027 } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3028 watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3029 if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3030 watch->message.type_data.response.version =
3031 GST_RTSP_VERSION_INVALID;
3032 res = GST_RTSP_EPARSE;
3036 if (G_LIKELY (res == GST_RTSP_OK)) {
3037 if (watch->funcs.message_received)
3038 watch->funcs.message_received (watch, &watch->message,
3045 gst_rtsp_message_unset (&watch->message);
3046 build_reset (&watch->builder);
3050 if (watch->writefd.revents & WRITE_COND) {
3051 if (watch->writefd.revents & WRITE_ERR)
3054 g_mutex_lock (watch->mutex);
3056 if (watch->write_data == NULL) {
3059 /* get a new message from the queue */
3060 rec = g_queue_pop_tail (watch->messages);
3064 watch->write_off = 0;
3065 watch->write_data = rec->data;
3066 watch->write_size = rec->size;
3067 watch->write_id = rec->id;
3069 g_slice_free (GstRTSPRec, rec);
3072 res = write_bytes (watch->conn->write_socket, watch->write_data,
3073 &watch->write_off, watch->write_size, watch->conn->cancellable);
3074 g_mutex_unlock (watch->mutex);
3076 if (res == GST_RTSP_EINTR)
3078 else if (G_LIKELY (res == GST_RTSP_OK)) {
3079 if (watch->funcs.message_sent)
3080 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3084 g_mutex_lock (watch->mutex);
3086 g_free (watch->write_data);
3087 watch->write_data = NULL;
3090 watch->writefd.events = WRITE_ERR;
3092 g_mutex_unlock (watch->mutex);
3096 return keep_running;
3101 if (watch->funcs.closed)
3102 watch->funcs.closed (watch, watch->user_data);
3104 /* always stop when the readfd returns EOF in non-tunneled mode */
3109 watch->readfd.events = 0;
3110 watch->readfd.revents = 0;
3111 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3112 keep_running = (watch->writefd.events != 0);
3115 if (watch->funcs.error_full)
3116 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3117 0, watch->user_data), error);
3125 watch->writefd.events = 0;
3126 watch->writefd.revents = 0;
3127 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3128 keep_running = (watch->readfd.events != 0);
3131 if (watch->funcs.error_full)
3132 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3133 watch->write_id, watch->user_data), error);
3141 if (watch->funcs.error)
3142 watch->funcs.error (watch, res, watch->user_data);
3144 return keep_running;
3149 gst_rtsp_rec_free (gpointer data)
3151 GstRTSPRec *rec = data;
3154 g_slice_free (GstRTSPRec, rec);
3158 gst_rtsp_source_finalize (GSource * source)
3160 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3162 build_reset (&watch->builder);
3163 gst_rtsp_message_unset (&watch->message);
3165 g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3166 g_queue_free (watch->messages);
3167 watch->messages = NULL;
3168 g_free (watch->write_data);
3170 g_mutex_free (watch->mutex);
3173 watch->notify (watch->user_data);
3176 static GSourceFuncs gst_rtsp_source_funcs = {
3177 gst_rtsp_source_prepare,
3178 gst_rtsp_source_check,
3179 gst_rtsp_source_dispatch,
3180 gst_rtsp_source_finalize,
3186 * gst_rtsp_watch_new:
3187 * @conn: a #GstRTSPConnection
3188 * @funcs: watch functions
3189 * @user_data: user data to pass to @funcs
3190 * @notify: notify when @user_data is not referenced anymore
3192 * Create a watch object for @conn. The functions provided in @funcs will be
3193 * called with @user_data when activity happened on the watch.
3195 * The new watch is usually created so that it can be attached to a
3196 * maincontext with gst_rtsp_watch_attach().
3198 * @conn must exist for the entire lifetime of the watch.
3200 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3201 * communication. Free with gst_rtsp_watch_unref () after usage.
3206 gst_rtsp_watch_new (GstRTSPConnection * conn,
3207 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3209 GstRTSPWatch *result;
3211 g_return_val_if_fail (conn != NULL, NULL);
3212 g_return_val_if_fail (funcs != NULL, NULL);
3213 g_return_val_if_fail (conn->read_socket != NULL, NULL);
3214 g_return_val_if_fail (conn->write_socket != NULL, NULL);
3216 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3217 sizeof (GstRTSPWatch));
3219 result->conn = conn;
3220 result->builder.state = STATE_START;
3222 result->mutex = g_mutex_new ();
3223 result->messages = g_queue_new ();
3225 result->readfd.fd = -1;
3226 result->writefd.fd = -1;
3228 gst_rtsp_watch_reset (result);
3230 result->funcs = *funcs;
3231 result->user_data = user_data;
3232 result->notify = notify;
3238 * gst_rtsp_watch_reset:
3239 * @watch: a #GstRTSPWatch
3241 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3242 * when the file descriptors of the connection might have changed.
3247 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3249 if (watch->readfd.fd != -1)
3250 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3251 if (watch->writefd.fd != -1)
3252 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3254 watch->readfd.fd = g_socket_get_fd (watch->conn->read_socket);
3255 watch->readfd.events = READ_COND;
3256 watch->readfd.revents = 0;
3258 watch->writefd.fd = g_socket_get_fd (watch->conn->write_socket);
3259 watch->writefd.events = WRITE_ERR;
3260 watch->writefd.revents = 0;
3262 if (watch->readfd.fd != -1)
3263 g_source_add_poll ((GSource *) watch, &watch->readfd);
3264 if (watch->writefd.fd != -1)
3265 g_source_add_poll ((GSource *) watch, &watch->writefd);
3269 * gst_rtsp_watch_attach:
3270 * @watch: a #GstRTSPWatch
3271 * @context: a GMainContext (if NULL, the default context will be used)
3273 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3275 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3280 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3282 g_return_val_if_fail (watch != NULL, 0);
3284 return g_source_attach ((GSource *) watch, context);
3288 * gst_rtsp_watch_unref:
3289 * @watch: a #GstRTSPWatch
3291 * Decreases the reference count of @watch by one. If the resulting reference
3292 * count is zero the watch and associated memory will be destroyed.
3297 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3299 g_return_if_fail (watch != NULL);
3301 g_source_unref ((GSource *) watch);
3305 * gst_rtsp_watch_write_data:
3306 * @watch: a #GstRTSPWatch
3307 * @data: the data to queue
3308 * @size: the size of @data
3309 * @id: location for a message ID or %NULL
3311 * Write @data using the connection of the @watch. If it cannot be sent
3312 * immediately, it will be queued for transmission in @watch. The contents of
3313 * @message will then be serialized and transmitted when the connection of the
3314 * @watch becomes writable. In case the @message is queued, the ID returned in
3315 * @id will be non-zero and used as the ID argument in the message_sent
3318 * This function will take ownership of @data and g_free() it after use.
3320 * Returns: #GST_RTSP_OK on success.
3325 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3326 guint size, guint * id)
3331 GMainContext *context = NULL;
3333 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3334 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3335 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3337 g_mutex_lock (watch->mutex);
3339 /* try to send the message synchronously first */
3340 if (watch->messages->length == 0 && watch->write_data == NULL) {
3342 write_bytes (watch->conn->write_socket, data, &off, size,
3343 watch->conn->cancellable);
3344 if (res != GST_RTSP_EINTR) {
3347 g_free ((gpointer) data);
3352 /* make a record with the data and id for sending async */
3353 rec = g_slice_new (GstRTSPRec);
3355 rec->data = (guint8 *) data;
3358 rec->data = g_memdup (data + off, size - off);
3359 rec->size = size - off;
3360 g_free ((gpointer) data);
3364 /* make sure rec->id is never 0 */
3365 rec->id = ++watch->id;
3366 } while (G_UNLIKELY (rec->id == 0));
3368 /* add the record to a queue. FIXME we would like to have an upper limit here */
3369 g_queue_push_head (watch->messages, rec);
3371 /* make sure the main context will now also check for writability on the
3373 if (watch->writefd.events != WRITE_COND) {
3374 watch->writefd.events = WRITE_COND;
3375 context = ((GSource *) watch)->context;
3383 g_mutex_unlock (watch->mutex);
3386 g_main_context_wakeup (context);
3392 * gst_rtsp_watch_send_message:
3393 * @watch: a #GstRTSPWatch
3394 * @message: a #GstRTSPMessage
3395 * @id: location for a message ID or %NULL
3397 * Send a @message using the connection of the @watch. If it cannot be sent
3398 * immediately, it will be queued for transmission in @watch. The contents of
3399 * @message will then be serialized and transmitted when the connection of the
3400 * @watch becomes writable. In case the @message is queued, the ID returned in
3401 * @id will be non-zero and used as the ID argument in the message_sent
3404 * Returns: #GST_RTSP_OK on success.
3409 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3415 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3416 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3418 /* make a record with the message as a string and id */
3419 str = message_to_string (watch->conn, message);
3421 return gst_rtsp_watch_write_data (watch,
3422 (guint8 *) g_string_free (str, FALSE), size, id);