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)
631 gchar *ip, *url_port_str;
632 guint16 port, url_port;
633 gchar codestr[4], *resultstr;
638 /* create a random sessionid */
639 for (i = 0; i < TUNNELID_LEN; i++)
640 conn->tunnelid[i] = g_random_int_range ('a', 'z');
641 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
644 /* get the port from the url */
645 gst_rtsp_url_get_port (url, &url_port);
647 if (conn->proxy_host) {
648 hostparam = g_strdup_printf ("Host: %s:%d\r\n", url->host, url_port);
649 url_port_str = g_strdup_printf (":%d", url_port);
650 ip = conn->proxy_host;
651 port = conn->proxy_port;
660 str = g_strdup_printf ("GET %s%s%s%s%s%s HTTP/1.0\r\n"
662 "x-sessioncookie: %s\r\n"
663 "Accept: application/x-rtsp-tunnelled\r\n"
664 "Pragma: no-cache\r\n"
665 "Cache-Control: no-cache\r\n" "\r\n",
666 conn->proxy_host ? "http://" : "",
667 conn->proxy_host ? url->host : "",
668 conn->proxy_host ? url_port_str : "",
669 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
670 hostparam ? hostparam : "", conn->tunnelid);
672 /* we start by writing to this fd */
673 conn->writefd = &conn->fd0;
675 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
677 if (res != GST_RTSP_OK)
680 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
681 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
683 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
691 res = read_line (conn, buffer, &idx, sizeof (buffer));
692 if (res == GST_RTSP_EEOF)
694 if (res == GST_RTSP_OK)
696 if (res != GST_RTSP_EINTR)
700 retval = gst_poll_wait (conn->fdset, to);
701 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
703 /* check for timeout */
715 /* check for last line */
716 if (buffer[0] == '\r')
718 if (buffer[0] == '\0')
722 /* first line, parse response */
723 gchar versionstr[20];
726 bptr = (gchar *) buffer;
728 parse_string (versionstr, sizeof (versionstr), &bptr);
729 parse_string (codestr, sizeof (codestr), &bptr);
730 code = atoi (codestr);
732 while (g_ascii_isspace (*bptr))
737 if (code != GST_RTSP_STS_OK)
743 /* other lines, parse key/value */
744 res = parse_key_value (buffer, key, sizeof (key), &value);
745 if (res == GST_RTSP_OK) {
746 /* we got a new ip address */
747 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
748 if (conn->proxy_host) {
749 /* if we use a proxy we need to change the destination url */
751 url->host = g_strdup (value);
753 g_free (url_port_str);
755 g_strdup_printf ("Host: %s:%d\r\n", url->host, url_port);
756 url_port_str = g_strdup_printf (":%d", url_port);
758 /* and resolve the new ip address */
759 if (!(ip = do_resolve (conn->ip)))
770 /* connect to the host/port */
771 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
772 if (res != GST_RTSP_OK)
775 /* this is now our writing socket */
776 conn->writefd = &conn->fd1;
779 str = g_strdup_printf ("POST %s%s%s%s%s%s HTTP/1.0\r\n"
781 "x-sessioncookie: %s\r\n"
782 "Content-Type: application/x-rtsp-tunnelled\r\n"
783 "Pragma: no-cache\r\n"
784 "Cache-Control: no-cache\r\n"
785 "Content-Length: 32767\r\n"
786 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
788 conn->proxy_host ? "http://" : "",
789 conn->proxy_host ? url->host : "",
790 conn->proxy_host ? url_port_str : "",
791 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
792 hostparam ? hostparam : "", conn->tunnelid);
794 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
796 if (res != GST_RTSP_OK)
801 g_free (url_port_str);
808 GST_ERROR ("write failed (%d)", res);
822 res = GST_RTSP_ETIMEOUT;
832 res = GST_RTSP_EINTR;
837 GST_ERROR ("got failure response %d %s", code, resultstr);
838 res = GST_RTSP_ERROR;
843 GST_ERROR ("could not resolve %s", conn->ip);
849 GST_ERROR ("failed to connect");
855 * gst_rtsp_connection_connect:
856 * @conn: a #GstRTSPConnection
857 * @timeout: a #GTimeVal timeout
859 * Attempt to connect to the url of @conn made with
860 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
861 * forever. If @timeout contains a valid timeout, this function will return
862 * #GST_RTSP_ETIMEOUT after the timeout expired.
864 * This function can be cancelled with gst_rtsp_connection_flush().
866 * Returns: #GST_RTSP_OK when a connection could be made.
869 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
876 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
877 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
878 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
882 if (conn->proxy_host && conn->tunneled) {
883 if (!(ip = do_resolve (conn->proxy_host))) {
884 GST_ERROR ("could not resolve %s", conn->proxy_host);
887 port = conn->proxy_port;
888 g_free (conn->proxy_host);
889 conn->proxy_host = ip;
891 if (!(ip = do_resolve (url->host))) {
892 GST_ERROR ("could not resolve %s", url->host);
895 /* get the port from the url */
896 gst_rtsp_url_get_port (url, &port);
902 /* connect to the host/port */
903 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
904 if (res != GST_RTSP_OK)
907 /* this is our read URL */
908 conn->readfd = &conn->fd0;
910 if (conn->tunneled) {
911 res = setup_tunneling (conn, timeout);
912 if (res != GST_RTSP_OK)
913 goto tunneling_failed;
915 conn->writefd = &conn->fd0;
922 return GST_RTSP_ENET;
926 GST_ERROR ("failed to connect");
931 GST_ERROR ("failed to setup tunneling");
937 auth_digest_compute_hex_urp (const gchar * username,
938 const gchar * realm, const gchar * password, gchar hex_urp[33])
940 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
941 const gchar *digest_string;
943 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
944 g_checksum_update (md5_context, (const guchar *) ":", 1);
945 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
946 g_checksum_update (md5_context, (const guchar *) ":", 1);
947 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
948 digest_string = g_checksum_get_string (md5_context);
950 memset (hex_urp, 0, 33);
951 memcpy (hex_urp, digest_string, strlen (digest_string));
953 g_checksum_free (md5_context);
957 auth_digest_compute_response (const gchar * method,
958 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
961 char hex_a2[33] = { 0, };
962 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
963 const gchar *digest_string;
966 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
967 g_checksum_update (md5_context, (const guchar *) ":", 1);
968 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
969 digest_string = g_checksum_get_string (md5_context);
970 memcpy (hex_a2, digest_string, strlen (digest_string));
973 #if GLIB_CHECK_VERSION (2, 18, 0)
974 g_checksum_reset (md5_context);
976 g_checksum_free (md5_context);
977 md5_context = g_checksum_new (G_CHECKSUM_MD5);
979 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
980 g_checksum_update (md5_context, (const guchar *) ":", 1);
981 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
982 g_checksum_update (md5_context, (const guchar *) ":", 1);
984 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
985 digest_string = g_checksum_get_string (md5_context);
986 memset (response, 0, 33);
987 memcpy (response, digest_string, strlen (digest_string));
989 g_checksum_free (md5_context);
993 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
995 switch (conn->auth_method) {
996 case GST_RTSP_AUTH_BASIC:{
1001 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
1002 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
1003 auth_string = g_strdup_printf ("Basic %s", user_pass64);
1005 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1009 g_free (user_pass64);
1012 case GST_RTSP_AUTH_DIGEST:{
1013 gchar response[33], hex_urp[33];
1014 gchar *auth_string, *auth_string2;
1019 const gchar *method;
1021 /* we need to have some params set */
1022 if (conn->auth_params == NULL)
1025 /* we need the realm and nonce */
1026 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
1027 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
1028 if (realm == NULL || nonce == NULL)
1031 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
1034 method = gst_rtsp_method_as_text (message->type_data.request.method);
1035 uri = message->type_data.request.uri;
1037 /* Assume no qop, algorithm=md5, stale=false */
1038 /* For algorithm MD5, a1 = urp. */
1039 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
1040 auth_string = g_strdup_printf ("Digest username=\"%s\", "
1041 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
1042 conn->username, realm, nonce, uri, response);
1044 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
1046 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
1048 g_free (auth_string);
1049 auth_string = auth_string2;
1051 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1062 gen_date_string (gchar * date_string, guint len)
1066 #ifdef HAVE_GMTIME_R
1070 g_get_current_time (&tv);
1071 t = (time_t) tv.tv_sec;
1073 #ifdef HAVE_GMTIME_R
1074 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1076 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1080 static GstRTSPResult
1081 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1085 if (G_UNLIKELY (*idx > size))
1086 return GST_RTSP_ERROR;
1093 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1094 if (G_UNLIKELY (r == 0)) {
1095 return GST_RTSP_EINTR;
1096 } else if (G_UNLIKELY (r < 0)) {
1097 if (ERRNO_IS_EAGAIN)
1098 return GST_RTSP_EINTR;
1099 if (!ERRNO_IS_EINTR)
1100 return GST_RTSP_ESYS;
1110 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1114 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1115 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1117 out = MIN (left, size);
1118 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1120 if (left == (gsize) out) {
1121 g_free (conn->initial_buffer);
1122 conn->initial_buffer = NULL;
1123 conn->initial_buffer_offset = 0;
1125 conn->initial_buffer_offset += out;
1128 if (G_LIKELY (size > (guint) out)) {
1131 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1143 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1145 DecodeCtx *ctx = conn->ctxp;
1150 guint8 in[sizeof (ctx->out) * 4 / 3];
1153 while (size > 0 && ctx->cout < ctx->coutl) {
1154 /* we have some leftover bytes */
1155 *buffer++ = ctx->out[ctx->cout++];
1160 /* got what we needed? */
1164 /* try to read more bytes */
1165 r = fill_raw_bytes (conn, in, sizeof (in));
1174 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1178 out = fill_raw_bytes (conn, buffer, size);
1184 static GstRTSPResult
1185 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1189 if (G_UNLIKELY (*idx > size))
1190 return GST_RTSP_ERROR;
1197 r = fill_bytes (conn, &buffer[*idx], left);
1198 if (G_UNLIKELY (r == 0)) {
1199 return GST_RTSP_EEOF;
1200 } else if (G_UNLIKELY (r < 0)) {
1201 if (ERRNO_IS_EAGAIN)
1202 return GST_RTSP_EINTR;
1203 if (!ERRNO_IS_EINTR)
1204 return GST_RTSP_ESYS;
1213 static GstRTSPResult
1214 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1220 r = fill_bytes (conn, &c, 1);
1221 if (G_UNLIKELY (r == 0)) {
1222 return GST_RTSP_EEOF;
1223 } else if (G_UNLIKELY (r < 0)) {
1224 if (ERRNO_IS_EAGAIN)
1225 return GST_RTSP_EINTR;
1226 if (!ERRNO_IS_EINTR)
1227 return GST_RTSP_ESYS;
1229 if (c == '\n') /* end on \n */
1231 if (c == '\r') /* ignore \r */
1234 if (G_LIKELY (*idx < size - 1))
1235 buffer[(*idx)++] = c;
1238 buffer[*idx] = '\0';
1244 * gst_rtsp_connection_write:
1245 * @conn: a #GstRTSPConnection
1246 * @data: the data to write
1247 * @size: the size of @data
1248 * @timeout: a timeout value or #NULL
1250 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1251 * the specified @timeout. @timeout can be #NULL, in which case this function
1252 * might block forever.
1254 * This function can be cancelled with gst_rtsp_connection_flush().
1256 * Returns: #GST_RTSP_OK on success.
1259 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1260 guint size, GTimeVal * timeout)
1267 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1268 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1269 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1271 gst_poll_set_controllable (conn->fdset, TRUE);
1272 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1273 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1274 /* clear all previous poll results */
1275 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1276 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1278 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1284 res = write_bytes (conn->writefd->fd, data, &offset, size);
1285 if (G_LIKELY (res == GST_RTSP_OK))
1287 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1290 /* not all is written, wait until we can write more */
1292 retval = gst_poll_wait (conn->fdset, to);
1293 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1295 if (G_UNLIKELY (retval == 0))
1298 if (G_UNLIKELY (retval == -1)) {
1310 return GST_RTSP_ETIMEOUT;
1314 return GST_RTSP_ESYS;
1318 return GST_RTSP_EINTR;
1327 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1329 GString *str = NULL;
1331 str = g_string_new ("");
1333 switch (message->type) {
1334 case GST_RTSP_MESSAGE_REQUEST:
1335 /* create request string, add CSeq */
1336 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1338 gst_rtsp_method_as_text (message->type_data.request.method),
1339 message->type_data.request.uri, conn->cseq++);
1340 /* add session id if we have one */
1341 if (conn->session_id[0] != '\0') {
1342 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1343 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1346 /* add any authentication headers */
1347 add_auth_header (conn, message);
1349 case GST_RTSP_MESSAGE_RESPONSE:
1350 /* create response string */
1351 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1352 message->type_data.response.code, message->type_data.response.reason);
1354 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1355 /* create request string */
1356 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1357 gst_rtsp_method_as_text (message->type_data.request.method),
1358 message->type_data.request.uri,
1359 gst_rtsp_version_as_text (message->type_data.request.version));
1360 /* add any authentication headers */
1361 add_auth_header (conn, message);
1363 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1364 /* create response string */
1365 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1366 gst_rtsp_version_as_text (message->type_data.request.version),
1367 message->type_data.response.code, message->type_data.response.reason);
1369 case GST_RTSP_MESSAGE_DATA:
1371 guint8 data_header[4];
1373 /* prepare data header */
1374 data_header[0] = '$';
1375 data_header[1] = message->type_data.data.channel;
1376 data_header[2] = (message->body_size >> 8) & 0xff;
1377 data_header[3] = message->body_size & 0xff;
1379 /* create string with header and data */
1380 str = g_string_append_len (str, (gchar *) data_header, 4);
1382 g_string_append_len (str, (gchar *) message->body,
1383 message->body_size);
1387 g_string_free (str, TRUE);
1388 g_return_val_if_reached (NULL);
1392 /* append headers and body */
1393 if (message->type != GST_RTSP_MESSAGE_DATA) {
1394 gchar date_string[100];
1396 gen_date_string (date_string, sizeof (date_string));
1398 /* add date header */
1399 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1400 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1402 /* append headers */
1403 gst_rtsp_message_append_headers (message, str);
1405 /* append Content-Length and body if needed */
1406 if (message->body != NULL && message->body_size > 0) {
1409 len = g_strdup_printf ("%d", message->body_size);
1410 g_string_append_printf (str, "%s: %s\r\n",
1411 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1413 /* header ends here */
1414 g_string_append (str, "\r\n");
1416 g_string_append_len (str, (gchar *) message->body,
1417 message->body_size);
1419 /* just end headers */
1420 g_string_append (str, "\r\n");
1428 * gst_rtsp_connection_send:
1429 * @conn: a #GstRTSPConnection
1430 * @message: the message to send
1431 * @timeout: a timeout value or #NULL
1433 * Attempt to send @message to the connected @conn, blocking up to
1434 * the specified @timeout. @timeout can be #NULL, in which case this function
1435 * might block forever.
1437 * This function can be cancelled with gst_rtsp_connection_flush().
1439 * Returns: #GST_RTSP_OK on success.
1442 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1445 GString *string = NULL;
1450 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1451 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1453 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1456 if (conn->tunneled) {
1457 str = g_base64_encode ((const guchar *) string->str, string->len);
1458 g_string_free (string, TRUE);
1463 g_string_free (string, FALSE);
1467 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1475 g_warning ("Wrong message");
1476 return GST_RTSP_EINVAL;
1480 static GstRTSPResult
1481 parse_string (gchar * dest, gint size, gchar ** src)
1483 GstRTSPResult res = GST_RTSP_OK;
1488 while (g_ascii_isspace (**src))
1491 while (!g_ascii_isspace (**src) && **src != '\0') {
1493 dest[idx++] = **src;
1495 res = GST_RTSP_EPARSE;
1505 parse_key (gchar * dest, gint size, gchar ** src)
1510 while (**src != ':' && **src != '\0') {
1512 dest[idx++] = **src;
1519 static GstRTSPResult
1520 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1521 GstRTSPVersion * version)
1523 GstRTSPResult res = GST_RTSP_OK;
1526 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1533 /* the version number must be formatted as X.Y with nothing following */
1534 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1535 res = GST_RTSP_EPARSE;
1537 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1538 if (major != 1 || minor != 0) {
1539 *version = GST_RTSP_VERSION_INVALID;
1540 res = GST_RTSP_ERROR;
1542 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1543 if (*type == GST_RTSP_MESSAGE_REQUEST)
1544 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1545 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1546 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1548 if (major == 1 && minor == 1) {
1549 *version = GST_RTSP_VERSION_1_1;
1550 } else if (major != 1 || minor != 0) {
1551 *version = GST_RTSP_VERSION_INVALID;
1552 res = GST_RTSP_ERROR;
1555 res = GST_RTSP_EPARSE;
1557 res = GST_RTSP_EPARSE;
1562 static GstRTSPResult
1563 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1565 GstRTSPResult res = GST_RTSP_OK;
1567 gchar versionstr[20];
1572 bptr = (gchar *) buffer;
1574 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1575 res = GST_RTSP_EPARSE;
1577 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1578 res = GST_RTSP_EPARSE;
1579 code = atoi (codestr);
1580 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1581 res = GST_RTSP_EPARSE;
1583 while (g_ascii_isspace (*bptr))
1586 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1587 NULL) != GST_RTSP_OK))
1588 res = GST_RTSP_EPARSE;
1590 res2 = parse_protocol_version (versionstr, &msg->type,
1591 &msg->type_data.response.version);
1592 if (G_LIKELY (res == GST_RTSP_OK))
1598 static GstRTSPResult
1599 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1601 GstRTSPResult res = GST_RTSP_OK;
1603 gchar versionstr[20];
1604 gchar methodstr[20];
1607 GstRTSPMethod method;
1609 bptr = (gchar *) buffer;
1611 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1612 res = GST_RTSP_EPARSE;
1613 method = gst_rtsp_find_method (methodstr);
1615 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1616 res = GST_RTSP_EPARSE;
1617 if (G_UNLIKELY (*urlstr == '\0'))
1618 res = GST_RTSP_EPARSE;
1620 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1621 res = GST_RTSP_EPARSE;
1623 if (G_UNLIKELY (*bptr != '\0'))
1624 res = GST_RTSP_EPARSE;
1626 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1627 urlstr) != GST_RTSP_OK))
1628 res = GST_RTSP_EPARSE;
1630 res2 = parse_protocol_version (versionstr, &msg->type,
1631 &msg->type_data.request.version);
1632 if (G_LIKELY (res == GST_RTSP_OK))
1635 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1636 /* GET and POST are not allowed as RTSP methods */
1637 if (msg->type_data.request.method == GST_RTSP_GET ||
1638 msg->type_data.request.method == GST_RTSP_POST) {
1639 msg->type_data.request.method = GST_RTSP_INVALID;
1640 if (res == GST_RTSP_OK)
1641 res = GST_RTSP_ERROR;
1643 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1644 /* only GET and POST are allowed as HTTP methods */
1645 if (msg->type_data.request.method != GST_RTSP_GET &&
1646 msg->type_data.request.method != GST_RTSP_POST) {
1647 msg->type_data.request.method = GST_RTSP_INVALID;
1648 if (res == GST_RTSP_OK)
1649 res = GST_RTSP_ERROR;
1656 static GstRTSPResult
1657 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1661 bptr = (gchar *) buffer;
1664 parse_key (key, keysize, &bptr);
1665 if (G_UNLIKELY (*bptr != ':'))
1669 while (g_ascii_isspace (*bptr))
1679 return GST_RTSP_EPARSE;
1683 /* parsing lines means reading a Key: Value pair */
1684 static GstRTSPResult
1685 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1690 GstRTSPHeaderField field;
1692 res = parse_key_value (buffer, key, sizeof (key), &value);
1693 if (G_UNLIKELY (res != GST_RTSP_OK))
1696 field = gst_rtsp_find_header_field (key);
1697 if (field != GST_RTSP_HDR_INVALID)
1698 gst_rtsp_message_add_header (msg, field, value);
1709 /* convert all consecutive whitespace to a single space */
1711 normalize_line (guint8 * buffer)
1714 if (g_ascii_isspace (*buffer)) {
1718 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1721 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1729 * GST_RTSP_OK when a complete message was read.
1730 * GST_RTSP_EEOF: when the socket is closed
1731 * GST_RTSP_EINTR: when more data is needed.
1732 * GST_RTSP_..: some other error occured.
1734 static GstRTSPResult
1735 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1736 GstRTSPConnection * conn)
1741 switch (builder->state) {
1743 builder->offset = 0;
1745 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1746 if (res != GST_RTSP_OK)
1749 /* we have 1 bytes now and we can see if this is a data message or
1751 if (builder->buffer[0] == '$') {
1752 /* data message, prepare for the header */
1753 builder->state = STATE_DATA_HEADER;
1756 builder->state = STATE_READ_LINES;
1759 case STATE_DATA_HEADER:
1762 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1763 if (res != GST_RTSP_OK)
1766 gst_rtsp_message_init_data (message, builder->buffer[1]);
1768 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1769 builder->body_data = g_malloc (builder->body_len + 1);
1770 builder->body_data[builder->body_len] = '\0';
1771 builder->offset = 0;
1772 builder->state = STATE_DATA_BODY;
1775 case STATE_DATA_BODY:
1778 read_bytes (conn, builder->body_data, &builder->offset,
1780 if (res != GST_RTSP_OK)
1783 /* we have the complete body now, store in the message adjusting the
1784 * length to include the traling '\0' */
1785 gst_rtsp_message_take_body (message,
1786 (guint8 *) builder->body_data, builder->body_len + 1);
1787 builder->body_data = NULL;
1788 builder->body_len = 0;
1790 builder->state = STATE_END;
1793 case STATE_READ_LINES:
1795 res = read_line (conn, builder->buffer, &builder->offset,
1796 sizeof (builder->buffer));
1797 if (res != GST_RTSP_OK)
1800 /* we have a regular response */
1801 if (builder->buffer[0] == '\r') {
1802 builder->buffer[0] = '\0';
1805 if (builder->buffer[0] == '\0') {
1808 /* empty line, end of message header */
1809 /* see if there is a Content-Length header, but ignore it if this
1810 * is a POST request with an x-sessioncookie header */
1811 if (gst_rtsp_message_get_header (message,
1812 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1813 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1814 message->type_data.request.method != GST_RTSP_POST ||
1815 gst_rtsp_message_get_header (message,
1816 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1817 /* there is, prepare to read the body */
1818 builder->body_len = atol (hdrval);
1819 builder->body_data = g_malloc (builder->body_len + 1);
1820 builder->body_data[builder->body_len] = '\0';
1821 builder->offset = 0;
1822 builder->state = STATE_DATA_BODY;
1824 builder->state = STATE_END;
1829 /* we have a line */
1830 normalize_line (builder->buffer);
1831 if (builder->line == 0) {
1832 /* first line, check for response status */
1833 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1834 memcmp (builder->buffer, "HTTP", 4) == 0) {
1835 builder->status = parse_response_status (builder->buffer, message);
1837 builder->status = parse_request_line (builder->buffer, message);
1840 /* else just parse the line */
1841 res = parse_line (builder->buffer, message);
1842 if (res != GST_RTSP_OK)
1843 builder->status = res;
1846 builder->offset = 0;
1851 gchar *session_cookie;
1854 if (message->type == GST_RTSP_MESSAGE_DATA) {
1855 /* data messages don't have headers */
1860 /* save the tunnel session in the connection */
1861 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1862 !conn->manual_http &&
1863 conn->tstate == TUNNEL_STATE_NONE &&
1864 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1865 &session_cookie, 0) == GST_RTSP_OK) {
1866 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1867 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1868 conn->tunneled = TRUE;
1871 /* save session id in the connection for further use */
1872 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1873 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1874 &session_id, 0) == GST_RTSP_OK) {
1877 maxlen = sizeof (conn->session_id) - 1;
1878 /* the sessionid can have attributes marked with ;
1879 * Make sure we strip them */
1880 for (i = 0; session_id[i] != '\0'; i++) {
1881 if (session_id[i] == ';') {
1886 } while (g_ascii_isspace (session_id[i]));
1887 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1890 /* if we parsed something valid, configure */
1891 if ((to = atoi (&session_id[i + 8])) > 0)
1898 /* make sure to not overflow */
1899 strncpy (conn->session_id, session_id, maxlen);
1900 conn->session_id[maxlen] = '\0';
1902 res = builder->status;
1906 res = GST_RTSP_ERROR;
1915 * gst_rtsp_connection_read:
1916 * @conn: a #GstRTSPConnection
1917 * @data: the data to read
1918 * @size: the size of @data
1919 * @timeout: a timeout value or #NULL
1921 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1922 * the specified @timeout. @timeout can be #NULL, in which case this function
1923 * might block forever.
1925 * This function can be cancelled with gst_rtsp_connection_flush().
1927 * Returns: #GST_RTSP_OK on success.
1930 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1938 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1939 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1940 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1942 if (G_UNLIKELY (size == 0))
1947 /* configure timeout if any */
1948 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1950 gst_poll_set_controllable (conn->fdset, TRUE);
1951 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1952 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1955 res = read_bytes (conn, data, &offset, size);
1956 if (G_UNLIKELY (res == GST_RTSP_EEOF))
1958 if (G_LIKELY (res == GST_RTSP_OK))
1960 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1964 retval = gst_poll_wait (conn->fdset, to);
1965 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1967 /* check for timeout */
1968 if (G_UNLIKELY (retval == 0))
1969 goto select_timeout;
1971 if (G_UNLIKELY (retval == -1)) {
1977 gst_poll_set_controllable (conn->fdset, FALSE);
1984 return GST_RTSP_ESYS;
1988 return GST_RTSP_ETIMEOUT;
1992 return GST_RTSP_EINTR;
1996 return GST_RTSP_EEOF;
2004 static GstRTSPMessage *
2005 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
2006 const GstRTSPMessage * request)
2008 GstRTSPMessage *msg;
2011 if (gst_rtsp_status_as_text (code) == NULL)
2012 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
2014 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
2017 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
2018 "GStreamer RTSP Server");
2019 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2020 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2021 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2023 if (code == GST_RTSP_STS_OK) {
2025 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2027 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2028 "application/x-rtsp-tunnelled");
2041 * gst_rtsp_connection_receive:
2042 * @conn: a #GstRTSPConnection
2043 * @message: the message to read
2044 * @timeout: a timeout value or #NULL
2046 * Attempt to read into @message from the connected @conn, blocking up to
2047 * the specified @timeout. @timeout can be #NULL, in which case this function
2048 * might block forever.
2050 * This function can be cancelled with gst_rtsp_connection_flush().
2052 * Returns: #GST_RTSP_OK on success.
2055 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2059 GstRTSPBuilder builder;
2063 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2064 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2065 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2067 /* configure timeout if any */
2068 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2070 gst_poll_set_controllable (conn->fdset, TRUE);
2071 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2072 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2074 memset (&builder, 0, sizeof (GstRTSPBuilder));
2076 res = build_next (&builder, message, conn);
2077 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2079 else if (G_LIKELY (res == GST_RTSP_OK)) {
2080 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2081 if (conn->tstate == TUNNEL_STATE_NONE &&
2082 message->type_data.request.method == GST_RTSP_GET) {
2083 GstRTSPMessage *response;
2085 conn->tstate = TUNNEL_STATE_GET;
2087 /* tunnel GET request, we can reply now */
2088 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2089 res = gst_rtsp_connection_send (conn, response, timeout);
2090 gst_rtsp_message_free (response);
2091 if (res == GST_RTSP_OK)
2092 res = GST_RTSP_ETGET;
2094 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2095 message->type_data.request.method == GST_RTSP_POST) {
2096 conn->tstate = TUNNEL_STATE_POST;
2098 /* tunnel POST request, the caller now has to link the two
2100 res = GST_RTSP_ETPOST;
2103 res = GST_RTSP_EPARSE;
2109 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2113 retval = gst_poll_wait (conn->fdset, to);
2114 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2116 /* check for timeout */
2117 if (G_UNLIKELY (retval == 0))
2118 goto select_timeout;
2120 if (G_UNLIKELY (retval == -1)) {
2126 gst_poll_set_controllable (conn->fdset, FALSE);
2129 /* we have a message here */
2130 build_reset (&builder);
2137 res = GST_RTSP_ESYS;
2142 res = GST_RTSP_ETIMEOUT;
2147 res = GST_RTSP_EINTR;
2152 res = GST_RTSP_EEOF;
2158 build_reset (&builder);
2159 gst_rtsp_message_unset (message);
2165 * gst_rtsp_connection_close:
2166 * @conn: a #GstRTSPConnection
2168 * Close the connected @conn. After this call, the connection is in the same
2169 * state as when it was first created.
2171 * Returns: #GST_RTSP_OK on success.
2174 gst_rtsp_connection_close (GstRTSPConnection * conn)
2176 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2181 g_free (conn->initial_buffer);
2182 conn->initial_buffer = NULL;
2183 conn->initial_buffer_offset = 0;
2185 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2186 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2187 conn->writefd = NULL;
2188 conn->readfd = NULL;
2189 conn->tunneled = FALSE;
2190 conn->tstate = TUNNEL_STATE_NONE;
2192 g_free (conn->username);
2193 conn->username = NULL;
2194 g_free (conn->passwd);
2195 conn->passwd = NULL;
2196 gst_rtsp_connection_clear_auth_params (conn);
2199 conn->session_id[0] = '\0';
2205 * gst_rtsp_connection_free:
2206 * @conn: a #GstRTSPConnection
2208 * Close and free @conn.
2210 * Returns: #GST_RTSP_OK on success.
2213 gst_rtsp_connection_free (GstRTSPConnection * conn)
2217 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2219 res = gst_rtsp_connection_close (conn);
2220 gst_poll_free (conn->fdset);
2221 g_timer_destroy (conn->timer);
2222 gst_rtsp_url_free (conn->url);
2223 g_free (conn->proxy_host);
2233 * gst_rtsp_connection_poll:
2234 * @conn: a #GstRTSPConnection
2235 * @events: a bitmask of #GstRTSPEvent flags to check
2236 * @revents: location for result flags
2237 * @timeout: a timeout
2239 * Wait up to the specified @timeout for the connection to become available for
2240 * at least one of the operations specified in @events. When the function returns
2241 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2244 * @timeout can be #NULL, in which case this function might block forever.
2246 * This function can be cancelled with gst_rtsp_connection_flush().
2248 * Returns: #GST_RTSP_OK on success.
2253 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2254 GstRTSPEvent * revents, GTimeVal * timeout)
2259 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2260 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2261 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2262 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2263 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2265 gst_poll_set_controllable (conn->fdset, TRUE);
2267 /* add fd to writer set when asked to */
2268 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2269 events & GST_RTSP_EV_WRITE);
2271 /* add fd to reader set when asked to */
2272 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2274 /* configure timeout if any */
2275 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2278 retval = gst_poll_wait (conn->fdset, to);
2279 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2281 if (G_UNLIKELY (retval == 0))
2282 goto select_timeout;
2284 if (G_UNLIKELY (retval == -1)) {
2292 if (events & GST_RTSP_EV_READ) {
2293 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2294 *revents |= GST_RTSP_EV_READ;
2296 if (events & GST_RTSP_EV_WRITE) {
2297 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2298 *revents |= GST_RTSP_EV_WRITE;
2305 return GST_RTSP_ETIMEOUT;
2309 return GST_RTSP_ESYS;
2313 return GST_RTSP_EINTR;
2318 * gst_rtsp_connection_next_timeout:
2319 * @conn: a #GstRTSPConnection
2320 * @timeout: a timeout
2322 * Calculate the next timeout for @conn, storing the result in @timeout.
2324 * Returns: #GST_RTSP_OK.
2327 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2333 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2334 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2336 elapsed = g_timer_elapsed (conn->timer, &usec);
2337 if (elapsed >= conn->timeout) {
2341 sec = conn->timeout - elapsed;
2344 timeout->tv_sec = sec;
2345 timeout->tv_usec = usec;
2351 * gst_rtsp_connection_reset_timeout:
2352 * @conn: a #GstRTSPConnection
2354 * Reset the timeout of @conn.
2356 * Returns: #GST_RTSP_OK.
2359 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2361 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2363 g_timer_start (conn->timer);
2369 * gst_rtsp_connection_flush:
2370 * @conn: a #GstRTSPConnection
2371 * @flush: start or stop the flush
2373 * Start or stop the flushing action on @conn. When flushing, all current
2374 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2375 * is set to non-flushing mode again.
2377 * Returns: #GST_RTSP_OK.
2380 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2382 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2384 gst_poll_set_flushing (conn->fdset, flush);
2390 * gst_rtsp_connection_set_proxy:
2391 * @conn: a #GstRTSPConnection
2392 * @host: the proxy host
2393 * @port: the proxy port
2395 * Set the proxy host and port.
2397 * Returns: #GST_RTSP_OK.
2402 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2403 const gchar * host, guint port)
2405 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2407 g_free (conn->proxy_host);
2408 conn->proxy_host = g_strdup (host);
2409 conn->proxy_port = port;
2415 * gst_rtsp_connection_set_auth:
2416 * @conn: a #GstRTSPConnection
2417 * @method: authentication method
2419 * @pass: the password
2421 * Configure @conn for authentication mode @method with @user and @pass as the
2422 * user and password respectively.
2424 * Returns: #GST_RTSP_OK.
2427 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2428 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2430 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2432 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2433 || g_strrstr (user, ":") != NULL))
2434 return GST_RTSP_EINVAL;
2436 /* Make sure the username and passwd are being set for authentication */
2437 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2438 return GST_RTSP_EINVAL;
2440 /* ":" chars are not allowed in usernames for basic auth */
2441 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2442 return GST_RTSP_EINVAL;
2444 g_free (conn->username);
2445 g_free (conn->passwd);
2447 conn->auth_method = method;
2448 conn->username = g_strdup (user);
2449 conn->passwd = g_strdup (pass);
2456 * @key: ASCII string to hash
2458 * Hashes @key in a case-insensitive manner.
2460 * Returns: the hash code.
2463 str_case_hash (gconstpointer key)
2465 const char *p = key;
2466 guint h = g_ascii_toupper (*p);
2469 for (p += 1; *p != '\0'; p++)
2470 h = (h << 5) - h + g_ascii_toupper (*p);
2477 * @v1: an ASCII string
2478 * @v2: another ASCII string
2480 * Compares @v1 and @v2 in a case-insensitive manner
2482 * Returns: %TRUE if they are equal (modulo case)
2485 str_case_equal (gconstpointer v1, gconstpointer v2)
2487 const char *string1 = v1;
2488 const char *string2 = v2;
2490 return g_ascii_strcasecmp (string1, string2) == 0;
2494 * gst_rtsp_connection_set_auth_param:
2495 * @conn: a #GstRTSPConnection
2496 * @param: authentication directive
2499 * Setup @conn with authentication directives. This is not necesary for
2500 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2501 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2502 * in the WWW-Authenticate response header and can include realm, domain,
2503 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2508 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2509 const gchar * param, const gchar * value)
2511 g_return_if_fail (conn != NULL);
2512 g_return_if_fail (param != NULL);
2514 if (conn->auth_params == NULL) {
2516 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2518 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2522 * gst_rtsp_connection_clear_auth_params:
2523 * @conn: a #GstRTSPConnection
2525 * Clear the list of authentication directives stored in @conn.
2530 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2532 g_return_if_fail (conn != NULL);
2534 if (conn->auth_params != NULL) {
2535 g_hash_table_destroy (conn->auth_params);
2536 conn->auth_params = NULL;
2540 static GstRTSPResult
2541 set_qos_dscp (gint fd, guint qos_dscp)
2543 union gst_sockaddr sa;
2544 socklen_t slen = sizeof (sa);
2551 if (getsockname (fd, &sa.sa, &slen) < 0)
2552 goto no_getsockname;
2554 af = sa.sa.sa_family;
2556 /* if this is an IPv4-mapped address then do IPv4 QoS */
2557 if (af == AF_INET6) {
2558 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2562 /* extract and shift 6 bits of the DSCP */
2563 tos = (qos_dscp & 0x3f) << 2;
2567 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2572 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2586 return GST_RTSP_ESYS;
2591 return GST_RTSP_ERROR;
2596 * gst_rtsp_connection_set_qos_dscp:
2597 * @conn: a #GstRTSPConnection
2598 * @qos_dscp: DSCP value
2600 * Configure @conn to use the specified DSCP value.
2602 * Returns: #GST_RTSP_OK on success.
2607 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2611 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2612 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2613 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2615 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2616 if (res == GST_RTSP_OK)
2617 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2624 * gst_rtsp_connection_get_url:
2625 * @conn: a #GstRTSPConnection
2627 * Retrieve the URL of the other end of @conn.
2629 * Returns: The URL. This value remains valid until the
2630 * connection is freed.
2635 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2637 g_return_val_if_fail (conn != NULL, NULL);
2643 * gst_rtsp_connection_get_ip:
2644 * @conn: a #GstRTSPConnection
2646 * Retrieve the IP address of the other end of @conn.
2648 * Returns: The IP address as a string. this value remains valid until the
2649 * connection is closed.
2654 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2656 g_return_val_if_fail (conn != NULL, NULL);
2662 * gst_rtsp_connection_set_ip:
2663 * @conn: a #GstRTSPConnection
2664 * @ip: an ip address
2666 * Set the IP address of the server.
2671 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2673 g_return_if_fail (conn != NULL);
2676 conn->ip = g_strdup (ip);
2680 * gst_rtsp_connection_get_readfd:
2681 * @conn: a #GstRTSPConnection
2683 * Get the file descriptor for reading.
2685 * Returns: the file descriptor used for reading or -1 on error. The file
2686 * descriptor remains valid until the connection is closed.
2691 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2693 g_return_val_if_fail (conn != NULL, -1);
2694 g_return_val_if_fail (conn->readfd != NULL, -1);
2696 return conn->readfd->fd;
2700 * gst_rtsp_connection_get_writefd:
2701 * @conn: a #GstRTSPConnection
2703 * Get the file descriptor for writing.
2705 * Returns: the file descriptor used for writing or -1 on error. The file
2706 * descriptor remains valid until the connection is closed.
2711 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2713 g_return_val_if_fail (conn != NULL, -1);
2714 g_return_val_if_fail (conn->writefd != NULL, -1);
2716 return conn->writefd->fd;
2721 * gst_rtsp_connection_set_tunneled:
2722 * @conn: a #GstRTSPConnection
2723 * @tunneled: the new state
2725 * Set the HTTP tunneling state of the connection. This must be configured before
2726 * the @conn is connected.
2731 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2733 g_return_if_fail (conn != NULL);
2734 g_return_if_fail (conn->readfd == NULL);
2735 g_return_if_fail (conn->writefd == NULL);
2737 conn->tunneled = tunneled;
2741 * gst_rtsp_connection_is_tunneled:
2742 * @conn: a #GstRTSPConnection
2744 * Get the tunneling state of the connection.
2746 * Returns: if @conn is using HTTP tunneling.
2751 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2753 g_return_val_if_fail (conn != NULL, FALSE);
2755 return conn->tunneled;
2759 * gst_rtsp_connection_get_tunnelid:
2760 * @conn: a #GstRTSPConnection
2762 * Get the tunnel session id the connection.
2764 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2769 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2771 g_return_val_if_fail (conn != NULL, NULL);
2773 if (!conn->tunneled)
2776 return conn->tunnelid;
2780 * gst_rtsp_connection_do_tunnel:
2781 * @conn: a #GstRTSPConnection
2782 * @conn2: a #GstRTSPConnection
2784 * If @conn received the first tunnel connection and @conn2 received
2785 * the second tunnel connection, link the two connections together so that
2786 * @conn manages the tunneled connection.
2788 * After this call, @conn2 cannot be used anymore and must be freed with
2789 * gst_rtsp_connection_free().
2791 * Returns: return GST_RTSP_OK on success.
2796 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2797 GstRTSPConnection * conn2)
2799 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2800 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2801 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2802 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2803 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2806 /* both connections have fd0 as the read/write socket. start by taking the
2807 * socket from conn2 and set it as the socket in conn */
2808 conn->fd1 = conn2->fd0;
2810 /* clean up some of the state of conn2 */
2811 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2813 conn2->readfd = conn2->writefd = NULL;
2815 /* We make fd0 the write socket and fd1 the read socket. */
2816 conn->writefd = &conn->fd0;
2817 conn->readfd = &conn->fd1;
2819 conn->tstate = TUNNEL_STATE_COMPLETE;
2821 /* we need base64 decoding for the readfd */
2822 conn->ctx.state = 0;
2825 conn->ctx.coutl = 0;
2826 conn->ctxp = &conn->ctx;
2831 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2832 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2841 /* async functions */
2842 struct _GstRTSPWatch
2846 GstRTSPConnection *conn;
2848 GstRTSPBuilder builder;
2849 GstRTSPMessage message;
2853 gboolean write_added;
2855 /* queued message for transmission */
2857 GAsyncQueue *messages;
2863 GstRTSPWatchFuncs funcs;
2866 GDestroyNotify notify;
2870 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2872 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2874 if (watch->conn->initial_buffer != NULL)
2877 *timeout = (watch->conn->timeout * 1000);
2883 gst_rtsp_source_check (GSource * source)
2885 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2887 if (watch->readfd.revents & READ_COND)
2890 if (watch->writefd.revents & WRITE_COND)
2897 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2898 gpointer user_data G_GNUC_UNUSED)
2900 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2903 /* first read as much as we can */
2904 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2906 res = build_next (&watch->builder, &watch->message, watch->conn);
2907 if (res == GST_RTSP_EINTR)
2909 else if (G_UNLIKELY (res == GST_RTSP_EEOF))
2911 else if (G_LIKELY (res == GST_RTSP_OK)) {
2912 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2913 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2914 watch->message.type_data.request.method == GST_RTSP_GET) {
2915 GstRTSPMessage *response;
2916 GstRTSPStatusCode code;
2918 watch->conn->tstate = TUNNEL_STATE_GET;
2920 if (watch->funcs.tunnel_start)
2921 code = watch->funcs.tunnel_start (watch, watch->user_data);
2923 code = GST_RTSP_STS_OK;
2925 /* queue the response */
2926 response = gen_tunnel_reply (watch->conn, code, &watch->message);
2927 gst_rtsp_watch_queue_message (watch, response);
2928 gst_rtsp_message_free (response);
2930 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2931 watch->message.type_data.request.method == GST_RTSP_POST) {
2932 watch->conn->tstate = TUNNEL_STATE_POST;
2934 /* in the callback the connection should be tunneled with the
2936 if (watch->funcs.tunnel_complete)
2937 watch->funcs.tunnel_complete (watch, watch->user_data);
2940 res = GST_RTSP_ERROR;
2945 if (G_LIKELY (res == GST_RTSP_OK)) {
2946 if (watch->funcs.message_received)
2947 watch->funcs.message_received (watch, &watch->message,
2953 gst_rtsp_message_unset (&watch->message);
2954 build_reset (&watch->builder);
2958 if (watch->writefd.revents & WRITE_COND) {
2960 if (watch->write_data == NULL) {
2963 /* get a new message from the queue */
2964 rec = g_async_queue_try_pop (watch->messages);
2968 watch->write_off = 0;
2969 watch->write_data = rec->data;
2970 watch->write_size = rec->size;
2971 watch->write_id = rec->id;
2973 g_slice_free (GstRTSPRec, rec);
2976 res = write_bytes (watch->writefd.fd, watch->write_data,
2977 &watch->write_off, watch->write_size);
2978 if (res == GST_RTSP_EINTR)
2980 if (G_UNLIKELY (res != GST_RTSP_OK))
2983 if (watch->funcs.message_sent)
2984 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
2987 if (g_async_queue_length (watch->messages) == 0 && watch->write_added) {
2988 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2989 watch->write_added = FALSE;
2990 watch->writefd.revents = 0;
2992 g_free (watch->write_data);
2993 watch->write_data = NULL;
3002 if (watch->funcs.closed)
3003 watch->funcs.closed (watch, watch->user_data);
3008 if (watch->funcs.error)
3009 watch->funcs.error (watch, res, watch->user_data);
3015 gst_rtsp_rec_free (gpointer data)
3017 GstRTSPRec *rec = data;
3020 g_slice_free (GstRTSPRec, rec);
3024 gst_rtsp_source_finalize (GSource * source)
3026 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3028 build_reset (&watch->builder);
3029 gst_rtsp_message_unset (&watch->message);
3031 g_async_queue_unref (watch->messages);
3032 watch->messages = NULL;
3034 g_free (watch->write_data);
3037 watch->notify (watch->user_data);
3040 static GSourceFuncs gst_rtsp_source_funcs = {
3041 gst_rtsp_source_prepare,
3042 gst_rtsp_source_check,
3043 gst_rtsp_source_dispatch,
3044 gst_rtsp_source_finalize,
3050 * gst_rtsp_watch_new:
3051 * @conn: a #GstRTSPConnection
3052 * @funcs: watch functions
3053 * @user_data: user data to pass to @funcs
3054 * @notify: notify when @user_data is not referenced anymore
3056 * Create a watch object for @conn. The functions provided in @funcs will be
3057 * called with @user_data when activity happened on the watch.
3059 * The new watch is usually created so that it can be attached to a
3060 * maincontext with gst_rtsp_watch_attach().
3062 * @conn must exist for the entire lifetime of the watch.
3064 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3065 * communication. Free with gst_rtsp_watch_unref () after usage.
3070 gst_rtsp_watch_new (GstRTSPConnection * conn,
3071 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3073 GstRTSPWatch *result;
3075 g_return_val_if_fail (conn != NULL, NULL);
3076 g_return_val_if_fail (funcs != NULL, NULL);
3077 g_return_val_if_fail (conn->readfd != NULL, NULL);
3078 g_return_val_if_fail (conn->writefd != NULL, NULL);
3080 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3081 sizeof (GstRTSPWatch));
3083 result->conn = conn;
3084 result->builder.state = STATE_START;
3086 result->messages = g_async_queue_new_full (gst_rtsp_rec_free);
3088 result->readfd.fd = -1;
3089 result->writefd.fd = -1;
3091 gst_rtsp_watch_reset (result);
3093 result->funcs = *funcs;
3094 result->user_data = user_data;
3095 result->notify = notify;
3097 /* only add the read fd, the write fd is only added when we have data
3099 g_source_add_poll ((GSource *) result, &result->readfd);
3105 * gst_rtsp_watch_reset:
3106 * @watch: a #GstRTSPWatch
3108 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3109 * when the file descriptors of the connection might have changed.
3114 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3116 if (watch->readfd.fd != -1)
3117 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3118 if (watch->writefd.fd != -1)
3119 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3121 watch->readfd.fd = watch->conn->readfd->fd;
3122 watch->readfd.events = READ_COND;
3123 watch->readfd.revents = 0;
3125 watch->writefd.fd = watch->conn->writefd->fd;
3126 watch->writefd.events = WRITE_COND;
3127 watch->writefd.revents = 0;
3128 watch->write_added = FALSE;
3130 g_source_add_poll ((GSource *) watch, &watch->readfd);
3134 * gst_rtsp_watch_attach:
3135 * @watch: a #GstRTSPWatch
3136 * @context: a GMainContext (if NULL, the default context will be used)
3138 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3140 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3145 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3147 g_return_val_if_fail (watch != NULL, 0);
3149 return g_source_attach ((GSource *) watch, context);
3153 * gst_rtsp_watch_unref:
3154 * @watch: a #GstRTSPWatch
3156 * Decreases the reference count of @watch by one. If the resulting reference
3157 * count is zero the watch and associated memory will be destroyed.
3162 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3164 g_return_if_fail (watch != NULL);
3166 g_source_unref ((GSource *) watch);
3170 * gst_rtsp_watch_queue_data:
3171 * @watch: a #GstRTSPWatch
3172 * @data: the data to queue
3173 * @size: the size of @data
3175 * Queue @data for transmission in @watch. It will be transmitted when the
3176 * connection of the @watch becomes writable.
3178 * This function will take ownership of @data and g_free() it after use.
3180 * The return value of this function will be used as the id argument in the
3181 * message_sent callback.
3188 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3193 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3194 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3195 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3197 /* make a record with the data and id */
3198 rec = g_slice_new (GstRTSPRec);
3199 rec->data = (guint8 *) data;
3202 /* make sure rec->id is never 0 */
3203 rec->id = ++watch->id;
3204 } while (G_UNLIKELY (rec->id == 0));
3206 /* add the record to a queue. FIXME we would like to have an upper limit here */
3207 g_async_queue_push (watch->messages, rec);
3209 /* FIXME: does the following need to be made thread-safe? (this might be
3210 * called from a streaming thread, like appsink's render function) */
3211 /* make sure the main context will now also check for writability on the
3213 if (!watch->write_added) {
3214 g_source_add_poll ((GSource *) watch, &watch->writefd);
3215 watch->write_added = TRUE;
3222 * gst_rtsp_watch_queue_message:
3223 * @watch: a #GstRTSPWatch
3224 * @message: a #GstRTSPMessage
3226 * Queue a @message for transmission in @watch. The contents of this
3227 * message will be serialized and transmitted when the connection of the
3228 * @watch becomes writable.
3230 * The return value of this function will be used as the id argument in the
3231 * message_sent callback.
3238 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3243 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3244 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3246 /* make a record with the message as a string and id */
3247 str = message_to_string (watch->conn, message);
3249 return gst_rtsp_watch_queue_data (watch,
3250 (guint8 *) g_string_free (str, FALSE), size);