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 SEND_FLAGS MSG_NOSIGNAL
124 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
125 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, SEND_FLAGS)
126 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
127 #define CLOSE_SOCKET(sock) closesocket (sock)
128 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
129 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
130 /* According to Microsoft's connect() documentation this one returns
131 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
132 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
134 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
135 #define WRITE_SOCKET(fd, buf, len) send (fd, buf, len, SEND_FLAGS)
136 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
137 #define CLOSE_SOCKET(sock) close (sock)
138 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
139 #define ERRNO_IS_EINTR (errno == EINTR)
140 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
143 #define ADD_POLLFD(fdset, pfd, fd) \
146 gst_poll_add_fd (fdset, pfd); \
149 #define REMOVE_POLLFD(fdset, pfd) \
151 if ((pfd)->fd != -1) { \
152 GST_DEBUG ("remove fd %d", (pfd)->fd); \
153 gst_poll_remove_fd (fdset, pfd); \
154 CLOSE_SOCKET ((pfd)->fd); \
164 TUNNEL_STATE_COMPLETE
165 } GstRTSPTunnelState;
167 #define TUNNELID_LEN 24
169 struct _GstRTSPConnection
172 /* URL for the connection */
175 /* connection state */
182 gboolean manual_http;
184 gchar tunnelid[TUNNELID_LEN];
186 GstRTSPTunnelState tstate;
193 gchar *initial_buffer;
194 gsize initial_buffer_offset;
197 gint cseq; /* sequence number */
198 gchar session_id[512]; /* session id */
199 gint timeout; /* session timeout in seconds */
200 GTimer *timer; /* timeout timer */
203 GstRTSPAuthMethod auth_method;
206 GHashTable *auth_params;
227 READ_AHEAD_EOH = -1, /* end of headers */
228 READ_AHEAD_CRLF = -2,
229 READ_AHEAD_CRLFCR = -3
232 /* a structure for constructing RTSPMessages */
236 GstRTSPResult status;
246 build_reset (GstRTSPBuilder * builder)
248 g_free (builder->body_data);
249 memset (builder, 0, sizeof (GstRTSPBuilder));
253 * gst_rtsp_connection_create:
254 * @url: a #GstRTSPUrl
255 * @conn: storage for a #GstRTSPConnection
257 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
258 * The connection will not yet attempt to connect to @url, use
259 * gst_rtsp_connection_connect().
261 * A copy of @url will be made.
263 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
266 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
268 GstRTSPConnection *newconn;
274 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
277 error = WSAStartup (0x0202, &w);
282 if (w.wVersion != 0x0202)
286 newconn = g_new0 (GstRTSPConnection, 1);
288 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
291 newconn->url = gst_rtsp_url_copy (url);
292 newconn->fd0.fd = -1;
293 newconn->fd1.fd = -1;
294 newconn->timer = g_timer_new ();
295 newconn->timeout = 60;
298 newconn->auth_method = GST_RTSP_AUTH_NONE;
299 newconn->username = NULL;
300 newconn->passwd = NULL;
301 newconn->auth_params = NULL;
311 g_warning ("Error %d on WSAStartup", error);
312 return GST_RTSP_EWSASTART;
316 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
319 return GST_RTSP_EWSAVERSION;
328 return GST_RTSP_ESYS;
333 * gst_rtsp_connection_create_from_fd:
334 * @fd: a file descriptor
335 * @ip: the IP address of the other end
336 * @port: the port used by the other end
337 * @initial_buffer: data already read from @fd
338 * @conn: storage for a #GstRTSPConnection
340 * Create a new #GstRTSPConnection for handling communication on the existing
341 * file descriptor @fd. The @initial_buffer contains any data already read from
342 * @fd which should be used before starting to read new data.
344 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
349 gst_rtsp_connection_create_from_fd (gint fd, const gchar * ip, guint16 port,
350 const gchar * initial_buffer, GstRTSPConnection ** conn)
352 GstRTSPConnection *newconn = NULL;
359 g_return_val_if_fail (fd >= 0, GST_RTSP_EINVAL);
360 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
361 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
363 /* set to non-blocking mode so that we can cancel the communication */
365 fcntl (fd, F_SETFL, O_NONBLOCK);
367 ioctlsocket (fd, FIONBIO, &flags);
368 #endif /* G_OS_WIN32 */
370 /* create a url for the client address */
371 url = g_new0 (GstRTSPUrl, 1);
372 url->host = g_strdup (ip);
375 /* now create the connection object */
376 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
377 gst_rtsp_url_free (url);
379 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
381 /* both read and write initially */
382 newconn->readfd = &newconn->fd0;
383 newconn->writefd = &newconn->fd0;
385 newconn->ip = g_strdup (ip);
387 newconn->initial_buffer = g_strdup (initial_buffer);
396 gst_rtsp_url_free (url);
402 * gst_rtsp_connection_accept:
404 * @conn: storage for a #GstRTSPConnection
406 * Accept a new connection on @sock and create a new #GstRTSPConnection for
407 * handling communication on new socket.
409 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
414 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
417 union gst_sockaddr sa;
418 socklen_t slen = sizeof (sa);
419 gchar ip[INET6_ADDRSTRLEN];
422 g_return_val_if_fail (sock >= 0, GST_RTSP_EINVAL);
423 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
425 memset (&sa, 0, slen);
428 fd = accept (sock, &sa.sa, &slen);
430 fd = accept (sock, &sa.sa, (gint *) & slen);
431 #endif /* G_OS_WIN32 */
435 if (getnameinfo (&sa.sa, slen, ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) != 0)
436 goto getnameinfo_failed;
438 if (sa.sa.sa_family == AF_INET)
439 port = sa.sa_in.sin_port;
440 else if (sa.sa.sa_family == AF_INET6)
441 port = sa.sa_in6.sin6_port;
445 return gst_rtsp_connection_create_from_fd (fd, ip, port, NULL, conn);
450 return GST_RTSP_ESYS;
456 return GST_RTSP_ERROR;
461 do_resolve (const gchar * host)
463 static gchar ip[INET6_ADDRSTRLEN];
464 struct addrinfo *aires;
468 aierr = getaddrinfo (host, NULL, NULL, &aires);
472 for (ai = aires; ai; ai = ai->ai_next) {
473 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
480 aierr = getnameinfo (ai->ai_addr, ai->ai_addrlen, ip, sizeof (ip), NULL, 0,
481 NI_NUMERICHOST | NI_NUMERICSERV);
485 freeaddrinfo (aires);
487 return g_strdup (ip);
492 GST_ERROR ("no addrinfo found for %s: %s", host, gai_strerror (aierr));
497 GST_ERROR ("no family found for %s", host);
498 freeaddrinfo (aires);
503 GST_ERROR ("no address found for %s: %s", host, gai_strerror (aierr));
504 freeaddrinfo (aires);
510 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
511 GstPoll * fdset, GTimeVal * timeout)
514 struct addrinfo hints;
515 struct addrinfo *aires;
518 gchar service[NI_MAXSERV];
521 unsigned long flags = 1;
522 #endif /* G_OS_WIN32 */
526 memset (&hints, 0, sizeof hints);
527 hints.ai_flags = AI_NUMERICHOST;
528 hints.ai_family = AF_UNSPEC;
529 hints.ai_socktype = SOCK_STREAM;
530 g_snprintf (service, sizeof (service) - 1, "%hu", port);
531 service[sizeof (service) - 1] = '\0';
533 aierr = getaddrinfo (ip, service, &hints, &aires);
537 for (ai = aires; ai; ai = ai->ai_next) {
538 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
545 fd = socket (ai->ai_family, SOCK_STREAM, 0);
549 /* set to non-blocking mode so that we can cancel the connect */
551 fcntl (fd, F_SETFL, O_NONBLOCK);
553 ioctlsocket (fd, FIONBIO, &flags);
554 #endif /* G_OS_WIN32 */
556 /* add the socket to our fdset */
557 ADD_POLLFD (fdset, fdout, fd);
559 /* we are going to connect ASYNC now */
560 ret = connect (fd, ai->ai_addr, ai->ai_addrlen);
563 if (!ERRNO_IS_EINPROGRESS)
566 /* wait for connect to complete up to the specified timeout or until we got
568 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
570 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
573 retval = gst_poll_wait (fdset, to);
574 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
578 else if (retval == -1)
581 /* we can still have an error connecting on windows */
582 if (gst_poll_fd_has_error (fdset, fdout)) {
583 socklen_t len = sizeof (errno);
585 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
587 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
592 gst_poll_fd_ignored (fdset, fdout);
595 freeaddrinfo (aires);
602 GST_ERROR ("no addrinfo found for %s: %s", ip, gai_strerror (aierr));
603 return GST_RTSP_ERROR;
607 GST_ERROR ("no family found for %s", ip);
608 freeaddrinfo (aires);
609 return GST_RTSP_ERROR;
613 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
614 freeaddrinfo (aires);
615 return GST_RTSP_ESYS;
619 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
620 REMOVE_POLLFD (fdset, fdout);
621 freeaddrinfo (aires);
622 return GST_RTSP_ESYS;
626 GST_ERROR ("timeout");
627 REMOVE_POLLFD (fdset, fdout);
628 freeaddrinfo (aires);
629 return GST_RTSP_ETIMEOUT;
634 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
641 guint16 port, url_port;
645 GstRTSPMessage response;
648 memset (&response, 0, sizeof (response));
649 gst_rtsp_message_init (&response);
651 /* create a random sessionid */
652 for (i = 0; i < TUNNELID_LEN; i++)
653 conn->tunnelid[i] = g_random_int_range ('a', 'z');
654 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
657 /* get the port from the url */
658 gst_rtsp_url_get_port (url, &url_port);
660 if (conn->proxy_host) {
661 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
662 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
663 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
664 ip = conn->proxy_host;
665 port = conn->proxy_port;
667 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
668 url->query ? url->query : "");
674 /* create the GET request for the read connection */
675 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
677 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
679 if (hostparam != NULL)
680 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
681 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
683 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
684 "application/x-rtsp-tunnelled");
685 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
686 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
688 /* we start by writing to this fd */
689 conn->writefd = &conn->fd0;
691 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
692 * request from being base64 encoded */
693 conn->tunneled = FALSE;
694 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
695 gst_rtsp_message_free (msg);
696 conn->tunneled = TRUE;
698 /* receive the response to the GET request */
699 /* we need to temporarily set manual_http to TRUE since
700 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
701 * failure otherwise */
702 old_http = conn->manual_http;
703 conn->manual_http = TRUE;
704 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
706 conn->manual_http = old_http;
708 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
709 response.type_data.response.code != GST_RTSP_STS_OK)
712 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
713 &value, 0) != GST_RTSP_OK) {
714 if (conn->proxy_host) {
715 /* if we use a proxy we need to change the destination url */
717 url->host = g_strdup (value);
719 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
721 /* and resolve the new ip address */
722 if (!(ip = do_resolve (conn->ip)))
729 /* connect to the host/port */
730 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
731 if (res != GST_RTSP_OK)
734 /* this is now our writing socket */
735 conn->writefd = &conn->fd1;
737 /* create the POST request for the write connection */
738 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
740 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
742 if (hostparam != NULL)
743 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
744 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
746 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
747 "application/x-rtsp-tunnelled");
748 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
749 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
750 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
751 "Sun, 9 Jan 1972 00:00:00 GMT");
752 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
754 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
755 * request from being base64 encoded */
756 conn->tunneled = FALSE;
757 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
758 gst_rtsp_message_free (msg);
759 conn->tunneled = TRUE;
762 gst_rtsp_message_unset (&response);
771 GST_ERROR ("failed to create request (%d)", res);
776 GST_ERROR ("write failed (%d)", res);
777 gst_rtsp_message_free (msg);
778 conn->tunneled = TRUE;
783 GST_ERROR ("read failed (%d)", res);
784 conn->manual_http = FALSE;
789 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
790 response.type_data.response.reason);
791 res = GST_RTSP_ERROR;
796 GST_ERROR ("could not resolve %s", conn->ip);
802 GST_ERROR ("failed to connect");
808 * gst_rtsp_connection_connect:
809 * @conn: a #GstRTSPConnection
810 * @timeout: a #GTimeVal timeout
812 * Attempt to connect to the url of @conn made with
813 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
814 * forever. If @timeout contains a valid timeout, this function will return
815 * #GST_RTSP_ETIMEOUT after the timeout expired.
817 * This function can be cancelled with gst_rtsp_connection_flush().
819 * Returns: #GST_RTSP_OK when a connection could be made.
822 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
829 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
830 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
831 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
835 if (conn->proxy_host && conn->tunneled) {
836 if (!(ip = do_resolve (conn->proxy_host))) {
837 GST_ERROR ("could not resolve %s", conn->proxy_host);
840 port = conn->proxy_port;
841 g_free (conn->proxy_host);
842 conn->proxy_host = ip;
844 if (!(ip = do_resolve (url->host))) {
845 GST_ERROR ("could not resolve %s", url->host);
848 /* get the port from the url */
849 gst_rtsp_url_get_port (url, &port);
855 /* connect to the host/port */
856 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
857 if (res != GST_RTSP_OK)
860 /* this is our read URL */
861 conn->readfd = &conn->fd0;
863 if (conn->tunneled) {
864 res = setup_tunneling (conn, timeout);
865 if (res != GST_RTSP_OK)
866 goto tunneling_failed;
868 conn->writefd = &conn->fd0;
875 return GST_RTSP_ENET;
879 GST_ERROR ("failed to connect");
884 GST_ERROR ("failed to setup tunneling");
890 auth_digest_compute_hex_urp (const gchar * username,
891 const gchar * realm, const gchar * password, gchar hex_urp[33])
893 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
894 const gchar *digest_string;
896 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
897 g_checksum_update (md5_context, (const guchar *) ":", 1);
898 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
899 g_checksum_update (md5_context, (const guchar *) ":", 1);
900 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
901 digest_string = g_checksum_get_string (md5_context);
903 memset (hex_urp, 0, 33);
904 memcpy (hex_urp, digest_string, strlen (digest_string));
906 g_checksum_free (md5_context);
910 auth_digest_compute_response (const gchar * method,
911 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
914 char hex_a2[33] = { 0, };
915 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
916 const gchar *digest_string;
919 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
920 g_checksum_update (md5_context, (const guchar *) ":", 1);
921 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
922 digest_string = g_checksum_get_string (md5_context);
923 memcpy (hex_a2, digest_string, strlen (digest_string));
926 g_checksum_reset (md5_context);
927 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
928 g_checksum_update (md5_context, (const guchar *) ":", 1);
929 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
930 g_checksum_update (md5_context, (const guchar *) ":", 1);
932 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
933 digest_string = g_checksum_get_string (md5_context);
934 memset (response, 0, 33);
935 memcpy (response, digest_string, strlen (digest_string));
937 g_checksum_free (md5_context);
941 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
943 switch (conn->auth_method) {
944 case GST_RTSP_AUTH_BASIC:{
949 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
950 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
951 auth_string = g_strdup_printf ("Basic %s", user_pass64);
953 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
957 g_free (user_pass64);
960 case GST_RTSP_AUTH_DIGEST:{
961 gchar response[33], hex_urp[33];
962 gchar *auth_string, *auth_string2;
969 /* we need to have some params set */
970 if (conn->auth_params == NULL)
973 /* we need the realm and nonce */
974 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
975 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
976 if (realm == NULL || nonce == NULL)
979 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
982 method = gst_rtsp_method_as_text (message->type_data.request.method);
983 uri = message->type_data.request.uri;
985 /* Assume no qop, algorithm=md5, stale=false */
986 /* For algorithm MD5, a1 = urp. */
987 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
988 auth_string = g_strdup_printf ("Digest username=\"%s\", "
989 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
990 conn->username, realm, nonce, uri, response);
992 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
994 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
996 g_free (auth_string);
997 auth_string = auth_string2;
999 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1010 gen_date_string (gchar * date_string, guint len)
1014 #ifdef HAVE_GMTIME_R
1018 g_get_current_time (&tv);
1019 t = (time_t) tv.tv_sec;
1021 #ifdef HAVE_GMTIME_R
1022 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1024 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1028 static GstRTSPResult
1029 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1033 if (G_UNLIKELY (*idx > size))
1034 return GST_RTSP_ERROR;
1041 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1042 if (G_UNLIKELY (r == 0)) {
1043 return GST_RTSP_EINTR;
1044 } else if (G_UNLIKELY (r < 0)) {
1045 if (ERRNO_IS_EAGAIN)
1046 return GST_RTSP_EINTR;
1047 if (!ERRNO_IS_EINTR)
1048 return GST_RTSP_ESYS;
1058 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1062 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1063 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1065 out = MIN (left, size);
1066 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1068 if (left == (gsize) out) {
1069 g_free (conn->initial_buffer);
1070 conn->initial_buffer = NULL;
1071 conn->initial_buffer_offset = 0;
1073 conn->initial_buffer_offset += out;
1076 if (G_LIKELY (size > (guint) out)) {
1079 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1091 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1093 DecodeCtx *ctx = conn->ctxp;
1098 guint8 in[sizeof (ctx->out) * 4 / 3];
1101 while (size > 0 && ctx->cout < ctx->coutl) {
1102 /* we have some leftover bytes */
1103 *buffer++ = ctx->out[ctx->cout++];
1108 /* got what we needed? */
1112 /* try to read more bytes */
1113 r = fill_raw_bytes (conn, in, sizeof (in));
1122 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1126 out = fill_raw_bytes (conn, buffer, size);
1132 static GstRTSPResult
1133 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1137 if (G_UNLIKELY (*idx > size))
1138 return GST_RTSP_ERROR;
1145 r = fill_bytes (conn, &buffer[*idx], left);
1146 if (G_UNLIKELY (r == 0)) {
1147 return GST_RTSP_EEOF;
1148 } else if (G_UNLIKELY (r < 0)) {
1149 if (ERRNO_IS_EAGAIN)
1150 return GST_RTSP_EINTR;
1151 if (!ERRNO_IS_EINTR)
1152 return GST_RTSP_ESYS;
1161 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1162 * end of a line. It even does its best to handle clients which mix them (even
1163 * though this is a really stupid idea (tm).) It also handles Line White Space
1164 * (LWS), where a line end followed by whitespace is considered LWS. This is
1165 * the method used in RTSP (and HTTP) to break long lines.
1167 static GstRTSPResult
1168 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1174 if (conn->read_ahead == READ_AHEAD_EOH) {
1175 /* the last call to read_line() already determined that we have reached
1176 * the end of the headers, so convey that information now */
1177 conn->read_ahead = 0;
1179 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1180 /* the last call to read_line() left off after having read \r\n */
1182 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1183 /* the last call to read_line() left off after having read \r\n\r */
1185 } else if (conn->read_ahead != 0) {
1186 /* the last call to read_line() left us with a character to start with */
1187 c = (guint8) conn->read_ahead;
1188 conn->read_ahead = 0;
1190 /* read the next character */
1191 r = fill_bytes (conn, &c, 1);
1192 if (G_UNLIKELY (r == 0)) {
1193 return GST_RTSP_EEOF;
1194 } else if (G_UNLIKELY (r < 0)) {
1195 if (ERRNO_IS_EAGAIN)
1196 return GST_RTSP_EINTR;
1197 if (!ERRNO_IS_EINTR)
1198 return GST_RTSP_ESYS;
1203 /* special treatment of line endings */
1204 if (c == '\r' || c == '\n') {
1208 /* need to read ahead one more character to know what to do... */
1209 r = fill_bytes (conn, &read_ahead, 1);
1210 if (G_UNLIKELY (r == 0)) {
1211 return GST_RTSP_EEOF;
1212 } else if (G_UNLIKELY (r < 0)) {
1213 if (ERRNO_IS_EAGAIN) {
1214 /* remember the original character we read and try again next time */
1215 if (conn->read_ahead == 0)
1216 conn->read_ahead = c;
1217 return GST_RTSP_EINTR;
1219 if (!ERRNO_IS_EINTR)
1220 return GST_RTSP_ESYS;
1224 if (read_ahead == ' ' || read_ahead == '\t') {
1225 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1226 /* got \r\n\r followed by whitespace, treat it as a normal line
1227 * followed by one starting with LWS */
1228 conn->read_ahead = read_ahead;
1231 /* got LWS, change the line ending to a space and continue */
1233 conn->read_ahead = read_ahead;
1235 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1236 if (read_ahead == '\r' || read_ahead == '\n') {
1237 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1238 conn->read_ahead = READ_AHEAD_EOH;
1241 /* got \r\n\r followed by something else, this is not really
1242 * supported since we have probably just eaten the first character
1243 * of the body or the next message, so just ignore the second \r
1244 * and live with it... */
1245 conn->read_ahead = read_ahead;
1248 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1249 if (read_ahead == '\r') {
1250 /* got \r\n\r so far, need one more character... */
1251 conn->read_ahead = READ_AHEAD_CRLFCR;
1253 } else if (read_ahead == '\n') {
1254 /* got \r\n\n, treat it as the end of the headers */
1255 conn->read_ahead = READ_AHEAD_EOH;
1258 /* found the end of a line, keep read_ahead for the next line */
1259 conn->read_ahead = read_ahead;
1262 } else if (c == read_ahead) {
1263 /* got double \r or \n, treat it as the end of the headers */
1264 conn->read_ahead = READ_AHEAD_EOH;
1266 } else if (c == '\r' && read_ahead == '\n') {
1267 /* got \r\n so far, still need more to know what to do... */
1268 conn->read_ahead = READ_AHEAD_CRLF;
1271 /* found the end of a line, keep read_ahead for the next line */
1272 conn->read_ahead = read_ahead;
1277 if (G_LIKELY (*idx < size - 1))
1278 buffer[(*idx)++] = c;
1280 buffer[*idx] = '\0';
1286 * gst_rtsp_connection_write:
1287 * @conn: a #GstRTSPConnection
1288 * @data: the data to write
1289 * @size: the size of @data
1290 * @timeout: a timeout value or #NULL
1292 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1293 * the specified @timeout. @timeout can be #NULL, in which case this function
1294 * might block forever.
1296 * This function can be cancelled with gst_rtsp_connection_flush().
1298 * Returns: #GST_RTSP_OK on success.
1301 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1302 guint size, GTimeVal * timeout)
1309 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1310 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1311 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1313 gst_poll_set_controllable (conn->fdset, TRUE);
1314 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1315 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1316 /* clear all previous poll results */
1317 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1318 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1320 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1326 res = write_bytes (conn->writefd->fd, data, &offset, size);
1327 if (G_LIKELY (res == GST_RTSP_OK))
1329 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1332 /* not all is written, wait until we can write more */
1334 retval = gst_poll_wait (conn->fdset, to);
1335 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1337 if (G_UNLIKELY (retval == 0))
1340 if (G_UNLIKELY (retval == -1)) {
1347 /* could also be an error with read socket */
1348 if (gst_poll_fd_has_error (conn->fdset, conn->readfd))
1356 return GST_RTSP_ETIMEOUT;
1360 return GST_RTSP_ESYS;
1364 return GST_RTSP_EINTR;
1368 return GST_RTSP_ENET;
1377 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1379 GString *str = NULL;
1381 str = g_string_new ("");
1383 switch (message->type) {
1384 case GST_RTSP_MESSAGE_REQUEST:
1385 /* create request string, add CSeq */
1386 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1388 gst_rtsp_method_as_text (message->type_data.request.method),
1389 message->type_data.request.uri, conn->cseq++);
1390 /* add session id if we have one */
1391 if (conn->session_id[0] != '\0') {
1392 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1393 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1396 /* add any authentication headers */
1397 add_auth_header (conn, message);
1399 case GST_RTSP_MESSAGE_RESPONSE:
1400 /* create response string */
1401 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1402 message->type_data.response.code, message->type_data.response.reason);
1404 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1405 /* create request string */
1406 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1407 gst_rtsp_method_as_text (message->type_data.request.method),
1408 message->type_data.request.uri,
1409 gst_rtsp_version_as_text (message->type_data.request.version));
1410 /* add any authentication headers */
1411 add_auth_header (conn, message);
1413 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1414 /* create response string */
1415 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1416 gst_rtsp_version_as_text (message->type_data.request.version),
1417 message->type_data.response.code, message->type_data.response.reason);
1419 case GST_RTSP_MESSAGE_DATA:
1421 guint8 data_header[4];
1423 /* prepare data header */
1424 data_header[0] = '$';
1425 data_header[1] = message->type_data.data.channel;
1426 data_header[2] = (message->body_size >> 8) & 0xff;
1427 data_header[3] = message->body_size & 0xff;
1429 /* create string with header and data */
1430 str = g_string_append_len (str, (gchar *) data_header, 4);
1432 g_string_append_len (str, (gchar *) message->body,
1433 message->body_size);
1437 g_string_free (str, TRUE);
1438 g_return_val_if_reached (NULL);
1442 /* append headers and body */
1443 if (message->type != GST_RTSP_MESSAGE_DATA) {
1444 gchar date_string[100];
1446 gen_date_string (date_string, sizeof (date_string));
1448 /* add date header */
1449 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1450 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1452 /* append headers */
1453 gst_rtsp_message_append_headers (message, str);
1455 /* append Content-Length and body if needed */
1456 if (message->body != NULL && message->body_size > 0) {
1459 len = g_strdup_printf ("%d", message->body_size);
1460 g_string_append_printf (str, "%s: %s\r\n",
1461 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1463 /* header ends here */
1464 g_string_append (str, "\r\n");
1466 g_string_append_len (str, (gchar *) message->body,
1467 message->body_size);
1469 /* just end headers */
1470 g_string_append (str, "\r\n");
1478 * gst_rtsp_connection_send:
1479 * @conn: a #GstRTSPConnection
1480 * @message: the message to send
1481 * @timeout: a timeout value or #NULL
1483 * Attempt to send @message to the connected @conn, blocking up to
1484 * the specified @timeout. @timeout can be #NULL, in which case this function
1485 * might block forever.
1487 * This function can be cancelled with gst_rtsp_connection_flush().
1489 * Returns: #GST_RTSP_OK on success.
1492 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1495 GString *string = NULL;
1500 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1501 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1503 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1506 if (conn->tunneled) {
1507 str = g_base64_encode ((const guchar *) string->str, string->len);
1508 g_string_free (string, TRUE);
1513 g_string_free (string, FALSE);
1517 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1525 g_warning ("Wrong message");
1526 return GST_RTSP_EINVAL;
1530 static GstRTSPResult
1531 parse_string (gchar * dest, gint size, gchar ** src)
1533 GstRTSPResult res = GST_RTSP_OK;
1538 while (g_ascii_isspace (**src))
1541 while (!g_ascii_isspace (**src) && **src != '\0') {
1543 dest[idx++] = **src;
1545 res = GST_RTSP_EPARSE;
1554 static GstRTSPResult
1555 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1556 GstRTSPVersion * version)
1558 GstRTSPResult res = GST_RTSP_OK;
1561 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1568 /* the version number must be formatted as X.Y with nothing following */
1569 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1570 res = GST_RTSP_EPARSE;
1572 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1573 if (major != 1 || minor != 0) {
1574 *version = GST_RTSP_VERSION_INVALID;
1575 res = GST_RTSP_ERROR;
1577 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1578 if (*type == GST_RTSP_MESSAGE_REQUEST)
1579 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1580 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1581 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1583 if (major == 1 && minor == 1) {
1584 *version = GST_RTSP_VERSION_1_1;
1585 } else if (major != 1 || minor != 0) {
1586 *version = GST_RTSP_VERSION_INVALID;
1587 res = GST_RTSP_ERROR;
1590 res = GST_RTSP_EPARSE;
1592 res = GST_RTSP_EPARSE;
1597 static GstRTSPResult
1598 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1600 GstRTSPResult res = GST_RTSP_OK;
1602 gchar versionstr[20];
1607 bptr = (gchar *) buffer;
1609 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1610 res = GST_RTSP_EPARSE;
1612 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1613 res = GST_RTSP_EPARSE;
1614 code = atoi (codestr);
1615 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1616 res = GST_RTSP_EPARSE;
1618 while (g_ascii_isspace (*bptr))
1621 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1622 NULL) != GST_RTSP_OK))
1623 res = GST_RTSP_EPARSE;
1625 res2 = parse_protocol_version (versionstr, &msg->type,
1626 &msg->type_data.response.version);
1627 if (G_LIKELY (res == GST_RTSP_OK))
1633 static GstRTSPResult
1634 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1636 GstRTSPResult res = GST_RTSP_OK;
1638 gchar versionstr[20];
1639 gchar methodstr[20];
1642 GstRTSPMethod method;
1644 bptr = (gchar *) buffer;
1646 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1647 res = GST_RTSP_EPARSE;
1648 method = gst_rtsp_find_method (methodstr);
1650 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1651 res = GST_RTSP_EPARSE;
1652 if (G_UNLIKELY (*urlstr == '\0'))
1653 res = GST_RTSP_EPARSE;
1655 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1656 res = GST_RTSP_EPARSE;
1658 if (G_UNLIKELY (*bptr != '\0'))
1659 res = GST_RTSP_EPARSE;
1661 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1662 urlstr) != GST_RTSP_OK))
1663 res = GST_RTSP_EPARSE;
1665 res2 = parse_protocol_version (versionstr, &msg->type,
1666 &msg->type_data.request.version);
1667 if (G_LIKELY (res == GST_RTSP_OK))
1670 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1671 /* GET and POST are not allowed as RTSP methods */
1672 if (msg->type_data.request.method == GST_RTSP_GET ||
1673 msg->type_data.request.method == GST_RTSP_POST) {
1674 msg->type_data.request.method = GST_RTSP_INVALID;
1675 if (res == GST_RTSP_OK)
1676 res = GST_RTSP_ERROR;
1678 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1679 /* only GET and POST are allowed as HTTP methods */
1680 if (msg->type_data.request.method != GST_RTSP_GET &&
1681 msg->type_data.request.method != GST_RTSP_POST) {
1682 msg->type_data.request.method = GST_RTSP_INVALID;
1683 if (res == GST_RTSP_OK)
1684 res = GST_RTSP_ERROR;
1691 /* parsing lines means reading a Key: Value pair */
1692 static GstRTSPResult
1693 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1695 GstRTSPHeaderField field;
1696 gchar *line = (gchar *) buffer;
1699 if ((value = strchr (line, ':')) == NULL || value == line)
1702 /* trim space before the colon */
1703 if (value[-1] == ' ')
1706 /* replace the colon with a NUL */
1709 /* find the header */
1710 field = gst_rtsp_find_header_field (line);
1711 if (field == GST_RTSP_HDR_INVALID)
1714 /* split up the value in multiple key:value pairs if it contains comma(s) */
1715 while (*value != '\0') {
1717 gchar *comma = NULL;
1718 gboolean quoted = FALSE;
1721 /* trim leading space */
1725 /* for headers which may not appear multiple times, and thus may not
1726 * contain multiple values on the same line, we can short-circuit the loop
1727 * below and the entire value results in just one key:value pair*/
1728 if (!gst_rtsp_header_allow_multiple (field))
1729 next_value = value + strlen (value);
1733 /* find the next value, taking special care of quotes and comments */
1734 while (*next_value != '\0') {
1735 if ((quoted || comment != 0) && *next_value == '\\' &&
1736 next_value[1] != '\0')
1738 else if (comment == 0 && *next_value == '"')
1740 else if (!quoted && *next_value == '(')
1742 else if (comment != 0 && *next_value == ')')
1744 else if (!quoted && comment == 0) {
1745 /* To quote RFC 2068: "User agents MUST take special care in parsing
1746 * the WWW-Authenticate field value if it contains more than one
1747 * challenge, or if more than one WWW-Authenticate header field is
1748 * provided, since the contents of a challenge may itself contain a
1749 * comma-separated list of authentication parameters."
1751 * What this means is that we cannot just look for an unquoted comma
1752 * when looking for multiple values in Proxy-Authenticate and
1753 * WWW-Authenticate headers. Instead we need to look for the sequence
1754 * "comma [space] token space token" before we can split after the
1757 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1758 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1759 if (*next_value == ',') {
1760 if (next_value[1] == ' ') {
1761 /* skip any space following the comma so we do not mistake it for
1762 * separating between two tokens */
1766 } else if (*next_value == ' ' && next_value[1] != ',' &&
1767 next_value[1] != '=' && comma != NULL) {
1772 } else if (*next_value == ',')
1780 if (value != next_value && next_value[-1] == ' ')
1781 next_value[-1] = '\0';
1783 if (*next_value != '\0')
1784 *next_value++ = '\0';
1786 /* add the key:value pair */
1788 gst_rtsp_message_add_header (msg, field, value);
1799 return GST_RTSP_EPARSE;
1803 /* convert all consecutive whitespace to a single space */
1805 normalize_line (guint8 * buffer)
1808 if (g_ascii_isspace (*buffer)) {
1812 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1815 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1823 * GST_RTSP_OK when a complete message was read.
1824 * GST_RTSP_EEOF: when the socket is closed
1825 * GST_RTSP_EINTR: when more data is needed.
1826 * GST_RTSP_..: some other error occured.
1828 static GstRTSPResult
1829 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1830 GstRTSPConnection * conn)
1835 switch (builder->state) {
1840 builder->offset = 0;
1842 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1843 if (res != GST_RTSP_OK)
1846 c = builder->buffer[0];
1848 /* we have 1 bytes now and we can see if this is a data message or
1851 /* data message, prepare for the header */
1852 builder->state = STATE_DATA_HEADER;
1853 } else if (c == '\n' || c == '\r') {
1854 /* skip \n and \r */
1855 builder->offset = 0;
1858 builder->state = STATE_READ_LINES;
1862 case STATE_DATA_HEADER:
1865 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1866 if (res != GST_RTSP_OK)
1869 gst_rtsp_message_init_data (message, builder->buffer[1]);
1871 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1872 builder->body_data = g_malloc (builder->body_len + 1);
1873 builder->body_data[builder->body_len] = '\0';
1874 builder->offset = 0;
1875 builder->state = STATE_DATA_BODY;
1878 case STATE_DATA_BODY:
1881 read_bytes (conn, builder->body_data, &builder->offset,
1883 if (res != GST_RTSP_OK)
1886 /* we have the complete body now, store in the message adjusting the
1887 * length to include the traling '\0' */
1888 gst_rtsp_message_take_body (message,
1889 (guint8 *) builder->body_data, builder->body_len + 1);
1890 builder->body_data = NULL;
1891 builder->body_len = 0;
1893 builder->state = STATE_END;
1896 case STATE_READ_LINES:
1898 res = read_line (conn, builder->buffer, &builder->offset,
1899 sizeof (builder->buffer));
1900 if (res != GST_RTSP_OK)
1903 /* we have a regular response */
1904 if (builder->buffer[0] == '\0') {
1907 /* empty line, end of message header */
1908 /* see if there is a Content-Length header, but ignore it if this
1909 * is a POST request with an x-sessioncookie header */
1910 if (gst_rtsp_message_get_header (message,
1911 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1912 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1913 message->type_data.request.method != GST_RTSP_POST ||
1914 gst_rtsp_message_get_header (message,
1915 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1916 /* there is, prepare to read the body */
1917 builder->body_len = atol (hdrval);
1918 builder->body_data = g_try_malloc (builder->body_len + 1);
1919 /* we can't do much here, we need the length to know how many bytes
1920 * we need to read next and when allocation fails, something is
1921 * probably wrong with the length. */
1922 if (builder->body_data == NULL)
1923 goto invalid_body_len;
1925 builder->body_data[builder->body_len] = '\0';
1926 builder->offset = 0;
1927 builder->state = STATE_DATA_BODY;
1929 builder->state = STATE_END;
1934 /* we have a line */
1935 normalize_line (builder->buffer);
1936 if (builder->line == 0) {
1937 /* first line, check for response status */
1938 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1939 memcmp (builder->buffer, "HTTP", 4) == 0) {
1940 builder->status = parse_response_status (builder->buffer, message);
1942 builder->status = parse_request_line (builder->buffer, message);
1945 /* else just parse the line */
1946 res = parse_line (builder->buffer, message);
1947 if (res != GST_RTSP_OK)
1948 builder->status = res;
1951 builder->offset = 0;
1956 gchar *session_cookie;
1959 if (message->type == GST_RTSP_MESSAGE_DATA) {
1960 /* data messages don't have headers */
1965 /* save the tunnel session in the connection */
1966 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1967 !conn->manual_http &&
1968 conn->tstate == TUNNEL_STATE_NONE &&
1969 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1970 &session_cookie, 0) == GST_RTSP_OK) {
1971 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1972 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1973 conn->tunneled = TRUE;
1976 /* save session id in the connection for further use */
1977 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1978 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1979 &session_id, 0) == GST_RTSP_OK) {
1982 maxlen = sizeof (conn->session_id) - 1;
1983 /* the sessionid can have attributes marked with ;
1984 * Make sure we strip them */
1985 for (i = 0; session_id[i] != '\0'; i++) {
1986 if (session_id[i] == ';') {
1991 } while (g_ascii_isspace (session_id[i]));
1992 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1995 /* if we parsed something valid, configure */
1996 if ((to = atoi (&session_id[i + 8])) > 0)
2003 /* make sure to not overflow */
2004 strncpy (conn->session_id, session_id, maxlen);
2005 conn->session_id[maxlen] = '\0';
2007 res = builder->status;
2011 res = GST_RTSP_ERROR;
2021 GST_DEBUG ("could not allocate body");
2022 return GST_RTSP_ERROR;
2027 * gst_rtsp_connection_read:
2028 * @conn: a #GstRTSPConnection
2029 * @data: the data to read
2030 * @size: the size of @data
2031 * @timeout: a timeout value or #NULL
2033 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
2034 * the specified @timeout. @timeout can be #NULL, in which case this function
2035 * might block forever.
2037 * This function can be cancelled with gst_rtsp_connection_flush().
2039 * Returns: #GST_RTSP_OK on success.
2042 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
2050 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2051 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
2052 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2054 if (G_UNLIKELY (size == 0))
2059 /* configure timeout if any */
2060 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2062 gst_poll_set_controllable (conn->fdset, TRUE);
2063 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2064 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2067 res = read_bytes (conn, data, &offset, size);
2068 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2070 if (G_LIKELY (res == GST_RTSP_OK))
2072 if (G_UNLIKELY (res != GST_RTSP_EINTR))
2076 retval = gst_poll_wait (conn->fdset, to);
2077 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2079 /* check for timeout */
2080 if (G_UNLIKELY (retval == 0))
2081 goto select_timeout;
2083 if (G_UNLIKELY (retval == -1)) {
2090 /* could also be an error with write socket */
2091 if (gst_poll_fd_has_error (conn->fdset, conn->writefd))
2094 gst_poll_set_controllable (conn->fdset, FALSE);
2101 return GST_RTSP_ESYS;
2105 return GST_RTSP_ETIMEOUT;
2109 return GST_RTSP_EINTR;
2113 return GST_RTSP_EEOF;
2117 res = GST_RTSP_ENET;
2125 static GstRTSPMessage *
2126 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
2127 const GstRTSPMessage * request)
2129 GstRTSPMessage *msg;
2132 if (gst_rtsp_status_as_text (code) == NULL)
2133 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
2135 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
2138 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
2139 "GStreamer RTSP Server");
2140 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2141 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2142 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2144 if (code == GST_RTSP_STS_OK) {
2146 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2148 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2149 "application/x-rtsp-tunnelled");
2162 * gst_rtsp_connection_receive:
2163 * @conn: a #GstRTSPConnection
2164 * @message: the message to read
2165 * @timeout: a timeout value or #NULL
2167 * Attempt to read into @message from the connected @conn, blocking up to
2168 * the specified @timeout. @timeout can be #NULL, in which case this function
2169 * might block forever.
2171 * This function can be cancelled with gst_rtsp_connection_flush().
2173 * Returns: #GST_RTSP_OK on success.
2176 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2180 GstRTSPBuilder builder;
2184 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2185 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2186 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2188 /* configure timeout if any */
2189 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2191 gst_poll_set_controllable (conn->fdset, TRUE);
2192 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2193 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2195 memset (&builder, 0, sizeof (GstRTSPBuilder));
2197 res = build_next (&builder, message, conn);
2198 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2200 else if (G_LIKELY (res == GST_RTSP_OK)) {
2201 if (!conn->manual_http) {
2202 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2203 if (conn->tstate == TUNNEL_STATE_NONE &&
2204 message->type_data.request.method == GST_RTSP_GET) {
2205 GstRTSPMessage *response;
2207 conn->tstate = TUNNEL_STATE_GET;
2209 /* tunnel GET request, we can reply now */
2210 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2211 res = gst_rtsp_connection_send (conn, response, timeout);
2212 gst_rtsp_message_free (response);
2213 if (res == GST_RTSP_OK)
2214 res = GST_RTSP_ETGET;
2216 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2217 message->type_data.request.method == GST_RTSP_POST) {
2218 conn->tstate = TUNNEL_STATE_POST;
2220 /* tunnel POST request, the caller now has to link the two
2222 res = GST_RTSP_ETPOST;
2225 res = GST_RTSP_EPARSE;
2228 } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2229 res = GST_RTSP_EPARSE;
2235 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2239 retval = gst_poll_wait (conn->fdset, to);
2240 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2242 /* check for timeout */
2243 if (G_UNLIKELY (retval == 0))
2244 goto select_timeout;
2246 if (G_UNLIKELY (retval == -1)) {
2253 /* could also be an error with write socket */
2254 if (gst_poll_fd_has_error (conn->fdset, conn->writefd))
2257 gst_poll_set_controllable (conn->fdset, FALSE);
2260 /* we have a message here */
2261 build_reset (&builder);
2268 res = GST_RTSP_ESYS;
2273 res = GST_RTSP_ETIMEOUT;
2278 res = GST_RTSP_EINTR;
2283 res = GST_RTSP_EEOF;
2288 res = GST_RTSP_ENET;
2294 build_reset (&builder);
2295 gst_rtsp_message_unset (message);
2301 * gst_rtsp_connection_close:
2302 * @conn: a #GstRTSPConnection
2304 * Close the connected @conn. After this call, the connection is in the same
2305 * state as when it was first created.
2307 * Returns: #GST_RTSP_OK on success.
2310 gst_rtsp_connection_close (GstRTSPConnection * conn)
2312 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2317 conn->read_ahead = 0;
2319 g_free (conn->initial_buffer);
2320 conn->initial_buffer = NULL;
2321 conn->initial_buffer_offset = 0;
2323 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2324 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2325 conn->writefd = NULL;
2326 conn->readfd = NULL;
2327 conn->tunneled = FALSE;
2328 conn->tstate = TUNNEL_STATE_NONE;
2330 g_free (conn->username);
2331 conn->username = NULL;
2332 g_free (conn->passwd);
2333 conn->passwd = NULL;
2334 gst_rtsp_connection_clear_auth_params (conn);
2337 conn->session_id[0] = '\0';
2343 * gst_rtsp_connection_free:
2344 * @conn: a #GstRTSPConnection
2346 * Close and free @conn.
2348 * Returns: #GST_RTSP_OK on success.
2351 gst_rtsp_connection_free (GstRTSPConnection * conn)
2355 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2357 res = gst_rtsp_connection_close (conn);
2358 gst_poll_free (conn->fdset);
2359 g_timer_destroy (conn->timer);
2360 gst_rtsp_url_free (conn->url);
2361 g_free (conn->proxy_host);
2371 * gst_rtsp_connection_poll:
2372 * @conn: a #GstRTSPConnection
2373 * @events: a bitmask of #GstRTSPEvent flags to check
2374 * @revents: location for result flags
2375 * @timeout: a timeout
2377 * Wait up to the specified @timeout for the connection to become available for
2378 * at least one of the operations specified in @events. When the function returns
2379 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2382 * @timeout can be #NULL, in which case this function might block forever.
2384 * This function can be cancelled with gst_rtsp_connection_flush().
2386 * Returns: #GST_RTSP_OK on success.
2391 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2392 GstRTSPEvent * revents, GTimeVal * timeout)
2397 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2398 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2399 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2400 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2401 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2403 gst_poll_set_controllable (conn->fdset, TRUE);
2405 /* add fd to writer set when asked to */
2406 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2407 events & GST_RTSP_EV_WRITE);
2409 /* add fd to reader set when asked to */
2410 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2412 /* configure timeout if any */
2413 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2416 retval = gst_poll_wait (conn->fdset, to);
2417 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2419 if (G_UNLIKELY (retval == 0))
2420 goto select_timeout;
2422 if (G_UNLIKELY (retval == -1)) {
2430 if (events & GST_RTSP_EV_READ) {
2431 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2432 *revents |= GST_RTSP_EV_READ;
2434 if (events & GST_RTSP_EV_WRITE) {
2435 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2436 *revents |= GST_RTSP_EV_WRITE;
2443 return GST_RTSP_ETIMEOUT;
2447 return GST_RTSP_ESYS;
2451 return GST_RTSP_EINTR;
2456 * gst_rtsp_connection_next_timeout:
2457 * @conn: a #GstRTSPConnection
2458 * @timeout: a timeout
2460 * Calculate the next timeout for @conn, storing the result in @timeout.
2462 * Returns: #GST_RTSP_OK.
2465 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2471 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2472 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2474 elapsed = g_timer_elapsed (conn->timer, &usec);
2475 if (elapsed >= conn->timeout) {
2479 sec = conn->timeout - elapsed;
2482 timeout->tv_sec = sec;
2483 timeout->tv_usec = usec;
2489 * gst_rtsp_connection_reset_timeout:
2490 * @conn: a #GstRTSPConnection
2492 * Reset the timeout of @conn.
2494 * Returns: #GST_RTSP_OK.
2497 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2499 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2501 g_timer_start (conn->timer);
2507 * gst_rtsp_connection_flush:
2508 * @conn: a #GstRTSPConnection
2509 * @flush: start or stop the flush
2511 * Start or stop the flushing action on @conn. When flushing, all current
2512 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2513 * is set to non-flushing mode again.
2515 * Returns: #GST_RTSP_OK.
2518 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2520 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2522 gst_poll_set_flushing (conn->fdset, flush);
2528 * gst_rtsp_connection_set_proxy:
2529 * @conn: a #GstRTSPConnection
2530 * @host: the proxy host
2531 * @port: the proxy port
2533 * Set the proxy host and port.
2535 * Returns: #GST_RTSP_OK.
2540 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2541 const gchar * host, guint port)
2543 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2545 g_free (conn->proxy_host);
2546 conn->proxy_host = g_strdup (host);
2547 conn->proxy_port = port;
2553 * gst_rtsp_connection_set_auth:
2554 * @conn: a #GstRTSPConnection
2555 * @method: authentication method
2557 * @pass: the password
2559 * Configure @conn for authentication mode @method with @user and @pass as the
2560 * user and password respectively.
2562 * Returns: #GST_RTSP_OK.
2565 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2566 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2568 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2570 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2571 || g_strrstr (user, ":") != NULL))
2572 return GST_RTSP_EINVAL;
2574 /* Make sure the username and passwd are being set for authentication */
2575 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2576 return GST_RTSP_EINVAL;
2578 /* ":" chars are not allowed in usernames for basic auth */
2579 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2580 return GST_RTSP_EINVAL;
2582 g_free (conn->username);
2583 g_free (conn->passwd);
2585 conn->auth_method = method;
2586 conn->username = g_strdup (user);
2587 conn->passwd = g_strdup (pass);
2594 * @key: ASCII string to hash
2596 * Hashes @key in a case-insensitive manner.
2598 * Returns: the hash code.
2601 str_case_hash (gconstpointer key)
2603 const char *p = key;
2604 guint h = g_ascii_toupper (*p);
2607 for (p += 1; *p != '\0'; p++)
2608 h = (h << 5) - h + g_ascii_toupper (*p);
2615 * @v1: an ASCII string
2616 * @v2: another ASCII string
2618 * Compares @v1 and @v2 in a case-insensitive manner
2620 * Returns: %TRUE if they are equal (modulo case)
2623 str_case_equal (gconstpointer v1, gconstpointer v2)
2625 const char *string1 = v1;
2626 const char *string2 = v2;
2628 return g_ascii_strcasecmp (string1, string2) == 0;
2632 * gst_rtsp_connection_set_auth_param:
2633 * @conn: a #GstRTSPConnection
2634 * @param: authentication directive
2637 * Setup @conn with authentication directives. This is not necesary for
2638 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2639 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2640 * in the WWW-Authenticate response header and can include realm, domain,
2641 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2646 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2647 const gchar * param, const gchar * value)
2649 g_return_if_fail (conn != NULL);
2650 g_return_if_fail (param != NULL);
2652 if (conn->auth_params == NULL) {
2654 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2656 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2660 * gst_rtsp_connection_clear_auth_params:
2661 * @conn: a #GstRTSPConnection
2663 * Clear the list of authentication directives stored in @conn.
2668 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2670 g_return_if_fail (conn != NULL);
2672 if (conn->auth_params != NULL) {
2673 g_hash_table_destroy (conn->auth_params);
2674 conn->auth_params = NULL;
2678 static GstRTSPResult
2679 set_qos_dscp (gint fd, guint qos_dscp)
2681 union gst_sockaddr sa;
2682 socklen_t slen = sizeof (sa);
2689 if (getsockname (fd, &sa.sa, &slen) < 0)
2690 goto no_getsockname;
2692 af = sa.sa.sa_family;
2694 /* if this is an IPv4-mapped address then do IPv4 QoS */
2695 if (af == AF_INET6) {
2696 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2700 /* extract and shift 6 bits of the DSCP */
2701 tos = (qos_dscp & 0x3f) << 2;
2705 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2710 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2724 return GST_RTSP_ESYS;
2729 return GST_RTSP_ERROR;
2734 * gst_rtsp_connection_set_qos_dscp:
2735 * @conn: a #GstRTSPConnection
2736 * @qos_dscp: DSCP value
2738 * Configure @conn to use the specified DSCP value.
2740 * Returns: #GST_RTSP_OK on success.
2745 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2749 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2750 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2751 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2753 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2754 if (res == GST_RTSP_OK)
2755 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2762 * gst_rtsp_connection_get_url:
2763 * @conn: a #GstRTSPConnection
2765 * Retrieve the URL of the other end of @conn.
2767 * Returns: The URL. This value remains valid until the
2768 * connection is freed.
2773 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2775 g_return_val_if_fail (conn != NULL, NULL);
2781 * gst_rtsp_connection_get_ip:
2782 * @conn: a #GstRTSPConnection
2784 * Retrieve the IP address of the other end of @conn.
2786 * Returns: The IP address as a string. this value remains valid until the
2787 * connection is closed.
2792 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2794 g_return_val_if_fail (conn != NULL, NULL);
2800 * gst_rtsp_connection_set_ip:
2801 * @conn: a #GstRTSPConnection
2802 * @ip: an ip address
2804 * Set the IP address of the server.
2809 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2811 g_return_if_fail (conn != NULL);
2814 conn->ip = g_strdup (ip);
2818 * gst_rtsp_connection_get_readfd:
2819 * @conn: a #GstRTSPConnection
2821 * Get the file descriptor for reading.
2823 * Returns: the file descriptor used for reading or -1 on error. The file
2824 * descriptor remains valid until the connection is closed.
2829 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2831 g_return_val_if_fail (conn != NULL, -1);
2832 g_return_val_if_fail (conn->readfd != NULL, -1);
2834 return conn->readfd->fd;
2838 * gst_rtsp_connection_get_writefd:
2839 * @conn: a #GstRTSPConnection
2841 * Get the file descriptor for writing.
2843 * Returns: the file descriptor used for writing or -1 on error. The file
2844 * descriptor remains valid until the connection is closed.
2849 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2851 g_return_val_if_fail (conn != NULL, -1);
2852 g_return_val_if_fail (conn->writefd != NULL, -1);
2854 return conn->writefd->fd;
2858 * gst_rtsp_connection_set_http_mode:
2859 * @conn: a #GstRTSPConnection
2860 * @enable: %TRUE to enable manual HTTP mode
2862 * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2863 * messages in addition to the RTSP messages. It will also disable the
2864 * automatic handling of setting up an HTTP tunnel.
2869 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2871 g_return_if_fail (conn != NULL);
2873 conn->manual_http = enable;
2877 * gst_rtsp_connection_set_tunneled:
2878 * @conn: a #GstRTSPConnection
2879 * @tunneled: the new state
2881 * Set the HTTP tunneling state of the connection. This must be configured before
2882 * the @conn is connected.
2887 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2889 g_return_if_fail (conn != NULL);
2890 g_return_if_fail (conn->readfd == NULL);
2891 g_return_if_fail (conn->writefd == NULL);
2893 conn->tunneled = tunneled;
2897 * gst_rtsp_connection_is_tunneled:
2898 * @conn: a #GstRTSPConnection
2900 * Get the tunneling state of the connection.
2902 * Returns: if @conn is using HTTP tunneling.
2907 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2909 g_return_val_if_fail (conn != NULL, FALSE);
2911 return conn->tunneled;
2915 * gst_rtsp_connection_get_tunnelid:
2916 * @conn: a #GstRTSPConnection
2918 * Get the tunnel session id the connection.
2920 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2925 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2927 g_return_val_if_fail (conn != NULL, NULL);
2929 if (!conn->tunneled)
2932 return conn->tunnelid;
2936 * gst_rtsp_connection_do_tunnel:
2937 * @conn: a #GstRTSPConnection
2938 * @conn2: a #GstRTSPConnection or %NULL
2940 * If @conn received the first tunnel connection and @conn2 received
2941 * the second tunnel connection, link the two connections together so that
2942 * @conn manages the tunneled connection.
2944 * After this call, @conn2 cannot be used anymore and must be freed with
2945 * gst_rtsp_connection_free().
2947 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2950 * Returns: return GST_RTSP_OK on success.
2955 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2956 GstRTSPConnection * conn2)
2958 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2960 if (conn2 != NULL) {
2961 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2962 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2963 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2964 TUNNELID_LEN), GST_RTSP_EINVAL);
2966 /* both connections have fd0 as the read/write socket. start by taking the
2967 * socket from conn2 and set it as the socket in conn */
2968 conn->fd1 = conn2->fd0;
2970 /* clean up some of the state of conn2 */
2971 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2973 conn2->readfd = conn2->writefd = NULL;
2975 /* We make fd0 the write socket and fd1 the read socket. */
2976 conn->writefd = &conn->fd0;
2977 conn->readfd = &conn->fd1;
2979 conn->tstate = TUNNEL_STATE_COMPLETE;
2982 /* we need base64 decoding for the readfd */
2983 conn->ctx.state = 0;
2986 conn->ctx.coutl = 0;
2987 conn->ctxp = &conn->ctx;
2992 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2993 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
3002 /* async functions */
3003 struct _GstRTSPWatch
3007 GstRTSPConnection *conn;
3009 GstRTSPBuilder builder;
3010 GstRTSPMessage message;
3014 gboolean write_added;
3016 /* queued message for transmission */
3025 GstRTSPWatchFuncs funcs;
3028 GDestroyNotify notify;
3032 gst_rtsp_source_prepare (GSource * source, gint * timeout)
3034 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3036 if (watch->conn->initial_buffer != NULL)
3039 *timeout = (watch->conn->timeout * 1000);
3045 gst_rtsp_source_check (GSource * source)
3047 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3049 if (watch->readfd.revents & READ_COND)
3052 if (watch->writefd.revents & WRITE_COND)
3059 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
3060 gpointer user_data G_GNUC_UNUSED)
3062 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3065 /* first read as much as we can */
3066 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
3068 res = build_next (&watch->builder, &watch->message, watch->conn);
3069 if (res == GST_RTSP_EINTR)
3071 else if (G_UNLIKELY (res == GST_RTSP_EEOF))
3073 else if (G_LIKELY (res == GST_RTSP_OK)) {
3074 if (!watch->conn->manual_http &&
3075 watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3076 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3077 watch->message.type_data.request.method == GST_RTSP_GET) {
3078 GstRTSPMessage *response;
3079 GstRTSPStatusCode code;
3081 watch->conn->tstate = TUNNEL_STATE_GET;
3083 if (watch->funcs.tunnel_start)
3084 code = watch->funcs.tunnel_start (watch, watch->user_data);
3086 code = GST_RTSP_STS_OK;
3088 /* queue the response */
3089 response = gen_tunnel_reply (watch->conn, code, &watch->message);
3090 gst_rtsp_watch_send_message (watch, response, NULL);
3091 gst_rtsp_message_free (response);
3093 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3094 watch->message.type_data.request.method == GST_RTSP_POST) {
3095 watch->conn->tstate = TUNNEL_STATE_POST;
3097 /* in the callback the connection should be tunneled with the
3099 if (watch->funcs.tunnel_complete)
3100 watch->funcs.tunnel_complete (watch, watch->user_data);
3106 if (!watch->conn->manual_http) {
3107 /* if manual HTTP support is not enabled, then restore the message to
3108 * what it would have looked like without the support for parsing HTTP
3109 * messages being present */
3110 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3111 watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3112 watch->message.type_data.request.method = GST_RTSP_INVALID;
3113 if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3114 watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3115 res = GST_RTSP_EPARSE;
3116 } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3117 watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3118 if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3119 watch->message.type_data.response.version =
3120 GST_RTSP_VERSION_INVALID;
3121 res = GST_RTSP_EPARSE;
3125 if (G_LIKELY (res == GST_RTSP_OK)) {
3126 if (watch->funcs.message_received)
3127 watch->funcs.message_received (watch, &watch->message,
3130 if (watch->funcs.error_full)
3131 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3132 0, watch->user_data), error);
3138 gst_rtsp_message_unset (&watch->message);
3139 build_reset (&watch->builder);
3143 if (watch->writefd.revents & WRITE_COND) {
3144 g_mutex_lock (watch->mutex);
3146 if (watch->write_data == NULL) {
3149 /* get a new message from the queue */
3150 rec = g_queue_pop_tail (watch->messages);
3154 watch->write_off = 0;
3155 watch->write_data = rec->data;
3156 watch->write_size = rec->size;
3157 watch->write_id = rec->id;
3159 g_slice_free (GstRTSPRec, rec);
3162 res = write_bytes (watch->writefd.fd, watch->write_data,
3163 &watch->write_off, watch->write_size);
3164 g_mutex_unlock (watch->mutex);
3165 if (res == GST_RTSP_EINTR)
3167 else if (G_LIKELY (res == GST_RTSP_OK)) {
3168 if (watch->funcs.message_sent)
3169 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3171 if (watch->funcs.error_full)
3172 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3173 watch->write_id, watch->user_data), error);
3177 g_mutex_lock (watch->mutex);
3179 g_free (watch->write_data);
3180 watch->write_data = NULL;
3184 if (watch->write_added) {
3185 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3186 watch->write_added = FALSE;
3187 watch->writefd.revents = 0;
3190 g_mutex_unlock (watch->mutex);
3199 if (watch->funcs.closed)
3200 watch->funcs.closed (watch, watch->user_data);
3205 if (watch->funcs.error)
3206 watch->funcs.error (watch, res, watch->user_data);
3212 gst_rtsp_rec_free (gpointer data)
3214 GstRTSPRec *rec = data;
3217 g_slice_free (GstRTSPRec, rec);
3221 gst_rtsp_source_finalize (GSource * source)
3223 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3225 build_reset (&watch->builder);
3226 gst_rtsp_message_unset (&watch->message);
3228 g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3229 g_queue_free (watch->messages);
3230 watch->messages = NULL;
3232 g_mutex_free (watch->mutex);
3234 g_free (watch->write_data);
3237 watch->notify (watch->user_data);
3240 static GSourceFuncs gst_rtsp_source_funcs = {
3241 gst_rtsp_source_prepare,
3242 gst_rtsp_source_check,
3243 gst_rtsp_source_dispatch,
3244 gst_rtsp_source_finalize,
3250 * gst_rtsp_watch_new:
3251 * @conn: a #GstRTSPConnection
3252 * @funcs: watch functions
3253 * @user_data: user data to pass to @funcs
3254 * @notify: notify when @user_data is not referenced anymore
3256 * Create a watch object for @conn. The functions provided in @funcs will be
3257 * called with @user_data when activity happened on the watch.
3259 * The new watch is usually created so that it can be attached to a
3260 * maincontext with gst_rtsp_watch_attach().
3262 * @conn must exist for the entire lifetime of the watch.
3264 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3265 * communication. Free with gst_rtsp_watch_unref () after usage.
3270 gst_rtsp_watch_new (GstRTSPConnection * conn,
3271 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3273 GstRTSPWatch *result;
3275 g_return_val_if_fail (conn != NULL, NULL);
3276 g_return_val_if_fail (funcs != NULL, NULL);
3277 g_return_val_if_fail (conn->readfd != NULL, NULL);
3278 g_return_val_if_fail (conn->writefd != NULL, NULL);
3280 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3281 sizeof (GstRTSPWatch));
3283 result->conn = conn;
3284 result->builder.state = STATE_START;
3286 result->mutex = g_mutex_new ();
3287 result->messages = g_queue_new ();
3289 result->readfd.fd = -1;
3290 result->writefd.fd = -1;
3292 gst_rtsp_watch_reset (result);
3294 result->funcs = *funcs;
3295 result->user_data = user_data;
3296 result->notify = notify;
3298 /* only add the read fd, the write fd is only added when we have data
3300 g_source_add_poll ((GSource *) result, &result->readfd);
3306 * gst_rtsp_watch_reset:
3307 * @watch: a #GstRTSPWatch
3309 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3310 * when the file descriptors of the connection might have changed.
3315 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3317 if (watch->readfd.fd != -1)
3318 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3319 if (watch->writefd.fd != -1)
3320 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3322 watch->readfd.fd = watch->conn->readfd->fd;
3323 watch->readfd.events = READ_COND;
3324 watch->readfd.revents = 0;
3326 watch->writefd.fd = watch->conn->writefd->fd;
3327 watch->writefd.events = WRITE_COND;
3328 watch->writefd.revents = 0;
3329 watch->write_added = FALSE;
3331 g_source_add_poll ((GSource *) watch, &watch->readfd);
3335 * gst_rtsp_watch_attach:
3336 * @watch: a #GstRTSPWatch
3337 * @context: a GMainContext (if NULL, the default context will be used)
3339 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3341 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3346 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3348 g_return_val_if_fail (watch != NULL, 0);
3350 return g_source_attach ((GSource *) watch, context);
3354 * gst_rtsp_watch_unref:
3355 * @watch: a #GstRTSPWatch
3357 * Decreases the reference count of @watch by one. If the resulting reference
3358 * count is zero the watch and associated memory will be destroyed.
3363 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3365 g_return_if_fail (watch != NULL);
3367 g_source_unref ((GSource *) watch);
3371 * gst_rtsp_watch_write_data:
3372 * @watch: a #GstRTSPWatch
3373 * @data: the data to queue
3374 * @size: the size of @data
3375 * @id: location for a message ID or %NULL
3377 * Write @data using the connection of the @watch. If it cannot be sent
3378 * immediately, it will be queued for transmission in @watch. The contents of
3379 * @message will then be serialized and transmitted when the connection of the
3380 * @watch becomes writable. In case the @message is queued, the ID returned in
3381 * @id will be non-zero and used as the ID argument in the message_sent
3384 * This function will take ownership of @data and g_free() it after use.
3386 * Returns: #GST_RTSP_OK on success.
3391 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3392 guint size, guint * id)
3398 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3399 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3400 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3402 g_mutex_lock (watch->mutex);
3404 if (watch->messages->length == 0) {
3405 res = write_bytes (watch->writefd.fd, data, &off, size);
3406 if (res != GST_RTSP_EINTR) {
3409 g_free ((gpointer) data);
3414 /* make a record with the data and id */
3415 rec = g_slice_new (GstRTSPRec);
3417 rec->data = (guint8 *) data;
3420 rec->data = g_memdup (data + off, size - off);
3421 rec->size = size - off;
3422 g_free ((gpointer) data);
3426 /* make sure rec->id is never 0 */
3427 rec->id = ++watch->id;
3428 } while (G_UNLIKELY (rec->id == 0));
3430 /* add the record to a queue. FIXME we would like to have an upper limit here */
3431 g_queue_push_head (watch->messages, rec);
3433 /* make sure the main context will now also check for writability on the
3435 if (!watch->write_added) {
3436 g_source_add_poll ((GSource *) watch, &watch->writefd);
3437 watch->write_added = TRUE;
3445 g_mutex_unlock (watch->mutex);
3450 * gst_rtsp_watch_send_message:
3451 * @watch: a #GstRTSPWatch
3452 * @message: a #GstRTSPMessage
3453 * @id: location for a message ID or %NULL
3455 * Send a @message using the connection of the @watch. If it cannot be sent
3456 * immediately, it will be queued for transmission in @watch. The contents of
3457 * @message will then be serialized and transmitted when the connection of the
3458 * @watch becomes writable. In case the @message is queued, the ID returned in
3459 * @id will be non-zero and used as the ID argument in the message_sent
3462 * Returns: #GST_RTSP_OK on success.
3467 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3473 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3474 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3476 /* make a record with the message as a string and id */
3477 str = message_to_string (watch->conn, message);
3479 return gst_rtsp_watch_write_data (watch,
3480 (guint8 *) g_string_free (str, FALSE), size, id);
3484 * gst_rtsp_watch_queue_data:
3485 * @watch: a #GstRTSPWatch
3486 * @data: the data to queue
3487 * @size: the size of @data
3489 * Queue @data for transmission in @watch. It will be transmitted when the
3490 * connection of the @watch becomes writable.
3492 * This function will take ownership of @data and g_free() it after use.
3494 * The return value of this function will be used as the id argument in the
3495 * message_sent callback.
3497 * Deprecated: Use gst_rtsp_watch_write_data()
3503 #ifndef GST_REMOVE_DEPRECATED
3505 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3510 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3511 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3512 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3514 g_mutex_lock (watch->mutex);
3516 /* make a record with the data and id */
3517 rec = g_slice_new (GstRTSPRec);
3518 rec->data = (guint8 *) data;
3521 /* make sure rec->id is never 0 */
3522 rec->id = ++watch->id;
3523 } while (G_UNLIKELY (rec->id == 0));
3525 /* add the record to a queue. FIXME we would like to have an upper limit here */
3526 g_queue_push_head (watch->messages, rec);
3528 /* make sure the main context will now also check for writability on the
3530 if (!watch->write_added) {
3531 g_source_add_poll ((GSource *) watch, &watch->writefd);
3532 watch->write_added = TRUE;
3535 g_mutex_unlock (watch->mutex);
3538 #endif /* GST_REMOVE_DEPRECATED */
3541 * gst_rtsp_watch_queue_message:
3542 * @watch: a #GstRTSPWatch
3543 * @message: a #GstRTSPMessage
3545 * Queue a @message for transmission in @watch. The contents of this
3546 * message will be serialized and transmitted when the connection of the
3547 * @watch becomes writable.
3549 * The return value of this function will be used as the id argument in the
3550 * message_sent callback.
3552 * Deprecated: Use gst_rtsp_watch_send_message()
3558 #ifndef GST_REMOVE_DEPRECATED
3560 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3565 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3566 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3568 /* make a record with the message as a string and id */
3569 str = message_to_string (watch->conn, message);
3571 return gst_rtsp_watch_queue_data (watch,
3572 (guint8 *) g_string_free (str, FALSE), size);
3574 #endif /* GST_REMOVE_DEPRECATED */