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"
108 static GstRTSPResult read_line (gint fd, guint8 * buffer, guint * idx,
109 guint size, DecodeCtx * ctxp);
110 static GstRTSPResult parse_key_value (guint8 * buffer, gchar * key,
111 guint keysize, gchar ** value);
112 static void parse_string (gchar * dest, gint size, gchar ** src);
115 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
116 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
117 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
118 #define CLOSE_SOCKET(sock) closesocket (sock)
119 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
120 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
121 /* According to Microsoft's connect() documentation this one returns
122 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
123 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
125 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
126 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
127 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
128 #define CLOSE_SOCKET(sock) close (sock)
129 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
130 #define ERRNO_IS_EINTR (errno == EINTR)
131 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
134 #define ADD_POLLFD(fdset, pfd, fd) \
137 gst_poll_add_fd (fdset, pfd); \
140 #define REMOVE_POLLFD(fdset, pfd) \
142 if ((pfd)->fd != -1) { \
143 GST_DEBUG ("remove fd %d", (pfd)->fd); \
144 gst_poll_remove_fd (fdset, pfd); \
145 CLOSE_SOCKET ((pfd)->fd); \
155 TUNNEL_STATE_COMPLETE
156 } GstRTSPTunnelState;
158 #define TUNNELID_LEN 24
160 struct _GstRTSPConnection
163 /* URL for the connection */
166 /* connection state */
173 gchar tunnelid[TUNNELID_LEN];
175 GstRTSPTunnelState tstate;
181 gint cseq; /* sequence number */
182 gchar session_id[512]; /* session id */
183 gint timeout; /* session timeout in seconds */
184 GTimer *timer; /* timeout timer */
187 GstRTSPAuthMethod auth_method;
190 GHashTable *auth_params;
198 inet_aton (const char *c, struct in_addr *paddr)
200 /* note that inet_addr is deprecated on unix because
201 * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
203 paddr->s_addr = inet_addr (c);
205 if (paddr->s_addr == INADDR_NONE)
222 /* a structure for constructing RTSPMessages */
235 build_reset (GstRTSPBuilder * builder)
237 g_free (builder->body_data);
238 memset (builder, 0, sizeof (builder));
242 * gst_rtsp_connection_create:
243 * @url: a #GstRTSPUrl
244 * @conn: storage for a #GstRTSPConnection
246 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
247 * The connection will not yet attempt to connect to @url, use
248 * gst_rtsp_connection_connect().
250 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
253 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
255 GstRTSPConnection *newconn;
261 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
264 error = WSAStartup (0x0202, &w);
269 if (w.wVersion != 0x0202)
273 newconn = g_new0 (GstRTSPConnection, 1);
275 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
279 newconn->fd0.fd = -1;
280 newconn->fd1.fd = -1;
281 newconn->timer = g_timer_new ();
282 newconn->timeout = 60;
283 newconn->tunneled = FALSE;
285 newconn->auth_method = GST_RTSP_AUTH_NONE;
286 newconn->username = NULL;
287 newconn->passwd = NULL;
288 newconn->auth_params = NULL;
298 g_warning ("Error %d on WSAStartup", error);
299 return GST_RTSP_EWSASTART;
303 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
306 return GST_RTSP_EWSAVERSION;
315 return GST_RTSP_ESYS;
320 * gst_rtsp_connection_accept:
322 * @conn: storage for a #GstRTSPConnection
324 * Accept a new connection on @sock and create a new #GstRTSPConnection for
325 * handling communication on new socket.
327 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
332 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
335 unsigned int address_len;
336 GstRTSPConnection *newconn = NULL;
337 struct sockaddr_in address;
343 address_len = sizeof (address);
344 memset (&address, 0, address_len);
347 fd = accept (sock, (struct sockaddr *) &address, &address_len);
349 fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
350 #endif /* G_OS_WIN32 */
354 /* set to non-blocking mode so that we can cancel the communication */
356 fcntl (fd, F_SETFL, O_NONBLOCK);
358 ioctlsocket (fd, FIONBIO, &flags);
359 #endif /* G_OS_WIN32 */
361 /* create a url for the client address */
362 url = g_new0 (GstRTSPUrl, 1);
363 url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
364 url->port = address.sin_port;
366 /* now create the connection object */
367 gst_rtsp_connection_create (url, &newconn);
368 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
370 /* both read and write initially */
371 newconn->readfd = &newconn->fd0;
372 newconn->writefd = &newconn->fd0;
381 return GST_RTSP_ESYS;
386 do_resolve (const gchar * host)
388 struct hostent *hostinfo;
392 struct in_addr *addrp;
395 gchar ipbuf[INET_ADDRSTRLEN];
396 #endif /* G_OS_WIN32 */
400 /* first check if it already is an IP address */
401 if (inet_aton (host, &addr)) {
404 hostinfo = gethostbyname (host);
406 goto not_resolved; /* h_errno set */
408 if (hostinfo->h_addrtype != AF_INET)
409 goto not_ip; /* host not an IP host */
411 addrp = (struct in_addr *) hostinfo->h_addr_list[0];
412 /* this is not threadsafe */
413 ip = inet_ntoa (*addrp);
415 addrs = hostinfo->h_addr_list;
416 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
418 #endif /* G_OS_WIN32 */
425 GST_ERROR ("could not resolve %s", host);
430 GST_ERROR ("not an IP address");
436 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
437 GstPoll * fdset, GTimeVal * timeout)
440 struct sockaddr_in sa_in;
443 unsigned long flags = 1;
444 #endif /* G_OS_WIN32 */
448 memset (&sa_in, 0, sizeof (sa_in));
449 sa_in.sin_family = AF_INET; /* network socket */
450 sa_in.sin_port = htons (port); /* on port */
451 sa_in.sin_addr.s_addr = inet_addr (ip); /* on host ip */
453 fd = socket (AF_INET, SOCK_STREAM, 0);
457 /* set to non-blocking mode so that we can cancel the connect */
459 fcntl (fd, F_SETFL, O_NONBLOCK);
461 ioctlsocket (fd, FIONBIO, &flags);
462 #endif /* G_OS_WIN32 */
464 /* add the socket to our fdset */
465 ADD_POLLFD (fdset, fdout, fd);
467 /* we are going to connect ASYNC now */
468 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
471 if (!ERRNO_IS_EINPROGRESS)
474 /* wait for connect to complete up to the specified timeout or until we got
476 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
478 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
481 retval = gst_poll_wait (fdset, to);
482 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
486 else if (retval == -1)
489 /* we can still have an error connecting on windows */
490 if (gst_poll_fd_has_error (fdset, fdout)) {
491 socklen_t len = sizeof (errno);
493 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
495 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
500 gst_poll_fd_ignored (fdset, fdout);
508 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
509 return GST_RTSP_ESYS;
513 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
514 REMOVE_POLLFD (fdset, fdout);
515 return GST_RTSP_ESYS;
519 GST_ERROR ("timeout");
520 REMOVE_POLLFD (fdset, fdout);
521 return GST_RTSP_ETIMEOUT;
526 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
536 gchar codestr[4], *resultstr;
540 /* create a random sessionid */
541 for (i = 0; i < TUNNELID_LEN; i++)
542 conn->tunnelid[i] = g_random_int_range ('a', 'z');
543 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
548 str = g_strdup_printf ("GET %s%s%s HTTP/1.0\r\n"
549 "x-sessioncookie: %s\r\n"
550 "Accept: application/x-rtsp-tunnelled\r\n"
551 "Pragma: no-cache\r\n"
552 "Cache-Control: no-cache\r\n" "\r\n",
553 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
556 /* we start by writing to this fd */
557 conn->writefd = &conn->fd0;
559 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
561 if (res != GST_RTSP_OK)
564 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
565 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
567 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
575 res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer), NULL);
576 if (res == GST_RTSP_EEOF)
578 if (res == GST_RTSP_OK)
580 if (res != GST_RTSP_EINTR)
584 retval = gst_poll_wait (conn->fdset, to);
585 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
587 /* check for timeout */
599 /* check for last line */
600 if (buffer[0] == '\r')
602 if (buffer[0] == '\0')
606 /* first line, parse response */
607 gchar versionstr[20];
610 bptr = (gchar *) buffer;
612 parse_string (versionstr, sizeof (versionstr), &bptr);
613 parse_string (codestr, sizeof (codestr), &bptr);
614 code = atoi (codestr);
616 while (g_ascii_isspace (*bptr))
627 /* other lines, parse key/value */
628 res = parse_key_value (buffer, key, sizeof (key), &value);
629 if (res == GST_RTSP_OK) {
630 /* we got a new ip address */
631 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
633 conn->ip = g_strdup (value);
640 if (!(ip = do_resolve (conn->ip)))
643 /* get the port from the url */
644 gst_rtsp_url_get_port (conn->url, &port);
646 /* connect to the host/port */
647 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
648 if (res != GST_RTSP_OK)
651 /* this is now our writing socket */
652 conn->writefd = &conn->fd1;
655 str = g_strdup_printf ("POST %s%s%s HTTP/1.0\r\n"
656 "x-sessioncookie: %s\r\n"
657 "Content-Type: application/x-rtsp-tunnelled\r\n"
658 "Pragma: no-cache\r\n"
659 "Cache-Control: no-cache\r\n"
660 "Content-Length: 32767\r\n"
661 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
663 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
666 /* we start by writing to this fd */
667 conn->writefd = &conn->fd1;
669 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
671 if (res != GST_RTSP_OK)
679 GST_ERROR ("write failed", res);
684 return GST_RTSP_EEOF;
692 return GST_RTSP_ETIMEOUT;
696 return GST_RTSP_ESYS;
700 return GST_RTSP_EINTR;
704 GST_ERROR ("got failure response %d %s", code, resultstr);
705 return GST_RTSP_ERROR;
709 GST_ERROR ("could not resolve %s", conn->ip);
710 return GST_RTSP_ENET;
714 GST_ERROR ("failed to connect");
720 * gst_rtsp_connection_connect:
721 * @conn: a #GstRTSPConnection
722 * @timeout: a #GTimeVal timeout
724 * Attempt to connect to the url of @conn made with
725 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
726 * forever. If @timeout contains a valid timeout, this function will return
727 * #GST_RTSP_ETIMEOUT after the timeout expired.
729 * This function can be cancelled with gst_rtsp_connection_flush().
731 * Returns: #GST_RTSP_OK when a connection could be made.
734 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
741 unsigned long flags = 1;
742 #endif /* G_OS_WIN32 */
744 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
745 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
746 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
750 if (!(ip = do_resolve (url->host)))
753 /* get the port from the url */
754 gst_rtsp_url_get_port (url, &port);
756 /* connect to the host/port */
757 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
758 if (res != GST_RTSP_OK)
762 conn->ip = g_strdup (ip);
764 /* this is our read URL */
765 conn->readfd = &conn->fd0;
767 if (conn->tunneled) {
768 res = setup_tunneling (conn, timeout);
769 if (res != GST_RTSP_OK)
770 goto tunneling_failed;
772 conn->writefd = &conn->fd0;
779 GST_ERROR ("could not resolve %s", url->host);
780 return GST_RTSP_ENET;
784 GST_ERROR ("failed to connect");
789 GST_ERROR ("failed to setup tunneling");
795 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
797 static const char hexdigits[] = "0123456789abcdef";
800 for (i = 0; i < 16; i++) {
801 string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
802 string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
808 auth_digest_compute_hex_urp (const gchar * username,
809 const gchar * realm, const gchar * password, gchar hex_urp[33])
811 struct MD5Context md5_context;
812 unsigned char digest[16];
814 MD5Init (&md5_context);
815 MD5Update (&md5_context, username, strlen (username));
816 MD5Update (&md5_context, ":", 1);
817 MD5Update (&md5_context, realm, strlen (realm));
818 MD5Update (&md5_context, ":", 1);
819 MD5Update (&md5_context, password, strlen (password));
820 MD5Final (digest, &md5_context);
821 md5_digest_to_hex_string (digest, hex_urp);
825 auth_digest_compute_response (const gchar * method,
826 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
830 struct MD5Context md5_context;
831 unsigned char digest[16];
834 MD5Init (&md5_context);
835 MD5Update (&md5_context, method, strlen (method));
836 MD5Update (&md5_context, ":", 1);
837 MD5Update (&md5_context, uri, strlen (uri));
838 MD5Final (digest, &md5_context);
839 md5_digest_to_hex_string (digest, hex_a2);
842 MD5Init (&md5_context);
843 MD5Update (&md5_context, hex_a1, strlen (hex_a1));
844 MD5Update (&md5_context, ":", 1);
845 MD5Update (&md5_context, nonce, strlen (nonce));
846 MD5Update (&md5_context, ":", 1);
848 MD5Update (&md5_context, hex_a2, 32);
849 MD5Final (digest, &md5_context);
850 md5_digest_to_hex_string (digest, response);
854 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
856 switch (conn->auth_method) {
857 case GST_RTSP_AUTH_BASIC:{
859 g_strdup_printf ("%s:%s", conn->username, conn->passwd);
861 gst_rtsp_base64_encode (user_pass, strlen (user_pass));
862 gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
864 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
868 g_free (user_pass64);
871 case GST_RTSP_AUTH_DIGEST:{
872 gchar response[33], hex_urp[33];
873 gchar *auth_string, *auth_string2;
880 /* we need to have some params set */
881 if (conn->auth_params == NULL)
884 /* we need the realm and nonce */
885 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
886 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
887 if (realm == NULL || nonce == NULL)
890 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
893 method = gst_rtsp_method_as_text (message->type_data.request.method);
894 uri = message->type_data.request.uri;
896 /* Assume no qop, algorithm=md5, stale=false */
897 /* For algorithm MD5, a1 = urp. */
898 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
899 auth_string = g_strdup_printf ("Digest username=\"%s\", "
900 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
901 conn->username, realm, nonce, uri, response);
903 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
905 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
907 g_free (auth_string);
908 auth_string = auth_string2;
910 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
921 gen_date_string (gchar * date_string, guint len)
929 g_get_current_time (&tv);
930 t = (time_t) tv.tv_sec;
933 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
935 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
940 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
945 return GST_RTSP_ERROR;
952 r = WRITE_SOCKET (fd, &buffer[*idx], left);
954 return GST_RTSP_EINTR;
957 return GST_RTSP_EINTR;
959 return GST_RTSP_ESYS;
969 fill_bytes (gint fd, guint8 * buffer, guint size, DecodeCtx * ctx)
977 while (size > 0 && ctx->cout < 3) {
978 /* we have some leftover bytes */
979 *buffer++ = ctx->out[ctx->cout];
984 /* nothing in the buffer */
988 /* try to read more bytes */
989 r = READ_SOCKET (fd, &ctx->in[ctx->cin], 4 - ctx->cin);
998 r = g_base64_decode_step ((const gchar *) ctx->in, 4,
999 (guchar *) ctx->out, &ctx->state, &ctx->save);
1005 out = READ_SOCKET (fd, buffer, size);
1011 static GstRTSPResult
1012 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1017 return GST_RTSP_ERROR;
1024 r = fill_bytes (fd, &buffer[*idx], left, ctx);
1026 return GST_RTSP_EEOF;
1028 if (ERRNO_IS_EAGAIN)
1029 return GST_RTSP_EINTR;
1030 if (!ERRNO_IS_EINTR)
1031 return GST_RTSP_ESYS;
1040 static GstRTSPResult
1041 read_line (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1047 r = fill_bytes (fd, &c, 1, ctx);
1049 return GST_RTSP_EEOF;
1051 if (ERRNO_IS_EAGAIN)
1052 return GST_RTSP_EINTR;
1053 if (!ERRNO_IS_EINTR)
1054 return GST_RTSP_ESYS;
1056 if (c == '\n') /* end on \n */
1058 if (c == '\r') /* ignore \r */
1061 if (*idx < size - 1)
1062 buffer[(*idx)++] = c;
1065 buffer[*idx] = '\0';
1071 * gst_rtsp_connection_write:
1072 * @conn: a #GstRTSPConnection
1073 * @data: the data to write
1074 * @size: the size of @data
1075 * @timeout: a timeout value or #NULL
1077 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1078 * the specified @timeout. @timeout can be #NULL, in which case this function
1079 * might block forever.
1081 * This function can be cancelled with gst_rtsp_connection_flush().
1083 * Returns: #GST_RTSP_OK on success.
1086 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1087 guint size, GTimeVal * timeout)
1094 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1095 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1096 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1098 gst_poll_set_controllable (conn->fdset, TRUE);
1099 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1100 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1101 /* clear all previous poll results */
1102 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1103 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1105 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1111 res = write_bytes (conn->writefd->fd, data, &offset, size);
1112 if (res == GST_RTSP_OK)
1114 if (res != GST_RTSP_EINTR)
1117 /* not all is written, wait until we can write more */
1119 retval = gst_poll_wait (conn->fdset, to);
1120 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1137 return GST_RTSP_ETIMEOUT;
1141 return GST_RTSP_ESYS;
1145 return GST_RTSP_EINTR;
1154 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1156 GString *str = NULL;
1158 str = g_string_new ("");
1160 switch (message->type) {
1161 case GST_RTSP_MESSAGE_REQUEST:
1162 /* create request string, add CSeq */
1163 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1165 gst_rtsp_method_as_text (message->type_data.request.method),
1166 message->type_data.request.uri, conn->cseq++);
1167 /* add session id if we have one */
1168 if (conn->session_id[0] != '\0') {
1169 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1172 /* add any authentication headers */
1173 add_auth_header (conn, message);
1175 case GST_RTSP_MESSAGE_RESPONSE:
1176 /* create response string */
1177 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1178 message->type_data.response.code, message->type_data.response.reason);
1180 case GST_RTSP_MESSAGE_DATA:
1182 guint8 data_header[4];
1184 /* prepare data header */
1185 data_header[0] = '$';
1186 data_header[1] = message->type_data.data.channel;
1187 data_header[2] = (message->body_size >> 8) & 0xff;
1188 data_header[3] = message->body_size & 0xff;
1190 /* create string with header and data */
1191 str = g_string_append_len (str, (gchar *) data_header, 4);
1193 g_string_append_len (str, (gchar *) message->body,
1194 message->body_size);
1198 g_string_free (str, TRUE);
1199 g_return_val_if_reached (NULL);
1203 /* append headers and body */
1204 if (message->type != GST_RTSP_MESSAGE_DATA) {
1205 gchar date_string[100];
1207 gen_date_string (date_string, sizeof (date_string));
1209 /* add date header */
1210 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1212 /* append headers */
1213 gst_rtsp_message_append_headers (message, str);
1215 /* append Content-Length and body if needed */
1216 if (message->body != NULL && message->body_size > 0) {
1219 len = g_strdup_printf ("%d", message->body_size);
1220 g_string_append_printf (str, "%s: %s\r\n",
1221 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1223 /* header ends here */
1224 g_string_append (str, "\r\n");
1226 g_string_append_len (str, (gchar *) message->body,
1227 message->body_size);
1229 /* just end headers */
1230 g_string_append (str, "\r\n");
1238 * gst_rtsp_connection_send:
1239 * @conn: a #GstRTSPConnection
1240 * @message: the message to send
1241 * @timeout: a timeout value or #NULL
1243 * Attempt to send @message to the connected @conn, blocking up to
1244 * the specified @timeout. @timeout can be #NULL, in which case this function
1245 * might block forever.
1247 * This function can be cancelled with gst_rtsp_connection_flush().
1249 * Returns: #GST_RTSP_OK on success.
1252 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1255 GString *string = NULL;
1260 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1261 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1263 if (!(string = message_to_string (conn, message)))
1266 if (conn->tunneled) {
1267 str = g_base64_encode ((const guchar *) string->str, string->len);
1268 g_string_free (string, TRUE);
1273 g_string_free (string, FALSE);
1277 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1285 g_warning ("Wrong message");
1286 return GST_RTSP_EINVAL;
1291 parse_string (gchar * dest, gint size, gchar ** src)
1297 while (g_ascii_isspace (**src))
1300 while (!g_ascii_isspace (**src) && **src != '\0') {
1302 dest[idx++] = **src;
1310 parse_key (gchar * dest, gint size, gchar ** src)
1315 while (**src != ':' && **src != '\0') {
1317 dest[idx++] = **src;
1324 static GstRTSPResult
1325 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1328 gchar versionstr[20];
1333 bptr = (gchar *) buffer;
1335 parse_string (versionstr, sizeof (versionstr), &bptr);
1336 parse_string (codestr, sizeof (codestr), &bptr);
1337 code = atoi (codestr);
1339 while (g_ascii_isspace (*bptr))
1342 if (strcmp (versionstr, "RTSP/1.0") == 0)
1343 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1345 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1346 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1348 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1356 return GST_RTSP_EPARSE;
1360 static GstRTSPResult
1361 parse_request_line (GstRTSPConnection * conn, guint8 * buffer,
1362 GstRTSPMessage * msg)
1364 GstRTSPResult res = GST_RTSP_OK;
1365 gchar versionstr[20];
1366 gchar methodstr[20];
1369 GstRTSPMethod method;
1370 GstRTSPTunnelState tstate = TUNNEL_STATE_NONE;
1372 bptr = (gchar *) buffer;
1374 parse_string (methodstr, sizeof (methodstr), &bptr);
1375 method = gst_rtsp_find_method (methodstr);
1376 if (method == GST_RTSP_INVALID) {
1377 /* a tunnel request is allowed when we don't have one yet */
1378 if (conn->tstate != TUNNEL_STATE_NONE)
1379 goto invalid_method;
1380 /* we need GET or POST for a valid tunnel request */
1381 if (!strcmp (methodstr, "GET"))
1382 tstate = TUNNEL_STATE_GET;
1383 else if (!strcmp (methodstr, "POST"))
1384 tstate = TUNNEL_STATE_POST;
1386 goto invalid_method;
1389 parse_string (urlstr, sizeof (urlstr), &bptr);
1390 if (*urlstr == '\0')
1393 parse_string (versionstr, sizeof (versionstr), &bptr);
1396 goto invalid_version;
1398 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1399 res = gst_rtsp_message_init_request (msg, method, urlstr);
1400 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1401 res = gst_rtsp_message_init_request (msg, method, urlstr);
1402 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1403 } else if (strcmp (versionstr, "HTTP/1.0") == 0) {
1404 /* tunnel request, we need a tunnel method */
1405 if (tstate == TUNNEL_STATE_NONE) {
1406 res = GST_RTSP_EPARSE;
1408 conn->tstate = tstate;
1411 res = GST_RTSP_EPARSE;
1419 GST_ERROR ("invalid method %s", methodstr);
1420 return GST_RTSP_EPARSE;
1424 GST_ERROR ("invalid url %s", urlstr);
1425 return GST_RTSP_EPARSE;
1429 GST_ERROR ("invalid version");
1430 return GST_RTSP_EPARSE;
1434 static GstRTSPResult
1435 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1439 bptr = (gchar *) buffer;
1442 parse_key (key, keysize, &bptr);
1447 while (g_ascii_isspace (*bptr))
1457 return GST_RTSP_EPARSE;
1461 /* parsing lines means reading a Key: Value pair */
1462 static GstRTSPResult
1463 parse_line (GstRTSPConnection * conn, guint8 * buffer, GstRTSPMessage * msg)
1468 GstRTSPHeaderField field;
1470 res = parse_key_value (buffer, key, sizeof (key), &value);
1471 if (res != GST_RTSP_OK)
1474 if (conn->tstate == TUNNEL_STATE_GET || conn->tstate == TUNNEL_STATE_POST) {
1475 /* save the tunnel session in the connection */
1476 if (!strcmp (key, "x-sessioncookie")) {
1477 strncpy (conn->tunnelid, value, TUNNELID_LEN);
1478 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1479 conn->tunneled = TRUE;
1482 field = gst_rtsp_find_header_field (key);
1483 if (field != GST_RTSP_HDR_INVALID)
1484 gst_rtsp_message_add_header (msg, field, value);
1497 * GST_RTSP_OK when a complete message was read.
1498 * GST_RTSP_EEOF: when the socket is closed
1499 * GST_RTSP_EINTR: when more data is needed.
1500 * GST_RTSP_..: some other error occured.
1502 static GstRTSPResult
1503 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1504 GstRTSPConnection * conn)
1509 switch (builder->state) {
1511 builder->offset = 0;
1513 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1514 &builder->offset, 1, conn->ctxp);
1515 if (res != GST_RTSP_OK)
1518 /* we have 1 bytes now and we can see if this is a data message or
1520 if (builder->buffer[0] == '$') {
1521 /* data message, prepare for the header */
1522 builder->state = STATE_DATA_HEADER;
1525 builder->state = STATE_READ_LINES;
1528 case STATE_DATA_HEADER:
1531 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1532 &builder->offset, 4, conn->ctxp);
1533 if (res != GST_RTSP_OK)
1536 gst_rtsp_message_init_data (message, builder->buffer[1]);
1538 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1539 builder->body_data = g_malloc (builder->body_len + 1);
1540 builder->body_data[builder->body_len] = '\0';
1541 builder->offset = 0;
1542 builder->state = STATE_DATA_BODY;
1545 case STATE_DATA_BODY:
1548 read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1549 builder->body_len, conn->ctxp);
1550 if (res != GST_RTSP_OK)
1553 /* we have the complete body now, store in the message adjusting the
1554 * length to include the traling '\0' */
1555 gst_rtsp_message_take_body (message,
1556 (guint8 *) builder->body_data, builder->body_len + 1);
1557 builder->body_data = NULL;
1558 builder->body_len = 0;
1560 builder->state = STATE_END;
1563 case STATE_READ_LINES:
1565 res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1566 sizeof (builder->buffer), conn->ctxp);
1567 if (res != GST_RTSP_OK)
1570 /* we have a regular response */
1571 if (builder->buffer[0] == '\r') {
1572 builder->buffer[0] = '\0';
1575 if (builder->buffer[0] == '\0') {
1578 /* empty line, end of message header */
1579 /* see if there is a Content-Length header */
1580 if (gst_rtsp_message_get_header (message,
1581 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1582 /* there is, prepare to read the body */
1583 builder->body_len = atol (hdrval);
1584 builder->body_data = g_malloc (builder->body_len + 1);
1585 builder->body_data[builder->body_len] = '\0';
1586 builder->offset = 0;
1587 builder->state = STATE_DATA_BODY;
1589 builder->state = STATE_END;
1594 /* we have a line */
1595 if (builder->line == 0) {
1596 /* first line, check for response status */
1597 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1598 res = parse_response_status (builder->buffer, message);
1600 res = parse_request_line (conn, builder->buffer, message);
1602 /* the first line must parse without errors */
1603 if (res != GST_RTSP_OK)
1606 /* else just parse the line, ignore errors */
1607 parse_line (conn, builder->buffer, message);
1610 builder->offset = 0;
1617 if (conn->tstate == TUNNEL_STATE_GET) {
1618 res = GST_RTSP_ETGET;
1620 } else if (conn->tstate == TUNNEL_STATE_POST) {
1621 res = GST_RTSP_ETPOST;
1625 if (message->type == GST_RTSP_MESSAGE_DATA) {
1626 /* data messages don't have headers */
1631 /* save session id in the connection for further use */
1632 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1633 &session_id, 0) == GST_RTSP_OK) {
1636 maxlen = sizeof (conn->session_id) - 1;
1637 /* the sessionid can have attributes marked with ;
1638 * Make sure we strip them */
1639 for (i = 0; session_id[i] != '\0'; i++) {
1640 if (session_id[i] == ';') {
1645 } while (g_ascii_isspace (session_id[i]));
1646 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1649 /* if we parsed something valid, configure */
1650 if ((to = atoi (&session_id[i + 9])) > 0)
1657 /* make sure to not overflow */
1658 strncpy (conn->session_id, session_id, maxlen);
1659 conn->session_id[maxlen] = '\0';
1665 res = GST_RTSP_ERROR;
1674 * gst_rtsp_connection_read:
1675 * @conn: a #GstRTSPConnection
1676 * @data: the data to read
1677 * @size: the size of @data
1678 * @timeout: a timeout value or #NULL
1680 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1681 * the specified @timeout. @timeout can be #NULL, in which case this function
1682 * might block forever.
1684 * This function can be cancelled with gst_rtsp_connection_flush().
1686 * Returns: #GST_RTSP_OK on success.
1689 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1697 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1698 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1699 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1706 /* configure timeout if any */
1707 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1709 gst_poll_set_controllable (conn->fdset, TRUE);
1710 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1711 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1714 res = read_bytes (conn->readfd->fd, data, &offset, size, conn->ctxp);
1715 if (res == GST_RTSP_EEOF)
1717 if (res == GST_RTSP_OK)
1719 if (res != GST_RTSP_EINTR)
1723 retval = gst_poll_wait (conn->fdset, to);
1724 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1726 /* check for timeout */
1728 goto select_timeout;
1736 gst_poll_set_controllable (conn->fdset, FALSE);
1743 return GST_RTSP_ESYS;
1747 return GST_RTSP_ETIMEOUT;
1751 return GST_RTSP_EINTR;
1755 return GST_RTSP_EEOF;
1764 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code)
1767 gchar date_string[100];
1768 const gchar *status;
1770 gen_date_string (date_string, sizeof (date_string));
1772 status = gst_rtsp_status_as_text (code);
1773 if (status == NULL) {
1775 status = "Internal Server Error";
1778 str = g_string_new ("");
1781 g_string_append_printf (str, "HTTP/1.0 %d %s\r\n", code, status);
1782 g_string_append_printf (str,
1783 "Server: GStreamer RTSP Server\r\n"
1785 "Connection: close\r\n"
1786 "Cache-Control: no-store\r\n" "Pragma: no-cache\r\n", date_string);
1789 g_string_append_printf (str, "x-server-ip-address: %s\r\n", conn->ip);
1790 g_string_append_printf (str,
1791 "Content-Type: application/x-rtsp-tunnelled\r\n" "\r\n");
1797 * gst_rtsp_connection_receive:
1798 * @conn: a #GstRTSPConnection
1799 * @message: the message to read
1800 * @timeout: a timeout value or #NULL
1802 * Attempt to read into @message from the connected @conn, blocking up to
1803 * the specified @timeout. @timeout can be #NULL, in which case this function
1804 * might block forever.
1806 * This function can be cancelled with gst_rtsp_connection_flush().
1808 * Returns: #GST_RTSP_OK on success.
1811 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1815 GstRTSPBuilder builder = { 0 };
1819 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1820 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1821 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1823 /* configure timeout if any */
1824 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1826 gst_poll_set_controllable (conn->fdset, TRUE);
1827 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1828 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1831 res = build_next (&builder, message, conn);
1832 if (res == GST_RTSP_EEOF)
1834 if (res == GST_RTSP_OK)
1836 if (res == GST_RTSP_ETGET) {
1839 /* tunnel GET request, we can reply now */
1840 str = gen_tunnel_reply (conn, GST_RTSP_STS_OK);
1842 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len,
1844 g_string_free (str, TRUE);
1845 } else if (res == GST_RTSP_ETPOST) {
1846 /* tunnel POST request, return the value, the caller now has to link the
1847 * two connections. */
1849 } else if (res != GST_RTSP_EINTR)
1853 retval = gst_poll_wait (conn->fdset, to);
1854 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1856 /* check for timeout */
1858 goto select_timeout;
1866 gst_poll_set_controllable (conn->fdset, FALSE);
1869 /* we have a message here */
1870 build_reset (&builder);
1877 res = GST_RTSP_ESYS;
1882 res = GST_RTSP_ETIMEOUT;
1887 res = GST_RTSP_EINTR;
1892 res = GST_RTSP_EEOF;
1898 build_reset (&builder);
1899 gst_rtsp_message_unset (message);
1905 * gst_rtsp_connection_close:
1906 * @conn: a #GstRTSPConnection
1908 * Close the connected @conn.
1910 * Returns: #GST_RTSP_OK on success.
1913 gst_rtsp_connection_close (GstRTSPConnection * conn)
1915 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1920 REMOVE_POLLFD (conn->fdset, &conn->fd0);
1921 REMOVE_POLLFD (conn->fdset, &conn->fd1);
1922 conn->writefd = NULL;
1923 conn->readfd = NULL;
1929 * gst_rtsp_connection_free:
1930 * @conn: a #GstRTSPConnection
1932 * Close and free @conn.
1934 * Returns: #GST_RTSP_OK on success.
1937 gst_rtsp_connection_free (GstRTSPConnection * conn)
1941 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1943 res = gst_rtsp_connection_close (conn);
1944 gst_poll_free (conn->fdset);
1945 g_timer_destroy (conn->timer);
1946 g_free (conn->username);
1947 g_free (conn->passwd);
1948 gst_rtsp_connection_clear_auth_params (conn);
1958 * gst_rtsp_connection_poll:
1959 * @conn: a #GstRTSPConnection
1960 * @events: a bitmask of #GstRTSPEvent flags to check
1961 * @revents: location for result flags
1962 * @timeout: a timeout
1964 * Wait up to the specified @timeout for the connection to become available for
1965 * at least one of the operations specified in @events. When the function returns
1966 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1969 * @timeout can be #NULL, in which case this function might block forever.
1971 * This function can be cancelled with gst_rtsp_connection_flush().
1973 * Returns: #GST_RTSP_OK on success.
1978 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1979 GstRTSPEvent * revents, GTimeVal * timeout)
1984 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1985 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
1986 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
1987 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1988 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1990 gst_poll_set_controllable (conn->fdset, TRUE);
1992 /* add fd to writer set when asked to */
1993 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
1994 events & GST_RTSP_EV_WRITE);
1996 /* add fd to reader set when asked to */
1997 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
1999 /* configure timeout if any */
2000 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2003 retval = gst_poll_wait (conn->fdset, to);
2004 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2007 goto select_timeout;
2017 if (events & GST_RTSP_EV_READ) {
2018 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2019 *revents |= GST_RTSP_EV_READ;
2021 if (events & GST_RTSP_EV_WRITE) {
2022 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2023 *revents |= GST_RTSP_EV_WRITE;
2030 return GST_RTSP_ETIMEOUT;
2034 return GST_RTSP_ESYS;
2038 return GST_RTSP_EINTR;
2043 * gst_rtsp_connection_next_timeout:
2044 * @conn: a #GstRTSPConnection
2045 * @timeout: a timeout
2047 * Calculate the next timeout for @conn, storing the result in @timeout.
2049 * Returns: #GST_RTSP_OK.
2052 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2058 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2059 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2061 elapsed = g_timer_elapsed (conn->timer, &usec);
2062 if (elapsed >= conn->timeout) {
2066 sec = conn->timeout - elapsed;
2069 timeout->tv_sec = sec;
2070 timeout->tv_usec = usec;
2076 * gst_rtsp_connection_reset_timeout:
2077 * @conn: a #GstRTSPConnection
2079 * Reset the timeout of @conn.
2081 * Returns: #GST_RTSP_OK.
2084 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2086 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2088 g_timer_start (conn->timer);
2094 * gst_rtsp_connection_flush:
2095 * @conn: a #GstRTSPConnection
2096 * @flush: start or stop the flush
2098 * Start or stop the flushing action on @conn. When flushing, all current
2099 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2100 * is set to non-flushing mode again.
2102 * Returns: #GST_RTSP_OK.
2105 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2107 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2109 gst_poll_set_flushing (conn->fdset, flush);
2115 * gst_rtsp_connection_set_auth:
2116 * @conn: a #GstRTSPConnection
2117 * @method: authentication method
2119 * @pass: the password
2121 * Configure @conn for authentication mode @method with @user and @pass as the
2122 * user and password respectively.
2124 * Returns: #GST_RTSP_OK.
2127 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2128 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2130 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2132 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2133 || g_strrstr (user, ":") != NULL))
2134 return GST_RTSP_EINVAL;
2136 /* Make sure the username and passwd are being set for authentication */
2137 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2138 return GST_RTSP_EINVAL;
2140 /* ":" chars are not allowed in usernames for basic auth */
2141 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2142 return GST_RTSP_EINVAL;
2144 g_free (conn->username);
2145 g_free (conn->passwd);
2147 conn->auth_method = method;
2148 conn->username = g_strdup (user);
2149 conn->passwd = g_strdup (pass);
2156 * @key: ASCII string to hash
2158 * Hashes @key in a case-insensitive manner.
2160 * Returns: the hash code.
2163 str_case_hash (gconstpointer key)
2165 const char *p = key;
2166 guint h = g_ascii_toupper (*p);
2169 for (p += 1; *p != '\0'; p++)
2170 h = (h << 5) - h + g_ascii_toupper (*p);
2177 * @v1: an ASCII string
2178 * @v2: another ASCII string
2180 * Compares @v1 and @v2 in a case-insensitive manner
2182 * Returns: %TRUE if they are equal (modulo case)
2185 str_case_equal (gconstpointer v1, gconstpointer v2)
2187 const char *string1 = v1;
2188 const char *string2 = v2;
2190 return g_ascii_strcasecmp (string1, string2) == 0;
2194 * gst_rtsp_connection_set_auth_param:
2195 * @conn: a #GstRTSPConnection
2196 * @param: authentication directive
2199 * Setup @conn with authentication directives. This is not necesary for
2200 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2201 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2202 * in the WWW-Authenticate response header and can include realm, domain,
2203 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2208 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2209 const gchar * param, const gchar * value)
2211 g_return_if_fail (conn != NULL);
2212 g_return_if_fail (param != NULL);
2214 if (conn->auth_params == NULL) {
2216 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2218 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2222 * gst_rtsp_connection_clear_auth_params:
2223 * @conn: a #GstRTSPConnection
2225 * Clear the list of authentication directives stored in @conn.
2230 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2232 g_return_if_fail (conn != NULL);
2234 if (conn->auth_params != NULL) {
2235 g_hash_table_destroy (conn->auth_params);
2236 conn->auth_params = NULL;
2240 static GstRTSPResult
2241 set_qos_dscp (gint fd, guint qos_dscp)
2246 struct sockaddr_in6 sa_in6;
2247 struct sockaddr_storage sa_stor;
2249 socklen_t slen = sizeof (sa);
2256 if (getsockname (fd, &sa.sa, &slen) < 0)
2257 goto no_getsockname;
2259 af = sa.sa.sa_family;
2261 /* if this is an IPv4-mapped address then do IPv4 QoS */
2262 if (af == AF_INET6) {
2263 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2267 /* extract and shift 6 bits of the DSCP */
2268 tos = (qos_dscp & 0x3f) << 2;
2272 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2277 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2291 return GST_RTSP_ESYS;
2296 return GST_RTSP_ERROR;
2301 * gst_rtsp_connection_set_qos_dscp:
2302 * @conn: a #GstRTSPConnection
2303 * @qos_dscp: DSCP value
2305 * Configure @conn to use the specified DSCP value.
2307 * Returns: #GST_RTSP_OK on success.
2312 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2316 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2317 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2318 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2320 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2321 if (res == GST_RTSP_OK)
2322 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2329 * gst_rtsp_connection_get_url:
2330 * @conn: a #GstRTSPConnection
2332 * Retrieve the URL of the other end of @conn.
2334 * Returns: The URL. This value remains valid until the
2335 * connection is closed.
2340 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2342 g_return_val_if_fail (conn != NULL, NULL);
2348 * gst_rtsp_connection_get_ip:
2349 * @conn: a #GstRTSPConnection
2351 * Retrieve the IP address of the other end of @conn.
2353 * Returns: The IP address as a string. this value remains valid until the
2354 * connection is closed.
2359 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2361 g_return_val_if_fail (conn != NULL, NULL);
2367 * gst_rtsp_connection_set_ip:
2368 * @conn: a #GstRTSPConnection
2369 * @ip: an ip address
2371 * Set the IP address of the server.
2376 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2378 g_return_if_fail (conn != NULL);
2381 conn->ip = g_strdup (ip);
2385 * gst_rtsp_connection_set_tunneled:
2386 * @conn: a #GstRTSPConnection
2387 * @tunneled: the new state
2389 * Set the HTTP tunneling state of the connection. This must be configured before
2390 * the @conn is connected.
2395 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2397 g_return_if_fail (conn != NULL);
2398 g_return_if_fail (conn->readfd == NULL);
2399 g_return_if_fail (conn->writefd == NULL);
2401 conn->tunneled = tunneled;
2405 * gst_rtsp_connection_is_tunneled:
2406 * @conn: a #GstRTSPConnection
2408 * Get the tunneling state of the connection.
2410 * Returns: if @conn is using HTTP tunneling.
2415 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2417 g_return_val_if_fail (conn != NULL, FALSE);
2419 return conn->tunneled;
2423 * gst_rtsp_connection_get_tunnelid:
2424 * @conn: a #GstRTSPConnection
2426 * Get the tunnel session id the connection.
2428 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2433 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2435 g_return_val_if_fail (conn != NULL, NULL);
2437 if (!conn->tunneled)
2440 return conn->tunnelid;
2444 * gst_rtsp_connection_do_tunnel:
2445 * @conn: a #GstRTSPConnection
2446 * @conn2: a #GstRTSPConnection
2448 * If @conn received the first tunnel connection and @conn2 received
2449 * the second tunnel connection, link the two connections together so that
2450 * @conn manages the tunneled connection.
2452 * After this call, @conn2 cannot be used anymore and must be freed with
2453 * gst_rtsp_connection_free().
2455 * Returns: return GST_RTSP_OK on success.
2460 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2461 GstRTSPConnection * conn2)
2463 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2464 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2465 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2466 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2467 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2470 /* both connections have fd0 as the read/write socket. start by taking the
2471 * socket from conn2 and set it as the socket in conn */
2472 conn->fd1 = conn2->fd0;
2474 /* clean up some of the state of conn2 */
2475 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2477 conn2->readfd = conn2->writefd = NULL;
2479 /* We make fd0 the write socket and fd1 the read socket. */
2480 conn->writefd = &conn->fd0;
2481 conn->readfd = &conn->fd1;
2483 conn->tstate = TUNNEL_STATE_COMPLETE;
2485 /* we need base64 decoding for the readfd */
2486 conn->ctx.state = 0;
2490 conn->ctxp = &conn->ctx;
2495 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2496 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2504 static GstRTSPRec *queue_response (GstRTSPWatch * watch, GString * str,
2507 /* async functions */
2508 struct _GstRTSPWatch
2512 GstRTSPConnection *conn;
2514 GstRTSPBuilder builder;
2515 GstRTSPMessage message;
2519 gboolean write_added;
2521 /* queued message for transmission */
2528 GstRTSPWatchFuncs funcs;
2531 GDestroyNotify notify;
2535 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2537 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2539 *timeout = (watch->conn->timeout * 1000);
2545 gst_rtsp_source_check (GSource * source)
2547 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2549 if (watch->readfd.revents & READ_COND)
2552 if (watch->writefd.revents & WRITE_COND)
2559 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2562 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2565 /* first read as much as we can */
2566 if (watch->readfd.revents & READ_COND) {
2568 res = build_next (&watch->builder, &watch->message, watch->conn);
2569 if (res == GST_RTSP_EINTR)
2571 if (res == GST_RTSP_EEOF)
2573 if (res == GST_RTSP_ETGET) {
2575 GstRTSPStatusCode code;
2577 if (watch->funcs.tunnel_start)
2578 code = watch->funcs.tunnel_start (watch, watch->user_data);
2580 code = GST_RTSP_STS_OK;
2582 /* queue the response string */
2583 str = gen_tunnel_reply (watch->conn, code);
2584 queue_response (watch, str, -1);
2585 } else if (res == GST_RTSP_ETPOST) {
2586 /* in the callback the connection should be tunneled with the
2588 if (watch->funcs.tunnel_complete)
2589 watch->funcs.tunnel_complete (watch, watch->user_data);
2590 } else if (res != GST_RTSP_OK)
2593 if (res == GST_RTSP_OK) {
2594 if (watch->funcs.message_received)
2595 watch->funcs.message_received (watch, &watch->message,
2598 gst_rtsp_message_unset (&watch->message);
2600 build_reset (&watch->builder);
2604 if (watch->writefd.revents & WRITE_COND) {
2606 if (watch->write_data == NULL) {
2609 if (!watch->messages)
2612 /* no data, get a new message from the queue */
2613 data = watch->messages->data;
2614 watch->messages = g_list_delete_link (watch->messages, watch->messages);
2616 watch->write_off = 0;
2617 watch->write_len = data->str->len;
2618 watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2619 watch->write_cseq = data->cseq;
2621 g_slice_free (GstRTSPRec, data);
2624 res = write_bytes (watch->writefd.fd, watch->write_data,
2625 &watch->write_off, watch->write_len);
2626 if (res == GST_RTSP_EINTR)
2628 if (res != GST_RTSP_OK)
2631 if (watch->funcs.message_sent && watch->write_cseq != -1)
2632 watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2635 if (watch->messages == NULL && watch->write_added) {
2636 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2637 watch->write_added = FALSE;
2638 watch->writefd.revents = 0;
2640 g_free (watch->write_data);
2641 watch->write_data = NULL;
2650 if (watch->funcs.closed)
2651 watch->funcs.closed (watch, watch->user_data);
2656 if (watch->funcs.error)
2657 watch->funcs.error (watch, res, watch->user_data);
2663 gst_rtsp_source_finalize (GSource * source)
2665 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2668 build_reset (&watch->builder);
2670 for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2671 GstRTSPRec *data = walk->data;
2673 g_string_free (data->str, TRUE);
2674 g_slice_free (GstRTSPRec, data);
2676 g_list_free (watch->messages);
2677 g_free (watch->write_data);
2680 watch->notify (watch->user_data);
2683 static GSourceFuncs gst_rtsp_source_funcs = {
2684 gst_rtsp_source_prepare,
2685 gst_rtsp_source_check,
2686 gst_rtsp_source_dispatch,
2687 gst_rtsp_source_finalize
2691 * gst_rtsp_watch_new:
2692 * @conn: a #GstRTSPConnection
2693 * @funcs: watch functions
2694 * @user_data: user data to pass to @funcs
2695 * @notify: notify when @user_data is not referenced anymore
2697 * Create a watch object for @conn. The functions provided in @funcs will be
2698 * called with @user_data when activity happened on the watch.
2700 * The new watch is usually created so that it can be attached to a
2701 * maincontext with gst_rtsp_watch_attach().
2703 * @conn must exist for the entire lifetime of the watch.
2705 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2706 * communication. Free with gst_rtsp_watch_unref () after usage.
2711 gst_rtsp_watch_new (GstRTSPConnection * conn,
2712 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2714 GstRTSPWatch *result;
2716 g_return_val_if_fail (conn != NULL, NULL);
2717 g_return_val_if_fail (funcs != NULL, NULL);
2718 g_return_val_if_fail (conn->readfd != NULL, NULL);
2719 g_return_val_if_fail (conn->writefd != NULL, NULL);
2721 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2722 sizeof (GstRTSPWatch));
2724 result->conn = conn;
2725 result->builder.state = STATE_START;
2727 result->readfd.fd = -1;
2728 result->writefd.fd = -1;
2730 gst_rtsp_watch_reset (result);
2732 result->funcs = *funcs;
2733 result->user_data = user_data;
2734 result->notify = notify;
2736 /* only add the read fd, the write fd is only added when we have data
2738 g_source_add_poll ((GSource *) result, &result->readfd);
2744 * gst_rtsp_watch_reset:
2745 * @watch: a #GstRTSPWatch
2747 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
2748 * when the file descriptors of the connection might have changed.
2753 gst_rtsp_watch_reset (GstRTSPWatch * watch)
2755 if (watch->readfd.fd != -1)
2756 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2757 if (watch->writefd.fd != -1)
2758 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2760 watch->readfd.fd = watch->conn->readfd->fd;
2761 watch->readfd.events = READ_COND;
2762 watch->readfd.revents = 0;
2764 watch->writefd.fd = watch->conn->writefd->fd;
2765 watch->writefd.events = WRITE_COND;
2766 watch->writefd.revents = 0;
2767 watch->write_added = FALSE;
2769 g_source_add_poll ((GSource *) watch, &watch->readfd);
2773 * gst_rtsp_watch_attach:
2774 * @watch: a #GstRTSPWatch
2775 * @context: a GMainContext (if NULL, the default context will be used)
2777 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2779 * Returns: the ID (greater than 0) for the watch within the GMainContext.
2784 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2786 g_return_val_if_fail (watch != NULL, 0);
2788 return g_source_attach ((GSource *) watch, context);
2792 * gst_rtsp_watch_unref:
2793 * @watch: a #GstRTSPWatch
2795 * Decreases the reference count of @watch by one. If the resulting reference
2796 * count is zero the watch and associated memory will be destroyed.
2801 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2803 g_return_if_fail (watch != NULL);
2805 g_source_unref ((GSource *) watch);
2809 queue_response (GstRTSPWatch * watch, GString * str, guint cseq)
2813 /* make a record with the message as a string ans cseq */
2814 data = g_slice_new (GstRTSPRec);
2818 /* add the record to a queue */
2819 watch->messages = g_list_append (watch->messages, data);
2821 /* make sure the main context will now also check for writability on the
2823 if (!watch->write_added) {
2824 g_source_add_poll ((GSource *) watch, &watch->writefd);
2825 watch->write_added = TRUE;
2832 * gst_rtsp_watch_queue_message:
2833 * @watch: a #GstRTSPWatch
2834 * @message: a #GstRTSPMessage
2836 * Queue a @message for transmission in @watch. The contents of this
2837 * message will be serialized and transmitted when the connection of the
2838 * watch becomes writable.
2840 * The return value of this function will be returned as the cseq argument in
2841 * the message_sent callback.
2843 * Returns: the sequence number of the message or -1 if the cseq could not be
2849 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2855 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2856 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2858 /* get the cseq from the message, when we finish writing this message on the
2859 * socket we will have to pass the cseq to the callback. */
2860 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2861 0) == GST_RTSP_OK) {
2862 cseq = atoi (header);
2867 /* make a record with the message as a string ans cseq */
2868 data = queue_response (watch, message_to_string (watch->conn, message), cseq);