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 * A copy of @url will be made.
252 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
255 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
257 GstRTSPConnection *newconn;
263 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
266 error = WSAStartup (0x0202, &w);
271 if (w.wVersion != 0x0202)
275 newconn = g_new0 (GstRTSPConnection, 1);
277 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
280 newconn->url = gst_rtsp_url_copy (url);
281 newconn->fd0.fd = -1;
282 newconn->fd1.fd = -1;
283 newconn->timer = g_timer_new ();
284 newconn->timeout = 60;
286 newconn->auth_method = GST_RTSP_AUTH_NONE;
287 newconn->username = NULL;
288 newconn->passwd = NULL;
289 newconn->auth_params = NULL;
299 g_warning ("Error %d on WSAStartup", error);
300 return GST_RTSP_EWSASTART;
304 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
307 return GST_RTSP_EWSAVERSION;
316 return GST_RTSP_ESYS;
321 * gst_rtsp_connection_accept:
323 * @conn: storage for a #GstRTSPConnection
325 * Accept a new connection on @sock and create a new #GstRTSPConnection for
326 * handling communication on new socket.
328 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
333 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
336 unsigned int address_len;
337 GstRTSPConnection *newconn = NULL;
338 struct sockaddr_in address;
344 address_len = sizeof (address);
345 memset (&address, 0, address_len);
348 fd = accept (sock, (struct sockaddr *) &address, &address_len);
350 fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
351 #endif /* G_OS_WIN32 */
355 /* set to non-blocking mode so that we can cancel the communication */
357 fcntl (fd, F_SETFL, O_NONBLOCK);
359 ioctlsocket (fd, FIONBIO, &flags);
360 #endif /* G_OS_WIN32 */
362 /* create a url for the client address */
363 url = g_new0 (GstRTSPUrl, 1);
364 url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
365 url->port = address.sin_port;
367 /* now create the connection object */
368 gst_rtsp_connection_create (url, &newconn);
369 gst_rtsp_url_free (url);
371 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
373 /* both read and write initially */
374 newconn->readfd = &newconn->fd0;
375 newconn->writefd = &newconn->fd0;
384 return GST_RTSP_ESYS;
389 do_resolve (const gchar * host)
391 struct hostent *hostinfo;
395 struct in_addr *addrp;
398 gchar ipbuf[INET_ADDRSTRLEN];
399 #endif /* G_OS_WIN32 */
403 /* first check if it already is an IP address */
404 if (inet_aton (host, &addr)) {
407 hostinfo = gethostbyname (host);
409 goto not_resolved; /* h_errno set */
411 if (hostinfo->h_addrtype != AF_INET)
412 goto not_ip; /* host not an IP host */
414 addrp = (struct in_addr *) hostinfo->h_addr_list[0];
415 /* this is not threadsafe */
416 ip = inet_ntoa (*addrp);
418 addrs = hostinfo->h_addr_list;
419 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
421 #endif /* G_OS_WIN32 */
428 GST_ERROR ("could not resolve %s", host);
433 GST_ERROR ("not an IP address");
439 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
440 GstPoll * fdset, GTimeVal * timeout)
443 struct sockaddr_in sa_in;
446 unsigned long flags = 1;
447 #endif /* G_OS_WIN32 */
451 memset (&sa_in, 0, sizeof (sa_in));
452 sa_in.sin_family = AF_INET; /* network socket */
453 sa_in.sin_port = htons (port); /* on port */
454 sa_in.sin_addr.s_addr = inet_addr (ip); /* on host ip */
456 fd = socket (AF_INET, SOCK_STREAM, 0);
460 /* set to non-blocking mode so that we can cancel the connect */
462 fcntl (fd, F_SETFL, O_NONBLOCK);
464 ioctlsocket (fd, FIONBIO, &flags);
465 #endif /* G_OS_WIN32 */
467 /* add the socket to our fdset */
468 ADD_POLLFD (fdset, fdout, fd);
470 /* we are going to connect ASYNC now */
471 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
474 if (!ERRNO_IS_EINPROGRESS)
477 /* wait for connect to complete up to the specified timeout or until we got
479 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
481 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
484 retval = gst_poll_wait (fdset, to);
485 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
489 else if (retval == -1)
492 /* we can still have an error connecting on windows */
493 if (gst_poll_fd_has_error (fdset, fdout)) {
494 socklen_t len = sizeof (errno);
496 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
498 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
503 gst_poll_fd_ignored (fdset, fdout);
511 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
512 return GST_RTSP_ESYS;
516 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
517 REMOVE_POLLFD (fdset, fdout);
518 return GST_RTSP_ESYS;
522 GST_ERROR ("timeout");
523 REMOVE_POLLFD (fdset, fdout);
524 return GST_RTSP_ETIMEOUT;
529 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
539 gchar codestr[4], *resultstr;
543 /* create a random sessionid */
544 for (i = 0; i < TUNNELID_LEN; i++)
545 conn->tunnelid[i] = g_random_int_range ('a', 'z');
546 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
551 str = g_strdup_printf ("GET %s%s%s HTTP/1.0\r\n"
552 "x-sessioncookie: %s\r\n"
553 "Accept: application/x-rtsp-tunnelled\r\n"
554 "Pragma: no-cache\r\n"
555 "Cache-Control: no-cache\r\n" "\r\n",
556 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
559 /* we start by writing to this fd */
560 conn->writefd = &conn->fd0;
562 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
564 if (res != GST_RTSP_OK)
567 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
568 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
570 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
578 res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer), NULL);
579 if (res == GST_RTSP_EEOF)
581 if (res == GST_RTSP_OK)
583 if (res != GST_RTSP_EINTR)
587 retval = gst_poll_wait (conn->fdset, to);
588 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
590 /* check for timeout */
602 /* check for last line */
603 if (buffer[0] == '\r')
605 if (buffer[0] == '\0')
609 /* first line, parse response */
610 gchar versionstr[20];
613 bptr = (gchar *) buffer;
615 parse_string (versionstr, sizeof (versionstr), &bptr);
616 parse_string (codestr, sizeof (codestr), &bptr);
617 code = atoi (codestr);
619 while (g_ascii_isspace (*bptr))
630 /* other lines, parse key/value */
631 res = parse_key_value (buffer, key, sizeof (key), &value);
632 if (res == GST_RTSP_OK) {
633 /* we got a new ip address */
634 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
636 conn->ip = g_strdup (value);
643 if (!(ip = do_resolve (conn->ip)))
646 /* get the port from the url */
647 gst_rtsp_url_get_port (conn->url, &port);
649 /* connect to the host/port */
650 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
651 if (res != GST_RTSP_OK)
654 /* this is now our writing socket */
655 conn->writefd = &conn->fd1;
658 str = g_strdup_printf ("POST %s%s%s HTTP/1.0\r\n"
659 "x-sessioncookie: %s\r\n"
660 "Content-Type: application/x-rtsp-tunnelled\r\n"
661 "Pragma: no-cache\r\n"
662 "Cache-Control: no-cache\r\n"
663 "Content-Length: 32767\r\n"
664 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
666 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
669 /* we start by writing to this fd */
670 conn->writefd = &conn->fd1;
672 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
674 if (res != GST_RTSP_OK)
682 GST_ERROR ("write failed (%d)", res);
687 return GST_RTSP_EEOF;
695 return GST_RTSP_ETIMEOUT;
699 return GST_RTSP_ESYS;
703 return GST_RTSP_EINTR;
707 GST_ERROR ("got failure response %d %s", code, resultstr);
708 return GST_RTSP_ERROR;
712 GST_ERROR ("could not resolve %s", conn->ip);
713 return GST_RTSP_ENET;
717 GST_ERROR ("failed to connect");
723 * gst_rtsp_connection_connect:
724 * @conn: a #GstRTSPConnection
725 * @timeout: a #GTimeVal timeout
727 * Attempt to connect to the url of @conn made with
728 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
729 * forever. If @timeout contains a valid timeout, this function will return
730 * #GST_RTSP_ETIMEOUT after the timeout expired.
732 * This function can be cancelled with gst_rtsp_connection_flush().
734 * Returns: #GST_RTSP_OK when a connection could be made.
737 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
744 unsigned long flags = 1;
745 #endif /* G_OS_WIN32 */
747 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
748 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
749 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
753 if (!(ip = do_resolve (url->host)))
756 /* get the port from the url */
757 gst_rtsp_url_get_port (url, &port);
759 /* connect to the host/port */
760 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
761 if (res != GST_RTSP_OK)
765 conn->ip = g_strdup (ip);
767 /* this is our read URL */
768 conn->readfd = &conn->fd0;
770 if (conn->tunneled) {
771 res = setup_tunneling (conn, timeout);
772 if (res != GST_RTSP_OK)
773 goto tunneling_failed;
775 conn->writefd = &conn->fd0;
782 GST_ERROR ("could not resolve %s", url->host);
783 return GST_RTSP_ENET;
787 GST_ERROR ("failed to connect");
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:{
862 g_strdup_printf ("%s:%s", conn->username, conn->passwd);
864 gst_rtsp_base64_encode (user_pass, strlen (user_pass));
865 gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
867 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
871 g_free (user_pass64);
874 case GST_RTSP_AUTH_DIGEST:{
875 gchar response[33], hex_urp[33];
876 gchar *auth_string, *auth_string2;
883 /* we need to have some params set */
884 if (conn->auth_params == NULL)
887 /* we need the realm and nonce */
888 realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
889 nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
890 if (realm == NULL || nonce == NULL)
893 auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
896 method = gst_rtsp_method_as_text (message->type_data.request.method);
897 uri = message->type_data.request.uri;
899 /* Assume no qop, algorithm=md5, stale=false */
900 /* For algorithm MD5, a1 = urp. */
901 auth_digest_compute_response (method, uri, hex_urp, nonce, response);
902 auth_string = g_strdup_printf ("Digest username=\"%s\", "
903 "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
904 conn->username, realm, nonce, uri, response);
906 opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
908 auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
910 g_free (auth_string);
911 auth_string = auth_string2;
913 gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
924 gen_date_string (gchar * date_string, guint len)
932 g_get_current_time (&tv);
933 t = (time_t) tv.tv_sec;
936 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r (&t, &tm_));
938 strftime (date_string, len, "%a, %d %b %Y %H:%M:%S GMT", gmtime (&t));
943 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
948 return GST_RTSP_ERROR;
955 r = WRITE_SOCKET (fd, &buffer[*idx], left);
957 return GST_RTSP_EINTR;
960 return GST_RTSP_EINTR;
962 return GST_RTSP_ESYS;
972 fill_bytes (gint fd, guint8 * buffer, guint size, DecodeCtx * ctx)
980 while (size > 0 && ctx->cout < 3) {
981 /* we have some leftover bytes */
982 *buffer++ = ctx->out[ctx->cout];
987 /* nothing in the buffer */
991 /* try to read more bytes */
992 r = READ_SOCKET (fd, &ctx->in[ctx->cin], 4 - ctx->cin);
1000 if (ctx->cin == 4) {
1001 r = g_base64_decode_step ((const gchar *) ctx->in, 4,
1002 (guchar *) ctx->out, &ctx->state, &ctx->save);
1008 out = READ_SOCKET (fd, buffer, size);
1014 static GstRTSPResult
1015 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1020 return GST_RTSP_ERROR;
1027 r = fill_bytes (fd, &buffer[*idx], left, ctx);
1029 return GST_RTSP_EEOF;
1031 if (ERRNO_IS_EAGAIN)
1032 return GST_RTSP_EINTR;
1033 if (!ERRNO_IS_EINTR)
1034 return GST_RTSP_ESYS;
1043 static GstRTSPResult
1044 read_line (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1050 r = fill_bytes (fd, &c, 1, ctx);
1052 return GST_RTSP_EEOF;
1054 if (ERRNO_IS_EAGAIN)
1055 return GST_RTSP_EINTR;
1056 if (!ERRNO_IS_EINTR)
1057 return GST_RTSP_ESYS;
1059 if (c == '\n') /* end on \n */
1061 if (c == '\r') /* ignore \r */
1064 if (*idx < size - 1)
1065 buffer[(*idx)++] = c;
1068 buffer[*idx] = '\0';
1074 * gst_rtsp_connection_write:
1075 * @conn: a #GstRTSPConnection
1076 * @data: the data to write
1077 * @size: the size of @data
1078 * @timeout: a timeout value or #NULL
1080 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1081 * the specified @timeout. @timeout can be #NULL, in which case this function
1082 * might block forever.
1084 * This function can be cancelled with gst_rtsp_connection_flush().
1086 * Returns: #GST_RTSP_OK on success.
1089 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1090 guint size, GTimeVal * timeout)
1097 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1098 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1099 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1101 gst_poll_set_controllable (conn->fdset, TRUE);
1102 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1103 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1104 /* clear all previous poll results */
1105 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1106 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1108 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1114 res = write_bytes (conn->writefd->fd, data, &offset, size);
1115 if (res == GST_RTSP_OK)
1117 if (res != GST_RTSP_EINTR)
1120 /* not all is written, wait until we can write more */
1122 retval = gst_poll_wait (conn->fdset, to);
1123 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1140 return GST_RTSP_ETIMEOUT;
1144 return GST_RTSP_ESYS;
1148 return GST_RTSP_EINTR;
1157 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1159 GString *str = NULL;
1161 str = g_string_new ("");
1163 switch (message->type) {
1164 case GST_RTSP_MESSAGE_REQUEST:
1165 /* create request string, add CSeq */
1166 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1168 gst_rtsp_method_as_text (message->type_data.request.method),
1169 message->type_data.request.uri, conn->cseq++);
1170 /* add session id if we have one */
1171 if (conn->session_id[0] != '\0') {
1172 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1175 /* add any authentication headers */
1176 add_auth_header (conn, message);
1178 case GST_RTSP_MESSAGE_RESPONSE:
1179 /* create response string */
1180 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1181 message->type_data.response.code, message->type_data.response.reason);
1183 case GST_RTSP_MESSAGE_DATA:
1185 guint8 data_header[4];
1187 /* prepare data header */
1188 data_header[0] = '$';
1189 data_header[1] = message->type_data.data.channel;
1190 data_header[2] = (message->body_size >> 8) & 0xff;
1191 data_header[3] = message->body_size & 0xff;
1193 /* create string with header and data */
1194 str = g_string_append_len (str, (gchar *) data_header, 4);
1196 g_string_append_len (str, (gchar *) message->body,
1197 message->body_size);
1201 g_string_free (str, TRUE);
1202 g_return_val_if_reached (NULL);
1206 /* append headers and body */
1207 if (message->type != GST_RTSP_MESSAGE_DATA) {
1208 gchar date_string[100];
1210 gen_date_string (date_string, sizeof (date_string));
1212 /* add date header */
1213 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1215 /* append headers */
1216 gst_rtsp_message_append_headers (message, str);
1218 /* append Content-Length and body if needed */
1219 if (message->body != NULL && message->body_size > 0) {
1222 len = g_strdup_printf ("%d", message->body_size);
1223 g_string_append_printf (str, "%s: %s\r\n",
1224 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1226 /* header ends here */
1227 g_string_append (str, "\r\n");
1229 g_string_append_len (str, (gchar *) message->body,
1230 message->body_size);
1232 /* just end headers */
1233 g_string_append (str, "\r\n");
1241 * gst_rtsp_connection_send:
1242 * @conn: a #GstRTSPConnection
1243 * @message: the message to send
1244 * @timeout: a timeout value or #NULL
1246 * Attempt to send @message to the connected @conn, blocking up to
1247 * the specified @timeout. @timeout can be #NULL, in which case this function
1248 * might block forever.
1250 * This function can be cancelled with gst_rtsp_connection_flush().
1252 * Returns: #GST_RTSP_OK on success.
1255 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1258 GString *string = NULL;
1263 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1264 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1266 if (!(string = message_to_string (conn, message)))
1269 if (conn->tunneled) {
1270 str = g_base64_encode ((const guchar *) string->str, string->len);
1271 g_string_free (string, TRUE);
1276 g_string_free (string, FALSE);
1280 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1288 g_warning ("Wrong message");
1289 return GST_RTSP_EINVAL;
1294 parse_string (gchar * dest, gint size, gchar ** src)
1300 while (g_ascii_isspace (**src))
1303 while (!g_ascii_isspace (**src) && **src != '\0') {
1305 dest[idx++] = **src;
1313 parse_key (gchar * dest, gint size, gchar ** src)
1318 while (**src != ':' && **src != '\0') {
1320 dest[idx++] = **src;
1327 static GstRTSPResult
1328 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1331 gchar versionstr[20];
1336 bptr = (gchar *) buffer;
1338 parse_string (versionstr, sizeof (versionstr), &bptr);
1339 parse_string (codestr, sizeof (codestr), &bptr);
1340 code = atoi (codestr);
1342 while (g_ascii_isspace (*bptr))
1345 if (strcmp (versionstr, "RTSP/1.0") == 0)
1346 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1348 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1349 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1351 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1359 return GST_RTSP_EPARSE;
1363 static GstRTSPResult
1364 parse_request_line (GstRTSPConnection * conn, guint8 * buffer,
1365 GstRTSPMessage * msg)
1367 GstRTSPResult res = GST_RTSP_OK;
1368 gchar versionstr[20];
1369 gchar methodstr[20];
1372 GstRTSPMethod method;
1373 GstRTSPTunnelState tstate = TUNNEL_STATE_NONE;
1375 bptr = (gchar *) buffer;
1377 parse_string (methodstr, sizeof (methodstr), &bptr);
1378 method = gst_rtsp_find_method (methodstr);
1379 if (method == GST_RTSP_INVALID) {
1380 /* a tunnel request is allowed when we don't have one yet */
1381 if (conn->tstate != TUNNEL_STATE_NONE)
1382 goto invalid_method;
1383 /* we need GET or POST for a valid tunnel request */
1384 if (!strcmp (methodstr, "GET"))
1385 tstate = TUNNEL_STATE_GET;
1386 else if (!strcmp (methodstr, "POST"))
1387 tstate = TUNNEL_STATE_POST;
1389 goto invalid_method;
1392 parse_string (urlstr, sizeof (urlstr), &bptr);
1393 if (*urlstr == '\0')
1396 parse_string (versionstr, sizeof (versionstr), &bptr);
1399 goto invalid_version;
1401 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1402 res = gst_rtsp_message_init_request (msg, method, urlstr);
1403 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1404 res = gst_rtsp_message_init_request (msg, method, urlstr);
1405 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1406 } else if (strcmp (versionstr, "HTTP/1.0") == 0) {
1407 /* tunnel request, we need a tunnel method */
1408 if (tstate == TUNNEL_STATE_NONE) {
1409 res = GST_RTSP_EPARSE;
1411 conn->tstate = tstate;
1414 res = GST_RTSP_EPARSE;
1422 GST_ERROR ("invalid method %s", methodstr);
1423 return GST_RTSP_EPARSE;
1427 GST_ERROR ("invalid url %s", urlstr);
1428 return GST_RTSP_EPARSE;
1432 GST_ERROR ("invalid version");
1433 return GST_RTSP_EPARSE;
1437 static GstRTSPResult
1438 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1442 bptr = (gchar *) buffer;
1445 parse_key (key, keysize, &bptr);
1450 while (g_ascii_isspace (*bptr))
1460 return GST_RTSP_EPARSE;
1464 /* parsing lines means reading a Key: Value pair */
1465 static GstRTSPResult
1466 parse_line (GstRTSPConnection * conn, guint8 * buffer, GstRTSPMessage * msg)
1471 GstRTSPHeaderField field;
1473 res = parse_key_value (buffer, key, sizeof (key), &value);
1474 if (res != GST_RTSP_OK)
1477 if (conn->tstate == TUNNEL_STATE_GET || conn->tstate == TUNNEL_STATE_POST) {
1478 /* save the tunnel session in the connection */
1479 if (!strcmp (key, "x-sessioncookie")) {
1480 strncpy (conn->tunnelid, value, TUNNELID_LEN);
1481 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1482 conn->tunneled = TRUE;
1485 field = gst_rtsp_find_header_field (key);
1486 if (field != GST_RTSP_HDR_INVALID)
1487 gst_rtsp_message_add_header (msg, field, value);
1500 * GST_RTSP_OK when a complete message was read.
1501 * GST_RTSP_EEOF: when the socket is closed
1502 * GST_RTSP_EINTR: when more data is needed.
1503 * GST_RTSP_..: some other error occured.
1505 static GstRTSPResult
1506 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1507 GstRTSPConnection * conn)
1512 switch (builder->state) {
1514 builder->offset = 0;
1516 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1517 &builder->offset, 1, conn->ctxp);
1518 if (res != GST_RTSP_OK)
1521 /* we have 1 bytes now and we can see if this is a data message or
1523 if (builder->buffer[0] == '$') {
1524 /* data message, prepare for the header */
1525 builder->state = STATE_DATA_HEADER;
1528 builder->state = STATE_READ_LINES;
1531 case STATE_DATA_HEADER:
1534 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1535 &builder->offset, 4, conn->ctxp);
1536 if (res != GST_RTSP_OK)
1539 gst_rtsp_message_init_data (message, builder->buffer[1]);
1541 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1542 builder->body_data = g_malloc (builder->body_len + 1);
1543 builder->body_data[builder->body_len] = '\0';
1544 builder->offset = 0;
1545 builder->state = STATE_DATA_BODY;
1548 case STATE_DATA_BODY:
1551 read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1552 builder->body_len, conn->ctxp);
1553 if (res != GST_RTSP_OK)
1556 /* we have the complete body now, store in the message adjusting the
1557 * length to include the traling '\0' */
1558 gst_rtsp_message_take_body (message,
1559 (guint8 *) builder->body_data, builder->body_len + 1);
1560 builder->body_data = NULL;
1561 builder->body_len = 0;
1563 builder->state = STATE_END;
1566 case STATE_READ_LINES:
1568 res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1569 sizeof (builder->buffer), conn->ctxp);
1570 if (res != GST_RTSP_OK)
1573 /* we have a regular response */
1574 if (builder->buffer[0] == '\r') {
1575 builder->buffer[0] = '\0';
1578 if (builder->buffer[0] == '\0') {
1581 /* empty line, end of message header */
1582 /* see if there is a Content-Length header */
1583 if (gst_rtsp_message_get_header (message,
1584 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1585 /* there is, prepare to read the body */
1586 builder->body_len = atol (hdrval);
1587 builder->body_data = g_malloc (builder->body_len + 1);
1588 builder->body_data[builder->body_len] = '\0';
1589 builder->offset = 0;
1590 builder->state = STATE_DATA_BODY;
1592 builder->state = STATE_END;
1597 /* we have a line */
1598 if (builder->line == 0) {
1599 /* first line, check for response status */
1600 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1601 res = parse_response_status (builder->buffer, message);
1603 res = parse_request_line (conn, builder->buffer, message);
1605 /* the first line must parse without errors */
1606 if (res != GST_RTSP_OK)
1609 /* else just parse the line, ignore errors */
1610 parse_line (conn, builder->buffer, message);
1613 builder->offset = 0;
1620 if (conn->tstate == TUNNEL_STATE_GET) {
1621 res = GST_RTSP_ETGET;
1623 } else if (conn->tstate == TUNNEL_STATE_POST) {
1624 res = GST_RTSP_ETPOST;
1628 if (message->type == GST_RTSP_MESSAGE_DATA) {
1629 /* data messages don't have headers */
1634 /* save session id in the connection for further use */
1635 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1636 &session_id, 0) == GST_RTSP_OK) {
1639 maxlen = sizeof (conn->session_id) - 1;
1640 /* the sessionid can have attributes marked with ;
1641 * Make sure we strip them */
1642 for (i = 0; session_id[i] != '\0'; i++) {
1643 if (session_id[i] == ';') {
1648 } while (g_ascii_isspace (session_id[i]));
1649 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1652 /* if we parsed something valid, configure */
1653 if ((to = atoi (&session_id[i + 9])) > 0)
1660 /* make sure to not overflow */
1661 strncpy (conn->session_id, session_id, maxlen);
1662 conn->session_id[maxlen] = '\0';
1668 res = GST_RTSP_ERROR;
1677 * gst_rtsp_connection_read:
1678 * @conn: a #GstRTSPConnection
1679 * @data: the data to read
1680 * @size: the size of @data
1681 * @timeout: a timeout value or #NULL
1683 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1684 * the specified @timeout. @timeout can be #NULL, in which case this function
1685 * might block forever.
1687 * This function can be cancelled with gst_rtsp_connection_flush().
1689 * Returns: #GST_RTSP_OK on success.
1692 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1700 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1701 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1702 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1709 /* configure timeout if any */
1710 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1712 gst_poll_set_controllable (conn->fdset, TRUE);
1713 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1714 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1717 res = read_bytes (conn->readfd->fd, data, &offset, size, conn->ctxp);
1718 if (res == GST_RTSP_EEOF)
1720 if (res == GST_RTSP_OK)
1722 if (res != GST_RTSP_EINTR)
1726 retval = gst_poll_wait (conn->fdset, to);
1727 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1729 /* check for timeout */
1731 goto select_timeout;
1739 gst_poll_set_controllable (conn->fdset, FALSE);
1746 return GST_RTSP_ESYS;
1750 return GST_RTSP_ETIMEOUT;
1754 return GST_RTSP_EINTR;
1758 return GST_RTSP_EEOF;
1767 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code)
1770 gchar date_string[100];
1771 const gchar *status;
1773 gen_date_string (date_string, sizeof (date_string));
1775 status = gst_rtsp_status_as_text (code);
1776 if (status == NULL) {
1778 status = "Internal Server Error";
1781 str = g_string_new ("");
1784 g_string_append_printf (str, "HTTP/1.0 %d %s\r\n", code, status);
1785 g_string_append_printf (str,
1786 "Server: GStreamer RTSP Server\r\n"
1788 "Connection: close\r\n"
1789 "Cache-Control: no-store\r\n" "Pragma: no-cache\r\n", date_string);
1792 g_string_append_printf (str, "x-server-ip-address: %s\r\n", conn->ip);
1793 g_string_append_printf (str,
1794 "Content-Type: application/x-rtsp-tunnelled\r\n" "\r\n");
1800 * gst_rtsp_connection_receive:
1801 * @conn: a #GstRTSPConnection
1802 * @message: the message to read
1803 * @timeout: a timeout value or #NULL
1805 * Attempt to read into @message from the connected @conn, blocking up to
1806 * the specified @timeout. @timeout can be #NULL, in which case this function
1807 * might block forever.
1809 * This function can be cancelled with gst_rtsp_connection_flush().
1811 * Returns: #GST_RTSP_OK on success.
1814 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1818 GstRTSPBuilder builder = { 0 };
1822 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1823 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1824 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1826 /* configure timeout if any */
1827 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1829 gst_poll_set_controllable (conn->fdset, TRUE);
1830 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1831 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1834 res = build_next (&builder, message, conn);
1835 if (res == GST_RTSP_EEOF)
1837 if (res == GST_RTSP_OK)
1839 if (res == GST_RTSP_ETGET) {
1842 /* tunnel GET request, we can reply now */
1843 str = gen_tunnel_reply (conn, GST_RTSP_STS_OK);
1845 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len,
1847 g_string_free (str, TRUE);
1848 } else if (res == GST_RTSP_ETPOST) {
1849 /* tunnel POST request, return the value, the caller now has to link the
1850 * two connections. */
1852 } else if (res != GST_RTSP_EINTR)
1856 retval = gst_poll_wait (conn->fdset, to);
1857 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1859 /* check for timeout */
1861 goto select_timeout;
1869 gst_poll_set_controllable (conn->fdset, FALSE);
1872 /* we have a message here */
1873 build_reset (&builder);
1880 res = GST_RTSP_ESYS;
1885 res = GST_RTSP_ETIMEOUT;
1890 res = GST_RTSP_EINTR;
1895 res = GST_RTSP_EEOF;
1901 build_reset (&builder);
1902 gst_rtsp_message_unset (message);
1908 * gst_rtsp_connection_close:
1909 * @conn: a #GstRTSPConnection
1911 * Close the connected @conn. After this call, the connection is in the same
1912 * state as when it was first created.
1914 * Returns: #GST_RTSP_OK on success.
1917 gst_rtsp_connection_close (GstRTSPConnection * conn)
1919 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1924 REMOVE_POLLFD (conn->fdset, &conn->fd0);
1925 REMOVE_POLLFD (conn->fdset, &conn->fd1);
1926 conn->writefd = NULL;
1927 conn->readfd = NULL;
1928 conn->tunneled = FALSE;
1929 conn->tstate = TUNNEL_STATE_NONE;
1931 g_free (conn->username);
1932 conn->username = NULL;
1933 g_free (conn->passwd);
1934 conn->passwd = NULL;
1935 gst_rtsp_connection_clear_auth_params (conn);
1938 conn->session_id[0] = '\0';
1944 * gst_rtsp_connection_free:
1945 * @conn: a #GstRTSPConnection
1947 * Close and free @conn.
1949 * Returns: #GST_RTSP_OK on success.
1952 gst_rtsp_connection_free (GstRTSPConnection * conn)
1956 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1958 res = gst_rtsp_connection_close (conn);
1959 gst_poll_free (conn->fdset);
1960 g_timer_destroy (conn->timer);
1961 gst_rtsp_url_free (conn->url);
1971 * gst_rtsp_connection_poll:
1972 * @conn: a #GstRTSPConnection
1973 * @events: a bitmask of #GstRTSPEvent flags to check
1974 * @revents: location for result flags
1975 * @timeout: a timeout
1977 * Wait up to the specified @timeout for the connection to become available for
1978 * at least one of the operations specified in @events. When the function returns
1979 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1982 * @timeout can be #NULL, in which case this function might block forever.
1984 * This function can be cancelled with gst_rtsp_connection_flush().
1986 * Returns: #GST_RTSP_OK on success.
1991 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1992 GstRTSPEvent * revents, GTimeVal * timeout)
1997 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1998 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
1999 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2000 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2001 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2003 gst_poll_set_controllable (conn->fdset, TRUE);
2005 /* add fd to writer set when asked to */
2006 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2007 events & GST_RTSP_EV_WRITE);
2009 /* add fd to reader set when asked to */
2010 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2012 /* configure timeout if any */
2013 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2016 retval = gst_poll_wait (conn->fdset, to);
2017 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2020 goto select_timeout;
2030 if (events & GST_RTSP_EV_READ) {
2031 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2032 *revents |= GST_RTSP_EV_READ;
2034 if (events & GST_RTSP_EV_WRITE) {
2035 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2036 *revents |= GST_RTSP_EV_WRITE;
2043 return GST_RTSP_ETIMEOUT;
2047 return GST_RTSP_ESYS;
2051 return GST_RTSP_EINTR;
2056 * gst_rtsp_connection_next_timeout:
2057 * @conn: a #GstRTSPConnection
2058 * @timeout: a timeout
2060 * Calculate the next timeout for @conn, storing the result in @timeout.
2062 * Returns: #GST_RTSP_OK.
2065 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2071 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2072 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2074 elapsed = g_timer_elapsed (conn->timer, &usec);
2075 if (elapsed >= conn->timeout) {
2079 sec = conn->timeout - elapsed;
2082 timeout->tv_sec = sec;
2083 timeout->tv_usec = usec;
2089 * gst_rtsp_connection_reset_timeout:
2090 * @conn: a #GstRTSPConnection
2092 * Reset the timeout of @conn.
2094 * Returns: #GST_RTSP_OK.
2097 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2099 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2101 g_timer_start (conn->timer);
2107 * gst_rtsp_connection_flush:
2108 * @conn: a #GstRTSPConnection
2109 * @flush: start or stop the flush
2111 * Start or stop the flushing action on @conn. When flushing, all current
2112 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2113 * is set to non-flushing mode again.
2115 * Returns: #GST_RTSP_OK.
2118 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2120 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2122 gst_poll_set_flushing (conn->fdset, flush);
2128 * gst_rtsp_connection_set_auth:
2129 * @conn: a #GstRTSPConnection
2130 * @method: authentication method
2132 * @pass: the password
2134 * Configure @conn for authentication mode @method with @user and @pass as the
2135 * user and password respectively.
2137 * Returns: #GST_RTSP_OK.
2140 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2141 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2143 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2145 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2146 || g_strrstr (user, ":") != NULL))
2147 return GST_RTSP_EINVAL;
2149 /* Make sure the username and passwd are being set for authentication */
2150 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2151 return GST_RTSP_EINVAL;
2153 /* ":" chars are not allowed in usernames for basic auth */
2154 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2155 return GST_RTSP_EINVAL;
2157 g_free (conn->username);
2158 g_free (conn->passwd);
2160 conn->auth_method = method;
2161 conn->username = g_strdup (user);
2162 conn->passwd = g_strdup (pass);
2169 * @key: ASCII string to hash
2171 * Hashes @key in a case-insensitive manner.
2173 * Returns: the hash code.
2176 str_case_hash (gconstpointer key)
2178 const char *p = key;
2179 guint h = g_ascii_toupper (*p);
2182 for (p += 1; *p != '\0'; p++)
2183 h = (h << 5) - h + g_ascii_toupper (*p);
2190 * @v1: an ASCII string
2191 * @v2: another ASCII string
2193 * Compares @v1 and @v2 in a case-insensitive manner
2195 * Returns: %TRUE if they are equal (modulo case)
2198 str_case_equal (gconstpointer v1, gconstpointer v2)
2200 const char *string1 = v1;
2201 const char *string2 = v2;
2203 return g_ascii_strcasecmp (string1, string2) == 0;
2207 * gst_rtsp_connection_set_auth_param:
2208 * @conn: a #GstRTSPConnection
2209 * @param: authentication directive
2212 * Setup @conn with authentication directives. This is not necesary for
2213 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2214 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2215 * in the WWW-Authenticate response header and can include realm, domain,
2216 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2221 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2222 const gchar * param, const gchar * value)
2224 g_return_if_fail (conn != NULL);
2225 g_return_if_fail (param != NULL);
2227 if (conn->auth_params == NULL) {
2229 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2231 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2235 * gst_rtsp_connection_clear_auth_params:
2236 * @conn: a #GstRTSPConnection
2238 * Clear the list of authentication directives stored in @conn.
2243 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2245 g_return_if_fail (conn != NULL);
2247 if (conn->auth_params != NULL) {
2248 g_hash_table_destroy (conn->auth_params);
2249 conn->auth_params = NULL;
2253 static GstRTSPResult
2254 set_qos_dscp (gint fd, guint qos_dscp)
2259 struct sockaddr_in6 sa_in6;
2260 struct sockaddr_storage sa_stor;
2262 socklen_t slen = sizeof (sa);
2269 if (getsockname (fd, &sa.sa, &slen) < 0)
2270 goto no_getsockname;
2272 af = sa.sa.sa_family;
2274 /* if this is an IPv4-mapped address then do IPv4 QoS */
2275 if (af == AF_INET6) {
2276 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2280 /* extract and shift 6 bits of the DSCP */
2281 tos = (qos_dscp & 0x3f) << 2;
2285 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2290 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2304 return GST_RTSP_ESYS;
2309 return GST_RTSP_ERROR;
2314 * gst_rtsp_connection_set_qos_dscp:
2315 * @conn: a #GstRTSPConnection
2316 * @qos_dscp: DSCP value
2318 * Configure @conn to use the specified DSCP value.
2320 * Returns: #GST_RTSP_OK on success.
2325 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2329 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2330 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2331 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2333 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2334 if (res == GST_RTSP_OK)
2335 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2342 * gst_rtsp_connection_get_url:
2343 * @conn: a #GstRTSPConnection
2345 * Retrieve the URL of the other end of @conn.
2347 * Returns: The URL. This value remains valid until the
2348 * connection is freed.
2353 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2355 g_return_val_if_fail (conn != NULL, NULL);
2361 * gst_rtsp_connection_get_ip:
2362 * @conn: a #GstRTSPConnection
2364 * Retrieve the IP address of the other end of @conn.
2366 * Returns: The IP address as a string. this value remains valid until the
2367 * connection is closed.
2372 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2374 g_return_val_if_fail (conn != NULL, NULL);
2380 * gst_rtsp_connection_set_ip:
2381 * @conn: a #GstRTSPConnection
2382 * @ip: an ip address
2384 * Set the IP address of the server.
2389 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2391 g_return_if_fail (conn != NULL);
2394 conn->ip = g_strdup (ip);
2398 * gst_rtsp_connection_set_tunneled:
2399 * @conn: a #GstRTSPConnection
2400 * @tunneled: the new state
2402 * Set the HTTP tunneling state of the connection. This must be configured before
2403 * the @conn is connected.
2408 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2410 g_return_if_fail (conn != NULL);
2411 g_return_if_fail (conn->readfd == NULL);
2412 g_return_if_fail (conn->writefd == NULL);
2414 conn->tunneled = tunneled;
2418 * gst_rtsp_connection_is_tunneled:
2419 * @conn: a #GstRTSPConnection
2421 * Get the tunneling state of the connection.
2423 * Returns: if @conn is using HTTP tunneling.
2428 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2430 g_return_val_if_fail (conn != NULL, FALSE);
2432 return conn->tunneled;
2436 * gst_rtsp_connection_get_tunnelid:
2437 * @conn: a #GstRTSPConnection
2439 * Get the tunnel session id the connection.
2441 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2446 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2448 g_return_val_if_fail (conn != NULL, NULL);
2450 if (!conn->tunneled)
2453 return conn->tunnelid;
2457 * gst_rtsp_connection_do_tunnel:
2458 * @conn: a #GstRTSPConnection
2459 * @conn2: a #GstRTSPConnection
2461 * If @conn received the first tunnel connection and @conn2 received
2462 * the second tunnel connection, link the two connections together so that
2463 * @conn manages the tunneled connection.
2465 * After this call, @conn2 cannot be used anymore and must be freed with
2466 * gst_rtsp_connection_free().
2468 * Returns: return GST_RTSP_OK on success.
2473 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2474 GstRTSPConnection * conn2)
2476 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2477 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2478 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2479 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2480 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2483 /* both connections have fd0 as the read/write socket. start by taking the
2484 * socket from conn2 and set it as the socket in conn */
2485 conn->fd1 = conn2->fd0;
2487 /* clean up some of the state of conn2 */
2488 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2490 conn2->readfd = conn2->writefd = NULL;
2492 /* We make fd0 the write socket and fd1 the read socket. */
2493 conn->writefd = &conn->fd0;
2494 conn->readfd = &conn->fd1;
2496 conn->tstate = TUNNEL_STATE_COMPLETE;
2498 /* we need base64 decoding for the readfd */
2499 conn->ctx.state = 0;
2503 conn->ctxp = &conn->ctx;
2508 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2509 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2517 static GstRTSPRec *queue_response (GstRTSPWatch * watch, GString * str,
2520 /* async functions */
2521 struct _GstRTSPWatch
2525 GstRTSPConnection *conn;
2527 GstRTSPBuilder builder;
2528 GstRTSPMessage message;
2532 gboolean write_added;
2534 /* queued message for transmission */
2541 GstRTSPWatchFuncs funcs;
2544 GDestroyNotify notify;
2548 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2550 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2552 *timeout = (watch->conn->timeout * 1000);
2558 gst_rtsp_source_check (GSource * source)
2560 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2562 if (watch->readfd.revents & READ_COND)
2565 if (watch->writefd.revents & WRITE_COND)
2572 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2575 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2578 /* first read as much as we can */
2579 if (watch->readfd.revents & READ_COND) {
2581 res = build_next (&watch->builder, &watch->message, watch->conn);
2582 if (res == GST_RTSP_EINTR)
2584 if (res == GST_RTSP_EEOF)
2586 if (res == GST_RTSP_ETGET) {
2588 GstRTSPStatusCode code;
2590 if (watch->funcs.tunnel_start)
2591 code = watch->funcs.tunnel_start (watch, watch->user_data);
2593 code = GST_RTSP_STS_OK;
2595 /* queue the response string */
2596 str = gen_tunnel_reply (watch->conn, code);
2597 queue_response (watch, str, -1);
2598 } else if (res == GST_RTSP_ETPOST) {
2599 /* in the callback the connection should be tunneled with the
2601 if (watch->funcs.tunnel_complete)
2602 watch->funcs.tunnel_complete (watch, watch->user_data);
2603 } else if (res != GST_RTSP_OK)
2606 if (res == GST_RTSP_OK) {
2607 if (watch->funcs.message_received)
2608 watch->funcs.message_received (watch, &watch->message,
2611 gst_rtsp_message_unset (&watch->message);
2613 build_reset (&watch->builder);
2617 if (watch->writefd.revents & WRITE_COND) {
2619 if (watch->write_data == NULL) {
2622 if (!watch->messages)
2625 /* no data, get a new message from the queue */
2626 data = watch->messages->data;
2627 watch->messages = g_list_delete_link (watch->messages, watch->messages);
2629 watch->write_off = 0;
2630 watch->write_len = data->str->len;
2631 watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2632 watch->write_cseq = data->cseq;
2634 g_slice_free (GstRTSPRec, data);
2637 res = write_bytes (watch->writefd.fd, watch->write_data,
2638 &watch->write_off, watch->write_len);
2639 if (res == GST_RTSP_EINTR)
2641 if (res != GST_RTSP_OK)
2644 if (watch->funcs.message_sent && watch->write_cseq != -1)
2645 watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2648 if (watch->messages == NULL && watch->write_added) {
2649 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2650 watch->write_added = FALSE;
2651 watch->writefd.revents = 0;
2653 g_free (watch->write_data);
2654 watch->write_data = NULL;
2663 if (watch->funcs.closed)
2664 watch->funcs.closed (watch, watch->user_data);
2669 if (watch->funcs.error)
2670 watch->funcs.error (watch, res, watch->user_data);
2676 gst_rtsp_source_finalize (GSource * source)
2678 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2681 build_reset (&watch->builder);
2683 for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2684 GstRTSPRec *data = walk->data;
2686 g_string_free (data->str, TRUE);
2687 g_slice_free (GstRTSPRec, data);
2689 g_list_free (watch->messages);
2690 g_free (watch->write_data);
2693 watch->notify (watch->user_data);
2696 static GSourceFuncs gst_rtsp_source_funcs = {
2697 gst_rtsp_source_prepare,
2698 gst_rtsp_source_check,
2699 gst_rtsp_source_dispatch,
2700 gst_rtsp_source_finalize
2704 * gst_rtsp_watch_new:
2705 * @conn: a #GstRTSPConnection
2706 * @funcs: watch functions
2707 * @user_data: user data to pass to @funcs
2708 * @notify: notify when @user_data is not referenced anymore
2710 * Create a watch object for @conn. The functions provided in @funcs will be
2711 * called with @user_data when activity happened on the watch.
2713 * The new watch is usually created so that it can be attached to a
2714 * maincontext with gst_rtsp_watch_attach().
2716 * @conn must exist for the entire lifetime of the watch.
2718 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2719 * communication. Free with gst_rtsp_watch_unref () after usage.
2724 gst_rtsp_watch_new (GstRTSPConnection * conn,
2725 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2727 GstRTSPWatch *result;
2729 g_return_val_if_fail (conn != NULL, NULL);
2730 g_return_val_if_fail (funcs != NULL, NULL);
2731 g_return_val_if_fail (conn->readfd != NULL, NULL);
2732 g_return_val_if_fail (conn->writefd != NULL, NULL);
2734 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2735 sizeof (GstRTSPWatch));
2737 result->conn = conn;
2738 result->builder.state = STATE_START;
2740 result->readfd.fd = -1;
2741 result->writefd.fd = -1;
2743 gst_rtsp_watch_reset (result);
2745 result->funcs = *funcs;
2746 result->user_data = user_data;
2747 result->notify = notify;
2749 /* only add the read fd, the write fd is only added when we have data
2751 g_source_add_poll ((GSource *) result, &result->readfd);
2757 * gst_rtsp_watch_reset:
2758 * @watch: a #GstRTSPWatch
2760 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
2761 * when the file descriptors of the connection might have changed.
2766 gst_rtsp_watch_reset (GstRTSPWatch * watch)
2768 if (watch->readfd.fd != -1)
2769 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2770 if (watch->writefd.fd != -1)
2771 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2773 watch->readfd.fd = watch->conn->readfd->fd;
2774 watch->readfd.events = READ_COND;
2775 watch->readfd.revents = 0;
2777 watch->writefd.fd = watch->conn->writefd->fd;
2778 watch->writefd.events = WRITE_COND;
2779 watch->writefd.revents = 0;
2780 watch->write_added = FALSE;
2782 g_source_add_poll ((GSource *) watch, &watch->readfd);
2786 * gst_rtsp_watch_attach:
2787 * @watch: a #GstRTSPWatch
2788 * @context: a GMainContext (if NULL, the default context will be used)
2790 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2792 * Returns: the ID (greater than 0) for the watch within the GMainContext.
2797 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2799 g_return_val_if_fail (watch != NULL, 0);
2801 return g_source_attach ((GSource *) watch, context);
2805 * gst_rtsp_watch_unref:
2806 * @watch: a #GstRTSPWatch
2808 * Decreases the reference count of @watch by one. If the resulting reference
2809 * count is zero the watch and associated memory will be destroyed.
2814 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2816 g_return_if_fail (watch != NULL);
2818 g_source_unref ((GSource *) watch);
2822 queue_response (GstRTSPWatch * watch, GString * str, guint cseq)
2826 /* make a record with the message as a string ans cseq */
2827 data = g_slice_new (GstRTSPRec);
2831 /* add the record to a queue */
2832 watch->messages = g_list_append (watch->messages, data);
2834 /* make sure the main context will now also check for writability on the
2836 if (!watch->write_added) {
2837 g_source_add_poll ((GSource *) watch, &watch->writefd);
2838 watch->write_added = TRUE;
2845 * gst_rtsp_watch_queue_message:
2846 * @watch: a #GstRTSPWatch
2847 * @message: a #GstRTSPMessage
2849 * Queue a @message for transmission in @watch. The contents of this
2850 * message will be serialized and transmitted when the connection of the
2851 * watch becomes writable.
2853 * The return value of this function will be returned as the cseq argument in
2854 * the message_sent callback.
2856 * Returns: the sequence number of the message or -1 if the cseq could not be
2862 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2868 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2869 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2871 /* get the cseq from the message, when we finish writing this message on the
2872 * socket we will have to pass the cseq to the callback. */
2873 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2874 0) == GST_RTSP_OK) {
2875 cseq = atoi (header);
2880 /* make a record with the message as a string ans cseq */
2881 data = queue_response (watch, message_to_string (watch->conn, message), cseq);