2 * Copyright (C) <2005,2006> Wim Taymans <wim@fluendo.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)
73 /* we include this here to get the G_OS_* defines */
80 #define EINPROGRESS WSAEINPROGRESS
82 #include <sys/ioctl.h>
84 #include <sys/socket.h>
85 #include <netinet/in.h>
86 #include <arpa/inet.h>
90 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
91 #include <sys/filio.h>
94 #include "gstrtspconnection.h"
95 #include "gstrtspbase64.h"
98 static GstRTSPResult read_line (gint fd, guint8 * buffer, guint * idx,
100 static GstRTSPResult parse_key_value (guint8 * buffer, gchar * key,
101 guint keysize, gchar ** value);
102 static void parse_string (gchar * dest, gint size, gchar ** src);
105 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
106 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
107 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
108 #define CLOSE_SOCKET(sock) closesocket (sock)
109 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
110 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
111 /* According to Microsoft's connect() documentation this one returns
112 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
113 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
115 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
116 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
117 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
118 #define CLOSE_SOCKET(sock) close (sock)
119 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
120 #define ERRNO_IS_EINTR (errno == EINTR)
121 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
124 #define ADD_POLLFD(fdset, pfd, fd) \
127 gst_poll_add_fd (fdset, pfd); \
130 #define REMOVE_POLLFD(fdset, pfd) \
132 if ((pfd)->fd != -1) { \
133 GST_DEBUG ("remove fd %d", (pfd)->fd); \
134 gst_poll_remove_fd (fdset, pfd); \
135 CLOSE_SOCKET ((pfd)->fd); \
140 struct _GstRTSPConnection
143 /* URL for the connection */
146 /* connection state */
159 gint cseq; /* sequence number */
160 gchar session_id[512]; /* session id */
161 gint timeout; /* session timeout in seconds */
162 GTimer *timer; /* timeout timer */
165 GstRTSPAuthMethod auth_method;
168 GHashTable *auth_params;
173 inet_aton (const char *c, struct in_addr *paddr)
175 /* note that inet_addr is deprecated on unix because
176 * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
178 paddr->s_addr = inet_addr (c);
180 if (paddr->s_addr == INADDR_NONE)
197 /* a structure for constructing RTSPMessages */
210 build_reset (GstRTSPBuilder * builder)
212 g_free (builder->body_data);
213 memset (builder, 0, sizeof (builder));
217 * gst_rtsp_connection_create:
218 * @url: a #GstRTSPUrl
219 * @conn: storage for a #GstRTSPConnection
221 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
222 * The connection will not yet attempt to connect to @url, use
223 * gst_rtsp_connection_connect().
225 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
228 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
230 GstRTSPConnection *newconn;
236 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
239 error = WSAStartup (0x0202, &w);
244 if (w.wVersion != 0x0202)
248 newconn = g_new0 (GstRTSPConnection, 1);
250 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
254 newconn->fd0.fd = -1;
255 newconn->fd1.fd = -1;
256 newconn->timer = g_timer_new ();
257 newconn->timeout = 60;
258 newconn->tunneled = FALSE;
260 newconn->auth_method = GST_RTSP_AUTH_NONE;
261 newconn->username = NULL;
262 newconn->passwd = NULL;
263 newconn->auth_params = NULL;
273 g_warning ("Error %d on WSAStartup", error);
274 return GST_RTSP_EWSASTART;
278 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
281 return GST_RTSP_EWSAVERSION;
290 return GST_RTSP_ESYS;
295 * gst_rtsp_connection_accept:
297 * @conn: storage for a #GstRTSPConnection
299 * Accept a new connection on @sock and create a new #GstRTSPConnection for
300 * handling communication on new socket.
302 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
307 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
310 unsigned int address_len;
311 GstRTSPConnection *newconn = NULL;
312 struct sockaddr_in address;
318 address_len = sizeof (address);
319 memset (&address, 0, address_len);
322 fd = accept (sock, (struct sockaddr *) &address, &address_len);
324 fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
325 #endif /* G_OS_WIN32 */
329 /* set to non-blocking mode so that we can cancel the communication */
331 fcntl (fd, F_SETFL, O_NONBLOCK);
333 ioctlsocket (fd, FIONBIO, &flags);
334 #endif /* G_OS_WIN32 */
336 /* create a url for the client address */
337 url = g_new0 (GstRTSPUrl, 1);
338 url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
339 url->port = address.sin_port;
341 /* now create the connection object */
342 gst_rtsp_connection_create (url, &newconn);
343 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
345 newconn->readfd = &newconn->fd0;
346 newconn->writefd = &newconn->fd0;
355 return GST_RTSP_ESYS;
360 do_resolve (const gchar * host)
362 struct hostent *hostinfo;
366 struct in_addr *addrp;
369 gchar ipbuf[INET_ADDRSTRLEN];
370 #endif /* G_OS_WIN32 */
374 /* first check if it already is an IP address */
375 if (inet_aton (host, &addr)) {
378 hostinfo = gethostbyname (host);
380 goto not_resolved; /* h_errno set */
382 if (hostinfo->h_addrtype != AF_INET)
383 goto not_ip; /* host not an IP host */
385 addrp = (struct in_addr *) hostinfo->h_addr_list[0];
386 /* this is not threadsafe */
387 ip = inet_ntoa (*addrp);
389 addrs = hostinfo->h_addr_list;
390 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
392 #endif /* G_OS_WIN32 */
399 GST_ERROR ("could not resolve %s", host);
404 GST_ERROR ("not an IP address");
410 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
411 GstPoll * fdset, GTimeVal * timeout)
414 struct sockaddr_in sa_in;
417 unsigned long flags = 1;
418 #endif /* G_OS_WIN32 */
422 g_message ("connect %s:%u", ip, port);
424 memset (&sa_in, 0, sizeof (sa_in));
425 sa_in.sin_family = AF_INET; /* network socket */
426 sa_in.sin_port = htons (port); /* on port */
427 sa_in.sin_addr.s_addr = inet_addr (ip); /* on host ip */
429 fd = socket (AF_INET, SOCK_STREAM, 0);
433 /* set to non-blocking mode so that we can cancel the connect */
435 fcntl (fd, F_SETFL, O_NONBLOCK);
437 ioctlsocket (fd, FIONBIO, &flags);
438 #endif /* G_OS_WIN32 */
440 /* add the socket to our fdset */
441 ADD_POLLFD (fdset, fdout, fd);
443 /* we are going to connect ASYNC now */
444 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
447 if (!ERRNO_IS_EINPROGRESS)
450 /* wait for connect to complete up to the specified timeout or until we got
452 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
454 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
457 retval = gst_poll_wait (fdset, to);
458 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
462 else if (retval == -1)
465 /* we can still have an error connecting on windows */
466 if (gst_poll_fd_has_error (fdset, fdout)) {
467 socklen_t len = sizeof (errno);
469 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
471 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
476 gst_poll_fd_ignored (fdset, fdout);
484 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
485 return GST_RTSP_ESYS;
489 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
490 REMOVE_POLLFD (fdset, fdout);
491 return GST_RTSP_ESYS;
495 GST_ERROR ("timeout");
496 REMOVE_POLLFD (fdset, fdout);
497 return GST_RTSP_ETIMEOUT;
502 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
516 /* create a random sessionid */
517 for (i = 0; i < 24; i++)
518 sessionid[i] = g_random_int_range ('a', 'z');
519 sessionid[23] = '\0';
522 str = g_strdup_printf ("GET %s HTTP/1.0\r\n"
523 "x-sessioncookie: %s\r\n"
524 "Accept: application/x-rtsp-tunnelled\r\n"
525 "Pragma: no-cache\r\n"
526 "Cache-Control: no-cache\r\n" "\r\n", conn->url->host, sessionid);
528 /* we start by writing to this fd */
529 conn->writefd = &conn->fd0;
531 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
533 if (res != GST_RTSP_OK)
536 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
537 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
539 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
547 res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer));
548 if (res == GST_RTSP_EEOF)
550 if (res == GST_RTSP_OK)
552 if (res != GST_RTSP_EINTR)
556 retval = gst_poll_wait (conn->fdset, to);
557 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
559 /* check for timeout */
571 /* check for last line */
572 if (buffer[0] == '\r')
574 if (buffer[0] == '\0')
578 /* first line, parse response */
579 gchar versionstr[20];
582 bptr = (gchar *) buffer;
584 parse_string (versionstr, sizeof (versionstr), &bptr);
585 parse_string (codestr, sizeof (codestr), &bptr);
586 code = atoi (codestr);
594 /* other lines, parse key/value */
595 res = parse_key_value (buffer, key, sizeof (key), &value);
596 if (res == GST_RTSP_OK) {
597 /* we got a new ip address */
598 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
600 conn->ip = g_strdup (value);
607 if (!(ip = do_resolve (conn->ip)))
610 /* get the port from the url */
611 gst_rtsp_url_get_port (conn->url, &port);
613 /* connect to the host/port */
614 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
615 if (res != GST_RTSP_OK)
618 /* this is now our writing socket */
619 conn->writefd = &conn->fd1;
622 str = g_strdup_printf ("POST %s HTTP/1.0\r\n"
623 "x-sessioncookie: %s\r\n"
624 "Content-Type: application/x-rtsp-tunnelled\r\n"
625 "Pragma: no-cache\r\n"
626 "Cache-Control: no-cache\r\n"
627 "Content-Length: 32767\r\n"
628 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
629 "\r\n", conn->url->host, sessionid);
631 /* we start by writing to this fd */
632 conn->writefd = &conn->fd1;
634 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
636 if (res != GST_RTSP_OK)
644 GST_ERROR ("write failed", res);
649 return GST_RTSP_EEOF;
657 return GST_RTSP_ETIMEOUT;
661 return GST_RTSP_ESYS;
665 return GST_RTSP_EINTR;
669 GST_ERROR ("got failure response %d %s", code, codestr);
670 return GST_RTSP_ERROR;
674 GST_ERROR ("could not resolve %s", conn->ip);
675 return GST_RTSP_ENET;
679 GST_ERROR ("failed to connect");
685 * gst_rtsp_connection_connect:
686 * @conn: a #GstRTSPConnection
687 * @timeout: a #GTimeVal timeout
689 * Attempt to connect to the url of @conn made with
690 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
691 * forever. If @timeout contains a valid timeout, this function will return
692 * #GST_RTSP_ETIMEOUT after the timeout expired.
694 * This function can be cancelled with gst_rtsp_connection_flush().
696 * Returns: #GST_RTSP_OK when a connection could be made.
699 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
706 unsigned long flags = 1;
707 #endif /* G_OS_WIN32 */
709 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
710 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
711 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
715 if (!(ip = do_resolve (url->host)))
718 /* get the port from the url */
719 gst_rtsp_url_get_port (url, &port);
721 /* connect to the host/port */
722 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
723 if (res != GST_RTSP_OK)
727 conn->ip = g_strdup (ip);
729 /* this is our read URL */
730 conn->readfd = &conn->fd0;
732 if (conn->tunneled) {
733 res = setup_tunneling (conn, timeout);
734 if (res != GST_RTSP_OK)
735 goto tunneling_failed;
737 conn->writefd = &conn->fd0;
744 GST_ERROR ("could not resolve %s", url->host);
745 return GST_RTSP_ENET;
749 GST_ERROR ("failed to connect");
754 GST_ERROR ("failed to setup tunneling");
760 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
762 static const char hexdigits[] = "0123456789abcdef";
765 for (i = 0; i < 16; i++) {
766 string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
767 string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
773 auth_digest_compute_hex_urp (const gchar * username,
774 const gchar * realm, const gchar * password, gchar hex_urp[33])
776 struct MD5Context md5_context;
777 unsigned char digest[16];
779 MD5Init (&md5_context);
780 MD5Update (&md5_context, username, strlen (username));
781 MD5Update (&md5_context, ":", 1);
782 MD5Update (&md5_context, realm, strlen (realm));
783 MD5Update (&md5_context, ":", 1);
784 MD5Update (&md5_context, password, strlen (password));
785 MD5Final (digest, &md5_context);
786 md5_digest_to_hex_string (digest, hex_urp);
790 auth_digest_compute_response (const gchar * method,
791 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
795 struct MD5Context md5_context;
796 unsigned char digest[16];
799 MD5Init (&md5_context);
800 MD5Update (&md5_context, method, strlen (method));
801 MD5Update (&md5_context, ":", 1);
802 MD5Update (&md5_context, uri, strlen (uri));
803 MD5Final (digest, &md5_context);
804 md5_digest_to_hex_string (digest, hex_a2);
807 MD5Init (&md5_context);
808 MD5Update (&md5_context, hex_a1, strlen (hex_a1));
809 MD5Update (&md5_context, ":", 1);
810 MD5Update (&md5_context, nonce, strlen (nonce));
811 MD5Update (&md5_context, ":", 1);
813 MD5Update (&md5_context, hex_a2, 32);
814 MD5Final (digest, &md5_context);
815 md5_digest_to_hex_string (digest, response);
819 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
821 switch (conn->auth_method) {
822 case GST_RTSP_AUTH_BASIC:{
824 g_strdup_printf ("%s:%s", conn->username, conn->passwd);
826 gst_rtsp_base64_encode (user_pass, strlen (user_pass));
827 gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
829 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
833 g_free (user_pass64);
836 case GST_RTSP_AUTH_DIGEST:{
837 gchar response[33], hex_urp[33];
838 gchar *auth_string, *auth_string2;
845 /* we need to have some params set */
846 if (conn->auth_params == NULL)
849 /* we need the realm and nonce */
850 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
851 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
852 if (realm == NULL || nonce == NULL)
855 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
858 method = gst_rtsp_method_as_text (message->type_data.request.method);
859 uri = message->type_data.request.uri;
861 /* Assume no qop, algorithm=md5, stale=false */
862 /* For algorithm MD5, a1 = urp. */
863 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
864 auth_string = g_strdup_printf ("Digest username=\"%s\", "
865 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
866 conn->username, realm, nonce, uri, response);
868 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
870 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
872 g_free (auth_string);
873 auth_string = auth_string2;
875 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
886 add_date_header (GstRTSPMessage * message)
889 gchar date_string[100];
896 g_get_current_time (&tv);
897 t = (time_t) tv.tv_sec;
900 strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
901 gmtime_r (&t, &tm_));
903 strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
907 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
911 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
916 return GST_RTSP_ERROR;
923 r = WRITE_SOCKET (fd, &buffer[*idx], left);
925 return GST_RTSP_EINTR;
928 return GST_RTSP_EINTR;
930 return GST_RTSP_ESYS;
940 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size)
945 return GST_RTSP_ERROR;
952 r = READ_SOCKET (fd, &buffer[*idx], left);
954 return GST_RTSP_EEOF;
957 return GST_RTSP_EINTR;
959 return GST_RTSP_ESYS;
969 read_line (gint fd, guint8 * buffer, guint * idx, guint size)
975 r = READ_SOCKET (fd, &c, 1);
977 return GST_RTSP_EEOF;
980 return GST_RTSP_EINTR;
982 return GST_RTSP_ESYS;
984 if (c == '\n') /* end on \n */
986 if (c == '\r') /* ignore \r */
990 buffer[(*idx)++] = c;
999 * gst_rtsp_connection_write:
1000 * @conn: a #GstRTSPConnection
1001 * @data: the data to write
1002 * @size: the size of @data
1003 * @timeout: a timeout value or #NULL
1005 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1006 * the specified @timeout. @timeout can be #NULL, in which case this function
1007 * might block forever.
1009 * This function can be cancelled with gst_rtsp_connection_flush().
1011 * Returns: #GST_RTSP_OK on success.
1014 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1015 guint size, GTimeVal * timeout)
1022 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1023 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1024 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1026 gst_poll_set_controllable (conn->fdset, TRUE);
1027 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1028 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1029 /* clear all previous poll results */
1030 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1031 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1033 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1039 res = write_bytes (conn->writefd->fd, data, &offset, size);
1040 if (res == GST_RTSP_OK)
1042 if (res != GST_RTSP_EINTR)
1045 /* not all is written, wait until we can write more */
1047 retval = gst_poll_wait (conn->fdset, to);
1048 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1065 return GST_RTSP_ETIMEOUT;
1069 return GST_RTSP_ESYS;
1073 return GST_RTSP_EINTR;
1082 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1084 GString *str = NULL;
1086 str = g_string_new ("");
1088 switch (message->type) {
1089 case GST_RTSP_MESSAGE_REQUEST:
1090 /* create request string, add CSeq */
1091 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1093 gst_rtsp_method_as_text (message->type_data.request.method),
1094 message->type_data.request.uri, conn->cseq++);
1095 /* add session id if we have one */
1096 if (conn->session_id[0] != '\0') {
1097 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1100 /* add any authentication headers */
1101 add_auth_header (conn, message);
1103 case GST_RTSP_MESSAGE_RESPONSE:
1104 /* create response string */
1105 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1106 message->type_data.response.code, message->type_data.response.reason);
1108 case GST_RTSP_MESSAGE_DATA:
1110 guint8 data_header[4];
1112 /* prepare data header */
1113 data_header[0] = '$';
1114 data_header[1] = message->type_data.data.channel;
1115 data_header[2] = (message->body_size >> 8) & 0xff;
1116 data_header[3] = message->body_size & 0xff;
1118 /* create string with header and data */
1119 str = g_string_append_len (str, (gchar *) data_header, 4);
1121 g_string_append_len (str, (gchar *) message->body,
1122 message->body_size);
1126 g_string_free (str, TRUE);
1127 g_return_val_if_reached (NULL);
1131 /* append headers and body */
1132 if (message->type != GST_RTSP_MESSAGE_DATA) {
1133 /* add date header */
1134 add_date_header (message);
1136 /* append headers */
1137 gst_rtsp_message_append_headers (message, str);
1139 /* append Content-Length and body if needed */
1140 if (message->body != NULL && message->body_size > 0) {
1143 len = g_strdup_printf ("%d", message->body_size);
1144 g_string_append_printf (str, "%s: %s\r\n",
1145 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1147 /* header ends here */
1148 g_string_append (str, "\r\n");
1150 g_string_append_len (str, (gchar *) message->body,
1151 message->body_size);
1153 /* just end headers */
1154 g_string_append (str, "\r\n");
1162 * gst_rtsp_connection_send:
1163 * @conn: a #GstRTSPConnection
1164 * @message: the message to send
1165 * @timeout: a timeout value or #NULL
1167 * Attempt to send @message to the connected @conn, blocking up to
1168 * the specified @timeout. @timeout can be #NULL, in which case this function
1169 * might block forever.
1171 * This function can be cancelled with gst_rtsp_connection_flush().
1173 * Returns: #GST_RTSP_OK on success.
1176 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1179 GString *string = NULL;
1184 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1185 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1187 if (!(string = message_to_string (conn, message)))
1190 if (conn->tunneled) {
1191 str = g_base64_encode ((const guchar *) string->str, string->len);
1192 g_string_free (string, TRUE);
1197 g_string_free (string, FALSE);
1201 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1209 g_warning ("Wrong message");
1210 return GST_RTSP_EINVAL;
1215 parse_string (gchar * dest, gint size, gchar ** src)
1221 while (g_ascii_isspace (**src))
1224 while (!g_ascii_isspace (**src) && **src != '\0') {
1226 dest[idx++] = **src;
1234 parse_key (gchar * dest, gint size, gchar ** src)
1239 while (**src != ':' && **src != '\0') {
1241 dest[idx++] = **src;
1248 static GstRTSPResult
1249 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1252 gchar versionstr[20];
1257 bptr = (gchar *) buffer;
1259 parse_string (versionstr, sizeof (versionstr), &bptr);
1260 parse_string (codestr, sizeof (codestr), &bptr);
1261 code = atoi (codestr);
1263 while (g_ascii_isspace (*bptr))
1266 if (strcmp (versionstr, "RTSP/1.0") == 0)
1267 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1269 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1270 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1272 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1280 return GST_RTSP_EPARSE;
1284 static GstRTSPResult
1285 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1287 GstRTSPResult res = GST_RTSP_OK;
1288 gchar versionstr[20];
1289 gchar methodstr[20];
1292 GstRTSPMethod method;
1294 bptr = (gchar *) buffer;
1296 parse_string (methodstr, sizeof (methodstr), &bptr);
1297 method = gst_rtsp_find_method (methodstr);
1299 parse_string (urlstr, sizeof (urlstr), &bptr);
1300 if (*urlstr == '\0')
1301 res = GST_RTSP_EPARSE;
1303 parse_string (versionstr, sizeof (versionstr), &bptr);
1306 res = GST_RTSP_EPARSE;
1308 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1309 if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
1310 res = GST_RTSP_EPARSE;
1311 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1312 if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
1313 res = GST_RTSP_EPARSE;
1314 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1316 gst_rtsp_message_init_request (msg, method, urlstr);
1317 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1318 res = GST_RTSP_EPARSE;
1324 static GstRTSPResult
1325 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1329 bptr = (gchar *) buffer;
1332 parse_key (key, keysize, &bptr);
1337 while (g_ascii_isspace (*bptr))
1347 return GST_RTSP_EPARSE;
1351 /* parsing lines means reading a Key: Value pair */
1352 static GstRTSPResult
1353 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1358 GstRTSPHeaderField field;
1360 res = parse_key_value (buffer, key, sizeof (key), &value);
1361 if (res != GST_RTSP_OK)
1364 field = gst_rtsp_find_header_field (key);
1365 if (field != GST_RTSP_HDR_INVALID)
1366 gst_rtsp_message_add_header (msg, field, value);
1378 * GST_RTSP_OK when a complete message was read.
1379 * GST_RTSP_EEOF: when the socket is closed
1380 * GST_RTSP_EINTR: when more data is needed.
1381 * GST_RTSP_..: some other error occured.
1383 static GstRTSPResult
1384 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1385 GstRTSPConnection * conn)
1390 switch (builder->state) {
1392 builder->offset = 0;
1394 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1395 &builder->offset, 1);
1396 if (res != GST_RTSP_OK)
1399 /* we have 1 bytes now and we can see if this is a data message or
1401 if (builder->buffer[0] == '$') {
1402 /* data message, prepare for the header */
1403 builder->state = STATE_DATA_HEADER;
1406 builder->state = STATE_READ_LINES;
1409 case STATE_DATA_HEADER:
1412 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1413 &builder->offset, 4);
1414 if (res != GST_RTSP_OK)
1417 gst_rtsp_message_init_data (message, builder->buffer[1]);
1419 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1420 builder->body_data = g_malloc (builder->body_len + 1);
1421 builder->body_data[builder->body_len] = '\0';
1422 builder->offset = 0;
1423 builder->state = STATE_DATA_BODY;
1426 case STATE_DATA_BODY:
1429 read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1431 if (res != GST_RTSP_OK)
1434 /* we have the complete body now, store in the message adjusting the
1435 * length to include the traling '\0' */
1436 gst_rtsp_message_take_body (message,
1437 (guint8 *) builder->body_data, builder->body_len + 1);
1438 builder->body_data = NULL;
1439 builder->body_len = 0;
1441 builder->state = STATE_END;
1444 case STATE_READ_LINES:
1446 res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1447 sizeof (builder->buffer));
1448 if (res != GST_RTSP_OK)
1451 /* we have a regular response */
1452 if (builder->buffer[0] == '\r') {
1453 builder->buffer[0] = '\0';
1456 if (builder->buffer[0] == '\0') {
1459 /* empty line, end of message header */
1460 /* see if there is a Content-Length header */
1461 if (gst_rtsp_message_get_header (message,
1462 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1463 /* there is, prepare to read the body */
1464 builder->body_len = atol (hdrval);
1465 builder->body_data = g_malloc (builder->body_len + 1);
1466 builder->body_data[builder->body_len] = '\0';
1467 builder->offset = 0;
1468 builder->state = STATE_DATA_BODY;
1470 builder->state = STATE_END;
1475 /* we have a line */
1476 if (builder->line == 0) {
1477 /* first line, check for response status */
1478 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1479 res = parse_response_status (builder->buffer, message);
1481 res = parse_request_line (builder->buffer, message);
1484 /* else just parse the line */
1485 parse_line (builder->buffer, message);
1488 builder->offset = 0;
1495 if (message->type == GST_RTSP_MESSAGE_DATA) {
1496 /* data messages don't have headers */
1501 /* save session id in the connection for further use */
1502 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1503 &session_id, 0) == GST_RTSP_OK) {
1506 maxlen = sizeof (conn->session_id) - 1;
1507 /* the sessionid can have attributes marked with ;
1508 * Make sure we strip them */
1509 for (i = 0; session_id[i] != '\0'; i++) {
1510 if (session_id[i] == ';') {
1515 } while (g_ascii_isspace (session_id[i]));
1516 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1519 /* if we parsed something valid, configure */
1520 if ((to = atoi (&session_id[i + 9])) > 0)
1527 /* make sure to not overflow */
1528 strncpy (conn->session_id, session_id, maxlen);
1529 conn->session_id[maxlen] = '\0';
1535 res = GST_RTSP_ERROR;
1544 * gst_rtsp_connection_read:
1545 * @conn: a #GstRTSPConnection
1546 * @data: the data to read
1547 * @size: the size of @data
1548 * @timeout: a timeout value or #NULL
1550 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1551 * the specified @timeout. @timeout can be #NULL, in which case this function
1552 * might block forever.
1554 * This function can be cancelled with gst_rtsp_connection_flush().
1556 * Returns: #GST_RTSP_OK on success.
1559 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1567 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1568 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1569 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1576 /* configure timeout if any */
1577 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1579 gst_poll_set_controllable (conn->fdset, TRUE);
1580 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1581 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1584 res = read_bytes (conn->readfd->fd, data, &offset, size);
1585 if (res == GST_RTSP_EEOF)
1587 if (res == GST_RTSP_OK)
1589 if (res != GST_RTSP_EINTR)
1593 retval = gst_poll_wait (conn->fdset, to);
1594 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1596 /* check for timeout */
1598 goto select_timeout;
1606 gst_poll_set_controllable (conn->fdset, FALSE);
1613 return GST_RTSP_ESYS;
1617 return GST_RTSP_ETIMEOUT;
1621 return GST_RTSP_EINTR;
1625 return GST_RTSP_EEOF;
1635 * gst_rtsp_connection_receive:
1636 * @conn: a #GstRTSPConnection
1637 * @message: the message to read
1638 * @timeout: a timeout value or #NULL
1640 * Attempt to read into @message from the connected @conn, blocking up to
1641 * the specified @timeout. @timeout can be #NULL, in which case this function
1642 * might block forever.
1644 * This function can be cancelled with gst_rtsp_connection_flush().
1646 * Returns: #GST_RTSP_OK on success.
1649 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1653 GstRTSPBuilder builder = { 0 };
1657 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1658 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1659 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1661 /* configure timeout if any */
1662 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1664 gst_poll_set_controllable (conn->fdset, TRUE);
1665 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1666 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1669 res = build_next (&builder, message, conn);
1670 if (res == GST_RTSP_EEOF)
1672 if (res == GST_RTSP_OK)
1674 if (res != GST_RTSP_EINTR)
1678 retval = gst_poll_wait (conn->fdset, to);
1679 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1681 /* check for timeout */
1683 goto select_timeout;
1691 gst_poll_set_controllable (conn->fdset, FALSE);
1694 /* we have a message here */
1695 build_reset (&builder);
1702 res = GST_RTSP_ESYS;
1707 res = GST_RTSP_ETIMEOUT;
1712 res = GST_RTSP_EINTR;
1717 res = GST_RTSP_EEOF;
1723 build_reset (&builder);
1724 gst_rtsp_message_unset (message);
1730 * gst_rtsp_connection_close:
1731 * @conn: a #GstRTSPConnection
1733 * Close the connected @conn.
1735 * Returns: #GST_RTSP_OK on success.
1738 gst_rtsp_connection_close (GstRTSPConnection * conn)
1740 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1745 REMOVE_POLLFD (conn->fdset, &conn->fd0);
1746 REMOVE_POLLFD (conn->fdset, &conn->fd1);
1747 conn->writefd = NULL;
1748 conn->readfd = NULL;
1754 * gst_rtsp_connection_free:
1755 * @conn: a #GstRTSPConnection
1757 * Close and free @conn.
1759 * Returns: #GST_RTSP_OK on success.
1762 gst_rtsp_connection_free (GstRTSPConnection * conn)
1766 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1768 res = gst_rtsp_connection_close (conn);
1769 gst_poll_free (conn->fdset);
1770 g_timer_destroy (conn->timer);
1771 g_free (conn->username);
1772 g_free (conn->passwd);
1773 gst_rtsp_connection_clear_auth_params (conn);
1783 * gst_rtsp_connection_poll:
1784 * @conn: a #GstRTSPConnection
1785 * @events: a bitmask of #GstRTSPEvent flags to check
1786 * @revents: location for result flags
1787 * @timeout: a timeout
1789 * Wait up to the specified @timeout for the connection to become available for
1790 * at least one of the operations specified in @events. When the function returns
1791 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1794 * @timeout can be #NULL, in which case this function might block forever.
1796 * This function can be cancelled with gst_rtsp_connection_flush().
1798 * Returns: #GST_RTSP_OK on success.
1803 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1804 GstRTSPEvent * revents, GTimeVal * timeout)
1809 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1810 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
1811 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
1812 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1813 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1815 gst_poll_set_controllable (conn->fdset, TRUE);
1817 /* add fd to writer set when asked to */
1818 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
1819 events & GST_RTSP_EV_WRITE);
1821 /* add fd to reader set when asked to */
1822 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
1824 /* configure timeout if any */
1825 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1828 retval = gst_poll_wait (conn->fdset, to);
1829 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1832 goto select_timeout;
1842 if (events & GST_RTSP_EV_READ) {
1843 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
1844 *revents |= GST_RTSP_EV_READ;
1846 if (events & GST_RTSP_EV_WRITE) {
1847 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
1848 *revents |= GST_RTSP_EV_WRITE;
1855 return GST_RTSP_ETIMEOUT;
1859 return GST_RTSP_ESYS;
1863 return GST_RTSP_EINTR;
1868 * gst_rtsp_connection_next_timeout:
1869 * @conn: a #GstRTSPConnection
1870 * @timeout: a timeout
1872 * Calculate the next timeout for @conn, storing the result in @timeout.
1874 * Returns: #GST_RTSP_OK.
1877 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
1883 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1884 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
1886 elapsed = g_timer_elapsed (conn->timer, &usec);
1887 if (elapsed >= conn->timeout) {
1891 sec = conn->timeout - elapsed;
1894 timeout->tv_sec = sec;
1895 timeout->tv_usec = usec;
1901 * gst_rtsp_connection_reset_timeout:
1902 * @conn: a #GstRTSPConnection
1904 * Reset the timeout of @conn.
1906 * Returns: #GST_RTSP_OK.
1909 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
1911 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1913 g_timer_start (conn->timer);
1919 * gst_rtsp_connection_flush:
1920 * @conn: a #GstRTSPConnection
1921 * @flush: start or stop the flush
1923 * Start or stop the flushing action on @conn. When flushing, all current
1924 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
1925 * is set to non-flushing mode again.
1927 * Returns: #GST_RTSP_OK.
1930 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
1932 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1934 gst_poll_set_flushing (conn->fdset, flush);
1940 * gst_rtsp_connection_set_auth:
1941 * @conn: a #GstRTSPConnection
1942 * @method: authentication method
1944 * @pass: the password
1946 * Configure @conn for authentication mode @method with @user and @pass as the
1947 * user and password respectively.
1949 * Returns: #GST_RTSP_OK.
1952 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
1953 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
1955 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1957 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
1958 || g_strrstr (user, ":") != NULL))
1959 return GST_RTSP_EINVAL;
1961 /* Make sure the username and passwd are being set for authentication */
1962 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
1963 return GST_RTSP_EINVAL;
1965 /* ":" chars are not allowed in usernames for basic auth */
1966 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
1967 return GST_RTSP_EINVAL;
1969 g_free (conn->username);
1970 g_free (conn->passwd);
1972 conn->auth_method = method;
1973 conn->username = g_strdup (user);
1974 conn->passwd = g_strdup (pass);
1981 * @key: ASCII string to hash
1983 * Hashes @key in a case-insensitive manner.
1985 * Returns: the hash code.
1988 str_case_hash (gconstpointer key)
1990 const char *p = key;
1991 guint h = g_ascii_toupper (*p);
1994 for (p += 1; *p != '\0'; p++)
1995 h = (h << 5) - h + g_ascii_toupper (*p);
2002 * @v1: an ASCII string
2003 * @v2: another ASCII string
2005 * Compares @v1 and @v2 in a case-insensitive manner
2007 * Returns: %TRUE if they are equal (modulo case)
2010 str_case_equal (gconstpointer v1, gconstpointer v2)
2012 const char *string1 = v1;
2013 const char *string2 = v2;
2015 return g_ascii_strcasecmp (string1, string2) == 0;
2019 * gst_rtsp_connection_set_auth_param:
2020 * @conn: a #GstRTSPConnection
2021 * @param: authentication directive
2024 * Setup @conn with authentication directives. This is not necesary for
2025 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2026 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2027 * in the WWW-Authenticate response header and can include realm, domain,
2028 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2033 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2034 const gchar * param, const gchar * value)
2036 g_return_if_fail (conn != NULL);
2037 g_return_if_fail (param != NULL);
2039 if (conn->auth_params == NULL) {
2041 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2043 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2047 * gst_rtsp_connection_clear_auth_params:
2048 * @conn: a #GstRTSPConnection
2050 * Clear the list of authentication directives stored in @conn.
2055 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2057 g_return_if_fail (conn != NULL);
2059 if (conn->auth_params != NULL) {
2060 g_hash_table_destroy (conn->auth_params);
2061 conn->auth_params = NULL;
2065 static GstRTSPResult
2066 set_qos_dscp (gint fd, guint qos_dscp)
2071 struct sockaddr_in6 sa_in6;
2072 struct sockaddr_storage sa_stor;
2074 socklen_t slen = sizeof (sa);
2081 if (getsockname (fd, &sa.sa, &slen) < 0)
2082 goto no_getsockname;
2084 af = sa.sa.sa_family;
2086 /* if this is an IPv4-mapped address then do IPv4 QoS */
2087 if (af == AF_INET6) {
2088 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2092 /* extract and shift 6 bits of the DSCP */
2093 tos = (qos_dscp & 0x3f) << 2;
2097 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2102 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2116 return GST_RTSP_ESYS;
2121 return GST_RTSP_ERROR;
2126 * gst_rtsp_connection_set_qos_dscp:
2127 * @conn: a #GstRTSPConnection
2128 * @qos_dscp: DSCP value
2130 * Configure @conn to use the specified DSCP value.
2132 * Returns: #GST_RTSP_OK on success.
2137 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2141 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2142 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2143 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2145 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2146 if (res == GST_RTSP_OK)
2147 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2154 * gst_rtsp_connection_get_url:
2155 * @conn: a #GstRTSPConnection
2157 * Retrieve the URL of the other end of @conn.
2159 * Returns: The URL. This value remains valid until the
2160 * connection is closed.
2165 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2167 g_return_val_if_fail (conn != NULL, NULL);
2173 * gst_rtsp_connection_get_ip:
2174 * @conn: a #GstRTSPConnection
2176 * Retrieve the IP address of the other end of @conn.
2178 * Returns: The IP address as a string. this value remains valid until the
2179 * connection is closed.
2184 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2186 g_return_val_if_fail (conn != NULL, NULL);
2192 * gst_rtsp_connection_set_tunneled:
2193 * @conn: a #GstRTSPConnection
2194 * @tunneled: the new state
2196 * Set the HTTP tunneling state of the connection. This must be configured before
2197 * the @conn is connected.
2202 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2204 g_return_if_fail (conn != NULL);
2205 g_return_if_fail (conn->readfd == NULL);
2206 g_return_if_fail (conn->writefd == NULL);
2208 conn->tunneled = tunneled;
2212 * gst_rtsp_connection_is_tunneled:
2213 * @conn: a #GstRTSPConnection
2215 * Get the tunneling state of the connection.
2217 * Returns: if @conn is using HTTP tunneling.
2222 gst_rtsp_connection_is_tunneled (GstRTSPConnection * conn)
2224 g_return_val_if_fail (conn != NULL, FALSE);
2226 return conn->tunneled;
2230 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2231 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2239 /* async functions */
2240 struct _GstRTSPWatch
2244 GstRTSPConnection *conn;
2246 GstRTSPBuilder builder;
2247 GstRTSPMessage message;
2251 gboolean write_added;
2253 /* queued message for transmission */
2260 GstRTSPWatchFuncs funcs;
2263 GDestroyNotify notify;
2267 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2269 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2271 *timeout = (watch->conn->timeout * 1000);
2277 gst_rtsp_source_check (GSource * source)
2279 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2281 if (watch->readfd.revents & READ_COND)
2284 if (watch->writefd.revents & WRITE_COND)
2291 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2294 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2297 /* first read as much as we can */
2298 if (watch->readfd.revents & READ_COND) {
2300 res = build_next (&watch->builder, &watch->message, watch->conn);
2301 if (res == GST_RTSP_EINTR)
2303 if (res == GST_RTSP_EEOF)
2305 if (res != GST_RTSP_OK)
2308 if (watch->funcs.message_received)
2309 watch->funcs.message_received (watch, &watch->message,
2312 gst_rtsp_message_unset (&watch->message);
2313 build_reset (&watch->builder);
2317 if (watch->writefd.revents & WRITE_COND) {
2319 if (watch->write_data == NULL) {
2322 if (!watch->messages)
2325 /* no data, get a new message from the queue */
2326 data = watch->messages->data;
2327 watch->messages = g_list_delete_link (watch->messages, watch->messages);
2329 watch->write_off = 0;
2330 watch->write_len = data->str->len;
2331 watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2332 watch->write_cseq = data->cseq;
2334 g_slice_free (GstRTSPRec, data);
2337 res = write_bytes (watch->writefd.fd, watch->write_data,
2338 &watch->write_off, watch->write_len);
2339 if (res == GST_RTSP_EINTR)
2341 if (res != GST_RTSP_OK)
2344 if (watch->funcs.message_sent)
2345 watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2348 if (watch->messages == NULL && watch->write_added) {
2349 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2350 watch->write_added = FALSE;
2351 watch->writefd.revents = 0;
2353 g_free (watch->write_data);
2354 watch->write_data = NULL;
2363 if (watch->funcs.closed)
2364 watch->funcs.closed (watch, watch->user_data);
2369 if (watch->funcs.error)
2370 watch->funcs.error (watch, res, watch->user_data);
2376 gst_rtsp_source_finalize (GSource * source)
2378 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2381 build_reset (&watch->builder);
2383 for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2384 GstRTSPRec *data = walk->data;
2386 g_string_free (data->str, TRUE);
2387 g_slice_free (GstRTSPRec, data);
2389 g_list_free (watch->messages);
2390 g_free (watch->write_data);
2393 watch->notify (watch->user_data);
2396 static GSourceFuncs gst_rtsp_source_funcs = {
2397 gst_rtsp_source_prepare,
2398 gst_rtsp_source_check,
2399 gst_rtsp_source_dispatch,
2400 gst_rtsp_source_finalize
2404 * gst_rtsp_watch_new:
2405 * @conn: a #GstRTSPConnection
2406 * @funcs: watch functions
2407 * @user_data: user data to pass to @funcs
2408 * @notify: notify when @user_data is not referenced anymore
2410 * Create a watch object for @conn. The functions provided in @funcs will be
2411 * called with @user_data when activity happened on the watch.
2413 * The new watch is usually created so that it can be attached to a
2414 * maincontext with gst_rtsp_watch_attach().
2416 * @conn must exist for the entire lifetime of the watch.
2418 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2419 * communication. Free with gst_rtsp_watch_unref () after usage.
2424 gst_rtsp_watch_new (GstRTSPConnection * conn,
2425 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2427 GstRTSPWatch *result;
2429 g_return_val_if_fail (conn != NULL, NULL);
2430 g_return_val_if_fail (funcs != NULL, NULL);
2431 g_return_val_if_fail (conn->readfd != NULL, NULL);
2432 g_return_val_if_fail (conn->writefd != NULL, NULL);
2434 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2435 sizeof (GstRTSPWatch));
2437 result->conn = conn;
2438 result->builder.state = STATE_START;
2440 result->readfd.fd = conn->readfd->fd;
2441 result->readfd.events = READ_COND;
2442 result->readfd.revents = 0;
2444 result->writefd.fd = conn->writefd->fd;
2445 result->writefd.events = WRITE_COND;
2446 result->writefd.revents = 0;
2447 result->write_added = FALSE;
2449 result->funcs = *funcs;
2450 result->user_data = user_data;
2451 result->notify = notify;
2453 /* only add the read fd, the write fd is only added when we have data
2455 g_source_add_poll ((GSource *) result, &result->readfd);
2461 * gst_rtsp_watch_attach:
2462 * @watch: a #GstRTSPWatch
2463 * @context: a GMainContext (if NULL, the default context will be used)
2465 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2467 * Returns: the ID (greater than 0) for the watch within the GMainContext.
2472 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2474 g_return_val_if_fail (watch != NULL, 0);
2476 return g_source_attach ((GSource *) watch, context);
2480 * gst_rtsp_watch_unref:
2481 * @watch: a #GstRTSPWatch
2483 * Decreases the reference count of @watch by one. If the resulting reference
2484 * count is zero the watch and associated memory will be destroyed.
2489 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2491 g_return_if_fail (watch != NULL);
2493 g_source_unref ((GSource *) watch);
2497 * gst_rtsp_watch_queue_message:
2498 * @watch: a #GstRTSPWatch
2499 * @message: a #GstRTSPMessage
2501 * Queue a @message for transmission in @watch. The contents of this
2502 * message will be serialized and transmitted when the connection of the
2503 * watch becomes writable.
2505 * The return value of this function will be returned as the cseq argument in
2506 * the message_sent callback.
2508 * Returns: the sequence number of the message or -1 if the cseq could not be
2514 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2520 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2521 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2523 /* get the cseq from the message, when we finish writing this message on the
2524 * socket we will have to pass the cseq to the callback. */
2525 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2526 0) == GST_RTSP_OK) {
2527 cseq = atoi (header);
2532 /* make a record with the message as a string ans cseq */
2533 data = g_slice_new (GstRTSPRec);
2534 data->str = message_to_string (watch->conn, message);
2537 /* add the record to a queue */
2538 watch->messages = g_list_append (watch->messages, data);
2540 /* make sure the main context will now also check for writability on the
2542 if (!watch->write_added) {
2543 g_source_add_poll ((GSource *) watch, &watch->writefd);
2544 watch->write_added = TRUE;