2 * Copyright (C) <2005,2006> Wim Taymans <wim@fluendo.com>
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
20 * Unless otherwise indicated, Source Code is licensed under MIT license.
21 * See further explanation attached in License Statement (distributed in the file
24 * Permission is hereby granted, free of charge, to any person obtaining a copy of
25 * this software and associated documentation files (the "Software"), to deal in
26 * the Software without restriction, including without limitation the rights to
27 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
28 * of the Software, and to permit persons to whom the Software is furnished to do
29 * so, subject to the following conditions:
31 * The above copyright notice and this permission notice shall be included in all
32 * copies or substantial portions of the Software.
34 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 * SECTION:gstrtspconnection
45 * @short_description: manage RTSP connections
46 * @see_also: gstrtspurl
50 * This object manages the RTSP connection to the server. It provides function
51 * to receive and send bytes and messages.
55 * Last reviewed on 2007-07-24 (0.10.14)
73 /* we include this here to get the G_OS_* defines */
80 #define EINPROGRESS WSAEINPROGRESS
82 #include <sys/ioctl.h>
84 #include <sys/socket.h>
85 #include <netinet/in.h>
86 #include <arpa/inet.h>
90 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
91 #include <sys/filio.h>
94 #include "gstrtspconnection.h"
95 #include "gstrtspbase64.h"
109 static GstRTSPResult read_line (gint fd, guint8 * buffer, guint * idx,
110 guint size, DecodeCtx * ctxp);
111 static GstRTSPResult parse_key_value (guint8 * buffer, gchar * key,
112 guint keysize, gchar ** value);
113 static void parse_string (gchar * dest, gint size, gchar ** src);
116 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
117 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
118 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
119 #define CLOSE_SOCKET(sock) closesocket (sock)
120 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
121 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
122 /* According to Microsoft's connect() documentation this one returns
123 * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
124 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
126 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
127 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
128 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
129 #define CLOSE_SOCKET(sock) close (sock)
130 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
131 #define ERRNO_IS_EINTR (errno == EINTR)
132 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
135 #define ADD_POLLFD(fdset, pfd, fd) \
138 gst_poll_add_fd (fdset, pfd); \
141 #define REMOVE_POLLFD(fdset, pfd) \
143 if ((pfd)->fd != -1) { \
144 GST_DEBUG ("remove fd %d", (pfd)->fd); \
145 gst_poll_remove_fd (fdset, pfd); \
146 CLOSE_SOCKET ((pfd)->fd); \
156 TUNNEL_STATE_COMPLETE
157 } GstRTSPTunnelState;
159 #define TUNNELID_LEN 24
161 struct _GstRTSPConnection
164 /* URL for the connection */
167 /* connection state */
174 gchar tunnelid[TUNNELID_LEN];
176 GstRTSPTunnelState tstate;
182 gint cseq; /* sequence number */
183 gchar session_id[512]; /* session id */
184 gint timeout; /* session timeout in seconds */
185 GTimer *timer; /* timeout timer */
188 GstRTSPAuthMethod auth_method;
191 GHashTable *auth_params;
199 inet_aton (const char *c, struct in_addr *paddr)
201 /* note that inet_addr is deprecated on unix because
202 * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
204 paddr->s_addr = inet_addr (c);
206 if (paddr->s_addr == INADDR_NONE)
223 /* a structure for constructing RTSPMessages */
236 build_reset (GstRTSPBuilder * builder)
238 g_free (builder->body_data);
239 memset (builder, 0, sizeof (builder));
243 * gst_rtsp_connection_create:
244 * @url: a #GstRTSPUrl
245 * @conn: storage for a #GstRTSPConnection
247 * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
248 * The connection will not yet attempt to connect to @url, use
249 * gst_rtsp_connection_connect().
251 * A copy of @url will be made.
253 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
256 gst_rtsp_connection_create (const GstRTSPUrl * url, GstRTSPConnection ** conn)
258 GstRTSPConnection *newconn;
264 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
267 error = WSAStartup (0x0202, &w);
272 if (w.wVersion != 0x0202)
276 newconn = g_new0 (GstRTSPConnection, 1);
278 if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
281 newconn->url = gst_rtsp_url_copy (url);
282 newconn->fd0.fd = -1;
283 newconn->fd1.fd = -1;
284 newconn->timer = g_timer_new ();
285 newconn->timeout = 60;
287 newconn->auth_method = GST_RTSP_AUTH_NONE;
288 newconn->username = NULL;
289 newconn->passwd = NULL;
290 newconn->auth_params = NULL;
300 g_warning ("Error %d on WSAStartup", error);
301 return GST_RTSP_EWSASTART;
305 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
308 return GST_RTSP_EWSAVERSION;
317 return GST_RTSP_ESYS;
322 * gst_rtsp_connection_accept:
324 * @conn: storage for a #GstRTSPConnection
326 * Accept a new connection on @sock and create a new #GstRTSPConnection for
327 * handling communication on new socket.
329 * Returns: #GST_RTSP_OK when @conn contains a valid connection.
334 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
337 unsigned int address_len;
338 GstRTSPConnection *newconn = NULL;
339 struct sockaddr_in address;
345 address_len = sizeof (address);
346 memset (&address, 0, address_len);
349 fd = accept (sock, (struct sockaddr *) &address, &address_len);
351 fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
352 #endif /* G_OS_WIN32 */
356 /* set to non-blocking mode so that we can cancel the communication */
358 fcntl (fd, F_SETFL, O_NONBLOCK);
360 ioctlsocket (fd, FIONBIO, &flags);
361 #endif /* G_OS_WIN32 */
363 /* create a url for the client address */
364 url = g_new0 (GstRTSPUrl, 1);
365 url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
366 url->port = address.sin_port;
368 /* now create the connection object */
369 gst_rtsp_connection_create (url, &newconn);
370 gst_rtsp_url_free (url);
372 ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
374 /* both read and write initially */
375 newconn->readfd = &newconn->fd0;
376 newconn->writefd = &newconn->fd0;
385 return GST_RTSP_ESYS;
390 do_resolve (const gchar * host)
392 struct hostent *hostinfo;
396 struct in_addr *addrp;
399 gchar ipbuf[INET_ADDRSTRLEN];
400 #endif /* G_OS_WIN32 */
404 /* first check if it already is an IP address */
405 if (inet_aton (host, &addr)) {
408 hostinfo = gethostbyname (host);
410 goto not_resolved; /* h_errno set */
412 if (hostinfo->h_addrtype != AF_INET)
413 goto not_ip; /* host not an IP host */
415 addrp = (struct in_addr *) hostinfo->h_addr_list[0];
416 /* this is not threadsafe */
417 ip = inet_ntoa (*addrp);
419 addrs = hostinfo->h_addr_list;
420 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
422 #endif /* G_OS_WIN32 */
429 GST_ERROR ("could not resolve %s", host);
434 GST_ERROR ("not an IP address");
440 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
441 GstPoll * fdset, GTimeVal * timeout)
444 struct sockaddr_in sa_in;
447 unsigned long flags = 1;
448 #endif /* G_OS_WIN32 */
452 memset (&sa_in, 0, sizeof (sa_in));
453 sa_in.sin_family = AF_INET; /* network socket */
454 sa_in.sin_port = htons (port); /* on port */
455 sa_in.sin_addr.s_addr = inet_addr (ip); /* on host ip */
457 fd = socket (AF_INET, SOCK_STREAM, 0);
461 /* set to non-blocking mode so that we can cancel the connect */
463 fcntl (fd, F_SETFL, O_NONBLOCK);
465 ioctlsocket (fd, FIONBIO, &flags);
466 #endif /* G_OS_WIN32 */
468 /* add the socket to our fdset */
469 ADD_POLLFD (fdset, fdout, fd);
471 /* we are going to connect ASYNC now */
472 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
475 if (!ERRNO_IS_EINPROGRESS)
478 /* wait for connect to complete up to the specified timeout or until we got
480 gst_poll_fd_ctl_write (fdset, fdout, TRUE);
482 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
485 retval = gst_poll_wait (fdset, to);
486 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
490 else if (retval == -1)
493 /* we can still have an error connecting on windows */
494 if (gst_poll_fd_has_error (fdset, fdout)) {
495 socklen_t len = sizeof (errno);
497 getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
499 getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
504 gst_poll_fd_ignored (fdset, fdout);
512 GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
513 return GST_RTSP_ESYS;
517 GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
518 REMOVE_POLLFD (fdset, fdout);
519 return GST_RTSP_ESYS;
523 GST_ERROR ("timeout");
524 REMOVE_POLLFD (fdset, fdout);
525 return GST_RTSP_ETIMEOUT;
530 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
540 gchar codestr[4], *resultstr;
544 /* create a random sessionid */
545 for (i = 0; i < TUNNELID_LEN; i++)
546 conn->tunnelid[i] = g_random_int_range ('a', 'z');
547 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
552 str = g_strdup_printf ("GET %s%s%s HTTP/1.0\r\n"
553 "x-sessioncookie: %s\r\n"
554 "Accept: application/x-rtsp-tunnelled\r\n"
555 "Pragma: no-cache\r\n"
556 "Cache-Control: no-cache\r\n" "\r\n",
557 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
560 /* we start by writing to this fd */
561 conn->writefd = &conn->fd0;
563 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
565 if (res != GST_RTSP_OK)
568 gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
569 gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
571 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
579 res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer), NULL);
580 if (res == GST_RTSP_EEOF)
582 if (res == GST_RTSP_OK)
584 if (res != GST_RTSP_EINTR)
588 retval = gst_poll_wait (conn->fdset, to);
589 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
591 /* check for timeout */
603 /* check for last line */
604 if (buffer[0] == '\r')
606 if (buffer[0] == '\0')
610 /* first line, parse response */
611 gchar versionstr[20];
614 bptr = (gchar *) buffer;
616 parse_string (versionstr, sizeof (versionstr), &bptr);
617 parse_string (codestr, sizeof (codestr), &bptr);
618 code = atoi (codestr);
620 while (g_ascii_isspace (*bptr))
631 /* other lines, parse key/value */
632 res = parse_key_value (buffer, key, sizeof (key), &value);
633 if (res == GST_RTSP_OK) {
634 /* we got a new ip address */
635 if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
637 conn->ip = g_strdup (value);
644 if (!(ip = do_resolve (conn->ip)))
647 /* get the port from the url */
648 gst_rtsp_url_get_port (conn->url, &port);
650 /* connect to the host/port */
651 res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
652 if (res != GST_RTSP_OK)
655 /* this is now our writing socket */
656 conn->writefd = &conn->fd1;
659 str = g_strdup_printf ("POST %s%s%s HTTP/1.0\r\n"
660 "x-sessioncookie: %s\r\n"
661 "Content-Type: application/x-rtsp-tunnelled\r\n"
662 "Pragma: no-cache\r\n"
663 "Cache-Control: no-cache\r\n"
664 "Content-Length: 32767\r\n"
665 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
667 url->abspath, url->query ? "?" : "", url->query ? url->query : "",
670 /* we start by writing to this fd */
671 conn->writefd = &conn->fd1;
673 res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
675 if (res != GST_RTSP_OK)
683 GST_ERROR ("write failed (%d)", res);
688 return GST_RTSP_EEOF;
696 return GST_RTSP_ETIMEOUT;
700 return GST_RTSP_ESYS;
704 return GST_RTSP_EINTR;
708 GST_ERROR ("got failure response %d %s", code, resultstr);
709 return GST_RTSP_ERROR;
713 GST_ERROR ("could not resolve %s", conn->ip);
714 return GST_RTSP_ENET;
718 GST_ERROR ("failed to connect");
724 * gst_rtsp_connection_connect:
725 * @conn: a #GstRTSPConnection
726 * @timeout: a #GTimeVal timeout
728 * Attempt to connect to the url of @conn made with
729 * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
730 * forever. If @timeout contains a valid timeout, this function will return
731 * #GST_RTSP_ETIMEOUT after the timeout expired.
733 * This function can be cancelled with gst_rtsp_connection_flush().
735 * Returns: #GST_RTSP_OK when a connection could be made.
738 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
745 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
746 g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
747 g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
751 if (!(ip = do_resolve (url->host)))
754 /* get the port from the url */
755 gst_rtsp_url_get_port (url, &port);
757 /* connect to the host/port */
758 res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
759 if (res != GST_RTSP_OK)
763 conn->ip = g_strdup (ip);
765 /* this is our read URL */
766 conn->readfd = &conn->fd0;
768 if (conn->tunneled) {
769 res = setup_tunneling (conn, timeout);
770 if (res != GST_RTSP_OK)
771 goto tunneling_failed;
773 conn->writefd = &conn->fd0;
780 GST_ERROR ("could not resolve %s", url->host);
781 return GST_RTSP_ENET;
785 GST_ERROR ("failed to connect");
790 GST_ERROR ("failed to setup tunneling");
796 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
798 static const char hexdigits[] = "0123456789abcdef";
801 for (i = 0; i < 16; i++) {
802 string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
803 string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
809 auth_digest_compute_hex_urp (const gchar * username,
810 const gchar * realm, const gchar * password, gchar hex_urp[33])
812 struct MD5Context md5_context;
813 unsigned char digest[16];
815 MD5Init (&md5_context);
816 MD5Update (&md5_context, username, strlen (username));
817 MD5Update (&md5_context, ":", 1);
818 MD5Update (&md5_context, realm, strlen (realm));
819 MD5Update (&md5_context, ":", 1);
820 MD5Update (&md5_context, password, strlen (password));
821 MD5Final (digest, &md5_context);
822 md5_digest_to_hex_string (digest, hex_urp);
826 auth_digest_compute_response (const gchar * method,
827 const gchar * uri, const gchar * hex_a1, const gchar * nonce,
831 struct MD5Context md5_context;
832 unsigned char digest[16];
835 MD5Init (&md5_context);
836 MD5Update (&md5_context, method, strlen (method));
837 MD5Update (&md5_context, ":", 1);
838 MD5Update (&md5_context, uri, strlen (uri));
839 MD5Final (digest, &md5_context);
840 md5_digest_to_hex_string (digest, hex_a2);
843 MD5Init (&md5_context);
844 MD5Update (&md5_context, hex_a1, strlen (hex_a1));
845 MD5Update (&md5_context, ":", 1);
846 MD5Update (&md5_context, nonce, strlen (nonce));
847 MD5Update (&md5_context, ":", 1);
849 MD5Update (&md5_context, hex_a2, 32);
850 MD5Final (digest, &md5_context);
851 md5_digest_to_hex_string (digest, response);
855 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
857 switch (conn->auth_method) {
858 case GST_RTSP_AUTH_BASIC:{
863 user_pass = g_strdup_printf ("%s:%s", conn->username, conn->passwd);
864 user_pass64 = g_base64_encode ((guchar *) user_pass, strlen (user_pass));
865 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 < ctx->coutl) {
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);
1009 out = READ_SOCKET (fd, buffer, size);
1015 static GstRTSPResult
1016 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1021 return GST_RTSP_ERROR;
1028 r = fill_bytes (fd, &buffer[*idx], left, ctx);
1030 return GST_RTSP_EEOF;
1032 if (ERRNO_IS_EAGAIN)
1033 return GST_RTSP_EINTR;
1034 if (!ERRNO_IS_EINTR)
1035 return GST_RTSP_ESYS;
1044 static GstRTSPResult
1045 read_line (gint fd, guint8 * buffer, guint * idx, guint size, DecodeCtx * ctx)
1051 r = fill_bytes (fd, &c, 1, ctx);
1053 return GST_RTSP_EEOF;
1055 if (ERRNO_IS_EAGAIN)
1056 return GST_RTSP_EINTR;
1057 if (!ERRNO_IS_EINTR)
1058 return GST_RTSP_ESYS;
1060 if (c == '\n') /* end on \n */
1062 if (c == '\r') /* ignore \r */
1065 if (*idx < size - 1)
1066 buffer[(*idx)++] = c;
1069 buffer[*idx] = '\0';
1075 * gst_rtsp_connection_write:
1076 * @conn: a #GstRTSPConnection
1077 * @data: the data to write
1078 * @size: the size of @data
1079 * @timeout: a timeout value or #NULL
1081 * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1082 * the specified @timeout. @timeout can be #NULL, in which case this function
1083 * might block forever.
1085 * This function can be cancelled with gst_rtsp_connection_flush().
1087 * Returns: #GST_RTSP_OK on success.
1090 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1091 guint size, GTimeVal * timeout)
1098 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1099 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1100 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1102 gst_poll_set_controllable (conn->fdset, TRUE);
1103 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1104 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1105 /* clear all previous poll results */
1106 gst_poll_fd_ignored (conn->fdset, conn->writefd);
1107 gst_poll_fd_ignored (conn->fdset, conn->readfd);
1109 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1115 res = write_bytes (conn->writefd->fd, data, &offset, size);
1116 if (res == GST_RTSP_OK)
1118 if (res != GST_RTSP_EINTR)
1121 /* not all is written, wait until we can write more */
1123 retval = gst_poll_wait (conn->fdset, to);
1124 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1141 return GST_RTSP_ETIMEOUT;
1145 return GST_RTSP_ESYS;
1149 return GST_RTSP_EINTR;
1158 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1160 GString *str = NULL;
1162 str = g_string_new ("");
1164 switch (message->type) {
1165 case GST_RTSP_MESSAGE_REQUEST:
1166 /* create request string, add CSeq */
1167 g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1169 gst_rtsp_method_as_text (message->type_data.request.method),
1170 message->type_data.request.uri, conn->cseq++);
1171 /* add session id if we have one */
1172 if (conn->session_id[0] != '\0') {
1173 gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1176 /* add any authentication headers */
1177 add_auth_header (conn, message);
1179 case GST_RTSP_MESSAGE_RESPONSE:
1180 /* create response string */
1181 g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1182 message->type_data.response.code, message->type_data.response.reason);
1184 case GST_RTSP_MESSAGE_DATA:
1186 guint8 data_header[4];
1188 /* prepare data header */
1189 data_header[0] = '$';
1190 data_header[1] = message->type_data.data.channel;
1191 data_header[2] = (message->body_size >> 8) & 0xff;
1192 data_header[3] = message->body_size & 0xff;
1194 /* create string with header and data */
1195 str = g_string_append_len (str, (gchar *) data_header, 4);
1197 g_string_append_len (str, (gchar *) message->body,
1198 message->body_size);
1202 g_string_free (str, TRUE);
1203 g_return_val_if_reached (NULL);
1207 /* append headers and body */
1208 if (message->type != GST_RTSP_MESSAGE_DATA) {
1209 gchar date_string[100];
1211 gen_date_string (date_string, sizeof (date_string));
1213 /* add date header */
1214 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1216 /* append headers */
1217 gst_rtsp_message_append_headers (message, str);
1219 /* append Content-Length and body if needed */
1220 if (message->body != NULL && message->body_size > 0) {
1223 len = g_strdup_printf ("%d", message->body_size);
1224 g_string_append_printf (str, "%s: %s\r\n",
1225 gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1227 /* header ends here */
1228 g_string_append (str, "\r\n");
1230 g_string_append_len (str, (gchar *) message->body,
1231 message->body_size);
1233 /* just end headers */
1234 g_string_append (str, "\r\n");
1242 * gst_rtsp_connection_send:
1243 * @conn: a #GstRTSPConnection
1244 * @message: the message to send
1245 * @timeout: a timeout value or #NULL
1247 * Attempt to send @message to the connected @conn, blocking up to
1248 * the specified @timeout. @timeout can be #NULL, in which case this function
1249 * might block forever.
1251 * This function can be cancelled with gst_rtsp_connection_flush().
1253 * Returns: #GST_RTSP_OK on success.
1256 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1259 GString *string = NULL;
1264 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1265 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1267 if (!(string = message_to_string (conn, message)))
1270 if (conn->tunneled) {
1271 str = g_base64_encode ((const guchar *) string->str, string->len);
1272 g_string_free (string, TRUE);
1277 g_string_free (string, FALSE);
1281 res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1289 g_warning ("Wrong message");
1290 return GST_RTSP_EINVAL;
1295 parse_string (gchar * dest, gint size, gchar ** src)
1301 while (g_ascii_isspace (**src))
1304 while (!g_ascii_isspace (**src) && **src != '\0') {
1306 dest[idx++] = **src;
1314 parse_key (gchar * dest, gint size, gchar ** src)
1319 while (**src != ':' && **src != '\0') {
1321 dest[idx++] = **src;
1328 static GstRTSPResult
1329 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1332 gchar versionstr[20];
1337 bptr = (gchar *) buffer;
1339 parse_string (versionstr, sizeof (versionstr), &bptr);
1340 parse_string (codestr, sizeof (codestr), &bptr);
1341 code = atoi (codestr);
1343 while (g_ascii_isspace (*bptr))
1346 if (strcmp (versionstr, "RTSP/1.0") == 0)
1347 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1349 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1350 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1352 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1360 return GST_RTSP_EPARSE;
1364 static GstRTSPResult
1365 parse_request_line (GstRTSPConnection * conn, guint8 * buffer,
1366 GstRTSPMessage * msg)
1368 GstRTSPResult res = GST_RTSP_OK;
1369 gchar versionstr[20];
1370 gchar methodstr[20];
1373 GstRTSPMethod method;
1374 GstRTSPTunnelState tstate = TUNNEL_STATE_NONE;
1376 bptr = (gchar *) buffer;
1378 parse_string (methodstr, sizeof (methodstr), &bptr);
1379 method = gst_rtsp_find_method (methodstr);
1380 if (method == GST_RTSP_INVALID) {
1381 /* a tunnel request is allowed when we don't have one yet */
1382 if (conn->tstate != TUNNEL_STATE_NONE)
1383 goto invalid_method;
1384 /* we need GET or POST for a valid tunnel request */
1385 if (!strcmp (methodstr, "GET"))
1386 tstate = TUNNEL_STATE_GET;
1387 else if (!strcmp (methodstr, "POST"))
1388 tstate = TUNNEL_STATE_POST;
1390 goto invalid_method;
1393 parse_string (urlstr, sizeof (urlstr), &bptr);
1394 if (*urlstr == '\0')
1397 parse_string (versionstr, sizeof (versionstr), &bptr);
1400 goto invalid_version;
1402 if (strcmp (versionstr, "RTSP/1.0") == 0) {
1403 res = gst_rtsp_message_init_request (msg, method, urlstr);
1404 } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1405 res = gst_rtsp_message_init_request (msg, method, urlstr);
1406 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1407 } else if (strcmp (versionstr, "HTTP/1.0") == 0) {
1408 /* tunnel request, we need a tunnel method */
1409 if (tstate == TUNNEL_STATE_NONE) {
1410 res = GST_RTSP_EPARSE;
1412 conn->tstate = tstate;
1415 res = GST_RTSP_EPARSE;
1423 GST_ERROR ("invalid method %s", methodstr);
1424 return GST_RTSP_EPARSE;
1428 GST_ERROR ("invalid url %s", urlstr);
1429 return GST_RTSP_EPARSE;
1433 GST_ERROR ("invalid version");
1434 return GST_RTSP_EPARSE;
1438 static GstRTSPResult
1439 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1443 bptr = (gchar *) buffer;
1446 parse_key (key, keysize, &bptr);
1451 while (g_ascii_isspace (*bptr))
1461 return GST_RTSP_EPARSE;
1465 /* parsing lines means reading a Key: Value pair */
1466 static GstRTSPResult
1467 parse_line (GstRTSPConnection * conn, guint8 * buffer, GstRTSPMessage * msg)
1472 GstRTSPHeaderField field;
1474 res = parse_key_value (buffer, key, sizeof (key), &value);
1475 if (res != GST_RTSP_OK)
1478 if (conn->tstate == TUNNEL_STATE_GET || conn->tstate == TUNNEL_STATE_POST) {
1479 /* save the tunnel session in the connection */
1480 if (!strcmp (key, "x-sessioncookie")) {
1481 strncpy (conn->tunnelid, value, TUNNELID_LEN);
1482 conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1483 conn->tunneled = TRUE;
1486 field = gst_rtsp_find_header_field (key);
1487 if (field != GST_RTSP_HDR_INVALID)
1488 gst_rtsp_message_add_header (msg, field, value);
1501 * GST_RTSP_OK when a complete message was read.
1502 * GST_RTSP_EEOF: when the socket is closed
1503 * GST_RTSP_EINTR: when more data is needed.
1504 * GST_RTSP_..: some other error occured.
1506 static GstRTSPResult
1507 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1508 GstRTSPConnection * conn)
1513 switch (builder->state) {
1515 builder->offset = 0;
1517 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1518 &builder->offset, 1, conn->ctxp);
1519 if (res != GST_RTSP_OK)
1522 /* we have 1 bytes now and we can see if this is a data message or
1524 if (builder->buffer[0] == '$') {
1525 /* data message, prepare for the header */
1526 builder->state = STATE_DATA_HEADER;
1529 builder->state = STATE_READ_LINES;
1532 case STATE_DATA_HEADER:
1535 read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1536 &builder->offset, 4, conn->ctxp);
1537 if (res != GST_RTSP_OK)
1540 gst_rtsp_message_init_data (message, builder->buffer[1]);
1542 builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1543 builder->body_data = g_malloc (builder->body_len + 1);
1544 builder->body_data[builder->body_len] = '\0';
1545 builder->offset = 0;
1546 builder->state = STATE_DATA_BODY;
1549 case STATE_DATA_BODY:
1552 read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1553 builder->body_len, conn->ctxp);
1554 if (res != GST_RTSP_OK)
1557 /* we have the complete body now, store in the message adjusting the
1558 * length to include the traling '\0' */
1559 gst_rtsp_message_take_body (message,
1560 (guint8 *) builder->body_data, builder->body_len + 1);
1561 builder->body_data = NULL;
1562 builder->body_len = 0;
1564 builder->state = STATE_END;
1567 case STATE_READ_LINES:
1569 res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1570 sizeof (builder->buffer), conn->ctxp);
1571 if (res != GST_RTSP_OK)
1574 /* we have a regular response */
1575 if (builder->buffer[0] == '\r') {
1576 builder->buffer[0] = '\0';
1579 if (builder->buffer[0] == '\0') {
1582 /* empty line, end of message header */
1583 /* see if there is a Content-Length header */
1584 if (gst_rtsp_message_get_header (message,
1585 GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1586 /* there is, prepare to read the body */
1587 builder->body_len = atol (hdrval);
1588 builder->body_data = g_malloc (builder->body_len + 1);
1589 builder->body_data[builder->body_len] = '\0';
1590 builder->offset = 0;
1591 builder->state = STATE_DATA_BODY;
1593 builder->state = STATE_END;
1598 /* we have a line */
1599 if (builder->line == 0) {
1600 /* first line, check for response status */
1601 if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1602 res = parse_response_status (builder->buffer, message);
1604 res = parse_request_line (conn, builder->buffer, message);
1606 /* the first line must parse without errors */
1607 if (res != GST_RTSP_OK)
1610 /* else just parse the line, ignore errors */
1611 parse_line (conn, builder->buffer, message);
1614 builder->offset = 0;
1621 if (conn->tstate == TUNNEL_STATE_GET) {
1622 res = GST_RTSP_ETGET;
1624 } else if (conn->tstate == TUNNEL_STATE_POST) {
1625 res = GST_RTSP_ETPOST;
1629 if (message->type == GST_RTSP_MESSAGE_DATA) {
1630 /* data messages don't have headers */
1635 /* save session id in the connection for further use */
1636 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1637 &session_id, 0) == GST_RTSP_OK) {
1640 maxlen = sizeof (conn->session_id) - 1;
1641 /* the sessionid can have attributes marked with ;
1642 * Make sure we strip them */
1643 for (i = 0; session_id[i] != '\0'; i++) {
1644 if (session_id[i] == ';') {
1649 } while (g_ascii_isspace (session_id[i]));
1650 if (g_str_has_prefix (&session_id[i], "timeout=")) {
1653 /* if we parsed something valid, configure */
1654 if ((to = atoi (&session_id[i + 9])) > 0)
1661 /* make sure to not overflow */
1662 strncpy (conn->session_id, session_id, maxlen);
1663 conn->session_id[maxlen] = '\0';
1669 res = GST_RTSP_ERROR;
1678 * gst_rtsp_connection_read:
1679 * @conn: a #GstRTSPConnection
1680 * @data: the data to read
1681 * @size: the size of @data
1682 * @timeout: a timeout value or #NULL
1684 * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1685 * the specified @timeout. @timeout can be #NULL, in which case this function
1686 * might block forever.
1688 * This function can be cancelled with gst_rtsp_connection_flush().
1690 * Returns: #GST_RTSP_OK on success.
1693 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1701 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1702 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1703 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1710 /* configure timeout if any */
1711 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1713 gst_poll_set_controllable (conn->fdset, TRUE);
1714 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1715 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1718 res = read_bytes (conn->readfd->fd, data, &offset, size, conn->ctxp);
1719 if (res == GST_RTSP_EEOF)
1721 if (res == GST_RTSP_OK)
1723 if (res != GST_RTSP_EINTR)
1727 retval = gst_poll_wait (conn->fdset, to);
1728 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1730 /* check for timeout */
1732 goto select_timeout;
1740 gst_poll_set_controllable (conn->fdset, FALSE);
1747 return GST_RTSP_ESYS;
1751 return GST_RTSP_ETIMEOUT;
1755 return GST_RTSP_EINTR;
1759 return GST_RTSP_EEOF;
1768 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code)
1771 gchar date_string[100];
1772 const gchar *status;
1774 gen_date_string (date_string, sizeof (date_string));
1776 status = gst_rtsp_status_as_text (code);
1777 if (status == NULL) {
1779 status = "Internal Server Error";
1782 str = g_string_new ("");
1785 g_string_append_printf (str, "HTTP/1.0 %d %s\r\n", code, status);
1786 g_string_append_printf (str,
1787 "Server: GStreamer RTSP Server\r\n"
1789 "Connection: close\r\n"
1790 "Cache-Control: no-store\r\n" "Pragma: no-cache\r\n", date_string);
1793 g_string_append_printf (str, "x-server-ip-address: %s\r\n", conn->ip);
1794 g_string_append_printf (str,
1795 "Content-Type: application/x-rtsp-tunnelled\r\n" "\r\n");
1801 * gst_rtsp_connection_receive:
1802 * @conn: a #GstRTSPConnection
1803 * @message: the message to read
1804 * @timeout: a timeout value or #NULL
1806 * Attempt to read into @message from the connected @conn, blocking up to
1807 * the specified @timeout. @timeout can be #NULL, in which case this function
1808 * might block forever.
1810 * This function can be cancelled with gst_rtsp_connection_flush().
1812 * Returns: #GST_RTSP_OK on success.
1815 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1819 GstRTSPBuilder builder = { 0 };
1823 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1824 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1825 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1827 /* configure timeout if any */
1828 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1830 gst_poll_set_controllable (conn->fdset, TRUE);
1831 gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1832 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1835 res = build_next (&builder, message, conn);
1836 if (res == GST_RTSP_EEOF)
1838 if (res == GST_RTSP_OK)
1840 if (res == GST_RTSP_ETGET) {
1843 /* tunnel GET request, we can reply now */
1844 str = gen_tunnel_reply (conn, GST_RTSP_STS_OK);
1846 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len,
1848 g_string_free (str, TRUE);
1849 } else if (res == GST_RTSP_ETPOST) {
1850 /* tunnel POST request, return the value, the caller now has to link the
1851 * two connections. */
1853 } else if (res != GST_RTSP_EINTR)
1857 retval = gst_poll_wait (conn->fdset, to);
1858 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1860 /* check for timeout */
1862 goto select_timeout;
1870 gst_poll_set_controllable (conn->fdset, FALSE);
1873 /* we have a message here */
1874 build_reset (&builder);
1881 res = GST_RTSP_ESYS;
1886 res = GST_RTSP_ETIMEOUT;
1891 res = GST_RTSP_EINTR;
1896 res = GST_RTSP_EEOF;
1902 build_reset (&builder);
1903 gst_rtsp_message_unset (message);
1909 * gst_rtsp_connection_close:
1910 * @conn: a #GstRTSPConnection
1912 * Close the connected @conn. After this call, the connection is in the same
1913 * state as when it was first created.
1915 * Returns: #GST_RTSP_OK on success.
1918 gst_rtsp_connection_close (GstRTSPConnection * conn)
1920 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1925 REMOVE_POLLFD (conn->fdset, &conn->fd0);
1926 REMOVE_POLLFD (conn->fdset, &conn->fd1);
1927 conn->writefd = NULL;
1928 conn->readfd = NULL;
1929 conn->tunneled = FALSE;
1930 conn->tstate = TUNNEL_STATE_NONE;
1932 g_free (conn->username);
1933 conn->username = NULL;
1934 g_free (conn->passwd);
1935 conn->passwd = NULL;
1936 gst_rtsp_connection_clear_auth_params (conn);
1939 conn->session_id[0] = '\0';
1945 * gst_rtsp_connection_free:
1946 * @conn: a #GstRTSPConnection
1948 * Close and free @conn.
1950 * Returns: #GST_RTSP_OK on success.
1953 gst_rtsp_connection_free (GstRTSPConnection * conn)
1957 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1959 res = gst_rtsp_connection_close (conn);
1960 gst_poll_free (conn->fdset);
1961 g_timer_destroy (conn->timer);
1962 gst_rtsp_url_free (conn->url);
1972 * gst_rtsp_connection_poll:
1973 * @conn: a #GstRTSPConnection
1974 * @events: a bitmask of #GstRTSPEvent flags to check
1975 * @revents: location for result flags
1976 * @timeout: a timeout
1978 * Wait up to the specified @timeout for the connection to become available for
1979 * at least one of the operations specified in @events. When the function returns
1980 * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1983 * @timeout can be #NULL, in which case this function might block forever.
1985 * This function can be cancelled with gst_rtsp_connection_flush().
1987 * Returns: #GST_RTSP_OK on success.
1992 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1993 GstRTSPEvent * revents, GTimeVal * timeout)
1998 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1999 g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2000 g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2001 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2002 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2004 gst_poll_set_controllable (conn->fdset, TRUE);
2006 /* add fd to writer set when asked to */
2007 gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2008 events & GST_RTSP_EV_WRITE);
2010 /* add fd to reader set when asked to */
2011 gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2013 /* configure timeout if any */
2014 to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2017 retval = gst_poll_wait (conn->fdset, to);
2018 } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2021 goto select_timeout;
2031 if (events & GST_RTSP_EV_READ) {
2032 if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2033 *revents |= GST_RTSP_EV_READ;
2035 if (events & GST_RTSP_EV_WRITE) {
2036 if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2037 *revents |= GST_RTSP_EV_WRITE;
2044 return GST_RTSP_ETIMEOUT;
2048 return GST_RTSP_ESYS;
2052 return GST_RTSP_EINTR;
2057 * gst_rtsp_connection_next_timeout:
2058 * @conn: a #GstRTSPConnection
2059 * @timeout: a timeout
2061 * Calculate the next timeout for @conn, storing the result in @timeout.
2063 * Returns: #GST_RTSP_OK.
2066 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2072 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2073 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2075 elapsed = g_timer_elapsed (conn->timer, &usec);
2076 if (elapsed >= conn->timeout) {
2080 sec = conn->timeout - elapsed;
2083 timeout->tv_sec = sec;
2084 timeout->tv_usec = usec;
2090 * gst_rtsp_connection_reset_timeout:
2091 * @conn: a #GstRTSPConnection
2093 * Reset the timeout of @conn.
2095 * Returns: #GST_RTSP_OK.
2098 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2100 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2102 g_timer_start (conn->timer);
2108 * gst_rtsp_connection_flush:
2109 * @conn: a #GstRTSPConnection
2110 * @flush: start or stop the flush
2112 * Start or stop the flushing action on @conn. When flushing, all current
2113 * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2114 * is set to non-flushing mode again.
2116 * Returns: #GST_RTSP_OK.
2119 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2121 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2123 gst_poll_set_flushing (conn->fdset, flush);
2129 * gst_rtsp_connection_set_auth:
2130 * @conn: a #GstRTSPConnection
2131 * @method: authentication method
2133 * @pass: the password
2135 * Configure @conn for authentication mode @method with @user and @pass as the
2136 * user and password respectively.
2138 * Returns: #GST_RTSP_OK.
2141 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2142 GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2144 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2146 if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2147 || g_strrstr (user, ":") != NULL))
2148 return GST_RTSP_EINVAL;
2150 /* Make sure the username and passwd are being set for authentication */
2151 if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2152 return GST_RTSP_EINVAL;
2154 /* ":" chars are not allowed in usernames for basic auth */
2155 if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2156 return GST_RTSP_EINVAL;
2158 g_free (conn->username);
2159 g_free (conn->passwd);
2161 conn->auth_method = method;
2162 conn->username = g_strdup (user);
2163 conn->passwd = g_strdup (pass);
2170 * @key: ASCII string to hash
2172 * Hashes @key in a case-insensitive manner.
2174 * Returns: the hash code.
2177 str_case_hash (gconstpointer key)
2179 const char *p = key;
2180 guint h = g_ascii_toupper (*p);
2183 for (p += 1; *p != '\0'; p++)
2184 h = (h << 5) - h + g_ascii_toupper (*p);
2191 * @v1: an ASCII string
2192 * @v2: another ASCII string
2194 * Compares @v1 and @v2 in a case-insensitive manner
2196 * Returns: %TRUE if they are equal (modulo case)
2199 str_case_equal (gconstpointer v1, gconstpointer v2)
2201 const char *string1 = v1;
2202 const char *string2 = v2;
2204 return g_ascii_strcasecmp (string1, string2) == 0;
2208 * gst_rtsp_connection_set_auth_param:
2209 * @conn: a #GstRTSPConnection
2210 * @param: authentication directive
2213 * Setup @conn with authentication directives. This is not necesary for
2214 * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2215 * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2216 * in the WWW-Authenticate response header and can include realm, domain,
2217 * nonce, opaque, stale, algorithm, qop as per RFC2617.
2222 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2223 const gchar * param, const gchar * value)
2225 g_return_if_fail (conn != NULL);
2226 g_return_if_fail (param != NULL);
2228 if (conn->auth_params == NULL) {
2230 g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2232 g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2236 * gst_rtsp_connection_clear_auth_params:
2237 * @conn: a #GstRTSPConnection
2239 * Clear the list of authentication directives stored in @conn.
2244 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2246 g_return_if_fail (conn != NULL);
2248 if (conn->auth_params != NULL) {
2249 g_hash_table_destroy (conn->auth_params);
2250 conn->auth_params = NULL;
2254 static GstRTSPResult
2255 set_qos_dscp (gint fd, guint qos_dscp)
2260 struct sockaddr_in6 sa_in6;
2261 struct sockaddr_storage sa_stor;
2263 socklen_t slen = sizeof (sa);
2270 if (getsockname (fd, &sa.sa, &slen) < 0)
2271 goto no_getsockname;
2273 af = sa.sa.sa_family;
2275 /* if this is an IPv4-mapped address then do IPv4 QoS */
2276 if (af == AF_INET6) {
2277 if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2281 /* extract and shift 6 bits of the DSCP */
2282 tos = (qos_dscp & 0x3f) << 2;
2286 if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2291 if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2305 return GST_RTSP_ESYS;
2310 return GST_RTSP_ERROR;
2315 * gst_rtsp_connection_set_qos_dscp:
2316 * @conn: a #GstRTSPConnection
2317 * @qos_dscp: DSCP value
2319 * Configure @conn to use the specified DSCP value.
2321 * Returns: #GST_RTSP_OK on success.
2326 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2330 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2331 g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2332 g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2334 res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2335 if (res == GST_RTSP_OK)
2336 res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2343 * gst_rtsp_connection_get_url:
2344 * @conn: a #GstRTSPConnection
2346 * Retrieve the URL of the other end of @conn.
2348 * Returns: The URL. This value remains valid until the
2349 * connection is freed.
2354 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2356 g_return_val_if_fail (conn != NULL, NULL);
2362 * gst_rtsp_connection_get_ip:
2363 * @conn: a #GstRTSPConnection
2365 * Retrieve the IP address of the other end of @conn.
2367 * Returns: The IP address as a string. this value remains valid until the
2368 * connection is closed.
2373 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2375 g_return_val_if_fail (conn != NULL, NULL);
2381 * gst_rtsp_connection_set_ip:
2382 * @conn: a #GstRTSPConnection
2383 * @ip: an ip address
2385 * Set the IP address of the server.
2390 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2392 g_return_if_fail (conn != NULL);
2395 conn->ip = g_strdup (ip);
2399 * gst_rtsp_connection_get_readfd:
2400 * @conn: a #GstRTSPConnection
2402 * Get the file descriptor for reading.
2404 * Returns: the file descriptor used for reading or -1 on error. The file
2405 * descriptor remains valid until the connection is closed.
2410 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2412 g_return_val_if_fail (conn != NULL, -1);
2413 g_return_val_if_fail (conn->readfd != NULL, -1);
2415 return conn->readfd->fd;
2419 * gst_rtsp_connection_get_writefd:
2420 * @conn: a #GstRTSPConnection
2422 * Get the file descriptor for writing.
2424 * Returns: the file descriptor used for writing or -1 on error. The file
2425 * descriptor remains valid until the connection is closed.
2430 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2432 g_return_val_if_fail (conn != NULL, -1);
2433 g_return_val_if_fail (conn->writefd != NULL, -1);
2435 return conn->writefd->fd;
2440 * gst_rtsp_connection_set_tunneled:
2441 * @conn: a #GstRTSPConnection
2442 * @tunneled: the new state
2444 * Set the HTTP tunneling state of the connection. This must be configured before
2445 * the @conn is connected.
2450 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2452 g_return_if_fail (conn != NULL);
2453 g_return_if_fail (conn->readfd == NULL);
2454 g_return_if_fail (conn->writefd == NULL);
2456 conn->tunneled = tunneled;
2460 * gst_rtsp_connection_is_tunneled:
2461 * @conn: a #GstRTSPConnection
2463 * Get the tunneling state of the connection.
2465 * Returns: if @conn is using HTTP tunneling.
2470 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2472 g_return_val_if_fail (conn != NULL, FALSE);
2474 return conn->tunneled;
2478 * gst_rtsp_connection_get_tunnelid:
2479 * @conn: a #GstRTSPConnection
2481 * Get the tunnel session id the connection.
2483 * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2488 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2490 g_return_val_if_fail (conn != NULL, NULL);
2492 if (!conn->tunneled)
2495 return conn->tunnelid;
2499 * gst_rtsp_connection_do_tunnel:
2500 * @conn: a #GstRTSPConnection
2501 * @conn2: a #GstRTSPConnection
2503 * If @conn received the first tunnel connection and @conn2 received
2504 * the second tunnel connection, link the two connections together so that
2505 * @conn manages the tunneled connection.
2507 * After this call, @conn2 cannot be used anymore and must be freed with
2508 * gst_rtsp_connection_free().
2510 * Returns: return GST_RTSP_OK on success.
2515 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2516 GstRTSPConnection * conn2)
2518 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2519 g_return_val_if_fail (conn2 != NULL, GST_RTSP_EINVAL);
2520 g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2521 g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2522 g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid, TUNNELID_LEN),
2525 /* both connections have fd0 as the read/write socket. start by taking the
2526 * socket from conn2 and set it as the socket in conn */
2527 conn->fd1 = conn2->fd0;
2529 /* clean up some of the state of conn2 */
2530 gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2532 conn2->readfd = conn2->writefd = NULL;
2534 /* We make fd0 the write socket and fd1 the read socket. */
2535 conn->writefd = &conn->fd0;
2536 conn->readfd = &conn->fd1;
2538 conn->tstate = TUNNEL_STATE_COMPLETE;
2540 /* we need base64 decoding for the readfd */
2541 conn->ctx.state = 0;
2545 conn->ctxp = &conn->ctx;
2550 #define READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR)
2551 #define WRITE_COND (G_IO_OUT | G_IO_ERR)
2559 static GstRTSPRec *queue_response (GstRTSPWatch * watch, GString * str,
2562 /* async functions */
2563 struct _GstRTSPWatch
2567 GstRTSPConnection *conn;
2569 GstRTSPBuilder builder;
2570 GstRTSPMessage message;
2574 gboolean write_added;
2576 /* queued message for transmission */
2583 GstRTSPWatchFuncs funcs;
2586 GDestroyNotify notify;
2590 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2592 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2594 *timeout = (watch->conn->timeout * 1000);
2600 gst_rtsp_source_check (GSource * source)
2602 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2604 if (watch->readfd.revents & READ_COND)
2607 if (watch->writefd.revents & WRITE_COND)
2614 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2617 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2620 /* first read as much as we can */
2621 if (watch->readfd.revents & READ_COND) {
2623 res = build_next (&watch->builder, &watch->message, watch->conn);
2624 if (res == GST_RTSP_EINTR)
2626 if (res == GST_RTSP_EEOF)
2628 if (res == GST_RTSP_ETGET) {
2630 GstRTSPStatusCode code;
2632 if (watch->funcs.tunnel_start)
2633 code = watch->funcs.tunnel_start (watch, watch->user_data);
2635 code = GST_RTSP_STS_OK;
2637 /* queue the response string */
2638 str = gen_tunnel_reply (watch->conn, code);
2639 queue_response (watch, str, -1);
2640 } else if (res == GST_RTSP_ETPOST) {
2641 /* in the callback the connection should be tunneled with the
2643 if (watch->funcs.tunnel_complete)
2644 watch->funcs.tunnel_complete (watch, watch->user_data);
2645 } else if (res != GST_RTSP_OK)
2648 if (res == GST_RTSP_OK) {
2649 if (watch->funcs.message_received)
2650 watch->funcs.message_received (watch, &watch->message,
2653 gst_rtsp_message_unset (&watch->message);
2655 build_reset (&watch->builder);
2659 if (watch->writefd.revents & WRITE_COND) {
2661 if (watch->write_data == NULL) {
2664 if (!watch->messages)
2667 /* no data, get a new message from the queue */
2668 data = watch->messages->data;
2669 watch->messages = g_list_delete_link (watch->messages, watch->messages);
2671 watch->write_off = 0;
2672 watch->write_len = data->str->len;
2673 watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2674 watch->write_cseq = data->cseq;
2676 g_slice_free (GstRTSPRec, data);
2679 res = write_bytes (watch->writefd.fd, watch->write_data,
2680 &watch->write_off, watch->write_len);
2681 if (res == GST_RTSP_EINTR)
2683 if (res != GST_RTSP_OK)
2686 if (watch->funcs.message_sent && watch->write_cseq != -1)
2687 watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2690 if (watch->messages == NULL && watch->write_added) {
2691 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2692 watch->write_added = FALSE;
2693 watch->writefd.revents = 0;
2695 g_free (watch->write_data);
2696 watch->write_data = NULL;
2705 if (watch->funcs.closed)
2706 watch->funcs.closed (watch, watch->user_data);
2711 if (watch->funcs.error)
2712 watch->funcs.error (watch, res, watch->user_data);
2718 gst_rtsp_source_finalize (GSource * source)
2720 GstRTSPWatch *watch = (GstRTSPWatch *) source;
2723 build_reset (&watch->builder);
2725 for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2726 GstRTSPRec *data = walk->data;
2728 g_string_free (data->str, TRUE);
2729 g_slice_free (GstRTSPRec, data);
2731 g_list_free (watch->messages);
2732 g_free (watch->write_data);
2735 watch->notify (watch->user_data);
2738 static GSourceFuncs gst_rtsp_source_funcs = {
2739 gst_rtsp_source_prepare,
2740 gst_rtsp_source_check,
2741 gst_rtsp_source_dispatch,
2742 gst_rtsp_source_finalize
2746 * gst_rtsp_watch_new:
2747 * @conn: a #GstRTSPConnection
2748 * @funcs: watch functions
2749 * @user_data: user data to pass to @funcs
2750 * @notify: notify when @user_data is not referenced anymore
2752 * Create a watch object for @conn. The functions provided in @funcs will be
2753 * called with @user_data when activity happened on the watch.
2755 * The new watch is usually created so that it can be attached to a
2756 * maincontext with gst_rtsp_watch_attach().
2758 * @conn must exist for the entire lifetime of the watch.
2760 * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2761 * communication. Free with gst_rtsp_watch_unref () after usage.
2766 gst_rtsp_watch_new (GstRTSPConnection * conn,
2767 GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2769 GstRTSPWatch *result;
2771 g_return_val_if_fail (conn != NULL, NULL);
2772 g_return_val_if_fail (funcs != NULL, NULL);
2773 g_return_val_if_fail (conn->readfd != NULL, NULL);
2774 g_return_val_if_fail (conn->writefd != NULL, NULL);
2776 result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2777 sizeof (GstRTSPWatch));
2779 result->conn = conn;
2780 result->builder.state = STATE_START;
2782 result->readfd.fd = -1;
2783 result->writefd.fd = -1;
2785 gst_rtsp_watch_reset (result);
2787 result->funcs = *funcs;
2788 result->user_data = user_data;
2789 result->notify = notify;
2791 /* only add the read fd, the write fd is only added when we have data
2793 g_source_add_poll ((GSource *) result, &result->readfd);
2799 * gst_rtsp_watch_reset:
2800 * @watch: a #GstRTSPWatch
2802 * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
2803 * when the file descriptors of the connection might have changed.
2808 gst_rtsp_watch_reset (GstRTSPWatch * watch)
2810 if (watch->readfd.fd != -1)
2811 g_source_remove_poll ((GSource *) watch, &watch->readfd);
2812 if (watch->writefd.fd != -1)
2813 g_source_remove_poll ((GSource *) watch, &watch->writefd);
2815 watch->readfd.fd = watch->conn->readfd->fd;
2816 watch->readfd.events = READ_COND;
2817 watch->readfd.revents = 0;
2819 watch->writefd.fd = watch->conn->writefd->fd;
2820 watch->writefd.events = WRITE_COND;
2821 watch->writefd.revents = 0;
2822 watch->write_added = FALSE;
2824 g_source_add_poll ((GSource *) watch, &watch->readfd);
2828 * gst_rtsp_watch_attach:
2829 * @watch: a #GstRTSPWatch
2830 * @context: a GMainContext (if NULL, the default context will be used)
2832 * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2834 * Returns: the ID (greater than 0) for the watch within the GMainContext.
2839 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2841 g_return_val_if_fail (watch != NULL, 0);
2843 return g_source_attach ((GSource *) watch, context);
2847 * gst_rtsp_watch_unref:
2848 * @watch: a #GstRTSPWatch
2850 * Decreases the reference count of @watch by one. If the resulting reference
2851 * count is zero the watch and associated memory will be destroyed.
2856 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2858 g_return_if_fail (watch != NULL);
2860 g_source_unref ((GSource *) watch);
2864 queue_response (GstRTSPWatch * watch, GString * str, guint cseq)
2868 /* make a record with the message as a string ans cseq */
2869 data = g_slice_new (GstRTSPRec);
2873 /* add the record to a queue */
2874 watch->messages = g_list_append (watch->messages, data);
2876 /* make sure the main context will now also check for writability on the
2878 if (!watch->write_added) {
2879 g_source_add_poll ((GSource *) watch, &watch->writefd);
2880 watch->write_added = TRUE;
2887 * gst_rtsp_watch_queue_message:
2888 * @watch: a #GstRTSPWatch
2889 * @message: a #GstRTSPMessage
2891 * Queue a @message for transmission in @watch. The contents of this
2892 * message will be serialized and transmitted when the connection of the
2893 * watch becomes writable.
2895 * The return value of this function will be returned as the cseq argument in
2896 * the message_sent callback.
2898 * Returns: the sequence number of the message or -1 if the cseq could not be
2904 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2910 g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2911 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2913 /* get the cseq from the message, when we finish writing this message on the
2914 * socket we will have to pass the cseq to the callback. */
2915 if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2916 0) == GST_RTSP_OK) {
2917 cseq = atoi (header);
2922 /* make a record with the message as a string ans cseq */
2923 data = queue_response (watch, message_to_string (watch->conn, message), cseq);