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, hints;
468 memset (&hints, 0, sizeof (struct addrinfo));
469 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
470 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
471 hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
472 hints.ai_protocol = 0; /* Any protocol */
473 hints.ai_canonname = NULL;
474 hints.ai_addr = NULL;
475 hints.ai_next = NULL;
477 aierr = getaddrinfo (host, NULL, &hints, &aires);
481 for (ai = aires; ai; ai = ai->ai_next) {
482 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
489 aierr = getnameinfo (ai->ai_addr, ai->ai_addrlen, ip, sizeof (ip), NULL, 0,
490 NI_NUMERICHOST | NI_NUMERICSERV);
494 freeaddrinfo (aires);
496 return g_strdup (ip);
501 GST_ERROR ("no addrinfo found for %s: %s", host, gai_strerror (aierr));
506 GST_ERROR ("no family found for %s", host);
507 freeaddrinfo (aires);
512 GST_ERROR ("no address found for %s: %s", host, gai_strerror (aierr));
513 freeaddrinfo (aires);
519 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
520 GstPoll * fdset, GTimeVal * timeout)
523 struct addrinfo hints;
524 struct addrinfo *aires;
527 gchar service[NI_MAXSERV];
530 unsigned long flags = 1;
531 #endif /* G_OS_WIN32 */
535 memset (&hints, 0, sizeof hints);
536 hints.ai_flags = AI_NUMERICHOST;
537 hints.ai_family = AF_UNSPEC;
538 hints.ai_socktype = SOCK_STREAM;
539 g_snprintf (service, sizeof (service) - 1, "%hu", port);
540 service[sizeof (service) - 1] = '\0';
542 aierr = getaddrinfo (ip, service, &hints, &aires);
546 for (ai = aires; ai; ai = ai->ai_next) {
547 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
554 fd = socket (ai->ai_family, SOCK_STREAM, 0);
558 /* set to non-blocking mode so that we can cancel the connect */
560 fcntl (fd, F_SETFL, O_NONBLOCK);
562 ioctlsocket (fd, FIONBIO, &flags);
563 #endif /* G_OS_WIN32 */
565 /* add the socket to our fdset */
566 ADD_POLLFD (fdset, fdout, fd);
568 /* we are going to connect ASYNC now */
569 ret = connect (fd, ai->ai_addr, ai->ai_addrlen);
572 if (!ERRNO_IS_EINPROGRESS)
575 /* wait for connect to complete up to the specified timeout or until we got
577 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
579 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
582 retval = gst_poll_wait (fdset, to);
583 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
587 else if (retval == -1)
590 /* we can still have an error connecting on windows */
591 if (gst_poll_fd_has_error (fdset, fdout)) {
592 socklen_t len = sizeof (errno);
594 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
596 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
601 gst_poll_fd_ignored (fdset, fdout);
604 freeaddrinfo (aires);
611 GST_ERROR ("no addrinfo found for %s: %s", ip, gai_strerror (aierr));
612 return GST_RTSP_ERROR;
616 GST_ERROR ("no family found for %s", ip);
617 freeaddrinfo (aires);
618 return GST_RTSP_ERROR;
622 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
623 freeaddrinfo (aires);
624 return GST_RTSP_ESYS;
628 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
629 REMOVE_POLLFD (fdset, fdout);
630 freeaddrinfo (aires);
631 return GST_RTSP_ESYS;
635 GST_ERROR ("timeout");
636 REMOVE_POLLFD (fdset, fdout);
637 freeaddrinfo (aires);
638 return GST_RTSP_ETIMEOUT;
643 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
650 guint16 port, url_port;
654 GstRTSPMessage response;
657 memset (&response, 0, sizeof (response));
658 gst_rtsp_message_init (&response);
660 /* create a random sessionid */
661 for (i = 0; i < TUNNELID_LEN; i++)
662 conn->tunnelid[i] = g_random_int_range ('a', 'z');
663 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
666 /* get the port from the url */
667 gst_rtsp_url_get_port (url, &url_port);
669 if (conn->proxy_host) {
670 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
671 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
672 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
673 ip = conn->proxy_host;
674 port = conn->proxy_port;
676 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
677 url->query ? url->query : "");
683 /* create the GET request for the read connection */
684 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
686 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
688 if (hostparam != NULL)
689 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
690 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
692 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
693 "application/x-rtsp-tunnelled");
694 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
695 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
697 /* we start by writing to this fd */
698 conn->writefd = &conn->fd0;
700 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
701 * request from being base64 encoded */
702 conn->tunneled = FALSE;
703 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
704 gst_rtsp_message_free (msg);
705 conn->tunneled = TRUE;
707 /* receive the response to the GET request */
708 /* we need to temporarily set manual_http to TRUE since
709 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
710 * failure otherwise */
711 old_http = conn->manual_http;
712 conn->manual_http = TRUE;
713 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
715 conn->manual_http = old_http;
717 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
718 response.type_data.response.code != GST_RTSP_STS_OK)
721 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
722 &value, 0) == GST_RTSP_OK) {
723 if (conn->proxy_host) {
724 /* if we use a proxy we need to change the destination url */
726 url->host = g_strdup (value);
728 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
730 /* and resolve the new ip address */
731 if (!(ip = do_resolve (value)))
738 /* connect to the host/port */
739 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
740 if (res != GST_RTSP_OK)
743 /* this is now our writing socket */
744 conn->writefd = &conn->fd1;
746 /* create the POST request for the write connection */
747 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
749 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
751 if (hostparam != NULL)
752 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
753 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
755 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
756 "application/x-rtsp-tunnelled");
757 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
758 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
759 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
760 "Sun, 9 Jan 1972 00:00:00 GMT");
761 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
763 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
764 * request from being base64 encoded */
765 conn->tunneled = FALSE;
766 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
767 gst_rtsp_message_free (msg);
768 conn->tunneled = TRUE;
771 gst_rtsp_message_unset (&response);
780 GST_ERROR ("failed to create request (%d)", res);
785 GST_ERROR ("write failed (%d)", res);
786 gst_rtsp_message_free (msg);
787 conn->tunneled = TRUE;
792 GST_ERROR ("read failed (%d)", res);
793 conn->manual_http = FALSE;
798 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
799 response.type_data.response.reason);
800 res = GST_RTSP_ERROR;
805 GST_ERROR ("could not resolve %s", conn->ip);
811 GST_ERROR ("failed to connect");
817 * gst_rtsp_connection_connect:
818 * @conn: a #GstRTSPConnection
819 * @timeout: a #GTimeVal timeout
821 * Attempt to connect to the url of @conn made with
822 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
823 * forever. If @timeout contains a valid timeout, this function will return
824 * #GST_RTSP_ETIMEOUT after the timeout expired.
826 * This function can be cancelled with gst_rtsp_connection_flush().
828 * Returns: #GST_RTSP_OK when a connection could be made.
831 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
838 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
839 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
840 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
844 if (conn->proxy_host && conn->tunneled) {
845 if (!(ip = do_resolve (conn->proxy_host))) {
846 GST_ERROR ("could not resolve %s", conn->proxy_host);
849 port = conn->proxy_port;
850 g_free (conn->proxy_host);
851 conn->proxy_host = ip;
853 if (!(ip = do_resolve (url->host))) {
854 GST_ERROR ("could not resolve %s", url->host);
857 /* get the port from the url */
858 gst_rtsp_url_get_port (url, &port);
864 /* connect to the host/port */
865 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
866 if (res != GST_RTSP_OK)
869 /* this is our read URL */
870 conn->readfd = &conn->fd0;
872 if (conn->tunneled) {
873 res = setup_tunneling (conn, timeout);
874 if (res != GST_RTSP_OK)
875 goto tunneling_failed;
877 conn->writefd = &conn->fd0;
884 return GST_RTSP_ENET;
888 GST_ERROR ("failed to connect");
893 GST_ERROR ("failed to setup tunneling");
899 auth_digest_compute_hex_urp (const gchar * username,
900 const gchar * realm, const gchar * password, gchar hex_urp[33])
902 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
903 const gchar *digest_string;
905 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
906 g_checksum_update (md5_context, (const guchar *) ":", 1);
907 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
908 g_checksum_update (md5_context, (const guchar *) ":", 1);
909 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
910 digest_string = g_checksum_get_string (md5_context);
912 memset (hex_urp, 0, 33);
913 memcpy (hex_urp, digest_string, strlen (digest_string));
915 g_checksum_free (md5_context);
919 auth_digest_compute_response (const gchar * method,
920 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
923 char hex_a2[33] = { 0, };
924 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
925 const gchar *digest_string;
928 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
929 g_checksum_update (md5_context, (const guchar *) ":", 1);
930 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
931 digest_string = g_checksum_get_string (md5_context);
932 memcpy (hex_a2, digest_string, strlen (digest_string));
935 g_checksum_reset (md5_context);
936 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
937 g_checksum_update (md5_context, (const guchar *) ":", 1);
938 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
939 g_checksum_update (md5_context, (const guchar *) ":", 1);
941 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
942 digest_string = g_checksum_get_string (md5_context);
943 memset (response, 0, 33);
944 memcpy (response, digest_string, strlen (digest_string));
946 g_checksum_free (md5_context);
950 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
952 switch (conn->auth_method) {
953 case GST_RTSP_AUTH_BASIC:{
958 if (conn->username == NULL || conn->passwd == NULL)
961 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
962 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
963 auth_string = g_strdup_printf ("Basic %s", user_pass64);
965 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
969 g_free (user_pass64);
972 case GST_RTSP_AUTH_DIGEST:{
973 gchar response[33], hex_urp[33];
974 gchar *auth_string, *auth_string2;
981 /* we need to have some params set */
982 if (conn->auth_params == NULL || conn->username == NULL ||
983 conn->passwd == NULL)
986 /* we need the realm and nonce */
987 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
988 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
989 if (realm == NULL || nonce == NULL)
992 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
995 method = gst_rtsp_method_as_text (message->type_data.request.method);
996 uri = message->type_data.request.uri;
998 /* Assume no qop, algorithm=md5, stale=false */
999 /* For algorithm MD5, a1 = urp. */
1000 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
1001 auth_string = g_strdup_printf ("Digest username=\"%s\", "
1002 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
1003 conn->username, realm, nonce, uri, response);
1005 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
1007 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
1009 g_free (auth_string);
1010 auth_string = auth_string2;
1012 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1023 gen_date_string (gchar * date_string, guint len)
1027 #ifdef HAVE_GMTIME_R
1031 g_get_current_time (&tv);
1032 t = (time_t) tv.tv_sec;
1034 #ifdef HAVE_GMTIME_R
1035 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1037 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1041 static GstRTSPResult
1042 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1046 if (G_UNLIKELY (*idx > size))
1047 return GST_RTSP_ERROR;
1054 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1055 if (G_UNLIKELY (r == 0)) {
1056 return GST_RTSP_EINTR;
1057 } else if (G_UNLIKELY (r < 0)) {
1058 if (ERRNO_IS_EAGAIN)
1059 return GST_RTSP_EINTR;
1060 if (!ERRNO_IS_EINTR)
1061 return GST_RTSP_ESYS;
1071 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1075 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1076 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1078 out = MIN (left, size);
1079 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1081 if (left == (gsize) out) {
1082 g_free (conn->initial_buffer);
1083 conn->initial_buffer = NULL;
1084 conn->initial_buffer_offset = 0;
1086 conn->initial_buffer_offset += out;
1089 if (G_LIKELY (size > (guint) out)) {
1092 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1104 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1106 DecodeCtx *ctx = conn->ctxp;
1111 guint8 in[sizeof (ctx->out) * 4 / 3];
1114 while (size > 0 && ctx->cout < ctx->coutl) {
1115 /* we have some leftover bytes */
1116 *buffer++ = ctx->out[ctx->cout++];
1121 /* got what we needed? */
1125 /* try to read more bytes */
1126 r = fill_raw_bytes (conn, in, sizeof (in));
1135 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1139 out = fill_raw_bytes (conn, buffer, size);
1145 static GstRTSPResult
1146 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1150 if (G_UNLIKELY (*idx > size))
1151 return GST_RTSP_ERROR;
1158 r = fill_bytes (conn, &buffer[*idx], left);
1159 if (G_UNLIKELY (r == 0)) {
1160 return GST_RTSP_EEOF;
1161 } else if (G_UNLIKELY (r < 0)) {
1162 if (ERRNO_IS_EAGAIN)
1163 return GST_RTSP_EINTR;
1164 if (!ERRNO_IS_EINTR)
1165 return GST_RTSP_ESYS;
1174 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1175 * end of a line. It even does its best to handle clients which mix them (even
1176 * though this is a really stupid idea (tm).) It also handles Line White Space
1177 * (LWS), where a line end followed by whitespace is considered LWS. This is
1178 * the method used in RTSP (and HTTP) to break long lines.
1180 static GstRTSPResult
1181 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1187 if (conn->read_ahead == READ_AHEAD_EOH) {
1188 /* the last call to read_line() already determined that we have reached
1189 * the end of the headers, so convey that information now */
1190 conn->read_ahead = 0;
1192 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1193 /* the last call to read_line() left off after having read \r\n */
1195 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1196 /* the last call to read_line() left off after having read \r\n\r */
1198 } else if (conn->read_ahead != 0) {
1199 /* the last call to read_line() left us with a character to start with */
1200 c = (guint8) conn->read_ahead;
1201 conn->read_ahead = 0;
1203 /* read the next character */
1204 r = fill_bytes (conn, &c, 1);
1205 if (G_UNLIKELY (r == 0)) {
1206 return GST_RTSP_EEOF;
1207 } else if (G_UNLIKELY (r < 0)) {
1208 if (ERRNO_IS_EAGAIN)
1209 return GST_RTSP_EINTR;
1210 if (!ERRNO_IS_EINTR)
1211 return GST_RTSP_ESYS;
1216 /* special treatment of line endings */
1217 if (c == '\r' || c == '\n') {
1221 /* need to read ahead one more character to know what to do... */
1222 r = fill_bytes (conn, &read_ahead, 1);
1223 if (G_UNLIKELY (r == 0)) {
1224 return GST_RTSP_EEOF;
1225 } else if (G_UNLIKELY (r < 0)) {
1226 if (ERRNO_IS_EAGAIN) {
1227 /* remember the original character we read and try again next time */
1228 if (conn->read_ahead == 0)
1229 conn->read_ahead = c;
1230 return GST_RTSP_EINTR;
1232 if (!ERRNO_IS_EINTR)
1233 return GST_RTSP_ESYS;
1237 if (read_ahead == ' ' || read_ahead == '\t') {
1238 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1239 /* got \r\n\r followed by whitespace, treat it as a normal line
1240 * followed by one starting with LWS */
1241 conn->read_ahead = read_ahead;
1244 /* got LWS, change the line ending to a space and continue */
1246 conn->read_ahead = read_ahead;
1248 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1249 if (read_ahead == '\r' || read_ahead == '\n') {
1250 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1251 conn->read_ahead = READ_AHEAD_EOH;
1254 /* got \r\n\r followed by something else, this is not really
1255 * supported since we have probably just eaten the first character
1256 * of the body or the next message, so just ignore the second \r
1257 * and live with it... */
1258 conn->read_ahead = read_ahead;
1261 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1262 if (read_ahead == '\r') {
1263 /* got \r\n\r so far, need one more character... */
1264 conn->read_ahead = READ_AHEAD_CRLFCR;
1266 } else if (read_ahead == '\n') {
1267 /* got \r\n\n, treat it as the end of the headers */
1268 conn->read_ahead = READ_AHEAD_EOH;
1271 /* found the end of a line, keep read_ahead for the next line */
1272 conn->read_ahead = read_ahead;
1275 } else if (c == read_ahead) {
1276 /* got double \r or \n, treat it as the end of the headers */
1277 conn->read_ahead = READ_AHEAD_EOH;
1279 } else if (c == '\r' && read_ahead == '\n') {
1280 /* got \r\n so far, still need more to know what to do... */
1281 conn->read_ahead = READ_AHEAD_CRLF;
1284 /* found the end of a line, keep read_ahead for the next line */
1285 conn->read_ahead = read_ahead;
1290 if (G_LIKELY (*idx < size - 1))
1291 buffer[(*idx)++] = c;
1293 buffer[*idx] = '\0';
1299 * gst_rtsp_connection_write:
1300 * @conn: a #GstRTSPConnection
1301 * @data: the data to write
1302 * @size: the size of @data
1303 * @timeout: a timeout value or #NULL
1305 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1306 * the specified @timeout. @timeout can be #NULL, in which case this function
1307 * might block forever.
1309 * This function can be cancelled with gst_rtsp_connection_flush().
1311 * Returns: #GST_RTSP_OK on success.
1314 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1315 guint size, GTimeVal * timeout)
1322 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1323 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1324 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1326 gst_poll_set_controllable (conn->fdset, TRUE);
1327 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1328 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1329 /* clear all previous poll results */
1330 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1331 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1333 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1339 res = write_bytes (conn->writefd->fd, data, &offset, size);
1340 if (G_LIKELY (res == GST_RTSP_OK))
1342 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1345 /* not all is written, wait until we can write more */
1347 retval = gst_poll_wait (conn->fdset, to);
1348 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1350 if (G_UNLIKELY (retval == 0))
1353 if (G_UNLIKELY (retval == -1)) {
1360 /* could also be an error with read socket */
1361 if (gst_poll_fd_has_error (conn->fdset, conn->readfd))
1369 return GST_RTSP_ETIMEOUT;
1373 return GST_RTSP_ESYS;
1377 return GST_RTSP_EINTR;
1381 return GST_RTSP_ENET;
1390 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1392 GString *str = NULL;
1394 str = g_string_new ("");
1396 switch (message->type) {
1397 case GST_RTSP_MESSAGE_REQUEST:
1398 /* create request string, add CSeq */
1399 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1401 gst_rtsp_method_as_text (message->type_data.request.method),
1402 message->type_data.request.uri, conn->cseq++);
1403 /* add session id if we have one */
1404 if (conn->session_id[0] != '\0') {
1405 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1406 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1409 /* add any authentication headers */
1410 add_auth_header (conn, message);
1412 case GST_RTSP_MESSAGE_RESPONSE:
1413 /* create response string */
1414 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1415 message->type_data.response.code, message->type_data.response.reason);
1417 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1418 /* create request string */
1419 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1420 gst_rtsp_method_as_text (message->type_data.request.method),
1421 message->type_data.request.uri,
1422 gst_rtsp_version_as_text (message->type_data.request.version));
1423 /* add any authentication headers */
1424 add_auth_header (conn, message);
1426 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1427 /* create response string */
1428 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1429 gst_rtsp_version_as_text (message->type_data.request.version),
1430 message->type_data.response.code, message->type_data.response.reason);
1432 case GST_RTSP_MESSAGE_DATA:
1434 guint8 data_header[4];
1436 /* prepare data header */
1437 data_header[0] = '$';
1438 data_header[1] = message->type_data.data.channel;
1439 data_header[2] = (message->body_size >> 8) & 0xff;
1440 data_header[3] = message->body_size & 0xff;
1442 /* create string with header and data */
1443 str = g_string_append_len (str, (gchar *) data_header, 4);
1445 g_string_append_len (str, (gchar *) message->body,
1446 message->body_size);
1450 g_string_free (str, TRUE);
1451 g_return_val_if_reached (NULL);
1455 /* append headers and body */
1456 if (message->type != GST_RTSP_MESSAGE_DATA) {
1457 gchar date_string[100];
1459 gen_date_string (date_string, sizeof (date_string));
1461 /* add date header */
1462 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1463 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1465 /* append headers */
1466 gst_rtsp_message_append_headers (message, str);
1468 /* append Content-Length and body if needed */
1469 if (message->body != NULL && message->body_size > 0) {
1472 len = g_strdup_printf ("%d", message->body_size);
1473 g_string_append_printf (str, "%s: %s\r\n",
1474 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1476 /* header ends here */
1477 g_string_append (str, "\r\n");
1479 g_string_append_len (str, (gchar *) message->body,
1480 message->body_size);
1482 /* just end headers */
1483 g_string_append (str, "\r\n");
1491 * gst_rtsp_connection_send:
1492 * @conn: a #GstRTSPConnection
1493 * @message: the message to send
1494 * @timeout: a timeout value or #NULL
1496 * Attempt to send @message to the connected @conn, blocking up to
1497 * the specified @timeout. @timeout can be #NULL, in which case this function
1498 * might block forever.
1500 * This function can be cancelled with gst_rtsp_connection_flush().
1502 * Returns: #GST_RTSP_OK on success.
1505 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1508 GString *string = NULL;
1513 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1514 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1516 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1519 if (conn->tunneled) {
1520 str = g_base64_encode ((const guchar *) string->str, string->len);
1521 g_string_free (string, TRUE);
1526 g_string_free (string, FALSE);
1530 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1538 g_warning ("Wrong message");
1539 return GST_RTSP_EINVAL;
1543 static GstRTSPResult
1544 parse_string (gchar * dest, gint size, gchar ** src)
1546 GstRTSPResult res = GST_RTSP_OK;
1551 while (g_ascii_isspace (**src))
1554 while (!g_ascii_isspace (**src) && **src != '\0') {
1556 dest[idx++] = **src;
1558 res = GST_RTSP_EPARSE;
1567 static GstRTSPResult
1568 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1569 GstRTSPVersion * version)
1571 GstRTSPResult res = GST_RTSP_OK;
1574 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1581 /* the version number must be formatted as X.Y with nothing following */
1582 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1583 res = GST_RTSP_EPARSE;
1585 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1586 if (major != 1 || minor != 0) {
1587 *version = GST_RTSP_VERSION_INVALID;
1588 res = GST_RTSP_ERROR;
1590 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1591 if (*type == GST_RTSP_MESSAGE_REQUEST)
1592 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1593 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1594 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1596 if (major == 1 && minor == 1) {
1597 *version = GST_RTSP_VERSION_1_1;
1598 } else if (major != 1 || minor != 0) {
1599 *version = GST_RTSP_VERSION_INVALID;
1600 res = GST_RTSP_ERROR;
1603 res = GST_RTSP_EPARSE;
1605 res = GST_RTSP_EPARSE;
1610 static GstRTSPResult
1611 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1613 GstRTSPResult res = GST_RTSP_OK;
1615 gchar versionstr[20];
1620 bptr = (gchar *) buffer;
1622 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1623 res = GST_RTSP_EPARSE;
1625 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1626 res = GST_RTSP_EPARSE;
1627 code = atoi (codestr);
1628 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1629 res = GST_RTSP_EPARSE;
1631 while (g_ascii_isspace (*bptr))
1634 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1635 NULL) != GST_RTSP_OK))
1636 res = GST_RTSP_EPARSE;
1638 res2 = parse_protocol_version (versionstr, &msg->type,
1639 &msg->type_data.response.version);
1640 if (G_LIKELY (res == GST_RTSP_OK))
1646 static GstRTSPResult
1647 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1649 GstRTSPResult res = GST_RTSP_OK;
1651 gchar versionstr[20];
1652 gchar methodstr[20];
1655 GstRTSPMethod method;
1657 bptr = (gchar *) buffer;
1659 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1660 res = GST_RTSP_EPARSE;
1661 method = gst_rtsp_find_method (methodstr);
1663 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1664 res = GST_RTSP_EPARSE;
1665 if (G_UNLIKELY (*urlstr == '\0'))
1666 res = GST_RTSP_EPARSE;
1668 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1669 res = GST_RTSP_EPARSE;
1671 if (G_UNLIKELY (*bptr != '\0'))
1672 res = GST_RTSP_EPARSE;
1674 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1675 urlstr) != GST_RTSP_OK))
1676 res = GST_RTSP_EPARSE;
1678 res2 = parse_protocol_version (versionstr, &msg->type,
1679 &msg->type_data.request.version);
1680 if (G_LIKELY (res == GST_RTSP_OK))
1683 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1684 /* GET and POST are not allowed as RTSP methods */
1685 if (msg->type_data.request.method == GST_RTSP_GET ||
1686 msg->type_data.request.method == GST_RTSP_POST) {
1687 msg->type_data.request.method = GST_RTSP_INVALID;
1688 if (res == GST_RTSP_OK)
1689 res = GST_RTSP_ERROR;
1691 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1692 /* only GET and POST are allowed as HTTP methods */
1693 if (msg->type_data.request.method != GST_RTSP_GET &&
1694 msg->type_data.request.method != GST_RTSP_POST) {
1695 msg->type_data.request.method = GST_RTSP_INVALID;
1696 if (res == GST_RTSP_OK)
1697 res = GST_RTSP_ERROR;
1704 /* parsing lines means reading a Key: Value pair */
1705 static GstRTSPResult
1706 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1708 GstRTSPHeaderField field;
1709 gchar *line = (gchar *) buffer;
1712 if ((value = strchr (line, ':')) == NULL || value == line)
1715 /* trim space before the colon */
1716 if (value[-1] == ' ')
1719 /* replace the colon with a NUL */
1722 /* find the header */
1723 field = gst_rtsp_find_header_field (line);
1724 if (field == GST_RTSP_HDR_INVALID)
1727 /* split up the value in multiple key:value pairs if it contains comma(s) */
1728 while (*value != '\0') {
1730 gchar *comma = NULL;
1731 gboolean quoted = FALSE;
1734 /* trim leading space */
1738 /* for headers which may not appear multiple times, and thus may not
1739 * contain multiple values on the same line, we can short-circuit the loop
1740 * below and the entire value results in just one key:value pair*/
1741 if (!gst_rtsp_header_allow_multiple (field))
1742 next_value = value + strlen (value);
1746 /* find the next value, taking special care of quotes and comments */
1747 while (*next_value != '\0') {
1748 if ((quoted || comment != 0) && *next_value == '\\' &&
1749 next_value[1] != '\0')
1751 else if (comment == 0 && *next_value == '"')
1753 else if (!quoted && *next_value == '(')
1755 else if (comment != 0 && *next_value == ')')
1757 else if (!quoted && comment == 0) {
1758 /* To quote RFC 2068: "User agents MUST take special care in parsing
1759 * the WWW-Authenticate field value if it contains more than one
1760 * challenge, or if more than one WWW-Authenticate header field is
1761 * provided, since the contents of a challenge may itself contain a
1762 * comma-separated list of authentication parameters."
1764 * What this means is that we cannot just look for an unquoted comma
1765 * when looking for multiple values in Proxy-Authenticate and
1766 * WWW-Authenticate headers. Instead we need to look for the sequence
1767 * "comma [space] token space token" before we can split after the
1770 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1771 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1772 if (*next_value == ',') {
1773 if (next_value[1] == ' ') {
1774 /* skip any space following the comma so we do not mistake it for
1775 * separating between two tokens */
1779 } else if (*next_value == ' ' && next_value[1] != ',' &&
1780 next_value[1] != '=' && comma != NULL) {
1785 } else if (*next_value == ',')
1793 if (value != next_value && next_value[-1] == ' ')
1794 next_value[-1] = '\0';
1796 if (*next_value != '\0')
1797 *next_value++ = '\0';
1799 /* add the key:value pair */
1801 gst_rtsp_message_add_header (msg, field, value);
1812 return GST_RTSP_EPARSE;
1816 /* convert all consecutive whitespace to a single space */
1818 normalize_line (guint8 * buffer)
1821 if (g_ascii_isspace (*buffer)) {
1825 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1828 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1836 * GST_RTSP_OK when a complete message was read.
1837 * GST_RTSP_EEOF: when the socket is closed
1838 * GST_RTSP_EINTR: when more data is needed.
1839 * GST_RTSP_..: some other error occured.
1841 static GstRTSPResult
1842 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1843 GstRTSPConnection * conn)
1848 switch (builder->state) {
1853 builder->offset = 0;
1855 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1856 if (res != GST_RTSP_OK)
1859 c = builder->buffer[0];
1861 /* we have 1 bytes now and we can see if this is a data message or
1864 /* data message, prepare for the header */
1865 builder->state = STATE_DATA_HEADER;
1866 } else if (c == '\n' || c == '\r') {
1867 /* skip \n and \r */
1868 builder->offset = 0;
1871 builder->state = STATE_READ_LINES;
1875 case STATE_DATA_HEADER:
1878 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1879 if (res != GST_RTSP_OK)
1882 gst_rtsp_message_init_data (message, builder->buffer[1]);
1884 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1885 builder->body_data = g_malloc (builder->body_len + 1);
1886 builder->body_data[builder->body_len] = '\0';
1887 builder->offset = 0;
1888 builder->state = STATE_DATA_BODY;
1891 case STATE_DATA_BODY:
1894 read_bytes (conn, builder->body_data, &builder->offset,
1896 if (res != GST_RTSP_OK)
1899 /* we have the complete body now, store in the message adjusting the
1900 * length to include the traling '\0' */
1901 gst_rtsp_message_take_body (message,
1902 (guint8 *) builder->body_data, builder->body_len + 1);
1903 builder->body_data = NULL;
1904 builder->body_len = 0;
1906 builder->state = STATE_END;
1909 case STATE_READ_LINES:
1911 res = read_line (conn, builder->buffer, &builder->offset,
1912 sizeof (builder->buffer));
1913 if (res != GST_RTSP_OK)
1916 /* we have a regular response */
1917 if (builder->buffer[0] == '\0') {
1920 /* empty line, end of message header */
1921 /* see if there is a Content-Length header, but ignore it if this
1922 * is a POST request with an x-sessioncookie header */
1923 if (gst_rtsp_message_get_header (message,
1924 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1925 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1926 message->type_data.request.method != GST_RTSP_POST ||
1927 gst_rtsp_message_get_header (message,
1928 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1929 /* there is, prepare to read the body */
1930 builder->body_len = atol (hdrval);
1931 builder->body_data = g_try_malloc (builder->body_len + 1);
1932 /* we can't do much here, we need the length to know how many bytes
1933 * we need to read next and when allocation fails, something is
1934 * probably wrong with the length. */
1935 if (builder->body_data == NULL)
1936 goto invalid_body_len;
1938 builder->body_data[builder->body_len] = '\0';
1939 builder->offset = 0;
1940 builder->state = STATE_DATA_BODY;
1942 builder->state = STATE_END;
1947 /* we have a line */
1948 normalize_line (builder->buffer);
1949 if (builder->line == 0) {
1950 /* first line, check for response status */
1951 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1952 memcmp (builder->buffer, "HTTP", 4) == 0) {
1953 builder->status = parse_response_status (builder->buffer, message);
1955 builder->status = parse_request_line (builder->buffer, message);
1958 /* else just parse the line */
1959 res = parse_line (builder->buffer, message);
1960 if (res != GST_RTSP_OK)
1961 builder->status = res;
1964 builder->offset = 0;
1969 gchar *session_cookie;
1972 if (message->type == GST_RTSP_MESSAGE_DATA) {
1973 /* data messages don't have headers */
1978 /* save the tunnel session in the connection */
1979 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1980 !conn->manual_http &&
1981 conn->tstate == TUNNEL_STATE_NONE &&
1982 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1983 &session_cookie, 0) == GST_RTSP_OK) {
1984 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1985 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1986 conn->tunneled = TRUE;
1989 /* save session id in the connection for further use */
1990 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1991 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1992 &session_id, 0) == GST_RTSP_OK) {
1995 maxlen = sizeof (conn->session_id) - 1;
1996 /* the sessionid can have attributes marked with ;
1997 * Make sure we strip them */
1998 for (i = 0; session_id[i] != '\0'; i++) {
1999 if (session_id[i] == ';') {
2004 } while (g_ascii_isspace (session_id[i]));
2005 if (g_str_has_prefix (&session_id[i], "timeout=")) {
2008 /* if we parsed something valid, configure */
2009 if ((to = atoi (&session_id[i + 8])) > 0)
2016 /* make sure to not overflow */
2017 strncpy (conn->session_id, session_id, maxlen);
2018 conn->session_id[maxlen] = '\0';
2020 res = builder->status;
2024 res = GST_RTSP_ERROR;
2034 GST_DEBUG ("could not allocate body");
2035 return GST_RTSP_ERROR;
2040 * gst_rtsp_connection_read:
2041 * @conn: a #GstRTSPConnection
2042 * @data: the data to read
2043 * @size: the size of @data
2044 * @timeout: a timeout value or #NULL
2046 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
2047 * the specified @timeout. @timeout can be #NULL, in which case this function
2048 * might block forever.
2050 * This function can be cancelled with gst_rtsp_connection_flush().
2052 * Returns: #GST_RTSP_OK on success.
2055 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
2063 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2064 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
2065 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2067 if (G_UNLIKELY (size == 0))
2072 /* configure timeout if any */
2073 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2075 gst_poll_set_controllable (conn->fdset, TRUE);
2076 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2077 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2080 res = read_bytes (conn, data, &offset, size);
2081 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2083 if (G_LIKELY (res == GST_RTSP_OK))
2085 if (G_UNLIKELY (res != GST_RTSP_EINTR))
2089 retval = gst_poll_wait (conn->fdset, to);
2090 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2092 /* check for timeout */
2093 if (G_UNLIKELY (retval == 0))
2094 goto select_timeout;
2096 if (G_UNLIKELY (retval == -1)) {
2103 /* could also be an error with write socket */
2104 if (gst_poll_fd_has_error (conn->fdset, conn->writefd))
2107 gst_poll_set_controllable (conn->fdset, FALSE);
2114 return GST_RTSP_ESYS;
2118 return GST_RTSP_ETIMEOUT;
2122 return GST_RTSP_EINTR;
2126 return GST_RTSP_EEOF;
2130 res = GST_RTSP_ENET;
2138 static GstRTSPMessage *
2139 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
2140 const GstRTSPMessage * request)
2142 GstRTSPMessage *msg;
2145 if (gst_rtsp_status_as_text (code) == NULL)
2146 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
2148 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
2151 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
2152 "GStreamer RTSP Server");
2153 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2154 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2155 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2157 if (code == GST_RTSP_STS_OK) {
2159 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2161 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2162 "application/x-rtsp-tunnelled");
2175 * gst_rtsp_connection_receive:
2176 * @conn: a #GstRTSPConnection
2177 * @message: the message to read
2178 * @timeout: a timeout value or #NULL
2180 * Attempt to read into @message from the connected @conn, blocking up to
2181 * the specified @timeout. @timeout can be #NULL, in which case this function
2182 * might block forever.
2184 * This function can be cancelled with gst_rtsp_connection_flush().
2186 * Returns: #GST_RTSP_OK on success.
2189 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2193 GstRTSPBuilder builder;
2197 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2198 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2199 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2201 /* configure timeout if any */
2202 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2204 gst_poll_set_controllable (conn->fdset, TRUE);
2205 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2206 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2208 memset (&builder, 0, sizeof (GstRTSPBuilder));
2210 res = build_next (&builder, message, conn);
2211 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2213 else if (G_LIKELY (res == GST_RTSP_OK)) {
2214 if (!conn->manual_http) {
2215 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2216 if (conn->tstate == TUNNEL_STATE_NONE &&
2217 message->type_data.request.method == GST_RTSP_GET) {
2218 GstRTSPMessage *response;
2220 conn->tstate = TUNNEL_STATE_GET;
2222 /* tunnel GET request, we can reply now */
2223 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2224 res = gst_rtsp_connection_send (conn, response, timeout);
2225 gst_rtsp_message_free (response);
2226 if (res == GST_RTSP_OK)
2227 res = GST_RTSP_ETGET;
2229 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2230 message->type_data.request.method == GST_RTSP_POST) {
2231 conn->tstate = TUNNEL_STATE_POST;
2233 /* tunnel POST request, the caller now has to link the two
2235 res = GST_RTSP_ETPOST;
2238 res = GST_RTSP_EPARSE;
2241 } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2242 res = GST_RTSP_EPARSE;
2248 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2252 retval = gst_poll_wait (conn->fdset, to);
2253 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2255 /* check for timeout */
2256 if (G_UNLIKELY (retval == 0))
2257 goto select_timeout;
2259 if (G_UNLIKELY (retval == -1)) {
2266 /* could also be an error with write socket */
2267 if (gst_poll_fd_has_error (conn->fdset, conn->writefd))
2270 gst_poll_set_controllable (conn->fdset, FALSE);
2273 /* we have a message here */
2274 build_reset (&builder);
2281 res = GST_RTSP_ESYS;
2286 res = GST_RTSP_ETIMEOUT;
2291 res = GST_RTSP_EINTR;
2296 res = GST_RTSP_EEOF;
2301 res = GST_RTSP_ENET;
2307 build_reset (&builder);
2308 gst_rtsp_message_unset (message);
2314 * gst_rtsp_connection_close:
2315 * @conn: a #GstRTSPConnection
2317 * Close the connected @conn. After this call, the connection is in the same
2318 * state as when it was first created.
2320 * Returns: #GST_RTSP_OK on success.
2323 gst_rtsp_connection_close (GstRTSPConnection * conn)
2325 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2330 conn->read_ahead = 0;
2332 g_free (conn->initial_buffer);
2333 conn->initial_buffer = NULL;
2334 conn->initial_buffer_offset = 0;
2336 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2337 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2338 conn->writefd = NULL;
2339 conn->readfd = NULL;
2340 conn->tunneled = FALSE;
2341 conn->tstate = TUNNEL_STATE_NONE;
2343 g_free (conn->username);
2344 conn->username = NULL;
2345 g_free (conn->passwd);
2346 conn->passwd = NULL;
2347 gst_rtsp_connection_clear_auth_params (conn);
2350 conn->session_id[0] = '\0';
2356 * gst_rtsp_connection_free:
2357 * @conn: a #GstRTSPConnection
2359 * Close and free @conn.
2361 * Returns: #GST_RTSP_OK on success.
2364 gst_rtsp_connection_free (GstRTSPConnection * conn)
2368 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2370 res = gst_rtsp_connection_close (conn);
2371 gst_poll_free (conn->fdset);
2372 g_timer_destroy (conn->timer);
2373 gst_rtsp_url_free (conn->url);
2374 g_free (conn->proxy_host);
2384 * gst_rtsp_connection_poll:
2385 * @conn: a #GstRTSPConnection
2386 * @events: a bitmask of #GstRTSPEvent flags to check
2387 * @revents: location for result flags
2388 * @timeout: a timeout
2390 * Wait up to the specified @timeout for the connection to become available for
2391 * at least one of the operations specified in @events. When the function returns
2392 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2395 * @timeout can be #NULL, in which case this function might block forever.
2397 * This function can be cancelled with gst_rtsp_connection_flush().
2399 * Returns: #GST_RTSP_OK on success.
2404 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2405 GstRTSPEvent * revents, GTimeVal * timeout)
2410 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2411 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2412 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2413 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2414 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2416 gst_poll_set_controllable (conn->fdset, TRUE);
2418 /* add fd to writer set when asked to */
2419 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2420 events & GST_RTSP_EV_WRITE);
2422 /* add fd to reader set when asked to */
2423 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2425 /* configure timeout if any */
2426 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2429 retval = gst_poll_wait (conn->fdset, to);
2430 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2432 if (G_UNLIKELY (retval == 0))
2433 goto select_timeout;
2435 if (G_UNLIKELY (retval == -1)) {
2443 if (events & GST_RTSP_EV_READ) {
2444 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2445 *revents |= GST_RTSP_EV_READ;
2447 if (events & GST_RTSP_EV_WRITE) {
2448 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2449 *revents |= GST_RTSP_EV_WRITE;
2456 return GST_RTSP_ETIMEOUT;
2460 return GST_RTSP_ESYS;
2464 return GST_RTSP_EINTR;
2469 * gst_rtsp_connection_next_timeout:
2470 * @conn: a #GstRTSPConnection
2471 * @timeout: a timeout
2473 * Calculate the next timeout for @conn, storing the result in @timeout.
2475 * Returns: #GST_RTSP_OK.
2478 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2484 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2485 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2487 elapsed = g_timer_elapsed (conn->timer, &usec);
2488 if (elapsed >= conn->timeout) {
2492 sec = conn->timeout - elapsed;
2493 if (usec <= G_USEC_PER_SEC)
2494 usec = G_USEC_PER_SEC - usec;
2499 timeout->tv_sec = sec;
2500 timeout->tv_usec = usec;
2506 * gst_rtsp_connection_reset_timeout:
2507 * @conn: a #GstRTSPConnection
2509 * Reset the timeout of @conn.
2511 * Returns: #GST_RTSP_OK.
2514 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2516 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2518 g_timer_start (conn->timer);
2524 * gst_rtsp_connection_flush:
2525 * @conn: a #GstRTSPConnection
2526 * @flush: start or stop the flush
2528 * Start or stop the flushing action on @conn. When flushing, all current
2529 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2530 * is set to non-flushing mode again.
2532 * Returns: #GST_RTSP_OK.
2535 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2537 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2539 gst_poll_set_flushing (conn->fdset, flush);
2545 * gst_rtsp_connection_set_proxy:
2546 * @conn: a #GstRTSPConnection
2547 * @host: the proxy host
2548 * @port: the proxy port
2550 * Set the proxy host and port.
2552 * Returns: #GST_RTSP_OK.
2557 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2558 const gchar * host, guint port)
2560 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2562 g_free (conn->proxy_host);
2563 conn->proxy_host = g_strdup (host);
2564 conn->proxy_port = port;
2570 * gst_rtsp_connection_set_auth:
2571 * @conn: a #GstRTSPConnection
2572 * @method: authentication method
2574 * @pass: the password
2576 * Configure @conn for authentication mode @method with @user and @pass as the
2577 * user and password respectively.
2579 * Returns: #GST_RTSP_OK.
2582 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2583 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2585 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2587 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2588 || g_strrstr (user, ":") != NULL))
2589 return GST_RTSP_EINVAL;
2591 /* Make sure the username and passwd are being set for authentication */
2592 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2593 return GST_RTSP_EINVAL;
2595 /* ":" chars are not allowed in usernames for basic auth */
2596 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2597 return GST_RTSP_EINVAL;
2599 g_free (conn->username);
2600 g_free (conn->passwd);
2602 conn->auth_method = method;
2603 conn->username = g_strdup (user);
2604 conn->passwd = g_strdup (pass);
2611 * @key: ASCII string to hash
2613 * Hashes @key in a case-insensitive manner.
2615 * Returns: the hash code.
2618 str_case_hash (gconstpointer key)
2620 const char *p = key;
2621 guint h = g_ascii_toupper (*p);
2624 for (p += 1; *p != '\0'; p++)
2625 h = (h << 5) - h + g_ascii_toupper (*p);
2632 * @v1: an ASCII string
2633 * @v2: another ASCII string
2635 * Compares @v1 and @v2 in a case-insensitive manner
2637 * Returns: %TRUE if they are equal (modulo case)
2640 str_case_equal (gconstpointer v1, gconstpointer v2)
2642 const char *string1 = v1;
2643 const char *string2 = v2;
2645 return g_ascii_strcasecmp (string1, string2) == 0;
2649 * gst_rtsp_connection_set_auth_param:
2650 * @conn: a #GstRTSPConnection
2651 * @param: authentication directive
2654 * Setup @conn with authentication directives. This is not necesary for
2655 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2656 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2657 * in the WWW-Authenticate response header and can include realm, domain,
2658 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2663 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2664 const gchar * param, const gchar * value)
2666 g_return_if_fail (conn != NULL);
2667 g_return_if_fail (param != NULL);
2669 if (conn->auth_params == NULL) {
2671 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2673 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2677 * gst_rtsp_connection_clear_auth_params:
2678 * @conn: a #GstRTSPConnection
2680 * Clear the list of authentication directives stored in @conn.
2685 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2687 g_return_if_fail (conn != NULL);
2689 if (conn->auth_params != NULL) {
2690 g_hash_table_destroy (conn->auth_params);
2691 conn->auth_params = NULL;
2695 static GstRTSPResult
2696 set_qos_dscp (gint fd, guint qos_dscp)
2698 union gst_sockaddr sa;
2699 socklen_t slen = sizeof (sa);
2706 if (getsockname (fd, &sa.sa, &slen) < 0)
2707 goto no_getsockname;
2709 af = sa.sa.sa_family;
2711 /* if this is an IPv4-mapped address then do IPv4 QoS */
2712 if (af == AF_INET6) {
2713 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2717 /* extract and shift 6 bits of the DSCP */
2718 tos = (qos_dscp & 0x3f) << 2;
2722 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2727 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2741 return GST_RTSP_ESYS;
2746 return GST_RTSP_ERROR;
2751 * gst_rtsp_connection_set_qos_dscp:
2752 * @conn: a #GstRTSPConnection
2753 * @qos_dscp: DSCP value
2755 * Configure @conn to use the specified DSCP value.
2757 * Returns: #GST_RTSP_OK on success.
2762 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2766 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2767 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2768 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2770 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2771 if (res == GST_RTSP_OK)
2772 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2779 * gst_rtsp_connection_get_url:
2780 * @conn: a #GstRTSPConnection
2782 * Retrieve the URL of the other end of @conn.
2784 * Returns: The URL. This value remains valid until the
2785 * connection is freed.
2790 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2792 g_return_val_if_fail (conn != NULL, NULL);
2798 * gst_rtsp_connection_get_ip:
2799 * @conn: a #GstRTSPConnection
2801 * Retrieve the IP address of the other end of @conn.
2803 * Returns: The IP address as a string. this value remains valid until the
2804 * connection is closed.
2809 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2811 g_return_val_if_fail (conn != NULL, NULL);
2817 * gst_rtsp_connection_set_ip:
2818 * @conn: a #GstRTSPConnection
2819 * @ip: an ip address
2821 * Set the IP address of the server.
2826 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2828 g_return_if_fail (conn != NULL);
2831 conn->ip = g_strdup (ip);
2835 * gst_rtsp_connection_get_readfd:
2836 * @conn: a #GstRTSPConnection
2838 * Get the file descriptor for reading.
2840 * Returns: the file descriptor used for reading or -1 on error. The file
2841 * descriptor remains valid until the connection is closed.
2846 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2848 g_return_val_if_fail (conn != NULL, -1);
2849 g_return_val_if_fail (conn->readfd != NULL, -1);
2851 return conn->readfd->fd;
2855 * gst_rtsp_connection_get_writefd:
2856 * @conn: a #GstRTSPConnection
2858 * Get the file descriptor for writing.
2860 * Returns: the file descriptor used for writing or -1 on error. The file
2861 * descriptor remains valid until the connection is closed.
2866 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2868 g_return_val_if_fail (conn != NULL, -1);
2869 g_return_val_if_fail (conn->writefd != NULL, -1);
2871 return conn->writefd->fd;
2875 * gst_rtsp_connection_set_http_mode:
2876 * @conn: a #GstRTSPConnection
2877 * @enable: %TRUE to enable manual HTTP mode
2879 * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2880 * messages in addition to the RTSP messages. It will also disable the
2881 * automatic handling of setting up an HTTP tunnel.
2886 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2888 g_return_if_fail (conn != NULL);
2890 conn->manual_http = enable;
2894 * gst_rtsp_connection_set_tunneled:
2895 * @conn: a #GstRTSPConnection
2896 * @tunneled: the new state
2898 * Set the HTTP tunneling state of the connection. This must be configured before
2899 * the @conn is connected.
2904 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2906 g_return_if_fail (conn != NULL);
2907 g_return_if_fail (conn->readfd == NULL);
2908 g_return_if_fail (conn->writefd == NULL);
2910 conn->tunneled = tunneled;
2914 * gst_rtsp_connection_is_tunneled:
2915 * @conn: a #GstRTSPConnection
2917 * Get the tunneling state of the connection.
2919 * Returns: if @conn is using HTTP tunneling.
2924 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2926 g_return_val_if_fail (conn != NULL, FALSE);
2928 return conn->tunneled;
2932 * gst_rtsp_connection_get_tunnelid:
2933 * @conn: a #GstRTSPConnection
2935 * Get the tunnel session id the connection.
2937 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2942 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2944 g_return_val_if_fail (conn != NULL, NULL);
2946 if (!conn->tunneled)
2949 return conn->tunnelid;
2953 * gst_rtsp_connection_do_tunnel:
2954 * @conn: a #GstRTSPConnection
2955 * @conn2: a #GstRTSPConnection or %NULL
2957 * If @conn received the first tunnel connection and @conn2 received
2958 * the second tunnel connection, link the two connections together so that
2959 * @conn manages the tunneled connection.
2961 * After this call, @conn2 cannot be used anymore and must be freed with
2962 * gst_rtsp_connection_free().
2964 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2967 * Returns: return GST_RTSP_OK on success.
2972 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2973 GstRTSPConnection * conn2)
2975 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2977 if (conn2 != NULL) {
2978 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2979 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2980 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2981 TUNNELID_LEN), GST_RTSP_EINVAL);
2983 /* both connections have fd0 as the read/write socket. start by taking the
2984 * socket from conn2 and set it as the socket in conn */
2985 conn->fd1 = conn2->fd0;
2987 /* clean up some of the state of conn2 */
2988 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2990 conn2->readfd = conn2->writefd = NULL;
2992 /* We make fd0 the write socket and fd1 the read socket. */
2993 conn->writefd = &conn->fd0;
2994 conn->readfd = &conn->fd1;
2996 conn->tstate = TUNNEL_STATE_COMPLETE;
2999 /* we need base64 decoding for the readfd */
3000 conn->ctx.state = 0;
3003 conn->ctx.coutl = 0;
3004 conn->ctxp = &conn->ctx;
3009 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
3010 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
3019 /* async functions */
3020 struct _GstRTSPWatch
3024 GstRTSPConnection *conn;
3026 GstRTSPBuilder builder;
3027 GstRTSPMessage message;
3031 gboolean write_added;
3033 /* queued message for transmission */
3042 GstRTSPWatchFuncs funcs;
3045 GDestroyNotify notify;
3049 gst_rtsp_source_prepare (GSource * source, gint * timeout)
3051 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3053 if (watch->conn->initial_buffer != NULL)
3056 *timeout = (watch->conn->timeout * 1000);
3062 gst_rtsp_source_check (GSource * source)
3064 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3066 if (watch->readfd.revents & READ_COND)
3069 if (watch->writefd.revents & WRITE_COND)
3076 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
3077 gpointer user_data G_GNUC_UNUSED)
3079 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3082 /* first read as much as we can */
3083 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
3085 res = build_next (&watch->builder, &watch->message, watch->conn);
3086 if (res == GST_RTSP_EINTR)
3088 else if (G_UNLIKELY (res == GST_RTSP_EEOF))
3090 else if (G_LIKELY (res == GST_RTSP_OK)) {
3091 if (!watch->conn->manual_http &&
3092 watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3093 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3094 watch->message.type_data.request.method == GST_RTSP_GET) {
3095 GstRTSPMessage *response;
3096 GstRTSPStatusCode code;
3098 watch->conn->tstate = TUNNEL_STATE_GET;
3100 if (watch->funcs.tunnel_start)
3101 code = watch->funcs.tunnel_start (watch, watch->user_data);
3103 code = GST_RTSP_STS_OK;
3105 /* queue the response */
3106 response = gen_tunnel_reply (watch->conn, code, &watch->message);
3107 gst_rtsp_watch_send_message (watch, response, NULL);
3108 gst_rtsp_message_free (response);
3110 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3111 watch->message.type_data.request.method == GST_RTSP_POST) {
3112 watch->conn->tstate = TUNNEL_STATE_POST;
3114 /* in the callback the connection should be tunneled with the
3116 if (watch->funcs.tunnel_complete)
3117 watch->funcs.tunnel_complete (watch, watch->user_data);
3123 if (!watch->conn->manual_http) {
3124 /* if manual HTTP support is not enabled, then restore the message to
3125 * what it would have looked like without the support for parsing HTTP
3126 * messages being present */
3127 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3128 watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3129 watch->message.type_data.request.method = GST_RTSP_INVALID;
3130 if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3131 watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3132 res = GST_RTSP_EPARSE;
3133 } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3134 watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3135 if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3136 watch->message.type_data.response.version =
3137 GST_RTSP_VERSION_INVALID;
3138 res = GST_RTSP_EPARSE;
3142 if (G_LIKELY (res == GST_RTSP_OK)) {
3143 if (watch->funcs.message_received)
3144 watch->funcs.message_received (watch, &watch->message,
3147 if (watch->funcs.error_full)
3148 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3149 0, watch->user_data), error);
3155 gst_rtsp_message_unset (&watch->message);
3156 build_reset (&watch->builder);
3160 if (watch->writefd.revents & WRITE_COND) {
3161 g_mutex_lock (watch->mutex);
3163 if (watch->write_data == NULL) {
3166 /* get a new message from the queue */
3167 rec = g_queue_pop_tail (watch->messages);
3171 watch->write_off = 0;
3172 watch->write_data = rec->data;
3173 watch->write_size = rec->size;
3174 watch->write_id = rec->id;
3176 g_slice_free (GstRTSPRec, rec);
3179 res = write_bytes (watch->writefd.fd, watch->write_data,
3180 &watch->write_off, watch->write_size);
3181 g_mutex_unlock (watch->mutex);
3182 if (res == GST_RTSP_EINTR)
3184 else if (G_LIKELY (res == GST_RTSP_OK)) {
3185 if (watch->funcs.message_sent)
3186 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3188 if (watch->funcs.error_full)
3189 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3190 watch->write_id, watch->user_data), error);
3194 g_mutex_lock (watch->mutex);
3196 g_free (watch->write_data);
3197 watch->write_data = NULL;
3201 if (watch->write_added) {
3202 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3203 watch->write_added = FALSE;
3204 watch->writefd.revents = 0;
3207 g_mutex_unlock (watch->mutex);
3216 if (watch->funcs.closed)
3217 watch->funcs.closed (watch, watch->user_data);
3222 if (watch->funcs.error)
3223 watch->funcs.error (watch, res, watch->user_data);
3229 gst_rtsp_rec_free (gpointer data)
3231 GstRTSPRec *rec = data;
3234 g_slice_free (GstRTSPRec, rec);
3238 gst_rtsp_source_finalize (GSource * source)
3240 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3242 build_reset (&watch->builder);
3243 gst_rtsp_message_unset (&watch->message);
3245 g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3246 g_queue_free (watch->messages);
3247 watch->messages = NULL;
3249 g_mutex_free (watch->mutex);
3251 g_free (watch->write_data);
3254 watch->notify (watch->user_data);
3257 static GSourceFuncs gst_rtsp_source_funcs = {
3258 gst_rtsp_source_prepare,
3259 gst_rtsp_source_check,
3260 gst_rtsp_source_dispatch,
3261 gst_rtsp_source_finalize,
3267 * gst_rtsp_watch_new:
3268 * @conn: a #GstRTSPConnection
3269 * @funcs: watch functions
3270 * @user_data: user data to pass to @funcs
3271 * @notify: notify when @user_data is not referenced anymore
3273 * Create a watch object for @conn. The functions provided in @funcs will be
3274 * called with @user_data when activity happened on the watch.
3276 * The new watch is usually created so that it can be attached to a
3277 * maincontext with gst_rtsp_watch_attach().
3279 * @conn must exist for the entire lifetime of the watch.
3281 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3282 * communication. Free with gst_rtsp_watch_unref () after usage.
3287 gst_rtsp_watch_new (GstRTSPConnection * conn,
3288 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3290 GstRTSPWatch *result;
3292 g_return_val_if_fail (conn != NULL, NULL);
3293 g_return_val_if_fail (funcs != NULL, NULL);
3294 g_return_val_if_fail (conn->readfd != NULL, NULL);
3295 g_return_val_if_fail (conn->writefd != NULL, NULL);
3297 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3298 sizeof (GstRTSPWatch));
3300 result->conn = conn;
3301 result->builder.state = STATE_START;
3303 result->mutex = g_mutex_new ();
3304 result->messages = g_queue_new ();
3306 result->readfd.fd = -1;
3307 result->writefd.fd = -1;
3309 gst_rtsp_watch_reset (result);
3311 result->funcs = *funcs;
3312 result->user_data = user_data;
3313 result->notify = notify;
3315 /* only add the read fd, the write fd is only added when we have data
3317 g_source_add_poll ((GSource *) result, &result->readfd);
3323 * gst_rtsp_watch_reset:
3324 * @watch: a #GstRTSPWatch
3326 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3327 * when the file descriptors of the connection might have changed.
3332 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3334 if (watch->readfd.fd != -1)
3335 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3336 if (watch->writefd.fd != -1)
3337 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3339 watch->readfd.fd = watch->conn->readfd->fd;
3340 watch->readfd.events = READ_COND;
3341 watch->readfd.revents = 0;
3343 watch->writefd.fd = watch->conn->writefd->fd;
3344 watch->writefd.events = WRITE_COND;
3345 watch->writefd.revents = 0;
3346 watch->write_added = FALSE;
3348 g_source_add_poll ((GSource *) watch, &watch->readfd);
3352 * gst_rtsp_watch_attach:
3353 * @watch: a #GstRTSPWatch
3354 * @context: a GMainContext (if NULL, the default context will be used)
3356 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3358 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3363 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3365 g_return_val_if_fail (watch != NULL, 0);
3367 return g_source_attach ((GSource *) watch, context);
3371 * gst_rtsp_watch_unref:
3372 * @watch: a #GstRTSPWatch
3374 * Decreases the reference count of @watch by one. If the resulting reference
3375 * count is zero the watch and associated memory will be destroyed.
3380 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3382 g_return_if_fail (watch != NULL);
3384 g_source_unref ((GSource *) watch);
3388 * gst_rtsp_watch_write_data:
3389 * @watch: a #GstRTSPWatch
3390 * @data: the data to queue
3391 * @size: the size of @data
3392 * @id: location for a message ID or %NULL
3394 * Write @data using the connection of the @watch. If it cannot be sent
3395 * immediately, it will be queued for transmission in @watch. The contents of
3396 * @message will then be serialized and transmitted when the connection of the
3397 * @watch becomes writable. In case the @message is queued, the ID returned in
3398 * @id will be non-zero and used as the ID argument in the message_sent
3401 * This function will take ownership of @data and g_free() it after use.
3403 * Returns: #GST_RTSP_OK on success.
3408 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3409 guint size, guint * id)
3415 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3416 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3417 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3419 g_mutex_lock (watch->mutex);
3421 if (watch->messages->length == 0) {
3422 res = write_bytes (watch->writefd.fd, data, &off, size);
3423 if (res != GST_RTSP_EINTR) {
3426 g_free ((gpointer) data);
3431 /* make a record with the data and id */
3432 rec = g_slice_new (GstRTSPRec);
3434 rec->data = (guint8 *) data;
3437 rec->data = g_memdup (data + off, size - off);
3438 rec->size = size - off;
3439 g_free ((gpointer) data);
3443 /* make sure rec->id is never 0 */
3444 rec->id = ++watch->id;
3445 } while (G_UNLIKELY (rec->id == 0));
3447 /* add the record to a queue. FIXME we would like to have an upper limit here */
3448 g_queue_push_head (watch->messages, rec);
3450 /* make sure the main context will now also check for writability on the
3452 if (!watch->write_added) {
3453 g_source_add_poll ((GSource *) watch, &watch->writefd);
3454 watch->write_added = TRUE;
3462 g_mutex_unlock (watch->mutex);
3467 * gst_rtsp_watch_send_message:
3468 * @watch: a #GstRTSPWatch
3469 * @message: a #GstRTSPMessage
3470 * @id: location for a message ID or %NULL
3472 * Send a @message using the connection of the @watch. If it cannot be sent
3473 * immediately, it will be queued for transmission in @watch. The contents of
3474 * @message will then be serialized and transmitted when the connection of the
3475 * @watch becomes writable. In case the @message is queued, the ID returned in
3476 * @id will be non-zero and used as the ID argument in the message_sent
3479 * Returns: #GST_RTSP_OK on success.
3484 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3490 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3491 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3493 /* make a record with the message as a string and id */
3494 str = message_to_string (watch->conn, message);
3496 return gst_rtsp_watch_write_data (watch,
3497 (guint8 *) g_string_free (str, FALSE), size, id);
3501 * gst_rtsp_watch_queue_data:
3502 * @watch: a #GstRTSPWatch
3503 * @data: the data to queue
3504 * @size: the size of @data
3506 * Queue @data for transmission in @watch. It will be transmitted when the
3507 * connection of the @watch becomes writable.
3509 * This function will take ownership of @data and g_free() it after use.
3511 * The return value of this function will be used as the id argument in the
3512 * message_sent callback.
3514 * Deprecated: Use gst_rtsp_watch_write_data()
3520 #ifndef GST_REMOVE_DEPRECATED
3521 #ifdef GST_DISABLE_DEPRECATED
3523 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3527 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3532 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3533 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3534 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3536 g_mutex_lock (watch->mutex);
3538 /* make a record with the data and id */
3539 rec = g_slice_new (GstRTSPRec);
3540 rec->data = (guint8 *) data;
3543 /* make sure rec->id is never 0 */
3544 rec->id = ++watch->id;
3545 } while (G_UNLIKELY (rec->id == 0));
3547 /* add the record to a queue. FIXME we would like to have an upper limit here */
3548 g_queue_push_head (watch->messages, rec);
3550 /* make sure the main context will now also check for writability on the
3552 if (!watch->write_added) {
3553 g_source_add_poll ((GSource *) watch, &watch->writefd);
3554 watch->write_added = TRUE;
3557 g_mutex_unlock (watch->mutex);
3560 #endif /* GST_REMOVE_DEPRECATED */
3563 * gst_rtsp_watch_queue_message:
3564 * @watch: a #GstRTSPWatch
3565 * @message: a #GstRTSPMessage
3567 * Queue a @message for transmission in @watch. The contents of this
3568 * message will be serialized and transmitted when the connection of the
3569 * @watch becomes writable.
3571 * The return value of this function will be used as the id argument in the
3572 * message_sent callback.
3574 * Deprecated: Use gst_rtsp_watch_send_message()
3580 #ifndef GST_REMOVE_DEPRECATED
3581 #ifdef GST_DISABLE_DEPRECATED
3583 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message);
3586 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3591 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3592 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3594 /* make a record with the message as a string and id */
3595 str = message_to_string (watch->conn, message);
3597 return gst_rtsp_watch_queue_data (watch,
3598 (guint8 *) g_string_free (str, FALSE), size);
3600 #endif /* GST_REMOVE_DEPRECATED */