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"
109 static GstRTSPResult read_line (gint fd, guint8 * buffer, guint * idx,
110 guint size, DecodeCtx * ctxp);
111 static GstRTSPResult parse_key_value (guint8 * buffer, gchar * key,
112 guint keysize, gchar ** value);
113 static void parse_string (gchar * dest, gint size, gchar ** src);
116 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
117 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
118 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
119 #define CLOSE_SOCKET(sock) closesocket (sock)
120 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
121 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
122 /* According to Microsoft's connect() documentation this one returns
123 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
124 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
126 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
127 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
128 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
129 #define CLOSE_SOCKET(sock) close (sock)
130 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
131 #define ERRNO_IS_EINTR (errno == EINTR)
132 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
135 #define ADD_POLLFD(fdset, pfd, fd) \
138 gst_poll_add_fd (fdset, pfd); \
141 #define REMOVE_POLLFD(fdset, pfd) \
143 if ((pfd)->fd != -1) { \
144 GST_DEBUG ("remove fd %d", (pfd)->fd); \
145 gst_poll_remove_fd (fdset, pfd); \
146 CLOSE_SOCKET ((pfd)->fd); \
156 TUNNEL_STATE_COMPLETE
157 } GstRTSPTunnelState;
159 #define TUNNELID_LEN 24
161 struct _GstRTSPConnection
164 /* URL for the connection */
167 /* connection state */
174 gchar tunnelid[TUNNELID_LEN];
176 GstRTSPTunnelState tstate;
182 gint cseq; /* sequence number */
183 gchar session_id[512]; /* session id */
184 gint timeout; /* session timeout in seconds */
185 GTimer *timer; /* timeout timer */
188 GstRTSPAuthMethod auth_method;
191 GHashTable *auth_params;
199 inet_aton (const char *c, struct in_addr *paddr)
201 /* note that inet_addr is deprecated on unix because
202 * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
204 paddr->s_addr = inet_addr (c);
206 if (paddr->s_addr == INADDR_NONE)
223 /* a structure for constructing RTSPMessages */
236 build_reset (GstRTSPBuilder * builder)
238 g_free (builder->body_data);
239 memset (builder, 0, sizeof (builder));
243 * gst_rtsp_connection_create:
244 * @url: a #GstRTSPUrl
245 * @conn: storage for a #GstRTSPConnection
247 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
248 * The connection will not yet attempt to connect to @url, use
249 * gst_rtsp_connection_connect().
251 * A copy of @url will be made.
253 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
256 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
258 GstRTSPConnection *newconn;
264 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
267 error = WSAStartup (0x0202, &w);
272 if (w.wVersion != 0x0202)
276 newconn = g_new0 (GstRTSPConnection, 1);
278 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
281 newconn->url = gst_rtsp_url_copy (url);
282 newconn->fd0.fd = -1;
283 newconn->fd1.fd = -1;
284 newconn->timer = g_timer_new ();
285 newconn->timeout = 60;
288 newconn->auth_method = GST_RTSP_AUTH_NONE;
289 newconn->username = NULL;
290 newconn->passwd = NULL;
291 newconn->auth_params = NULL;
301 g_warning ("Error %d on WSAStartup", error);
302 return GST_RTSP_EWSASTART;
306 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
309 return GST_RTSP_EWSAVERSION;
318 return GST_RTSP_ESYS;
323 * gst_rtsp_connection_accept:
325 * @conn: storage for a #GstRTSPConnection
327 * Accept a new connection on @sock and create a new #GstRTSPConnection for
328 * handling communication on new socket.
330 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
335 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
338 unsigned int address_len;
339 GstRTSPConnection *newconn = NULL;
340 struct sockaddr_in address;
346 address_len = sizeof (address);
347 memset (&address, 0, address_len);
350 fd = accept (sock, (struct sockaddr *) &address, &address_len);
352 fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
353 #endif /* G_OS_WIN32 */
357 /* set to non-blocking mode so that we can cancel the communication */
359 fcntl (fd, F_SETFL, O_NONBLOCK);
361 ioctlsocket (fd, FIONBIO, &flags);
362 #endif /* G_OS_WIN32 */
364 /* create a url for the client address */
365 url = g_new0 (GstRTSPUrl, 1);
366 url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
367 url->port = address.sin_port;
369 /* now create the connection object */
370 gst_rtsp_connection_create (url, &newconn);
371 gst_rtsp_url_free (url);
373 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
375 /* both read and write initially */
376 newconn->readfd = &newconn->fd0;
377 newconn->writefd = &newconn->fd0;
386 return GST_RTSP_ESYS;
391 do_resolve (const gchar * host)
393 struct hostent *hostinfo;
397 struct in_addr *addrp;
400 gchar ipbuf[INET_ADDRSTRLEN];
401 #endif /* G_OS_WIN32 */
405 /* first check if it already is an IP address */
406 if (inet_aton (host, &addr)) {
409 hostinfo = gethostbyname (host);
411 goto not_resolved; /* h_errno set */
413 if (hostinfo->h_addrtype != AF_INET)
414 goto not_ip; /* host not an IP host */
416 addrp = (struct in_addr *) hostinfo->h_addr_list[0];
417 /* this is not threadsafe */
418 ip = inet_ntoa (*addrp);
420 addrs = hostinfo->h_addr_list;
421 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
423 #endif /* G_OS_WIN32 */
425 return g_strdup (ip);
430 GST_ERROR ("could not resolve %s", host);
435 GST_ERROR ("not an IP address");
441 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
442 GstPoll * fdset, GTimeVal * timeout)
445 struct sockaddr_in sa_in;
448 unsigned long flags = 1;
449 #endif /* G_OS_WIN32 */
453 memset (&sa_in, 0, sizeof (sa_in));
454 sa_in.sin_family = AF_INET; /* network socket */
455 sa_in.sin_port = htons (port); /* on port */
456 sa_in.sin_addr.s_addr = inet_addr (ip); /* on host ip */
458 fd = socket (AF_INET, SOCK_STREAM, 0);
462 /* set to non-blocking mode so that we can cancel the connect */
464 fcntl (fd, F_SETFL, O_NONBLOCK);
466 ioctlsocket (fd, FIONBIO, &flags);
467 #endif /* G_OS_WIN32 */
469 /* add the socket to our fdset */
470 ADD_POLLFD (fdset, fdout, fd);
472 /* we are going to connect ASYNC now */
473 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
476 if (!ERRNO_IS_EINPROGRESS)
479 /* wait for connect to complete up to the specified timeout or until we got
481 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
483 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
486 retval = gst_poll_wait (fdset, to);
487 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
491 else if (retval == -1)
494 /* we can still have an error connecting on windows */
495 if (gst_poll_fd_has_error (fdset, fdout)) {
496 socklen_t len = sizeof (errno);
498 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
500 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
505 gst_poll_fd_ignored (fdset, fdout);
513 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
514 return GST_RTSP_ESYS;
518 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
519 REMOVE_POLLFD (fdset, fdout);
520 return GST_RTSP_ESYS;
524 GST_ERROR ("timeout");
525 REMOVE_POLLFD (fdset, fdout);
526 return GST_RTSP_ETIMEOUT;
531 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
541 gchar codestr[4], *resultstr;
545 /* create a random sessionid */
546 for (i = 0; i < TUNNELID_LEN; i++)
547 conn->tunnelid[i] = g_random_int_range ('a', 'z');
548 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
553 str = g_strdup_printf ("GET %s%s%s HTTP/1.0\r\n"
554 "x-sessioncookie: %s\r\n"
555 "Accept: application/x-rtsp-tunnelled\r\n"
556 "Pragma: no-cache\r\n"
557 "Cache-Control: no-cache\r\n" "\r\n",
558 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
561 /* we start by writing to this fd */
562 conn->writefd = &conn->fd0;
564 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
566 if (res != GST_RTSP_OK)
569 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
570 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
572 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
580 res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer), NULL);
581 if (res == GST_RTSP_EEOF)
583 if (res == GST_RTSP_OK)
585 if (res != GST_RTSP_EINTR)
589 retval = gst_poll_wait (conn->fdset, to);
590 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
592 /* check for timeout */
604 /* check for last line */
605 if (buffer[0] == '\r')
607 if (buffer[0] == '\0')
611 /* first line, parse response */
612 gchar versionstr[20];
615 bptr = (gchar *) buffer;
617 parse_string (versionstr, sizeof (versionstr), &bptr);
618 parse_string (codestr, sizeof (codestr), &bptr);
619 code = atoi (codestr);
621 while (g_ascii_isspace (*bptr))
632 /* other lines, parse key/value */
633 res = parse_key_value (buffer, key, sizeof (key), &value);
634 if (res == GST_RTSP_OK) {
635 /* we got a new ip address */
636 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
638 conn->ip = g_strdup (value);
645 if (!(ip = do_resolve (conn->ip)))
648 /* get the port from the url */
649 gst_rtsp_url_get_port (conn->url, &port);
651 /* connect to the host/port */
652 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
654 if (res != GST_RTSP_OK)
657 /* this is now our writing socket */
658 conn->writefd = &conn->fd1;
661 str = g_strdup_printf ("POST %s%s%s HTTP/1.0\r\n"
662 "x-sessioncookie: %s\r\n"
663 "Content-Type: application/x-rtsp-tunnelled\r\n"
664 "Pragma: no-cache\r\n"
665 "Cache-Control: no-cache\r\n"
666 "Content-Length: 32767\r\n"
667 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
669 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
672 /* we start by writing to this fd */
673 conn->writefd = &conn->fd1;
675 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
677 if (res != GST_RTSP_OK)
685 GST_ERROR ("write failed (%d)", res);
690 return GST_RTSP_EEOF;
698 return GST_RTSP_ETIMEOUT;
702 return GST_RTSP_ESYS;
706 return GST_RTSP_EINTR;
710 GST_ERROR ("got failure response %d %s", code, resultstr);
711 return GST_RTSP_ERROR;
715 GST_ERROR ("could not resolve %s", conn->ip);
716 return GST_RTSP_ENET;
720 GST_ERROR ("failed to connect");
726 * gst_rtsp_connection_connect:
727 * @conn: a #GstRTSPConnection
728 * @timeout: a #GTimeVal timeout
730 * Attempt to connect to the url of @conn made with
731 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
732 * forever. If @timeout contains a valid timeout, this function will return
733 * #GST_RTSP_ETIMEOUT after the timeout expired.
735 * This function can be cancelled with gst_rtsp_connection_flush().
737 * Returns: #GST_RTSP_OK when a connection could be made.
740 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
747 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
748 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
749 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
753 if (!(ip = do_resolve (url->host)))
756 /* get the port from the url */
757 gst_rtsp_url_get_port (url, &port);
759 /* connect to the host/port */
760 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
761 if (res != GST_RTSP_OK)
767 /* this is our read URL */
768 conn->readfd = &conn->fd0;
770 if (conn->tunneled) {
771 res = setup_tunneling (conn, timeout);
772 if (res != GST_RTSP_OK)
773 goto tunneling_failed;
775 conn->writefd = &conn->fd0;
782 GST_ERROR ("could not resolve %s", url->host);
783 return GST_RTSP_ENET;
787 GST_ERROR ("failed to connect");
793 GST_ERROR ("failed to setup tunneling");
799 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
801 static const char hexdigits[] = "0123456789abcdef";
804 for (i = 0; i < 16; i++) {
805 string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
806 string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
812 auth_digest_compute_hex_urp (const gchar * username,
813 const gchar * realm, const gchar * password, gchar hex_urp[33])
815 struct MD5Context md5_context;
816 unsigned char digest[16];
818 MD5Init (&md5_context);
819 MD5Update (&md5_context, username, strlen (username));
820 MD5Update (&md5_context, ":", 1);
821 MD5Update (&md5_context, realm, strlen (realm));
822 MD5Update (&md5_context, ":", 1);
823 MD5Update (&md5_context, password, strlen (password));
824 MD5Final (digest, &md5_context);
825 md5_digest_to_hex_string (digest, hex_urp);
829 auth_digest_compute_response (const gchar * method,
830 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
834 struct MD5Context md5_context;
835 unsigned char digest[16];
838 MD5Init (&md5_context);
839 MD5Update (&md5_context, method, strlen (method));
840 MD5Update (&md5_context, ":", 1);
841 MD5Update (&md5_context, uri, strlen (uri));
842 MD5Final (digest, &md5_context);
843 md5_digest_to_hex_string (digest, hex_a2);
846 MD5Init (&md5_context);
847 MD5Update (&md5_context, hex_a1, strlen (hex_a1));
848 MD5Update (&md5_context, ":", 1);
849 MD5Update (&md5_context, nonce, strlen (nonce));
850 MD5Update (&md5_context, ":", 1);
852 MD5Update (&md5_context, hex_a2, 32);
853 MD5Final (digest, &md5_context);
854 md5_digest_to_hex_string (digest, response);
858 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
860 switch (conn->auth_method) {
861 case GST_RTSP_AUTH_BASIC:{
866 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
867 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
868 auth_string = g_strdup_printf ("Basic %s", user_pass64);
870 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
874 g_free (user_pass64);
877 case GST_RTSP_AUTH_DIGEST:{
878 gchar response[33], hex_urp[33];
879 gchar *auth_string, *auth_string2;
886 /* we need to have some params set */
887 if (conn->auth_params == NULL)
890 /* we need the realm and nonce */
891 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
892 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
893 if (realm == NULL || nonce == NULL)
896 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
899 method = gst_rtsp_method_as_text (message->type_data.request.method);
900 uri = message->type_data.request.uri;
902 /* Assume no qop, algorithm=md5, stale=false */
903 /* For algorithm MD5, a1 = urp. */
904 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
905 auth_string = g_strdup_printf ("Digest username=\"%s\", "
906 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
907 conn->username, realm, nonce, uri, response);
909 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
911 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
913 g_free (auth_string);
914 auth_string = auth_string2;
916 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
927 gen_date_string (gchar * date_string, guint len)
935 g_get_current_time (&tv);
936 t = (time_t) tv.tv_sec;
939 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
941 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
946 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
951 return GST_RTSP_ERROR;
958 r = WRITE_SOCKET (fd, &buffer[*idx], left);
960 return GST_RTSP_EINTR;
963 return GST_RTSP_EINTR;
965 return GST_RTSP_ESYS;
975 fill_bytes (gint fd, guint8 * buffer, guint size, DecodeCtx * ctx)
983 while (size > 0 && ctx->cout < ctx->coutl) {
984 /* we have some leftover bytes */
985 *buffer++ = ctx->out[ctx->cout];
990 /* nothing in the buffer */
994 /* try to read more bytes */
995 r = READ_SOCKET (fd, &ctx->in[ctx->cin], 4 - ctx->cin);
1003 if (ctx->cin == 4) {
1004 r = g_base64_decode_step ((const gchar *) ctx->in, 4,
1005 (guchar *) ctx->out, &ctx->state, &ctx->save);
1012 out = READ_SOCKET (fd, buffer, size);
1018 static GstRTSPResult
1019 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1024 return GST_RTSP_ERROR;
1031 r = fill_bytes (fd, &buffer[*idx], left, ctx);
1033 return GST_RTSP_EEOF;
1035 if (ERRNO_IS_EAGAIN)
1036 return GST_RTSP_EINTR;
1037 if (!ERRNO_IS_EINTR)
1038 return GST_RTSP_ESYS;
1047 static GstRTSPResult
1048 read_line (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1054 r = fill_bytes (fd, &c, 1, ctx);
1056 return GST_RTSP_EEOF;
1058 if (ERRNO_IS_EAGAIN)
1059 return GST_RTSP_EINTR;
1060 if (!ERRNO_IS_EINTR)
1061 return GST_RTSP_ESYS;
1063 if (c == '\n') /* end on \n */
1065 if (c == '\r') /* ignore \r */
1068 if (*idx < size - 1)
1069 buffer[(*idx)++] = c;
1072 buffer[*idx] = '\0';
1078 * gst_rtsp_connection_write:
1079 * @conn: a #GstRTSPConnection
1080 * @data: the data to write
1081 * @size: the size of @data
1082 * @timeout: a timeout value or #NULL
1084 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1085 * the specified @timeout. @timeout can be #NULL, in which case this function
1086 * might block forever.
1088 * This function can be cancelled with gst_rtsp_connection_flush().
1090 * Returns: #GST_RTSP_OK on success.
1093 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1094 guint size, GTimeVal * timeout)
1101 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1102 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1103 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1105 gst_poll_set_controllable (conn->fdset, TRUE);
1106 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1107 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1108 /* clear all previous poll results */
1109 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1110 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1112 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1118 res = write_bytes (conn->writefd->fd, data, &offset, size);
1119 if (res == GST_RTSP_OK)
1121 if (res != GST_RTSP_EINTR)
1124 /* not all is written, wait until we can write more */
1126 retval = gst_poll_wait (conn->fdset, to);
1127 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1144 return GST_RTSP_ETIMEOUT;
1148 return GST_RTSP_ESYS;
1152 return GST_RTSP_EINTR;
1161 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1163 GString *str = NULL;
1165 str = g_string_new ("");
1167 switch (message->type) {
1168 case GST_RTSP_MESSAGE_REQUEST:
1169 /* create request string, add CSeq */
1170 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1172 gst_rtsp_method_as_text (message->type_data.request.method),
1173 message->type_data.request.uri, conn->cseq++);
1174 /* add session id if we have one */
1175 if (conn->session_id[0] != '\0') {
1176 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1179 /* add any authentication headers */
1180 add_auth_header (conn, message);
1182 case GST_RTSP_MESSAGE_RESPONSE:
1183 /* create response string */
1184 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1185 message->type_data.response.code, message->type_data.response.reason);
1187 case GST_RTSP_MESSAGE_DATA:
1189 guint8 data_header[4];
1191 /* prepare data header */
1192 data_header[0] = '$';
1193 data_header[1] = message->type_data.data.channel;
1194 data_header[2] = (message->body_size >> 8) & 0xff;
1195 data_header[3] = message->body_size & 0xff;
1197 /* create string with header and data */
1198 str = g_string_append_len (str, (gchar *) data_header, 4);
1200 g_string_append_len (str, (gchar *) message->body,
1201 message->body_size);
1205 g_string_free (str, TRUE);
1206 g_return_val_if_reached (NULL);
1210 /* append headers and body */
1211 if (message->type != GST_RTSP_MESSAGE_DATA) {
1212 gchar date_string[100];
1214 gen_date_string (date_string, sizeof (date_string));
1216 /* add date header */
1217 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1219 /* append headers */
1220 gst_rtsp_message_append_headers (message, str);
1222 /* append Content-Length and body if needed */
1223 if (message->body != NULL && message->body_size > 0) {
1226 len = g_strdup_printf ("%d", message->body_size);
1227 g_string_append_printf (str, "%s: %s\r\n",
1228 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1230 /* header ends here */
1231 g_string_append (str, "\r\n");
1233 g_string_append_len (str, (gchar *) message->body,
1234 message->body_size);
1236 /* just end headers */
1237 g_string_append (str, "\r\n");
1245 * gst_rtsp_connection_send:
1246 * @conn: a #GstRTSPConnection
1247 * @message: the message to send
1248 * @timeout: a timeout value or #NULL
1250 * Attempt to send @message to the connected @conn, blocking up to
1251 * the specified @timeout. @timeout can be #NULL, in which case this function
1252 * might block forever.
1254 * This function can be cancelled with gst_rtsp_connection_flush().
1256 * Returns: #GST_RTSP_OK on success.
1259 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1262 GString *string = NULL;
1267 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1268 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1270 if (!(string = message_to_string (conn, message)))
1273 if (conn->tunneled) {
1274 str = g_base64_encode ((const guchar *) string->str, string->len);
1275 g_string_free (string, TRUE);
1280 g_string_free (string, FALSE);
1284 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1292 g_warning ("Wrong message");
1293 return GST_RTSP_EINVAL;
1298 parse_string (gchar * dest, gint size, gchar ** src)
1304 while (g_ascii_isspace (**src))
1307 while (!g_ascii_isspace (**src) && **src != '\0') {
1309 dest[idx++] = **src;
1317 parse_key (gchar * dest, gint size, gchar ** src)
1322 while (**src != ':' && **src != '\0') {
1324 dest[idx++] = **src;
1331 static GstRTSPResult
1332 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1335 gchar versionstr[20];
1340 bptr = (gchar *) buffer;
1342 parse_string (versionstr, sizeof (versionstr), &bptr);
1343 parse_string (codestr, sizeof (codestr), &bptr);
1344 code = atoi (codestr);
1346 while (g_ascii_isspace (*bptr))
1349 if (strcmp (versionstr, "RTSP/1.0") == 0)
1350 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1352 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1353 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1355 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1363 return GST_RTSP_EPARSE;
1367 static GstRTSPResult
1368 parse_request_line (GstRTSPConnection * conn, guint8 * buffer,
1369 GstRTSPMessage * msg)
1371 GstRTSPResult res = GST_RTSP_OK;
1372 gchar versionstr[20];
1373 gchar methodstr[20];
1376 GstRTSPMethod method;
1377 GstRTSPTunnelState tstate = TUNNEL_STATE_NONE;
1379 bptr = (gchar *) buffer;
1381 parse_string (methodstr, sizeof (methodstr), &bptr);
1382 method = gst_rtsp_find_method (methodstr);
1383 if (method == GST_RTSP_INVALID) {
1384 /* a tunnel request is allowed when we don't have one yet */
1385 if (conn->tstate != TUNNEL_STATE_NONE)
1386 goto invalid_method;
1387 /* we need GET or POST for a valid tunnel request */
1388 if (!strcmp (methodstr, "GET"))
1389 tstate = TUNNEL_STATE_GET;
1390 else if (!strcmp (methodstr, "POST"))
1391 tstate = TUNNEL_STATE_POST;
1393 goto invalid_method;
1396 parse_string (urlstr, sizeof (urlstr), &bptr);
1397 if (*urlstr == '\0')
1400 parse_string (versionstr, sizeof (versionstr), &bptr);
1403 goto invalid_version;
1405 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1406 res = gst_rtsp_message_init_request (msg, method, urlstr);
1407 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1408 res = gst_rtsp_message_init_request (msg, method, urlstr);
1409 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1410 } else if (strcmp (versionstr, "HTTP/1.0") == 0) {
1411 /* tunnel request, we need a tunnel method */
1412 if (tstate == TUNNEL_STATE_NONE) {
1413 res = GST_RTSP_EPARSE;
1415 conn->tstate = tstate;
1418 res = GST_RTSP_EPARSE;
1426 GST_ERROR ("invalid method %s", methodstr);
1427 return GST_RTSP_EPARSE;
1431 GST_ERROR ("invalid url %s", urlstr);
1432 return GST_RTSP_EPARSE;
1436 GST_ERROR ("invalid version");
1437 return GST_RTSP_EPARSE;
1441 static GstRTSPResult
1442 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1446 bptr = (gchar *) buffer;
1449 parse_key (key, keysize, &bptr);
1454 while (g_ascii_isspace (*bptr))
1464 return GST_RTSP_EPARSE;
1468 /* parsing lines means reading a Key: Value pair */
1469 static GstRTSPResult
1470 parse_line (GstRTSPConnection * conn, guint8 * buffer, GstRTSPMessage * msg)
1475 GstRTSPHeaderField field;
1477 res = parse_key_value (buffer, key, sizeof (key), &value);
1478 if (res != GST_RTSP_OK)
1481 if (conn->tstate == TUNNEL_STATE_GET || conn->tstate == TUNNEL_STATE_POST) {
1482 /* save the tunnel session in the connection */
1483 if (!strcmp (key, "x-sessioncookie")) {
1484 strncpy (conn->tunnelid, value, TUNNELID_LEN);
1485 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1486 conn->tunneled = TRUE;
1489 field = gst_rtsp_find_header_field (key);
1490 if (field != GST_RTSP_HDR_INVALID)
1491 gst_rtsp_message_add_header (msg, field, value);
1504 * GST_RTSP_OK when a complete message was read.
1505 * GST_RTSP_EEOF: when the socket is closed
1506 * GST_RTSP_EINTR: when more data is needed.
1507 * GST_RTSP_..: some other error occured.
1509 static GstRTSPResult
1510 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1511 GstRTSPConnection * conn)
1516 switch (builder->state) {
1518 builder->offset = 0;
1520 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1521 &builder->offset, 1, conn->ctxp);
1522 if (res != GST_RTSP_OK)
1525 /* we have 1 bytes now and we can see if this is a data message or
1527 if (builder->buffer[0] == '$') {
1528 /* data message, prepare for the header */
1529 builder->state = STATE_DATA_HEADER;
1532 builder->state = STATE_READ_LINES;
1535 case STATE_DATA_HEADER:
1538 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1539 &builder->offset, 4, conn->ctxp);
1540 if (res != GST_RTSP_OK)
1543 gst_rtsp_message_init_data (message, builder->buffer[1]);
1545 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1546 builder->body_data = g_malloc (builder->body_len + 1);
1547 builder->body_data[builder->body_len] = '\0';
1548 builder->offset = 0;
1549 builder->state = STATE_DATA_BODY;
1552 case STATE_DATA_BODY:
1555 read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1556 builder->body_len, conn->ctxp);
1557 if (res != GST_RTSP_OK)
1560 /* we have the complete body now, store in the message adjusting the
1561 * length to include the traling '\0' */
1562 gst_rtsp_message_take_body (message,
1563 (guint8 *) builder->body_data, builder->body_len + 1);
1564 builder->body_data = NULL;
1565 builder->body_len = 0;
1567 builder->state = STATE_END;
1570 case STATE_READ_LINES:
1572 res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1573 sizeof (builder->buffer), conn->ctxp);
1574 if (res != GST_RTSP_OK)
1577 /* we have a regular response */
1578 if (builder->buffer[0] == '\r') {
1579 builder->buffer[0] = '\0';
1582 if (builder->buffer[0] == '\0') {
1585 /* empty line, end of message header */
1586 /* see if there is a Content-Length header */
1587 if (gst_rtsp_message_get_header (message,
1588 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1589 /* there is, prepare to read the body */
1590 builder->body_len = atol (hdrval);
1591 builder->body_data = g_malloc (builder->body_len + 1);
1592 builder->body_data[builder->body_len] = '\0';
1593 builder->offset = 0;
1594 builder->state = STATE_DATA_BODY;
1596 builder->state = STATE_END;
1601 /* we have a line */
1602 if (builder->line == 0) {
1603 /* first line, check for response status */
1604 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1605 res = parse_response_status (builder->buffer, message);
1607 res = parse_request_line (conn, builder->buffer, message);
1609 /* the first line must parse without errors */
1610 if (res != GST_RTSP_OK)
1613 /* else just parse the line, ignore errors */
1614 parse_line (conn, builder->buffer, message);
1617 builder->offset = 0;
1624 if (conn->tstate == TUNNEL_STATE_GET) {
1625 res = GST_RTSP_ETGET;
1627 } else if (conn->tstate == TUNNEL_STATE_POST) {
1628 res = GST_RTSP_ETPOST;
1632 if (message->type == GST_RTSP_MESSAGE_DATA) {
1633 /* data messages don't have headers */
1638 /* save session id in the connection for further use */
1639 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1640 &session_id, 0) == GST_RTSP_OK) {
1643 maxlen = sizeof (conn->session_id) - 1;
1644 /* the sessionid can have attributes marked with ;
1645 * Make sure we strip them */
1646 for (i = 0; session_id[i] != '\0'; i++) {
1647 if (session_id[i] == ';') {
1652 } while (g_ascii_isspace (session_id[i]));
1653 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1656 /* if we parsed something valid, configure */
1657 if ((to = atoi (&session_id[i + 8])) > 0)
1664 /* make sure to not overflow */
1665 strncpy (conn->session_id, session_id, maxlen);
1666 conn->session_id[maxlen] = '\0';
1672 res = GST_RTSP_ERROR;
1681 * gst_rtsp_connection_read:
1682 * @conn: a #GstRTSPConnection
1683 * @data: the data to read
1684 * @size: the size of @data
1685 * @timeout: a timeout value or #NULL
1687 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1688 * the specified @timeout. @timeout can be #NULL, in which case this function
1689 * might block forever.
1691 * This function can be cancelled with gst_rtsp_connection_flush().
1693 * Returns: #GST_RTSP_OK on success.
1696 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1704 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1705 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1706 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1713 /* configure timeout if any */
1714 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1716 gst_poll_set_controllable (conn->fdset, TRUE);
1717 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1718 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1721 res = read_bytes (conn->readfd->fd, data, &offset, size, conn->ctxp);
1722 if (res == GST_RTSP_EEOF)
1724 if (res == GST_RTSP_OK)
1726 if (res != GST_RTSP_EINTR)
1730 retval = gst_poll_wait (conn->fdset, to);
1731 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1733 /* check for timeout */
1735 goto select_timeout;
1743 gst_poll_set_controllable (conn->fdset, FALSE);
1750 return GST_RTSP_ESYS;
1754 return GST_RTSP_ETIMEOUT;
1758 return GST_RTSP_EINTR;
1762 return GST_RTSP_EEOF;
1771 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code)
1774 gchar date_string[100];
1775 const gchar *status;
1777 gen_date_string (date_string, sizeof (date_string));
1779 status = gst_rtsp_status_as_text (code);
1780 if (status == NULL) {
1782 status = "Internal Server Error";
1785 str = g_string_new ("");
1788 g_string_append_printf (str, "HTTP/1.0 %d %s\r\n", code, status);
1789 g_string_append_printf (str,
1790 "Server: GStreamer RTSP Server\r\n"
1792 "Connection: close\r\n"
1793 "Cache-Control: no-store\r\n" "Pragma: no-cache\r\n", date_string);
1796 g_string_append_printf (str, "x-server-ip-address: %s\r\n", conn->ip);
1797 g_string_append_printf (str,
1798 "Content-Type: application/x-rtsp-tunnelled\r\n" "\r\n");
1804 * gst_rtsp_connection_receive:
1805 * @conn: a #GstRTSPConnection
1806 * @message: the message to read
1807 * @timeout: a timeout value or #NULL
1809 * Attempt to read into @message from the connected @conn, blocking up to
1810 * the specified @timeout. @timeout can be #NULL, in which case this function
1811 * might block forever.
1813 * This function can be cancelled with gst_rtsp_connection_flush().
1815 * Returns: #GST_RTSP_OK on success.
1818 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1822 GstRTSPBuilder builder = { 0 };
1826 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1827 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1828 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1830 /* configure timeout if any */
1831 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1833 gst_poll_set_controllable (conn->fdset, TRUE);
1834 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1835 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1838 res = build_next (&builder, message, conn);
1839 if (res == GST_RTSP_EEOF)
1841 if (res == GST_RTSP_OK)
1843 if (res == GST_RTSP_ETGET) {
1846 /* tunnel GET request, we can reply now */
1847 str = gen_tunnel_reply (conn, GST_RTSP_STS_OK);
1849 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len,
1851 g_string_free (str, TRUE);
1852 } else if (res == GST_RTSP_ETPOST) {
1853 /* tunnel POST request, return the value, the caller now has to link the
1854 * two connections. */
1856 } else if (res != GST_RTSP_EINTR)
1860 retval = gst_poll_wait (conn->fdset, to);
1861 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1863 /* check for timeout */
1865 goto select_timeout;
1873 gst_poll_set_controllable (conn->fdset, FALSE);
1876 /* we have a message here */
1877 build_reset (&builder);
1884 res = GST_RTSP_ESYS;
1889 res = GST_RTSP_ETIMEOUT;
1894 res = GST_RTSP_EINTR;
1899 res = GST_RTSP_EEOF;
1905 build_reset (&builder);
1906 gst_rtsp_message_unset (message);
1912 * gst_rtsp_connection_close:
1913 * @conn: a #GstRTSPConnection
1915 * Close the connected @conn. After this call, the connection is in the same
1916 * state as when it was first created.
1918 * Returns: #GST_RTSP_OK on success.
1921 gst_rtsp_connection_close (GstRTSPConnection * conn)
1923 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1928 REMOVE_POLLFD (conn->fdset, &conn->fd0);
1929 REMOVE_POLLFD (conn->fdset, &conn->fd1);
1930 conn->writefd = NULL;
1931 conn->readfd = NULL;
1932 conn->tunneled = FALSE;
1933 conn->tstate = TUNNEL_STATE_NONE;
1935 g_free (conn->username);
1936 conn->username = NULL;
1937 g_free (conn->passwd);
1938 conn->passwd = NULL;
1939 gst_rtsp_connection_clear_auth_params (conn);
1942 conn->session_id[0] = '\0';
1948 * gst_rtsp_connection_free:
1949 * @conn: a #GstRTSPConnection
1951 * Close and free @conn.
1953 * Returns: #GST_RTSP_OK on success.
1956 gst_rtsp_connection_free (GstRTSPConnection * conn)
1960 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1962 res = gst_rtsp_connection_close (conn);
1963 gst_poll_free (conn->fdset);
1964 g_timer_destroy (conn->timer);
1965 gst_rtsp_url_free (conn->url);
1975 * gst_rtsp_connection_poll:
1976 * @conn: a #GstRTSPConnection
1977 * @events: a bitmask of #GstRTSPEvent flags to check
1978 * @revents: location for result flags
1979 * @timeout: a timeout
1981 * Wait up to the specified @timeout for the connection to become available for
1982 * at least one of the operations specified in @events. When the function returns
1983 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1986 * @timeout can be #NULL, in which case this function might block forever.
1988 * This function can be cancelled with gst_rtsp_connection_flush().
1990 * Returns: #GST_RTSP_OK on success.
1995 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1996 GstRTSPEvent * revents, GTimeVal * timeout)
2001 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2002 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2003 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2004 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2005 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2007 gst_poll_set_controllable (conn->fdset, TRUE);
2009 /* add fd to writer set when asked to */
2010 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2011 events & GST_RTSP_EV_WRITE);
2013 /* add fd to reader set when asked to */
2014 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2016 /* configure timeout if any */
2017 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2020 retval = gst_poll_wait (conn->fdset, to);
2021 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2024 goto select_timeout;
2034 if (events & GST_RTSP_EV_READ) {
2035 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2036 *revents |= GST_RTSP_EV_READ;
2038 if (events & GST_RTSP_EV_WRITE) {
2039 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2040 *revents |= GST_RTSP_EV_WRITE;
2047 return GST_RTSP_ETIMEOUT;
2051 return GST_RTSP_ESYS;
2055 return GST_RTSP_EINTR;
2060 * gst_rtsp_connection_next_timeout:
2061 * @conn: a #GstRTSPConnection
2062 * @timeout: a timeout
2064 * Calculate the next timeout for @conn, storing the result in @timeout.
2066 * Returns: #GST_RTSP_OK.
2069 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2075 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2076 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2078 elapsed = g_timer_elapsed (conn->timer, &usec);
2079 if (elapsed >= conn->timeout) {
2083 sec = conn->timeout - elapsed;
2086 timeout->tv_sec = sec;
2087 timeout->tv_usec = usec;
2093 * gst_rtsp_connection_reset_timeout:
2094 * @conn: a #GstRTSPConnection
2096 * Reset the timeout of @conn.
2098 * Returns: #GST_RTSP_OK.
2101 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2103 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2105 g_timer_start (conn->timer);
2111 * gst_rtsp_connection_flush:
2112 * @conn: a #GstRTSPConnection
2113 * @flush: start or stop the flush
2115 * Start or stop the flushing action on @conn. When flushing, all current
2116 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2117 * is set to non-flushing mode again.
2119 * Returns: #GST_RTSP_OK.
2122 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2124 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2126 gst_poll_set_flushing (conn->fdset, flush);
2132 * gst_rtsp_connection_set_auth:
2133 * @conn: a #GstRTSPConnection
2134 * @method: authentication method
2136 * @pass: the password
2138 * Configure @conn for authentication mode @method with @user and @pass as the
2139 * user and password respectively.
2141 * Returns: #GST_RTSP_OK.
2144 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2145 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2147 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2149 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2150 || g_strrstr (user, ":") != NULL))
2151 return GST_RTSP_EINVAL;
2153 /* Make sure the username and passwd are being set for authentication */
2154 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2155 return GST_RTSP_EINVAL;
2157 /* ":" chars are not allowed in usernames for basic auth */
2158 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2159 return GST_RTSP_EINVAL;
2161 g_free (conn->username);
2162 g_free (conn->passwd);
2164 conn->auth_method = method;
2165 conn->username = g_strdup (user);
2166 conn->passwd = g_strdup (pass);
2173 * @key: ASCII string to hash
2175 * Hashes @key in a case-insensitive manner.
2177 * Returns: the hash code.
2180 str_case_hash (gconstpointer key)
2182 const char *p = key;
2183 guint h = g_ascii_toupper (*p);
2186 for (p += 1; *p != '\0'; p++)
2187 h = (h << 5) - h + g_ascii_toupper (*p);
2194 * @v1: an ASCII string
2195 * @v2: another ASCII string
2197 * Compares @v1 and @v2 in a case-insensitive manner
2199 * Returns: %TRUE if they are equal (modulo case)
2202 str_case_equal (gconstpointer v1, gconstpointer v2)
2204 const char *string1 = v1;
2205 const char *string2 = v2;
2207 return g_ascii_strcasecmp (string1, string2) == 0;
2211 * gst_rtsp_connection_set_auth_param:
2212 * @conn: a #GstRTSPConnection
2213 * @param: authentication directive
2216 * Setup @conn with authentication directives. This is not necesary for
2217 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2218 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2219 * in the WWW-Authenticate response header and can include realm, domain,
2220 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2225 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2226 const gchar * param, const gchar * value)
2228 g_return_if_fail (conn != NULL);
2229 g_return_if_fail (param != NULL);
2231 if (conn->auth_params == NULL) {
2233 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2235 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2239 * gst_rtsp_connection_clear_auth_params:
2240 * @conn: a #GstRTSPConnection
2242 * Clear the list of authentication directives stored in @conn.
2247 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2249 g_return_if_fail (conn != NULL);
2251 if (conn->auth_params != NULL) {
2252 g_hash_table_destroy (conn->auth_params);
2253 conn->auth_params = NULL;
2257 static GstRTSPResult
2258 set_qos_dscp (gint fd, guint qos_dscp)
2263 struct sockaddr_in6 sa_in6;
2264 struct sockaddr_storage sa_stor;
2266 socklen_t slen = sizeof (sa);
2273 if (getsockname (fd, &sa.sa, &slen) < 0)
2274 goto no_getsockname;
2276 af = sa.sa.sa_family;
2278 /* if this is an IPv4-mapped address then do IPv4 QoS */
2279 if (af == AF_INET6) {
2280 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2284 /* extract and shift 6 bits of the DSCP */
2285 tos = (qos_dscp & 0x3f) << 2;
2289 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2294 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2308 return GST_RTSP_ESYS;
2313 return GST_RTSP_ERROR;
2318 * gst_rtsp_connection_set_qos_dscp:
2319 * @conn: a #GstRTSPConnection
2320 * @qos_dscp: DSCP value
2322 * Configure @conn to use the specified DSCP value.
2324 * Returns: #GST_RTSP_OK on success.
2329 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2333 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2334 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2335 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2337 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2338 if (res == GST_RTSP_OK)
2339 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2346 * gst_rtsp_connection_get_url:
2347 * @conn: a #GstRTSPConnection
2349 * Retrieve the URL of the other end of @conn.
2351 * Returns: The URL. This value remains valid until the
2352 * connection is freed.
2357 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2359 g_return_val_if_fail (conn != NULL, NULL);
2365 * gst_rtsp_connection_get_ip:
2366 * @conn: a #GstRTSPConnection
2368 * Retrieve the IP address of the other end of @conn.
2370 * Returns: The IP address as a string. this value remains valid until the
2371 * connection is closed.
2376 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2378 g_return_val_if_fail (conn != NULL, NULL);
2384 * gst_rtsp_connection_set_ip:
2385 * @conn: a #GstRTSPConnection
2386 * @ip: an ip address
2388 * Set the IP address of the server.
2393 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2395 g_return_if_fail (conn != NULL);
2398 conn->ip = g_strdup (ip);
2402 * gst_rtsp_connection_get_readfd:
2403 * @conn: a #GstRTSPConnection
2405 * Get the file descriptor for reading.
2407 * Returns: the file descriptor used for reading or -1 on error. The file
2408 * descriptor remains valid until the connection is closed.
2413 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2415 g_return_val_if_fail (conn != NULL, -1);
2416 g_return_val_if_fail (conn->readfd != NULL, -1);
2418 return conn->readfd->fd;
2422 * gst_rtsp_connection_get_writefd:
2423 * @conn: a #GstRTSPConnection
2425 * Get the file descriptor for writing.
2427 * Returns: the file descriptor used for writing or -1 on error. The file
2428 * descriptor remains valid until the connection is closed.
2433 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2435 g_return_val_if_fail (conn != NULL, -1);
2436 g_return_val_if_fail (conn->writefd != NULL, -1);
2438 return conn->writefd->fd;
2443 * gst_rtsp_connection_set_tunneled:
2444 * @conn: a #GstRTSPConnection
2445 * @tunneled: the new state
2447 * Set the HTTP tunneling state of the connection. This must be configured before
2448 * the @conn is connected.
2453 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2455 g_return_if_fail (conn != NULL);
2456 g_return_if_fail (conn->readfd == NULL);
2457 g_return_if_fail (conn->writefd == NULL);
2459 conn->tunneled = tunneled;
2463 * gst_rtsp_connection_is_tunneled:
2464 * @conn: a #GstRTSPConnection
2466 * Get the tunneling state of the connection.
2468 * Returns: if @conn is using HTTP tunneling.
2473 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2475 g_return_val_if_fail (conn != NULL, FALSE);
2477 return conn->tunneled;
2481 * gst_rtsp_connection_get_tunnelid:
2482 * @conn: a #GstRTSPConnection
2484 * Get the tunnel session id the connection.
2486 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2491 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2493 g_return_val_if_fail (conn != NULL, NULL);
2495 if (!conn->tunneled)
2498 return conn->tunnelid;
2502 * gst_rtsp_connection_do_tunnel:
2503 * @conn: a #GstRTSPConnection
2504 * @conn2: a #GstRTSPConnection
2506 * If @conn received the first tunnel connection and @conn2 received
2507 * the second tunnel connection, link the two connections together so that
2508 * @conn manages the tunneled connection.
2510 * After this call, @conn2 cannot be used anymore and must be freed with
2511 * gst_rtsp_connection_free().
2513 * Returns: return GST_RTSP_OK on success.
2518 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2519 GstRTSPConnection * conn2)
2521 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2522 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2523 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2524 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2525 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2528 /* both connections have fd0 as the read/write socket. start by taking the
2529 * socket from conn2 and set it as the socket in conn */
2530 conn->fd1 = conn2->fd0;
2532 /* clean up some of the state of conn2 */
2533 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2535 conn2->readfd = conn2->writefd = NULL;
2537 /* We make fd0 the write socket and fd1 the read socket. */
2538 conn->writefd = &conn->fd0;
2539 conn->readfd = &conn->fd1;
2541 conn->tstate = TUNNEL_STATE_COMPLETE;
2543 /* we need base64 decoding for the readfd */
2544 conn->ctx.state = 0;
2548 conn->ctxp = &conn->ctx;
2553 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2554 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2562 static GstRTSPRec *queue_response (GstRTSPWatch * watch, GString * str,
2565 /* async functions */
2566 struct _GstRTSPWatch
2570 GstRTSPConnection *conn;
2572 GstRTSPBuilder builder;
2573 GstRTSPMessage message;
2577 gboolean write_added;
2579 /* queued message for transmission */
2586 GstRTSPWatchFuncs funcs;
2589 GDestroyNotify notify;
2593 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2595 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2597 *timeout = (watch->conn->timeout * 1000);
2603 gst_rtsp_source_check (GSource * source)
2605 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2607 if (watch->readfd.revents & READ_COND)
2610 if (watch->writefd.revents & WRITE_COND)
2617 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2620 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2623 /* first read as much as we can */
2624 if (watch->readfd.revents & READ_COND) {
2626 res = build_next (&watch->builder, &watch->message, watch->conn);
2627 if (res == GST_RTSP_EINTR)
2629 if (res == GST_RTSP_EEOF)
2631 if (res == GST_RTSP_ETGET) {
2633 GstRTSPStatusCode code;
2635 if (watch->funcs.tunnel_start)
2636 code = watch->funcs.tunnel_start (watch, watch->user_data);
2638 code = GST_RTSP_STS_OK;
2640 /* queue the response string */
2641 str = gen_tunnel_reply (watch->conn, code);
2642 queue_response (watch, str, -1);
2643 } else if (res == GST_RTSP_ETPOST) {
2644 /* in the callback the connection should be tunneled with the
2646 if (watch->funcs.tunnel_complete)
2647 watch->funcs.tunnel_complete (watch, watch->user_data);
2648 } else if (res != GST_RTSP_OK)
2651 if (res == GST_RTSP_OK) {
2652 if (watch->funcs.message_received)
2653 watch->funcs.message_received (watch, &watch->message,
2656 gst_rtsp_message_unset (&watch->message);
2658 build_reset (&watch->builder);
2662 if (watch->writefd.revents & WRITE_COND) {
2664 if (watch->write_data == NULL) {
2667 if (!watch->messages)
2670 /* no data, get a new message from the queue */
2671 data = watch->messages->data;
2672 watch->messages = g_list_delete_link (watch->messages, watch->messages);
2674 watch->write_off = 0;
2675 watch->write_len = data->str->len;
2676 watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2677 watch->write_cseq = data->cseq;
2679 g_slice_free (GstRTSPRec, data);
2682 res = write_bytes (watch->writefd.fd, watch->write_data,
2683 &watch->write_off, watch->write_len);
2684 if (res == GST_RTSP_EINTR)
2686 if (res != GST_RTSP_OK)
2689 if (watch->funcs.message_sent && watch->write_cseq != -1)
2690 watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2693 if (watch->messages == NULL && watch->write_added) {
2694 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2695 watch->write_added = FALSE;
2696 watch->writefd.revents = 0;
2698 g_free (watch->write_data);
2699 watch->write_data = NULL;
2708 if (watch->funcs.closed)
2709 watch->funcs.closed (watch, watch->user_data);
2714 if (watch->funcs.error)
2715 watch->funcs.error (watch, res, watch->user_data);
2721 gst_rtsp_source_finalize (GSource * source)
2723 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2726 build_reset (&watch->builder);
2728 for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2729 GstRTSPRec *data = walk->data;
2731 g_string_free (data->str, TRUE);
2732 g_slice_free (GstRTSPRec, data);
2734 g_list_free (watch->messages);
2735 g_free (watch->write_data);
2738 watch->notify (watch->user_data);
2741 static GSourceFuncs gst_rtsp_source_funcs = {
2742 gst_rtsp_source_prepare,
2743 gst_rtsp_source_check,
2744 gst_rtsp_source_dispatch,
2745 gst_rtsp_source_finalize
2749 * gst_rtsp_watch_new:
2750 * @conn: a #GstRTSPConnection
2751 * @funcs: watch functions
2752 * @user_data: user data to pass to @funcs
2753 * @notify: notify when @user_data is not referenced anymore
2755 * Create a watch object for @conn. The functions provided in @funcs will be
2756 * called with @user_data when activity happened on the watch.
2758 * The new watch is usually created so that it can be attached to a
2759 * maincontext with gst_rtsp_watch_attach().
2761 * @conn must exist for the entire lifetime of the watch.
2763 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2764 * communication. Free with gst_rtsp_watch_unref () after usage.
2769 gst_rtsp_watch_new (GstRTSPConnection * conn,
2770 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2772 GstRTSPWatch *result;
2774 g_return_val_if_fail (conn != NULL, NULL);
2775 g_return_val_if_fail (funcs != NULL, NULL);
2776 g_return_val_if_fail (conn->readfd != NULL, NULL);
2777 g_return_val_if_fail (conn->writefd != NULL, NULL);
2779 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2780 sizeof (GstRTSPWatch));
2782 result->conn = conn;
2783 result->builder.state = STATE_START;
2785 result->readfd.fd = -1;
2786 result->writefd.fd = -1;
2788 gst_rtsp_watch_reset (result);
2790 result->funcs = *funcs;
2791 result->user_data = user_data;
2792 result->notify = notify;
2794 /* only add the read fd, the write fd is only added when we have data
2796 g_source_add_poll ((GSource *) result, &result->readfd);
2802 * gst_rtsp_watch_reset:
2803 * @watch: a #GstRTSPWatch
2805 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
2806 * when the file descriptors of the connection might have changed.
2811 gst_rtsp_watch_reset (GstRTSPWatch * watch)
2813 if (watch->readfd.fd != -1)
2814 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2815 if (watch->writefd.fd != -1)
2816 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2818 watch->readfd.fd = watch->conn->readfd->fd;
2819 watch->readfd.events = READ_COND;
2820 watch->readfd.revents = 0;
2822 watch->writefd.fd = watch->conn->writefd->fd;
2823 watch->writefd.events = WRITE_COND;
2824 watch->writefd.revents = 0;
2825 watch->write_added = FALSE;
2827 g_source_add_poll ((GSource *) watch, &watch->readfd);
2831 * gst_rtsp_watch_attach:
2832 * @watch: a #GstRTSPWatch
2833 * @context: a GMainContext (if NULL, the default context will be used)
2835 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2837 * Returns: the ID (greater than 0) for the watch within the GMainContext.
2842 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2844 g_return_val_if_fail (watch != NULL, 0);
2846 return g_source_attach ((GSource *) watch, context);
2850 * gst_rtsp_watch_unref:
2851 * @watch: a #GstRTSPWatch
2853 * Decreases the reference count of @watch by one. If the resulting reference
2854 * count is zero the watch and associated memory will be destroyed.
2859 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2861 g_return_if_fail (watch != NULL);
2863 g_source_unref ((GSource *) watch);
2867 queue_response (GstRTSPWatch * watch, GString * str, guint cseq)
2871 /* make a record with the message as a string ans cseq */
2872 data = g_slice_new (GstRTSPRec);
2876 /* add the record to a queue. FIXME we would like to have an upper limit here */
2877 watch->messages = g_list_append (watch->messages, data);
2879 /* make sure the main context will now also check for writability on the
2881 if (!watch->write_added) {
2882 g_source_add_poll ((GSource *) watch, &watch->writefd);
2883 watch->write_added = TRUE;
2890 * gst_rtsp_watch_queue_message:
2891 * @watch: a #GstRTSPWatch
2892 * @message: a #GstRTSPMessage
2894 * Queue a @message for transmission in @watch. The contents of this
2895 * message will be serialized and transmitted when the connection of the
2896 * watch becomes writable.
2898 * The return value of this function will be returned as the cseq argument in
2899 * the message_sent callback.
2901 * Returns: the sequence number of the message or -1 if the cseq could not be
2907 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2913 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2914 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2916 /* get the cseq from the message, when we finish writing this message on the
2917 * socket we will have to pass the cseq to the callback. */
2918 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2919 0) == GST_RTSP_OK) {
2920 cseq = atoi (header);
2925 /* make a record with the message as a string ans cseq */
2926 data = queue_response (watch, message_to_string (watch->conn, message), cseq);