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;
287 newconn->auth_method = GST_RTSP_AUTH_NONE;
288 newconn->username = NULL;
289 newconn->passwd = NULL;
290 newconn->auth_params = NULL;
300 g_warning ("Error %d on WSAStartup", error);
301 return GST_RTSP_EWSASTART;
305 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
308 return GST_RTSP_EWSAVERSION;
317 return GST_RTSP_ESYS;
322 * gst_rtsp_connection_accept:
324 * @conn: storage for a #GstRTSPConnection
326 * Accept a new connection on @sock and create a new #GstRTSPConnection for
327 * handling communication on new socket.
329 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
334 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
337 unsigned int address_len;
338 GstRTSPConnection *newconn = NULL;
339 struct sockaddr_in address;
345 address_len = sizeof (address);
346 memset (&address, 0, address_len);
349 fd = accept (sock, (struct sockaddr *) &address, &address_len);
351 fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
352 #endif /* G_OS_WIN32 */
356 /* set to non-blocking mode so that we can cancel the communication */
358 fcntl (fd, F_SETFL, O_NONBLOCK);
360 ioctlsocket (fd, FIONBIO, &flags);
361 #endif /* G_OS_WIN32 */
363 /* create a url for the client address */
364 url = g_new0 (GstRTSPUrl, 1);
365 url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
366 url->port = address.sin_port;
368 /* now create the connection object */
369 gst_rtsp_connection_create (url, &newconn);
370 gst_rtsp_url_free (url);
372 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
374 /* both read and write initially */
375 newconn->readfd = &newconn->fd0;
376 newconn->writefd = &newconn->fd0;
385 return GST_RTSP_ESYS;
390 do_resolve (const gchar * host)
392 struct hostent *hostinfo;
396 struct in_addr *addrp;
399 gchar ipbuf[INET_ADDRSTRLEN];
400 #endif /* G_OS_WIN32 */
404 /* first check if it already is an IP address */
405 if (inet_aton (host, &addr)) {
408 hostinfo = gethostbyname (host);
410 goto not_resolved; /* h_errno set */
412 if (hostinfo->h_addrtype != AF_INET)
413 goto not_ip; /* host not an IP host */
415 addrp = (struct in_addr *) hostinfo->h_addr_list[0];
416 /* this is not threadsafe */
417 ip = inet_ntoa (*addrp);
419 addrs = hostinfo->h_addr_list;
420 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
422 #endif /* G_OS_WIN32 */
424 return g_strdup (ip);
429 GST_ERROR ("could not resolve %s", host);
434 GST_ERROR ("not an IP address");
440 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
441 GstPoll * fdset, GTimeVal * timeout)
444 struct sockaddr_in sa_in;
447 unsigned long flags = 1;
448 #endif /* G_OS_WIN32 */
452 memset (&sa_in, 0, sizeof (sa_in));
453 sa_in.sin_family = AF_INET; /* network socket */
454 sa_in.sin_port = htons (port); /* on port */
455 sa_in.sin_addr.s_addr = inet_addr (ip); /* on host ip */
457 fd = socket (AF_INET, SOCK_STREAM, 0);
461 /* set to non-blocking mode so that we can cancel the connect */
463 fcntl (fd, F_SETFL, O_NONBLOCK);
465 ioctlsocket (fd, FIONBIO, &flags);
466 #endif /* G_OS_WIN32 */
468 /* add the socket to our fdset */
469 ADD_POLLFD (fdset, fdout, fd);
471 /* we are going to connect ASYNC now */
472 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
475 if (!ERRNO_IS_EINPROGRESS)
478 /* wait for connect to complete up to the specified timeout or until we got
480 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
482 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
485 retval = gst_poll_wait (fdset, to);
486 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
490 else if (retval == -1)
493 /* we can still have an error connecting on windows */
494 if (gst_poll_fd_has_error (fdset, fdout)) {
495 socklen_t len = sizeof (errno);
497 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
499 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
504 gst_poll_fd_ignored (fdset, fdout);
512 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
513 return GST_RTSP_ESYS;
517 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
518 REMOVE_POLLFD (fdset, fdout);
519 return GST_RTSP_ESYS;
523 GST_ERROR ("timeout");
524 REMOVE_POLLFD (fdset, fdout);
525 return GST_RTSP_ETIMEOUT;
530 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
540 gchar codestr[4], *resultstr;
544 /* create a random sessionid */
545 for (i = 0; i < TUNNELID_LEN; i++)
546 conn->tunnelid[i] = g_random_int_range ('a', 'z');
547 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
552 str = g_strdup_printf ("GET %s%s%s HTTP/1.0\r\n"
553 "x-sessioncookie: %s\r\n"
554 "Accept: application/x-rtsp-tunnelled\r\n"
555 "Pragma: no-cache\r\n"
556 "Cache-Control: no-cache\r\n" "\r\n",
557 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
560 /* we start by writing to this fd */
561 conn->writefd = &conn->fd0;
563 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
565 if (res != GST_RTSP_OK)
568 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
569 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
571 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
579 res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer), NULL);
580 if (res == GST_RTSP_EEOF)
582 if (res == GST_RTSP_OK)
584 if (res != GST_RTSP_EINTR)
588 retval = gst_poll_wait (conn->fdset, to);
589 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
591 /* check for timeout */
603 /* check for last line */
604 if (buffer[0] == '\r')
606 if (buffer[0] == '\0')
610 /* first line, parse response */
611 gchar versionstr[20];
614 bptr = (gchar *) buffer;
616 parse_string (versionstr, sizeof (versionstr), &bptr);
617 parse_string (codestr, sizeof (codestr), &bptr);
618 code = atoi (codestr);
620 while (g_ascii_isspace (*bptr))
631 /* other lines, parse key/value */
632 res = parse_key_value (buffer, key, sizeof (key), &value);
633 if (res == GST_RTSP_OK) {
634 /* we got a new ip address */
635 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
637 conn->ip = g_strdup (value);
644 if (!(ip = do_resolve (conn->ip)))
647 /* get the port from the url */
648 gst_rtsp_url_get_port (conn->url, &port);
650 /* connect to the host/port */
651 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
653 if (res != GST_RTSP_OK)
656 /* this is now our writing socket */
657 conn->writefd = &conn->fd1;
660 str = g_strdup_printf ("POST %s%s%s HTTP/1.0\r\n"
661 "x-sessioncookie: %s\r\n"
662 "Content-Type: application/x-rtsp-tunnelled\r\n"
663 "Pragma: no-cache\r\n"
664 "Cache-Control: no-cache\r\n"
665 "Content-Length: 32767\r\n"
666 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
668 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
671 /* we start by writing to this fd */
672 conn->writefd = &conn->fd1;
674 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
676 if (res != GST_RTSP_OK)
684 GST_ERROR ("write failed (%d)", res);
689 return GST_RTSP_EEOF;
697 return GST_RTSP_ETIMEOUT;
701 return GST_RTSP_ESYS;
705 return GST_RTSP_EINTR;
709 GST_ERROR ("got failure response %d %s", code, resultstr);
710 return GST_RTSP_ERROR;
714 GST_ERROR ("could not resolve %s", conn->ip);
715 return GST_RTSP_ENET;
719 GST_ERROR ("failed to connect");
725 * gst_rtsp_connection_connect:
726 * @conn: a #GstRTSPConnection
727 * @timeout: a #GTimeVal timeout
729 * Attempt to connect to the url of @conn made with
730 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
731 * forever. If @timeout contains a valid timeout, this function will return
732 * #GST_RTSP_ETIMEOUT after the timeout expired.
734 * This function can be cancelled with gst_rtsp_connection_flush().
736 * Returns: #GST_RTSP_OK when a connection could be made.
739 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
746 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
747 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
748 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
752 if (!(ip = do_resolve (url->host)))
755 /* get the port from the url */
756 gst_rtsp_url_get_port (url, &port);
758 /* connect to the host/port */
759 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
760 if (res != GST_RTSP_OK)
766 /* this is our read URL */
767 conn->readfd = &conn->fd0;
769 if (conn->tunneled) {
770 res = setup_tunneling (conn, timeout);
771 if (res != GST_RTSP_OK)
772 goto tunneling_failed;
774 conn->writefd = &conn->fd0;
781 GST_ERROR ("could not resolve %s", url->host);
782 return GST_RTSP_ENET;
786 GST_ERROR ("failed to connect");
792 GST_ERROR ("failed to setup tunneling");
798 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
800 static const char hexdigits[] = "0123456789abcdef";
803 for (i = 0; i < 16; i++) {
804 string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
805 string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
811 auth_digest_compute_hex_urp (const gchar * username,
812 const gchar * realm, const gchar * password, gchar hex_urp[33])
814 struct MD5Context md5_context;
815 unsigned char digest[16];
817 MD5Init (&md5_context);
818 MD5Update (&md5_context, username, strlen (username));
819 MD5Update (&md5_context, ":", 1);
820 MD5Update (&md5_context, realm, strlen (realm));
821 MD5Update (&md5_context, ":", 1);
822 MD5Update (&md5_context, password, strlen (password));
823 MD5Final (digest, &md5_context);
824 md5_digest_to_hex_string (digest, hex_urp);
828 auth_digest_compute_response (const gchar * method,
829 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
833 struct MD5Context md5_context;
834 unsigned char digest[16];
837 MD5Init (&md5_context);
838 MD5Update (&md5_context, method, strlen (method));
839 MD5Update (&md5_context, ":", 1);
840 MD5Update (&md5_context, uri, strlen (uri));
841 MD5Final (digest, &md5_context);
842 md5_digest_to_hex_string (digest, hex_a2);
845 MD5Init (&md5_context);
846 MD5Update (&md5_context, hex_a1, strlen (hex_a1));
847 MD5Update (&md5_context, ":", 1);
848 MD5Update (&md5_context, nonce, strlen (nonce));
849 MD5Update (&md5_context, ":", 1);
851 MD5Update (&md5_context, hex_a2, 32);
852 MD5Final (digest, &md5_context);
853 md5_digest_to_hex_string (digest, response);
857 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
859 switch (conn->auth_method) {
860 case GST_RTSP_AUTH_BASIC:{
865 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
866 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
867 auth_string = g_strdup_printf ("Basic %s", user_pass64);
869 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
873 g_free (user_pass64);
876 case GST_RTSP_AUTH_DIGEST:{
877 gchar response[33], hex_urp[33];
878 gchar *auth_string, *auth_string2;
885 /* we need to have some params set */
886 if (conn->auth_params == NULL)
889 /* we need the realm and nonce */
890 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
891 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
892 if (realm == NULL || nonce == NULL)
895 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
898 method = gst_rtsp_method_as_text (message->type_data.request.method);
899 uri = message->type_data.request.uri;
901 /* Assume no qop, algorithm=md5, stale=false */
902 /* For algorithm MD5, a1 = urp. */
903 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
904 auth_string = g_strdup_printf ("Digest username=\"%s\", "
905 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
906 conn->username, realm, nonce, uri, response);
908 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
910 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
912 g_free (auth_string);
913 auth_string = auth_string2;
915 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
926 gen_date_string (gchar * date_string, guint len)
934 g_get_current_time (&tv);
935 t = (time_t) tv.tv_sec;
938 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
940 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
945 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
950 return GST_RTSP_ERROR;
957 r = WRITE_SOCKET (fd, &buffer[*idx], left);
959 return GST_RTSP_EINTR;
962 return GST_RTSP_EINTR;
964 return GST_RTSP_ESYS;
974 fill_bytes (gint fd, guint8 * buffer, guint size, DecodeCtx * ctx)
982 while (size > 0 && ctx->cout < ctx->coutl) {
983 /* we have some leftover bytes */
984 *buffer++ = ctx->out[ctx->cout];
989 /* nothing in the buffer */
993 /* try to read more bytes */
994 r = READ_SOCKET (fd, &ctx->in[ctx->cin], 4 - ctx->cin);
1002 if (ctx->cin == 4) {
1003 r = g_base64_decode_step ((const gchar *) ctx->in, 4,
1004 (guchar *) ctx->out, &ctx->state, &ctx->save);
1011 out = READ_SOCKET (fd, buffer, size);
1017 static GstRTSPResult
1018 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1023 return GST_RTSP_ERROR;
1030 r = fill_bytes (fd, &buffer[*idx], left, ctx);
1032 return GST_RTSP_EEOF;
1034 if (ERRNO_IS_EAGAIN)
1035 return GST_RTSP_EINTR;
1036 if (!ERRNO_IS_EINTR)
1037 return GST_RTSP_ESYS;
1046 static GstRTSPResult
1047 read_line (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1053 r = fill_bytes (fd, &c, 1, ctx);
1055 return GST_RTSP_EEOF;
1057 if (ERRNO_IS_EAGAIN)
1058 return GST_RTSP_EINTR;
1059 if (!ERRNO_IS_EINTR)
1060 return GST_RTSP_ESYS;
1062 if (c == '\n') /* end on \n */
1064 if (c == '\r') /* ignore \r */
1067 if (*idx < size - 1)
1068 buffer[(*idx)++] = c;
1071 buffer[*idx] = '\0';
1077 * gst_rtsp_connection_write:
1078 * @conn: a #GstRTSPConnection
1079 * @data: the data to write
1080 * @size: the size of @data
1081 * @timeout: a timeout value or #NULL
1083 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1084 * the specified @timeout. @timeout can be #NULL, in which case this function
1085 * might block forever.
1087 * This function can be cancelled with gst_rtsp_connection_flush().
1089 * Returns: #GST_RTSP_OK on success.
1092 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1093 guint size, GTimeVal * timeout)
1100 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1101 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1102 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1104 gst_poll_set_controllable (conn->fdset, TRUE);
1105 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1106 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1107 /* clear all previous poll results */
1108 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1109 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1111 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1117 res = write_bytes (conn->writefd->fd, data, &offset, size);
1118 if (res == GST_RTSP_OK)
1120 if (res != GST_RTSP_EINTR)
1123 /* not all is written, wait until we can write more */
1125 retval = gst_poll_wait (conn->fdset, to);
1126 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1143 return GST_RTSP_ETIMEOUT;
1147 return GST_RTSP_ESYS;
1151 return GST_RTSP_EINTR;
1160 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1162 GString *str = NULL;
1164 str = g_string_new ("");
1166 switch (message->type) {
1167 case GST_RTSP_MESSAGE_REQUEST:
1168 /* create request string, add CSeq */
1169 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1171 gst_rtsp_method_as_text (message->type_data.request.method),
1172 message->type_data.request.uri, conn->cseq++);
1173 /* add session id if we have one */
1174 if (conn->session_id[0] != '\0') {
1175 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1178 /* add any authentication headers */
1179 add_auth_header (conn, message);
1181 case GST_RTSP_MESSAGE_RESPONSE:
1182 /* create response string */
1183 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1184 message->type_data.response.code, message->type_data.response.reason);
1186 case GST_RTSP_MESSAGE_DATA:
1188 guint8 data_header[4];
1190 /* prepare data header */
1191 data_header[0] = '$';
1192 data_header[1] = message->type_data.data.channel;
1193 data_header[2] = (message->body_size >> 8) & 0xff;
1194 data_header[3] = message->body_size & 0xff;
1196 /* create string with header and data */
1197 str = g_string_append_len (str, (gchar *) data_header, 4);
1199 g_string_append_len (str, (gchar *) message->body,
1200 message->body_size);
1204 g_string_free (str, TRUE);
1205 g_return_val_if_reached (NULL);
1209 /* append headers and body */
1210 if (message->type != GST_RTSP_MESSAGE_DATA) {
1211 gchar date_string[100];
1213 gen_date_string (date_string, sizeof (date_string));
1215 /* add date header */
1216 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1218 /* append headers */
1219 gst_rtsp_message_append_headers (message, str);
1221 /* append Content-Length and body if needed */
1222 if (message->body != NULL && message->body_size > 0) {
1225 len = g_strdup_printf ("%d", message->body_size);
1226 g_string_append_printf (str, "%s: %s\r\n",
1227 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1229 /* header ends here */
1230 g_string_append (str, "\r\n");
1232 g_string_append_len (str, (gchar *) message->body,
1233 message->body_size);
1235 /* just end headers */
1236 g_string_append (str, "\r\n");
1244 * gst_rtsp_connection_send:
1245 * @conn: a #GstRTSPConnection
1246 * @message: the message to send
1247 * @timeout: a timeout value or #NULL
1249 * Attempt to send @message to the connected @conn, blocking up to
1250 * the specified @timeout. @timeout can be #NULL, in which case this function
1251 * might block forever.
1253 * This function can be cancelled with gst_rtsp_connection_flush().
1255 * Returns: #GST_RTSP_OK on success.
1258 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1261 GString *string = NULL;
1266 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1267 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1269 if (!(string = message_to_string (conn, message)))
1272 if (conn->tunneled) {
1273 str = g_base64_encode ((const guchar *) string->str, string->len);
1274 g_string_free (string, TRUE);
1279 g_string_free (string, FALSE);
1283 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1291 g_warning ("Wrong message");
1292 return GST_RTSP_EINVAL;
1297 parse_string (gchar * dest, gint size, gchar ** src)
1303 while (g_ascii_isspace (**src))
1306 while (!g_ascii_isspace (**src) && **src != '\0') {
1308 dest[idx++] = **src;
1316 parse_key (gchar * dest, gint size, gchar ** src)
1321 while (**src != ':' && **src != '\0') {
1323 dest[idx++] = **src;
1330 static GstRTSPResult
1331 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1334 gchar versionstr[20];
1339 bptr = (gchar *) buffer;
1341 parse_string (versionstr, sizeof (versionstr), &bptr);
1342 parse_string (codestr, sizeof (codestr), &bptr);
1343 code = atoi (codestr);
1345 while (g_ascii_isspace (*bptr))
1348 if (strcmp (versionstr, "RTSP/1.0") == 0)
1349 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1351 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1352 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1354 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1362 return GST_RTSP_EPARSE;
1366 static GstRTSPResult
1367 parse_request_line (GstRTSPConnection * conn, guint8 * buffer,
1368 GstRTSPMessage * msg)
1370 GstRTSPResult res = GST_RTSP_OK;
1371 gchar versionstr[20];
1372 gchar methodstr[20];
1375 GstRTSPMethod method;
1376 GstRTSPTunnelState tstate = TUNNEL_STATE_NONE;
1378 bptr = (gchar *) buffer;
1380 parse_string (methodstr, sizeof (methodstr), &bptr);
1381 method = gst_rtsp_find_method (methodstr);
1382 if (method == GST_RTSP_INVALID) {
1383 /* a tunnel request is allowed when we don't have one yet */
1384 if (conn->tstate != TUNNEL_STATE_NONE)
1385 goto invalid_method;
1386 /* we need GET or POST for a valid tunnel request */
1387 if (!strcmp (methodstr, "GET"))
1388 tstate = TUNNEL_STATE_GET;
1389 else if (!strcmp (methodstr, "POST"))
1390 tstate = TUNNEL_STATE_POST;
1392 goto invalid_method;
1395 parse_string (urlstr, sizeof (urlstr), &bptr);
1396 if (*urlstr == '\0')
1399 parse_string (versionstr, sizeof (versionstr), &bptr);
1402 goto invalid_version;
1404 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1405 res = gst_rtsp_message_init_request (msg, method, urlstr);
1406 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1407 res = gst_rtsp_message_init_request (msg, method, urlstr);
1408 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1409 } else if (strcmp (versionstr, "HTTP/1.0") == 0) {
1410 /* tunnel request, we need a tunnel method */
1411 if (tstate == TUNNEL_STATE_NONE) {
1412 res = GST_RTSP_EPARSE;
1414 conn->tstate = tstate;
1417 res = GST_RTSP_EPARSE;
1425 GST_ERROR ("invalid method %s", methodstr);
1426 return GST_RTSP_EPARSE;
1430 GST_ERROR ("invalid url %s", urlstr);
1431 return GST_RTSP_EPARSE;
1435 GST_ERROR ("invalid version");
1436 return GST_RTSP_EPARSE;
1440 static GstRTSPResult
1441 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1445 bptr = (gchar *) buffer;
1448 parse_key (key, keysize, &bptr);
1453 while (g_ascii_isspace (*bptr))
1463 return GST_RTSP_EPARSE;
1467 /* parsing lines means reading a Key: Value pair */
1468 static GstRTSPResult
1469 parse_line (GstRTSPConnection * conn, guint8 * buffer, GstRTSPMessage * msg)
1474 GstRTSPHeaderField field;
1476 res = parse_key_value (buffer, key, sizeof (key), &value);
1477 if (res != GST_RTSP_OK)
1480 if (conn->tstate == TUNNEL_STATE_GET || conn->tstate == TUNNEL_STATE_POST) {
1481 /* save the tunnel session in the connection */
1482 if (!strcmp (key, "x-sessioncookie")) {
1483 strncpy (conn->tunnelid, value, TUNNELID_LEN);
1484 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1485 conn->tunneled = TRUE;
1488 field = gst_rtsp_find_header_field (key);
1489 if (field != GST_RTSP_HDR_INVALID)
1490 gst_rtsp_message_add_header (msg, field, value);
1503 * GST_RTSP_OK when a complete message was read.
1504 * GST_RTSP_EEOF: when the socket is closed
1505 * GST_RTSP_EINTR: when more data is needed.
1506 * GST_RTSP_..: some other error occured.
1508 static GstRTSPResult
1509 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1510 GstRTSPConnection * conn)
1515 switch (builder->state) {
1517 builder->offset = 0;
1519 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1520 &builder->offset, 1, conn->ctxp);
1521 if (res != GST_RTSP_OK)
1524 /* we have 1 bytes now and we can see if this is a data message or
1526 if (builder->buffer[0] == '$') {
1527 /* data message, prepare for the header */
1528 builder->state = STATE_DATA_HEADER;
1531 builder->state = STATE_READ_LINES;
1534 case STATE_DATA_HEADER:
1537 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1538 &builder->offset, 4, conn->ctxp);
1539 if (res != GST_RTSP_OK)
1542 gst_rtsp_message_init_data (message, builder->buffer[1]);
1544 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1545 builder->body_data = g_malloc (builder->body_len + 1);
1546 builder->body_data[builder->body_len] = '\0';
1547 builder->offset = 0;
1548 builder->state = STATE_DATA_BODY;
1551 case STATE_DATA_BODY:
1554 read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1555 builder->body_len, conn->ctxp);
1556 if (res != GST_RTSP_OK)
1559 /* we have the complete body now, store in the message adjusting the
1560 * length to include the traling '\0' */
1561 gst_rtsp_message_take_body (message,
1562 (guint8 *) builder->body_data, builder->body_len + 1);
1563 builder->body_data = NULL;
1564 builder->body_len = 0;
1566 builder->state = STATE_END;
1569 case STATE_READ_LINES:
1571 res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1572 sizeof (builder->buffer), conn->ctxp);
1573 if (res != GST_RTSP_OK)
1576 /* we have a regular response */
1577 if (builder->buffer[0] == '\r') {
1578 builder->buffer[0] = '\0';
1581 if (builder->buffer[0] == '\0') {
1584 /* empty line, end of message header */
1585 /* see if there is a Content-Length header */
1586 if (gst_rtsp_message_get_header (message,
1587 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1588 /* there is, prepare to read the body */
1589 builder->body_len = atol (hdrval);
1590 builder->body_data = g_malloc (builder->body_len + 1);
1591 builder->body_data[builder->body_len] = '\0';
1592 builder->offset = 0;
1593 builder->state = STATE_DATA_BODY;
1595 builder->state = STATE_END;
1600 /* we have a line */
1601 if (builder->line == 0) {
1602 /* first line, check for response status */
1603 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1604 res = parse_response_status (builder->buffer, message);
1606 res = parse_request_line (conn, builder->buffer, message);
1608 /* the first line must parse without errors */
1609 if (res != GST_RTSP_OK)
1612 /* else just parse the line, ignore errors */
1613 parse_line (conn, builder->buffer, message);
1616 builder->offset = 0;
1623 if (conn->tstate == TUNNEL_STATE_GET) {
1624 res = GST_RTSP_ETGET;
1626 } else if (conn->tstate == TUNNEL_STATE_POST) {
1627 res = GST_RTSP_ETPOST;
1631 if (message->type == GST_RTSP_MESSAGE_DATA) {
1632 /* data messages don't have headers */
1637 /* save session id in the connection for further use */
1638 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1639 &session_id, 0) == GST_RTSP_OK) {
1642 maxlen = sizeof (conn->session_id) - 1;
1643 /* the sessionid can have attributes marked with ;
1644 * Make sure we strip them */
1645 for (i = 0; session_id[i] != '\0'; i++) {
1646 if (session_id[i] == ';') {
1651 } while (g_ascii_isspace (session_id[i]));
1652 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1655 /* if we parsed something valid, configure */
1656 if ((to = atoi (&session_id[i + 8])) > 0)
1663 /* make sure to not overflow */
1664 strncpy (conn->session_id, session_id, maxlen);
1665 conn->session_id[maxlen] = '\0';
1671 res = GST_RTSP_ERROR;
1680 * gst_rtsp_connection_read:
1681 * @conn: a #GstRTSPConnection
1682 * @data: the data to read
1683 * @size: the size of @data
1684 * @timeout: a timeout value or #NULL
1686 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1687 * the specified @timeout. @timeout can be #NULL, in which case this function
1688 * might block forever.
1690 * This function can be cancelled with gst_rtsp_connection_flush().
1692 * Returns: #GST_RTSP_OK on success.
1695 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1703 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1704 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1705 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1712 /* configure timeout if any */
1713 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1715 gst_poll_set_controllable (conn->fdset, TRUE);
1716 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1717 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1720 res = read_bytes (conn->readfd->fd, data, &offset, size, conn->ctxp);
1721 if (res == GST_RTSP_EEOF)
1723 if (res == GST_RTSP_OK)
1725 if (res != GST_RTSP_EINTR)
1729 retval = gst_poll_wait (conn->fdset, to);
1730 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1732 /* check for timeout */
1734 goto select_timeout;
1742 gst_poll_set_controllable (conn->fdset, FALSE);
1749 return GST_RTSP_ESYS;
1753 return GST_RTSP_ETIMEOUT;
1757 return GST_RTSP_EINTR;
1761 return GST_RTSP_EEOF;
1770 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code)
1773 gchar date_string[100];
1774 const gchar *status;
1776 gen_date_string (date_string, sizeof (date_string));
1778 status = gst_rtsp_status_as_text (code);
1779 if (status == NULL) {
1781 status = "Internal Server Error";
1784 str = g_string_new ("");
1787 g_string_append_printf (str, "HTTP/1.0 %d %s\r\n", code, status);
1788 g_string_append_printf (str,
1789 "Server: GStreamer RTSP Server\r\n"
1791 "Connection: close\r\n"
1792 "Cache-Control: no-store\r\n" "Pragma: no-cache\r\n", date_string);
1795 g_string_append_printf (str, "x-server-ip-address: %s\r\n", conn->ip);
1796 g_string_append_printf (str,
1797 "Content-Type: application/x-rtsp-tunnelled\r\n" "\r\n");
1803 * gst_rtsp_connection_receive:
1804 * @conn: a #GstRTSPConnection
1805 * @message: the message to read
1806 * @timeout: a timeout value or #NULL
1808 * Attempt to read into @message from the connected @conn, blocking up to
1809 * the specified @timeout. @timeout can be #NULL, in which case this function
1810 * might block forever.
1812 * This function can be cancelled with gst_rtsp_connection_flush().
1814 * Returns: #GST_RTSP_OK on success.
1817 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1821 GstRTSPBuilder builder = { 0 };
1825 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1826 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1827 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1829 /* configure timeout if any */
1830 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1832 gst_poll_set_controllable (conn->fdset, TRUE);
1833 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1834 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1837 res = build_next (&builder, message, conn);
1838 if (res == GST_RTSP_EEOF)
1840 if (res == GST_RTSP_OK)
1842 if (res == GST_RTSP_ETGET) {
1845 /* tunnel GET request, we can reply now */
1846 str = gen_tunnel_reply (conn, GST_RTSP_STS_OK);
1848 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len,
1850 g_string_free (str, TRUE);
1851 } else if (res == GST_RTSP_ETPOST) {
1852 /* tunnel POST request, return the value, the caller now has to link the
1853 * two connections. */
1855 } else if (res != GST_RTSP_EINTR)
1859 retval = gst_poll_wait (conn->fdset, to);
1860 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1862 /* check for timeout */
1864 goto select_timeout;
1872 gst_poll_set_controllable (conn->fdset, FALSE);
1875 /* we have a message here */
1876 build_reset (&builder);
1883 res = GST_RTSP_ESYS;
1888 res = GST_RTSP_ETIMEOUT;
1893 res = GST_RTSP_EINTR;
1898 res = GST_RTSP_EEOF;
1904 build_reset (&builder);
1905 gst_rtsp_message_unset (message);
1911 * gst_rtsp_connection_close:
1912 * @conn: a #GstRTSPConnection
1914 * Close the connected @conn. After this call, the connection is in the same
1915 * state as when it was first created.
1917 * Returns: #GST_RTSP_OK on success.
1920 gst_rtsp_connection_close (GstRTSPConnection * conn)
1922 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1927 REMOVE_POLLFD (conn->fdset, &conn->fd0);
1928 REMOVE_POLLFD (conn->fdset, &conn->fd1);
1929 conn->writefd = NULL;
1930 conn->readfd = NULL;
1931 conn->tunneled = FALSE;
1932 conn->tstate = TUNNEL_STATE_NONE;
1934 g_free (conn->username);
1935 conn->username = NULL;
1936 g_free (conn->passwd);
1937 conn->passwd = NULL;
1938 gst_rtsp_connection_clear_auth_params (conn);
1941 conn->session_id[0] = '\0';
1947 * gst_rtsp_connection_free:
1948 * @conn: a #GstRTSPConnection
1950 * Close and free @conn.
1952 * Returns: #GST_RTSP_OK on success.
1955 gst_rtsp_connection_free (GstRTSPConnection * conn)
1959 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1961 res = gst_rtsp_connection_close (conn);
1962 gst_poll_free (conn->fdset);
1963 g_timer_destroy (conn->timer);
1964 gst_rtsp_url_free (conn->url);
1974 * gst_rtsp_connection_poll:
1975 * @conn: a #GstRTSPConnection
1976 * @events: a bitmask of #GstRTSPEvent flags to check
1977 * @revents: location for result flags
1978 * @timeout: a timeout
1980 * Wait up to the specified @timeout for the connection to become available for
1981 * at least one of the operations specified in @events. When the function returns
1982 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1985 * @timeout can be #NULL, in which case this function might block forever.
1987 * This function can be cancelled with gst_rtsp_connection_flush().
1989 * Returns: #GST_RTSP_OK on success.
1994 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1995 GstRTSPEvent * revents, GTimeVal * timeout)
2000 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2001 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2002 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2003 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2004 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2006 gst_poll_set_controllable (conn->fdset, TRUE);
2008 /* add fd to writer set when asked to */
2009 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2010 events & GST_RTSP_EV_WRITE);
2012 /* add fd to reader set when asked to */
2013 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2015 /* configure timeout if any */
2016 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2019 retval = gst_poll_wait (conn->fdset, to);
2020 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2023 goto select_timeout;
2033 if (events & GST_RTSP_EV_READ) {
2034 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2035 *revents |= GST_RTSP_EV_READ;
2037 if (events & GST_RTSP_EV_WRITE) {
2038 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2039 *revents |= GST_RTSP_EV_WRITE;
2046 return GST_RTSP_ETIMEOUT;
2050 return GST_RTSP_ESYS;
2054 return GST_RTSP_EINTR;
2059 * gst_rtsp_connection_next_timeout:
2060 * @conn: a #GstRTSPConnection
2061 * @timeout: a timeout
2063 * Calculate the next timeout for @conn, storing the result in @timeout.
2065 * Returns: #GST_RTSP_OK.
2068 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2074 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2075 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2077 elapsed = g_timer_elapsed (conn->timer, &usec);
2078 if (elapsed >= conn->timeout) {
2082 sec = conn->timeout - elapsed;
2085 timeout->tv_sec = sec;
2086 timeout->tv_usec = usec;
2092 * gst_rtsp_connection_reset_timeout:
2093 * @conn: a #GstRTSPConnection
2095 * Reset the timeout of @conn.
2097 * Returns: #GST_RTSP_OK.
2100 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2102 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2104 g_timer_start (conn->timer);
2110 * gst_rtsp_connection_flush:
2111 * @conn: a #GstRTSPConnection
2112 * @flush: start or stop the flush
2114 * Start or stop the flushing action on @conn. When flushing, all current
2115 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2116 * is set to non-flushing mode again.
2118 * Returns: #GST_RTSP_OK.
2121 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2123 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2125 gst_poll_set_flushing (conn->fdset, flush);
2131 * gst_rtsp_connection_set_auth:
2132 * @conn: a #GstRTSPConnection
2133 * @method: authentication method
2135 * @pass: the password
2137 * Configure @conn for authentication mode @method with @user and @pass as the
2138 * user and password respectively.
2140 * Returns: #GST_RTSP_OK.
2143 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2144 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2146 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2148 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2149 || g_strrstr (user, ":") != NULL))
2150 return GST_RTSP_EINVAL;
2152 /* Make sure the username and passwd are being set for authentication */
2153 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2154 return GST_RTSP_EINVAL;
2156 /* ":" chars are not allowed in usernames for basic auth */
2157 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2158 return GST_RTSP_EINVAL;
2160 g_free (conn->username);
2161 g_free (conn->passwd);
2163 conn->auth_method = method;
2164 conn->username = g_strdup (user);
2165 conn->passwd = g_strdup (pass);
2172 * @key: ASCII string to hash
2174 * Hashes @key in a case-insensitive manner.
2176 * Returns: the hash code.
2179 str_case_hash (gconstpointer key)
2181 const char *p = key;
2182 guint h = g_ascii_toupper (*p);
2185 for (p += 1; *p != '\0'; p++)
2186 h = (h << 5) - h + g_ascii_toupper (*p);
2193 * @v1: an ASCII string
2194 * @v2: another ASCII string
2196 * Compares @v1 and @v2 in a case-insensitive manner
2198 * Returns: %TRUE if they are equal (modulo case)
2201 str_case_equal (gconstpointer v1, gconstpointer v2)
2203 const char *string1 = v1;
2204 const char *string2 = v2;
2206 return g_ascii_strcasecmp (string1, string2) == 0;
2210 * gst_rtsp_connection_set_auth_param:
2211 * @conn: a #GstRTSPConnection
2212 * @param: authentication directive
2215 * Setup @conn with authentication directives. This is not necesary for
2216 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2217 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2218 * in the WWW-Authenticate response header and can include realm, domain,
2219 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2224 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2225 const gchar * param, const gchar * value)
2227 g_return_if_fail (conn != NULL);
2228 g_return_if_fail (param != NULL);
2230 if (conn->auth_params == NULL) {
2232 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2234 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2238 * gst_rtsp_connection_clear_auth_params:
2239 * @conn: a #GstRTSPConnection
2241 * Clear the list of authentication directives stored in @conn.
2246 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2248 g_return_if_fail (conn != NULL);
2250 if (conn->auth_params != NULL) {
2251 g_hash_table_destroy (conn->auth_params);
2252 conn->auth_params = NULL;
2256 static GstRTSPResult
2257 set_qos_dscp (gint fd, guint qos_dscp)
2262 struct sockaddr_in6 sa_in6;
2263 struct sockaddr_storage sa_stor;
2265 socklen_t slen = sizeof (sa);
2272 if (getsockname (fd, &sa.sa, &slen) < 0)
2273 goto no_getsockname;
2275 af = sa.sa.sa_family;
2277 /* if this is an IPv4-mapped address then do IPv4 QoS */
2278 if (af == AF_INET6) {
2279 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2283 /* extract and shift 6 bits of the DSCP */
2284 tos = (qos_dscp & 0x3f) << 2;
2288 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2293 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2307 return GST_RTSP_ESYS;
2312 return GST_RTSP_ERROR;
2317 * gst_rtsp_connection_set_qos_dscp:
2318 * @conn: a #GstRTSPConnection
2319 * @qos_dscp: DSCP value
2321 * Configure @conn to use the specified DSCP value.
2323 * Returns: #GST_RTSP_OK on success.
2328 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2332 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2333 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2334 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2336 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2337 if (res == GST_RTSP_OK)
2338 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2345 * gst_rtsp_connection_get_url:
2346 * @conn: a #GstRTSPConnection
2348 * Retrieve the URL of the other end of @conn.
2350 * Returns: The URL. This value remains valid until the
2351 * connection is freed.
2356 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2358 g_return_val_if_fail (conn != NULL, NULL);
2364 * gst_rtsp_connection_get_ip:
2365 * @conn: a #GstRTSPConnection
2367 * Retrieve the IP address of the other end of @conn.
2369 * Returns: The IP address as a string. this value remains valid until the
2370 * connection is closed.
2375 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2377 g_return_val_if_fail (conn != NULL, NULL);
2383 * gst_rtsp_connection_set_ip:
2384 * @conn: a #GstRTSPConnection
2385 * @ip: an ip address
2387 * Set the IP address of the server.
2392 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2394 g_return_if_fail (conn != NULL);
2397 conn->ip = g_strdup (ip);
2401 * gst_rtsp_connection_get_readfd:
2402 * @conn: a #GstRTSPConnection
2404 * Get the file descriptor for reading.
2406 * Returns: the file descriptor used for reading or -1 on error. The file
2407 * descriptor remains valid until the connection is closed.
2412 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2414 g_return_val_if_fail (conn != NULL, -1);
2415 g_return_val_if_fail (conn->readfd != NULL, -1);
2417 return conn->readfd->fd;
2421 * gst_rtsp_connection_get_writefd:
2422 * @conn: a #GstRTSPConnection
2424 * Get the file descriptor for writing.
2426 * Returns: the file descriptor used for writing or -1 on error. The file
2427 * descriptor remains valid until the connection is closed.
2432 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2434 g_return_val_if_fail (conn != NULL, -1);
2435 g_return_val_if_fail (conn->writefd != NULL, -1);
2437 return conn->writefd->fd;
2442 * gst_rtsp_connection_set_tunneled:
2443 * @conn: a #GstRTSPConnection
2444 * @tunneled: the new state
2446 * Set the HTTP tunneling state of the connection. This must be configured before
2447 * the @conn is connected.
2452 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2454 g_return_if_fail (conn != NULL);
2455 g_return_if_fail (conn->readfd == NULL);
2456 g_return_if_fail (conn->writefd == NULL);
2458 conn->tunneled = tunneled;
2462 * gst_rtsp_connection_is_tunneled:
2463 * @conn: a #GstRTSPConnection
2465 * Get the tunneling state of the connection.
2467 * Returns: if @conn is using HTTP tunneling.
2472 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2474 g_return_val_if_fail (conn != NULL, FALSE);
2476 return conn->tunneled;
2480 * gst_rtsp_connection_get_tunnelid:
2481 * @conn: a #GstRTSPConnection
2483 * Get the tunnel session id the connection.
2485 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2490 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2492 g_return_val_if_fail (conn != NULL, NULL);
2494 if (!conn->tunneled)
2497 return conn->tunnelid;
2501 * gst_rtsp_connection_do_tunnel:
2502 * @conn: a #GstRTSPConnection
2503 * @conn2: a #GstRTSPConnection
2505 * If @conn received the first tunnel connection and @conn2 received
2506 * the second tunnel connection, link the two connections together so that
2507 * @conn manages the tunneled connection.
2509 * After this call, @conn2 cannot be used anymore and must be freed with
2510 * gst_rtsp_connection_free().
2512 * Returns: return GST_RTSP_OK on success.
2517 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2518 GstRTSPConnection * conn2)
2520 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2521 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2522 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2523 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2524 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2527 /* both connections have fd0 as the read/write socket. start by taking the
2528 * socket from conn2 and set it as the socket in conn */
2529 conn->fd1 = conn2->fd0;
2531 /* clean up some of the state of conn2 */
2532 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2534 conn2->readfd = conn2->writefd = NULL;
2536 /* We make fd0 the write socket and fd1 the read socket. */
2537 conn->writefd = &conn->fd0;
2538 conn->readfd = &conn->fd1;
2540 conn->tstate = TUNNEL_STATE_COMPLETE;
2542 /* we need base64 decoding for the readfd */
2543 conn->ctx.state = 0;
2547 conn->ctxp = &conn->ctx;
2552 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2553 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2561 static GstRTSPRec *queue_response (GstRTSPWatch * watch, GString * str,
2564 /* async functions */
2565 struct _GstRTSPWatch
2569 GstRTSPConnection *conn;
2571 GstRTSPBuilder builder;
2572 GstRTSPMessage message;
2576 gboolean write_added;
2578 /* queued message for transmission */
2585 GstRTSPWatchFuncs funcs;
2588 GDestroyNotify notify;
2592 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2594 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2596 *timeout = (watch->conn->timeout * 1000);
2602 gst_rtsp_source_check (GSource * source)
2604 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2606 if (watch->readfd.revents & READ_COND)
2609 if (watch->writefd.revents & WRITE_COND)
2616 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2619 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2622 /* first read as much as we can */
2623 if (watch->readfd.revents & READ_COND) {
2625 res = build_next (&watch->builder, &watch->message, watch->conn);
2626 if (res == GST_RTSP_EINTR)
2628 if (res == GST_RTSP_EEOF)
2630 if (res == GST_RTSP_ETGET) {
2632 GstRTSPStatusCode code;
2634 if (watch->funcs.tunnel_start)
2635 code = watch->funcs.tunnel_start (watch, watch->user_data);
2637 code = GST_RTSP_STS_OK;
2639 /* queue the response string */
2640 str = gen_tunnel_reply (watch->conn, code);
2641 queue_response (watch, str, -1);
2642 } else if (res == GST_RTSP_ETPOST) {
2643 /* in the callback the connection should be tunneled with the
2645 if (watch->funcs.tunnel_complete)
2646 watch->funcs.tunnel_complete (watch, watch->user_data);
2647 } else if (res != GST_RTSP_OK)
2650 if (res == GST_RTSP_OK) {
2651 if (watch->funcs.message_received)
2652 watch->funcs.message_received (watch, &watch->message,
2655 gst_rtsp_message_unset (&watch->message);
2657 build_reset (&watch->builder);
2661 if (watch->writefd.revents & WRITE_COND) {
2663 if (watch->write_data == NULL) {
2666 if (!watch->messages)
2669 /* no data, get a new message from the queue */
2670 data = watch->messages->data;
2671 watch->messages = g_list_delete_link (watch->messages, watch->messages);
2673 watch->write_off = 0;
2674 watch->write_len = data->str->len;
2675 watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2676 watch->write_cseq = data->cseq;
2678 g_slice_free (GstRTSPRec, data);
2681 res = write_bytes (watch->writefd.fd, watch->write_data,
2682 &watch->write_off, watch->write_len);
2683 if (res == GST_RTSP_EINTR)
2685 if (res != GST_RTSP_OK)
2688 if (watch->funcs.message_sent && watch->write_cseq != -1)
2689 watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2692 if (watch->messages == NULL && watch->write_added) {
2693 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2694 watch->write_added = FALSE;
2695 watch->writefd.revents = 0;
2697 g_free (watch->write_data);
2698 watch->write_data = NULL;
2707 if (watch->funcs.closed)
2708 watch->funcs.closed (watch, watch->user_data);
2713 if (watch->funcs.error)
2714 watch->funcs.error (watch, res, watch->user_data);
2720 gst_rtsp_source_finalize (GSource * source)
2722 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2725 build_reset (&watch->builder);
2727 for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2728 GstRTSPRec *data = walk->data;
2730 g_string_free (data->str, TRUE);
2731 g_slice_free (GstRTSPRec, data);
2733 g_list_free (watch->messages);
2734 g_free (watch->write_data);
2737 watch->notify (watch->user_data);
2740 static GSourceFuncs gst_rtsp_source_funcs = {
2741 gst_rtsp_source_prepare,
2742 gst_rtsp_source_check,
2743 gst_rtsp_source_dispatch,
2744 gst_rtsp_source_finalize
2748 * gst_rtsp_watch_new:
2749 * @conn: a #GstRTSPConnection
2750 * @funcs: watch functions
2751 * @user_data: user data to pass to @funcs
2752 * @notify: notify when @user_data is not referenced anymore
2754 * Create a watch object for @conn. The functions provided in @funcs will be
2755 * called with @user_data when activity happened on the watch.
2757 * The new watch is usually created so that it can be attached to a
2758 * maincontext with gst_rtsp_watch_attach().
2760 * @conn must exist for the entire lifetime of the watch.
2762 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2763 * communication. Free with gst_rtsp_watch_unref () after usage.
2768 gst_rtsp_watch_new (GstRTSPConnection * conn,
2769 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2771 GstRTSPWatch *result;
2773 g_return_val_if_fail (conn != NULL, NULL);
2774 g_return_val_if_fail (funcs != NULL, NULL);
2775 g_return_val_if_fail (conn->readfd != NULL, NULL);
2776 g_return_val_if_fail (conn->writefd != NULL, NULL);
2778 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2779 sizeof (GstRTSPWatch));
2781 result->conn = conn;
2782 result->builder.state = STATE_START;
2784 result->readfd.fd = -1;
2785 result->writefd.fd = -1;
2787 gst_rtsp_watch_reset (result);
2789 result->funcs = *funcs;
2790 result->user_data = user_data;
2791 result->notify = notify;
2793 /* only add the read fd, the write fd is only added when we have data
2795 g_source_add_poll ((GSource *) result, &result->readfd);
2801 * gst_rtsp_watch_reset:
2802 * @watch: a #GstRTSPWatch
2804 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
2805 * when the file descriptors of the connection might have changed.
2810 gst_rtsp_watch_reset (GstRTSPWatch * watch)
2812 if (watch->readfd.fd != -1)
2813 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2814 if (watch->writefd.fd != -1)
2815 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2817 watch->readfd.fd = watch->conn->readfd->fd;
2818 watch->readfd.events = READ_COND;
2819 watch->readfd.revents = 0;
2821 watch->writefd.fd = watch->conn->writefd->fd;
2822 watch->writefd.events = WRITE_COND;
2823 watch->writefd.revents = 0;
2824 watch->write_added = FALSE;
2826 g_source_add_poll ((GSource *) watch, &watch->readfd);
2830 * gst_rtsp_watch_attach:
2831 * @watch: a #GstRTSPWatch
2832 * @context: a GMainContext (if NULL, the default context will be used)
2834 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2836 * Returns: the ID (greater than 0) for the watch within the GMainContext.
2841 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2843 g_return_val_if_fail (watch != NULL, 0);
2845 return g_source_attach ((GSource *) watch, context);
2849 * gst_rtsp_watch_unref:
2850 * @watch: a #GstRTSPWatch
2852 * Decreases the reference count of @watch by one. If the resulting reference
2853 * count is zero the watch and associated memory will be destroyed.
2858 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2860 g_return_if_fail (watch != NULL);
2862 g_source_unref ((GSource *) watch);
2866 queue_response (GstRTSPWatch * watch, GString * str, guint cseq)
2870 /* make a record with the message as a string ans cseq */
2871 data = g_slice_new (GstRTSPRec);
2875 /* add the record to a queue. FIXME we would like to have an upper limit here */
2876 watch->messages = g_list_append (watch->messages, data);
2878 /* make sure the main context will now also check for writability on the
2880 if (!watch->write_added) {
2881 g_source_add_poll ((GSource *) watch, &watch->writefd);
2882 watch->write_added = TRUE;
2889 * gst_rtsp_watch_queue_message:
2890 * @watch: a #GstRTSPWatch
2891 * @message: a #GstRTSPMessage
2893 * Queue a @message for transmission in @watch. The contents of this
2894 * message will be serialized and transmitted when the connection of the
2895 * watch becomes writable.
2897 * The return value of this function will be returned as the cseq argument in
2898 * the message_sent callback.
2900 * Returns: the sequence number of the message or -1 if the cseq could not be
2906 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2912 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2913 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2915 /* get the cseq from the message, when we finish writing this message on the
2916 * socket we will have to pass the cseq to the callback. */
2917 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2918 0) == GST_RTSP_OK) {
2919 cseq = atoi (header);
2924 /* make a record with the message as a string ans cseq */
2925 data = queue_response (watch, message_to_string (watch->conn, message), cseq);