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
50 * This object manages the RTSP connection to the server. It provides function
51 * to receive and send bytes and messages.
55 * Last reviewed on 2007-07-24 (0.10.14)
72 /* we include this here to get the G_OS_* defines */
77 /* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later.
78 * minwg32 headers check WINVER before allowing the use of these */
84 #define EINPROGRESS WSAEINPROGRESS
86 #include <sys/ioctl.h>
88 #include <sys/socket.h>
90 #include <netinet/in.h>
93 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
94 #include <sys/filio.h>
97 #include "gstrtspconnection.h"
98 #include "gstrtspbase64.h"
103 struct sockaddr_in sa_in;
104 struct sockaddr_in6 sa_in6;
105 struct sockaddr_storage sa_stor;
112 guchar out[3]; /* the size must be evenly divisible by 3 */
118 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
119 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
120 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
121 #define CLOSE_SOCKET(sock) closesocket (sock)
122 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
123 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
124 /* According to Microsoft's connect() documentation this one returns
125 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
126 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
128 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
129 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
130 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
131 #define CLOSE_SOCKET(sock) close (sock)
132 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
133 #define ERRNO_IS_EINTR (errno == EINTR)
134 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
137 #define ADD_POLLFD(fdset, pfd, fd) \
140 gst_poll_add_fd (fdset, pfd); \
143 #define REMOVE_POLLFD(fdset, pfd) \
145 if ((pfd)->fd != -1) { \
146 GST_DEBUG ("remove fd %d", (pfd)->fd); \
147 gst_poll_remove_fd (fdset, pfd); \
148 CLOSE_SOCKET ((pfd)->fd); \
158 TUNNEL_STATE_COMPLETE
159 } GstRTSPTunnelState;
161 #define TUNNELID_LEN 24
163 struct _GstRTSPConnection
166 /* URL for the connection */
169 /* connection state */
176 gchar tunnelid[TUNNELID_LEN];
178 GstRTSPTunnelState tstate;
183 gchar *initial_buffer;
184 gsize initial_buffer_offset;
187 gint cseq; /* sequence number */
188 gchar session_id[512]; /* session id */
189 gint timeout; /* session timeout in seconds */
190 GTimer *timer; /* timeout timer */
193 GstRTSPAuthMethod auth_method;
196 GHashTable *auth_params;
215 /* a structure for constructing RTSPMessages */
219 GstRTSPResult status;
229 build_reset (GstRTSPBuilder * builder)
231 g_free (builder->body_data);
232 memset (builder, 0, sizeof (GstRTSPBuilder));
236 * gst_rtsp_connection_create:
237 * @url: a #GstRTSPUrl
238 * @conn: storage for a #GstRTSPConnection
240 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
241 * The connection will not yet attempt to connect to @url, use
242 * gst_rtsp_connection_connect().
244 * A copy of @url will be made.
246 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
249 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
251 GstRTSPConnection *newconn;
257 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
260 error = WSAStartup (0x0202, &w);
265 if (w.wVersion != 0x0202)
269 newconn = g_new0 (GstRTSPConnection, 1);
271 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
274 newconn->url = gst_rtsp_url_copy (url);
275 newconn->fd0.fd = -1;
276 newconn->fd1.fd = -1;
277 newconn->timer = g_timer_new ();
278 newconn->timeout = 60;
281 newconn->auth_method = GST_RTSP_AUTH_NONE;
282 newconn->username = NULL;
283 newconn->passwd = NULL;
284 newconn->auth_params = NULL;
294 g_warning ("Error %d on WSAStartup", error);
295 return GST_RTSP_EWSASTART;
299 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
302 return GST_RTSP_EWSAVERSION;
311 return GST_RTSP_ESYS;
316 * gst_rtsp_connection_create_from_fd:
317 * @fd: a file descriptor
318 * @ip: the IP address of the other end
319 * @port: the port used by the other end
320 * @initial_buffer: data already read from @fd
321 * @conn: storage for a #GstRTSPConnection
323 * Create a new #GstRTSPConnection for handling communication on the existing
324 * file descriptor @fd. The @initial_buffer contains any data already read from
325 * @fd which should be used before starting to read new data.
327 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
332 gst_rtsp_connection_create_from_fd (gint fd, const gchar * ip, guint16 port,
333 const gchar * initial_buffer, GstRTSPConnection ** conn)
335 GstRTSPConnection *newconn = NULL;
342 g_return_val_if_fail (fd >= 0, GST_RTSP_EINVAL);
343 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
344 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
346 /* set to non-blocking mode so that we can cancel the communication */
348 fcntl (fd, F_SETFL, O_NONBLOCK);
350 ioctlsocket (fd, FIONBIO, &flags);
351 #endif /* G_OS_WIN32 */
353 /* create a url for the client address */
354 url = g_new0 (GstRTSPUrl, 1);
355 url->host = g_strdup (ip);
358 /* now create the connection object */
359 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
360 gst_rtsp_url_free (url);
362 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
364 /* both read and write initially */
365 newconn->readfd = &newconn->fd0;
366 newconn->writefd = &newconn->fd0;
368 newconn->ip = g_strdup (ip);
370 newconn->initial_buffer = g_strdup (initial_buffer);
379 gst_rtsp_url_free (url);
385 * gst_rtsp_connection_accept:
387 * @conn: storage for a #GstRTSPConnection
389 * Accept a new connection on @sock and create a new #GstRTSPConnection for
390 * handling communication on new socket.
392 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
397 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
400 union gst_sockaddr sa;
401 socklen_t slen = sizeof (sa);
402 gchar ip[INET6_ADDRSTRLEN];
405 g_return_val_if_fail (sock >= 0, GST_RTSP_EINVAL);
406 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
408 memset (&sa, 0, slen);
411 fd = accept (sock, &sa.sa, &slen);
413 fd = accept (sock, &sa.sa, (gint *) & slen);
414 #endif /* G_OS_WIN32 */
418 if (getnameinfo (&sa.sa, slen, ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) != 0)
419 goto getnameinfo_failed;
421 if (sa.sa.sa_family == AF_INET)
422 port = sa.sa_in.sin_port;
423 else if (sa.sa.sa_family == AF_INET6)
424 port = sa.sa_in6.sin6_port;
428 return gst_rtsp_connection_create_from_fd (fd, ip, port, NULL, conn);
433 return GST_RTSP_ESYS;
439 return GST_RTSP_ERROR;
444 do_resolve (const gchar * host)
446 static gchar ip[INET6_ADDRSTRLEN];
447 struct addrinfo *aires;
451 aierr = getaddrinfo (host, NULL, NULL, &aires);
455 for (ai = aires; ai; ai = ai->ai_next) {
456 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
463 aierr = getnameinfo (ai->ai_addr, ai->ai_addrlen, ip, sizeof (ip), NULL, 0,
464 NI_NUMERICHOST | NI_NUMERICSERV);
468 freeaddrinfo (aires);
470 return g_strdup (ip);
475 GST_ERROR ("no addrinfo found for %s: %s", host, gai_strerror (aierr));
480 GST_ERROR ("no family found for %s", host);
481 freeaddrinfo (aires);
486 GST_ERROR ("no address found for %s: %s", host, gai_strerror (aierr));
487 freeaddrinfo (aires);
493 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
494 GstPoll * fdset, GTimeVal * timeout)
497 struct addrinfo hints;
498 struct addrinfo *aires;
501 gchar service[NI_MAXSERV];
504 unsigned long flags = 1;
505 #endif /* G_OS_WIN32 */
509 memset (&hints, 0, sizeof hints);
510 hints.ai_flags = AI_NUMERICHOST;
511 hints.ai_family = AF_UNSPEC;
512 hints.ai_socktype = SOCK_STREAM;
513 g_snprintf (service, sizeof (service) - 1, "%hu", port);
514 service[sizeof (service) - 1] = '\0';
516 aierr = getaddrinfo (ip, service, &hints, &aires);
520 for (ai = aires; ai; ai = ai->ai_next) {
521 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
528 fd = socket (ai->ai_family, SOCK_STREAM, 0);
532 /* set to non-blocking mode so that we can cancel the connect */
534 fcntl (fd, F_SETFL, O_NONBLOCK);
536 ioctlsocket (fd, FIONBIO, &flags);
537 #endif /* G_OS_WIN32 */
539 /* add the socket to our fdset */
540 ADD_POLLFD (fdset, fdout, fd);
542 /* we are going to connect ASYNC now */
543 ret = connect (fd, ai->ai_addr, ai->ai_addrlen);
546 if (!ERRNO_IS_EINPROGRESS)
549 /* wait for connect to complete up to the specified timeout or until we got
551 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
553 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
556 retval = gst_poll_wait (fdset, to);
557 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
561 else if (retval == -1)
564 /* we can still have an error connecting on windows */
565 if (gst_poll_fd_has_error (fdset, fdout)) {
566 socklen_t len = sizeof (errno);
568 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
570 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
575 gst_poll_fd_ignored (fdset, fdout);
578 freeaddrinfo (aires);
585 GST_ERROR ("no addrinfo found for %s: %s", ip, gai_strerror (aierr));
586 return GST_RTSP_ERROR;
590 GST_ERROR ("no family found for %s", ip);
591 freeaddrinfo (aires);
592 return GST_RTSP_ERROR;
596 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
597 freeaddrinfo (aires);
598 return GST_RTSP_ESYS;
602 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
603 REMOVE_POLLFD (fdset, fdout);
604 freeaddrinfo (aires);
605 return GST_RTSP_ESYS;
609 GST_ERROR ("timeout");
610 REMOVE_POLLFD (fdset, fdout);
611 freeaddrinfo (aires);
612 return GST_RTSP_ETIMEOUT;
617 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
624 guint16 port, url_port;
628 GstRTSPMessage response;
630 memset (&response, 0, sizeof (response));
631 gst_rtsp_message_init (&response);
633 /* create a random sessionid */
634 for (i = 0; i < TUNNELID_LEN; i++)
635 conn->tunnelid[i] = g_random_int_range ('a', 'z');
636 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
639 /* get the port from the url */
640 gst_rtsp_url_get_port (url, &url_port);
642 if (conn->proxy_host) {
643 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
644 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
645 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
646 ip = conn->proxy_host;
647 port = conn->proxy_port;
649 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
650 url->query ? url->query : "");
656 /* create the GET request for the read connection */
657 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
659 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
661 if (hostparam != NULL)
662 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
663 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
665 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
666 "application/x-rtsp-tunnelled");
667 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
668 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
670 /* we start by writing to this fd */
671 conn->writefd = &conn->fd0;
673 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
674 * request from being base64 encoded */
675 conn->tunneled = FALSE;
676 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
677 gst_rtsp_message_free (msg);
678 conn->tunneled = TRUE;
680 /* receive the response to the GET request */
681 /* we need to temporarily set manual_http to TRUE since
682 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
683 * failure otherwise */
684 conn->manual_http = TRUE;
685 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
687 conn->manual_http = FALSE;
689 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
690 response.type_data.response.code != GST_RTSP_STS_OK)
693 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
694 &value, 0) != GST_RTSP_OK) {
695 if (conn->proxy_host) {
696 /* if we use a proxy we need to change the destination url */
698 url->host = g_strdup (value);
700 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
702 /* and resolve the new ip address */
703 if (!(ip = do_resolve (conn->ip)))
710 /* connect to the host/port */
711 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
712 if (res != GST_RTSP_OK)
715 /* this is now our writing socket */
716 conn->writefd = &conn->fd1;
718 /* create the POST request for the write connection */
719 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
721 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
723 if (hostparam != NULL)
724 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
725 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
727 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
728 "application/x-rtsp-tunnelled");
729 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
730 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
731 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
732 "Sun, 9 Jan 1972 00:00:00 GMT");
733 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
735 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
736 * request from being base64 encoded */
737 conn->tunneled = FALSE;
738 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
739 gst_rtsp_message_free (msg);
740 conn->tunneled = TRUE;
743 gst_rtsp_message_unset (&response);
752 GST_ERROR ("failed to create request (%d)", res);
757 GST_ERROR ("write failed (%d)", res);
758 gst_rtsp_message_free (msg);
759 conn->tunneled = TRUE;
764 GST_ERROR ("read failed (%d)", res);
765 conn->manual_http = FALSE;
770 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
771 response.type_data.response.reason);
772 res = GST_RTSP_ERROR;
777 GST_ERROR ("could not resolve %s", conn->ip);
783 GST_ERROR ("failed to connect");
789 * gst_rtsp_connection_connect:
790 * @conn: a #GstRTSPConnection
791 * @timeout: a #GTimeVal timeout
793 * Attempt to connect to the url of @conn made with
794 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
795 * forever. If @timeout contains a valid timeout, this function will return
796 * #GST_RTSP_ETIMEOUT after the timeout expired.
798 * This function can be cancelled with gst_rtsp_connection_flush().
800 * Returns: #GST_RTSP_OK when a connection could be made.
803 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
810 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
811 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
812 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
816 if (conn->proxy_host && conn->tunneled) {
817 if (!(ip = do_resolve (conn->proxy_host))) {
818 GST_ERROR ("could not resolve %s", conn->proxy_host);
821 port = conn->proxy_port;
822 g_free (conn->proxy_host);
823 conn->proxy_host = ip;
825 if (!(ip = do_resolve (url->host))) {
826 GST_ERROR ("could not resolve %s", url->host);
829 /* get the port from the url */
830 gst_rtsp_url_get_port (url, &port);
836 /* connect to the host/port */
837 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
838 if (res != GST_RTSP_OK)
841 /* this is our read URL */
842 conn->readfd = &conn->fd0;
844 if (conn->tunneled) {
845 res = setup_tunneling (conn, timeout);
846 if (res != GST_RTSP_OK)
847 goto tunneling_failed;
849 conn->writefd = &conn->fd0;
856 return GST_RTSP_ENET;
860 GST_ERROR ("failed to connect");
865 GST_ERROR ("failed to setup tunneling");
871 auth_digest_compute_hex_urp (const gchar * username,
872 const gchar * realm, const gchar * password, gchar hex_urp[33])
874 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
875 const gchar *digest_string;
877 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
878 g_checksum_update (md5_context, (const guchar *) ":", 1);
879 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
880 g_checksum_update (md5_context, (const guchar *) ":", 1);
881 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
882 digest_string = g_checksum_get_string (md5_context);
884 memset (hex_urp, 0, 33);
885 memcpy (hex_urp, digest_string, strlen (digest_string));
887 g_checksum_free (md5_context);
891 auth_digest_compute_response (const gchar * method,
892 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
895 char hex_a2[33] = { 0, };
896 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
897 const gchar *digest_string;
900 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
901 g_checksum_update (md5_context, (const guchar *) ":", 1);
902 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
903 digest_string = g_checksum_get_string (md5_context);
904 memcpy (hex_a2, digest_string, strlen (digest_string));
907 #if GLIB_CHECK_VERSION (2, 18, 0)
908 g_checksum_reset (md5_context);
910 g_checksum_free (md5_context);
911 md5_context = g_checksum_new (G_CHECKSUM_MD5);
913 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
914 g_checksum_update (md5_context, (const guchar *) ":", 1);
915 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
916 g_checksum_update (md5_context, (const guchar *) ":", 1);
918 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
919 digest_string = g_checksum_get_string (md5_context);
920 memset (response, 0, 33);
921 memcpy (response, digest_string, strlen (digest_string));
923 g_checksum_free (md5_context);
927 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
929 switch (conn->auth_method) {
930 case GST_RTSP_AUTH_BASIC:{
935 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
936 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
937 auth_string = g_strdup_printf ("Basic %s", user_pass64);
939 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
943 g_free (user_pass64);
946 case GST_RTSP_AUTH_DIGEST:{
947 gchar response[33], hex_urp[33];
948 gchar *auth_string, *auth_string2;
955 /* we need to have some params set */
956 if (conn->auth_params == NULL)
959 /* we need the realm and nonce */
960 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
961 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
962 if (realm == NULL || nonce == NULL)
965 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
968 method = gst_rtsp_method_as_text (message->type_data.request.method);
969 uri = message->type_data.request.uri;
971 /* Assume no qop, algorithm=md5, stale=false */
972 /* For algorithm MD5, a1 = urp. */
973 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
974 auth_string = g_strdup_printf ("Digest username=\"%s\", "
975 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
976 conn->username, realm, nonce, uri, response);
978 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
980 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
982 g_free (auth_string);
983 auth_string = auth_string2;
985 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
996 gen_date_string (gchar * date_string, guint len)
1000 #ifdef HAVE_GMTIME_R
1004 g_get_current_time (&tv);
1005 t = (time_t) tv.tv_sec;
1007 #ifdef HAVE_GMTIME_R
1008 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1010 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1014 static GstRTSPResult
1015 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1019 if (G_UNLIKELY (*idx > size))
1020 return GST_RTSP_ERROR;
1027 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1028 if (G_UNLIKELY (r == 0)) {
1029 return GST_RTSP_EINTR;
1030 } else if (G_UNLIKELY (r < 0)) {
1031 if (ERRNO_IS_EAGAIN)
1032 return GST_RTSP_EINTR;
1033 if (!ERRNO_IS_EINTR)
1034 return GST_RTSP_ESYS;
1044 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1048 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1049 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1051 out = MIN (left, size);
1052 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1054 if (left == (gsize) out) {
1055 g_free (conn->initial_buffer);
1056 conn->initial_buffer = NULL;
1057 conn->initial_buffer_offset = 0;
1059 conn->initial_buffer_offset += out;
1062 if (G_LIKELY (size > (guint) out)) {
1065 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1077 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1079 DecodeCtx *ctx = conn->ctxp;
1084 guint8 in[sizeof (ctx->out) * 4 / 3];
1087 while (size > 0 && ctx->cout < ctx->coutl) {
1088 /* we have some leftover bytes */
1089 *buffer++ = ctx->out[ctx->cout++];
1094 /* got what we needed? */
1098 /* try to read more bytes */
1099 r = fill_raw_bytes (conn, in, sizeof (in));
1108 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1112 out = fill_raw_bytes (conn, buffer, size);
1118 static GstRTSPResult
1119 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1123 if (G_UNLIKELY (*idx > size))
1124 return GST_RTSP_ERROR;
1131 r = fill_bytes (conn, &buffer[*idx], left);
1132 if (G_UNLIKELY (r == 0)) {
1133 return GST_RTSP_EEOF;
1134 } else if (G_UNLIKELY (r < 0)) {
1135 if (ERRNO_IS_EAGAIN)
1136 return GST_RTSP_EINTR;
1137 if (!ERRNO_IS_EINTR)
1138 return GST_RTSP_ESYS;
1147 static GstRTSPResult
1148 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1154 r = fill_bytes (conn, &c, 1);
1155 if (G_UNLIKELY (r == 0)) {
1156 return GST_RTSP_EEOF;
1157 } else if (G_UNLIKELY (r < 0)) {
1158 if (ERRNO_IS_EAGAIN)
1159 return GST_RTSP_EINTR;
1160 if (!ERRNO_IS_EINTR)
1161 return GST_RTSP_ESYS;
1163 if (c == '\n') /* end on \n */
1165 if (c == '\r') /* ignore \r */
1168 if (G_LIKELY (*idx < size - 1))
1169 buffer[(*idx)++] = c;
1172 buffer[*idx] = '\0';
1178 * gst_rtsp_connection_write:
1179 * @conn: a #GstRTSPConnection
1180 * @data: the data to write
1181 * @size: the size of @data
1182 * @timeout: a timeout value or #NULL
1184 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1185 * the specified @timeout. @timeout can be #NULL, in which case this function
1186 * might block forever.
1188 * This function can be cancelled with gst_rtsp_connection_flush().
1190 * Returns: #GST_RTSP_OK on success.
1193 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1194 guint size, GTimeVal * timeout)
1201 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1202 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1203 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1205 gst_poll_set_controllable (conn->fdset, TRUE);
1206 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1207 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1208 /* clear all previous poll results */
1209 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1210 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1212 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1218 res = write_bytes (conn->writefd->fd, data, &offset, size);
1219 if (G_LIKELY (res == GST_RTSP_OK))
1221 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1224 /* not all is written, wait until we can write more */
1226 retval = gst_poll_wait (conn->fdset, to);
1227 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1229 if (G_UNLIKELY (retval == 0))
1232 if (G_UNLIKELY (retval == -1)) {
1244 return GST_RTSP_ETIMEOUT;
1248 return GST_RTSP_ESYS;
1252 return GST_RTSP_EINTR;
1261 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1263 GString *str = NULL;
1265 str = g_string_new ("");
1267 switch (message->type) {
1268 case GST_RTSP_MESSAGE_REQUEST:
1269 /* create request string, add CSeq */
1270 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1272 gst_rtsp_method_as_text (message->type_data.request.method),
1273 message->type_data.request.uri, conn->cseq++);
1274 /* add session id if we have one */
1275 if (conn->session_id[0] != '\0') {
1276 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1277 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1280 /* add any authentication headers */
1281 add_auth_header (conn, message);
1283 case GST_RTSP_MESSAGE_RESPONSE:
1284 /* create response string */
1285 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1286 message->type_data.response.code, message->type_data.response.reason);
1288 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1289 /* create request string */
1290 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1291 gst_rtsp_method_as_text (message->type_data.request.method),
1292 message->type_data.request.uri,
1293 gst_rtsp_version_as_text (message->type_data.request.version));
1294 /* add any authentication headers */
1295 add_auth_header (conn, message);
1297 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1298 /* create response string */
1299 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1300 gst_rtsp_version_as_text (message->type_data.request.version),
1301 message->type_data.response.code, message->type_data.response.reason);
1303 case GST_RTSP_MESSAGE_DATA:
1305 guint8 data_header[4];
1307 /* prepare data header */
1308 data_header[0] = '$';
1309 data_header[1] = message->type_data.data.channel;
1310 data_header[2] = (message->body_size >> 8) & 0xff;
1311 data_header[3] = message->body_size & 0xff;
1313 /* create string with header and data */
1314 str = g_string_append_len (str, (gchar *) data_header, 4);
1316 g_string_append_len (str, (gchar *) message->body,
1317 message->body_size);
1321 g_string_free (str, TRUE);
1322 g_return_val_if_reached (NULL);
1326 /* append headers and body */
1327 if (message->type != GST_RTSP_MESSAGE_DATA) {
1328 gchar date_string[100];
1330 gen_date_string (date_string, sizeof (date_string));
1332 /* add date header */
1333 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1334 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1336 /* append headers */
1337 gst_rtsp_message_append_headers (message, str);
1339 /* append Content-Length and body if needed */
1340 if (message->body != NULL && message->body_size > 0) {
1343 len = g_strdup_printf ("%d", message->body_size);
1344 g_string_append_printf (str, "%s: %s\r\n",
1345 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1347 /* header ends here */
1348 g_string_append (str, "\r\n");
1350 g_string_append_len (str, (gchar *) message->body,
1351 message->body_size);
1353 /* just end headers */
1354 g_string_append (str, "\r\n");
1362 * gst_rtsp_connection_send:
1363 * @conn: a #GstRTSPConnection
1364 * @message: the message to send
1365 * @timeout: a timeout value or #NULL
1367 * Attempt to send @message to the connected @conn, blocking up to
1368 * the specified @timeout. @timeout can be #NULL, in which case this function
1369 * might block forever.
1371 * This function can be cancelled with gst_rtsp_connection_flush().
1373 * Returns: #GST_RTSP_OK on success.
1376 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1379 GString *string = NULL;
1384 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1385 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1387 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1390 if (conn->tunneled) {
1391 str = g_base64_encode ((const guchar *) string->str, string->len);
1392 g_string_free (string, TRUE);
1397 g_string_free (string, FALSE);
1401 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1409 g_warning ("Wrong message");
1410 return GST_RTSP_EINVAL;
1414 static GstRTSPResult
1415 parse_string (gchar * dest, gint size, gchar ** src)
1417 GstRTSPResult res = GST_RTSP_OK;
1422 while (g_ascii_isspace (**src))
1425 while (!g_ascii_isspace (**src) && **src != '\0') {
1427 dest[idx++] = **src;
1429 res = GST_RTSP_EPARSE;
1438 static GstRTSPResult
1439 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1440 GstRTSPVersion * version)
1442 GstRTSPResult res = GST_RTSP_OK;
1445 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1452 /* the version number must be formatted as X.Y with nothing following */
1453 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1454 res = GST_RTSP_EPARSE;
1456 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1457 if (major != 1 || minor != 0) {
1458 *version = GST_RTSP_VERSION_INVALID;
1459 res = GST_RTSP_ERROR;
1461 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1462 if (*type == GST_RTSP_MESSAGE_REQUEST)
1463 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1464 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1465 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1467 if (major == 1 && minor == 1) {
1468 *version = GST_RTSP_VERSION_1_1;
1469 } else if (major != 1 || minor != 0) {
1470 *version = GST_RTSP_VERSION_INVALID;
1471 res = GST_RTSP_ERROR;
1474 res = GST_RTSP_EPARSE;
1476 res = GST_RTSP_EPARSE;
1481 static GstRTSPResult
1482 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1484 GstRTSPResult res = GST_RTSP_OK;
1486 gchar versionstr[20];
1491 bptr = (gchar *) buffer;
1493 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1494 res = GST_RTSP_EPARSE;
1496 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1497 res = GST_RTSP_EPARSE;
1498 code = atoi (codestr);
1499 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1500 res = GST_RTSP_EPARSE;
1502 while (g_ascii_isspace (*bptr))
1505 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1506 NULL) != GST_RTSP_OK))
1507 res = GST_RTSP_EPARSE;
1509 res2 = parse_protocol_version (versionstr, &msg->type,
1510 &msg->type_data.response.version);
1511 if (G_LIKELY (res == GST_RTSP_OK))
1517 static GstRTSPResult
1518 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1520 GstRTSPResult res = GST_RTSP_OK;
1522 gchar versionstr[20];
1523 gchar methodstr[20];
1526 GstRTSPMethod method;
1528 bptr = (gchar *) buffer;
1530 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1531 res = GST_RTSP_EPARSE;
1532 method = gst_rtsp_find_method (methodstr);
1534 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1535 res = GST_RTSP_EPARSE;
1536 if (G_UNLIKELY (*urlstr == '\0'))
1537 res = GST_RTSP_EPARSE;
1539 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1540 res = GST_RTSP_EPARSE;
1542 if (G_UNLIKELY (*bptr != '\0'))
1543 res = GST_RTSP_EPARSE;
1545 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1546 urlstr) != GST_RTSP_OK))
1547 res = GST_RTSP_EPARSE;
1549 res2 = parse_protocol_version (versionstr, &msg->type,
1550 &msg->type_data.request.version);
1551 if (G_LIKELY (res == GST_RTSP_OK))
1554 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1555 /* GET and POST are not allowed as RTSP methods */
1556 if (msg->type_data.request.method == GST_RTSP_GET ||
1557 msg->type_data.request.method == GST_RTSP_POST) {
1558 msg->type_data.request.method = GST_RTSP_INVALID;
1559 if (res == GST_RTSP_OK)
1560 res = GST_RTSP_ERROR;
1562 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1563 /* only GET and POST are allowed as HTTP methods */
1564 if (msg->type_data.request.method != GST_RTSP_GET &&
1565 msg->type_data.request.method != GST_RTSP_POST) {
1566 msg->type_data.request.method = GST_RTSP_INVALID;
1567 if (res == GST_RTSP_OK)
1568 res = GST_RTSP_ERROR;
1575 /* parsing lines means reading a Key: Value pair */
1576 static GstRTSPResult
1577 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1579 GstRTSPHeaderField field;
1580 gchar *line = (gchar *) buffer;
1583 if ((value = strchr (line, ':')) == NULL || value == line)
1586 /* trim space before the colon */
1587 if (value[-1] == ' ')
1590 /* replace the colon with a NUL */
1593 /* find the header */
1594 field = gst_rtsp_find_header_field (line);
1595 if (field == GST_RTSP_HDR_INVALID)
1598 /* split up the value in multiple key:value pairs if it contains comma(s) */
1599 while (*value != '\0') {
1601 gchar *comma = NULL;
1602 gboolean quoted = FALSE;
1605 /* trim leading space */
1609 /* find the next value, taking special care of quotes and comments */
1611 while (*next_value != '\0') {
1612 if ((quoted || comment != 0) && *next_value == '\\' &&
1613 next_value[1] != '\0')
1615 else if (comment == 0 && *next_value == '"')
1617 else if (!quoted && *next_value == '(')
1619 else if (comment != 0 && *next_value == ')')
1621 else if (!quoted && comment == 0) {
1622 /* To quote RFC 2068: "User agents MUST take special care in parsing
1623 * the WWW-Authenticate field value if it contains more than one
1624 * challenge, or if more than one WWW-Authenticate header field is
1625 * provided, since the contents of a challenge may itself contain a
1626 * comma-separated list of authentication parameters."
1628 * What this means is that we cannot just look for an unquoted comma
1629 * when looking for multiple values in Proxy-Authenticate and
1630 * WWW-Authenticate headers. Instead we need to look for the sequence
1631 * "comma [space] token space token" before we can split after the
1634 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1635 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1636 if (*next_value == ',') {
1637 if (next_value[1] == ' ') {
1638 /* skip any space following the comma so we do not mistake it for
1639 * separating between two tokens */
1643 } else if (*next_value == ' ' && next_value[1] != ',' &&
1644 next_value[1] != '=' && comma != NULL) {
1649 } else if (*next_value == ',')
1657 if (value != next_value && next_value[-1] == ' ')
1658 next_value[-1] = '\0';
1660 if (*next_value != '\0')
1661 *next_value++ = '\0';
1663 /* add the key:value pair */
1665 gst_rtsp_message_add_header (msg, field, value);
1676 return GST_RTSP_EPARSE;
1680 /* convert all consecutive whitespace to a single space */
1682 normalize_line (guint8 * buffer)
1685 if (g_ascii_isspace (*buffer)) {
1689 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1692 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1700 * GST_RTSP_OK when a complete message was read.
1701 * GST_RTSP_EEOF: when the socket is closed
1702 * GST_RTSP_EINTR: when more data is needed.
1703 * GST_RTSP_..: some other error occured.
1705 static GstRTSPResult
1706 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1707 GstRTSPConnection * conn)
1712 switch (builder->state) {
1714 builder->offset = 0;
1716 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1717 if (res != GST_RTSP_OK)
1720 /* we have 1 bytes now and we can see if this is a data message or
1722 if (builder->buffer[0] == '$') {
1723 /* data message, prepare for the header */
1724 builder->state = STATE_DATA_HEADER;
1727 builder->state = STATE_READ_LINES;
1730 case STATE_DATA_HEADER:
1733 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1734 if (res != GST_RTSP_OK)
1737 gst_rtsp_message_init_data (message, builder->buffer[1]);
1739 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1740 builder->body_data = g_malloc (builder->body_len + 1);
1741 builder->body_data[builder->body_len] = '\0';
1742 builder->offset = 0;
1743 builder->state = STATE_DATA_BODY;
1746 case STATE_DATA_BODY:
1749 read_bytes (conn, builder->body_data, &builder->offset,
1751 if (res != GST_RTSP_OK)
1754 /* we have the complete body now, store in the message adjusting the
1755 * length to include the traling '\0' */
1756 gst_rtsp_message_take_body (message,
1757 (guint8 *) builder->body_data, builder->body_len + 1);
1758 builder->body_data = NULL;
1759 builder->body_len = 0;
1761 builder->state = STATE_END;
1764 case STATE_READ_LINES:
1766 res = read_line (conn, builder->buffer, &builder->offset,
1767 sizeof (builder->buffer));
1768 if (res != GST_RTSP_OK)
1771 /* we have a regular response */
1772 if (builder->buffer[0] == '\r') {
1773 builder->buffer[0] = '\0';
1776 if (builder->buffer[0] == '\0') {
1779 /* empty line, end of message header */
1780 /* see if there is a Content-Length header, but ignore it if this
1781 * is a POST request with an x-sessioncookie header */
1782 if (gst_rtsp_message_get_header (message,
1783 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1784 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1785 message->type_data.request.method != GST_RTSP_POST ||
1786 gst_rtsp_message_get_header (message,
1787 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1788 /* there is, prepare to read the body */
1789 builder->body_len = atol (hdrval);
1790 builder->body_data = g_malloc (builder->body_len + 1);
1791 builder->body_data[builder->body_len] = '\0';
1792 builder->offset = 0;
1793 builder->state = STATE_DATA_BODY;
1795 builder->state = STATE_END;
1800 /* we have a line */
1801 normalize_line (builder->buffer);
1802 if (builder->line == 0) {
1803 /* first line, check for response status */
1804 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1805 memcmp (builder->buffer, "HTTP", 4) == 0) {
1806 builder->status = parse_response_status (builder->buffer, message);
1808 builder->status = parse_request_line (builder->buffer, message);
1811 /* else just parse the line */
1812 res = parse_line (builder->buffer, message);
1813 if (res != GST_RTSP_OK)
1814 builder->status = res;
1817 builder->offset = 0;
1822 gchar *session_cookie;
1825 if (message->type == GST_RTSP_MESSAGE_DATA) {
1826 /* data messages don't have headers */
1831 /* save the tunnel session in the connection */
1832 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1833 !conn->manual_http &&
1834 conn->tstate == TUNNEL_STATE_NONE &&
1835 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1836 &session_cookie, 0) == GST_RTSP_OK) {
1837 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1838 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1839 conn->tunneled = TRUE;
1842 /* save session id in the connection for further use */
1843 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1844 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1845 &session_id, 0) == GST_RTSP_OK) {
1848 maxlen = sizeof (conn->session_id) - 1;
1849 /* the sessionid can have attributes marked with ;
1850 * Make sure we strip them */
1851 for (i = 0; session_id[i] != '\0'; i++) {
1852 if (session_id[i] == ';') {
1857 } while (g_ascii_isspace (session_id[i]));
1858 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1861 /* if we parsed something valid, configure */
1862 if ((to = atoi (&session_id[i + 8])) > 0)
1869 /* make sure to not overflow */
1870 strncpy (conn->session_id, session_id, maxlen);
1871 conn->session_id[maxlen] = '\0';
1873 res = builder->status;
1877 res = GST_RTSP_ERROR;
1886 * gst_rtsp_connection_read:
1887 * @conn: a #GstRTSPConnection
1888 * @data: the data to read
1889 * @size: the size of @data
1890 * @timeout: a timeout value or #NULL
1892 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1893 * the specified @timeout. @timeout can be #NULL, in which case this function
1894 * might block forever.
1896 * This function can be cancelled with gst_rtsp_connection_flush().
1898 * Returns: #GST_RTSP_OK on success.
1901 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1909 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1910 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1911 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1913 if (G_UNLIKELY (size == 0))
1918 /* configure timeout if any */
1919 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1921 gst_poll_set_controllable (conn->fdset, TRUE);
1922 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1923 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1926 res = read_bytes (conn, data, &offset, size);
1927 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1929 if (G_LIKELY (res == GST_RTSP_OK))
1931 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1935 retval = gst_poll_wait (conn->fdset, to);
1936 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1938 /* check for timeout */
1939 if (G_UNLIKELY (retval == 0))
1940 goto select_timeout;
1942 if (G_UNLIKELY (retval == -1)) {
1948 gst_poll_set_controllable (conn->fdset, FALSE);
1955 return GST_RTSP_ESYS;
1959 return GST_RTSP_ETIMEOUT;
1963 return GST_RTSP_EINTR;
1967 return GST_RTSP_EEOF;
1975 static GstRTSPMessage *
1976 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
1977 const GstRTSPMessage * request)
1979 GstRTSPMessage *msg;
1982 if (gst_rtsp_status_as_text (code) == NULL)
1983 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1985 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
1988 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
1989 "GStreamer RTSP Server");
1990 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
1991 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
1992 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
1994 if (code == GST_RTSP_STS_OK) {
1996 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
1998 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
1999 "application/x-rtsp-tunnelled");
2012 * gst_rtsp_connection_receive:
2013 * @conn: a #GstRTSPConnection
2014 * @message: the message to read
2015 * @timeout: a timeout value or #NULL
2017 * Attempt to read into @message from the connected @conn, blocking up to
2018 * the specified @timeout. @timeout can be #NULL, in which case this function
2019 * might block forever.
2021 * This function can be cancelled with gst_rtsp_connection_flush().
2023 * Returns: #GST_RTSP_OK on success.
2026 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2030 GstRTSPBuilder builder;
2034 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2035 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2036 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2038 /* configure timeout if any */
2039 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2041 gst_poll_set_controllable (conn->fdset, TRUE);
2042 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2043 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2045 memset (&builder, 0, sizeof (GstRTSPBuilder));
2047 res = build_next (&builder, message, conn);
2048 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2050 else if (G_LIKELY (res == GST_RTSP_OK)) {
2051 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2052 if (conn->tstate == TUNNEL_STATE_NONE &&
2053 message->type_data.request.method == GST_RTSP_GET) {
2054 GstRTSPMessage *response;
2056 conn->tstate = TUNNEL_STATE_GET;
2058 /* tunnel GET request, we can reply now */
2059 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2060 res = gst_rtsp_connection_send (conn, response, timeout);
2061 gst_rtsp_message_free (response);
2062 if (res == GST_RTSP_OK)
2063 res = GST_RTSP_ETGET;
2065 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2066 message->type_data.request.method == GST_RTSP_POST) {
2067 conn->tstate = TUNNEL_STATE_POST;
2069 /* tunnel POST request, the caller now has to link the two
2071 res = GST_RTSP_ETPOST;
2074 res = GST_RTSP_EPARSE;
2080 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2084 retval = gst_poll_wait (conn->fdset, to);
2085 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2087 /* check for timeout */
2088 if (G_UNLIKELY (retval == 0))
2089 goto select_timeout;
2091 if (G_UNLIKELY (retval == -1)) {
2097 gst_poll_set_controllable (conn->fdset, FALSE);
2100 /* we have a message here */
2101 build_reset (&builder);
2108 res = GST_RTSP_ESYS;
2113 res = GST_RTSP_ETIMEOUT;
2118 res = GST_RTSP_EINTR;
2123 res = GST_RTSP_EEOF;
2129 build_reset (&builder);
2130 gst_rtsp_message_unset (message);
2136 * gst_rtsp_connection_close:
2137 * @conn: a #GstRTSPConnection
2139 * Close the connected @conn. After this call, the connection is in the same
2140 * state as when it was first created.
2142 * Returns: #GST_RTSP_OK on success.
2145 gst_rtsp_connection_close (GstRTSPConnection * conn)
2147 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2152 g_free (conn->initial_buffer);
2153 conn->initial_buffer = NULL;
2154 conn->initial_buffer_offset = 0;
2156 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2157 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2158 conn->writefd = NULL;
2159 conn->readfd = NULL;
2160 conn->tunneled = FALSE;
2161 conn->tstate = TUNNEL_STATE_NONE;
2163 g_free (conn->username);
2164 conn->username = NULL;
2165 g_free (conn->passwd);
2166 conn->passwd = NULL;
2167 gst_rtsp_connection_clear_auth_params (conn);
2170 conn->session_id[0] = '\0';
2176 * gst_rtsp_connection_free:
2177 * @conn: a #GstRTSPConnection
2179 * Close and free @conn.
2181 * Returns: #GST_RTSP_OK on success.
2184 gst_rtsp_connection_free (GstRTSPConnection * conn)
2188 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2190 res = gst_rtsp_connection_close (conn);
2191 gst_poll_free (conn->fdset);
2192 g_timer_destroy (conn->timer);
2193 gst_rtsp_url_free (conn->url);
2194 g_free (conn->proxy_host);
2204 * gst_rtsp_connection_poll:
2205 * @conn: a #GstRTSPConnection
2206 * @events: a bitmask of #GstRTSPEvent flags to check
2207 * @revents: location for result flags
2208 * @timeout: a timeout
2210 * Wait up to the specified @timeout for the connection to become available for
2211 * at least one of the operations specified in @events. When the function returns
2212 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2215 * @timeout can be #NULL, in which case this function might block forever.
2217 * This function can be cancelled with gst_rtsp_connection_flush().
2219 * Returns: #GST_RTSP_OK on success.
2224 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2225 GstRTSPEvent * revents, GTimeVal * timeout)
2230 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2231 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2232 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2233 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2234 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2236 gst_poll_set_controllable (conn->fdset, TRUE);
2238 /* add fd to writer set when asked to */
2239 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2240 events & GST_RTSP_EV_WRITE);
2242 /* add fd to reader set when asked to */
2243 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2245 /* configure timeout if any */
2246 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2249 retval = gst_poll_wait (conn->fdset, to);
2250 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2252 if (G_UNLIKELY (retval == 0))
2253 goto select_timeout;
2255 if (G_UNLIKELY (retval == -1)) {
2263 if (events & GST_RTSP_EV_READ) {
2264 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2265 *revents |= GST_RTSP_EV_READ;
2267 if (events & GST_RTSP_EV_WRITE) {
2268 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2269 *revents |= GST_RTSP_EV_WRITE;
2276 return GST_RTSP_ETIMEOUT;
2280 return GST_RTSP_ESYS;
2284 return GST_RTSP_EINTR;
2289 * gst_rtsp_connection_next_timeout:
2290 * @conn: a #GstRTSPConnection
2291 * @timeout: a timeout
2293 * Calculate the next timeout for @conn, storing the result in @timeout.
2295 * Returns: #GST_RTSP_OK.
2298 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2304 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2305 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2307 elapsed = g_timer_elapsed (conn->timer, &usec);
2308 if (elapsed >= conn->timeout) {
2312 sec = conn->timeout - elapsed;
2315 timeout->tv_sec = sec;
2316 timeout->tv_usec = usec;
2322 * gst_rtsp_connection_reset_timeout:
2323 * @conn: a #GstRTSPConnection
2325 * Reset the timeout of @conn.
2327 * Returns: #GST_RTSP_OK.
2330 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2332 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2334 g_timer_start (conn->timer);
2340 * gst_rtsp_connection_flush:
2341 * @conn: a #GstRTSPConnection
2342 * @flush: start or stop the flush
2344 * Start or stop the flushing action on @conn. When flushing, all current
2345 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2346 * is set to non-flushing mode again.
2348 * Returns: #GST_RTSP_OK.
2351 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2353 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2355 gst_poll_set_flushing (conn->fdset, flush);
2361 * gst_rtsp_connection_set_proxy:
2362 * @conn: a #GstRTSPConnection
2363 * @host: the proxy host
2364 * @port: the proxy port
2366 * Set the proxy host and port.
2368 * Returns: #GST_RTSP_OK.
2373 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2374 const gchar * host, guint port)
2376 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2378 g_free (conn->proxy_host);
2379 conn->proxy_host = g_strdup (host);
2380 conn->proxy_port = port;
2386 * gst_rtsp_connection_set_auth:
2387 * @conn: a #GstRTSPConnection
2388 * @method: authentication method
2390 * @pass: the password
2392 * Configure @conn for authentication mode @method with @user and @pass as the
2393 * user and password respectively.
2395 * Returns: #GST_RTSP_OK.
2398 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2399 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2401 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2403 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2404 || g_strrstr (user, ":") != NULL))
2405 return GST_RTSP_EINVAL;
2407 /* Make sure the username and passwd are being set for authentication */
2408 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2409 return GST_RTSP_EINVAL;
2411 /* ":" chars are not allowed in usernames for basic auth */
2412 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2413 return GST_RTSP_EINVAL;
2415 g_free (conn->username);
2416 g_free (conn->passwd);
2418 conn->auth_method = method;
2419 conn->username = g_strdup (user);
2420 conn->passwd = g_strdup (pass);
2427 * @key: ASCII string to hash
2429 * Hashes @key in a case-insensitive manner.
2431 * Returns: the hash code.
2434 str_case_hash (gconstpointer key)
2436 const char *p = key;
2437 guint h = g_ascii_toupper (*p);
2440 for (p += 1; *p != '\0'; p++)
2441 h = (h << 5) - h + g_ascii_toupper (*p);
2448 * @v1: an ASCII string
2449 * @v2: another ASCII string
2451 * Compares @v1 and @v2 in a case-insensitive manner
2453 * Returns: %TRUE if they are equal (modulo case)
2456 str_case_equal (gconstpointer v1, gconstpointer v2)
2458 const char *string1 = v1;
2459 const char *string2 = v2;
2461 return g_ascii_strcasecmp (string1, string2) == 0;
2465 * gst_rtsp_connection_set_auth_param:
2466 * @conn: a #GstRTSPConnection
2467 * @param: authentication directive
2470 * Setup @conn with authentication directives. This is not necesary for
2471 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2472 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2473 * in the WWW-Authenticate response header and can include realm, domain,
2474 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2479 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2480 const gchar * param, const gchar * value)
2482 g_return_if_fail (conn != NULL);
2483 g_return_if_fail (param != NULL);
2485 if (conn->auth_params == NULL) {
2487 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2489 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2493 * gst_rtsp_connection_clear_auth_params:
2494 * @conn: a #GstRTSPConnection
2496 * Clear the list of authentication directives stored in @conn.
2501 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2503 g_return_if_fail (conn != NULL);
2505 if (conn->auth_params != NULL) {
2506 g_hash_table_destroy (conn->auth_params);
2507 conn->auth_params = NULL;
2511 static GstRTSPResult
2512 set_qos_dscp (gint fd, guint qos_dscp)
2514 union gst_sockaddr sa;
2515 socklen_t slen = sizeof (sa);
2522 if (getsockname (fd, &sa.sa, &slen) < 0)
2523 goto no_getsockname;
2525 af = sa.sa.sa_family;
2527 /* if this is an IPv4-mapped address then do IPv4 QoS */
2528 if (af == AF_INET6) {
2529 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2533 /* extract and shift 6 bits of the DSCP */
2534 tos = (qos_dscp & 0x3f) << 2;
2538 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2543 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2557 return GST_RTSP_ESYS;
2562 return GST_RTSP_ERROR;
2567 * gst_rtsp_connection_set_qos_dscp:
2568 * @conn: a #GstRTSPConnection
2569 * @qos_dscp: DSCP value
2571 * Configure @conn to use the specified DSCP value.
2573 * Returns: #GST_RTSP_OK on success.
2578 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2582 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2583 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2584 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2586 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2587 if (res == GST_RTSP_OK)
2588 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2595 * gst_rtsp_connection_get_url:
2596 * @conn: a #GstRTSPConnection
2598 * Retrieve the URL of the other end of @conn.
2600 * Returns: The URL. This value remains valid until the
2601 * connection is freed.
2606 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2608 g_return_val_if_fail (conn != NULL, NULL);
2614 * gst_rtsp_connection_get_ip:
2615 * @conn: a #GstRTSPConnection
2617 * Retrieve the IP address of the other end of @conn.
2619 * Returns: The IP address as a string. this value remains valid until the
2620 * connection is closed.
2625 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2627 g_return_val_if_fail (conn != NULL, NULL);
2633 * gst_rtsp_connection_set_ip:
2634 * @conn: a #GstRTSPConnection
2635 * @ip: an ip address
2637 * Set the IP address of the server.
2642 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2644 g_return_if_fail (conn != NULL);
2647 conn->ip = g_strdup (ip);
2651 * gst_rtsp_connection_get_readfd:
2652 * @conn: a #GstRTSPConnection
2654 * Get the file descriptor for reading.
2656 * Returns: the file descriptor used for reading or -1 on error. The file
2657 * descriptor remains valid until the connection is closed.
2662 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2664 g_return_val_if_fail (conn != NULL, -1);
2665 g_return_val_if_fail (conn->readfd != NULL, -1);
2667 return conn->readfd->fd;
2671 * gst_rtsp_connection_get_writefd:
2672 * @conn: a #GstRTSPConnection
2674 * Get the file descriptor for writing.
2676 * Returns: the file descriptor used for writing or -1 on error. The file
2677 * descriptor remains valid until the connection is closed.
2682 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2684 g_return_val_if_fail (conn != NULL, -1);
2685 g_return_val_if_fail (conn->writefd != NULL, -1);
2687 return conn->writefd->fd;
2692 * gst_rtsp_connection_set_tunneled:
2693 * @conn: a #GstRTSPConnection
2694 * @tunneled: the new state
2696 * Set the HTTP tunneling state of the connection. This must be configured before
2697 * the @conn is connected.
2702 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2704 g_return_if_fail (conn != NULL);
2705 g_return_if_fail (conn->readfd == NULL);
2706 g_return_if_fail (conn->writefd == NULL);
2708 conn->tunneled = tunneled;
2712 * gst_rtsp_connection_is_tunneled:
2713 * @conn: a #GstRTSPConnection
2715 * Get the tunneling state of the connection.
2717 * Returns: if @conn is using HTTP tunneling.
2722 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2724 g_return_val_if_fail (conn != NULL, FALSE);
2726 return conn->tunneled;
2730 * gst_rtsp_connection_get_tunnelid:
2731 * @conn: a #GstRTSPConnection
2733 * Get the tunnel session id the connection.
2735 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2740 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2742 g_return_val_if_fail (conn != NULL, NULL);
2744 if (!conn->tunneled)
2747 return conn->tunnelid;
2751 * gst_rtsp_connection_do_tunnel:
2752 * @conn: a #GstRTSPConnection
2753 * @conn2: a #GstRTSPConnection
2755 * If @conn received the first tunnel connection and @conn2 received
2756 * the second tunnel connection, link the two connections together so that
2757 * @conn manages the tunneled connection.
2759 * After this call, @conn2 cannot be used anymore and must be freed with
2760 * gst_rtsp_connection_free().
2762 * Returns: return GST_RTSP_OK on success.
2767 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2768 GstRTSPConnection * conn2)
2770 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2771 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2772 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2773 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2774 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2777 /* both connections have fd0 as the read/write socket. start by taking the
2778 * socket from conn2 and set it as the socket in conn */
2779 conn->fd1 = conn2->fd0;
2781 /* clean up some of the state of conn2 */
2782 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2784 conn2->readfd = conn2->writefd = NULL;
2786 /* We make fd0 the write socket and fd1 the read socket. */
2787 conn->writefd = &conn->fd0;
2788 conn->readfd = &conn->fd1;
2790 conn->tstate = TUNNEL_STATE_COMPLETE;
2792 /* we need base64 decoding for the readfd */
2793 conn->ctx.state = 0;
2796 conn->ctx.coutl = 0;
2797 conn->ctxp = &conn->ctx;
2802 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2803 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2812 /* async functions */
2813 struct _GstRTSPWatch
2817 GstRTSPConnection *conn;
2819 GstRTSPBuilder builder;
2820 GstRTSPMessage message;
2824 gboolean write_added;
2826 /* queued message for transmission */
2828 GAsyncQueue *messages;
2834 GstRTSPWatchFuncs funcs;
2837 GDestroyNotify notify;
2841 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2843 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2845 if (watch->conn->initial_buffer != NULL)
2848 *timeout = (watch->conn->timeout * 1000);
2854 gst_rtsp_source_check (GSource * source)
2856 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2858 if (watch->readfd.revents & READ_COND)
2861 if (watch->writefd.revents & WRITE_COND)
2868 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2869 gpointer user_data G_GNUC_UNUSED)
2871 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2874 /* first read as much as we can */
2875 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2877 res = build_next (&watch->builder, &watch->message, watch->conn);
2878 if (res == GST_RTSP_EINTR)
2880 else if (G_UNLIKELY (res == GST_RTSP_EEOF))
2882 else if (G_LIKELY (res == GST_RTSP_OK)) {
2883 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2884 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2885 watch->message.type_data.request.method == GST_RTSP_GET) {
2886 GstRTSPMessage *response;
2887 GstRTSPStatusCode code;
2889 watch->conn->tstate = TUNNEL_STATE_GET;
2891 if (watch->funcs.tunnel_start)
2892 code = watch->funcs.tunnel_start (watch, watch->user_data);
2894 code = GST_RTSP_STS_OK;
2896 /* queue the response */
2897 response = gen_tunnel_reply (watch->conn, code, &watch->message);
2898 gst_rtsp_watch_queue_message (watch, response);
2899 gst_rtsp_message_free (response);
2901 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2902 watch->message.type_data.request.method == GST_RTSP_POST) {
2903 watch->conn->tstate = TUNNEL_STATE_POST;
2905 /* in the callback the connection should be tunneled with the
2907 if (watch->funcs.tunnel_complete)
2908 watch->funcs.tunnel_complete (watch, watch->user_data);
2911 res = GST_RTSP_ERROR;
2916 if (G_LIKELY (res == GST_RTSP_OK)) {
2917 if (watch->funcs.message_received)
2918 watch->funcs.message_received (watch, &watch->message,
2924 gst_rtsp_message_unset (&watch->message);
2925 build_reset (&watch->builder);
2929 if (watch->writefd.revents & WRITE_COND) {
2931 if (watch->write_data == NULL) {
2934 /* get a new message from the queue */
2935 rec = g_async_queue_try_pop (watch->messages);
2939 watch->write_off = 0;
2940 watch->write_data = rec->data;
2941 watch->write_size = rec->size;
2942 watch->write_id = rec->id;
2944 g_slice_free (GstRTSPRec, rec);
2947 res = write_bytes (watch->writefd.fd, watch->write_data,
2948 &watch->write_off, watch->write_size);
2949 if (res == GST_RTSP_EINTR)
2951 if (G_UNLIKELY (res != GST_RTSP_OK))
2954 if (watch->funcs.message_sent)
2955 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
2958 if (g_async_queue_length (watch->messages) == 0 && watch->write_added) {
2959 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2960 watch->write_added = FALSE;
2961 watch->writefd.revents = 0;
2963 g_free (watch->write_data);
2964 watch->write_data = NULL;
2973 if (watch->funcs.closed)
2974 watch->funcs.closed (watch, watch->user_data);
2979 if (watch->funcs.error)
2980 watch->funcs.error (watch, res, watch->user_data);
2986 gst_rtsp_rec_free (gpointer data)
2988 GstRTSPRec *rec = data;
2991 g_slice_free (GstRTSPRec, rec);
2995 gst_rtsp_source_finalize (GSource * source)
2997 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2999 build_reset (&watch->builder);
3000 gst_rtsp_message_unset (&watch->message);
3002 g_async_queue_unref (watch->messages);
3003 watch->messages = NULL;
3005 g_free (watch->write_data);
3008 watch->notify (watch->user_data);
3011 static GSourceFuncs gst_rtsp_source_funcs = {
3012 gst_rtsp_source_prepare,
3013 gst_rtsp_source_check,
3014 gst_rtsp_source_dispatch,
3015 gst_rtsp_source_finalize,
3021 * gst_rtsp_watch_new:
3022 * @conn: a #GstRTSPConnection
3023 * @funcs: watch functions
3024 * @user_data: user data to pass to @funcs
3025 * @notify: notify when @user_data is not referenced anymore
3027 * Create a watch object for @conn. The functions provided in @funcs will be
3028 * called with @user_data when activity happened on the watch.
3030 * The new watch is usually created so that it can be attached to a
3031 * maincontext with gst_rtsp_watch_attach().
3033 * @conn must exist for the entire lifetime of the watch.
3035 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3036 * communication. Free with gst_rtsp_watch_unref () after usage.
3041 gst_rtsp_watch_new (GstRTSPConnection * conn,
3042 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3044 GstRTSPWatch *result;
3046 g_return_val_if_fail (conn != NULL, NULL);
3047 g_return_val_if_fail (funcs != NULL, NULL);
3048 g_return_val_if_fail (conn->readfd != NULL, NULL);
3049 g_return_val_if_fail (conn->writefd != NULL, NULL);
3051 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3052 sizeof (GstRTSPWatch));
3054 result->conn = conn;
3055 result->builder.state = STATE_START;
3057 result->messages = g_async_queue_new_full (gst_rtsp_rec_free);
3059 result->readfd.fd = -1;
3060 result->writefd.fd = -1;
3062 gst_rtsp_watch_reset (result);
3064 result->funcs = *funcs;
3065 result->user_data = user_data;
3066 result->notify = notify;
3068 /* only add the read fd, the write fd is only added when we have data
3070 g_source_add_poll ((GSource *) result, &result->readfd);
3076 * gst_rtsp_watch_reset:
3077 * @watch: a #GstRTSPWatch
3079 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3080 * when the file descriptors of the connection might have changed.
3085 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3087 if (watch->readfd.fd != -1)
3088 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3089 if (watch->writefd.fd != -1)
3090 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3092 watch->readfd.fd = watch->conn->readfd->fd;
3093 watch->readfd.events = READ_COND;
3094 watch->readfd.revents = 0;
3096 watch->writefd.fd = watch->conn->writefd->fd;
3097 watch->writefd.events = WRITE_COND;
3098 watch->writefd.revents = 0;
3099 watch->write_added = FALSE;
3101 g_source_add_poll ((GSource *) watch, &watch->readfd);
3105 * gst_rtsp_watch_attach:
3106 * @watch: a #GstRTSPWatch
3107 * @context: a GMainContext (if NULL, the default context will be used)
3109 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3111 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3116 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3118 g_return_val_if_fail (watch != NULL, 0);
3120 return g_source_attach ((GSource *) watch, context);
3124 * gst_rtsp_watch_unref:
3125 * @watch: a #GstRTSPWatch
3127 * Decreases the reference count of @watch by one. If the resulting reference
3128 * count is zero the watch and associated memory will be destroyed.
3133 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3135 g_return_if_fail (watch != NULL);
3137 g_source_unref ((GSource *) watch);
3141 * gst_rtsp_watch_queue_data:
3142 * @watch: a #GstRTSPWatch
3143 * @data: the data to queue
3144 * @size: the size of @data
3146 * Queue @data for transmission in @watch. It will be transmitted when the
3147 * connection of the @watch becomes writable.
3149 * This function will take ownership of @data and g_free() it after use.
3151 * The return value of this function will be used as the id argument in the
3152 * message_sent callback.
3159 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3164 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3165 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3166 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3168 /* make a record with the data and id */
3169 rec = g_slice_new (GstRTSPRec);
3170 rec->data = (guint8 *) data;
3173 /* make sure rec->id is never 0 */
3174 rec->id = ++watch->id;
3175 } while (G_UNLIKELY (rec->id == 0));
3177 /* add the record to a queue. FIXME we would like to have an upper limit here */
3178 g_async_queue_push (watch->messages, rec);
3180 /* FIXME: does the following need to be made thread-safe? (this might be
3181 * called from a streaming thread, like appsink's render function) */
3182 /* make sure the main context will now also check for writability on the
3184 if (!watch->write_added) {
3185 g_source_add_poll ((GSource *) watch, &watch->writefd);
3186 watch->write_added = TRUE;
3193 * gst_rtsp_watch_queue_message:
3194 * @watch: a #GstRTSPWatch
3195 * @message: a #GstRTSPMessage
3197 * Queue a @message for transmission in @watch. The contents of this
3198 * message will be serialized and transmitted when the connection of the
3199 * @watch becomes writable.
3201 * The return value of this function will be used as the id argument in the
3202 * message_sent callback.
3209 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3214 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3215 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3217 /* make a record with the message as a string and id */
3218 str = message_to_string (watch->conn, message);
3220 return gst_rtsp_watch_queue_data (watch,
3221 (guint8 *) g_string_free (str, FALSE), size);