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 */
117 static GstRTSPResult read_line (GstRTSPConnection * conn, guint8 * buffer,
118 guint * idx, guint size);
119 static GstRTSPResult parse_key_value (guint8 * buffer, gchar * key,
120 guint keysize, gchar ** value);
121 static GstRTSPResult parse_string (gchar * dest, gint size, gchar ** src);
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, 0)
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) write (fd, buf, len)
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 gchar tunnelid[TUNNELID_LEN];
184 GstRTSPTunnelState tstate;
189 gchar *initial_buffer;
190 gsize initial_buffer_offset;
193 gint cseq; /* sequence number */
194 gchar session_id[512]; /* session id */
195 gint timeout; /* session timeout in seconds */
196 GTimer *timer; /* timeout timer */
199 GstRTSPAuthMethod auth_method;
202 GHashTable *auth_params;
221 /* a structure for constructing RTSPMessages */
225 GstRTSPResult status;
235 build_reset (GstRTSPBuilder * builder)
237 g_free (builder->body_data);
238 memset (builder, 0, sizeof (GstRTSPBuilder));
242 * gst_rtsp_connection_create:
243 * @url: a #GstRTSPUrl
244 * @conn: storage for a #GstRTSPConnection
246 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
247 * The connection will not yet attempt to connect to @url, use
248 * gst_rtsp_connection_connect().
250 * A copy of @url will be made.
252 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
255 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
257 GstRTSPConnection *newconn;
263 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
266 error = WSAStartup (0x0202, &w);
271 if (w.wVersion != 0x0202)
275 newconn = g_new0 (GstRTSPConnection, 1);
277 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
280 newconn->url = gst_rtsp_url_copy (url);
281 newconn->fd0.fd = -1;
282 newconn->fd1.fd = -1;
283 newconn->timer = g_timer_new ();
284 newconn->timeout = 60;
287 newconn->auth_method = GST_RTSP_AUTH_NONE;
288 newconn->username = NULL;
289 newconn->passwd = NULL;
290 newconn->auth_params = NULL;
300 g_warning ("Error %d on WSAStartup", error);
301 return GST_RTSP_EWSASTART;
305 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
308 return GST_RTSP_EWSAVERSION;
317 return GST_RTSP_ESYS;
322 * gst_rtsp_connection_create_from_fd:
323 * @fd: a file descriptor
324 * @ip: the IP address of the other end
325 * @port: the port used by the other end
326 * @initial_buffer: data already read from @fd
327 * @conn: storage for a #GstRTSPConnection
329 * Create a new #GstRTSPConnection for handling communication on the existing
330 * file descriptor @fd. The @initial_buffer contains any data already read from
331 * @fd which should be used before starting to read new data.
333 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
338 gst_rtsp_connection_create_from_fd (gint fd, const gchar * ip, guint16 port,
339 const gchar * initial_buffer, GstRTSPConnection ** conn)
341 GstRTSPConnection *newconn = NULL;
348 g_return_val_if_fail (fd >= 0, GST_RTSP_EINVAL);
349 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
350 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
352 /* set to non-blocking mode so that we can cancel the communication */
354 fcntl (fd, F_SETFL, O_NONBLOCK);
356 ioctlsocket (fd, FIONBIO, &flags);
357 #endif /* G_OS_WIN32 */
359 /* create a url for the client address */
360 url = g_new0 (GstRTSPUrl, 1);
361 url->host = g_strdup (ip);
364 /* now create the connection object */
365 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
366 gst_rtsp_url_free (url);
368 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
370 /* both read and write initially */
371 newconn->readfd = &newconn->fd0;
372 newconn->writefd = &newconn->fd0;
374 newconn->ip = g_strdup (ip);
376 newconn->initial_buffer = g_strdup (initial_buffer);
385 gst_rtsp_url_free (url);
391 * gst_rtsp_connection_accept:
393 * @conn: storage for a #GstRTSPConnection
395 * Accept a new connection on @sock and create a new #GstRTSPConnection for
396 * handling communication on new socket.
398 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
403 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
406 union gst_sockaddr sa;
407 socklen_t slen = sizeof (sa);
408 gchar ip[INET6_ADDRSTRLEN];
411 g_return_val_if_fail (sock >= 0, GST_RTSP_EINVAL);
412 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
414 memset (&sa, 0, slen);
417 fd = accept (sock, &sa.sa, &slen);
419 fd = accept (sock, &sa.sa, (gint *) & slen);
420 #endif /* G_OS_WIN32 */
424 if (getnameinfo (&sa.sa, slen, ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) != 0)
425 goto getnameinfo_failed;
427 if (sa.sa.sa_family == AF_INET)
428 port = sa.sa_in.sin_port;
429 else if (sa.sa.sa_family == AF_INET6)
430 port = sa.sa_in6.sin6_port;
434 return gst_rtsp_connection_create_from_fd (fd, ip, port, NULL, conn);
439 return GST_RTSP_ESYS;
445 return GST_RTSP_ERROR;
450 do_resolve (const gchar * host)
452 static gchar ip[INET6_ADDRSTRLEN];
453 struct addrinfo *aires;
457 aierr = getaddrinfo (host, NULL, NULL, &aires);
461 for (ai = aires; ai; ai = ai->ai_next) {
462 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
469 aierr = getnameinfo (ai->ai_addr, ai->ai_addrlen, ip, sizeof (ip), NULL, 0,
470 NI_NUMERICHOST | NI_NUMERICSERV);
474 freeaddrinfo (aires);
476 return g_strdup (ip);
481 GST_ERROR ("no addrinfo found for %s: %s", host, gai_strerror (aierr));
486 GST_ERROR ("no family found for %s", host);
487 freeaddrinfo (aires);
492 GST_ERROR ("no address found for %s: %s", host, gai_strerror (aierr));
493 freeaddrinfo (aires);
499 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
500 GstPoll * fdset, GTimeVal * timeout)
503 struct addrinfo hints;
504 struct addrinfo *aires;
507 gchar service[NI_MAXSERV];
510 unsigned long flags = 1;
511 #endif /* G_OS_WIN32 */
515 memset (&hints, 0, sizeof hints);
516 hints.ai_flags = AI_NUMERICHOST;
517 hints.ai_family = AF_UNSPEC;
518 hints.ai_socktype = SOCK_STREAM;
519 g_snprintf (service, sizeof (service) - 1, "%hu", port);
520 service[sizeof (service) - 1] = '\0';
522 aierr = getaddrinfo (ip, service, &hints, &aires);
526 for (ai = aires; ai; ai = ai->ai_next) {
527 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
534 fd = socket (ai->ai_family, SOCK_STREAM, 0);
538 /* set to non-blocking mode so that we can cancel the connect */
540 fcntl (fd, F_SETFL, O_NONBLOCK);
542 ioctlsocket (fd, FIONBIO, &flags);
543 #endif /* G_OS_WIN32 */
545 /* add the socket to our fdset */
546 ADD_POLLFD (fdset, fdout, fd);
548 /* we are going to connect ASYNC now */
549 ret = connect (fd, ai->ai_addr, ai->ai_addrlen);
552 if (!ERRNO_IS_EINPROGRESS)
555 /* wait for connect to complete up to the specified timeout or until we got
557 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
559 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
562 retval = gst_poll_wait (fdset, to);
563 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
567 else if (retval == -1)
570 /* we can still have an error connecting on windows */
571 if (gst_poll_fd_has_error (fdset, fdout)) {
572 socklen_t len = sizeof (errno);
574 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
576 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
581 gst_poll_fd_ignored (fdset, fdout);
584 freeaddrinfo (aires);
591 GST_ERROR ("no addrinfo found for %s: %s", ip, gai_strerror (aierr));
592 return GST_RTSP_ERROR;
596 GST_ERROR ("no family found for %s", ip);
597 freeaddrinfo (aires);
598 return GST_RTSP_ERROR;
602 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
603 freeaddrinfo (aires);
604 return GST_RTSP_ESYS;
608 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
609 REMOVE_POLLFD (fdset, fdout);
610 freeaddrinfo (aires);
611 return GST_RTSP_ESYS;
615 GST_ERROR ("timeout");
616 REMOVE_POLLFD (fdset, fdout);
617 freeaddrinfo (aires);
618 return GST_RTSP_ETIMEOUT;
623 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
630 guint16 port, url_port;
634 GstRTSPMessage response;
636 memset (&response, 0, sizeof (response));
637 gst_rtsp_message_init (&response);
639 /* create a random sessionid */
640 for (i = 0; i < TUNNELID_LEN; i++)
641 conn->tunnelid[i] = g_random_int_range ('a', 'z');
642 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
645 /* get the port from the url */
646 gst_rtsp_url_get_port (url, &url_port);
648 if (conn->proxy_host) {
649 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
650 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
651 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
652 ip = conn->proxy_host;
653 port = conn->proxy_port;
655 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
656 url->query ? url->query : "");
662 /* create the GET request for the read connection */
663 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
665 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
667 if (hostparam != NULL)
668 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
669 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
671 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
672 "application/x-rtsp-tunnelled");
673 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
674 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
676 /* we start by writing to this fd */
677 conn->writefd = &conn->fd0;
679 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
680 * request from being base64 encoded */
681 conn->tunneled = FALSE;
682 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
683 gst_rtsp_message_free (msg);
684 conn->tunneled = TRUE;
686 /* receive the response to the GET request */
687 /* we need to temporarily set manual_http to TRUE since
688 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
689 * failure otherwise */
690 conn->manual_http = TRUE;
691 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
693 conn->manual_http = FALSE;
695 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
696 response.type_data.response.code != GST_RTSP_STS_OK)
699 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
700 &value, 0) != GST_RTSP_OK) {
701 if (conn->proxy_host) {
702 /* if we use a proxy we need to change the destination url */
704 url->host = g_strdup (value);
706 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
708 /* and resolve the new ip address */
709 if (!(ip = do_resolve (conn->ip)))
716 /* connect to the host/port */
717 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
718 if (res != GST_RTSP_OK)
721 /* this is now our writing socket */
722 conn->writefd = &conn->fd1;
724 /* create the POST request for the write connection */
725 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
727 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
729 if (hostparam != NULL)
730 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
731 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
733 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
734 "application/x-rtsp-tunnelled");
735 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
736 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
737 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
738 "Sun, 9 Jan 1972 00:00:00 GMT");
739 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
741 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
742 * request from being base64 encoded */
743 conn->tunneled = FALSE;
744 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
745 gst_rtsp_message_free (msg);
746 conn->tunneled = TRUE;
749 gst_rtsp_message_unset (&response);
758 GST_ERROR ("failed to create request (%d)", res);
763 GST_ERROR ("write failed (%d)", res);
764 gst_rtsp_message_free (msg);
765 conn->tunneled = TRUE;
770 GST_ERROR ("read failed (%d)", res);
771 conn->manual_http = FALSE;
776 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
777 response.type_data.response.reason);
778 res = GST_RTSP_ERROR;
783 GST_ERROR ("could not resolve %s", conn->ip);
789 GST_ERROR ("failed to connect");
795 * gst_rtsp_connection_connect:
796 * @conn: a #GstRTSPConnection
797 * @timeout: a #GTimeVal timeout
799 * Attempt to connect to the url of @conn made with
800 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
801 * forever. If @timeout contains a valid timeout, this function will return
802 * #GST_RTSP_ETIMEOUT after the timeout expired.
804 * This function can be cancelled with gst_rtsp_connection_flush().
806 * Returns: #GST_RTSP_OK when a connection could be made.
809 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
816 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
817 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
818 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
822 if (conn->proxy_host && conn->tunneled) {
823 if (!(ip = do_resolve (conn->proxy_host))) {
824 GST_ERROR ("could not resolve %s", conn->proxy_host);
827 port = conn->proxy_port;
828 g_free (conn->proxy_host);
829 conn->proxy_host = ip;
831 if (!(ip = do_resolve (url->host))) {
832 GST_ERROR ("could not resolve %s", url->host);
835 /* get the port from the url */
836 gst_rtsp_url_get_port (url, &port);
842 /* connect to the host/port */
843 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
844 if (res != GST_RTSP_OK)
847 /* this is our read URL */
848 conn->readfd = &conn->fd0;
850 if (conn->tunneled) {
851 res = setup_tunneling (conn, timeout);
852 if (res != GST_RTSP_OK)
853 goto tunneling_failed;
855 conn->writefd = &conn->fd0;
862 return GST_RTSP_ENET;
866 GST_ERROR ("failed to connect");
871 GST_ERROR ("failed to setup tunneling");
877 auth_digest_compute_hex_urp (const gchar * username,
878 const gchar * realm, const gchar * password, gchar hex_urp[33])
880 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
881 const gchar *digest_string;
883 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
884 g_checksum_update (md5_context, (const guchar *) ":", 1);
885 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
886 g_checksum_update (md5_context, (const guchar *) ":", 1);
887 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
888 digest_string = g_checksum_get_string (md5_context);
890 memset (hex_urp, 0, 33);
891 memcpy (hex_urp, digest_string, strlen (digest_string));
893 g_checksum_free (md5_context);
897 auth_digest_compute_response (const gchar * method,
898 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
901 char hex_a2[33] = { 0, };
902 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
903 const gchar *digest_string;
906 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
907 g_checksum_update (md5_context, (const guchar *) ":", 1);
908 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
909 digest_string = g_checksum_get_string (md5_context);
910 memcpy (hex_a2, digest_string, strlen (digest_string));
913 #if GLIB_CHECK_VERSION (2, 18, 0)
914 g_checksum_reset (md5_context);
916 g_checksum_free (md5_context);
917 md5_context = g_checksum_new (G_CHECKSUM_MD5);
919 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
920 g_checksum_update (md5_context, (const guchar *) ":", 1);
921 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
922 g_checksum_update (md5_context, (const guchar *) ":", 1);
924 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
925 digest_string = g_checksum_get_string (md5_context);
926 memset (response, 0, 33);
927 memcpy (response, digest_string, strlen (digest_string));
929 g_checksum_free (md5_context);
933 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
935 switch (conn->auth_method) {
936 case GST_RTSP_AUTH_BASIC:{
941 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
942 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
943 auth_string = g_strdup_printf ("Basic %s", user_pass64);
945 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
949 g_free (user_pass64);
952 case GST_RTSP_AUTH_DIGEST:{
953 gchar response[33], hex_urp[33];
954 gchar *auth_string, *auth_string2;
961 /* we need to have some params set */
962 if (conn->auth_params == NULL)
965 /* we need the realm and nonce */
966 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
967 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
968 if (realm == NULL || nonce == NULL)
971 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
974 method = gst_rtsp_method_as_text (message->type_data.request.method);
975 uri = message->type_data.request.uri;
977 /* Assume no qop, algorithm=md5, stale=false */
978 /* For algorithm MD5, a1 = urp. */
979 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
980 auth_string = g_strdup_printf ("Digest username=\"%s\", "
981 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
982 conn->username, realm, nonce, uri, response);
984 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
986 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
988 g_free (auth_string);
989 auth_string = auth_string2;
991 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1002 gen_date_string (gchar * date_string, guint len)
1006 #ifdef HAVE_GMTIME_R
1010 g_get_current_time (&tv);
1011 t = (time_t) tv.tv_sec;
1013 #ifdef HAVE_GMTIME_R
1014 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1016 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1020 static GstRTSPResult
1021 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1025 if (G_UNLIKELY (*idx > size))
1026 return GST_RTSP_ERROR;
1033 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1034 if (G_UNLIKELY (r == 0)) {
1035 return GST_RTSP_EINTR;
1036 } else if (G_UNLIKELY (r < 0)) {
1037 if (ERRNO_IS_EAGAIN)
1038 return GST_RTSP_EINTR;
1039 if (!ERRNO_IS_EINTR)
1040 return GST_RTSP_ESYS;
1050 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1054 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1055 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1057 out = MIN (left, size);
1058 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1060 if (left == (gsize) out) {
1061 g_free (conn->initial_buffer);
1062 conn->initial_buffer = NULL;
1063 conn->initial_buffer_offset = 0;
1065 conn->initial_buffer_offset += out;
1068 if (G_LIKELY (size > (guint) out)) {
1071 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1083 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1085 DecodeCtx *ctx = conn->ctxp;
1090 guint8 in[sizeof (ctx->out) * 4 / 3];
1093 while (size > 0 && ctx->cout < ctx->coutl) {
1094 /* we have some leftover bytes */
1095 *buffer++ = ctx->out[ctx->cout++];
1100 /* got what we needed? */
1104 /* try to read more bytes */
1105 r = fill_raw_bytes (conn, in, sizeof (in));
1114 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1118 out = fill_raw_bytes (conn, buffer, size);
1124 static GstRTSPResult
1125 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1129 if (G_UNLIKELY (*idx > size))
1130 return GST_RTSP_ERROR;
1137 r = fill_bytes (conn, &buffer[*idx], left);
1138 if (G_UNLIKELY (r == 0)) {
1139 return GST_RTSP_EEOF;
1140 } else if (G_UNLIKELY (r < 0)) {
1141 if (ERRNO_IS_EAGAIN)
1142 return GST_RTSP_EINTR;
1143 if (!ERRNO_IS_EINTR)
1144 return GST_RTSP_ESYS;
1153 static GstRTSPResult
1154 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1160 r = fill_bytes (conn, &c, 1);
1161 if (G_UNLIKELY (r == 0)) {
1162 return GST_RTSP_EEOF;
1163 } else if (G_UNLIKELY (r < 0)) {
1164 if (ERRNO_IS_EAGAIN)
1165 return GST_RTSP_EINTR;
1166 if (!ERRNO_IS_EINTR)
1167 return GST_RTSP_ESYS;
1169 if (c == '\n') /* end on \n */
1171 if (c == '\r') /* ignore \r */
1174 if (G_LIKELY (*idx < size - 1))
1175 buffer[(*idx)++] = c;
1178 buffer[*idx] = '\0';
1184 * gst_rtsp_connection_write:
1185 * @conn: a #GstRTSPConnection
1186 * @data: the data to write
1187 * @size: the size of @data
1188 * @timeout: a timeout value or #NULL
1190 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1191 * the specified @timeout. @timeout can be #NULL, in which case this function
1192 * might block forever.
1194 * This function can be cancelled with gst_rtsp_connection_flush().
1196 * Returns: #GST_RTSP_OK on success.
1199 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1200 guint size, GTimeVal * timeout)
1207 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1208 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1209 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1211 gst_poll_set_controllable (conn->fdset, TRUE);
1212 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1213 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1214 /* clear all previous poll results */
1215 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1216 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1218 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1224 res = write_bytes (conn->writefd->fd, data, &offset, size);
1225 if (G_LIKELY (res == GST_RTSP_OK))
1227 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1230 /* not all is written, wait until we can write more */
1232 retval = gst_poll_wait (conn->fdset, to);
1233 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1235 if (G_UNLIKELY (retval == 0))
1238 if (G_UNLIKELY (retval == -1)) {
1250 return GST_RTSP_ETIMEOUT;
1254 return GST_RTSP_ESYS;
1258 return GST_RTSP_EINTR;
1267 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1269 GString *str = NULL;
1271 str = g_string_new ("");
1273 switch (message->type) {
1274 case GST_RTSP_MESSAGE_REQUEST:
1275 /* create request string, add CSeq */
1276 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1278 gst_rtsp_method_as_text (message->type_data.request.method),
1279 message->type_data.request.uri, conn->cseq++);
1280 /* add session id if we have one */
1281 if (conn->session_id[0] != '\0') {
1282 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1283 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1286 /* add any authentication headers */
1287 add_auth_header (conn, message);
1289 case GST_RTSP_MESSAGE_RESPONSE:
1290 /* create response string */
1291 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1292 message->type_data.response.code, message->type_data.response.reason);
1294 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1295 /* create request string */
1296 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1297 gst_rtsp_method_as_text (message->type_data.request.method),
1298 message->type_data.request.uri,
1299 gst_rtsp_version_as_text (message->type_data.request.version));
1300 /* add any authentication headers */
1301 add_auth_header (conn, message);
1303 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1304 /* create response string */
1305 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1306 gst_rtsp_version_as_text (message->type_data.request.version),
1307 message->type_data.response.code, message->type_data.response.reason);
1309 case GST_RTSP_MESSAGE_DATA:
1311 guint8 data_header[4];
1313 /* prepare data header */
1314 data_header[0] = '$';
1315 data_header[1] = message->type_data.data.channel;
1316 data_header[2] = (message->body_size >> 8) & 0xff;
1317 data_header[3] = message->body_size & 0xff;
1319 /* create string with header and data */
1320 str = g_string_append_len (str, (gchar *) data_header, 4);
1322 g_string_append_len (str, (gchar *) message->body,
1323 message->body_size);
1327 g_string_free (str, TRUE);
1328 g_return_val_if_reached (NULL);
1332 /* append headers and body */
1333 if (message->type != GST_RTSP_MESSAGE_DATA) {
1334 gchar date_string[100];
1336 gen_date_string (date_string, sizeof (date_string));
1338 /* add date header */
1339 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1340 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1342 /* append headers */
1343 gst_rtsp_message_append_headers (message, str);
1345 /* append Content-Length and body if needed */
1346 if (message->body != NULL && message->body_size > 0) {
1349 len = g_strdup_printf ("%d", message->body_size);
1350 g_string_append_printf (str, "%s: %s\r\n",
1351 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1353 /* header ends here */
1354 g_string_append (str, "\r\n");
1356 g_string_append_len (str, (gchar *) message->body,
1357 message->body_size);
1359 /* just end headers */
1360 g_string_append (str, "\r\n");
1368 * gst_rtsp_connection_send:
1369 * @conn: a #GstRTSPConnection
1370 * @message: the message to send
1371 * @timeout: a timeout value or #NULL
1373 * Attempt to send @message to the connected @conn, blocking up to
1374 * the specified @timeout. @timeout can be #NULL, in which case this function
1375 * might block forever.
1377 * This function can be cancelled with gst_rtsp_connection_flush().
1379 * Returns: #GST_RTSP_OK on success.
1382 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1385 GString *string = NULL;
1390 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1391 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1393 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1396 if (conn->tunneled) {
1397 str = g_base64_encode ((const guchar *) string->str, string->len);
1398 g_string_free (string, TRUE);
1403 g_string_free (string, FALSE);
1407 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1415 g_warning ("Wrong message");
1416 return GST_RTSP_EINVAL;
1420 static GstRTSPResult
1421 parse_string (gchar * dest, gint size, gchar ** src)
1423 GstRTSPResult res = GST_RTSP_OK;
1428 while (g_ascii_isspace (**src))
1431 while (!g_ascii_isspace (**src) && **src != '\0') {
1433 dest[idx++] = **src;
1435 res = GST_RTSP_EPARSE;
1445 parse_key (gchar * dest, gint size, gchar ** src)
1450 while (**src != ':' && **src != '\0') {
1452 dest[idx++] = **src;
1459 static GstRTSPResult
1460 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1461 GstRTSPVersion * version)
1463 GstRTSPResult res = GST_RTSP_OK;
1466 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1473 /* the version number must be formatted as X.Y with nothing following */
1474 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1475 res = GST_RTSP_EPARSE;
1477 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1478 if (major != 1 || minor != 0) {
1479 *version = GST_RTSP_VERSION_INVALID;
1480 res = GST_RTSP_ERROR;
1482 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1483 if (*type == GST_RTSP_MESSAGE_REQUEST)
1484 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1485 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1486 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1488 if (major == 1 && minor == 1) {
1489 *version = GST_RTSP_VERSION_1_1;
1490 } else if (major != 1 || minor != 0) {
1491 *version = GST_RTSP_VERSION_INVALID;
1492 res = GST_RTSP_ERROR;
1495 res = GST_RTSP_EPARSE;
1497 res = GST_RTSP_EPARSE;
1502 static GstRTSPResult
1503 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1505 GstRTSPResult res = GST_RTSP_OK;
1507 gchar versionstr[20];
1512 bptr = (gchar *) buffer;
1514 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1515 res = GST_RTSP_EPARSE;
1517 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1518 res = GST_RTSP_EPARSE;
1519 code = atoi (codestr);
1520 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1521 res = GST_RTSP_EPARSE;
1523 while (g_ascii_isspace (*bptr))
1526 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1527 NULL) != GST_RTSP_OK))
1528 res = GST_RTSP_EPARSE;
1530 res2 = parse_protocol_version (versionstr, &msg->type,
1531 &msg->type_data.response.version);
1532 if (G_LIKELY (res == GST_RTSP_OK))
1538 static GstRTSPResult
1539 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1541 GstRTSPResult res = GST_RTSP_OK;
1543 gchar versionstr[20];
1544 gchar methodstr[20];
1547 GstRTSPMethod method;
1549 bptr = (gchar *) buffer;
1551 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1552 res = GST_RTSP_EPARSE;
1553 method = gst_rtsp_find_method (methodstr);
1555 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1556 res = GST_RTSP_EPARSE;
1557 if (G_UNLIKELY (*urlstr == '\0'))
1558 res = GST_RTSP_EPARSE;
1560 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1561 res = GST_RTSP_EPARSE;
1563 if (G_UNLIKELY (*bptr != '\0'))
1564 res = GST_RTSP_EPARSE;
1566 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1567 urlstr) != GST_RTSP_OK))
1568 res = GST_RTSP_EPARSE;
1570 res2 = parse_protocol_version (versionstr, &msg->type,
1571 &msg->type_data.request.version);
1572 if (G_LIKELY (res == GST_RTSP_OK))
1575 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1576 /* GET and POST are not allowed as RTSP methods */
1577 if (msg->type_data.request.method == GST_RTSP_GET ||
1578 msg->type_data.request.method == GST_RTSP_POST) {
1579 msg->type_data.request.method = GST_RTSP_INVALID;
1580 if (res == GST_RTSP_OK)
1581 res = GST_RTSP_ERROR;
1583 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1584 /* only GET and POST are allowed as HTTP methods */
1585 if (msg->type_data.request.method != GST_RTSP_GET &&
1586 msg->type_data.request.method != GST_RTSP_POST) {
1587 msg->type_data.request.method = GST_RTSP_INVALID;
1588 if (res == GST_RTSP_OK)
1589 res = GST_RTSP_ERROR;
1596 static GstRTSPResult
1597 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1601 bptr = (gchar *) buffer;
1604 parse_key (key, keysize, &bptr);
1605 if (G_UNLIKELY (*bptr != ':'))
1609 while (g_ascii_isspace (*bptr))
1619 return GST_RTSP_EPARSE;
1623 /* parsing lines means reading a Key: Value pair */
1624 static GstRTSPResult
1625 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1630 GstRTSPHeaderField field;
1632 res = parse_key_value (buffer, key, sizeof (key), &value);
1633 if (G_UNLIKELY (res != GST_RTSP_OK))
1636 field = gst_rtsp_find_header_field (key);
1637 if (field != GST_RTSP_HDR_INVALID)
1638 gst_rtsp_message_add_header (msg, field, value);
1649 /* convert all consecutive whitespace to a single space */
1651 normalize_line (guint8 * buffer)
1654 if (g_ascii_isspace (*buffer)) {
1658 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1661 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1669 * GST_RTSP_OK when a complete message was read.
1670 * GST_RTSP_EEOF: when the socket is closed
1671 * GST_RTSP_EINTR: when more data is needed.
1672 * GST_RTSP_..: some other error occured.
1674 static GstRTSPResult
1675 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1676 GstRTSPConnection * conn)
1681 switch (builder->state) {
1683 builder->offset = 0;
1685 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1686 if (res != GST_RTSP_OK)
1689 /* we have 1 bytes now and we can see if this is a data message or
1691 if (builder->buffer[0] == '$') {
1692 /* data message, prepare for the header */
1693 builder->state = STATE_DATA_HEADER;
1696 builder->state = STATE_READ_LINES;
1699 case STATE_DATA_HEADER:
1702 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1703 if (res != GST_RTSP_OK)
1706 gst_rtsp_message_init_data (message, builder->buffer[1]);
1708 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1709 builder->body_data = g_malloc (builder->body_len + 1);
1710 builder->body_data[builder->body_len] = '\0';
1711 builder->offset = 0;
1712 builder->state = STATE_DATA_BODY;
1715 case STATE_DATA_BODY:
1718 read_bytes (conn, builder->body_data, &builder->offset,
1720 if (res != GST_RTSP_OK)
1723 /* we have the complete body now, store in the message adjusting the
1724 * length to include the traling '\0' */
1725 gst_rtsp_message_take_body (message,
1726 (guint8 *) builder->body_data, builder->body_len + 1);
1727 builder->body_data = NULL;
1728 builder->body_len = 0;
1730 builder->state = STATE_END;
1733 case STATE_READ_LINES:
1735 res = read_line (conn, builder->buffer, &builder->offset,
1736 sizeof (builder->buffer));
1737 if (res != GST_RTSP_OK)
1740 /* we have a regular response */
1741 if (builder->buffer[0] == '\r') {
1742 builder->buffer[0] = '\0';
1745 if (builder->buffer[0] == '\0') {
1748 /* empty line, end of message header */
1749 /* see if there is a Content-Length header, but ignore it if this
1750 * is a POST request with an x-sessioncookie header */
1751 if (gst_rtsp_message_get_header (message,
1752 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1753 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1754 message->type_data.request.method != GST_RTSP_POST ||
1755 gst_rtsp_message_get_header (message,
1756 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1757 /* there is, prepare to read the body */
1758 builder->body_len = atol (hdrval);
1759 builder->body_data = g_malloc (builder->body_len + 1);
1760 builder->body_data[builder->body_len] = '\0';
1761 builder->offset = 0;
1762 builder->state = STATE_DATA_BODY;
1764 builder->state = STATE_END;
1769 /* we have a line */
1770 normalize_line (builder->buffer);
1771 if (builder->line == 0) {
1772 /* first line, check for response status */
1773 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1774 memcmp (builder->buffer, "HTTP", 4) == 0) {
1775 builder->status = parse_response_status (builder->buffer, message);
1777 builder->status = parse_request_line (builder->buffer, message);
1780 /* else just parse the line */
1781 res = parse_line (builder->buffer, message);
1782 if (res != GST_RTSP_OK)
1783 builder->status = res;
1786 builder->offset = 0;
1791 gchar *session_cookie;
1794 if (message->type == GST_RTSP_MESSAGE_DATA) {
1795 /* data messages don't have headers */
1800 /* save the tunnel session in the connection */
1801 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1802 !conn->manual_http &&
1803 conn->tstate == TUNNEL_STATE_NONE &&
1804 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1805 &session_cookie, 0) == GST_RTSP_OK) {
1806 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1807 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1808 conn->tunneled = TRUE;
1811 /* save session id in the connection for further use */
1812 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1813 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1814 &session_id, 0) == GST_RTSP_OK) {
1817 maxlen = sizeof (conn->session_id) - 1;
1818 /* the sessionid can have attributes marked with ;
1819 * Make sure we strip them */
1820 for (i = 0; session_id[i] != '\0'; i++) {
1821 if (session_id[i] == ';') {
1826 } while (g_ascii_isspace (session_id[i]));
1827 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1830 /* if we parsed something valid, configure */
1831 if ((to = atoi (&session_id[i + 8])) > 0)
1838 /* make sure to not overflow */
1839 strncpy (conn->session_id, session_id, maxlen);
1840 conn->session_id[maxlen] = '\0';
1842 res = builder->status;
1846 res = GST_RTSP_ERROR;
1855 * gst_rtsp_connection_read:
1856 * @conn: a #GstRTSPConnection
1857 * @data: the data to read
1858 * @size: the size of @data
1859 * @timeout: a timeout value or #NULL
1861 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1862 * the specified @timeout. @timeout can be #NULL, in which case this function
1863 * might block forever.
1865 * This function can be cancelled with gst_rtsp_connection_flush().
1867 * Returns: #GST_RTSP_OK on success.
1870 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1878 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1879 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1880 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1882 if (G_UNLIKELY (size == 0))
1887 /* configure timeout if any */
1888 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1890 gst_poll_set_controllable (conn->fdset, TRUE);
1891 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1892 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1895 res = read_bytes (conn, data, &offset, size);
1896 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1898 if (G_LIKELY (res == GST_RTSP_OK))
1900 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1904 retval = gst_poll_wait (conn->fdset, to);
1905 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1907 /* check for timeout */
1908 if (G_UNLIKELY (retval == 0))
1909 goto select_timeout;
1911 if (G_UNLIKELY (retval == -1)) {
1917 gst_poll_set_controllable (conn->fdset, FALSE);
1924 return GST_RTSP_ESYS;
1928 return GST_RTSP_ETIMEOUT;
1932 return GST_RTSP_EINTR;
1936 return GST_RTSP_EEOF;
1944 static GstRTSPMessage *
1945 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
1946 const GstRTSPMessage * request)
1948 GstRTSPMessage *msg;
1951 if (gst_rtsp_status_as_text (code) == NULL)
1952 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1954 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
1957 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
1958 "GStreamer RTSP Server");
1959 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
1960 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
1961 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
1963 if (code == GST_RTSP_STS_OK) {
1965 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
1967 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
1968 "application/x-rtsp-tunnelled");
1981 * gst_rtsp_connection_receive:
1982 * @conn: a #GstRTSPConnection
1983 * @message: the message to read
1984 * @timeout: a timeout value or #NULL
1986 * Attempt to read into @message from the connected @conn, blocking up to
1987 * the specified @timeout. @timeout can be #NULL, in which case this function
1988 * might block forever.
1990 * This function can be cancelled with gst_rtsp_connection_flush().
1992 * Returns: #GST_RTSP_OK on success.
1995 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1999 GstRTSPBuilder builder;
2003 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2004 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2005 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2007 /* configure timeout if any */
2008 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2010 gst_poll_set_controllable (conn->fdset, TRUE);
2011 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2012 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2014 memset (&builder, 0, sizeof (GstRTSPBuilder));
2016 res = build_next (&builder, message, conn);
2017 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2019 else if (G_LIKELY (res == GST_RTSP_OK)) {
2020 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2021 if (conn->tstate == TUNNEL_STATE_NONE &&
2022 message->type_data.request.method == GST_RTSP_GET) {
2023 GstRTSPMessage *response;
2025 conn->tstate = TUNNEL_STATE_GET;
2027 /* tunnel GET request, we can reply now */
2028 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2029 res = gst_rtsp_connection_send (conn, response, timeout);
2030 gst_rtsp_message_free (response);
2031 if (res == GST_RTSP_OK)
2032 res = GST_RTSP_ETGET;
2034 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2035 message->type_data.request.method == GST_RTSP_POST) {
2036 conn->tstate = TUNNEL_STATE_POST;
2038 /* tunnel POST request, the caller now has to link the two
2040 res = GST_RTSP_ETPOST;
2043 res = GST_RTSP_EPARSE;
2049 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2053 retval = gst_poll_wait (conn->fdset, to);
2054 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2056 /* check for timeout */
2057 if (G_UNLIKELY (retval == 0))
2058 goto select_timeout;
2060 if (G_UNLIKELY (retval == -1)) {
2066 gst_poll_set_controllable (conn->fdset, FALSE);
2069 /* we have a message here */
2070 build_reset (&builder);
2077 res = GST_RTSP_ESYS;
2082 res = GST_RTSP_ETIMEOUT;
2087 res = GST_RTSP_EINTR;
2092 res = GST_RTSP_EEOF;
2098 build_reset (&builder);
2099 gst_rtsp_message_unset (message);
2105 * gst_rtsp_connection_close:
2106 * @conn: a #GstRTSPConnection
2108 * Close the connected @conn. After this call, the connection is in the same
2109 * state as when it was first created.
2111 * Returns: #GST_RTSP_OK on success.
2114 gst_rtsp_connection_close (GstRTSPConnection * conn)
2116 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2121 g_free (conn->initial_buffer);
2122 conn->initial_buffer = NULL;
2123 conn->initial_buffer_offset = 0;
2125 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2126 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2127 conn->writefd = NULL;
2128 conn->readfd = NULL;
2129 conn->tunneled = FALSE;
2130 conn->tstate = TUNNEL_STATE_NONE;
2132 g_free (conn->username);
2133 conn->username = NULL;
2134 g_free (conn->passwd);
2135 conn->passwd = NULL;
2136 gst_rtsp_connection_clear_auth_params (conn);
2139 conn->session_id[0] = '\0';
2145 * gst_rtsp_connection_free:
2146 * @conn: a #GstRTSPConnection
2148 * Close and free @conn.
2150 * Returns: #GST_RTSP_OK on success.
2153 gst_rtsp_connection_free (GstRTSPConnection * conn)
2157 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2159 res = gst_rtsp_connection_close (conn);
2160 gst_poll_free (conn->fdset);
2161 g_timer_destroy (conn->timer);
2162 gst_rtsp_url_free (conn->url);
2163 g_free (conn->proxy_host);
2173 * gst_rtsp_connection_poll:
2174 * @conn: a #GstRTSPConnection
2175 * @events: a bitmask of #GstRTSPEvent flags to check
2176 * @revents: location for result flags
2177 * @timeout: a timeout
2179 * Wait up to the specified @timeout for the connection to become available for
2180 * at least one of the operations specified in @events. When the function returns
2181 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2184 * @timeout can be #NULL, in which case this function might block forever.
2186 * This function can be cancelled with gst_rtsp_connection_flush().
2188 * Returns: #GST_RTSP_OK on success.
2193 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2194 GstRTSPEvent * revents, GTimeVal * timeout)
2199 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2200 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2201 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2202 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2203 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2205 gst_poll_set_controllable (conn->fdset, TRUE);
2207 /* add fd to writer set when asked to */
2208 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2209 events & GST_RTSP_EV_WRITE);
2211 /* add fd to reader set when asked to */
2212 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2214 /* configure timeout if any */
2215 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2218 retval = gst_poll_wait (conn->fdset, to);
2219 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2221 if (G_UNLIKELY (retval == 0))
2222 goto select_timeout;
2224 if (G_UNLIKELY (retval == -1)) {
2232 if (events & GST_RTSP_EV_READ) {
2233 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2234 *revents |= GST_RTSP_EV_READ;
2236 if (events & GST_RTSP_EV_WRITE) {
2237 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2238 *revents |= GST_RTSP_EV_WRITE;
2245 return GST_RTSP_ETIMEOUT;
2249 return GST_RTSP_ESYS;
2253 return GST_RTSP_EINTR;
2258 * gst_rtsp_connection_next_timeout:
2259 * @conn: a #GstRTSPConnection
2260 * @timeout: a timeout
2262 * Calculate the next timeout for @conn, storing the result in @timeout.
2264 * Returns: #GST_RTSP_OK.
2267 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2273 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2274 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2276 elapsed = g_timer_elapsed (conn->timer, &usec);
2277 if (elapsed >= conn->timeout) {
2281 sec = conn->timeout - elapsed;
2284 timeout->tv_sec = sec;
2285 timeout->tv_usec = usec;
2291 * gst_rtsp_connection_reset_timeout:
2292 * @conn: a #GstRTSPConnection
2294 * Reset the timeout of @conn.
2296 * Returns: #GST_RTSP_OK.
2299 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2301 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2303 g_timer_start (conn->timer);
2309 * gst_rtsp_connection_flush:
2310 * @conn: a #GstRTSPConnection
2311 * @flush: start or stop the flush
2313 * Start or stop the flushing action on @conn. When flushing, all current
2314 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2315 * is set to non-flushing mode again.
2317 * Returns: #GST_RTSP_OK.
2320 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2322 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2324 gst_poll_set_flushing (conn->fdset, flush);
2330 * gst_rtsp_connection_set_proxy:
2331 * @conn: a #GstRTSPConnection
2332 * @host: the proxy host
2333 * @port: the proxy port
2335 * Set the proxy host and port.
2337 * Returns: #GST_RTSP_OK.
2342 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2343 const gchar * host, guint port)
2345 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2347 g_free (conn->proxy_host);
2348 conn->proxy_host = g_strdup (host);
2349 conn->proxy_port = port;
2355 * gst_rtsp_connection_set_auth:
2356 * @conn: a #GstRTSPConnection
2357 * @method: authentication method
2359 * @pass: the password
2361 * Configure @conn for authentication mode @method with @user and @pass as the
2362 * user and password respectively.
2364 * Returns: #GST_RTSP_OK.
2367 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2368 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2370 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2372 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2373 || g_strrstr (user, ":") != NULL))
2374 return GST_RTSP_EINVAL;
2376 /* Make sure the username and passwd are being set for authentication */
2377 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2378 return GST_RTSP_EINVAL;
2380 /* ":" chars are not allowed in usernames for basic auth */
2381 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2382 return GST_RTSP_EINVAL;
2384 g_free (conn->username);
2385 g_free (conn->passwd);
2387 conn->auth_method = method;
2388 conn->username = g_strdup (user);
2389 conn->passwd = g_strdup (pass);
2396 * @key: ASCII string to hash
2398 * Hashes @key in a case-insensitive manner.
2400 * Returns: the hash code.
2403 str_case_hash (gconstpointer key)
2405 const char *p = key;
2406 guint h = g_ascii_toupper (*p);
2409 for (p += 1; *p != '\0'; p++)
2410 h = (h << 5) - h + g_ascii_toupper (*p);
2417 * @v1: an ASCII string
2418 * @v2: another ASCII string
2420 * Compares @v1 and @v2 in a case-insensitive manner
2422 * Returns: %TRUE if they are equal (modulo case)
2425 str_case_equal (gconstpointer v1, gconstpointer v2)
2427 const char *string1 = v1;
2428 const char *string2 = v2;
2430 return g_ascii_strcasecmp (string1, string2) == 0;
2434 * gst_rtsp_connection_set_auth_param:
2435 * @conn: a #GstRTSPConnection
2436 * @param: authentication directive
2439 * Setup @conn with authentication directives. This is not necesary for
2440 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2441 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2442 * in the WWW-Authenticate response header and can include realm, domain,
2443 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2448 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2449 const gchar * param, const gchar * value)
2451 g_return_if_fail (conn != NULL);
2452 g_return_if_fail (param != NULL);
2454 if (conn->auth_params == NULL) {
2456 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2458 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2462 * gst_rtsp_connection_clear_auth_params:
2463 * @conn: a #GstRTSPConnection
2465 * Clear the list of authentication directives stored in @conn.
2470 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2472 g_return_if_fail (conn != NULL);
2474 if (conn->auth_params != NULL) {
2475 g_hash_table_destroy (conn->auth_params);
2476 conn->auth_params = NULL;
2480 static GstRTSPResult
2481 set_qos_dscp (gint fd, guint qos_dscp)
2483 union gst_sockaddr sa;
2484 socklen_t slen = sizeof (sa);
2491 if (getsockname (fd, &sa.sa, &slen) < 0)
2492 goto no_getsockname;
2494 af = sa.sa.sa_family;
2496 /* if this is an IPv4-mapped address then do IPv4 QoS */
2497 if (af == AF_INET6) {
2498 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2502 /* extract and shift 6 bits of the DSCP */
2503 tos = (qos_dscp & 0x3f) << 2;
2507 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2512 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2526 return GST_RTSP_ESYS;
2531 return GST_RTSP_ERROR;
2536 * gst_rtsp_connection_set_qos_dscp:
2537 * @conn: a #GstRTSPConnection
2538 * @qos_dscp: DSCP value
2540 * Configure @conn to use the specified DSCP value.
2542 * Returns: #GST_RTSP_OK on success.
2547 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2551 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2552 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2553 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2555 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2556 if (res == GST_RTSP_OK)
2557 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2564 * gst_rtsp_connection_get_url:
2565 * @conn: a #GstRTSPConnection
2567 * Retrieve the URL of the other end of @conn.
2569 * Returns: The URL. This value remains valid until the
2570 * connection is freed.
2575 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2577 g_return_val_if_fail (conn != NULL, NULL);
2583 * gst_rtsp_connection_get_ip:
2584 * @conn: a #GstRTSPConnection
2586 * Retrieve the IP address of the other end of @conn.
2588 * Returns: The IP address as a string. this value remains valid until the
2589 * connection is closed.
2594 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2596 g_return_val_if_fail (conn != NULL, NULL);
2602 * gst_rtsp_connection_set_ip:
2603 * @conn: a #GstRTSPConnection
2604 * @ip: an ip address
2606 * Set the IP address of the server.
2611 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2613 g_return_if_fail (conn != NULL);
2616 conn->ip = g_strdup (ip);
2620 * gst_rtsp_connection_get_readfd:
2621 * @conn: a #GstRTSPConnection
2623 * Get the file descriptor for reading.
2625 * Returns: the file descriptor used for reading or -1 on error. The file
2626 * descriptor remains valid until the connection is closed.
2631 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2633 g_return_val_if_fail (conn != NULL, -1);
2634 g_return_val_if_fail (conn->readfd != NULL, -1);
2636 return conn->readfd->fd;
2640 * gst_rtsp_connection_get_writefd:
2641 * @conn: a #GstRTSPConnection
2643 * Get the file descriptor for writing.
2645 * Returns: the file descriptor used for writing or -1 on error. The file
2646 * descriptor remains valid until the connection is closed.
2651 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2653 g_return_val_if_fail (conn != NULL, -1);
2654 g_return_val_if_fail (conn->writefd != NULL, -1);
2656 return conn->writefd->fd;
2661 * gst_rtsp_connection_set_tunneled:
2662 * @conn: a #GstRTSPConnection
2663 * @tunneled: the new state
2665 * Set the HTTP tunneling state of the connection. This must be configured before
2666 * the @conn is connected.
2671 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2673 g_return_if_fail (conn != NULL);
2674 g_return_if_fail (conn->readfd == NULL);
2675 g_return_if_fail (conn->writefd == NULL);
2677 conn->tunneled = tunneled;
2681 * gst_rtsp_connection_is_tunneled:
2682 * @conn: a #GstRTSPConnection
2684 * Get the tunneling state of the connection.
2686 * Returns: if @conn is using HTTP tunneling.
2691 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2693 g_return_val_if_fail (conn != NULL, FALSE);
2695 return conn->tunneled;
2699 * gst_rtsp_connection_get_tunnelid:
2700 * @conn: a #GstRTSPConnection
2702 * Get the tunnel session id the connection.
2704 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2709 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2711 g_return_val_if_fail (conn != NULL, NULL);
2713 if (!conn->tunneled)
2716 return conn->tunnelid;
2720 * gst_rtsp_connection_do_tunnel:
2721 * @conn: a #GstRTSPConnection
2722 * @conn2: a #GstRTSPConnection
2724 * If @conn received the first tunnel connection and @conn2 received
2725 * the second tunnel connection, link the two connections together so that
2726 * @conn manages the tunneled connection.
2728 * After this call, @conn2 cannot be used anymore and must be freed with
2729 * gst_rtsp_connection_free().
2731 * Returns: return GST_RTSP_OK on success.
2736 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2737 GstRTSPConnection * conn2)
2739 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2740 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2741 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2742 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2743 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2746 /* both connections have fd0 as the read/write socket. start by taking the
2747 * socket from conn2 and set it as the socket in conn */
2748 conn->fd1 = conn2->fd0;
2750 /* clean up some of the state of conn2 */
2751 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2753 conn2->readfd = conn2->writefd = NULL;
2755 /* We make fd0 the write socket and fd1 the read socket. */
2756 conn->writefd = &conn->fd0;
2757 conn->readfd = &conn->fd1;
2759 conn->tstate = TUNNEL_STATE_COMPLETE;
2761 /* we need base64 decoding for the readfd */
2762 conn->ctx.state = 0;
2765 conn->ctx.coutl = 0;
2766 conn->ctxp = &conn->ctx;
2771 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2772 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2781 /* async functions */
2782 struct _GstRTSPWatch
2786 GstRTSPConnection *conn;
2788 GstRTSPBuilder builder;
2789 GstRTSPMessage message;
2793 gboolean write_added;
2795 /* queued message for transmission */
2797 GAsyncQueue *messages;
2803 GstRTSPWatchFuncs funcs;
2806 GDestroyNotify notify;
2810 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2812 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2814 if (watch->conn->initial_buffer != NULL)
2817 *timeout = (watch->conn->timeout * 1000);
2823 gst_rtsp_source_check (GSource * source)
2825 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2827 if (watch->readfd.revents & READ_COND)
2830 if (watch->writefd.revents & WRITE_COND)
2837 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2838 gpointer user_data G_GNUC_UNUSED)
2840 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2843 /* first read as much as we can */
2844 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2846 res = build_next (&watch->builder, &watch->message, watch->conn);
2847 if (res == GST_RTSP_EINTR)
2849 else if (G_UNLIKELY (res == GST_RTSP_EEOF))
2851 else if (G_LIKELY (res == GST_RTSP_OK)) {
2852 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2853 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2854 watch->message.type_data.request.method == GST_RTSP_GET) {
2855 GstRTSPMessage *response;
2856 GstRTSPStatusCode code;
2858 watch->conn->tstate = TUNNEL_STATE_GET;
2860 if (watch->funcs.tunnel_start)
2861 code = watch->funcs.tunnel_start (watch, watch->user_data);
2863 code = GST_RTSP_STS_OK;
2865 /* queue the response */
2866 response = gen_tunnel_reply (watch->conn, code, &watch->message);
2867 gst_rtsp_watch_queue_message (watch, response);
2868 gst_rtsp_message_free (response);
2870 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2871 watch->message.type_data.request.method == GST_RTSP_POST) {
2872 watch->conn->tstate = TUNNEL_STATE_POST;
2874 /* in the callback the connection should be tunneled with the
2876 if (watch->funcs.tunnel_complete)
2877 watch->funcs.tunnel_complete (watch, watch->user_data);
2880 res = GST_RTSP_ERROR;
2885 if (G_LIKELY (res == GST_RTSP_OK)) {
2886 if (watch->funcs.message_received)
2887 watch->funcs.message_received (watch, &watch->message,
2893 gst_rtsp_message_unset (&watch->message);
2894 build_reset (&watch->builder);
2898 if (watch->writefd.revents & WRITE_COND) {
2900 if (watch->write_data == NULL) {
2903 /* get a new message from the queue */
2904 rec = g_async_queue_try_pop (watch->messages);
2908 watch->write_off = 0;
2909 watch->write_data = rec->data;
2910 watch->write_size = rec->size;
2911 watch->write_id = rec->id;
2913 g_slice_free (GstRTSPRec, rec);
2916 res = write_bytes (watch->writefd.fd, watch->write_data,
2917 &watch->write_off, watch->write_size);
2918 if (res == GST_RTSP_EINTR)
2920 if (G_UNLIKELY (res != GST_RTSP_OK))
2923 if (watch->funcs.message_sent)
2924 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
2927 if (g_async_queue_length (watch->messages) == 0 && watch->write_added) {
2928 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2929 watch->write_added = FALSE;
2930 watch->writefd.revents = 0;
2932 g_free (watch->write_data);
2933 watch->write_data = NULL;
2942 if (watch->funcs.closed)
2943 watch->funcs.closed (watch, watch->user_data);
2948 if (watch->funcs.error)
2949 watch->funcs.error (watch, res, watch->user_data);
2955 gst_rtsp_rec_free (gpointer data)
2957 GstRTSPRec *rec = data;
2960 g_slice_free (GstRTSPRec, rec);
2964 gst_rtsp_source_finalize (GSource * source)
2966 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2968 build_reset (&watch->builder);
2969 gst_rtsp_message_unset (&watch->message);
2971 g_async_queue_unref (watch->messages);
2972 watch->messages = NULL;
2974 g_free (watch->write_data);
2977 watch->notify (watch->user_data);
2980 static GSourceFuncs gst_rtsp_source_funcs = {
2981 gst_rtsp_source_prepare,
2982 gst_rtsp_source_check,
2983 gst_rtsp_source_dispatch,
2984 gst_rtsp_source_finalize,
2990 * gst_rtsp_watch_new:
2991 * @conn: a #GstRTSPConnection
2992 * @funcs: watch functions
2993 * @user_data: user data to pass to @funcs
2994 * @notify: notify when @user_data is not referenced anymore
2996 * Create a watch object for @conn. The functions provided in @funcs will be
2997 * called with @user_data when activity happened on the watch.
2999 * The new watch is usually created so that it can be attached to a
3000 * maincontext with gst_rtsp_watch_attach().
3002 * @conn must exist for the entire lifetime of the watch.
3004 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3005 * communication. Free with gst_rtsp_watch_unref () after usage.
3010 gst_rtsp_watch_new (GstRTSPConnection * conn,
3011 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3013 GstRTSPWatch *result;
3015 g_return_val_if_fail (conn != NULL, NULL);
3016 g_return_val_if_fail (funcs != NULL, NULL);
3017 g_return_val_if_fail (conn->readfd != NULL, NULL);
3018 g_return_val_if_fail (conn->writefd != NULL, NULL);
3020 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3021 sizeof (GstRTSPWatch));
3023 result->conn = conn;
3024 result->builder.state = STATE_START;
3026 result->messages = g_async_queue_new_full (gst_rtsp_rec_free);
3028 result->readfd.fd = -1;
3029 result->writefd.fd = -1;
3031 gst_rtsp_watch_reset (result);
3033 result->funcs = *funcs;
3034 result->user_data = user_data;
3035 result->notify = notify;
3037 /* only add the read fd, the write fd is only added when we have data
3039 g_source_add_poll ((GSource *) result, &result->readfd);
3045 * gst_rtsp_watch_reset:
3046 * @watch: a #GstRTSPWatch
3048 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3049 * when the file descriptors of the connection might have changed.
3054 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3056 if (watch->readfd.fd != -1)
3057 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3058 if (watch->writefd.fd != -1)
3059 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3061 watch->readfd.fd = watch->conn->readfd->fd;
3062 watch->readfd.events = READ_COND;
3063 watch->readfd.revents = 0;
3065 watch->writefd.fd = watch->conn->writefd->fd;
3066 watch->writefd.events = WRITE_COND;
3067 watch->writefd.revents = 0;
3068 watch->write_added = FALSE;
3070 g_source_add_poll ((GSource *) watch, &watch->readfd);
3074 * gst_rtsp_watch_attach:
3075 * @watch: a #GstRTSPWatch
3076 * @context: a GMainContext (if NULL, the default context will be used)
3078 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3080 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3085 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3087 g_return_val_if_fail (watch != NULL, 0);
3089 return g_source_attach ((GSource *) watch, context);
3093 * gst_rtsp_watch_unref:
3094 * @watch: a #GstRTSPWatch
3096 * Decreases the reference count of @watch by one. If the resulting reference
3097 * count is zero the watch and associated memory will be destroyed.
3102 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3104 g_return_if_fail (watch != NULL);
3106 g_source_unref ((GSource *) watch);
3110 * gst_rtsp_watch_queue_data:
3111 * @watch: a #GstRTSPWatch
3112 * @data: the data to queue
3113 * @size: the size of @data
3115 * Queue @data for transmission in @watch. It will be transmitted when the
3116 * connection of the @watch becomes writable.
3118 * This function will take ownership of @data and g_free() it after use.
3120 * The return value of this function will be used as the id argument in the
3121 * message_sent callback.
3128 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3133 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3134 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3135 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3137 /* make a record with the data and id */
3138 rec = g_slice_new (GstRTSPRec);
3139 rec->data = (guint8 *) data;
3142 /* make sure rec->id is never 0 */
3143 rec->id = ++watch->id;
3144 } while (G_UNLIKELY (rec->id == 0));
3146 /* add the record to a queue. FIXME we would like to have an upper limit here */
3147 g_async_queue_push (watch->messages, rec);
3149 /* FIXME: does the following need to be made thread-safe? (this might be
3150 * called from a streaming thread, like appsink's render function) */
3151 /* make sure the main context will now also check for writability on the
3153 if (!watch->write_added) {
3154 g_source_add_poll ((GSource *) watch, &watch->writefd);
3155 watch->write_added = TRUE;
3162 * gst_rtsp_watch_queue_message:
3163 * @watch: a #GstRTSPWatch
3164 * @message: a #GstRTSPMessage
3166 * Queue a @message for transmission in @watch. The contents of this
3167 * message will be serialized and transmitted when the connection of the
3168 * @watch becomes writable.
3170 * The return value of this function will be used as the id argument in the
3171 * message_sent callback.
3178 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3183 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3184 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3186 /* make a record with the message as a string and id */
3187 str = message_to_string (watch->conn, message);
3189 return gst_rtsp_watch_queue_data (watch,
3190 (guint8 *) g_string_free (str, FALSE), size);