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 void 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 */
234 build_reset (GstRTSPBuilder * builder)
236 g_free (builder->body_data);
237 memset (builder, 0, sizeof (GstRTSPBuilder));
241 * gst_rtsp_connection_create:
242 * @url: a #GstRTSPUrl
243 * @conn: storage for a #GstRTSPConnection
245 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
246 * The connection will not yet attempt to connect to @url, use
247 * gst_rtsp_connection_connect().
249 * A copy of @url will be made.
251 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
254 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
256 GstRTSPConnection *newconn;
262 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
265 error = WSAStartup (0x0202, &w);
270 if (w.wVersion != 0x0202)
274 newconn = g_new0 (GstRTSPConnection, 1);
276 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
279 newconn->url = gst_rtsp_url_copy (url);
280 newconn->fd0.fd = -1;
281 newconn->fd1.fd = -1;
282 newconn->timer = g_timer_new ();
283 newconn->timeout = 60;
286 newconn->auth_method = GST_RTSP_AUTH_NONE;
287 newconn->username = NULL;
288 newconn->passwd = NULL;
289 newconn->auth_params = NULL;
299 g_warning ("Error %d on WSAStartup", error);
300 return GST_RTSP_EWSASTART;
304 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
307 return GST_RTSP_EWSAVERSION;
316 return GST_RTSP_ESYS;
321 * gst_rtsp_connection_create_from_fd:
322 * @fd: a file descriptor
323 * @ip: the IP address of the other end
324 * @port: the port used by the other end
325 * @initial_buffer: data already read from @fd
326 * @conn: storage for a #GstRTSPConnection
328 * Create a new #GstRTSPConnection for handling communication on the existing
329 * file descriptor @fd. The @initial_buffer contains any data already read from
330 * @fd which should be used before starting to read new data.
332 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
337 gst_rtsp_connection_create_from_fd (gint fd, const gchar * ip, guint16 port,
338 const gchar * initial_buffer, GstRTSPConnection ** conn)
340 GstRTSPConnection *newconn = NULL;
347 g_return_val_if_fail (fd >= 0, GST_RTSP_EINVAL);
348 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
349 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
351 /* set to non-blocking mode so that we can cancel the communication */
353 fcntl (fd, F_SETFL, O_NONBLOCK);
355 ioctlsocket (fd, FIONBIO, &flags);
356 #endif /* G_OS_WIN32 */
358 /* create a url for the client address */
359 url = g_new0 (GstRTSPUrl, 1);
360 url->host = g_strdup (ip);
363 /* now create the connection object */
364 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
365 gst_rtsp_url_free (url);
367 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
369 /* both read and write initially */
370 newconn->readfd = &newconn->fd0;
371 newconn->writefd = &newconn->fd0;
373 newconn->ip = g_strdup (ip);
375 newconn->initial_buffer = g_strdup (initial_buffer);
384 gst_rtsp_url_free (url);
390 * gst_rtsp_connection_accept:
392 * @conn: storage for a #GstRTSPConnection
394 * Accept a new connection on @sock and create a new #GstRTSPConnection for
395 * handling communication on new socket.
397 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
402 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
405 union gst_sockaddr sa;
406 socklen_t slen = sizeof (sa);
407 gchar ip[INET6_ADDRSTRLEN];
410 g_return_val_if_fail (sock >= 0, GST_RTSP_EINVAL);
411 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
413 memset (&sa, 0, slen);
416 fd = accept (sock, &sa.sa, &slen);
418 fd = accept (sock, &sa.sa, (gint *) & slen);
419 #endif /* G_OS_WIN32 */
423 if (getnameinfo (&sa.sa, slen, ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) != 0)
424 goto getnameinfo_failed;
426 if (sa.sa.sa_family == AF_INET)
427 port = sa.sa_in.sin_port;
428 else if (sa.sa.sa_family == AF_INET6)
429 port = sa.sa_in6.sin6_port;
433 return gst_rtsp_connection_create_from_fd (fd, ip, port, NULL, conn);
438 return GST_RTSP_ESYS;
444 return GST_RTSP_ERROR;
449 do_resolve (const gchar * host)
451 static gchar ip[INET6_ADDRSTRLEN];
452 struct addrinfo *aires;
456 aierr = getaddrinfo (host, NULL, NULL, &aires);
460 for (ai = aires; ai; ai = ai->ai_next) {
461 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
468 aierr = getnameinfo (ai->ai_addr, ai->ai_addrlen, ip, sizeof (ip), NULL, 0,
469 NI_NUMERICHOST | NI_NUMERICSERV);
473 freeaddrinfo (aires);
475 return g_strdup (ip);
480 GST_ERROR ("no addrinfo found for %s: %s", host, gai_strerror (aierr));
485 GST_ERROR ("no family found for %s", host);
486 freeaddrinfo (aires);
491 GST_ERROR ("no address found for %s: %s", host, gai_strerror (aierr));
492 freeaddrinfo (aires);
498 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
499 GstPoll * fdset, GTimeVal * timeout)
502 struct addrinfo hints;
503 struct addrinfo *aires;
506 gchar service[NI_MAXSERV];
509 unsigned long flags = 1;
510 #endif /* G_OS_WIN32 */
514 memset (&hints, 0, sizeof hints);
515 hints.ai_flags = AI_NUMERICHOST;
516 hints.ai_family = AF_UNSPEC;
517 hints.ai_socktype = SOCK_STREAM;
518 g_snprintf (service, sizeof (service) - 1, "%hu", port);
519 service[sizeof (service) - 1] = '\0';
521 aierr = getaddrinfo (ip, service, &hints, &aires);
525 for (ai = aires; ai; ai = ai->ai_next) {
526 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
533 fd = socket (ai->ai_family, SOCK_STREAM, 0);
537 /* set to non-blocking mode so that we can cancel the connect */
539 fcntl (fd, F_SETFL, O_NONBLOCK);
541 ioctlsocket (fd, FIONBIO, &flags);
542 #endif /* G_OS_WIN32 */
544 /* add the socket to our fdset */
545 ADD_POLLFD (fdset, fdout, fd);
547 /* we are going to connect ASYNC now */
548 ret = connect (fd, ai->ai_addr, ai->ai_addrlen);
551 if (!ERRNO_IS_EINPROGRESS)
554 /* wait for connect to complete up to the specified timeout or until we got
556 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
558 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
561 retval = gst_poll_wait (fdset, to);
562 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
566 else if (retval == -1)
569 /* we can still have an error connecting on windows */
570 if (gst_poll_fd_has_error (fdset, fdout)) {
571 socklen_t len = sizeof (errno);
573 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
575 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
580 gst_poll_fd_ignored (fdset, fdout);
583 freeaddrinfo (aires);
590 GST_ERROR ("no addrinfo found for %s: %s", ip, gai_strerror (aierr));
591 return GST_RTSP_ERROR;
595 GST_ERROR ("no family found for %s", ip);
596 freeaddrinfo (aires);
597 return GST_RTSP_ERROR;
601 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
602 freeaddrinfo (aires);
603 return GST_RTSP_ESYS;
607 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
608 REMOVE_POLLFD (fdset, fdout);
609 freeaddrinfo (aires);
610 return GST_RTSP_ESYS;
614 GST_ERROR ("timeout");
615 REMOVE_POLLFD (fdset, fdout);
616 freeaddrinfo (aires);
617 return GST_RTSP_ETIMEOUT;
622 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
630 gchar *ip, *url_port_str;
631 guint16 port, url_port;
632 gchar codestr[4], *resultstr;
637 /* create a random sessionid */
638 for (i = 0; i < TUNNELID_LEN; i++)
639 conn->tunnelid[i] = g_random_int_range ('a', 'z');
640 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
643 /* get the port from the url */
644 gst_rtsp_url_get_port (url, &url_port);
646 if (conn->proxy_host) {
647 hostparam = g_strdup_printf ("Host: %s:%d\r\n", url->host, url_port);
648 url_port_str = g_strdup_printf (":%d", url_port);
649 ip = conn->proxy_host;
650 port = conn->proxy_port;
659 str = g_strdup_printf ("GET %s%s%s%s%s%s HTTP/1.0\r\n"
661 "x-sessioncookie: %s\r\n"
662 "Accept: application/x-rtsp-tunnelled\r\n"
663 "Pragma: no-cache\r\n"
664 "Cache-Control: no-cache\r\n" "\r\n",
665 conn->proxy_host ? "http://" : "",
666 conn->proxy_host ? url->host : "",
667 conn->proxy_host ? url_port_str : "",
668 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
669 hostparam ? hostparam : "", conn->tunnelid);
671 /* we start by writing to this fd */
672 conn->writefd = &conn->fd0;
674 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
676 if (res != GST_RTSP_OK)
679 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
680 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
682 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
690 res = read_line (conn, buffer, &idx, sizeof (buffer));
691 if (res == GST_RTSP_EEOF)
693 if (res == GST_RTSP_OK)
695 if (res != GST_RTSP_EINTR)
699 retval = gst_poll_wait (conn->fdset, to);
700 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
702 /* check for timeout */
714 /* check for last line */
715 if (buffer[0] == '\r')
717 if (buffer[0] == '\0')
721 /* first line, parse response */
722 gchar versionstr[20];
725 bptr = (gchar *) buffer;
727 parse_string (versionstr, sizeof (versionstr), &bptr);
728 parse_string (codestr, sizeof (codestr), &bptr);
729 code = atoi (codestr);
731 while (g_ascii_isspace (*bptr))
736 if (code != GST_RTSP_STS_OK)
742 /* other lines, parse key/value */
743 res = parse_key_value (buffer, key, sizeof (key), &value);
744 if (res == GST_RTSP_OK) {
745 /* we got a new ip address */
746 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
747 if (conn->proxy_host) {
748 /* if we use a proxy we need to change the destination url */
750 url->host = g_strdup (value);
752 g_free (url_port_str);
754 g_strdup_printf ("Host: %s:%d\r\n", url->host, url_port);
755 url_port_str = g_strdup_printf (":%d", url_port);
757 /* and resolve the new ip address */
758 if (!(ip = do_resolve (conn->ip)))
769 /* connect to the host/port */
770 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
771 if (res != GST_RTSP_OK)
774 /* this is now our writing socket */
775 conn->writefd = &conn->fd1;
778 str = g_strdup_printf ("POST %s%s%s%s%s%s HTTP/1.0\r\n"
780 "x-sessioncookie: %s\r\n"
781 "Content-Type: application/x-rtsp-tunnelled\r\n"
782 "Pragma: no-cache\r\n"
783 "Cache-Control: no-cache\r\n"
784 "Content-Length: 32767\r\n"
785 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
787 conn->proxy_host ? "http://" : "",
788 conn->proxy_host ? url->host : "",
789 conn->proxy_host ? url_port_str : "",
790 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
791 hostparam ? hostparam : "", conn->tunnelid);
793 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
795 if (res != GST_RTSP_OK)
800 g_free (url_port_str);
807 GST_ERROR ("write failed (%d)", res);
821 res = GST_RTSP_ETIMEOUT;
831 res = GST_RTSP_EINTR;
836 GST_ERROR ("got failure response %d %s", code, resultstr);
837 res = GST_RTSP_ERROR;
842 GST_ERROR ("could not resolve %s", conn->ip);
848 GST_ERROR ("failed to connect");
854 * gst_rtsp_connection_connect:
855 * @conn: a #GstRTSPConnection
856 * @timeout: a #GTimeVal timeout
858 * Attempt to connect to the url of @conn made with
859 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
860 * forever. If @timeout contains a valid timeout, this function will return
861 * #GST_RTSP_ETIMEOUT after the timeout expired.
863 * This function can be cancelled with gst_rtsp_connection_flush().
865 * Returns: #GST_RTSP_OK when a connection could be made.
868 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
875 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
876 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
877 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
881 if (conn->proxy_host && conn->tunneled) {
882 if (!(ip = do_resolve (conn->proxy_host))) {
883 GST_ERROR ("could not resolve %s", conn->proxy_host);
886 port = conn->proxy_port;
887 g_free (conn->proxy_host);
888 conn->proxy_host = ip;
890 if (!(ip = do_resolve (url->host))) {
891 GST_ERROR ("could not resolve %s", url->host);
894 /* get the port from the url */
895 gst_rtsp_url_get_port (url, &port);
901 /* connect to the host/port */
902 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
903 if (res != GST_RTSP_OK)
906 /* this is our read URL */
907 conn->readfd = &conn->fd0;
909 if (conn->tunneled) {
910 res = setup_tunneling (conn, timeout);
911 if (res != GST_RTSP_OK)
912 goto tunneling_failed;
914 conn->writefd = &conn->fd0;
921 return GST_RTSP_ENET;
925 GST_ERROR ("failed to connect");
930 GST_ERROR ("failed to setup tunneling");
936 auth_digest_compute_hex_urp (const gchar * username,
937 const gchar * realm, const gchar * password, gchar hex_urp[33])
939 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
940 const gchar *digest_string;
942 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
943 g_checksum_update (md5_context, (const guchar *) ":", 1);
944 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
945 g_checksum_update (md5_context, (const guchar *) ":", 1);
946 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
947 digest_string = g_checksum_get_string (md5_context);
949 memset (hex_urp, 0, 33);
950 memcpy (hex_urp, digest_string, strlen (digest_string));
952 g_checksum_free (md5_context);
956 auth_digest_compute_response (const gchar * method,
957 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
960 char hex_a2[33] = { 0, };
961 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
962 const gchar *digest_string;
965 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
966 g_checksum_update (md5_context, (const guchar *) ":", 1);
967 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
968 digest_string = g_checksum_get_string (md5_context);
969 memcpy (hex_a2, digest_string, strlen (digest_string));
972 #if GLIB_CHECK_VERSION (2, 18, 0)
973 g_checksum_reset (md5_context);
975 g_checksum_free (md5_context);
976 md5_context = g_checksum_new (G_CHECKSUM_MD5);
978 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
979 g_checksum_update (md5_context, (const guchar *) ":", 1);
980 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
981 g_checksum_update (md5_context, (const guchar *) ":", 1);
983 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
984 digest_string = g_checksum_get_string (md5_context);
985 memset (response, 0, 33);
986 memcpy (response, digest_string, strlen (digest_string));
988 g_checksum_free (md5_context);
992 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
994 switch (conn->auth_method) {
995 case GST_RTSP_AUTH_BASIC:{
1000 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
1001 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
1002 auth_string = g_strdup_printf ("Basic %s", user_pass64);
1004 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1008 g_free (user_pass64);
1011 case GST_RTSP_AUTH_DIGEST:{
1012 gchar response[33], hex_urp[33];
1013 gchar *auth_string, *auth_string2;
1018 const gchar *method;
1020 /* we need to have some params set */
1021 if (conn->auth_params == NULL)
1024 /* we need the realm and nonce */
1025 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
1026 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
1027 if (realm == NULL || nonce == NULL)
1030 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
1033 method = gst_rtsp_method_as_text (message->type_data.request.method);
1034 uri = message->type_data.request.uri;
1036 /* Assume no qop, algorithm=md5, stale=false */
1037 /* For algorithm MD5, a1 = urp. */
1038 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
1039 auth_string = g_strdup_printf ("Digest username=\"%s\", "
1040 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
1041 conn->username, realm, nonce, uri, response);
1043 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
1045 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
1047 g_free (auth_string);
1048 auth_string = auth_string2;
1050 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1061 gen_date_string (gchar * date_string, guint len)
1065 #ifdef HAVE_GMTIME_R
1069 g_get_current_time (&tv);
1070 t = (time_t) tv.tv_sec;
1072 #ifdef HAVE_GMTIME_R
1073 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1075 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1079 static GstRTSPResult
1080 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1084 if (G_UNLIKELY (*idx > size))
1085 return GST_RTSP_ERROR;
1092 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1093 if (G_UNLIKELY (r == 0)) {
1094 return GST_RTSP_EINTR;
1095 } else if (G_UNLIKELY (r < 0)) {
1096 if (ERRNO_IS_EAGAIN)
1097 return GST_RTSP_EINTR;
1098 if (!ERRNO_IS_EINTR)
1099 return GST_RTSP_ESYS;
1109 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1113 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1114 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1116 out = MIN (left, size);
1117 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1119 if (left == (gsize) out) {
1120 g_free (conn->initial_buffer);
1121 conn->initial_buffer = NULL;
1122 conn->initial_buffer_offset = 0;
1124 conn->initial_buffer_offset += out;
1127 if (G_LIKELY (size > (guint) out)) {
1130 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1142 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1144 DecodeCtx *ctx = conn->ctxp;
1149 guint8 in[sizeof (ctx->out) * 4 / 3];
1152 while (size > 0 && ctx->cout < ctx->coutl) {
1153 /* we have some leftover bytes */
1154 *buffer++ = ctx->out[ctx->cout++];
1159 /* got what we needed? */
1163 /* try to read more bytes */
1164 r = fill_raw_bytes (conn, in, sizeof (in));
1173 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1177 out = fill_raw_bytes (conn, buffer, size);
1183 static GstRTSPResult
1184 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1188 if (G_UNLIKELY (*idx > size))
1189 return GST_RTSP_ERROR;
1196 r = fill_bytes (conn, &buffer[*idx], left);
1197 if (G_UNLIKELY (r == 0)) {
1198 return GST_RTSP_EEOF;
1199 } else if (G_UNLIKELY (r < 0)) {
1200 if (ERRNO_IS_EAGAIN)
1201 return GST_RTSP_EINTR;
1202 if (!ERRNO_IS_EINTR)
1203 return GST_RTSP_ESYS;
1212 static GstRTSPResult
1213 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1219 r = fill_bytes (conn, &c, 1);
1220 if (G_UNLIKELY (r == 0)) {
1221 return GST_RTSP_EEOF;
1222 } else if (G_UNLIKELY (r < 0)) {
1223 if (ERRNO_IS_EAGAIN)
1224 return GST_RTSP_EINTR;
1225 if (!ERRNO_IS_EINTR)
1226 return GST_RTSP_ESYS;
1228 if (c == '\n') /* end on \n */
1230 if (c == '\r') /* ignore \r */
1233 if (G_LIKELY (*idx < size - 1))
1234 buffer[(*idx)++] = c;
1237 buffer[*idx] = '\0';
1243 * gst_rtsp_connection_write:
1244 * @conn: a #GstRTSPConnection
1245 * @data: the data to write
1246 * @size: the size of @data
1247 * @timeout: a timeout value or #NULL
1249 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1250 * the specified @timeout. @timeout can be #NULL, in which case this function
1251 * might block forever.
1253 * This function can be cancelled with gst_rtsp_connection_flush().
1255 * Returns: #GST_RTSP_OK on success.
1258 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1259 guint size, GTimeVal * timeout)
1266 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1267 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1268 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1270 gst_poll_set_controllable (conn->fdset, TRUE);
1271 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1272 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1273 /* clear all previous poll results */
1274 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1275 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1277 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1283 res = write_bytes (conn->writefd->fd, data, &offset, size);
1284 if (G_LIKELY (res == GST_RTSP_OK))
1286 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1289 /* not all is written, wait until we can write more */
1291 retval = gst_poll_wait (conn->fdset, to);
1292 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1294 if (G_UNLIKELY (retval == 0))
1297 if (G_UNLIKELY (retval == -1)) {
1309 return GST_RTSP_ETIMEOUT;
1313 return GST_RTSP_ESYS;
1317 return GST_RTSP_EINTR;
1326 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1328 GString *str = NULL;
1330 str = g_string_new ("");
1332 switch (message->type) {
1333 case GST_RTSP_MESSAGE_REQUEST:
1334 /* create request string, add CSeq */
1335 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1337 gst_rtsp_method_as_text (message->type_data.request.method),
1338 message->type_data.request.uri, conn->cseq++);
1339 /* add session id if we have one */
1340 if (conn->session_id[0] != '\0') {
1341 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1342 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1345 /* add any authentication headers */
1346 add_auth_header (conn, message);
1348 case GST_RTSP_MESSAGE_RESPONSE:
1349 /* create response string */
1350 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1351 message->type_data.response.code, message->type_data.response.reason);
1353 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1354 /* create request string */
1355 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1356 gst_rtsp_method_as_text (message->type_data.request.method),
1357 message->type_data.request.uri,
1358 gst_rtsp_version_as_text (message->type_data.request.version));
1359 /* add any authentication headers */
1360 add_auth_header (conn, message);
1362 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1363 /* create response string */
1364 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1365 gst_rtsp_version_as_text (message->type_data.request.version),
1366 message->type_data.response.code, message->type_data.response.reason);
1368 case GST_RTSP_MESSAGE_DATA:
1370 guint8 data_header[4];
1372 /* prepare data header */
1373 data_header[0] = '$';
1374 data_header[1] = message->type_data.data.channel;
1375 data_header[2] = (message->body_size >> 8) & 0xff;
1376 data_header[3] = message->body_size & 0xff;
1378 /* create string with header and data */
1379 str = g_string_append_len (str, (gchar *) data_header, 4);
1381 g_string_append_len (str, (gchar *) message->body,
1382 message->body_size);
1386 g_string_free (str, TRUE);
1387 g_return_val_if_reached (NULL);
1391 /* append headers and body */
1392 if (message->type != GST_RTSP_MESSAGE_DATA) {
1393 gchar date_string[100];
1395 gen_date_string (date_string, sizeof (date_string));
1397 /* add date header */
1398 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1399 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1401 /* append headers */
1402 gst_rtsp_message_append_headers (message, str);
1404 /* append Content-Length and body if needed */
1405 if (message->body != NULL && message->body_size > 0) {
1408 len = g_strdup_printf ("%d", message->body_size);
1409 g_string_append_printf (str, "%s: %s\r\n",
1410 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1412 /* header ends here */
1413 g_string_append (str, "\r\n");
1415 g_string_append_len (str, (gchar *) message->body,
1416 message->body_size);
1418 /* just end headers */
1419 g_string_append (str, "\r\n");
1427 * gst_rtsp_connection_send:
1428 * @conn: a #GstRTSPConnection
1429 * @message: the message to send
1430 * @timeout: a timeout value or #NULL
1432 * Attempt to send @message to the connected @conn, blocking up to
1433 * the specified @timeout. @timeout can be #NULL, in which case this function
1434 * might block forever.
1436 * This function can be cancelled with gst_rtsp_connection_flush().
1438 * Returns: #GST_RTSP_OK on success.
1441 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1444 GString *string = NULL;
1449 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1450 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1452 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1455 if (conn->tunneled) {
1456 str = g_base64_encode ((const guchar *) string->str, string->len);
1457 g_string_free (string, TRUE);
1462 g_string_free (string, FALSE);
1466 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1474 g_warning ("Wrong message");
1475 return GST_RTSP_EINVAL;
1480 parse_string (gchar * dest, gint size, gchar ** src)
1486 while (g_ascii_isspace (**src))
1489 while (!g_ascii_isspace (**src) && **src != '\0') {
1491 dest[idx++] = **src;
1499 parse_key (gchar * dest, gint size, gchar ** src)
1504 while (**src != ':' && **src != '\0') {
1506 dest[idx++] = **src;
1513 static GstRTSPResult
1514 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1517 gchar versionstr[20];
1522 bptr = (gchar *) buffer;
1524 parse_string (versionstr, sizeof (versionstr), &bptr);
1525 parse_string (codestr, sizeof (codestr), &bptr);
1526 code = atoi (codestr);
1528 while (g_ascii_isspace (*bptr))
1531 if (strcmp (versionstr, "RTSP/1.0") == 0)
1532 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1534 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1535 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1537 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1545 return GST_RTSP_EPARSE;
1549 static GstRTSPResult
1550 parse_request_line (GstRTSPConnection * conn, guint8 * buffer,
1551 GstRTSPMessage * msg)
1553 GstRTSPResult res = GST_RTSP_OK;
1554 gchar versionstr[20];
1555 gchar methodstr[20];
1558 GstRTSPMethod method;
1559 GstRTSPTunnelState tstate = TUNNEL_STATE_NONE;
1561 bptr = (gchar *) buffer;
1563 parse_string (methodstr, sizeof (methodstr), &bptr);
1564 method = gst_rtsp_find_method (methodstr);
1565 if (method == GST_RTSP_INVALID) {
1566 /* a tunnel request is allowed when we don't have one yet */
1567 if (conn->tstate != TUNNEL_STATE_NONE)
1568 goto invalid_method;
1569 /* we need GET or POST for a valid tunnel request */
1570 if (!strcmp (methodstr, "GET"))
1571 tstate = TUNNEL_STATE_GET;
1572 else if (!strcmp (methodstr, "POST"))
1573 tstate = TUNNEL_STATE_POST;
1575 goto invalid_method;
1578 parse_string (urlstr, sizeof (urlstr), &bptr);
1579 if (G_UNLIKELY (*urlstr == '\0'))
1582 parse_string (versionstr, sizeof (versionstr), &bptr);
1584 if (G_UNLIKELY (*bptr != '\0'))
1585 goto invalid_version;
1587 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1588 res = gst_rtsp_message_init_request (msg, method, urlstr);
1589 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1590 res = gst_rtsp_message_init_request (msg, method, urlstr);
1591 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1592 } else if (strcmp (versionstr, "HTTP/1.0") == 0) {
1593 /* tunnel request, we need a tunnel method */
1594 if (tstate == TUNNEL_STATE_NONE) {
1595 res = GST_RTSP_EPARSE;
1597 conn->tstate = tstate;
1600 res = GST_RTSP_EPARSE;
1608 GST_ERROR ("invalid method %s", methodstr);
1609 return GST_RTSP_EPARSE;
1613 GST_ERROR ("invalid url %s", urlstr);
1614 return GST_RTSP_EPARSE;
1618 GST_ERROR ("invalid version");
1619 return GST_RTSP_EPARSE;
1623 static GstRTSPResult
1624 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1628 bptr = (gchar *) buffer;
1631 parse_key (key, keysize, &bptr);
1632 if (G_UNLIKELY (*bptr != ':'))
1636 while (g_ascii_isspace (*bptr))
1646 return GST_RTSP_EPARSE;
1650 /* parsing lines means reading a Key: Value pair */
1651 static GstRTSPResult
1652 parse_line (GstRTSPConnection * conn, guint8 * buffer, GstRTSPMessage * msg)
1657 GstRTSPHeaderField field;
1659 res = parse_key_value (buffer, key, sizeof (key), &value);
1660 if (G_UNLIKELY (res != GST_RTSP_OK))
1663 if (conn->tstate == TUNNEL_STATE_GET || conn->tstate == TUNNEL_STATE_POST) {
1664 /* save the tunnel session in the connection */
1665 if (!strcmp (key, "x-sessioncookie")) {
1666 strncpy (conn->tunnelid, value, TUNNELID_LEN);
1667 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1668 conn->tunneled = TRUE;
1671 field = gst_rtsp_find_header_field (key);
1672 if (field != GST_RTSP_HDR_INVALID)
1673 gst_rtsp_message_add_header (msg, field, value);
1686 * GST_RTSP_OK when a complete message was read.
1687 * GST_RTSP_EEOF: when the socket is closed
1688 * GST_RTSP_EINTR: when more data is needed.
1689 * GST_RTSP_..: some other error occured.
1691 static GstRTSPResult
1692 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1693 GstRTSPConnection * conn)
1698 switch (builder->state) {
1700 builder->offset = 0;
1702 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1703 if (res != GST_RTSP_OK)
1706 /* we have 1 bytes now and we can see if this is a data message or
1708 if (builder->buffer[0] == '$') {
1709 /* data message, prepare for the header */
1710 builder->state = STATE_DATA_HEADER;
1713 builder->state = STATE_READ_LINES;
1716 case STATE_DATA_HEADER:
1719 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1720 if (res != GST_RTSP_OK)
1723 gst_rtsp_message_init_data (message, builder->buffer[1]);
1725 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1726 builder->body_data = g_malloc (builder->body_len + 1);
1727 builder->body_data[builder->body_len] = '\0';
1728 builder->offset = 0;
1729 builder->state = STATE_DATA_BODY;
1732 case STATE_DATA_BODY:
1735 read_bytes (conn, builder->body_data, &builder->offset,
1737 if (res != GST_RTSP_OK)
1740 /* we have the complete body now, store in the message adjusting the
1741 * length to include the traling '\0' */
1742 gst_rtsp_message_take_body (message,
1743 (guint8 *) builder->body_data, builder->body_len + 1);
1744 builder->body_data = NULL;
1745 builder->body_len = 0;
1747 builder->state = STATE_END;
1750 case STATE_READ_LINES:
1752 res = read_line (conn, builder->buffer, &builder->offset,
1753 sizeof (builder->buffer));
1754 if (res != GST_RTSP_OK)
1757 /* we have a regular response */
1758 if (builder->buffer[0] == '\r') {
1759 builder->buffer[0] = '\0';
1762 if (builder->buffer[0] == '\0') {
1765 /* empty line, end of message header */
1766 /* see if there is a Content-Length header */
1767 if (gst_rtsp_message_get_header (message,
1768 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1769 /* there is, prepare to read the body */
1770 builder->body_len = atol (hdrval);
1771 builder->body_data = g_malloc (builder->body_len + 1);
1772 builder->body_data[builder->body_len] = '\0';
1773 builder->offset = 0;
1774 builder->state = STATE_DATA_BODY;
1776 builder->state = STATE_END;
1781 /* we have a line */
1782 if (builder->line == 0) {
1783 /* first line, check for response status */
1784 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1785 res = parse_response_status (builder->buffer, message);
1787 res = parse_request_line (conn, builder->buffer, message);
1789 /* the first line must parse without errors */
1790 if (res != GST_RTSP_OK)
1793 /* else just parse the line, ignore errors */
1794 parse_line (conn, builder->buffer, message);
1797 builder->offset = 0;
1804 if (conn->tstate == TUNNEL_STATE_GET) {
1805 res = GST_RTSP_ETGET;
1807 } else if (conn->tstate == TUNNEL_STATE_POST) {
1808 res = GST_RTSP_ETPOST;
1812 if (message->type == GST_RTSP_MESSAGE_DATA) {
1813 /* data messages don't have headers */
1818 /* save session id in the connection for further use */
1819 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1820 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1821 &session_id, 0) == GST_RTSP_OK) {
1824 maxlen = sizeof (conn->session_id) - 1;
1825 /* the sessionid can have attributes marked with ;
1826 * Make sure we strip them */
1827 for (i = 0; session_id[i] != '\0'; i++) {
1828 if (session_id[i] == ';') {
1833 } while (g_ascii_isspace (session_id[i]));
1834 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1837 /* if we parsed something valid, configure */
1838 if ((to = atoi (&session_id[i + 8])) > 0)
1845 /* make sure to not overflow */
1846 strncpy (conn->session_id, session_id, maxlen);
1847 conn->session_id[maxlen] = '\0';
1853 res = GST_RTSP_ERROR;
1862 * gst_rtsp_connection_read:
1863 * @conn: a #GstRTSPConnection
1864 * @data: the data to read
1865 * @size: the size of @data
1866 * @timeout: a timeout value or #NULL
1868 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1869 * the specified @timeout. @timeout can be #NULL, in which case this function
1870 * might block forever.
1872 * This function can be cancelled with gst_rtsp_connection_flush().
1874 * Returns: #GST_RTSP_OK on success.
1877 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1885 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1886 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1887 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1889 if (G_UNLIKELY (size == 0))
1894 /* configure timeout if any */
1895 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1897 gst_poll_set_controllable (conn->fdset, TRUE);
1898 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1899 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1902 res = read_bytes (conn, data, &offset, size);
1903 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1905 if (G_LIKELY (res == GST_RTSP_OK))
1907 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1911 retval = gst_poll_wait (conn->fdset, to);
1912 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1914 /* check for timeout */
1915 if (G_UNLIKELY (retval == 0))
1916 goto select_timeout;
1918 if (G_UNLIKELY (retval == -1)) {
1924 gst_poll_set_controllable (conn->fdset, FALSE);
1931 return GST_RTSP_ESYS;
1935 return GST_RTSP_ETIMEOUT;
1939 return GST_RTSP_EINTR;
1943 return GST_RTSP_EEOF;
1952 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code)
1955 gchar date_string[100];
1956 const gchar *status;
1958 gen_date_string (date_string, sizeof (date_string));
1960 status = gst_rtsp_status_as_text (code);
1961 if (status == NULL) {
1962 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
1963 status = "Internal Server Error";
1966 str = g_string_new ("");
1969 g_string_append_printf (str, "HTTP/1.0 %d %s\r\n", code, status);
1970 g_string_append_printf (str,
1971 "Server: GStreamer RTSP Server\r\n"
1973 "Connection: close\r\n"
1974 "Cache-Control: no-store\r\n" "Pragma: no-cache\r\n", date_string);
1975 if (code == GST_RTSP_STS_OK) {
1977 g_string_append_printf (str, "x-server-ip-address: %s\r\n", conn->ip);
1978 g_string_append_printf (str,
1979 "Content-Type: application/x-rtsp-tunnelled\r\n");
1981 g_string_append_printf (str, "\r\n");
1986 * gst_rtsp_connection_receive:
1987 * @conn: a #GstRTSPConnection
1988 * @message: the message to read
1989 * @timeout: a timeout value or #NULL
1991 * Attempt to read into @message from the connected @conn, blocking up to
1992 * the specified @timeout. @timeout can be #NULL, in which case this function
1993 * might block forever.
1995 * This function can be cancelled with gst_rtsp_connection_flush().
1997 * Returns: #GST_RTSP_OK on success.
2000 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2004 GstRTSPBuilder builder;
2008 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2009 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2010 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2012 /* configure timeout if any */
2013 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2015 gst_poll_set_controllable (conn->fdset, TRUE);
2016 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2017 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2019 memset (&builder, 0, sizeof (GstRTSPBuilder));
2021 res = build_next (&builder, message, conn);
2022 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2024 if (G_LIKELY (res == GST_RTSP_OK))
2026 if (res == GST_RTSP_ETGET) {
2029 /* tunnel GET request, we can reply now */
2030 str = gen_tunnel_reply (conn, GST_RTSP_STS_OK);
2032 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len,
2034 g_string_free (str, TRUE);
2035 } else if (res == GST_RTSP_ETPOST) {
2036 /* tunnel POST request, return the value, the caller now has to link the
2037 * two connections. */
2039 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2043 retval = gst_poll_wait (conn->fdset, to);
2044 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2046 /* check for timeout */
2047 if (G_UNLIKELY (retval == 0))
2048 goto select_timeout;
2050 if (G_UNLIKELY (retval == -1)) {
2056 gst_poll_set_controllable (conn->fdset, FALSE);
2059 /* we have a message here */
2060 build_reset (&builder);
2067 res = GST_RTSP_ESYS;
2072 res = GST_RTSP_ETIMEOUT;
2077 res = GST_RTSP_EINTR;
2082 res = GST_RTSP_EEOF;
2088 build_reset (&builder);
2089 gst_rtsp_message_unset (message);
2095 * gst_rtsp_connection_close:
2096 * @conn: a #GstRTSPConnection
2098 * Close the connected @conn. After this call, the connection is in the same
2099 * state as when it was first created.
2101 * Returns: #GST_RTSP_OK on success.
2104 gst_rtsp_connection_close (GstRTSPConnection * conn)
2106 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2111 g_free (conn->initial_buffer);
2112 conn->initial_buffer = NULL;
2113 conn->initial_buffer_offset = 0;
2115 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2116 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2117 conn->writefd = NULL;
2118 conn->readfd = NULL;
2119 conn->tunneled = FALSE;
2120 conn->tstate = TUNNEL_STATE_NONE;
2122 g_free (conn->username);
2123 conn->username = NULL;
2124 g_free (conn->passwd);
2125 conn->passwd = NULL;
2126 gst_rtsp_connection_clear_auth_params (conn);
2129 conn->session_id[0] = '\0';
2135 * gst_rtsp_connection_free:
2136 * @conn: a #GstRTSPConnection
2138 * Close and free @conn.
2140 * Returns: #GST_RTSP_OK on success.
2143 gst_rtsp_connection_free (GstRTSPConnection * conn)
2147 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2149 res = gst_rtsp_connection_close (conn);
2150 gst_poll_free (conn->fdset);
2151 g_timer_destroy (conn->timer);
2152 gst_rtsp_url_free (conn->url);
2153 g_free (conn->proxy_host);
2163 * gst_rtsp_connection_poll:
2164 * @conn: a #GstRTSPConnection
2165 * @events: a bitmask of #GstRTSPEvent flags to check
2166 * @revents: location for result flags
2167 * @timeout: a timeout
2169 * Wait up to the specified @timeout for the connection to become available for
2170 * at least one of the operations specified in @events. When the function returns
2171 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2174 * @timeout can be #NULL, in which case this function might block forever.
2176 * This function can be cancelled with gst_rtsp_connection_flush().
2178 * Returns: #GST_RTSP_OK on success.
2183 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2184 GstRTSPEvent * revents, GTimeVal * timeout)
2189 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2190 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2191 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2192 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2193 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2195 gst_poll_set_controllable (conn->fdset, TRUE);
2197 /* add fd to writer set when asked to */
2198 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2199 events & GST_RTSP_EV_WRITE);
2201 /* add fd to reader set when asked to */
2202 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2204 /* configure timeout if any */
2205 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2208 retval = gst_poll_wait (conn->fdset, to);
2209 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2211 if (G_UNLIKELY (retval == 0))
2212 goto select_timeout;
2214 if (G_UNLIKELY (retval == -1)) {
2222 if (events & GST_RTSP_EV_READ) {
2223 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2224 *revents |= GST_RTSP_EV_READ;
2226 if (events & GST_RTSP_EV_WRITE) {
2227 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2228 *revents |= GST_RTSP_EV_WRITE;
2235 return GST_RTSP_ETIMEOUT;
2239 return GST_RTSP_ESYS;
2243 return GST_RTSP_EINTR;
2248 * gst_rtsp_connection_next_timeout:
2249 * @conn: a #GstRTSPConnection
2250 * @timeout: a timeout
2252 * Calculate the next timeout for @conn, storing the result in @timeout.
2254 * Returns: #GST_RTSP_OK.
2257 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2263 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2264 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2266 elapsed = g_timer_elapsed (conn->timer, &usec);
2267 if (elapsed >= conn->timeout) {
2271 sec = conn->timeout - elapsed;
2274 timeout->tv_sec = sec;
2275 timeout->tv_usec = usec;
2281 * gst_rtsp_connection_reset_timeout:
2282 * @conn: a #GstRTSPConnection
2284 * Reset the timeout of @conn.
2286 * Returns: #GST_RTSP_OK.
2289 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2291 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2293 g_timer_start (conn->timer);
2299 * gst_rtsp_connection_flush:
2300 * @conn: a #GstRTSPConnection
2301 * @flush: start or stop the flush
2303 * Start or stop the flushing action on @conn. When flushing, all current
2304 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2305 * is set to non-flushing mode again.
2307 * Returns: #GST_RTSP_OK.
2310 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2312 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2314 gst_poll_set_flushing (conn->fdset, flush);
2320 * gst_rtsp_connection_set_proxy:
2321 * @conn: a #GstRTSPConnection
2322 * @host: the proxy host
2323 * @port: the proxy port
2325 * Set the proxy host and port.
2327 * Returns: #GST_RTSP_OK.
2332 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2333 const gchar * host, guint port)
2335 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2337 g_free (conn->proxy_host);
2338 conn->proxy_host = g_strdup (host);
2339 conn->proxy_port = port;
2345 * gst_rtsp_connection_set_auth:
2346 * @conn: a #GstRTSPConnection
2347 * @method: authentication method
2349 * @pass: the password
2351 * Configure @conn for authentication mode @method with @user and @pass as the
2352 * user and password respectively.
2354 * Returns: #GST_RTSP_OK.
2357 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2358 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2360 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2362 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2363 || g_strrstr (user, ":") != NULL))
2364 return GST_RTSP_EINVAL;
2366 /* Make sure the username and passwd are being set for authentication */
2367 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2368 return GST_RTSP_EINVAL;
2370 /* ":" chars are not allowed in usernames for basic auth */
2371 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2372 return GST_RTSP_EINVAL;
2374 g_free (conn->username);
2375 g_free (conn->passwd);
2377 conn->auth_method = method;
2378 conn->username = g_strdup (user);
2379 conn->passwd = g_strdup (pass);
2386 * @key: ASCII string to hash
2388 * Hashes @key in a case-insensitive manner.
2390 * Returns: the hash code.
2393 str_case_hash (gconstpointer key)
2395 const char *p = key;
2396 guint h = g_ascii_toupper (*p);
2399 for (p += 1; *p != '\0'; p++)
2400 h = (h << 5) - h + g_ascii_toupper (*p);
2407 * @v1: an ASCII string
2408 * @v2: another ASCII string
2410 * Compares @v1 and @v2 in a case-insensitive manner
2412 * Returns: %TRUE if they are equal (modulo case)
2415 str_case_equal (gconstpointer v1, gconstpointer v2)
2417 const char *string1 = v1;
2418 const char *string2 = v2;
2420 return g_ascii_strcasecmp (string1, string2) == 0;
2424 * gst_rtsp_connection_set_auth_param:
2425 * @conn: a #GstRTSPConnection
2426 * @param: authentication directive
2429 * Setup @conn with authentication directives. This is not necesary for
2430 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2431 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2432 * in the WWW-Authenticate response header and can include realm, domain,
2433 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2438 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2439 const gchar * param, const gchar * value)
2441 g_return_if_fail (conn != NULL);
2442 g_return_if_fail (param != NULL);
2444 if (conn->auth_params == NULL) {
2446 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2448 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2452 * gst_rtsp_connection_clear_auth_params:
2453 * @conn: a #GstRTSPConnection
2455 * Clear the list of authentication directives stored in @conn.
2460 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2462 g_return_if_fail (conn != NULL);
2464 if (conn->auth_params != NULL) {
2465 g_hash_table_destroy (conn->auth_params);
2466 conn->auth_params = NULL;
2470 static GstRTSPResult
2471 set_qos_dscp (gint fd, guint qos_dscp)
2473 union gst_sockaddr sa;
2474 socklen_t slen = sizeof (sa);
2481 if (getsockname (fd, &sa.sa, &slen) < 0)
2482 goto no_getsockname;
2484 af = sa.sa.sa_family;
2486 /* if this is an IPv4-mapped address then do IPv4 QoS */
2487 if (af == AF_INET6) {
2488 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2492 /* extract and shift 6 bits of the DSCP */
2493 tos = (qos_dscp & 0x3f) << 2;
2497 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2502 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2516 return GST_RTSP_ESYS;
2521 return GST_RTSP_ERROR;
2526 * gst_rtsp_connection_set_qos_dscp:
2527 * @conn: a #GstRTSPConnection
2528 * @qos_dscp: DSCP value
2530 * Configure @conn to use the specified DSCP value.
2532 * Returns: #GST_RTSP_OK on success.
2537 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2541 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2542 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2543 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2545 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2546 if (res == GST_RTSP_OK)
2547 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2554 * gst_rtsp_connection_get_url:
2555 * @conn: a #GstRTSPConnection
2557 * Retrieve the URL of the other end of @conn.
2559 * Returns: The URL. This value remains valid until the
2560 * connection is freed.
2565 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2567 g_return_val_if_fail (conn != NULL, NULL);
2573 * gst_rtsp_connection_get_ip:
2574 * @conn: a #GstRTSPConnection
2576 * Retrieve the IP address of the other end of @conn.
2578 * Returns: The IP address as a string. this value remains valid until the
2579 * connection is closed.
2584 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2586 g_return_val_if_fail (conn != NULL, NULL);
2592 * gst_rtsp_connection_set_ip:
2593 * @conn: a #GstRTSPConnection
2594 * @ip: an ip address
2596 * Set the IP address of the server.
2601 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2603 g_return_if_fail (conn != NULL);
2606 conn->ip = g_strdup (ip);
2610 * gst_rtsp_connection_get_readfd:
2611 * @conn: a #GstRTSPConnection
2613 * Get the file descriptor for reading.
2615 * Returns: the file descriptor used for reading or -1 on error. The file
2616 * descriptor remains valid until the connection is closed.
2621 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2623 g_return_val_if_fail (conn != NULL, -1);
2624 g_return_val_if_fail (conn->readfd != NULL, -1);
2626 return conn->readfd->fd;
2630 * gst_rtsp_connection_get_writefd:
2631 * @conn: a #GstRTSPConnection
2633 * Get the file descriptor for writing.
2635 * Returns: the file descriptor used for writing or -1 on error. The file
2636 * descriptor remains valid until the connection is closed.
2641 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2643 g_return_val_if_fail (conn != NULL, -1);
2644 g_return_val_if_fail (conn->writefd != NULL, -1);
2646 return conn->writefd->fd;
2651 * gst_rtsp_connection_set_tunneled:
2652 * @conn: a #GstRTSPConnection
2653 * @tunneled: the new state
2655 * Set the HTTP tunneling state of the connection. This must be configured before
2656 * the @conn is connected.
2661 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2663 g_return_if_fail (conn != NULL);
2664 g_return_if_fail (conn->readfd == NULL);
2665 g_return_if_fail (conn->writefd == NULL);
2667 conn->tunneled = tunneled;
2671 * gst_rtsp_connection_is_tunneled:
2672 * @conn: a #GstRTSPConnection
2674 * Get the tunneling state of the connection.
2676 * Returns: if @conn is using HTTP tunneling.
2681 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2683 g_return_val_if_fail (conn != NULL, FALSE);
2685 return conn->tunneled;
2689 * gst_rtsp_connection_get_tunnelid:
2690 * @conn: a #GstRTSPConnection
2692 * Get the tunnel session id the connection.
2694 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2699 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2701 g_return_val_if_fail (conn != NULL, NULL);
2703 if (!conn->tunneled)
2706 return conn->tunnelid;
2710 * gst_rtsp_connection_do_tunnel:
2711 * @conn: a #GstRTSPConnection
2712 * @conn2: a #GstRTSPConnection
2714 * If @conn received the first tunnel connection and @conn2 received
2715 * the second tunnel connection, link the two connections together so that
2716 * @conn manages the tunneled connection.
2718 * After this call, @conn2 cannot be used anymore and must be freed with
2719 * gst_rtsp_connection_free().
2721 * Returns: return GST_RTSP_OK on success.
2726 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2727 GstRTSPConnection * conn2)
2729 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2730 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2731 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2732 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2733 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2736 /* both connections have fd0 as the read/write socket. start by taking the
2737 * socket from conn2 and set it as the socket in conn */
2738 conn->fd1 = conn2->fd0;
2740 /* clean up some of the state of conn2 */
2741 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2743 conn2->readfd = conn2->writefd = NULL;
2745 /* We make fd0 the write socket and fd1 the read socket. */
2746 conn->writefd = &conn->fd0;
2747 conn->readfd = &conn->fd1;
2749 conn->tstate = TUNNEL_STATE_COMPLETE;
2751 /* we need base64 decoding for the readfd */
2752 conn->ctx.state = 0;
2755 conn->ctx.coutl = 0;
2756 conn->ctxp = &conn->ctx;
2761 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2762 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2771 /* async functions */
2772 struct _GstRTSPWatch
2776 GstRTSPConnection *conn;
2778 GstRTSPBuilder builder;
2779 GstRTSPMessage message;
2783 gboolean write_added;
2785 /* queued message for transmission */
2787 GAsyncQueue *messages;
2793 GstRTSPWatchFuncs funcs;
2796 GDestroyNotify notify;
2800 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2802 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2804 if (watch->conn->initial_buffer != NULL)
2807 *timeout = (watch->conn->timeout * 1000);
2813 gst_rtsp_source_check (GSource * source)
2815 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2817 if (watch->readfd.revents & READ_COND)
2820 if (watch->writefd.revents & WRITE_COND)
2827 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2828 gpointer user_data G_GNUC_UNUSED)
2830 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2833 /* first read as much as we can */
2834 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2836 res = build_next (&watch->builder, &watch->message, watch->conn);
2837 if (res == GST_RTSP_EINTR)
2839 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2841 if (res == GST_RTSP_ETGET) {
2843 GstRTSPStatusCode code;
2846 if (watch->funcs.tunnel_start)
2847 code = watch->funcs.tunnel_start (watch, watch->user_data);
2849 code = GST_RTSP_STS_OK;
2851 /* queue the response string */
2852 str = gen_tunnel_reply (watch->conn, code);
2854 gst_rtsp_watch_queue_data (watch, (guint8 *) g_string_free (str, FALSE),
2856 } else if (res == GST_RTSP_ETPOST) {
2857 /* in the callback the connection should be tunneled with the
2859 if (watch->funcs.tunnel_complete)
2860 watch->funcs.tunnel_complete (watch, watch->user_data);
2861 } else if (G_UNLIKELY (res != GST_RTSP_OK))
2864 if (G_LIKELY (res == GST_RTSP_OK)) {
2865 if (watch->funcs.message_received)
2866 watch->funcs.message_received (watch, &watch->message,
2869 gst_rtsp_message_unset (&watch->message);
2871 build_reset (&watch->builder);
2875 if (watch->writefd.revents & WRITE_COND) {
2877 if (watch->write_data == NULL) {
2880 /* get a new message from the queue */
2881 rec = g_async_queue_try_pop (watch->messages);
2885 watch->write_off = 0;
2886 watch->write_data = rec->data;
2887 watch->write_size = rec->size;
2888 watch->write_id = rec->id;
2890 g_slice_free (GstRTSPRec, rec);
2893 res = write_bytes (watch->writefd.fd, watch->write_data,
2894 &watch->write_off, watch->write_size);
2895 if (res == GST_RTSP_EINTR)
2897 if (G_UNLIKELY (res != GST_RTSP_OK))
2900 if (watch->funcs.message_sent)
2901 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
2904 if (g_async_queue_length (watch->messages) == 0 && watch->write_added) {
2905 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2906 watch->write_added = FALSE;
2907 watch->writefd.revents = 0;
2909 g_free (watch->write_data);
2910 watch->write_data = NULL;
2919 if (watch->funcs.closed)
2920 watch->funcs.closed (watch, watch->user_data);
2925 if (watch->funcs.error)
2926 watch->funcs.error (watch, res, watch->user_data);
2932 gst_rtsp_rec_free (gpointer data)
2934 GstRTSPRec *rec = data;
2937 g_slice_free (GstRTSPRec, rec);
2941 gst_rtsp_source_finalize (GSource * source)
2943 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2945 build_reset (&watch->builder);
2946 gst_rtsp_message_unset (&watch->message);
2948 g_async_queue_unref (watch->messages);
2949 watch->messages = NULL;
2951 g_free (watch->write_data);
2954 watch->notify (watch->user_data);
2957 static GSourceFuncs gst_rtsp_source_funcs = {
2958 gst_rtsp_source_prepare,
2959 gst_rtsp_source_check,
2960 gst_rtsp_source_dispatch,
2961 gst_rtsp_source_finalize,
2967 * gst_rtsp_watch_new:
2968 * @conn: a #GstRTSPConnection
2969 * @funcs: watch functions
2970 * @user_data: user data to pass to @funcs
2971 * @notify: notify when @user_data is not referenced anymore
2973 * Create a watch object for @conn. The functions provided in @funcs will be
2974 * called with @user_data when activity happened on the watch.
2976 * The new watch is usually created so that it can be attached to a
2977 * maincontext with gst_rtsp_watch_attach().
2979 * @conn must exist for the entire lifetime of the watch.
2981 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2982 * communication. Free with gst_rtsp_watch_unref () after usage.
2987 gst_rtsp_watch_new (GstRTSPConnection * conn,
2988 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2990 GstRTSPWatch *result;
2992 g_return_val_if_fail (conn != NULL, NULL);
2993 g_return_val_if_fail (funcs != NULL, NULL);
2994 g_return_val_if_fail (conn->readfd != NULL, NULL);
2995 g_return_val_if_fail (conn->writefd != NULL, NULL);
2997 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2998 sizeof (GstRTSPWatch));
3000 result->conn = conn;
3001 result->builder.state = STATE_START;
3003 result->messages = g_async_queue_new_full (gst_rtsp_rec_free);
3005 result->readfd.fd = -1;
3006 result->writefd.fd = -1;
3008 gst_rtsp_watch_reset (result);
3010 result->funcs = *funcs;
3011 result->user_data = user_data;
3012 result->notify = notify;
3014 /* only add the read fd, the write fd is only added when we have data
3016 g_source_add_poll ((GSource *) result, &result->readfd);
3022 * gst_rtsp_watch_reset:
3023 * @watch: a #GstRTSPWatch
3025 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3026 * when the file descriptors of the connection might have changed.
3031 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3033 if (watch->readfd.fd != -1)
3034 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3035 if (watch->writefd.fd != -1)
3036 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3038 watch->readfd.fd = watch->conn->readfd->fd;
3039 watch->readfd.events = READ_COND;
3040 watch->readfd.revents = 0;
3042 watch->writefd.fd = watch->conn->writefd->fd;
3043 watch->writefd.events = WRITE_COND;
3044 watch->writefd.revents = 0;
3045 watch->write_added = FALSE;
3047 g_source_add_poll ((GSource *) watch, &watch->readfd);
3051 * gst_rtsp_watch_attach:
3052 * @watch: a #GstRTSPWatch
3053 * @context: a GMainContext (if NULL, the default context will be used)
3055 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3057 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3062 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3064 g_return_val_if_fail (watch != NULL, 0);
3066 return g_source_attach ((GSource *) watch, context);
3070 * gst_rtsp_watch_unref:
3071 * @watch: a #GstRTSPWatch
3073 * Decreases the reference count of @watch by one. If the resulting reference
3074 * count is zero the watch and associated memory will be destroyed.
3079 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3081 g_return_if_fail (watch != NULL);
3083 g_source_unref ((GSource *) watch);
3087 * gst_rtsp_watch_queue_data:
3088 * @watch: a #GstRTSPWatch
3089 * @data: the data to queue
3090 * @size: the size of @data
3092 * Queue @data for transmission in @watch. It will be transmitted when the
3093 * connection of the @watch becomes writable.
3095 * This function will take ownership of @data and g_free() it after use.
3097 * The return value of this function will be used as the id argument in the
3098 * message_sent callback.
3105 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3110 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3111 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3112 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3114 /* make a record with the data and id */
3115 rec = g_slice_new (GstRTSPRec);
3116 rec->data = (guint8 *) data;
3119 /* make sure rec->id is never 0 */
3120 rec->id = ++watch->id;
3121 } while (G_UNLIKELY (rec->id == 0));
3123 /* add the record to a queue. FIXME we would like to have an upper limit here */
3124 g_async_queue_push (watch->messages, rec);
3126 /* FIXME: does the following need to be made thread-safe? (this might be
3127 * called from a streaming thread, like appsink's render function) */
3128 /* make sure the main context will now also check for writability on the
3130 if (!watch->write_added) {
3131 g_source_add_poll ((GSource *) watch, &watch->writefd);
3132 watch->write_added = TRUE;
3139 * gst_rtsp_watch_queue_message:
3140 * @watch: a #GstRTSPWatch
3141 * @message: a #GstRTSPMessage
3143 * Queue a @message for transmission in @watch. The contents of this
3144 * message will be serialized and transmitted when the connection of the
3145 * @watch becomes writable.
3147 * The return value of this function will be used as the id argument in the
3148 * message_sent callback.
3155 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3160 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3161 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3163 /* make a record with the message as a string and id */
3164 str = message_to_string (watch->conn, message);
3166 return gst_rtsp_watch_queue_data (watch,
3167 (guint8 *) g_string_free (str, FALSE), size);