2 * Copyright (C) <2005-2009> Wim Taymans <wim.taymans@gmail.com>
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
20 * Unless otherwise indicated, Source Code is licensed under MIT license.
21 * See further explanation attached in License Statement (distributed in the file
24 * Permission is hereby granted, free of charge, to any person obtaining a copy of
25 * this software and associated documentation files (the "Software"), to deal in
26 * the Software without restriction, including without limitation the rights to
27 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
28 * of the Software, and to permit persons to whom the Software is furnished to do
29 * so, subject to the following conditions:
31 * The above copyright notice and this permission notice shall be included in all
32 * copies or substantial portions of the Software.
34 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 * SECTION:gstrtspconnection
45 * @short_description: manage RTSP connections
46 * @see_also: gstrtspurl
50 * This object manages the RTSP connection to the server. It provides function
51 * to receive and send bytes and messages.
55 * Last reviewed on 2007-07-24 (0.10.14)
72 /* we include this here to get the G_OS_* defines */
77 /* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later.
78 * minwg32 headers check WINVER before allowing the use of these */
84 #define EINPROGRESS WSAEINPROGRESS
86 #include <sys/ioctl.h>
88 #include <sys/socket.h>
90 #include <netinet/in.h>
93 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
94 #include <sys/filio.h>
97 #include "gstrtspconnection.h"
98 #include "gstrtspbase64.h"
103 struct sockaddr_in sa_in;
104 struct sockaddr_in6 sa_in6;
105 struct sockaddr_storage sa_stor;
112 guchar out[3]; /* the size must be evenly divisible by 3 */
118 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
119 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
120 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
121 #define CLOSE_SOCKET(sock) closesocket (sock)
122 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
123 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
124 /* According to Microsoft's connect() documentation this one returns
125 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
126 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
128 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
129 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
130 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
131 #define CLOSE_SOCKET(sock) close (sock)
132 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
133 #define ERRNO_IS_EINTR (errno == EINTR)
134 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
137 #define ADD_POLLFD(fdset, pfd, fd) \
140 gst_poll_add_fd (fdset, pfd); \
143 #define REMOVE_POLLFD(fdset, pfd) \
145 if ((pfd)->fd != -1) { \
146 GST_DEBUG ("remove fd %d", (pfd)->fd); \
147 gst_poll_remove_fd (fdset, pfd); \
148 CLOSE_SOCKET ((pfd)->fd); \
158 TUNNEL_STATE_COMPLETE
159 } GstRTSPTunnelState;
161 #define TUNNELID_LEN 24
163 struct _GstRTSPConnection
166 /* URL for the connection */
169 /* connection state */
176 gchar tunnelid[TUNNELID_LEN];
178 GstRTSPTunnelState tstate;
185 gchar *initial_buffer;
186 gsize initial_buffer_offset;
189 gint cseq; /* sequence number */
190 gchar session_id[512]; /* session id */
191 gint timeout; /* session timeout in seconds */
192 GTimer *timer; /* timeout timer */
195 GstRTSPAuthMethod auth_method;
198 GHashTable *auth_params;
219 READ_AHEAD_EOH = -1, /* end of headers */
220 READ_AHEAD_CRLF = -2,
221 READ_AHEAD_CRLFCR = -3
224 /* a structure for constructing RTSPMessages */
228 GstRTSPResult status;
238 build_reset (GstRTSPBuilder * builder)
240 g_free (builder->body_data);
241 memset (builder, 0, sizeof (GstRTSPBuilder));
245 * gst_rtsp_connection_create:
246 * @url: a #GstRTSPUrl
247 * @conn: storage for a #GstRTSPConnection
249 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
250 * The connection will not yet attempt to connect to @url, use
251 * gst_rtsp_connection_connect().
253 * A copy of @url will be made.
255 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
258 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
260 GstRTSPConnection *newconn;
266 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
269 error = WSAStartup (0x0202, &w);
274 if (w.wVersion != 0x0202)
278 newconn = g_new0 (GstRTSPConnection, 1);
280 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
283 newconn->url = gst_rtsp_url_copy (url);
284 newconn->fd0.fd = -1;
285 newconn->fd1.fd = -1;
286 newconn->timer = g_timer_new ();
287 newconn->timeout = 60;
290 newconn->auth_method = GST_RTSP_AUTH_NONE;
291 newconn->username = NULL;
292 newconn->passwd = NULL;
293 newconn->auth_params = NULL;
303 g_warning ("Error %d on WSAStartup", error);
304 return GST_RTSP_EWSASTART;
308 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
311 return GST_RTSP_EWSAVERSION;
320 return GST_RTSP_ESYS;
325 * gst_rtsp_connection_create_from_fd:
326 * @fd: a file descriptor
327 * @ip: the IP address of the other end
328 * @port: the port used by the other end
329 * @initial_buffer: data already read from @fd
330 * @conn: storage for a #GstRTSPConnection
332 * Create a new #GstRTSPConnection for handling communication on the existing
333 * file descriptor @fd. The @initial_buffer contains any data already read from
334 * @fd which should be used before starting to read new data.
336 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
341 gst_rtsp_connection_create_from_fd (gint fd, const gchar * ip, guint16 port,
342 const gchar * initial_buffer, GstRTSPConnection ** conn)
344 GstRTSPConnection *newconn = NULL;
351 g_return_val_if_fail (fd >= 0, GST_RTSP_EINVAL);
352 g_return_val_if_fail (ip != NULL, GST_RTSP_EINVAL);
353 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
355 /* set to non-blocking mode so that we can cancel the communication */
357 fcntl (fd, F_SETFL, O_NONBLOCK);
359 ioctlsocket (fd, FIONBIO, &flags);
360 #endif /* G_OS_WIN32 */
362 /* create a url for the client address */
363 url = g_new0 (GstRTSPUrl, 1);
364 url->host = g_strdup (ip);
367 /* now create the connection object */
368 GST_RTSP_CHECK (gst_rtsp_connection_create (url, &newconn), newconn_failed);
369 gst_rtsp_url_free (url);
371 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
373 /* both read and write initially */
374 newconn->readfd = &newconn->fd0;
375 newconn->writefd = &newconn->fd0;
377 newconn->ip = g_strdup (ip);
379 newconn->initial_buffer = g_strdup (initial_buffer);
388 gst_rtsp_url_free (url);
394 * gst_rtsp_connection_accept:
396 * @conn: storage for a #GstRTSPConnection
398 * Accept a new connection on @sock and create a new #GstRTSPConnection for
399 * handling communication on new socket.
401 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
406 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
409 union gst_sockaddr sa;
410 socklen_t slen = sizeof (sa);
411 gchar ip[INET6_ADDRSTRLEN];
414 g_return_val_if_fail (sock >= 0, GST_RTSP_EINVAL);
415 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
417 memset (&sa, 0, slen);
420 fd = accept (sock, &sa.sa, &slen);
422 fd = accept (sock, &sa.sa, (gint *) & slen);
423 #endif /* G_OS_WIN32 */
427 if (getnameinfo (&sa.sa, slen, ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) != 0)
428 goto getnameinfo_failed;
430 if (sa.sa.sa_family == AF_INET)
431 port = sa.sa_in.sin_port;
432 else if (sa.sa.sa_family == AF_INET6)
433 port = sa.sa_in6.sin6_port;
437 return gst_rtsp_connection_create_from_fd (fd, ip, port, NULL, conn);
442 return GST_RTSP_ESYS;
448 return GST_RTSP_ERROR;
453 do_resolve (const gchar * host)
455 static gchar ip[INET6_ADDRSTRLEN];
456 struct addrinfo *aires;
460 aierr = getaddrinfo (host, NULL, NULL, &aires);
464 for (ai = aires; ai; ai = ai->ai_next) {
465 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
472 aierr = getnameinfo (ai->ai_addr, ai->ai_addrlen, ip, sizeof (ip), NULL, 0,
473 NI_NUMERICHOST | NI_NUMERICSERV);
477 freeaddrinfo (aires);
479 return g_strdup (ip);
484 GST_ERROR ("no addrinfo found for %s: %s", host, gai_strerror (aierr));
489 GST_ERROR ("no family found for %s", host);
490 freeaddrinfo (aires);
495 GST_ERROR ("no address found for %s: %s", host, gai_strerror (aierr));
496 freeaddrinfo (aires);
502 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
503 GstPoll * fdset, GTimeVal * timeout)
506 struct addrinfo hints;
507 struct addrinfo *aires;
510 gchar service[NI_MAXSERV];
513 unsigned long flags = 1;
514 #endif /* G_OS_WIN32 */
518 memset (&hints, 0, sizeof hints);
519 hints.ai_flags = AI_NUMERICHOST;
520 hints.ai_family = AF_UNSPEC;
521 hints.ai_socktype = SOCK_STREAM;
522 g_snprintf (service, sizeof (service) - 1, "%hu", port);
523 service[sizeof (service) - 1] = '\0';
525 aierr = getaddrinfo (ip, service, &hints, &aires);
529 for (ai = aires; ai; ai = ai->ai_next) {
530 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
537 fd = socket (ai->ai_family, SOCK_STREAM, 0);
541 /* set to non-blocking mode so that we can cancel the connect */
543 fcntl (fd, F_SETFL, O_NONBLOCK);
545 ioctlsocket (fd, FIONBIO, &flags);
546 #endif /* G_OS_WIN32 */
548 /* add the socket to our fdset */
549 ADD_POLLFD (fdset, fdout, fd);
551 /* we are going to connect ASYNC now */
552 ret = connect (fd, ai->ai_addr, ai->ai_addrlen);
555 if (!ERRNO_IS_EINPROGRESS)
558 /* wait for connect to complete up to the specified timeout or until we got
560 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
562 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
565 retval = gst_poll_wait (fdset, to);
566 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
570 else if (retval == -1)
573 /* we can still have an error connecting on windows */
574 if (gst_poll_fd_has_error (fdset, fdout)) {
575 socklen_t len = sizeof (errno);
577 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
579 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
584 gst_poll_fd_ignored (fdset, fdout);
587 freeaddrinfo (aires);
594 GST_ERROR ("no addrinfo found for %s: %s", ip, gai_strerror (aierr));
595 return GST_RTSP_ERROR;
599 GST_ERROR ("no family found for %s", ip);
600 freeaddrinfo (aires);
601 return GST_RTSP_ERROR;
605 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
606 freeaddrinfo (aires);
607 return GST_RTSP_ESYS;
611 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
612 REMOVE_POLLFD (fdset, fdout);
613 freeaddrinfo (aires);
614 return GST_RTSP_ESYS;
618 GST_ERROR ("timeout");
619 REMOVE_POLLFD (fdset, fdout);
620 freeaddrinfo (aires);
621 return GST_RTSP_ETIMEOUT;
626 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
633 guint16 port, url_port;
637 GstRTSPMessage response;
639 memset (&response, 0, sizeof (response));
640 gst_rtsp_message_init (&response);
642 /* create a random sessionid */
643 for (i = 0; i < TUNNELID_LEN; i++)
644 conn->tunnelid[i] = g_random_int_range ('a', 'z');
645 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
648 /* get the port from the url */
649 gst_rtsp_url_get_port (url, &url_port);
651 if (conn->proxy_host) {
652 uri = g_strdup_printf ("http://%s:%d%s%s%s", url->host, url_port,
653 url->abspath, url->query ? "?" : "", url->query ? url->query : "");
654 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
655 ip = conn->proxy_host;
656 port = conn->proxy_port;
658 uri = g_strdup_printf ("%s%s%s", url->abspath, url->query ? "?" : "",
659 url->query ? url->query : "");
665 /* create the GET request for the read connection */
666 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_GET, uri),
668 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
670 if (hostparam != NULL)
671 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
672 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
674 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
675 "application/x-rtsp-tunnelled");
676 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
677 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
679 /* we start by writing to this fd */
680 conn->writefd = &conn->fd0;
682 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
683 * request from being base64 encoded */
684 conn->tunneled = FALSE;
685 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
686 gst_rtsp_message_free (msg);
687 conn->tunneled = TRUE;
689 /* receive the response to the GET request */
690 /* we need to temporarily set manual_http to TRUE since
691 * gst_rtsp_connection_receive() will treat the HTTP response as a parsing
692 * failure otherwise */
693 conn->manual_http = TRUE;
694 GST_RTSP_CHECK (gst_rtsp_connection_receive (conn, &response, timeout),
696 conn->manual_http = FALSE;
698 if (response.type != GST_RTSP_MESSAGE_HTTP_RESPONSE ||
699 response.type_data.response.code != GST_RTSP_STS_OK)
702 if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
703 &value, 0) != GST_RTSP_OK) {
704 if (conn->proxy_host) {
705 /* if we use a proxy we need to change the destination url */
707 url->host = g_strdup (value);
709 hostparam = g_strdup_printf ("%s:%d", url->host, url_port);
711 /* and resolve the new ip address */
712 if (!(ip = do_resolve (conn->ip)))
719 /* connect to the host/port */
720 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
721 if (res != GST_RTSP_OK)
724 /* this is now our writing socket */
725 conn->writefd = &conn->fd1;
727 /* create the POST request for the write connection */
728 GST_RTSP_CHECK (gst_rtsp_message_new_request (&msg, GST_RTSP_POST, uri),
730 msg->type = GST_RTSP_MESSAGE_HTTP_REQUEST;
732 if (hostparam != NULL)
733 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_HOST, hostparam);
734 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SESSIONCOOKIE,
736 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_ACCEPT,
737 "application/x-rtsp-tunnelled");
738 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-cache");
739 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
740 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_EXPIRES,
741 "Sun, 9 Jan 1972 00:00:00 GMT");
742 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_LENGTH, "32767");
744 /* we need to temporarily set conn->tunneled to FALSE to prevent the HTTP
745 * request from being base64 encoded */
746 conn->tunneled = FALSE;
747 GST_RTSP_CHECK (gst_rtsp_connection_send (conn, msg, timeout), write_failed);
748 gst_rtsp_message_free (msg);
749 conn->tunneled = TRUE;
752 gst_rtsp_message_unset (&response);
761 GST_ERROR ("failed to create request (%d)", res);
766 GST_ERROR ("write failed (%d)", res);
767 gst_rtsp_message_free (msg);
768 conn->tunneled = TRUE;
773 GST_ERROR ("read failed (%d)", res);
774 conn->manual_http = FALSE;
779 GST_ERROR ("got failure response %d %s", response.type_data.response.code,
780 response.type_data.response.reason);
781 res = GST_RTSP_ERROR;
786 GST_ERROR ("could not resolve %s", conn->ip);
792 GST_ERROR ("failed to connect");
798 * gst_rtsp_connection_connect:
799 * @conn: a #GstRTSPConnection
800 * @timeout: a #GTimeVal timeout
802 * Attempt to connect to the url of @conn made with
803 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
804 * forever. If @timeout contains a valid timeout, this function will return
805 * #GST_RTSP_ETIMEOUT after the timeout expired.
807 * This function can be cancelled with gst_rtsp_connection_flush().
809 * Returns: #GST_RTSP_OK when a connection could be made.
812 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
819 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
820 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
821 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
825 if (conn->proxy_host && conn->tunneled) {
826 if (!(ip = do_resolve (conn->proxy_host))) {
827 GST_ERROR ("could not resolve %s", conn->proxy_host);
830 port = conn->proxy_port;
831 g_free (conn->proxy_host);
832 conn->proxy_host = ip;
834 if (!(ip = do_resolve (url->host))) {
835 GST_ERROR ("could not resolve %s", url->host);
838 /* get the port from the url */
839 gst_rtsp_url_get_port (url, &port);
845 /* connect to the host/port */
846 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
847 if (res != GST_RTSP_OK)
850 /* this is our read URL */
851 conn->readfd = &conn->fd0;
853 if (conn->tunneled) {
854 res = setup_tunneling (conn, timeout);
855 if (res != GST_RTSP_OK)
856 goto tunneling_failed;
858 conn->writefd = &conn->fd0;
865 return GST_RTSP_ENET;
869 GST_ERROR ("failed to connect");
874 GST_ERROR ("failed to setup tunneling");
880 auth_digest_compute_hex_urp (const gchar * username,
881 const gchar * realm, const gchar * password, gchar hex_urp[33])
883 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
884 const gchar *digest_string;
886 g_checksum_update (md5_context, (const guchar *) username, strlen (username));
887 g_checksum_update (md5_context, (const guchar *) ":", 1);
888 g_checksum_update (md5_context, (const guchar *) realm, strlen (realm));
889 g_checksum_update (md5_context, (const guchar *) ":", 1);
890 g_checksum_update (md5_context, (const guchar *) password, strlen (password));
891 digest_string = g_checksum_get_string (md5_context);
893 memset (hex_urp, 0, 33);
894 memcpy (hex_urp, digest_string, strlen (digest_string));
896 g_checksum_free (md5_context);
900 auth_digest_compute_response (const gchar * method,
901 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
904 char hex_a2[33] = { 0, };
905 GChecksum *md5_context = g_checksum_new (G_CHECKSUM_MD5);
906 const gchar *digest_string;
909 g_checksum_update (md5_context, (const guchar *) method, strlen (method));
910 g_checksum_update (md5_context, (const guchar *) ":", 1);
911 g_checksum_update (md5_context, (const guchar *) uri, strlen (uri));
912 digest_string = g_checksum_get_string (md5_context);
913 memcpy (hex_a2, digest_string, strlen (digest_string));
916 #if GLIB_CHECK_VERSION (2, 18, 0)
917 g_checksum_reset (md5_context);
919 g_checksum_free (md5_context);
920 md5_context = g_checksum_new (G_CHECKSUM_MD5);
922 g_checksum_update (md5_context, (const guchar *) hex_a1, strlen (hex_a1));
923 g_checksum_update (md5_context, (const guchar *) ":", 1);
924 g_checksum_update (md5_context, (const guchar *) nonce, strlen (nonce));
925 g_checksum_update (md5_context, (const guchar *) ":", 1);
927 g_checksum_update (md5_context, (const guchar *) hex_a2, 32);
928 digest_string = g_checksum_get_string (md5_context);
929 memset (response, 0, 33);
930 memcpy (response, digest_string, strlen (digest_string));
932 g_checksum_free (md5_context);
936 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
938 switch (conn->auth_method) {
939 case GST_RTSP_AUTH_BASIC:{
944 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
945 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
946 auth_string = g_strdup_printf ("Basic %s", user_pass64);
948 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
952 g_free (user_pass64);
955 case GST_RTSP_AUTH_DIGEST:{
956 gchar response[33], hex_urp[33];
957 gchar *auth_string, *auth_string2;
964 /* we need to have some params set */
965 if (conn->auth_params == NULL)
968 /* we need the realm and nonce */
969 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
970 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
971 if (realm == NULL || nonce == NULL)
974 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
977 method = gst_rtsp_method_as_text (message->type_data.request.method);
978 uri = message->type_data.request.uri;
980 /* Assume no qop, algorithm=md5, stale=false */
981 /* For algorithm MD5, a1 = urp. */
982 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
983 auth_string = g_strdup_printf ("Digest username=\"%s\", "
984 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
985 conn->username, realm, nonce, uri, response);
987 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
989 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
991 g_free (auth_string);
992 auth_string = auth_string2;
994 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
1005 gen_date_string (gchar * date_string, guint len)
1009 #ifdef HAVE_GMTIME_R
1013 g_get_current_time (&tv);
1014 t = (time_t) tv.tv_sec;
1016 #ifdef HAVE_GMTIME_R
1017 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
1019 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
1023 static GstRTSPResult
1024 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1028 if (G_UNLIKELY (*idx > size))
1029 return GST_RTSP_ERROR;
1036 r = WRITE_SOCKET (fd, &buffer[*idx], left);
1037 if (G_UNLIKELY (r == 0)) {
1038 return GST_RTSP_EINTR;
1039 } else if (G_UNLIKELY (r < 0)) {
1040 if (ERRNO_IS_EAGAIN)
1041 return GST_RTSP_EINTR;
1042 if (!ERRNO_IS_EINTR)
1043 return GST_RTSP_ESYS;
1053 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1057 if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1058 gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1060 out = MIN (left, size);
1061 memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1063 if (left == (gsize) out) {
1064 g_free (conn->initial_buffer);
1065 conn->initial_buffer = NULL;
1066 conn->initial_buffer_offset = 0;
1068 conn->initial_buffer_offset += out;
1071 if (G_LIKELY (size > (guint) out)) {
1074 r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1086 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1088 DecodeCtx *ctx = conn->ctxp;
1093 guint8 in[sizeof (ctx->out) * 4 / 3];
1096 while (size > 0 && ctx->cout < ctx->coutl) {
1097 /* we have some leftover bytes */
1098 *buffer++ = ctx->out[ctx->cout++];
1103 /* got what we needed? */
1107 /* try to read more bytes */
1108 r = fill_raw_bytes (conn, in, sizeof (in));
1117 g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1121 out = fill_raw_bytes (conn, buffer, size);
1127 static GstRTSPResult
1128 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1132 if (G_UNLIKELY (*idx > size))
1133 return GST_RTSP_ERROR;
1140 r = fill_bytes (conn, &buffer[*idx], left);
1141 if (G_UNLIKELY (r == 0)) {
1142 return GST_RTSP_EEOF;
1143 } else if (G_UNLIKELY (r < 0)) {
1144 if (ERRNO_IS_EAGAIN)
1145 return GST_RTSP_EINTR;
1146 if (!ERRNO_IS_EINTR)
1147 return GST_RTSP_ESYS;
1156 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1157 * end of a line. It even does its best to handle clients which mix them (even
1158 * though this is a really stupid idea (tm).) It also handles Line White Space
1159 * (LWS), where a line end followed by whitespace is considered LWS. This is
1160 * the method used in RTSP (and HTTP) to break long lines.
1162 static GstRTSPResult
1163 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1169 if (conn->read_ahead == READ_AHEAD_EOH) {
1170 /* the last call to read_line() already determined that we have reached
1171 * the end of the headers, so convey that information now */
1172 conn->read_ahead = 0;
1174 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1175 /* the last call to read_line() left off after having read \r\n */
1177 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1178 /* the last call to read_line() left off after having read \r\n\r */
1180 } else if (conn->read_ahead != 0) {
1181 /* the last call to read_line() left us with a character to start with */
1182 c = (guint8) conn->read_ahead;
1183 conn->read_ahead = 0;
1185 /* read the next character */
1186 r = fill_bytes (conn, &c, 1);
1187 if (G_UNLIKELY (r == 0)) {
1188 return GST_RTSP_EEOF;
1189 } else if (G_UNLIKELY (r < 0)) {
1190 if (ERRNO_IS_EAGAIN)
1191 return GST_RTSP_EINTR;
1192 if (!ERRNO_IS_EINTR)
1193 return GST_RTSP_ESYS;
1198 /* special treatment of line endings */
1199 if (c == '\r' || c == '\n') {
1203 /* need to read ahead one more character to know what to do... */
1204 r = fill_bytes (conn, &read_ahead, 1);
1205 if (G_UNLIKELY (r == 0)) {
1206 return GST_RTSP_EEOF;
1207 } else if (G_UNLIKELY (r < 0)) {
1208 if (ERRNO_IS_EAGAIN) {
1209 /* remember the original character we read and try again next time */
1210 if (conn->read_ahead == 0)
1211 conn->read_ahead = c;
1212 return GST_RTSP_EINTR;
1214 if (!ERRNO_IS_EINTR)
1215 return GST_RTSP_ESYS;
1219 if (read_ahead == ' ' || read_ahead == '\t') {
1220 if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1221 /* got \r\n\r followed by whitespace, treat it as a normal line
1222 * followed by one starting with LWS */
1223 conn->read_ahead = read_ahead;
1226 /* got LWS, change the line ending to a space and continue */
1228 conn->read_ahead = read_ahead;
1230 } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1231 if (read_ahead == '\r' || read_ahead == '\n') {
1232 /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1233 conn->read_ahead = READ_AHEAD_EOH;
1236 /* got \r\n\r followed by something else, this is not really
1237 * supported since we have probably just eaten the first character
1238 * of the body or the next message, so just ignore the second \r
1239 * and live with it... */
1240 conn->read_ahead = read_ahead;
1243 } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1244 if (read_ahead == '\r') {
1245 /* got \r\n\r so far, need one more character... */
1246 conn->read_ahead = READ_AHEAD_CRLFCR;
1248 } else if (read_ahead == '\n') {
1249 /* got \r\n\n, treat it as the end of the headers */
1250 conn->read_ahead = READ_AHEAD_EOH;
1253 /* found the end of a line, keep read_ahead for the next line */
1254 conn->read_ahead = read_ahead;
1257 } else if (c == read_ahead) {
1258 /* got double \r or \n, treat it as the end of the headers */
1259 conn->read_ahead = READ_AHEAD_EOH;
1261 } else if (c == '\r' && read_ahead == '\n') {
1262 /* got \r\n so far, still need more to know what to do... */
1263 conn->read_ahead = READ_AHEAD_CRLF;
1266 /* found the end of a line, keep read_ahead for the next line */
1267 conn->read_ahead = read_ahead;
1272 if (G_LIKELY (*idx < size - 1))
1273 buffer[(*idx)++] = c;
1275 buffer[*idx] = '\0';
1281 * gst_rtsp_connection_write:
1282 * @conn: a #GstRTSPConnection
1283 * @data: the data to write
1284 * @size: the size of @data
1285 * @timeout: a timeout value or #NULL
1287 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1288 * the specified @timeout. @timeout can be #NULL, in which case this function
1289 * might block forever.
1291 * This function can be cancelled with gst_rtsp_connection_flush().
1293 * Returns: #GST_RTSP_OK on success.
1296 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1297 guint size, GTimeVal * timeout)
1304 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1305 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1306 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1308 gst_poll_set_controllable (conn->fdset, TRUE);
1309 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1310 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1311 /* clear all previous poll results */
1312 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1313 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1315 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1321 res = write_bytes (conn->writefd->fd, data, &offset, size);
1322 if (G_LIKELY (res == GST_RTSP_OK))
1324 if (G_UNLIKELY (res != GST_RTSP_EINTR))
1327 /* not all is written, wait until we can write more */
1329 retval = gst_poll_wait (conn->fdset, to);
1330 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1332 if (G_UNLIKELY (retval == 0))
1335 if (G_UNLIKELY (retval == -1)) {
1347 return GST_RTSP_ETIMEOUT;
1351 return GST_RTSP_ESYS;
1355 return GST_RTSP_EINTR;
1364 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1366 GString *str = NULL;
1368 str = g_string_new ("");
1370 switch (message->type) {
1371 case GST_RTSP_MESSAGE_REQUEST:
1372 /* create request string, add CSeq */
1373 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1375 gst_rtsp_method_as_text (message->type_data.request.method),
1376 message->type_data.request.uri, conn->cseq++);
1377 /* add session id if we have one */
1378 if (conn->session_id[0] != '\0') {
1379 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1380 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1383 /* add any authentication headers */
1384 add_auth_header (conn, message);
1386 case GST_RTSP_MESSAGE_RESPONSE:
1387 /* create response string */
1388 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1389 message->type_data.response.code, message->type_data.response.reason);
1391 case GST_RTSP_MESSAGE_HTTP_REQUEST:
1392 /* create request string */
1393 g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1394 gst_rtsp_method_as_text (message->type_data.request.method),
1395 message->type_data.request.uri,
1396 gst_rtsp_version_as_text (message->type_data.request.version));
1397 /* add any authentication headers */
1398 add_auth_header (conn, message);
1400 case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1401 /* create response string */
1402 g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1403 gst_rtsp_version_as_text (message->type_data.request.version),
1404 message->type_data.response.code, message->type_data.response.reason);
1406 case GST_RTSP_MESSAGE_DATA:
1408 guint8 data_header[4];
1410 /* prepare data header */
1411 data_header[0] = '$';
1412 data_header[1] = message->type_data.data.channel;
1413 data_header[2] = (message->body_size >> 8) & 0xff;
1414 data_header[3] = message->body_size & 0xff;
1416 /* create string with header and data */
1417 str = g_string_append_len (str, (gchar *) data_header, 4);
1419 g_string_append_len (str, (gchar *) message->body,
1420 message->body_size);
1424 g_string_free (str, TRUE);
1425 g_return_val_if_reached (NULL);
1429 /* append headers and body */
1430 if (message->type != GST_RTSP_MESSAGE_DATA) {
1431 gchar date_string[100];
1433 gen_date_string (date_string, sizeof (date_string));
1435 /* add date header */
1436 gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1437 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1439 /* append headers */
1440 gst_rtsp_message_append_headers (message, str);
1442 /* append Content-Length and body if needed */
1443 if (message->body != NULL && message->body_size > 0) {
1446 len = g_strdup_printf ("%d", message->body_size);
1447 g_string_append_printf (str, "%s: %s\r\n",
1448 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1450 /* header ends here */
1451 g_string_append (str, "\r\n");
1453 g_string_append_len (str, (gchar *) message->body,
1454 message->body_size);
1456 /* just end headers */
1457 g_string_append (str, "\r\n");
1465 * gst_rtsp_connection_send:
1466 * @conn: a #GstRTSPConnection
1467 * @message: the message to send
1468 * @timeout: a timeout value or #NULL
1470 * Attempt to send @message to the connected @conn, blocking up to
1471 * the specified @timeout. @timeout can be #NULL, in which case this function
1472 * might block forever.
1474 * This function can be cancelled with gst_rtsp_connection_flush().
1476 * Returns: #GST_RTSP_OK on success.
1479 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1482 GString *string = NULL;
1487 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1488 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1490 if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1493 if (conn->tunneled) {
1494 str = g_base64_encode ((const guchar *) string->str, string->len);
1495 g_string_free (string, TRUE);
1500 g_string_free (string, FALSE);
1504 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1512 g_warning ("Wrong message");
1513 return GST_RTSP_EINVAL;
1517 static GstRTSPResult
1518 parse_string (gchar * dest, gint size, gchar ** src)
1520 GstRTSPResult res = GST_RTSP_OK;
1525 while (g_ascii_isspace (**src))
1528 while (!g_ascii_isspace (**src) && **src != '\0') {
1530 dest[idx++] = **src;
1532 res = GST_RTSP_EPARSE;
1541 static GstRTSPResult
1542 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1543 GstRTSPVersion * version)
1545 GstRTSPResult res = GST_RTSP_OK;
1548 if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1555 /* the version number must be formatted as X.Y with nothing following */
1556 if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1557 res = GST_RTSP_EPARSE;
1559 if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1560 if (major != 1 || minor != 0) {
1561 *version = GST_RTSP_VERSION_INVALID;
1562 res = GST_RTSP_ERROR;
1564 } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1565 if (*type == GST_RTSP_MESSAGE_REQUEST)
1566 *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1567 else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1568 *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1570 if (major == 1 && minor == 1) {
1571 *version = GST_RTSP_VERSION_1_1;
1572 } else if (major != 1 || minor != 0) {
1573 *version = GST_RTSP_VERSION_INVALID;
1574 res = GST_RTSP_ERROR;
1577 res = GST_RTSP_EPARSE;
1579 res = GST_RTSP_EPARSE;
1584 static GstRTSPResult
1585 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1587 GstRTSPResult res = GST_RTSP_OK;
1589 gchar versionstr[20];
1594 bptr = (gchar *) buffer;
1596 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1597 res = GST_RTSP_EPARSE;
1599 if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1600 res = GST_RTSP_EPARSE;
1601 code = atoi (codestr);
1602 if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1603 res = GST_RTSP_EPARSE;
1605 while (g_ascii_isspace (*bptr))
1608 if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1609 NULL) != GST_RTSP_OK))
1610 res = GST_RTSP_EPARSE;
1612 res2 = parse_protocol_version (versionstr, &msg->type,
1613 &msg->type_data.response.version);
1614 if (G_LIKELY (res == GST_RTSP_OK))
1620 static GstRTSPResult
1621 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1623 GstRTSPResult res = GST_RTSP_OK;
1625 gchar versionstr[20];
1626 gchar methodstr[20];
1629 GstRTSPMethod method;
1631 bptr = (gchar *) buffer;
1633 if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1634 res = GST_RTSP_EPARSE;
1635 method = gst_rtsp_find_method (methodstr);
1637 if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1638 res = GST_RTSP_EPARSE;
1639 if (G_UNLIKELY (*urlstr == '\0'))
1640 res = GST_RTSP_EPARSE;
1642 if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1643 res = GST_RTSP_EPARSE;
1645 if (G_UNLIKELY (*bptr != '\0'))
1646 res = GST_RTSP_EPARSE;
1648 if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1649 urlstr) != GST_RTSP_OK))
1650 res = GST_RTSP_EPARSE;
1652 res2 = parse_protocol_version (versionstr, &msg->type,
1653 &msg->type_data.request.version);
1654 if (G_LIKELY (res == GST_RTSP_OK))
1657 if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1658 /* GET and POST are not allowed as RTSP methods */
1659 if (msg->type_data.request.method == GST_RTSP_GET ||
1660 msg->type_data.request.method == GST_RTSP_POST) {
1661 msg->type_data.request.method = GST_RTSP_INVALID;
1662 if (res == GST_RTSP_OK)
1663 res = GST_RTSP_ERROR;
1665 } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1666 /* only GET and POST are allowed as HTTP methods */
1667 if (msg->type_data.request.method != GST_RTSP_GET &&
1668 msg->type_data.request.method != GST_RTSP_POST) {
1669 msg->type_data.request.method = GST_RTSP_INVALID;
1670 if (res == GST_RTSP_OK)
1671 res = GST_RTSP_ERROR;
1678 /* parsing lines means reading a Key: Value pair */
1679 static GstRTSPResult
1680 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1682 GstRTSPHeaderField field;
1683 gchar *line = (gchar *) buffer;
1686 if ((value = strchr (line, ':')) == NULL || value == line)
1689 /* trim space before the colon */
1690 if (value[-1] == ' ')
1693 /* replace the colon with a NUL */
1696 /* find the header */
1697 field = gst_rtsp_find_header_field (line);
1698 if (field == GST_RTSP_HDR_INVALID)
1701 /* split up the value in multiple key:value pairs if it contains comma(s) */
1702 while (*value != '\0') {
1704 gchar *comma = NULL;
1705 gboolean quoted = FALSE;
1708 /* trim leading space */
1712 /* for headers which may not appear multiple times, and thus may not
1713 * contain multiple values on the same line, we can short-circuit the loop
1714 * below and the entire value results in just one key:value pair*/
1715 if (!gst_rtsp_header_allow_multiple (field))
1716 next_value = value + strlen (value);
1720 /* find the next value, taking special care of quotes and comments */
1721 while (*next_value != '\0') {
1722 if ((quoted || comment != 0) && *next_value == '\\' &&
1723 next_value[1] != '\0')
1725 else if (comment == 0 && *next_value == '"')
1727 else if (!quoted && *next_value == '(')
1729 else if (comment != 0 && *next_value == ')')
1731 else if (!quoted && comment == 0) {
1732 /* To quote RFC 2068: "User agents MUST take special care in parsing
1733 * the WWW-Authenticate field value if it contains more than one
1734 * challenge, or if more than one WWW-Authenticate header field is
1735 * provided, since the contents of a challenge may itself contain a
1736 * comma-separated list of authentication parameters."
1738 * What this means is that we cannot just look for an unquoted comma
1739 * when looking for multiple values in Proxy-Authenticate and
1740 * WWW-Authenticate headers. Instead we need to look for the sequence
1741 * "comma [space] token space token" before we can split after the
1744 if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1745 field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1746 if (*next_value == ',') {
1747 if (next_value[1] == ' ') {
1748 /* skip any space following the comma so we do not mistake it for
1749 * separating between two tokens */
1753 } else if (*next_value == ' ' && next_value[1] != ',' &&
1754 next_value[1] != '=' && comma != NULL) {
1759 } else if (*next_value == ',')
1767 if (value != next_value && next_value[-1] == ' ')
1768 next_value[-1] = '\0';
1770 if (*next_value != '\0')
1771 *next_value++ = '\0';
1773 /* add the key:value pair */
1775 gst_rtsp_message_add_header (msg, field, value);
1786 return GST_RTSP_EPARSE;
1790 /* convert all consecutive whitespace to a single space */
1792 normalize_line (guint8 * buffer)
1795 if (g_ascii_isspace (*buffer)) {
1799 for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1802 memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1810 * GST_RTSP_OK when a complete message was read.
1811 * GST_RTSP_EEOF: when the socket is closed
1812 * GST_RTSP_EINTR: when more data is needed.
1813 * GST_RTSP_..: some other error occured.
1815 static GstRTSPResult
1816 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1817 GstRTSPConnection * conn)
1822 switch (builder->state) {
1824 builder->offset = 0;
1826 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1827 if (res != GST_RTSP_OK)
1830 /* we have 1 bytes now and we can see if this is a data message or
1832 if (builder->buffer[0] == '$') {
1833 /* data message, prepare for the header */
1834 builder->state = STATE_DATA_HEADER;
1837 builder->state = STATE_READ_LINES;
1840 case STATE_DATA_HEADER:
1843 read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1844 if (res != GST_RTSP_OK)
1847 gst_rtsp_message_init_data (message, builder->buffer[1]);
1849 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1850 builder->body_data = g_malloc (builder->body_len + 1);
1851 builder->body_data[builder->body_len] = '\0';
1852 builder->offset = 0;
1853 builder->state = STATE_DATA_BODY;
1856 case STATE_DATA_BODY:
1859 read_bytes (conn, builder->body_data, &builder->offset,
1861 if (res != GST_RTSP_OK)
1864 /* we have the complete body now, store in the message adjusting the
1865 * length to include the traling '\0' */
1866 gst_rtsp_message_take_body (message,
1867 (guint8 *) builder->body_data, builder->body_len + 1);
1868 builder->body_data = NULL;
1869 builder->body_len = 0;
1871 builder->state = STATE_END;
1874 case STATE_READ_LINES:
1876 res = read_line (conn, builder->buffer, &builder->offset,
1877 sizeof (builder->buffer));
1878 if (res != GST_RTSP_OK)
1881 /* we have a regular response */
1882 if (builder->buffer[0] == '\0') {
1885 /* empty line, end of message header */
1886 /* see if there is a Content-Length header, but ignore it if this
1887 * is a POST request with an x-sessioncookie header */
1888 if (gst_rtsp_message_get_header (message,
1889 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1890 (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1891 message->type_data.request.method != GST_RTSP_POST ||
1892 gst_rtsp_message_get_header (message,
1893 GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1894 /* there is, prepare to read the body */
1895 builder->body_len = atol (hdrval);
1896 builder->body_data = g_malloc (builder->body_len + 1);
1897 builder->body_data[builder->body_len] = '\0';
1898 builder->offset = 0;
1899 builder->state = STATE_DATA_BODY;
1901 builder->state = STATE_END;
1906 /* we have a line */
1907 normalize_line (builder->buffer);
1908 if (builder->line == 0) {
1909 /* first line, check for response status */
1910 if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1911 memcmp (builder->buffer, "HTTP", 4) == 0) {
1912 builder->status = parse_response_status (builder->buffer, message);
1914 builder->status = parse_request_line (builder->buffer, message);
1917 /* else just parse the line */
1918 res = parse_line (builder->buffer, message);
1919 if (res != GST_RTSP_OK)
1920 builder->status = res;
1923 builder->offset = 0;
1928 gchar *session_cookie;
1931 if (message->type == GST_RTSP_MESSAGE_DATA) {
1932 /* data messages don't have headers */
1937 /* save the tunnel session in the connection */
1938 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1939 !conn->manual_http &&
1940 conn->tstate == TUNNEL_STATE_NONE &&
1941 gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1942 &session_cookie, 0) == GST_RTSP_OK) {
1943 strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1944 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1945 conn->tunneled = TRUE;
1948 /* save session id in the connection for further use */
1949 if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1950 gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1951 &session_id, 0) == GST_RTSP_OK) {
1954 maxlen = sizeof (conn->session_id) - 1;
1955 /* the sessionid can have attributes marked with ;
1956 * Make sure we strip them */
1957 for (i = 0; session_id[i] != '\0'; i++) {
1958 if (session_id[i] == ';') {
1963 } while (g_ascii_isspace (session_id[i]));
1964 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1967 /* if we parsed something valid, configure */
1968 if ((to = atoi (&session_id[i + 8])) > 0)
1975 /* make sure to not overflow */
1976 strncpy (conn->session_id, session_id, maxlen);
1977 conn->session_id[maxlen] = '\0';
1979 res = builder->status;
1983 res = GST_RTSP_ERROR;
1992 * gst_rtsp_connection_read:
1993 * @conn: a #GstRTSPConnection
1994 * @data: the data to read
1995 * @size: the size of @data
1996 * @timeout: a timeout value or #NULL
1998 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1999 * the specified @timeout. @timeout can be #NULL, in which case this function
2000 * might block forever.
2002 * This function can be cancelled with gst_rtsp_connection_flush().
2004 * Returns: #GST_RTSP_OK on success.
2007 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
2015 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2016 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
2017 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2019 if (G_UNLIKELY (size == 0))
2024 /* configure timeout if any */
2025 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2027 gst_poll_set_controllable (conn->fdset, TRUE);
2028 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2029 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2032 res = read_bytes (conn, data, &offset, size);
2033 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2035 if (G_LIKELY (res == GST_RTSP_OK))
2037 if (G_UNLIKELY (res != GST_RTSP_EINTR))
2041 retval = gst_poll_wait (conn->fdset, to);
2042 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2044 /* check for timeout */
2045 if (G_UNLIKELY (retval == 0))
2046 goto select_timeout;
2048 if (G_UNLIKELY (retval == -1)) {
2054 gst_poll_set_controllable (conn->fdset, FALSE);
2061 return GST_RTSP_ESYS;
2065 return GST_RTSP_ETIMEOUT;
2069 return GST_RTSP_EINTR;
2073 return GST_RTSP_EEOF;
2081 static GstRTSPMessage *
2082 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
2083 const GstRTSPMessage * request)
2085 GstRTSPMessage *msg;
2088 if (gst_rtsp_status_as_text (code) == NULL)
2089 code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
2091 GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
2094 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
2095 "GStreamer RTSP Server");
2096 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2097 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2098 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2100 if (code == GST_RTSP_STS_OK) {
2102 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2104 gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2105 "application/x-rtsp-tunnelled");
2118 * gst_rtsp_connection_receive:
2119 * @conn: a #GstRTSPConnection
2120 * @message: the message to read
2121 * @timeout: a timeout value or #NULL
2123 * Attempt to read into @message from the connected @conn, blocking up to
2124 * the specified @timeout. @timeout can be #NULL, in which case this function
2125 * might block forever.
2127 * This function can be cancelled with gst_rtsp_connection_flush().
2129 * Returns: #GST_RTSP_OK on success.
2132 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2136 GstRTSPBuilder builder;
2140 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2141 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2142 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2144 /* configure timeout if any */
2145 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2147 gst_poll_set_controllable (conn->fdset, TRUE);
2148 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2149 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2151 memset (&builder, 0, sizeof (GstRTSPBuilder));
2153 res = build_next (&builder, message, conn);
2154 if (G_UNLIKELY (res == GST_RTSP_EEOF))
2156 else if (G_LIKELY (res == GST_RTSP_OK)) {
2157 if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2158 if (conn->tstate == TUNNEL_STATE_NONE &&
2159 message->type_data.request.method == GST_RTSP_GET) {
2160 GstRTSPMessage *response;
2162 conn->tstate = TUNNEL_STATE_GET;
2164 /* tunnel GET request, we can reply now */
2165 response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2166 res = gst_rtsp_connection_send (conn, response, timeout);
2167 gst_rtsp_message_free (response);
2168 if (res == GST_RTSP_OK)
2169 res = GST_RTSP_ETGET;
2171 } else if (conn->tstate == TUNNEL_STATE_NONE &&
2172 message->type_data.request.method == GST_RTSP_POST) {
2173 conn->tstate = TUNNEL_STATE_POST;
2175 /* tunnel POST request, the caller now has to link the two
2177 res = GST_RTSP_ETPOST;
2180 res = GST_RTSP_EPARSE;
2186 } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2190 retval = gst_poll_wait (conn->fdset, to);
2191 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2193 /* check for timeout */
2194 if (G_UNLIKELY (retval == 0))
2195 goto select_timeout;
2197 if (G_UNLIKELY (retval == -1)) {
2203 gst_poll_set_controllable (conn->fdset, FALSE);
2206 /* we have a message here */
2207 build_reset (&builder);
2214 res = GST_RTSP_ESYS;
2219 res = GST_RTSP_ETIMEOUT;
2224 res = GST_RTSP_EINTR;
2229 res = GST_RTSP_EEOF;
2235 build_reset (&builder);
2236 gst_rtsp_message_unset (message);
2242 * gst_rtsp_connection_close:
2243 * @conn: a #GstRTSPConnection
2245 * Close the connected @conn. After this call, the connection is in the same
2246 * state as when it was first created.
2248 * Returns: #GST_RTSP_OK on success.
2251 gst_rtsp_connection_close (GstRTSPConnection * conn)
2253 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2258 conn->read_ahead = 0;
2260 g_free (conn->initial_buffer);
2261 conn->initial_buffer = NULL;
2262 conn->initial_buffer_offset = 0;
2264 REMOVE_POLLFD (conn->fdset, &conn->fd0);
2265 REMOVE_POLLFD (conn->fdset, &conn->fd1);
2266 conn->writefd = NULL;
2267 conn->readfd = NULL;
2268 conn->tunneled = FALSE;
2269 conn->tstate = TUNNEL_STATE_NONE;
2271 g_free (conn->username);
2272 conn->username = NULL;
2273 g_free (conn->passwd);
2274 conn->passwd = NULL;
2275 gst_rtsp_connection_clear_auth_params (conn);
2278 conn->session_id[0] = '\0';
2284 * gst_rtsp_connection_free:
2285 * @conn: a #GstRTSPConnection
2287 * Close and free @conn.
2289 * Returns: #GST_RTSP_OK on success.
2292 gst_rtsp_connection_free (GstRTSPConnection * conn)
2296 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2298 res = gst_rtsp_connection_close (conn);
2299 gst_poll_free (conn->fdset);
2300 g_timer_destroy (conn->timer);
2301 gst_rtsp_url_free (conn->url);
2302 g_free (conn->proxy_host);
2312 * gst_rtsp_connection_poll:
2313 * @conn: a #GstRTSPConnection
2314 * @events: a bitmask of #GstRTSPEvent flags to check
2315 * @revents: location for result flags
2316 * @timeout: a timeout
2318 * Wait up to the specified @timeout for the connection to become available for
2319 * at least one of the operations specified in @events. When the function returns
2320 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2323 * @timeout can be #NULL, in which case this function might block forever.
2325 * This function can be cancelled with gst_rtsp_connection_flush().
2327 * Returns: #GST_RTSP_OK on success.
2332 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2333 GstRTSPEvent * revents, GTimeVal * timeout)
2338 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2339 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2340 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2341 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2342 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2344 gst_poll_set_controllable (conn->fdset, TRUE);
2346 /* add fd to writer set when asked to */
2347 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2348 events & GST_RTSP_EV_WRITE);
2350 /* add fd to reader set when asked to */
2351 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2353 /* configure timeout if any */
2354 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2357 retval = gst_poll_wait (conn->fdset, to);
2358 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2360 if (G_UNLIKELY (retval == 0))
2361 goto select_timeout;
2363 if (G_UNLIKELY (retval == -1)) {
2371 if (events & GST_RTSP_EV_READ) {
2372 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2373 *revents |= GST_RTSP_EV_READ;
2375 if (events & GST_RTSP_EV_WRITE) {
2376 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2377 *revents |= GST_RTSP_EV_WRITE;
2384 return GST_RTSP_ETIMEOUT;
2388 return GST_RTSP_ESYS;
2392 return GST_RTSP_EINTR;
2397 * gst_rtsp_connection_next_timeout:
2398 * @conn: a #GstRTSPConnection
2399 * @timeout: a timeout
2401 * Calculate the next timeout for @conn, storing the result in @timeout.
2403 * Returns: #GST_RTSP_OK.
2406 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2412 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2413 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2415 elapsed = g_timer_elapsed (conn->timer, &usec);
2416 if (elapsed >= conn->timeout) {
2420 sec = conn->timeout - elapsed;
2423 timeout->tv_sec = sec;
2424 timeout->tv_usec = usec;
2430 * gst_rtsp_connection_reset_timeout:
2431 * @conn: a #GstRTSPConnection
2433 * Reset the timeout of @conn.
2435 * Returns: #GST_RTSP_OK.
2438 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2440 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2442 g_timer_start (conn->timer);
2448 * gst_rtsp_connection_flush:
2449 * @conn: a #GstRTSPConnection
2450 * @flush: start or stop the flush
2452 * Start or stop the flushing action on @conn. When flushing, all current
2453 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2454 * is set to non-flushing mode again.
2456 * Returns: #GST_RTSP_OK.
2459 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2461 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2463 gst_poll_set_flushing (conn->fdset, flush);
2469 * gst_rtsp_connection_set_proxy:
2470 * @conn: a #GstRTSPConnection
2471 * @host: the proxy host
2472 * @port: the proxy port
2474 * Set the proxy host and port.
2476 * Returns: #GST_RTSP_OK.
2481 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2482 const gchar * host, guint port)
2484 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2486 g_free (conn->proxy_host);
2487 conn->proxy_host = g_strdup (host);
2488 conn->proxy_port = port;
2494 * gst_rtsp_connection_set_auth:
2495 * @conn: a #GstRTSPConnection
2496 * @method: authentication method
2498 * @pass: the password
2500 * Configure @conn for authentication mode @method with @user and @pass as the
2501 * user and password respectively.
2503 * Returns: #GST_RTSP_OK.
2506 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2507 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2509 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2511 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2512 || g_strrstr (user, ":") != NULL))
2513 return GST_RTSP_EINVAL;
2515 /* Make sure the username and passwd are being set for authentication */
2516 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2517 return GST_RTSP_EINVAL;
2519 /* ":" chars are not allowed in usernames for basic auth */
2520 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2521 return GST_RTSP_EINVAL;
2523 g_free (conn->username);
2524 g_free (conn->passwd);
2526 conn->auth_method = method;
2527 conn->username = g_strdup (user);
2528 conn->passwd = g_strdup (pass);
2535 * @key: ASCII string to hash
2537 * Hashes @key in a case-insensitive manner.
2539 * Returns: the hash code.
2542 str_case_hash (gconstpointer key)
2544 const char *p = key;
2545 guint h = g_ascii_toupper (*p);
2548 for (p += 1; *p != '\0'; p++)
2549 h = (h << 5) - h + g_ascii_toupper (*p);
2556 * @v1: an ASCII string
2557 * @v2: another ASCII string
2559 * Compares @v1 and @v2 in a case-insensitive manner
2561 * Returns: %TRUE if they are equal (modulo case)
2564 str_case_equal (gconstpointer v1, gconstpointer v2)
2566 const char *string1 = v1;
2567 const char *string2 = v2;
2569 return g_ascii_strcasecmp (string1, string2) == 0;
2573 * gst_rtsp_connection_set_auth_param:
2574 * @conn: a #GstRTSPConnection
2575 * @param: authentication directive
2578 * Setup @conn with authentication directives. This is not necesary for
2579 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2580 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2581 * in the WWW-Authenticate response header and can include realm, domain,
2582 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2587 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2588 const gchar * param, const gchar * value)
2590 g_return_if_fail (conn != NULL);
2591 g_return_if_fail (param != NULL);
2593 if (conn->auth_params == NULL) {
2595 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2597 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2601 * gst_rtsp_connection_clear_auth_params:
2602 * @conn: a #GstRTSPConnection
2604 * Clear the list of authentication directives stored in @conn.
2609 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2611 g_return_if_fail (conn != NULL);
2613 if (conn->auth_params != NULL) {
2614 g_hash_table_destroy (conn->auth_params);
2615 conn->auth_params = NULL;
2619 static GstRTSPResult
2620 set_qos_dscp (gint fd, guint qos_dscp)
2622 union gst_sockaddr sa;
2623 socklen_t slen = sizeof (sa);
2630 if (getsockname (fd, &sa.sa, &slen) < 0)
2631 goto no_getsockname;
2633 af = sa.sa.sa_family;
2635 /* if this is an IPv4-mapped address then do IPv4 QoS */
2636 if (af == AF_INET6) {
2637 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2641 /* extract and shift 6 bits of the DSCP */
2642 tos = (qos_dscp & 0x3f) << 2;
2646 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2651 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2665 return GST_RTSP_ESYS;
2670 return GST_RTSP_ERROR;
2675 * gst_rtsp_connection_set_qos_dscp:
2676 * @conn: a #GstRTSPConnection
2677 * @qos_dscp: DSCP value
2679 * Configure @conn to use the specified DSCP value.
2681 * Returns: #GST_RTSP_OK on success.
2686 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2690 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2691 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2692 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2694 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2695 if (res == GST_RTSP_OK)
2696 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2703 * gst_rtsp_connection_get_url:
2704 * @conn: a #GstRTSPConnection
2706 * Retrieve the URL of the other end of @conn.
2708 * Returns: The URL. This value remains valid until the
2709 * connection is freed.
2714 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2716 g_return_val_if_fail (conn != NULL, NULL);
2722 * gst_rtsp_connection_get_ip:
2723 * @conn: a #GstRTSPConnection
2725 * Retrieve the IP address of the other end of @conn.
2727 * Returns: The IP address as a string. this value remains valid until the
2728 * connection is closed.
2733 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2735 g_return_val_if_fail (conn != NULL, NULL);
2741 * gst_rtsp_connection_set_ip:
2742 * @conn: a #GstRTSPConnection
2743 * @ip: an ip address
2745 * Set the IP address of the server.
2750 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2752 g_return_if_fail (conn != NULL);
2755 conn->ip = g_strdup (ip);
2759 * gst_rtsp_connection_get_readfd:
2760 * @conn: a #GstRTSPConnection
2762 * Get the file descriptor for reading.
2764 * Returns: the file descriptor used for reading or -1 on error. The file
2765 * descriptor remains valid until the connection is closed.
2770 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2772 g_return_val_if_fail (conn != NULL, -1);
2773 g_return_val_if_fail (conn->readfd != NULL, -1);
2775 return conn->readfd->fd;
2779 * gst_rtsp_connection_get_writefd:
2780 * @conn: a #GstRTSPConnection
2782 * Get the file descriptor for writing.
2784 * Returns: the file descriptor used for writing or -1 on error. The file
2785 * descriptor remains valid until the connection is closed.
2790 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2792 g_return_val_if_fail (conn != NULL, -1);
2793 g_return_val_if_fail (conn->writefd != NULL, -1);
2795 return conn->writefd->fd;
2800 * gst_rtsp_connection_set_tunneled:
2801 * @conn: a #GstRTSPConnection
2802 * @tunneled: the new state
2804 * Set the HTTP tunneling state of the connection. This must be configured before
2805 * the @conn is connected.
2810 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2812 g_return_if_fail (conn != NULL);
2813 g_return_if_fail (conn->readfd == NULL);
2814 g_return_if_fail (conn->writefd == NULL);
2816 conn->tunneled = tunneled;
2820 * gst_rtsp_connection_is_tunneled:
2821 * @conn: a #GstRTSPConnection
2823 * Get the tunneling state of the connection.
2825 * Returns: if @conn is using HTTP tunneling.
2830 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2832 g_return_val_if_fail (conn != NULL, FALSE);
2834 return conn->tunneled;
2838 * gst_rtsp_connection_get_tunnelid:
2839 * @conn: a #GstRTSPConnection
2841 * Get the tunnel session id the connection.
2843 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2848 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2850 g_return_val_if_fail (conn != NULL, NULL);
2852 if (!conn->tunneled)
2855 return conn->tunnelid;
2859 * gst_rtsp_connection_do_tunnel:
2860 * @conn: a #GstRTSPConnection
2861 * @conn2: a #GstRTSPConnection or %NULL
2863 * If @conn received the first tunnel connection and @conn2 received
2864 * the second tunnel connection, link the two connections together so that
2865 * @conn manages the tunneled connection.
2867 * After this call, @conn2 cannot be used anymore and must be freed with
2868 * gst_rtsp_connection_free().
2870 * If @conn2 is %NULL then only the base64 decoding context will be setup for
2873 * Returns: return GST_RTSP_OK on success.
2878 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2879 GstRTSPConnection * conn2)
2881 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2883 if (conn2 != NULL) {
2884 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2885 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2886 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2887 TUNNELID_LEN), GST_RTSP_EINVAL);
2889 /* both connections have fd0 as the read/write socket. start by taking the
2890 * socket from conn2 and set it as the socket in conn */
2891 conn->fd1 = conn2->fd0;
2893 /* clean up some of the state of conn2 */
2894 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2896 conn2->readfd = conn2->writefd = NULL;
2898 /* We make fd0 the write socket and fd1 the read socket. */
2899 conn->writefd = &conn->fd0;
2900 conn->readfd = &conn->fd1;
2902 conn->tstate = TUNNEL_STATE_COMPLETE;
2905 /* we need base64 decoding for the readfd */
2906 conn->ctx.state = 0;
2909 conn->ctx.coutl = 0;
2910 conn->ctxp = &conn->ctx;
2915 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2916 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2925 /* async functions */
2926 struct _GstRTSPWatch
2930 GstRTSPConnection *conn;
2932 GstRTSPBuilder builder;
2933 GstRTSPMessage message;
2937 gboolean write_added;
2939 /* queued message for transmission */
2941 GAsyncQueue *messages;
2947 GstRTSPWatchFuncs funcs;
2950 GDestroyNotify notify;
2954 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2956 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2958 if (watch->conn->initial_buffer != NULL)
2961 *timeout = (watch->conn->timeout * 1000);
2967 gst_rtsp_source_check (GSource * source)
2969 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2971 if (watch->readfd.revents & READ_COND)
2974 if (watch->writefd.revents & WRITE_COND)
2981 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
2982 gpointer user_data G_GNUC_UNUSED)
2984 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2987 /* first read as much as we can */
2988 if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
2990 res = build_next (&watch->builder, &watch->message, watch->conn);
2991 if (res == GST_RTSP_EINTR)
2993 else if (G_UNLIKELY (res == GST_RTSP_EEOF))
2995 else if (G_LIKELY (res == GST_RTSP_OK)) {
2996 if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2997 if (watch->conn->tstate == TUNNEL_STATE_NONE &&
2998 watch->message.type_data.request.method == GST_RTSP_GET) {
2999 GstRTSPMessage *response;
3000 GstRTSPStatusCode code;
3002 watch->conn->tstate = TUNNEL_STATE_GET;
3004 if (watch->funcs.tunnel_start)
3005 code = watch->funcs.tunnel_start (watch, watch->user_data);
3007 code = GST_RTSP_STS_OK;
3009 /* queue the response */
3010 response = gen_tunnel_reply (watch->conn, code, &watch->message);
3011 gst_rtsp_watch_queue_message (watch, response);
3012 gst_rtsp_message_free (response);
3014 } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3015 watch->message.type_data.request.method == GST_RTSP_POST) {
3016 watch->conn->tstate = TUNNEL_STATE_POST;
3018 /* in the callback the connection should be tunneled with the
3020 if (watch->funcs.tunnel_complete)
3021 watch->funcs.tunnel_complete (watch, watch->user_data);
3024 res = GST_RTSP_ERROR;
3029 if (G_LIKELY (res == GST_RTSP_OK)) {
3030 if (watch->funcs.message_received)
3031 watch->funcs.message_received (watch, &watch->message,
3034 if (watch->funcs.error_full)
3035 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3036 0, watch->user_data), error);
3042 gst_rtsp_message_unset (&watch->message);
3043 build_reset (&watch->builder);
3047 if (watch->writefd.revents & WRITE_COND) {
3049 if (watch->write_data == NULL) {
3052 /* get a new message from the queue */
3053 rec = g_async_queue_try_pop (watch->messages);
3057 watch->write_off = 0;
3058 watch->write_data = rec->data;
3059 watch->write_size = rec->size;
3060 watch->write_id = rec->id;
3062 g_slice_free (GstRTSPRec, rec);
3065 res = write_bytes (watch->writefd.fd, watch->write_data,
3066 &watch->write_off, watch->write_size);
3067 if (res == GST_RTSP_EINTR)
3069 else if (G_LIKELY (res == GST_RTSP_OK)) {
3070 if (watch->funcs.message_sent)
3071 watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3073 if (watch->funcs.error_full)
3074 GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3075 watch->write_id, watch->user_data), error);
3080 g_free (watch->write_data);
3081 watch->write_data = NULL;
3085 if (watch->write_added) {
3086 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3087 watch->write_added = FALSE;
3088 watch->writefd.revents = 0;
3098 if (watch->funcs.closed)
3099 watch->funcs.closed (watch, watch->user_data);
3104 if (watch->funcs.error)
3105 watch->funcs.error (watch, res, watch->user_data);
3111 gst_rtsp_rec_free (gpointer data)
3113 GstRTSPRec *rec = data;
3116 g_slice_free (GstRTSPRec, rec);
3120 gst_rtsp_source_finalize (GSource * source)
3122 GstRTSPWatch *watch = (GstRTSPWatch *) source;
3124 build_reset (&watch->builder);
3125 gst_rtsp_message_unset (&watch->message);
3127 g_async_queue_unref (watch->messages);
3128 watch->messages = NULL;
3130 g_free (watch->write_data);
3133 watch->notify (watch->user_data);
3136 static GSourceFuncs gst_rtsp_source_funcs = {
3137 gst_rtsp_source_prepare,
3138 gst_rtsp_source_check,
3139 gst_rtsp_source_dispatch,
3140 gst_rtsp_source_finalize,
3146 * gst_rtsp_watch_new:
3147 * @conn: a #GstRTSPConnection
3148 * @funcs: watch functions
3149 * @user_data: user data to pass to @funcs
3150 * @notify: notify when @user_data is not referenced anymore
3152 * Create a watch object for @conn. The functions provided in @funcs will be
3153 * called with @user_data when activity happened on the watch.
3155 * The new watch is usually created so that it can be attached to a
3156 * maincontext with gst_rtsp_watch_attach().
3158 * @conn must exist for the entire lifetime of the watch.
3160 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3161 * communication. Free with gst_rtsp_watch_unref () after usage.
3166 gst_rtsp_watch_new (GstRTSPConnection * conn,
3167 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3169 GstRTSPWatch *result;
3171 g_return_val_if_fail (conn != NULL, NULL);
3172 g_return_val_if_fail (funcs != NULL, NULL);
3173 g_return_val_if_fail (conn->readfd != NULL, NULL);
3174 g_return_val_if_fail (conn->writefd != NULL, NULL);
3176 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3177 sizeof (GstRTSPWatch));
3179 result->conn = conn;
3180 result->builder.state = STATE_START;
3182 result->messages = g_async_queue_new_full (gst_rtsp_rec_free);
3184 result->readfd.fd = -1;
3185 result->writefd.fd = -1;
3187 gst_rtsp_watch_reset (result);
3189 result->funcs = *funcs;
3190 result->user_data = user_data;
3191 result->notify = notify;
3193 /* only add the read fd, the write fd is only added when we have data
3195 g_source_add_poll ((GSource *) result, &result->readfd);
3201 * gst_rtsp_watch_reset:
3202 * @watch: a #GstRTSPWatch
3204 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3205 * when the file descriptors of the connection might have changed.
3210 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3212 if (watch->readfd.fd != -1)
3213 g_source_remove_poll ((GSource *) watch, &watch->readfd);
3214 if (watch->writefd.fd != -1)
3215 g_source_remove_poll ((GSource *) watch, &watch->writefd);
3217 watch->readfd.fd = watch->conn->readfd->fd;
3218 watch->readfd.events = READ_COND;
3219 watch->readfd.revents = 0;
3221 watch->writefd.fd = watch->conn->writefd->fd;
3222 watch->writefd.events = WRITE_COND;
3223 watch->writefd.revents = 0;
3224 watch->write_added = FALSE;
3226 g_source_add_poll ((GSource *) watch, &watch->readfd);
3230 * gst_rtsp_watch_attach:
3231 * @watch: a #GstRTSPWatch
3232 * @context: a GMainContext (if NULL, the default context will be used)
3234 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3236 * Returns: the ID (greater than 0) for the watch within the GMainContext.
3241 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3243 g_return_val_if_fail (watch != NULL, 0);
3245 return g_source_attach ((GSource *) watch, context);
3249 * gst_rtsp_watch_unref:
3250 * @watch: a #GstRTSPWatch
3252 * Decreases the reference count of @watch by one. If the resulting reference
3253 * count is zero the watch and associated memory will be destroyed.
3258 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3260 g_return_if_fail (watch != NULL);
3262 g_source_unref ((GSource *) watch);
3266 * gst_rtsp_watch_queue_data:
3267 * @watch: a #GstRTSPWatch
3268 * @data: the data to queue
3269 * @size: the size of @data
3271 * Queue @data for transmission in @watch. It will be transmitted when the
3272 * connection of the @watch becomes writable.
3274 * This function will take ownership of @data and g_free() it after use.
3276 * The return value of this function will be used as the id argument in the
3277 * message_sent callback.
3284 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3289 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3290 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3291 g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3293 /* make a record with the data and id */
3294 rec = g_slice_new (GstRTSPRec);
3295 rec->data = (guint8 *) data;
3298 /* make sure rec->id is never 0 */
3299 rec->id = ++watch->id;
3300 } while (G_UNLIKELY (rec->id == 0));
3302 /* add the record to a queue. FIXME we would like to have an upper limit here */
3303 g_async_queue_push (watch->messages, rec);
3305 /* FIXME: does the following need to be made thread-safe? (this might be
3306 * called from a streaming thread, like appsink's render function) */
3307 /* make sure the main context will now also check for writability on the
3309 if (!watch->write_added) {
3310 g_source_add_poll ((GSource *) watch, &watch->writefd);
3311 watch->write_added = TRUE;
3318 * gst_rtsp_watch_queue_message:
3319 * @watch: a #GstRTSPWatch
3320 * @message: a #GstRTSPMessage
3322 * Queue a @message for transmission in @watch. The contents of this
3323 * message will be serialized and transmitted when the connection of the
3324 * @watch becomes writable.
3326 * The return value of this function will be used as the id argument in the
3327 * message_sent callback.
3334 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3339 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3340 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3342 /* make a record with the message as a string and id */
3343 str = message_to_string (watch->conn, message);
3345 return gst_rtsp_watch_queue_data (watch,
3346 (guint8 *) g_string_free (str, FALSE), size);