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));
327 gst_rtsp_connection_create_from_socket (client_sock, ip, port, NULL,
336 GST_DEBUG ("Accepting client failed: %s", err->message);
337 g_clear_error (&err);
338 return GST_RTSP_ESYS;
342 if (!g_socket_close (client_sock, &err)) {
343 GST_DEBUG ("Closing socket failed: %s", err->message);
344 g_clear_error (&err);
346 g_object_unref (client_sock);
347 return GST_RTSP_ERROR;
352 do_resolve (const gchar * host, GCancellable * cancellable)
359 addr = g_inet_address_new_from_string (host);
363 resolver = g_resolver_get_default ();
365 results = g_resolver_lookup_by_name (resolver, host, cancellable, &err);
369 for (l = results; l; l = l->next) {
370 GInetAddress *tmp = l->data;
372 if (g_inet_address_get_family (tmp) == G_SOCKET_FAMILY_IPV4 ||
373 g_inet_address_get_family (tmp) == G_SOCKET_FAMILY_IPV6) {
374 addr = G_INET_ADDRESS (g_object_ref (tmp));
379 g_resolver_free_addresses (results);
380 g_object_unref (resolver);
386 ip = g_inet_address_to_string (addr);
387 g_object_unref (addr);
394 GST_ERROR ("failed to resolve %s: %s", host, err->message);
395 g_clear_error (&err);
396 g_object_unref (resolver);
402 do_connect (const gchar * ip, guint16 port, GSocket ** socket_out,
403 GTimeVal * timeout, GCancellable * cancellable)
408 GSocketAddress *saddr;
411 addr = g_inet_address_new_from_string (ip);
413 saddr = g_inet_socket_address_new (addr, port);
414 g_object_unref (addr);
417 g_socket_new (g_socket_address_get_family (saddr), G_SOCKET_TYPE_STREAM,
418 G_SOCKET_PROTOCOL_TCP, &err);
422 /* set to non-blocking mode so that we can cancel the connect */
423 g_socket_set_blocking (socket, FALSE);
425 /* we are going to connect ASYNC now */
426 if (!g_socket_connect (socket, saddr, cancellable, &err)) {
427 if (!g_error_matches (err, G_IO_ERROR, G_IO_ERROR_PENDING))
433 /* wait for connect to complete up to the specified timeout or until we got
435 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
437 g_socket_set_timeout (socket, (to + GST_SECOND - 1) / GST_SECOND);
438 if (!g_socket_condition_wait (socket, G_IO_OUT, cancellable, &err)) {
439 g_socket_set_timeout (socket, 0);
440 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT))
445 g_socket_set_timeout (socket, 0);
447 if (!g_socket_check_connect_result (socket, &err))
451 g_object_unref (saddr);
453 *socket_out = socket;
460 GST_ERROR ("no socket: %s", err->message);
461 g_clear_error (&err);
462 g_object_unref (saddr);
463 return GST_RTSP_ESYS;
467 GST_ERROR ("system error: %s", err->message);
468 g_clear_error (&err);
469 g_object_unref (saddr);
470 g_object_unref (socket);
471 return GST_RTSP_ESYS;
475 GST_ERROR ("timeout");
476 g_clear_error (&err);
477 g_object_unref (saddr);
478 g_object_unref (socket);
479 return GST_RTSP_ETIMEOUT;
484 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
491 guint16 port, url_port;
495 GstRTSPMessage response;
498 memset (&response, 0, sizeof (response));
499 gst_rtsp_message_init (&response);
501 /* create a random sessionid */
502 for (i = 0; i < TUNNELID_LEN; i++)
503 conn->tunnelid[i] = g_random_int_range ('a', 'z');
504 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
507 /* get the port from the url */
508 gst_rtsp_url_get_port (url, &url_port);
510 if (conn->proxy_host) {
511 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
512 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
513 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
514 ip = conn->proxy_host;
515 port = conn->proxy_port;
517 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
518 url->query ? url->query : "");
524 /* create the GET request for the read connection */
525 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
527 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
529 if (hostparam != NULL)
530 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
531 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
533 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
534 "application/x-rtsp-tunnelled");
535 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
536 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
538 /* we start by writing to this fd */
539 conn->write_socket = conn->socket0;
541 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
542 * request from being base64 encoded */
543 conn->tunneled = FALSE;
544 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
545 gst_rtsp_message_free (msg);
546 conn->tunneled = TRUE;
548 /* receive the response to the GET request */
549 /* we need to temporarily set manual_http to TRUE since
550 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
551 * failure otherwise */
552 old_http = conn->manual_http;
553 conn->manual_http = TRUE;
554 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
556 conn->manual_http = old_http;
558 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
559 response.type_data.response.code != GST_RTSP_STS_OK)
562 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
563 &value, 0) == GST_RTSP_OK) {
564 if (conn->proxy_host) {
565 /* if we use a proxy we need to change the destination url */
567 url->host = g_strdup (value);
569 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
571 /* and resolve the new ip address */
572 if (!(ip = do_resolve (value, conn->cancellable)))
579 /* connect to the host/port */
580 res = do_connect (ip, port, &conn->socket1, timeout, conn->cancellable);
581 if (res != GST_RTSP_OK)
584 /* this is now our writing socket */
585 conn->write_socket = conn->socket1;
587 /* create the POST request for the write connection */
588 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
590 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
592 if (hostparam != NULL)
593 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
594 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
596 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
597 "application/x-rtsp-tunnelled");
598 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
599 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
600 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
601 "Sun, 9 Jan 1972 00:00:00 GMT");
602 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
604 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
605 * request from being base64 encoded */
606 conn->tunneled = FALSE;
607 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
608 gst_rtsp_message_free (msg);
609 conn->tunneled = TRUE;
612 gst_rtsp_message_unset (&response);
621 GST_ERROR ("failed to create request (%d)", res);
626 GST_ERROR ("write failed (%d)", res);
627 gst_rtsp_message_free (msg);
628 conn->tunneled = TRUE;
633 GST_ERROR ("read failed (%d)", res);
634 conn->manual_http = FALSE;
639 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
640 response.type_data.response.reason);
641 res = GST_RTSP_ERROR;
646 GST_ERROR ("could not resolve %s", conn->ip);
652 GST_ERROR ("failed to connect");
658 * gst_rtsp_connection_connect:
659 * @conn: a #GstRTSPConnection
660 * @timeout: a #GTimeVal timeout
662 * Attempt to connect to the url of @conn made with
663 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
664 * forever. If @timeout contains a valid timeout, this function will return
665 * #GST_RTSP_ETIMEOUT after the timeout expired.
667 * This function can be cancelled with gst_rtsp_connection_flush().
669 * Returns: #GST_RTSP_OK when a connection could be made.
672 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
679 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
680 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
681 g_return_val_if_fail (conn->socket0 == NULL, GST_RTSP_EINVAL);
685 if (conn->proxy_host && conn->tunneled) {
686 if (!(ip = do_resolve (conn->proxy_host, conn->cancellable))) {
687 GST_ERROR ("could not resolve %s", conn->proxy_host);
690 port = conn->proxy_port;
691 g_free (conn->proxy_host);
692 conn->proxy_host = ip;
694 if (!(ip = do_resolve (url->host, conn->cancellable))) {
695 GST_ERROR ("could not resolve %s", url->host);
698 /* get the port from the url */
699 gst_rtsp_url_get_port (url, &port);
705 /* connect to the host/port */
706 res = do_connect (ip, port, &conn->socket0, timeout, conn->cancellable);
707 if (res != GST_RTSP_OK)
710 /* this is our read URL */
711 conn->read_socket = conn->socket0;
713 if (conn->tunneled) {
714 res = setup_tunneling (conn, timeout);
715 if (res != GST_RTSP_OK)
716 goto tunneling_failed;
718 conn->write_socket = conn->socket0;
725 return GST_RTSP_ENET;
729 GST_ERROR ("failed to connect");
734 GST_ERROR ("failed to setup tunneling");
740 auth_digest_compute_hex_urp (const gchar * username,
741 const gchar * realm, const gchar * password, gchar hex_urp[33])
743 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
744 const gchar *digest_string;
746 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
747 g_checksum_update (md5_context, (const guchar *) ":", 1);
748 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
749 g_checksum_update (md5_context, (const guchar *) ":", 1);
750 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
751 digest_string = g_checksum_get_string (md5_context);
753 memset (hex_urp, 0, 33);
754 memcpy (hex_urp, digest_string, strlen (digest_string));
756 g_checksum_free (md5_context);
760 auth_digest_compute_response (const gchar * method,
761 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
764 char hex_a2[33] = { 0, };
765 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
766 const gchar *digest_string;
769 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
770 g_checksum_update (md5_context, (const guchar *) ":", 1);
771 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
772 digest_string = g_checksum_get_string (md5_context);
773 memcpy (hex_a2, digest_string, strlen (digest_string));
776 g_checksum_reset (md5_context);
777 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
778 g_checksum_update (md5_context, (const guchar *) ":", 1);
779 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
780 g_checksum_update (md5_context, (const guchar *) ":", 1);
782 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
783 digest_string = g_checksum_get_string (md5_context);
784 memset (response, 0, 33);
785 memcpy (response, digest_string, strlen (digest_string));
787 g_checksum_free (md5_context);
791 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
793 switch (conn->auth_method) {
794 case GST_RTSP_AUTH_BASIC:{
799 if (conn->username == NULL || conn->passwd == NULL)
802 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
803 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
804 auth_string = g_strdup_printf ("Basic %s", user_pass64);
806 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
810 g_free (user_pass64);
813 case GST_RTSP_AUTH_DIGEST:{
814 gchar response[33], hex_urp[33];
815 gchar *auth_string, *auth_string2;
822 /* we need to have some params set */
823 if (conn->auth_params == NULL || conn->username == NULL ||
824 conn->passwd == NULL)
827 /* we need the realm and nonce */
828 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
829 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
830 if (realm == NULL || nonce == NULL)
833 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
836 method = gst_rtsp_method_as_text (message->type_data.request.method);
837 uri = message->type_data.request.uri;
839 /* Assume no qop, algorithm=md5, stale=false */
840 /* For algorithm MD5, a1 = urp. */
841 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
842 auth_string = g_strdup_printf ("Digest username=\"%s\", "
843 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
844 conn->username, realm, nonce, uri, response);
846 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
848 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
850 g_free (auth_string);
851 auth_string = auth_string2;
853 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
864 gen_date_string (gchar * date_string, guint len)
866 static const char wkdays[7][4] =
867 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
868 static const char months[12][4] =
869 { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
883 g_snprintf (date_string, len, "%s, %02d %s %04d %02d:%02d:%02d GMT",
884 wkdays[tm.tm_wday], tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900,
885 tm.tm_hour, tm.tm_min, tm.tm_sec);
889 write_bytes (GSocket * socket, const guint8 * buffer, guint * idx, guint size,
890 GCancellable * cancellable)
894 if (G_UNLIKELY (*idx > size))
895 return GST_RTSP_ERROR;
903 r = g_socket_send (socket, (gchar *) & buffer[*idx], left, cancellable,
905 if (G_UNLIKELY (r == 0)) {
906 return GST_RTSP_EINTR;
907 } else if (G_UNLIKELY (r < 0)) {
908 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
909 g_clear_error (&err);
910 return GST_RTSP_EINTR;
912 g_clear_error (&err);
913 return GST_RTSP_ESYS;
923 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size,
928 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
929 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
931 out = MIN (left, size);
932 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
934 if (left == (gsize) out) {
935 g_free (conn->initial_buffer);
936 conn->initial_buffer = NULL;
937 conn->initial_buffer_offset = 0;
939 conn->initial_buffer_offset += out;
942 if (G_LIKELY (size > (guint) out)) {
945 r = g_socket_receive (conn->read_socket, (gchar *) & buffer[out],
946 size - out, conn->cancellable, err);
958 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size,
961 DecodeCtx *ctx = conn->ctxp;
966 guint8 in[sizeof (ctx->out) * 4 / 3];
969 while (size > 0 && ctx->cout < ctx->coutl) {
970 /* we have some leftover bytes */
971 *buffer++ = ctx->out[ctx->cout++];
976 /* got what we needed? */
980 /* try to read more bytes */
981 r = fill_raw_bytes (conn, in, sizeof (in), err);
990 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
994 out = fill_raw_bytes (conn, buffer, size, err);
1000 static GstRTSPResult
1001 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1006 if (G_UNLIKELY (*idx > size))
1007 return GST_RTSP_ERROR;
1014 r = fill_bytes (conn, &buffer[*idx], left, &err);
1015 if (G_UNLIKELY (r == 0)) {
1016 return GST_RTSP_EEOF;
1017 } else if (G_UNLIKELY (r < 0)) {
1018 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1019 g_clear_error (&err);
1020 return GST_RTSP_EINTR;
1022 g_clear_error (&err);
1023 return GST_RTSP_ESYS;
1032 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1033 * end of a line. It even does its best to handle clients which mix them (even
1034 * though this is a really stupid idea (tm).) It also handles Line White Space
1035 * (LWS), where a line end followed by whitespace is considered LWS. This is
1036 * the method used in RTSP (and HTTP) to break long lines.
1038 static GstRTSPResult
1039 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1047 if (conn->read_ahead == READ_AHEAD_EOH) {
1048 /* the last call to read_line() already determined that we have reached
1049 * the end of the headers, so convey that information now */
1050 conn->read_ahead = 0;
1052 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1053 /* the last call to read_line() left off after having read \r\n */
1055 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1056 /* the last call to read_line() left off after having read \r\n\r */
1058 } else if (conn->read_ahead != 0) {
1059 /* the last call to read_line() left us with a character to start with */
1060 c = (guint8) conn->read_ahead;
1061 conn->read_ahead = 0;
1063 /* read the next character */
1064 r = fill_bytes (conn, &c, 1, &err);
1065 if (G_UNLIKELY (r == 0)) {
1066 return GST_RTSP_EEOF;
1067 } else if (G_UNLIKELY (r < 0)) {
1068 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1069 g_clear_error (&err);
1070 return GST_RTSP_EINTR;
1073 g_clear_error (&err);
1074 return GST_RTSP_ESYS;
1078 /* special treatment of line endings */
1079 if (c == '\r' || c == '\n') {
1083 /* need to read ahead one more character to know what to do... */
1084 r = fill_bytes (conn, &read_ahead, 1, &err);
1085 if (G_UNLIKELY (r == 0)) {
1086 return GST_RTSP_EEOF;
1087 } else if (G_UNLIKELY (r < 0)) {
1088 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
1089 /* remember the original character we read and try again next time */
1090 if (conn->read_ahead == 0)
1091 conn->read_ahead = c;
1092 return GST_RTSP_EINTR;
1093 g_clear_error (&err);
1094 return GST_RTSP_EINTR;
1097 g_clear_error (&err);
1098 return GST_RTSP_ESYS;
1101 if (read_ahead == ' ' || read_ahead == '\t') {
1102 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1103 /* got \r\n\r followed by whitespace, treat it as a normal line
1104 * followed by one starting with LWS */
1105 conn->read_ahead = read_ahead;
1108 /* got LWS, change the line ending to a space and continue */
1110 conn->read_ahead = read_ahead;
1112 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1113 if (read_ahead == '\r' || read_ahead == '\n') {
1114 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1115 conn->read_ahead = READ_AHEAD_EOH;
1118 /* got \r\n\r followed by something else, this is not really
1119 * supported since we have probably just eaten the first character
1120 * of the body or the next message, so just ignore the second \r
1121 * and live with it... */
1122 conn->read_ahead = read_ahead;
1125 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1126 if (read_ahead == '\r') {
1127 /* got \r\n\r so far, need one more character... */
1128 conn->read_ahead = READ_AHEAD_CRLFCR;
1130 } else if (read_ahead == '\n') {
1131 /* got \r\n\n, treat it as the end of the headers */
1132 conn->read_ahead = READ_AHEAD_EOH;
1135 /* found the end of a line, keep read_ahead for the next line */
1136 conn->read_ahead = read_ahead;
1139 } else if (c == read_ahead) {
1140 /* got double \r or \n, treat it as the end of the headers */
1141 conn->read_ahead = READ_AHEAD_EOH;
1143 } else if (c == '\r' && read_ahead == '\n') {
1144 /* got \r\n so far, still need more to know what to do... */
1145 conn->read_ahead = READ_AHEAD_CRLF;
1148 /* found the end of a line, keep read_ahead for the next line */
1149 conn->read_ahead = read_ahead;
1154 if (G_LIKELY (*idx < size - 1))
1155 buffer[(*idx)++] = c;
1157 buffer[*idx] = '\0';
1163 * gst_rtsp_connection_write:
1164 * @conn: a #GstRTSPConnection
1165 * @data: the data to write
1166 * @size: the size of @data
1167 * @timeout: a timeout value or #NULL
1169 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1170 * the specified @timeout. @timeout can be #NULL, in which case this function
1171 * might block forever.
1173 * This function can be cancelled with gst_rtsp_connection_flush().
1175 * Returns: #GST_RTSP_OK on success.
1178 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1179 guint size, GTimeVal * timeout)
1186 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1187 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1188 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
1190 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1197 write_bytes (conn->write_socket, data, &offset, size,
1199 if (G_LIKELY (res == GST_RTSP_OK))
1201 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1204 /* not all is written, wait until we can write more */
1205 g_socket_set_timeout (conn->write_socket,
1206 (to + GST_SECOND - 1) / GST_SECOND);
1207 if (!g_socket_condition_wait (conn->write_socket,
1208 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable, &err)) {
1209 g_socket_set_timeout (conn->write_socket, 0);
1210 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1211 g_clear_error (&err);
1213 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1214 g_clear_error (&err);
1217 g_clear_error (&err);
1220 g_socket_set_timeout (conn->write_socket, 0);
1227 return GST_RTSP_ETIMEOUT;
1231 return GST_RTSP_ESYS;
1235 return GST_RTSP_EINTR;
1244 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1246 GString *str = NULL;
1248 str = g_string_new ("");
1250 switch (message->type) {
1251 case GST_RTSP_MESSAGE_REQUEST:
1252 /* create request string, add CSeq */
1253 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1255 gst_rtsp_method_as_text (message->type_data.request.method),
1256 message->type_data.request.uri, conn->cseq++);
1257 /* add session id if we have one */
1258 if (conn->session_id[0] != '\0') {
1259 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1260 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1263 /* add any authentication headers */
1264 add_auth_header (conn, message);
1266 case GST_RTSP_MESSAGE_RESPONSE:
1267 /* create response string */
1268 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1269 message->type_data.response.code, message->type_data.response.reason);
1271 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1272 /* create request string */
1273 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1274 gst_rtsp_method_as_text (message->type_data.request.method),
1275 message->type_data.request.uri,
1276 gst_rtsp_version_as_text (message->type_data.request.version));
1277 /* add any authentication headers */
1278 add_auth_header (conn, message);
1280 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1281 /* create response string */
1282 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1283 gst_rtsp_version_as_text (message->type_data.request.version),
1284 message->type_data.response.code, message->type_data.response.reason);
1286 case GST_RTSP_MESSAGE_DATA:
1288 guint8 data_header[4];
1290 /* prepare data header */
1291 data_header[0] = '$';
1292 data_header[1] = message->type_data.data.channel;
1293 data_header[2] = (message->body_size >> 8) & 0xff;
1294 data_header[3] = message->body_size & 0xff;
1296 /* create string with header and data */
1297 str = g_string_append_len (str, (gchar *) data_header, 4);
1299 g_string_append_len (str, (gchar *) message->body,
1300 message->body_size);
1304 g_string_free (str, TRUE);
1305 g_return_val_if_reached (NULL);
1309 /* append headers and body */
1310 if (message->type != GST_RTSP_MESSAGE_DATA) {
1311 gchar date_string[100];
1313 gen_date_string (date_string, sizeof (date_string));
1315 /* add date header */
1316 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1317 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1319 /* append headers */
1320 gst_rtsp_message_append_headers (message, str);
1322 /* append Content-Length and body if needed */
1323 if (message->body != NULL && message->body_size > 0) {
1326 len = g_strdup_printf ("%d", message->body_size);
1327 g_string_append_printf (str, "%s: %s\r\n",
1328 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1330 /* header ends here */
1331 g_string_append (str, "\r\n");
1333 g_string_append_len (str, (gchar *) message->body,
1334 message->body_size);
1336 /* just end headers */
1337 g_string_append (str, "\r\n");
1345 * gst_rtsp_connection_send:
1346 * @conn: a #GstRTSPConnection
1347 * @message: the message to send
1348 * @timeout: a timeout value or #NULL
1350 * Attempt to send @message to the connected @conn, blocking up to
1351 * the specified @timeout. @timeout can be #NULL, in which case this function
1352 * might block forever.
1354 * This function can be cancelled with gst_rtsp_connection_flush().
1356 * Returns: #GST_RTSP_OK on success.
1359 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1362 GString *string = NULL;
1367 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1368 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1370 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1373 if (conn->tunneled) {
1374 str = g_base64_encode ((const guchar *) string->str, string->len);
1375 g_string_free (string, TRUE);
1380 g_string_free (string, FALSE);
1384 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1392 g_warning ("Wrong message");
1393 return GST_RTSP_EINVAL;
1397 static GstRTSPResult
1398 parse_string (gchar * dest, gint size, gchar ** src)
1400 GstRTSPResult res = GST_RTSP_OK;
1405 while (g_ascii_isspace (**src))
1408 while (!g_ascii_isspace (**src) && **src != '\0') {
1410 dest[idx++] = **src;
1412 res = GST_RTSP_EPARSE;
1421 static GstRTSPResult
1422 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1423 GstRTSPVersion * version)
1425 GstRTSPResult res = GST_RTSP_OK;
1428 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1435 /* the version number must be formatted as X.Y with nothing following */
1436 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1437 res = GST_RTSP_EPARSE;
1439 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1440 if (major != 1 || minor != 0) {
1441 *version = GST_RTSP_VERSION_INVALID;
1442 res = GST_RTSP_ERROR;
1444 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1445 if (*type == GST_RTSP_MESSAGE_REQUEST)
1446 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1447 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1448 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1450 if (major == 1 && minor == 1) {
1451 *version = GST_RTSP_VERSION_1_1;
1452 } else if (major != 1 || minor != 0) {
1453 *version = GST_RTSP_VERSION_INVALID;
1454 res = GST_RTSP_ERROR;
1457 res = GST_RTSP_EPARSE;
1459 res = GST_RTSP_EPARSE;
1464 static GstRTSPResult
1465 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1467 GstRTSPResult res = GST_RTSP_OK;
1469 gchar versionstr[20];
1474 bptr = (gchar *) buffer;
1476 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1477 res = GST_RTSP_EPARSE;
1479 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1480 res = GST_RTSP_EPARSE;
1481 code = atoi (codestr);
1482 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1483 res = GST_RTSP_EPARSE;
1485 while (g_ascii_isspace (*bptr))
1488 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1489 NULL) != GST_RTSP_OK))
1490 res = GST_RTSP_EPARSE;
1492 res2 = parse_protocol_version (versionstr, &msg->type,
1493 &msg->type_data.response.version);
1494 if (G_LIKELY (res == GST_RTSP_OK))
1500 static GstRTSPResult
1501 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1503 GstRTSPResult res = GST_RTSP_OK;
1505 gchar versionstr[20];
1506 gchar methodstr[20];
1509 GstRTSPMethod method;
1511 bptr = (gchar *) buffer;
1513 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1514 res = GST_RTSP_EPARSE;
1515 method = gst_rtsp_find_method (methodstr);
1517 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1518 res = GST_RTSP_EPARSE;
1519 if (G_UNLIKELY (*urlstr == '\0'))
1520 res = GST_RTSP_EPARSE;
1522 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1523 res = GST_RTSP_EPARSE;
1525 if (G_UNLIKELY (*bptr != '\0'))
1526 res = GST_RTSP_EPARSE;
1528 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1529 urlstr) != GST_RTSP_OK))
1530 res = GST_RTSP_EPARSE;
1532 res2 = parse_protocol_version (versionstr, &msg->type,
1533 &msg->type_data.request.version);
1534 if (G_LIKELY (res == GST_RTSP_OK))
1537 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1538 /* GET and POST are not allowed as RTSP methods */
1539 if (msg->type_data.request.method == GST_RTSP_GET ||
1540 msg->type_data.request.method == GST_RTSP_POST) {
1541 msg->type_data.request.method = GST_RTSP_INVALID;
1542 if (res == GST_RTSP_OK)
1543 res = GST_RTSP_ERROR;
1545 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1546 /* only GET and POST are allowed as HTTP methods */
1547 if (msg->type_data.request.method != GST_RTSP_GET &&
1548 msg->type_data.request.method != GST_RTSP_POST) {
1549 msg->type_data.request.method = GST_RTSP_INVALID;
1550 if (res == GST_RTSP_OK)
1551 res = GST_RTSP_ERROR;
1558 /* parsing lines means reading a Key: Value pair */
1559 static GstRTSPResult
1560 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1562 GstRTSPHeaderField field;
1563 gchar *line = (gchar *) buffer;
1566 if ((value = strchr (line, ':')) == NULL || value == line)
1569 /* trim space before the colon */
1570 if (value[-1] == ' ')
1573 /* replace the colon with a NUL */
1576 /* find the header */
1577 field = gst_rtsp_find_header_field (line);
1578 if (field == GST_RTSP_HDR_INVALID)
1581 /* split up the value in multiple key:value pairs if it contains comma(s) */
1582 while (*value != '\0') {
1584 gchar *comma = NULL;
1585 gboolean quoted = FALSE;
1588 /* trim leading space */
1592 /* for headers which may not appear multiple times, and thus may not
1593 * contain multiple values on the same line, we can short-circuit the loop
1594 * below and the entire value results in just one key:value pair*/
1595 if (!gst_rtsp_header_allow_multiple (field))
1596 next_value = value + strlen (value);
1600 /* find the next value, taking special care of quotes and comments */
1601 while (*next_value != '\0') {
1602 if ((quoted || comment != 0) && *next_value == '\\' &&
1603 next_value[1] != '\0')
1605 else if (comment == 0 && *next_value == '"')
1607 else if (!quoted && *next_value == '(')
1609 else if (comment != 0 && *next_value == ')')
1611 else if (!quoted && comment == 0) {
1612 /* To quote RFC 2068: "User agents MUST take special care in parsing
1613 * the WWW-Authenticate field value if it contains more than one
1614 * challenge, or if more than one WWW-Authenticate header field is
1615 * provided, since the contents of a challenge may itself contain a
1616 * comma-separated list of authentication parameters."
1618 * What this means is that we cannot just look for an unquoted comma
1619 * when looking for multiple values in Proxy-Authenticate and
1620 * WWW-Authenticate headers. Instead we need to look for the sequence
1621 * "comma [space] token space token" before we can split after the
1624 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1625 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1626 if (*next_value == ',') {
1627 if (next_value[1] == ' ') {
1628 /* skip any space following the comma so we do not mistake it for
1629 * separating between two tokens */
1633 } else if (*next_value == ' ' && next_value[1] != ',' &&
1634 next_value[1] != '=' && comma != NULL) {
1639 } else if (*next_value == ',')
1647 if (value != next_value && next_value[-1] == ' ')
1648 next_value[-1] = '\0';
1650 if (*next_value != '\0')
1651 *next_value++ = '\0';
1653 /* add the key:value pair */
1655 gst_rtsp_message_add_header (msg, field, value);
1666 return GST_RTSP_EPARSE;
1670 /* convert all consecutive whitespace to a single space */
1672 normalize_line (guint8 * buffer)
1675 if (g_ascii_isspace (*buffer)) {
1679 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1682 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1690 * GST_RTSP_OK when a complete message was read.
1691 * GST_RTSP_EEOF: when the read socket is closed
1692 * GST_RTSP_EINTR: when more data is needed.
1693 * GST_RTSP_..: some other error occured.
1695 static GstRTSPResult
1696 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1697 GstRTSPConnection * conn)
1702 switch (builder->state) {
1707 builder->offset = 0;
1709 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1710 if (res != GST_RTSP_OK)
1713 c = builder->buffer[0];
1715 /* we have 1 bytes now and we can see if this is a data message or
1718 /* data message, prepare for the header */
1719 builder->state = STATE_DATA_HEADER;
1720 } else if (c == '\n' || c == '\r') {
1721 /* skip \n and \r */
1722 builder->offset = 0;
1725 builder->state = STATE_READ_LINES;
1729 case STATE_DATA_HEADER:
1732 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1733 if (res != GST_RTSP_OK)
1736 gst_rtsp_message_init_data (message, builder->buffer[1]);
1738 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1739 builder->body_data = g_malloc (builder->body_len + 1);
1740 builder->body_data[builder->body_len] = '\0';
1741 builder->offset = 0;
1742 builder->state = STATE_DATA_BODY;
1745 case STATE_DATA_BODY:
1748 read_bytes (conn, builder->body_data, &builder->offset,
1750 if (res != GST_RTSP_OK)
1753 /* we have the complete body now, store in the message adjusting the
1754 * length to include the trailing '\0' */
1755 gst_rtsp_message_take_body (message,
1756 (guint8 *) builder->body_data, builder->body_len + 1);
1757 builder->body_data = NULL;
1758 builder->body_len = 0;
1760 builder->state = STATE_END;
1763 case STATE_READ_LINES:
1765 res = read_line (conn, builder->buffer, &builder->offset,
1766 sizeof (builder->buffer));
1767 if (res != GST_RTSP_OK)
1770 /* we have a regular response */
1771 if (builder->buffer[0] == '\0') {
1774 /* empty line, end of message header */
1775 /* see if there is a Content-Length header, but ignore it if this
1776 * is a POST request with an x-sessioncookie header */
1777 if (gst_rtsp_message_get_header (message,
1778 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1779 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1780 message->type_data.request.method != GST_RTSP_POST ||
1781 gst_rtsp_message_get_header (message,
1782 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1783 /* there is, prepare to read the body */
1784 builder->body_len = atol (hdrval);
1785 builder->body_data = g_try_malloc (builder->body_len + 1);
1786 /* we can't do much here, we need the length to know how many bytes
1787 * we need to read next and when allocation fails, something is
1788 * probably wrong with the length. */
1789 if (builder->body_data == NULL)
1790 goto invalid_body_len;
1792 builder->body_data[builder->body_len] = '\0';
1793 builder->offset = 0;
1794 builder->state = STATE_DATA_BODY;
1796 builder->state = STATE_END;
1801 /* we have a line */
1802 normalize_line (builder->buffer);
1803 if (builder->line == 0) {
1804 /* first line, check for response status */
1805 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1806 memcmp (builder->buffer, "HTTP", 4) == 0) {
1807 builder->status = parse_response_status (builder->buffer, message);
1809 builder->status = parse_request_line (builder->buffer, message);
1812 /* else just parse the line */
1813 res = parse_line (builder->buffer, message);
1814 if (res != GST_RTSP_OK)
1815 builder->status = res;
1818 builder->offset = 0;
1823 gchar *session_cookie;
1826 if (message->type == GST_RTSP_MESSAGE_DATA) {
1827 /* data messages don't have headers */
1832 /* save the tunnel session in the connection */
1833 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1834 !conn->manual_http &&
1835 conn->tstate == TUNNEL_STATE_NONE &&
1836 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1837 &session_cookie, 0) == GST_RTSP_OK) {
1838 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1839 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1840 conn->tunneled = TRUE;
1843 /* save session id in the connection for further use */
1844 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1845 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1846 &session_id, 0) == GST_RTSP_OK) {
1849 maxlen = sizeof (conn->session_id) - 1;
1850 /* the sessionid can have attributes marked with ;
1851 * Make sure we strip them */
1852 for (i = 0; session_id[i] != '\0'; i++) {
1853 if (session_id[i] == ';') {
1858 } while (g_ascii_isspace (session_id[i]));
1859 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1862 /* if we parsed something valid, configure */
1863 if ((to = atoi (&session_id[i + 8])) > 0)
1870 /* make sure to not overflow */
1871 strncpy (conn->session_id, session_id, maxlen);
1872 conn->session_id[maxlen] = '\0';
1874 res = builder->status;
1878 res = GST_RTSP_ERROR;
1888 GST_DEBUG ("could not allocate body");
1889 return GST_RTSP_ERROR;
1894 * gst_rtsp_connection_read:
1895 * @conn: a #GstRTSPConnection
1896 * @data: the data to read
1897 * @size: the size of @data
1898 * @timeout: a timeout value or #NULL
1900 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1901 * the specified @timeout. @timeout can be #NULL, in which case this function
1902 * might block forever.
1904 * This function can be cancelled with gst_rtsp_connection_flush().
1906 * Returns: #GST_RTSP_OK on success.
1909 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1917 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1918 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1919 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
1921 if (G_UNLIKELY (size == 0))
1926 /* configure timeout if any */
1927 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1930 res = read_bytes (conn, data, &offset, size);
1931 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1933 if (G_LIKELY (res == GST_RTSP_OK))
1935 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1938 g_socket_set_timeout (conn->read_socket,
1939 (to + GST_SECOND - 1) / GST_SECOND);
1940 if (!g_socket_condition_wait (conn->read_socket,
1941 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
1943 g_socket_set_timeout (conn->read_socket, 0);
1944 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
1945 g_clear_error (&err);
1947 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
1948 g_clear_error (&err);
1949 goto select_timeout;
1951 g_clear_error (&err);
1954 g_socket_set_timeout (conn->read_socket, 0);
1961 return GST_RTSP_ESYS;
1965 return GST_RTSP_ETIMEOUT;
1969 return GST_RTSP_EINTR;
1973 return GST_RTSP_EEOF;
1981 static GstRTSPMessage *
1982 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
1983 const GstRTSPMessage * request)
1985 GstRTSPMessage *msg;
1988 if (gst_rtsp_status_as_text (code) == NULL)
1989 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1991 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
1994 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
1995 "GStreamer RTSP Server");
1996 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
1997 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
1998 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2000 if (code == GST_RTSP_STS_OK) {
2002 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2004 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2005 "application/x-rtsp-tunnelled");
2018 * gst_rtsp_connection_receive:
2019 * @conn: a #GstRTSPConnection
2020 * @message: the message to read
2021 * @timeout: a timeout value or #NULL
2023 * Attempt to read into @message from the connected @conn, blocking up to
2024 * the specified @timeout. @timeout can be #NULL, in which case this function
2025 * might block forever.
2027 * This function can be cancelled with gst_rtsp_connection_flush().
2029 * Returns: #GST_RTSP_OK on success.
2032 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2036 GstRTSPBuilder builder;
2040 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2041 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2042 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2044 /* configure timeout if any */
2045 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2047 memset (&builder, 0, sizeof (GstRTSPBuilder));
2049 res = build_next (&builder, message, conn);
2050 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2052 else if (G_LIKELY (res == GST_RTSP_OK)) {
2053 if (!conn->manual_http) {
2054 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2055 if (conn->tstate == TUNNEL_STATE_NONE &&
2056 message->type_data.request.method == GST_RTSP_GET) {
2057 GstRTSPMessage *response;
2059 conn->tstate = TUNNEL_STATE_GET;
2061 /* tunnel GET request, we can reply now */
2062 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2063 res = gst_rtsp_connection_send (conn, response, timeout);
2064 gst_rtsp_message_free (response);
2065 if (res == GST_RTSP_OK)
2066 res = GST_RTSP_ETGET;
2068 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2069 message->type_data.request.method == GST_RTSP_POST) {
2070 conn->tstate = TUNNEL_STATE_POST;
2072 /* tunnel POST request, the caller now has to link the two
2074 res = GST_RTSP_ETPOST;
2077 res = GST_RTSP_EPARSE;
2080 } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2081 res = GST_RTSP_EPARSE;
2087 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2090 g_socket_set_timeout (conn->read_socket,
2091 (to + GST_SECOND - 1) / GST_SECOND);
2092 if (!g_socket_condition_wait (conn->read_socket,
2093 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable,
2095 g_socket_set_timeout (conn->read_socket, 0);
2096 if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_BUSY)) {
2097 g_clear_error (&err);
2099 } else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
2100 g_clear_error (&err);
2101 goto select_timeout;
2103 g_clear_error (&err);
2106 g_socket_set_timeout (conn->read_socket, 0);
2109 /* we have a message here */
2110 build_reset (&builder);
2117 res = GST_RTSP_ESYS;
2122 res = GST_RTSP_ETIMEOUT;
2127 res = GST_RTSP_EINTR;
2132 res = GST_RTSP_EEOF;
2138 build_reset (&builder);
2139 gst_rtsp_message_unset (message);
2145 * gst_rtsp_connection_close:
2146 * @conn: a #GstRTSPConnection
2148 * Close the connected @conn. After this call, the connection is in the same
2149 * state as when it was first created.
2151 * Returns: #GST_RTSP_OK on success.
2154 gst_rtsp_connection_close (GstRTSPConnection * conn)
2156 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2161 conn->read_ahead = 0;
2163 g_free (conn->initial_buffer);
2164 conn->initial_buffer = NULL;
2165 conn->initial_buffer_offset = 0;
2167 conn->write_socket = NULL;
2168 conn->read_socket = NULL;
2169 conn->tunneled = FALSE;
2170 conn->tstate = TUNNEL_STATE_NONE;
2172 g_free (conn->username);
2173 conn->username = NULL;
2174 g_free (conn->passwd);
2175 conn->passwd = NULL;
2176 gst_rtsp_connection_clear_auth_params (conn);
2179 conn->session_id[0] = '\0';
2185 * gst_rtsp_connection_free:
2186 * @conn: a #GstRTSPConnection
2188 * Close and free @conn.
2190 * Returns: #GST_RTSP_OK on success.
2193 gst_rtsp_connection_free (GstRTSPConnection * conn)
2197 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2199 res = gst_rtsp_connection_close (conn);
2201 g_object_unref (conn->socket0);
2203 g_object_unref (conn->socket1);
2205 if (conn->cancellable)
2206 g_object_unref (conn->cancellable);
2208 g_timer_destroy (conn->timer);
2209 gst_rtsp_url_free (conn->url);
2210 g_free (conn->proxy_host);
2217 * gst_rtsp_connection_poll:
2218 * @conn: a #GstRTSPConnection
2219 * @events: a bitmask of #GstRTSPEvent flags to check
2220 * @revents: location for result flags
2221 * @timeout: a timeout
2223 * Wait up to the specified @timeout for the connection to become available for
2224 * at least one of the operations specified in @events. When the function returns
2225 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2228 * @timeout can be #NULL, in which case this function might block forever.
2230 * This function can be cancelled with gst_rtsp_connection_flush().
2232 * Returns: #GST_RTSP_OK on success.
2237 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2238 GstRTSPEvent * revents, GTimeVal * timeout)
2242 GSource *rs, *ws, *ts;
2243 GIOCondition condition;
2245 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2246 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2247 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2248 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2249 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2251 ctx = g_main_context_new ();
2253 /* configure timeout if any */
2254 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2257 ts = g_timeout_source_new (to / GST_MSECOND);
2258 g_source_set_dummy_callback (ts);
2259 g_source_attach (ts, ctx);
2260 g_source_unref (ts);
2263 rs = g_socket_create_source (conn->read_socket,
2264 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, conn->cancellable);
2265 g_source_set_dummy_callback (rs);
2266 g_source_attach (rs, ctx);
2267 g_source_unref (rs);
2269 ws = g_socket_create_source (conn->write_socket,
2270 G_IO_OUT | G_IO_ERR | G_IO_HUP, conn->cancellable);
2271 g_source_set_dummy_callback (ws);
2272 g_source_attach (ws, ctx);
2273 g_source_unref (ws);
2275 /* Returns after handling all pending events */
2276 g_main_context_iteration (ctx, TRUE);
2278 g_main_context_unref (ctx);
2281 g_socket_condition_check (conn->read_socket,
2282 G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP);
2284 g_socket_condition_check (conn->write_socket,
2285 G_IO_OUT | G_IO_ERR | G_IO_HUP);
2288 if (events & GST_RTSP_EV_READ) {
2289 if ((condition & G_IO_IN) || (condition & G_IO_PRI))
2290 *revents |= GST_RTSP_EV_READ;
2292 if (events & GST_RTSP_EV_WRITE) {
2293 if ((condition & G_IO_OUT))
2294 *revents |= GST_RTSP_EV_WRITE;
2298 return GST_RTSP_ETIMEOUT;
2304 * gst_rtsp_connection_next_timeout:
2305 * @conn: a #GstRTSPConnection
2306 * @timeout: a timeout
2308 * Calculate the next timeout for @conn, storing the result in @timeout.
2310 * Returns: #GST_RTSP_OK.
2313 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2320 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2321 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2323 ctimeout = conn->timeout;
2324 if (ctimeout >= 20) {
2325 /* Because we should act before the timeout we timeout 5
2326 * seconds in advance. */
2328 } else if (ctimeout >= 5) {
2329 /* else timeout 20% earlier */
2330 ctimeout -= ctimeout / 5;
2331 } else if (ctimeout >= 1) {
2332 /* else timeout 1 second earlier */
2336 elapsed = g_timer_elapsed (conn->timer, &usec);
2337 if (elapsed >= ctimeout) {
2341 sec = ctimeout - elapsed;
2342 if (usec <= G_USEC_PER_SEC)
2343 usec = G_USEC_PER_SEC - usec;
2348 timeout->tv_sec = sec;
2349 timeout->tv_usec = usec;
2355 * gst_rtsp_connection_reset_timeout:
2356 * @conn: a #GstRTSPConnection
2358 * Reset the timeout of @conn.
2360 * Returns: #GST_RTSP_OK.
2363 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2365 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2367 g_timer_start (conn->timer);
2373 * gst_rtsp_connection_flush:
2374 * @conn: a #GstRTSPConnection
2375 * @flush: start or stop the flush
2377 * Start or stop the flushing action on @conn. When flushing, all current
2378 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2379 * is set to non-flushing mode again.
2381 * Returns: #GST_RTSP_OK.
2384 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2386 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2389 g_cancellable_cancel (conn->cancellable);
2391 g_cancellable_reset (conn->cancellable);
2397 * gst_rtsp_connection_set_proxy:
2398 * @conn: a #GstRTSPConnection
2399 * @host: the proxy host
2400 * @port: the proxy port
2402 * Set the proxy host and port.
2404 * Returns: #GST_RTSP_OK.
2409 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2410 const gchar * host, guint port)
2412 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2414 g_free (conn->proxy_host);
2415 conn->proxy_host = g_strdup (host);
2416 conn->proxy_port = port;
2422 * gst_rtsp_connection_set_auth:
2423 * @conn: a #GstRTSPConnection
2424 * @method: authentication method
2426 * @pass: the password
2428 * Configure @conn for authentication mode @method with @user and @pass as the
2429 * user and password respectively.
2431 * Returns: #GST_RTSP_OK.
2434 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2435 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2437 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2439 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2440 || g_strrstr (user, ":") != NULL))
2441 return GST_RTSP_EINVAL;
2443 /* Make sure the username and passwd are being set for authentication */
2444 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2445 return GST_RTSP_EINVAL;
2447 /* ":" chars are not allowed in usernames for basic auth */
2448 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2449 return GST_RTSP_EINVAL;
2451 g_free (conn->username);
2452 g_free (conn->passwd);
2454 conn->auth_method = method;
2455 conn->username = g_strdup (user);
2456 conn->passwd = g_strdup (pass);
2463 * @key: ASCII string to hash
2465 * Hashes @key in a case-insensitive manner.
2467 * Returns: the hash code.
2470 str_case_hash (gconstpointer key)
2472 const char *p = key;
2473 guint h = g_ascii_toupper (*p);
2476 for (p += 1; *p != '\0'; p++)
2477 h = (h << 5) - h + g_ascii_toupper (*p);
2484 * @v1: an ASCII string
2485 * @v2: another ASCII string
2487 * Compares @v1 and @v2 in a case-insensitive manner
2489 * Returns: %TRUE if they are equal (modulo case)
2492 str_case_equal (gconstpointer v1, gconstpointer v2)
2494 const char *string1 = v1;
2495 const char *string2 = v2;
2497 return g_ascii_strcasecmp (string1, string2) == 0;
2501 * gst_rtsp_connection_set_auth_param:
2502 * @conn: a #GstRTSPConnection
2503 * @param: authentication directive
2506 * Setup @conn with authentication directives. This is not necesary for
2507 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2508 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2509 * in the WWW-Authenticate response header and can include realm, domain,
2510 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2515 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2516 const gchar * param, const gchar * value)
2518 g_return_if_fail (conn != NULL);
2519 g_return_if_fail (param != NULL);
2521 if (conn->auth_params == NULL) {
2523 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2525 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2529 * gst_rtsp_connection_clear_auth_params:
2530 * @conn: a #GstRTSPConnection
2532 * Clear the list of authentication directives stored in @conn.
2537 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2539 g_return_if_fail (conn != NULL);
2541 if (conn->auth_params != NULL) {
2542 g_hash_table_destroy (conn->auth_params);
2543 conn->auth_params = NULL;
2547 static GstRTSPResult
2548 set_qos_dscp (GSocket * socket, guint qos_dscp)
2554 union gst_sockaddr sa;
2555 socklen_t slen = sizeof (sa);
2562 fd = g_socket_get_fd (socket);
2563 if (getsockname (fd, &sa.sa, &slen) < 0)
2564 goto no_getsockname;
2566 af = sa.sa.sa_family;
2568 /* if this is an IPv4-mapped address then do IPv4 QoS */
2569 if (af == AF_INET6) {
2570 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2574 /* extract and shift 6 bits of the DSCP */
2575 tos = (qos_dscp & 0x3f) << 2;
2579 if (setsockopt (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2584 if (setsockopt (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2598 return GST_RTSP_ESYS;
2602 return GST_RTSP_ERROR;
2608 * gst_rtsp_connection_set_qos_dscp:
2609 * @conn: a #GstRTSPConnection
2610 * @qos_dscp: DSCP value
2612 * Configure @conn to use the specified DSCP value.
2614 * Returns: #GST_RTSP_OK on success.
2619 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2623 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2624 g_return_val_if_fail (conn->read_socket != NULL, GST_RTSP_EINVAL);
2625 g_return_val_if_fail (conn->write_socket != NULL, GST_RTSP_EINVAL);
2627 res = set_qos_dscp (conn->socket0, qos_dscp);
2628 if (res == GST_RTSP_OK)
2629 res = set_qos_dscp (conn->socket1, qos_dscp);
2636 * gst_rtsp_connection_get_url:
2637 * @conn: a #GstRTSPConnection
2639 * Retrieve the URL of the other end of @conn.
2641 * Returns: The URL. This value remains valid until the
2642 * connection is freed.
2647 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2649 g_return_val_if_fail (conn != NULL, NULL);
2655 * gst_rtsp_connection_get_ip:
2656 * @conn: a #GstRTSPConnection
2658 * Retrieve the IP address of the other end of @conn.
2660 * Returns: The IP address as a string. this value remains valid until the
2661 * connection is closed.
2666 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2668 g_return_val_if_fail (conn != NULL, NULL);
2674 * gst_rtsp_connection_set_ip:
2675 * @conn: a #GstRTSPConnection
2676 * @ip: an ip address
2678 * Set the IP address of the server.
2683 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2685 g_return_if_fail (conn != NULL);
2688 conn->ip = g_strdup (ip);
2692 * gst_rtsp_connection_get_readfd:
2693 * @conn: a #GstRTSPConnection
2695 * Get the file descriptor for reading.
2697 * Returns: the file descriptor used for reading or %NULL on error. The file
2698 * descriptor remains valid until the connection is closed.
2703 gst_rtsp_connection_get_read_socket (const GstRTSPConnection * conn)
2705 g_return_val_if_fail (conn != NULL, NULL);
2706 g_return_val_if_fail (conn->read_socket != NULL, NULL);
2708 return conn->read_socket;
2712 * gst_rtsp_connection_get_write_socket:
2713 * @conn: a #GstRTSPConnection
2715 * Get the file descriptor for writing.
2717 * Returns: the file descriptor used for writing or NULL on error. The file
2718 * descriptor remains valid until the connection is closed.
2723 gst_rtsp_connection_get_write_socket (const GstRTSPConnection * conn)
2725 g_return_val_if_fail (conn != NULL, NULL);
2726 g_return_val_if_fail (conn->write_socket != NULL, NULL);
2728 return conn->write_socket;
2732 * gst_rtsp_connection_set_http_mode:
2733 * @conn: a #GstRTSPConnection
2734 * @enable: %TRUE to enable manual HTTP mode
2736 * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2737 * messages in addition to the RTSP messages. It will also disable the
2738 * automatic handling of setting up an HTTP tunnel.
2743 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2745 g_return_if_fail (conn != NULL);
2747 conn->manual_http = enable;
2751 * gst_rtsp_connection_set_tunneled:
2752 * @conn: a #GstRTSPConnection
2753 * @tunneled: the new state
2755 * Set the HTTP tunneling state of the connection. This must be configured before
2756 * the @conn is connected.
2761 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2763 g_return_if_fail (conn != NULL);
2764 g_return_if_fail (conn->read_socket == NULL);
2765 g_return_if_fail (conn->write_socket == NULL);
2767 conn->tunneled = tunneled;
2771 * gst_rtsp_connection_is_tunneled:
2772 * @conn: a #GstRTSPConnection
2774 * Get the tunneling state of the connection.
2776 * Returns: if @conn is using HTTP tunneling.
2781 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2783 g_return_val_if_fail (conn != NULL, FALSE);
2785 return conn->tunneled;
2789 * gst_rtsp_connection_get_tunnelid:
2790 * @conn: a #GstRTSPConnection
2792 * Get the tunnel session id the connection.
2794 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2799 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2801 g_return_val_if_fail (conn != NULL, NULL);
2803 if (!conn->tunneled)
2806 return conn->tunnelid;
2810 * gst_rtsp_connection_do_tunnel:
2811 * @conn: a #GstRTSPConnection
2812 * @conn2: a #GstRTSPConnection or %NULL
2814 * If @conn received the first tunnel connection and @conn2 received
2815 * the second tunnel connection, link the two connections together so that
2816 * @conn manages the tunneled connection.
2818 * After this call, @conn2 cannot be used anymore and must be freed with
2819 * gst_rtsp_connection_free().
2821 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2824 * Returns: return GST_RTSP_OK on success.
2829 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2830 GstRTSPConnection * conn2)
2832 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2834 if (conn2 != NULL) {
2835 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2836 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2837 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2838 TUNNELID_LEN), GST_RTSP_EINVAL);
2840 /* both connections have socket0 as the read/write socket. start by taking the
2841 * socket from conn2 and set it as the socket in conn */
2842 conn->socket1 = conn2->socket0;
2844 /* clean up some of the state of conn2 */
2845 g_cancellable_cancel (conn2->cancellable);
2847 g_object_unref (conn2->socket1);
2848 conn2->socket1 = NULL;
2849 conn2->write_socket = conn2->read_socket = NULL;
2850 g_cancellable_reset (conn2->cancellable);
2852 /* We make socket0 the write socket and socket1 the read socket. */
2853 conn->write_socket = conn->socket0;
2854 conn->read_socket = conn->socket1;
2856 conn->tstate = TUNNEL_STATE_COMPLETE;
2859 /* we need base64 decoding for the readfd */
2860 conn->ctx.state = 0;
2863 conn->ctx.coutl = 0;
2864 conn->ctxp = &conn->ctx;
2869 #define READ_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2870 #define READ_COND (G_IO_IN | READ_ERR)
2871 #define WRITE_ERR (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
2872 #define WRITE_COND (G_IO_OUT | WRITE_ERR)
2881 /* async functions */
2882 struct _GstRTSPWatch
2886 GstRTSPConnection *conn;
2888 GstRTSPBuilder builder;
2889 GstRTSPMessage message;
2894 /* queued message for transmission */
2903 GstRTSPWatchFuncs funcs;
2906 GDestroyNotify notify;
2910 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2912 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2914 if (watch->conn->initial_buffer != NULL)
2917 *timeout = (watch->conn->timeout * 1000);
2923 gst_rtsp_source_check (GSource * source)
2925 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2927 if (watch->readfd.revents & READ_COND)
2930 if (watch->writefd.revents & WRITE_COND)
2937 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2938 gpointer user_data G_GNUC_UNUSED)
2940 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2941 GstRTSPResult res = GST_RTSP_ERROR;
2942 gboolean keep_running = TRUE;
2944 /* first read as much as we can */
2945 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2947 if (watch->readfd.revents & READ_ERR)
2950 res = build_next (&watch->builder, &watch->message, watch->conn);
2951 if (res == GST_RTSP_EINTR)
2953 else if (G_UNLIKELY (res == GST_RTSP_EEOF)) {
2954 watch->readfd.events = 0;
2955 watch->readfd.revents = 0;
2956 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2957 /* When we are in tunnelled mode, the read socket can be closed and we
2958 * should be prepared for a new POST method to reopen it */
2959 if (watch->conn->tstate == TUNNEL_STATE_COMPLETE) {
2960 /* remove the read connection for the tunnel */
2961 /* we accept a new POST request */
2962 watch->conn->tstate = TUNNEL_STATE_GET;
2963 /* and signal that we lost our tunnel */
2964 if (watch->funcs.tunnel_lost)
2965 res = watch->funcs.tunnel_lost (watch, watch->user_data);
2969 } else if (G_LIKELY (res == GST_RTSP_OK)) {
2970 if (!watch->conn->manual_http &&
2971 watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2972 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2973 watch->message.type_data.request.method == GST_RTSP_GET) {
2974 GstRTSPMessage *response;
2975 GstRTSPStatusCode code;
2977 watch->conn->tstate = TUNNEL_STATE_GET;
2979 if (watch->funcs.tunnel_start)
2980 code = watch->funcs.tunnel_start (watch, watch->user_data);
2982 code = GST_RTSP_STS_OK;
2984 /* queue the response */
2985 response = gen_tunnel_reply (watch->conn, code, &watch->message);
2986 gst_rtsp_watch_send_message (watch, response, NULL);
2987 gst_rtsp_message_free (response);
2989 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2990 watch->message.type_data.request.method == GST_RTSP_POST) {
2991 watch->conn->tstate = TUNNEL_STATE_POST;
2993 /* in the callback the connection should be tunneled with the
2995 if (watch->funcs.tunnel_complete)
2996 watch->funcs.tunnel_complete (watch, watch->user_data);
3002 if (!watch->conn->manual_http) {
3003 /* if manual HTTP support is not enabled, then restore the message to
3004 * what it would have looked like without the support for parsing HTTP
3005 * messages being present */
3006 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3007 watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3008 watch->message.type_data.request.method = GST_RTSP_INVALID;
3009 if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3010 watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3011 res = GST_RTSP_EPARSE;
3012 } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3013 watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3014 if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3015 watch->message.type_data.response.version =
3016 GST_RTSP_VERSION_INVALID;
3017 res = GST_RTSP_EPARSE;
3021 if (G_LIKELY (res == GST_RTSP_OK)) {
3022 if (watch->funcs.message_received)
3023 watch->funcs.message_received (watch, &watch->message,
3030 gst_rtsp_message_unset (&watch->message);
3031 build_reset (&watch->builder);
3035 if (watch->writefd.revents & WRITE_COND) {
3036 if (watch->writefd.revents & WRITE_ERR)
3039 g_mutex_lock (watch->mutex);
3041 if (watch->write_data == NULL) {
3044 /* get a new message from the queue */
3045 rec = g_queue_pop_tail (watch->messages);
3049 watch->write_off = 0;
3050 watch->write_data = rec->data;
3051 watch->write_size = rec->size;
3052 watch->write_id = rec->id;
3054 g_slice_free (GstRTSPRec, rec);
3057 res = write_bytes (watch->conn->write_socket, watch->write_data,
3058 &watch->write_off, watch->write_size, watch->conn->cancellable);
3059 g_mutex_unlock (watch->mutex);
3061 if (res == GST_RTSP_EINTR)
3063 else if (G_LIKELY (res == GST_RTSP_OK)) {
3064 if (watch->funcs.message_sent)
3065 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3069 g_mutex_lock (watch->mutex);
3071 g_free (watch->write_data);
3072 watch->write_data = NULL;
3075 watch->writefd.events = WRITE_ERR;
3077 g_mutex_unlock (watch->mutex);
3081 return keep_running;
3086 if (watch->funcs.closed)
3087 watch->funcs.closed (watch, watch->user_data);
3089 /* always stop when the readfd returns EOF in non-tunneled mode */
3094 watch->readfd.events = 0;
3095 watch->readfd.revents = 0;
3096 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3097 keep_running = (watch->writefd.events != 0);
3100 if (watch->funcs.error_full)
3101 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3102 0, watch->user_data), error);
3110 watch->writefd.events = 0;
3111 watch->writefd.revents = 0;
3112 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3113 keep_running = (watch->readfd.events != 0);
3116 if (watch->funcs.error_full)
3117 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3118 watch->write_id, watch->user_data), error);
3126 if (watch->funcs.error)
3127 watch->funcs.error (watch, res, watch->user_data);
3129 return keep_running;
3134 gst_rtsp_rec_free (gpointer data)
3136 GstRTSPRec *rec = data;
3139 g_slice_free (GstRTSPRec, rec);
3143 gst_rtsp_source_finalize (GSource * source)
3145 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3147 build_reset (&watch->builder);
3148 gst_rtsp_message_unset (&watch->message);
3150 g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3151 g_queue_free (watch->messages);
3152 watch->messages = NULL;
3153 g_free (watch->write_data);
3155 g_mutex_free (watch->mutex);
3158 watch->notify (watch->user_data);
3161 static GSourceFuncs gst_rtsp_source_funcs = {
3162 gst_rtsp_source_prepare,
3163 gst_rtsp_source_check,
3164 gst_rtsp_source_dispatch,
3165 gst_rtsp_source_finalize,
3171 * gst_rtsp_watch_new:
3172 * @conn: a #GstRTSPConnection
3173 * @funcs: watch functions
3174 * @user_data: user data to pass to @funcs
3175 * @notify: notify when @user_data is not referenced anymore
3177 * Create a watch object for @conn. The functions provided in @funcs will be
3178 * called with @user_data when activity happened on the watch.
3180 * The new watch is usually created so that it can be attached to a
3181 * maincontext with gst_rtsp_watch_attach().
3183 * @conn must exist for the entire lifetime of the watch.
3185 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3186 * communication. Free with gst_rtsp_watch_unref () after usage.
3191 gst_rtsp_watch_new (GstRTSPConnection * conn,
3192 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3194 GstRTSPWatch *result;
3196 g_return_val_if_fail (conn != NULL, NULL);
3197 g_return_val_if_fail (funcs != NULL, NULL);
3198 g_return_val_if_fail (conn->read_socket != NULL, NULL);
3199 g_return_val_if_fail (conn->write_socket != NULL, NULL);
3201 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3202 sizeof (GstRTSPWatch));
3204 result->conn = conn;
3205 result->builder.state = STATE_START;
3207 result->mutex = g_mutex_new ();
3208 result->messages = g_queue_new ();
3210 result->readfd.fd = -1;
3211 result->writefd.fd = -1;
3213 gst_rtsp_watch_reset (result);
3215 result->funcs = *funcs;
3216 result->user_data = user_data;
3217 result->notify = notify;
3223 * gst_rtsp_watch_reset:
3224 * @watch: a #GstRTSPWatch
3226 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3227 * when the file descriptors of the connection might have changed.
3232 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3234 if (watch->readfd.fd != -1)
3235 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3236 if (watch->writefd.fd != -1)
3237 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3239 watch->readfd.fd = g_socket_get_fd (watch->conn->read_socket);
3240 watch->readfd.events = READ_COND;
3241 watch->readfd.revents = 0;
3243 watch->writefd.fd = g_socket_get_fd (watch->conn->write_socket);
3244 watch->writefd.events = WRITE_ERR;
3245 watch->writefd.revents = 0;
3247 if (watch->readfd.fd != -1)
3248 g_source_add_poll ((GSource *) watch, &watch->readfd);
3249 if (watch->writefd.fd != -1)
3250 g_source_add_poll ((GSource *) watch, &watch->writefd);
3254 * gst_rtsp_watch_attach:
3255 * @watch: a #GstRTSPWatch
3256 * @context: a GMainContext (if NULL, the default context will be used)
3258 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3260 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3265 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3267 g_return_val_if_fail (watch != NULL, 0);
3269 return g_source_attach ((GSource *) watch, context);
3273 * gst_rtsp_watch_unref:
3274 * @watch: a #GstRTSPWatch
3276 * Decreases the reference count of @watch by one. If the resulting reference
3277 * count is zero the watch and associated memory will be destroyed.
3282 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3284 g_return_if_fail (watch != NULL);
3286 g_source_unref ((GSource *) watch);
3290 * gst_rtsp_watch_write_data:
3291 * @watch: a #GstRTSPWatch
3292 * @data: the data to queue
3293 * @size: the size of @data
3294 * @id: location for a message ID or %NULL
3296 * Write @data using the connection of the @watch. If it cannot be sent
3297 * immediately, it will be queued for transmission in @watch. The contents of
3298 * @message will then be serialized and transmitted when the connection of the
3299 * @watch becomes writable. In case the @message is queued, the ID returned in
3300 * @id will be non-zero and used as the ID argument in the message_sent
3303 * This function will take ownership of @data and g_free() it after use.
3305 * Returns: #GST_RTSP_OK on success.
3310 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3311 guint size, guint * id)
3316 GMainContext *context = NULL;
3318 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3319 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3320 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3322 g_mutex_lock (watch->mutex);
3324 /* try to send the message synchronously first */
3325 if (watch->messages->length == 0 && watch->write_data == NULL) {
3327 write_bytes (watch->conn->write_socket, data, &off, size,
3328 watch->conn->cancellable);
3329 if (res != GST_RTSP_EINTR) {
3332 g_free ((gpointer) data);
3337 /* make a record with the data and id for sending async */
3338 rec = g_slice_new (GstRTSPRec);
3340 rec->data = (guint8 *) data;
3343 rec->data = g_memdup (data + off, size - off);
3344 rec->size = size - off;
3345 g_free ((gpointer) data);
3349 /* make sure rec->id is never 0 */
3350 rec->id = ++watch->id;
3351 } while (G_UNLIKELY (rec->id == 0));
3353 /* add the record to a queue. FIXME we would like to have an upper limit here */
3354 g_queue_push_head (watch->messages, rec);
3356 /* make sure the main context will now also check for writability on the
3358 if (watch->writefd.events != WRITE_COND) {
3359 watch->writefd.events = WRITE_COND;
3360 context = ((GSource *) watch)->context;
3368 g_mutex_unlock (watch->mutex);
3371 g_main_context_wakeup (context);
3377 * gst_rtsp_watch_send_message:
3378 * @watch: a #GstRTSPWatch
3379 * @message: a #GstRTSPMessage
3380 * @id: location for a message ID or %NULL
3382 * Send a @message using the connection of the @watch. If it cannot be sent
3383 * immediately, it will be queued for transmission in @watch. The contents of
3384 * @message will then be serialized and transmitted when the connection of the
3385 * @watch becomes writable. In case the @message is queued, the ID returned in
3386 * @id will be non-zero and used as the ID argument in the message_sent
3389 * Returns: #GST_RTSP_OK on success.
3394 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3400 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3401 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3403 /* make a record with the message as a string and id */
3404 str = message_to_string (watch->conn, message);
3406 return gst_rtsp_watch_write_data (watch,
3407 (guint8 *) g_string_free (str, FALSE), size, id);