RTSP: add support for Quicktime tunneled RTSP
[platform/upstream/gstreamer.git] / gst-libs / gst / rtsp / gstrtspconnection.c
1 /* GStreamer
2  * Copyright (C) <2005,2006> Wim Taymans <wim@fluendo.com>
3  *
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.
8  *
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.
13  *
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.
18  */
19 /*
20  * Unless otherwise indicated, Source Code is licensed under MIT license.
21  * See further explanation attached in License Statement (distributed in the file
22  * LICENSE).
23  *
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:
30  *
31  * The above copyright notice and this permission notice shall be included in all
32  * copies or substantial portions of the Software.
33  *
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
40  * SOFTWARE.
41  */
42
43 /**
44  * SECTION:gstrtspconnection
45  * @short_description: manage RTSP connections
46  * @see_also: gstrtspurl
47  *  
48  * <refsect2>
49  * <para>
50  * This object manages the RTSP connection to the server. It provides function
51  * to receive and send bytes and messages.
52  * </para>
53  * </refsect2>
54  *  
55  * Last reviewed on 2007-07-24 (0.10.14)
56  */
57
58 #ifdef HAVE_CONFIG_H
59 #  include <config.h>
60 #endif
61
62 #include <stdio.h>
63 #include <errno.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <time.h>
67
68 #ifdef HAVE_UNISTD_H
69 #include <unistd.h>
70 #endif
71
72
73 /* we include this here to get the G_OS_* defines */
74 #include <glib.h>
75 #include <gst/gst.h>
76
77 #ifdef G_OS_WIN32
78 #include <winsock2.h>
79 #include <ws2tcpip.h>
80 #define EINPROGRESS WSAEINPROGRESS
81 #else
82 #include <sys/ioctl.h>
83 #include <netdb.h>
84 #include <sys/socket.h>
85 #include <netinet/in.h>
86 #include <arpa/inet.h>
87 #include <fcntl.h>
88 #endif
89
90 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
91 #include <sys/filio.h>
92 #endif
93
94 #include "gstrtspconnection.h"
95 #include "gstrtspbase64.h"
96 #include "md5.h"
97
98 static GstRTSPResult read_line (gint fd, guint8 * buffer, guint * idx,
99     guint size);
100 static GstRTSPResult parse_key_value (guint8 * buffer, gchar * key,
101     guint keysize, gchar ** value);
102 static void parse_string (gchar * dest, gint size, gchar ** src);
103
104 #ifdef G_OS_WIN32
105 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
106 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
107 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
108 #define CLOSE_SOCKET(sock) closesocket (sock)
109 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
110 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
111 /* According to Microsoft's connect() documentation this one returns
112  * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
113 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
114 #else
115 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
116 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
117 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
118 #define CLOSE_SOCKET(sock) close (sock)
119 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
120 #define ERRNO_IS_EINTR (errno == EINTR)
121 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
122 #endif
123
124 #define ADD_POLLFD(fdset, pfd, fd)        \
125 G_STMT_START {                            \
126   (pfd)->fd = fd;                         \
127   gst_poll_add_fd (fdset, pfd);           \
128 } G_STMT_END
129
130 #define REMOVE_POLLFD(fdset, pfd)          \
131 G_STMT_START {                             \
132   if ((pfd)->fd != -1) {                   \
133     GST_DEBUG ("remove fd %d", (pfd)->fd); \
134     gst_poll_remove_fd (fdset, pfd);       \
135     CLOSE_SOCKET ((pfd)->fd);              \
136     (pfd)->fd = -1;                        \
137   }                                        \
138 } G_STMT_END
139
140 struct _GstRTSPConnection
141 {
142   /*< private > */
143   /* URL for the connection */
144   GstRTSPUrl *url;
145
146   /* connection state */
147   GstPollFD fd0;
148   GstPollFD fd1;
149
150   GstPollFD *readfd;
151   GstPollFD *writefd;
152
153   gboolean tunneled;
154
155   GstPoll *fdset;
156   gchar *ip;
157
158   /* Session state */
159   gint cseq;                    /* sequence number */
160   gchar session_id[512];        /* session id */
161   gint timeout;                 /* session timeout in seconds */
162   GTimer *timer;                /* timeout timer */
163
164   /* Authentication */
165   GstRTSPAuthMethod auth_method;
166   gchar *username;
167   gchar *passwd;
168   GHashTable *auth_params;
169 };
170
171 #ifdef G_OS_WIN32
172 static int
173 inet_aton (const char *c, struct in_addr *paddr)
174 {
175   /* note that inet_addr is deprecated on unix because
176    * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
177    * address. */
178   paddr->s_addr = inet_addr (c);
179
180   if (paddr->s_addr == INADDR_NONE)
181     return 0;
182
183   return 1;
184 }
185 #endif
186
187 enum
188 {
189   STATE_START = 0,
190   STATE_DATA_HEADER,
191   STATE_DATA_BODY,
192   STATE_READ_LINES,
193   STATE_END,
194   STATE_LAST
195 };
196
197 /* a structure for constructing RTSPMessages */
198 typedef struct
199 {
200   gint state;
201   guint8 buffer[4096];
202   guint offset;
203
204   guint line;
205   guint8 *body_data;
206   glong body_len;
207 } GstRTSPBuilder;
208
209 static void
210 build_reset (GstRTSPBuilder * builder)
211 {
212   g_free (builder->body_data);
213   memset (builder, 0, sizeof (builder));
214 }
215
216 /**
217  * gst_rtsp_connection_create:
218  * @url: a #GstRTSPUrl 
219  * @conn: storage for a #GstRTSPConnection
220  *
221  * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
222  * The connection will not yet attempt to connect to @url, use
223  * gst_rtsp_connection_connect().
224  *
225  * Returns: #GST_RTSP_OK when @conn contains a valid connection.
226  */
227 GstRTSPResult
228 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
229 {
230   GstRTSPConnection *newconn;
231 #ifdef G_OS_WIN32
232   WSADATA w;
233   int error;
234 #endif
235
236   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
237
238 #ifdef G_OS_WIN32
239   error = WSAStartup (0x0202, &w);
240
241   if (error)
242     goto startup_error;
243
244   if (w.wVersion != 0x0202)
245     goto version_error;
246 #endif
247
248   newconn = g_new0 (GstRTSPConnection, 1);
249
250   if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
251     goto no_fdset;
252
253   newconn->url = url;
254   newconn->fd0.fd = -1;
255   newconn->fd1.fd = -1;
256   newconn->timer = g_timer_new ();
257   newconn->timeout = 60;
258   newconn->tunneled = FALSE;
259
260   newconn->auth_method = GST_RTSP_AUTH_NONE;
261   newconn->username = NULL;
262   newconn->passwd = NULL;
263   newconn->auth_params = NULL;
264
265   *conn = newconn;
266
267   return GST_RTSP_OK;
268
269   /* ERRORS */
270 #ifdef G_OS_WIN32
271 startup_error:
272   {
273     g_warning ("Error %d on WSAStartup", error);
274     return GST_RTSP_EWSASTART;
275   }
276 version_error:
277   {
278     g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
279         w.wVersion);
280     WSACleanup ();
281     return GST_RTSP_EWSAVERSION;
282   }
283 #endif
284 no_fdset:
285   {
286     g_free (newconn);
287 #ifdef G_OS_WIN32
288     WSACleanup ();
289 #endif
290     return GST_RTSP_ESYS;
291   }
292 }
293
294 /**
295  * gst_rtsp_connection_accept:
296  * @sock: a socket
297  * @conn: storage for a #GstRTSPConnection
298  *
299  * Accept a new connection on @sock and create a new #GstRTSPConnection for
300  * handling communication on new socket.
301  *
302  * Returns: #GST_RTSP_OK when @conn contains a valid connection.
303  *
304  * Since: 0.10.23
305  */
306 GstRTSPResult
307 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
308 {
309   int fd;
310   unsigned int address_len;
311   GstRTSPConnection *newconn = NULL;
312   struct sockaddr_in address;
313   GstRTSPUrl *url;
314 #ifdef G_OS_WIN32
315   gulong flags = 1;
316 #endif
317
318   address_len = sizeof (address);
319   memset (&address, 0, address_len);
320
321 #ifndef G_OS_WIN32
322   fd = accept (sock, (struct sockaddr *) &address, &address_len);
323 #else
324   fd = accept (sock, (struct sockaddr *) &address, (gint *) & address_len);
325 #endif /* G_OS_WIN32 */
326   if (fd == -1)
327     goto accept_failed;
328
329   /* set to non-blocking mode so that we can cancel the communication */
330 #ifndef G_OS_WIN32
331   fcntl (fd, F_SETFL, O_NONBLOCK);
332 #else
333   ioctlsocket (fd, FIONBIO, &flags);
334 #endif /* G_OS_WIN32 */
335
336   /* create a url for the client address */
337   url = g_new0 (GstRTSPUrl, 1);
338   url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
339   url->port = address.sin_port;
340
341   /* now create the connection object */
342   gst_rtsp_connection_create (url, &newconn);
343   ADD_POLLFD (newconn->fdset, &newconn->fd0, fd);
344
345   newconn->readfd = &newconn->fd0;
346   newconn->writefd = &newconn->fd0;
347
348   *conn = newconn;
349
350   return GST_RTSP_OK;
351
352   /* ERRORS */
353 accept_failed:
354   {
355     return GST_RTSP_ESYS;
356   }
357 }
358
359 static const gchar *
360 do_resolve (const gchar * host)
361 {
362   struct hostent *hostinfo;
363   struct in_addr addr;
364   const gchar *ip;
365 #ifdef G_OS_WIN32
366   struct in_addr *addrp;
367 #else
368   char **addrs;
369   gchar ipbuf[INET_ADDRSTRLEN];
370 #endif /* G_OS_WIN32 */
371
372   ip = NULL;
373
374   /* first check if it already is an IP address */
375   if (inet_aton (host, &addr)) {
376     ip = host;
377   } else {
378     hostinfo = gethostbyname (host);
379     if (!hostinfo)
380       goto not_resolved;        /* h_errno set */
381
382     if (hostinfo->h_addrtype != AF_INET)
383       goto not_ip;              /* host not an IP host */
384 #ifdef G_OS_WIN32
385     addrp = (struct in_addr *) hostinfo->h_addr_list[0];
386     /* this is not threadsafe */
387     ip = inet_ntoa (*addrp);
388 #else
389     addrs = hostinfo->h_addr_list;
390     ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
391         sizeof (ipbuf));
392 #endif /* G_OS_WIN32 */
393   }
394   return ip;
395
396   /* ERRORS */
397 not_resolved:
398   {
399     GST_ERROR ("could not resolve %s", host);
400     return NULL;
401   }
402 not_ip:
403   {
404     GST_ERROR ("not an IP address");
405     return NULL;
406   }
407 }
408
409 static GstRTSPResult
410 do_connect (const gchar * ip, guint16 port, GstPollFD * fdout,
411     GstPoll * fdset, GTimeVal * timeout)
412 {
413   gint fd;
414   struct sockaddr_in sa_in;
415   gint ret;
416 #ifdef G_OS_WIN32
417   unsigned long flags = 1;
418 #endif /* G_OS_WIN32 */
419   GstClockTime to;
420   gint retval;
421
422   g_message ("connect %s:%u", ip, port);
423
424   memset (&sa_in, 0, sizeof (sa_in));
425   sa_in.sin_family = AF_INET;   /* network socket */
426   sa_in.sin_port = htons (port);        /* on port */
427   sa_in.sin_addr.s_addr = inet_addr (ip);       /* on host ip */
428
429   fd = socket (AF_INET, SOCK_STREAM, 0);
430   if (fd == -1)
431     goto no_socket;
432
433   /* set to non-blocking mode so that we can cancel the connect */
434 #ifndef G_OS_WIN32
435   fcntl (fd, F_SETFL, O_NONBLOCK);
436 #else
437   ioctlsocket (fd, FIONBIO, &flags);
438 #endif /* G_OS_WIN32 */
439
440   /* add the socket to our fdset */
441   ADD_POLLFD (fdset, fdout, fd);
442
443   /* we are going to connect ASYNC now */
444   ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
445   if (ret == 0)
446     goto done;
447   if (!ERRNO_IS_EINPROGRESS)
448     goto sys_error;
449
450   /* wait for connect to complete up to the specified timeout or until we got
451    * interrupted. */
452   gst_poll_fd_ctl_write (fdset, fdout, TRUE);
453
454   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
455
456   do {
457     retval = gst_poll_wait (fdset, to);
458   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
459
460   if (retval == 0)
461     goto timeout;
462   else if (retval == -1)
463     goto sys_error;
464
465   /* we can still have an error connecting on windows */
466   if (gst_poll_fd_has_error (fdset, fdout)) {
467     socklen_t len = sizeof (errno);
468 #ifndef G_OS_WIN32
469     getsockopt (fd, SOL_SOCKET, SO_ERROR, &errno, &len);
470 #else
471     getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &errno, &len);
472 #endif
473     goto sys_error;
474   }
475
476   gst_poll_fd_ignored (fdset, fdout);
477 done:
478
479   return GST_RTSP_OK;
480
481   /* ERRORS */
482 no_socket:
483   {
484     GST_ERROR ("no socket %d (%s)", errno, g_strerror (errno));
485     return GST_RTSP_ESYS;
486   }
487 sys_error:
488   {
489     GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
490     REMOVE_POLLFD (fdset, fdout);
491     return GST_RTSP_ESYS;
492   }
493 timeout:
494   {
495     GST_ERROR ("timeout");
496     REMOVE_POLLFD (fdset, fdout);
497     return GST_RTSP_ETIMEOUT;
498   }
499 }
500
501 static GstRTSPResult
502 setup_tunneling (GstRTSPConnection * conn, GTimeVal * timeout)
503 {
504   gchar sessionid[24];
505   gint i;
506   GstRTSPResult res;
507   gchar *str;
508   guint idx, line;
509   gint retval;
510   GstClockTime to;
511   const gchar *ip;
512   guint16 port;
513   gchar codestr[4];
514   gint code;
515
516   /* create a random sessionid */
517   for (i = 0; i < 24; i++)
518     sessionid[i] = g_random_int_range ('a', 'z');
519   sessionid[23] = '\0';
520
521   /* */
522   str = g_strdup_printf ("GET %s HTTP/1.0\r\n"
523       "x-sessioncookie: %s\r\n"
524       "Accept: application/x-rtsp-tunnelled\r\n"
525       "Pragma: no-cache\r\n"
526       "Cache-Control: no-cache\r\n" "\r\n", conn->url->host, sessionid);
527
528   /* we start by writing to this fd */
529   conn->writefd = &conn->fd0;
530
531   res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
532   g_free (str);
533   if (res != GST_RTSP_OK)
534     goto write_failed;
535
536   gst_poll_fd_ctl_write (conn->fdset, &conn->fd0, FALSE);
537   gst_poll_fd_ctl_read (conn->fdset, &conn->fd0, TRUE);
538
539   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
540
541   line = 0;
542   while (TRUE) {
543     guint8 buffer[4096];
544
545     idx = 0;
546     while (TRUE) {
547       res = read_line (conn->fd0.fd, buffer, &idx, sizeof (buffer));
548       if (res == GST_RTSP_EEOF)
549         goto eof;
550       if (res == GST_RTSP_OK)
551         break;
552       if (res != GST_RTSP_EINTR)
553         goto read_error;
554
555       do {
556         retval = gst_poll_wait (conn->fdset, to);
557       } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
558
559       /* check for timeout */
560       if (retval == 0)
561         goto timeout;
562
563       if (retval == -1) {
564         if (errno == EBUSY)
565           goto stopped;
566         else
567           goto select_error;
568       }
569     }
570
571     /* check for last line */
572     if (buffer[0] == '\r')
573       buffer[0] = '\0';
574     if (buffer[0] == '\0')
575       break;
576
577     if (line == 0) {
578       /* first line, parse response */
579       gchar versionstr[20];
580       gchar *bptr;
581
582       bptr = (gchar *) buffer;
583
584       parse_string (versionstr, sizeof (versionstr), &bptr);
585       parse_string (codestr, sizeof (codestr), &bptr);
586       code = atoi (codestr);
587
588       if (code != 200)
589         goto wrong_result;
590     } else {
591       gchar key[32];
592       gchar *value;
593
594       /* other lines, parse key/value */
595       res = parse_key_value (buffer, key, sizeof (key), &value);
596       if (res == GST_RTSP_OK) {
597         /* we got a new ip address */
598         if (g_ascii_strcasecmp (key, "x-server-ip-address") == 0) {
599           g_free (conn->ip);
600           conn->ip = g_strdup (value);
601         }
602       }
603     }
604     line++;
605   }
606
607   if (!(ip = do_resolve (conn->ip)))
608     goto not_resolved;
609
610   /* get the port from the url */
611   gst_rtsp_url_get_port (conn->url, &port);
612
613   /* connect to the host/port */
614   res = do_connect (ip, port, &conn->fd1, conn->fdset, timeout);
615   if (res != GST_RTSP_OK)
616     goto connect_failed;
617
618   /* this is now our writing socket */
619   conn->writefd = &conn->fd1;
620
621   /* */
622   str = g_strdup_printf ("POST %s HTTP/1.0\r\n"
623       "x-sessioncookie: %s\r\n"
624       "Content-Type: application/x-rtsp-tunnelled\r\n"
625       "Pragma: no-cache\r\n"
626       "Cache-Control: no-cache\r\n"
627       "Content-Length: 32767\r\n"
628       "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n"
629       "\r\n", conn->url->host, sessionid);
630
631   /* we start by writing to this fd */
632   conn->writefd = &conn->fd1;
633
634   res = gst_rtsp_connection_write (conn, (guint8 *) str, strlen (str), timeout);
635   g_free (str);
636   if (res != GST_RTSP_OK)
637     goto write_failed;
638
639   return res;
640
641   /* ERRORS */
642 write_failed:
643   {
644     GST_ERROR ("write failed", res);
645     return res;
646   }
647 eof:
648   {
649     return GST_RTSP_EEOF;
650   }
651 read_error:
652   {
653     return res;
654   }
655 timeout:
656   {
657     return GST_RTSP_ETIMEOUT;
658   }
659 select_error:
660   {
661     return GST_RTSP_ESYS;
662   }
663 stopped:
664   {
665     return GST_RTSP_EINTR;
666   }
667 wrong_result:
668   {
669     GST_ERROR ("got failure response %d %s", code, codestr);
670     return GST_RTSP_ERROR;
671   }
672 not_resolved:
673   {
674     GST_ERROR ("could not resolve %s", conn->ip);
675     return GST_RTSP_ENET;
676   }
677 connect_failed:
678   {
679     GST_ERROR ("failed to connect");
680     return res;
681   }
682 }
683
684 /**
685  * gst_rtsp_connection_connect:
686  * @conn: a #GstRTSPConnection 
687  * @timeout: a #GTimeVal timeout
688  *
689  * Attempt to connect to the url of @conn made with
690  * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
691  * forever. If @timeout contains a valid timeout, this function will return
692  * #GST_RTSP_ETIMEOUT after the timeout expired.
693  *
694  * This function can be cancelled with gst_rtsp_connection_flush().
695  *
696  * Returns: #GST_RTSP_OK when a connection could be made.
697  */
698 GstRTSPResult
699 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
700 {
701   GstRTSPResult res;
702   const gchar *ip;
703   guint16 port;
704   GstRTSPUrl *url;
705 #ifdef G_OS_WIN32
706   unsigned long flags = 1;
707 #endif /* G_OS_WIN32 */
708
709   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
710   g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
711   g_return_val_if_fail (conn->fd0.fd < 0, GST_RTSP_EINVAL);
712
713   url = conn->url;
714
715   if (!(ip = do_resolve (url->host)))
716     goto not_resolved;
717
718   /* get the port from the url */
719   gst_rtsp_url_get_port (url, &port);
720
721   /* connect to the host/port */
722   res = do_connect (ip, port, &conn->fd0, conn->fdset, timeout);
723   if (res != GST_RTSP_OK)
724     goto connect_failed;
725
726   g_free (conn->ip);
727   conn->ip = g_strdup (ip);
728
729   /* this is our read URL */
730   conn->readfd = &conn->fd0;
731
732   if (conn->tunneled) {
733     res = setup_tunneling (conn, timeout);
734     if (res != GST_RTSP_OK)
735       goto tunneling_failed;
736   } else {
737     conn->writefd = &conn->fd0;
738   }
739
740   return GST_RTSP_OK;
741
742 not_resolved:
743   {
744     GST_ERROR ("could not resolve %s", url->host);
745     return GST_RTSP_ENET;
746   }
747 connect_failed:
748   {
749     GST_ERROR ("failed to connect");
750     return res;
751   }
752 tunneling_failed:
753   {
754     GST_ERROR ("failed to setup tunneling");
755     return res;
756   }
757 }
758
759 static void
760 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
761 {
762   static const char hexdigits[] = "0123456789abcdef";
763   int i;
764
765   for (i = 0; i < 16; i++) {
766     string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
767     string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
768   }
769   string[32] = 0;
770 }
771
772 static void
773 auth_digest_compute_hex_urp (const gchar * username,
774     const gchar * realm, const gchar * password, gchar hex_urp[33])
775 {
776   struct MD5Context md5_context;
777   unsigned char digest[16];
778
779   MD5Init (&md5_context);
780   MD5Update (&md5_context, username, strlen (username));
781   MD5Update (&md5_context, ":", 1);
782   MD5Update (&md5_context, realm, strlen (realm));
783   MD5Update (&md5_context, ":", 1);
784   MD5Update (&md5_context, password, strlen (password));
785   MD5Final (digest, &md5_context);
786   md5_digest_to_hex_string (digest, hex_urp);
787 }
788
789 static void
790 auth_digest_compute_response (const gchar * method,
791     const gchar * uri, const gchar * hex_a1, const gchar * nonce,
792     gchar response[33])
793 {
794   char hex_a2[33];
795   struct MD5Context md5_context;
796   unsigned char digest[16];
797
798   /* compute A2 */
799   MD5Init (&md5_context);
800   MD5Update (&md5_context, method, strlen (method));
801   MD5Update (&md5_context, ":", 1);
802   MD5Update (&md5_context, uri, strlen (uri));
803   MD5Final (digest, &md5_context);
804   md5_digest_to_hex_string (digest, hex_a2);
805
806   /* compute KD */
807   MD5Init (&md5_context);
808   MD5Update (&md5_context, hex_a1, strlen (hex_a1));
809   MD5Update (&md5_context, ":", 1);
810   MD5Update (&md5_context, nonce, strlen (nonce));
811   MD5Update (&md5_context, ":", 1);
812
813   MD5Update (&md5_context, hex_a2, 32);
814   MD5Final (digest, &md5_context);
815   md5_digest_to_hex_string (digest, response);
816 }
817
818 static void
819 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
820 {
821   switch (conn->auth_method) {
822     case GST_RTSP_AUTH_BASIC:{
823       gchar *user_pass =
824           g_strdup_printf ("%s:%s", conn->username, conn->passwd);
825       gchar *user_pass64 =
826           gst_rtsp_base64_encode (user_pass, strlen (user_pass));
827       gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
828
829       gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
830           auth_string);
831
832       g_free (user_pass);
833       g_free (user_pass64);
834       break;
835     }
836     case GST_RTSP_AUTH_DIGEST:{
837       gchar response[33], hex_urp[33];
838       gchar *auth_string, *auth_string2;
839       gchar *realm;
840       gchar *nonce;
841       gchar *opaque;
842       const gchar *uri;
843       const gchar *method;
844
845       /* we need to have some params set */
846       if (conn->auth_params == NULL)
847         break;
848
849       /* we need the realm and nonce */
850       realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
851       nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
852       if (realm == NULL || nonce == NULL)
853         break;
854
855       auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
856           hex_urp);
857
858       method = gst_rtsp_method_as_text (message->type_data.request.method);
859       uri = message->type_data.request.uri;
860
861       /* Assume no qop, algorithm=md5, stale=false */
862       /* For algorithm MD5, a1 = urp. */
863       auth_digest_compute_response (method, uri, hex_urp, nonce, response);
864       auth_string = g_strdup_printf ("Digest username=\"%s\", "
865           "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
866           conn->username, realm, nonce, uri, response);
867
868       opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
869       if (opaque) {
870         auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
871             opaque);
872         g_free (auth_string);
873         auth_string = auth_string2;
874       }
875       gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
876           auth_string);
877       break;
878     }
879     default:
880       /* Nothing to do */
881       break;
882   }
883 }
884
885 static void
886 add_date_header (GstRTSPMessage * message)
887 {
888   GTimeVal tv;
889   gchar date_string[100];
890   time_t t;
891
892 #ifdef HAVE_GMTIME_R
893   struct tm tm_;
894 #endif
895
896   g_get_current_time (&tv);
897   t = (time_t) tv.tv_sec;
898
899 #ifdef HAVE_GMTIME_R
900   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
901       gmtime_r (&t, &tm_));
902 #else
903   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
904       gmtime (&t));
905 #endif
906
907   gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
908 }
909
910 static GstRTSPResult
911 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
912 {
913   guint left;
914
915   if (*idx > size)
916     return GST_RTSP_ERROR;
917
918   left = size - *idx;
919
920   while (left) {
921     gint r;
922
923     r = WRITE_SOCKET (fd, &buffer[*idx], left);
924     if (r == 0) {
925       return GST_RTSP_EINTR;
926     } else if (r < 0) {
927       if (ERRNO_IS_EAGAIN)
928         return GST_RTSP_EINTR;
929       if (!ERRNO_IS_EINTR)
930         return GST_RTSP_ESYS;
931     } else {
932       left -= r;
933       *idx += r;
934     }
935   }
936   return GST_RTSP_OK;
937 }
938
939 static GstRTSPResult
940 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size)
941 {
942   guint left;
943
944   if (*idx > size)
945     return GST_RTSP_ERROR;
946
947   left = size - *idx;
948
949   while (left) {
950     gint r;
951
952     r = READ_SOCKET (fd, &buffer[*idx], left);
953     if (r == 0) {
954       return GST_RTSP_EEOF;
955     } else if (r < 0) {
956       if (ERRNO_IS_EAGAIN)
957         return GST_RTSP_EINTR;
958       if (!ERRNO_IS_EINTR)
959         return GST_RTSP_ESYS;
960     } else {
961       left -= r;
962       *idx += r;
963     }
964   }
965   return GST_RTSP_OK;
966 }
967
968 static GstRTSPResult
969 read_line (gint fd, guint8 * buffer, guint * idx, guint size)
970 {
971   while (TRUE) {
972     guint8 c;
973     gint r;
974
975     r = READ_SOCKET (fd, &c, 1);
976     if (r == 0) {
977       return GST_RTSP_EEOF;
978     } else if (r < 0) {
979       if (ERRNO_IS_EAGAIN)
980         return GST_RTSP_EINTR;
981       if (!ERRNO_IS_EINTR)
982         return GST_RTSP_ESYS;
983     } else {
984       if (c == '\n')            /* end on \n */
985         break;
986       if (c == '\r')            /* ignore \r */
987         continue;
988
989       if (*idx < size - 1)
990         buffer[(*idx)++] = c;
991     }
992   }
993   buffer[*idx] = '\0';
994
995   return GST_RTSP_OK;
996 }
997
998 /**
999  * gst_rtsp_connection_write:
1000  * @conn: a #GstRTSPConnection
1001  * @data: the data to write
1002  * @size: the size of @data
1003  * @timeout: a timeout value or #NULL
1004  *
1005  * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1006  * the specified @timeout. @timeout can be #NULL, in which case this function
1007  * might block forever.
1008  * 
1009  * This function can be cancelled with gst_rtsp_connection_flush().
1010  *
1011  * Returns: #GST_RTSP_OK on success.
1012  */
1013 GstRTSPResult
1014 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1015     guint size, GTimeVal * timeout)
1016 {
1017   guint offset;
1018   gint retval;
1019   GstClockTime to;
1020   GstRTSPResult res;
1021
1022   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1023   g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1024   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1025
1026   gst_poll_set_controllable (conn->fdset, TRUE);
1027   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1028   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1029   /* clear all previous poll results */
1030   gst_poll_fd_ignored (conn->fdset, conn->writefd);
1031   gst_poll_fd_ignored (conn->fdset, conn->readfd);
1032
1033   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1034
1035   offset = 0;
1036
1037   while (TRUE) {
1038     /* try to write */
1039     res = write_bytes (conn->writefd->fd, data, &offset, size);
1040     if (res == GST_RTSP_OK)
1041       break;
1042     if (res != GST_RTSP_EINTR)
1043       goto write_error;
1044
1045     /* not all is written, wait until we can write more */
1046     do {
1047       retval = gst_poll_wait (conn->fdset, to);
1048     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1049
1050     if (retval == 0)
1051       goto timeout;
1052
1053     if (retval == -1) {
1054       if (errno == EBUSY)
1055         goto stopped;
1056       else
1057         goto select_error;
1058     }
1059   }
1060   return GST_RTSP_OK;
1061
1062   /* ERRORS */
1063 timeout:
1064   {
1065     return GST_RTSP_ETIMEOUT;
1066   }
1067 select_error:
1068   {
1069     return GST_RTSP_ESYS;
1070   }
1071 stopped:
1072   {
1073     return GST_RTSP_EINTR;
1074   }
1075 write_error:
1076   {
1077     return res;
1078   }
1079 }
1080
1081 static GString *
1082 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1083 {
1084   GString *str = NULL;
1085
1086   str = g_string_new ("");
1087
1088   switch (message->type) {
1089     case GST_RTSP_MESSAGE_REQUEST:
1090       /* create request string, add CSeq */
1091       g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1092           "CSeq: %d\r\n",
1093           gst_rtsp_method_as_text (message->type_data.request.method),
1094           message->type_data.request.uri, conn->cseq++);
1095       /* add session id if we have one */
1096       if (conn->session_id[0] != '\0') {
1097         gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1098             conn->session_id);
1099       }
1100       /* add any authentication headers */
1101       add_auth_header (conn, message);
1102       break;
1103     case GST_RTSP_MESSAGE_RESPONSE:
1104       /* create response string */
1105       g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1106           message->type_data.response.code, message->type_data.response.reason);
1107       break;
1108     case GST_RTSP_MESSAGE_DATA:
1109     {
1110       guint8 data_header[4];
1111
1112       /* prepare data header */
1113       data_header[0] = '$';
1114       data_header[1] = message->type_data.data.channel;
1115       data_header[2] = (message->body_size >> 8) & 0xff;
1116       data_header[3] = message->body_size & 0xff;
1117
1118       /* create string with header and data */
1119       str = g_string_append_len (str, (gchar *) data_header, 4);
1120       str =
1121           g_string_append_len (str, (gchar *) message->body,
1122           message->body_size);
1123       break;
1124     }
1125     default:
1126       g_string_free (str, TRUE);
1127       g_return_val_if_reached (NULL);
1128       break;
1129   }
1130
1131   /* append headers and body */
1132   if (message->type != GST_RTSP_MESSAGE_DATA) {
1133     /* add date header */
1134     add_date_header (message);
1135
1136     /* append headers */
1137     gst_rtsp_message_append_headers (message, str);
1138
1139     /* append Content-Length and body if needed */
1140     if (message->body != NULL && message->body_size > 0) {
1141       gchar *len;
1142
1143       len = g_strdup_printf ("%d", message->body_size);
1144       g_string_append_printf (str, "%s: %s\r\n",
1145           gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1146       g_free (len);
1147       /* header ends here */
1148       g_string_append (str, "\r\n");
1149       str =
1150           g_string_append_len (str, (gchar *) message->body,
1151           message->body_size);
1152     } else {
1153       /* just end headers */
1154       g_string_append (str, "\r\n");
1155     }
1156   }
1157
1158   return str;
1159 }
1160
1161 /**
1162  * gst_rtsp_connection_send:
1163  * @conn: a #GstRTSPConnection
1164  * @message: the message to send
1165  * @timeout: a timeout value or #NULL
1166  *
1167  * Attempt to send @message to the connected @conn, blocking up to
1168  * the specified @timeout. @timeout can be #NULL, in which case this function
1169  * might block forever.
1170  * 
1171  * This function can be cancelled with gst_rtsp_connection_flush().
1172  *
1173  * Returns: #GST_RTSP_OK on success.
1174  */
1175 GstRTSPResult
1176 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1177     GTimeVal * timeout)
1178 {
1179   GString *string = NULL;
1180   GstRTSPResult res;
1181   gchar *str;
1182   gsize len;
1183
1184   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1185   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1186
1187   if (!(string = message_to_string (conn, message)))
1188     goto no_message;
1189
1190   if (conn->tunneled) {
1191     str = g_base64_encode ((const guchar *) string->str, string->len);
1192     g_string_free (string, TRUE);
1193     len = strlen (str);
1194   } else {
1195     str = string->str;
1196     len = string->len;
1197     g_string_free (string, FALSE);
1198   }
1199
1200   /* write request */
1201   res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1202
1203   g_free (str);
1204
1205   return res;
1206
1207 no_message:
1208   {
1209     g_warning ("Wrong message");
1210     return GST_RTSP_EINVAL;
1211   }
1212 }
1213
1214 static void
1215 parse_string (gchar * dest, gint size, gchar ** src)
1216 {
1217   gint idx;
1218
1219   idx = 0;
1220   /* skip spaces */
1221   while (g_ascii_isspace (**src))
1222     (*src)++;
1223
1224   while (!g_ascii_isspace (**src) && **src != '\0') {
1225     if (idx < size - 1)
1226       dest[idx++] = **src;
1227     (*src)++;
1228   }
1229   if (size > 0)
1230     dest[idx] = '\0';
1231 }
1232
1233 static void
1234 parse_key (gchar * dest, gint size, gchar ** src)
1235 {
1236   gint idx;
1237
1238   idx = 0;
1239   while (**src != ':' && **src != '\0') {
1240     if (idx < size - 1)
1241       dest[idx++] = **src;
1242     (*src)++;
1243   }
1244   if (size > 0)
1245     dest[idx] = '\0';
1246 }
1247
1248 static GstRTSPResult
1249 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1250 {
1251   GstRTSPResult res;
1252   gchar versionstr[20];
1253   gchar codestr[4];
1254   gint code;
1255   gchar *bptr;
1256
1257   bptr = (gchar *) buffer;
1258
1259   parse_string (versionstr, sizeof (versionstr), &bptr);
1260   parse_string (codestr, sizeof (codestr), &bptr);
1261   code = atoi (codestr);
1262
1263   while (g_ascii_isspace (*bptr))
1264     bptr++;
1265
1266   if (strcmp (versionstr, "RTSP/1.0") == 0)
1267     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1268         parse_error);
1269   else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1270     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
1271         parse_error);
1272     msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
1273   } else
1274     goto parse_error;
1275
1276   return GST_RTSP_OK;
1277
1278 parse_error:
1279   {
1280     return GST_RTSP_EPARSE;
1281   }
1282 }
1283
1284 static GstRTSPResult
1285 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1286 {
1287   GstRTSPResult res = GST_RTSP_OK;
1288   gchar versionstr[20];
1289   gchar methodstr[20];
1290   gchar urlstr[4096];
1291   gchar *bptr;
1292   GstRTSPMethod method;
1293
1294   bptr = (gchar *) buffer;
1295
1296   parse_string (methodstr, sizeof (methodstr), &bptr);
1297   method = gst_rtsp_find_method (methodstr);
1298
1299   parse_string (urlstr, sizeof (urlstr), &bptr);
1300   if (*urlstr == '\0')
1301     res = GST_RTSP_EPARSE;
1302
1303   parse_string (versionstr, sizeof (versionstr), &bptr);
1304
1305   if (*bptr != '\0')
1306     res = GST_RTSP_EPARSE;
1307
1308   if (strcmp (versionstr, "RTSP/1.0") == 0) {
1309     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
1310       res = GST_RTSP_EPARSE;
1311   } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1312     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
1313       res = GST_RTSP_EPARSE;
1314     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1315   } else {
1316     gst_rtsp_message_init_request (msg, method, urlstr);
1317     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1318     res = GST_RTSP_EPARSE;
1319   }
1320
1321   return res;
1322 }
1323
1324 static GstRTSPResult
1325 parse_key_value (guint8 * buffer, gchar * key, guint keysize, gchar ** value)
1326 {
1327   gchar *bptr;
1328
1329   bptr = (gchar *) buffer;
1330
1331   /* read key */
1332   parse_key (key, keysize, &bptr);
1333   if (*bptr != ':')
1334     goto no_column;
1335
1336   bptr++;
1337   while (g_ascii_isspace (*bptr))
1338     bptr++;
1339
1340   *value = bptr;
1341
1342   return GST_RTSP_OK;
1343
1344   /* ERRORS */
1345 no_column:
1346   {
1347     return GST_RTSP_EPARSE;
1348   }
1349 }
1350
1351 /* parsing lines means reading a Key: Value pair */
1352 static GstRTSPResult
1353 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1354 {
1355   GstRTSPResult res;
1356   gchar key[32];
1357   gchar *value;
1358   GstRTSPHeaderField field;
1359
1360   res = parse_key_value (buffer, key, sizeof (key), &value);
1361   if (res != GST_RTSP_OK)
1362     goto parse_error;
1363
1364   field = gst_rtsp_find_header_field (key);
1365   if (field != GST_RTSP_HDR_INVALID)
1366     gst_rtsp_message_add_header (msg, field, value);
1367
1368   return GST_RTSP_OK;
1369
1370   /* ERRORS */
1371 parse_error:
1372   {
1373     return res;
1374   }
1375 }
1376
1377 /* returns:
1378  *  GST_RTSP_OK when a complete message was read.
1379  *  GST_RTSP_EEOF: when the socket is closed
1380  *  GST_RTSP_EINTR: when more data is needed.
1381  *  GST_RTSP_..: some other error occured.
1382  */
1383 static GstRTSPResult
1384 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1385     GstRTSPConnection * conn)
1386 {
1387   GstRTSPResult res;
1388
1389   while (TRUE) {
1390     switch (builder->state) {
1391       case STATE_START:
1392         builder->offset = 0;
1393         res =
1394             read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1395             &builder->offset, 1);
1396         if (res != GST_RTSP_OK)
1397           goto done;
1398
1399         /* we have 1 bytes now and we can see if this is a data message or
1400          * not */
1401         if (builder->buffer[0] == '$') {
1402           /* data message, prepare for the header */
1403           builder->state = STATE_DATA_HEADER;
1404         } else {
1405           builder->line = 0;
1406           builder->state = STATE_READ_LINES;
1407         }
1408         break;
1409       case STATE_DATA_HEADER:
1410       {
1411         res =
1412             read_bytes (conn->readfd->fd, (guint8 *) builder->buffer,
1413             &builder->offset, 4);
1414         if (res != GST_RTSP_OK)
1415           goto done;
1416
1417         gst_rtsp_message_init_data (message, builder->buffer[1]);
1418
1419         builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1420         builder->body_data = g_malloc (builder->body_len + 1);
1421         builder->body_data[builder->body_len] = '\0';
1422         builder->offset = 0;
1423         builder->state = STATE_DATA_BODY;
1424         break;
1425       }
1426       case STATE_DATA_BODY:
1427       {
1428         res =
1429             read_bytes (conn->readfd->fd, builder->body_data, &builder->offset,
1430             builder->body_len);
1431         if (res != GST_RTSP_OK)
1432           goto done;
1433
1434         /* we have the complete body now, store in the message adjusting the
1435          * length to include the traling '\0' */
1436         gst_rtsp_message_take_body (message,
1437             (guint8 *) builder->body_data, builder->body_len + 1);
1438         builder->body_data = NULL;
1439         builder->body_len = 0;
1440
1441         builder->state = STATE_END;
1442         break;
1443       }
1444       case STATE_READ_LINES:
1445       {
1446         res = read_line (conn->readfd->fd, builder->buffer, &builder->offset,
1447             sizeof (builder->buffer));
1448         if (res != GST_RTSP_OK)
1449           goto done;
1450
1451         /* we have a regular response */
1452         if (builder->buffer[0] == '\r') {
1453           builder->buffer[0] = '\0';
1454         }
1455
1456         if (builder->buffer[0] == '\0') {
1457           gchar *hdrval;
1458
1459           /* empty line, end of message header */
1460           /* see if there is a Content-Length header */
1461           if (gst_rtsp_message_get_header (message,
1462                   GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1463             /* there is, prepare to read the body */
1464             builder->body_len = atol (hdrval);
1465             builder->body_data = g_malloc (builder->body_len + 1);
1466             builder->body_data[builder->body_len] = '\0';
1467             builder->offset = 0;
1468             builder->state = STATE_DATA_BODY;
1469           } else {
1470             builder->state = STATE_END;
1471           }
1472           break;
1473         }
1474
1475         /* we have a line */
1476         if (builder->line == 0) {
1477           /* first line, check for response status */
1478           if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1479             res = parse_response_status (builder->buffer, message);
1480           } else {
1481             res = parse_request_line (builder->buffer, message);
1482           }
1483         } else {
1484           /* else just parse the line */
1485           parse_line (builder->buffer, message);
1486         }
1487         builder->line++;
1488         builder->offset = 0;
1489         break;
1490       }
1491       case STATE_END:
1492       {
1493         gchar *session_id;
1494
1495         if (message->type == GST_RTSP_MESSAGE_DATA) {
1496           /* data messages don't have headers */
1497           res = GST_RTSP_OK;
1498           goto done;
1499         }
1500
1501         /* save session id in the connection for further use */
1502         if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1503                 &session_id, 0) == GST_RTSP_OK) {
1504           gint maxlen, i;
1505
1506           maxlen = sizeof (conn->session_id) - 1;
1507           /* the sessionid can have attributes marked with ;
1508            * Make sure we strip them */
1509           for (i = 0; session_id[i] != '\0'; i++) {
1510             if (session_id[i] == ';') {
1511               maxlen = i;
1512               /* parse timeout */
1513               do {
1514                 i++;
1515               } while (g_ascii_isspace (session_id[i]));
1516               if (g_str_has_prefix (&session_id[i], "timeout=")) {
1517                 gint to;
1518
1519                 /* if we parsed something valid, configure */
1520                 if ((to = atoi (&session_id[i + 9])) > 0)
1521                   conn->timeout = to;
1522               }
1523               break;
1524             }
1525           }
1526
1527           /* make sure to not overflow */
1528           strncpy (conn->session_id, session_id, maxlen);
1529           conn->session_id[maxlen] = '\0';
1530         }
1531         res = GST_RTSP_OK;
1532         goto done;
1533       }
1534       default:
1535         res = GST_RTSP_ERROR;
1536         break;
1537     }
1538   }
1539 done:
1540   return res;
1541 }
1542
1543 /**
1544  * gst_rtsp_connection_read:
1545  * @conn: a #GstRTSPConnection
1546  * @data: the data to read
1547  * @size: the size of @data
1548  * @timeout: a timeout value or #NULL
1549  *
1550  * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1551  * the specified @timeout. @timeout can be #NULL, in which case this function
1552  * might block forever.
1553  *
1554  * This function can be cancelled with gst_rtsp_connection_flush().
1555  *
1556  * Returns: #GST_RTSP_OK on success.
1557  */
1558 GstRTSPResult
1559 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1560     GTimeVal * timeout)
1561 {
1562   guint offset;
1563   gint retval;
1564   GstClockTime to;
1565   GstRTSPResult res;
1566
1567   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1568   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1569   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1570
1571   if (size == 0)
1572     return GST_RTSP_OK;
1573
1574   offset = 0;
1575
1576   /* configure timeout if any */
1577   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1578
1579   gst_poll_set_controllable (conn->fdset, TRUE);
1580   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1581   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1582
1583   while (TRUE) {
1584     res = read_bytes (conn->readfd->fd, data, &offset, size);
1585     if (res == GST_RTSP_EEOF)
1586       goto eof;
1587     if (res == GST_RTSP_OK)
1588       break;
1589     if (res != GST_RTSP_EINTR)
1590       goto read_error;
1591
1592     do {
1593       retval = gst_poll_wait (conn->fdset, to);
1594     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1595
1596     /* check for timeout */
1597     if (retval == 0)
1598       goto select_timeout;
1599
1600     if (retval == -1) {
1601       if (errno == EBUSY)
1602         goto stopped;
1603       else
1604         goto select_error;
1605     }
1606     gst_poll_set_controllable (conn->fdset, FALSE);
1607   }
1608   return GST_RTSP_OK;
1609
1610   /* ERRORS */
1611 select_error:
1612   {
1613     return GST_RTSP_ESYS;
1614   }
1615 select_timeout:
1616   {
1617     return GST_RTSP_ETIMEOUT;
1618   }
1619 stopped:
1620   {
1621     return GST_RTSP_EINTR;
1622   }
1623 eof:
1624   {
1625     return GST_RTSP_EEOF;
1626   }
1627 read_error:
1628   {
1629     return res;
1630   }
1631 }
1632
1633
1634 /**
1635  * gst_rtsp_connection_receive:
1636  * @conn: a #GstRTSPConnection
1637  * @message: the message to read
1638  * @timeout: a timeout value or #NULL
1639  *
1640  * Attempt to read into @message from the connected @conn, blocking up to
1641  * the specified @timeout. @timeout can be #NULL, in which case this function
1642  * might block forever.
1643  * 
1644  * This function can be cancelled with gst_rtsp_connection_flush().
1645  *
1646  * Returns: #GST_RTSP_OK on success.
1647  */
1648 GstRTSPResult
1649 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1650     GTimeVal * timeout)
1651 {
1652   GstRTSPResult res;
1653   GstRTSPBuilder builder = { 0 };
1654   gint retval;
1655   GstClockTime to;
1656
1657   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1658   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1659   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1660
1661   /* configure timeout if any */
1662   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1663
1664   gst_poll_set_controllable (conn->fdset, TRUE);
1665   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
1666   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
1667
1668   while (TRUE) {
1669     res = build_next (&builder, message, conn);
1670     if (res == GST_RTSP_EEOF)
1671       goto eof;
1672     if (res == GST_RTSP_OK)
1673       break;
1674     if (res != GST_RTSP_EINTR)
1675       goto read_error;
1676
1677     do {
1678       retval = gst_poll_wait (conn->fdset, to);
1679     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1680
1681     /* check for timeout */
1682     if (retval == 0)
1683       goto select_timeout;
1684
1685     if (retval == -1) {
1686       if (errno == EBUSY)
1687         goto stopped;
1688       else
1689         goto select_error;
1690     }
1691     gst_poll_set_controllable (conn->fdset, FALSE);
1692   }
1693
1694   /* we have a message here */
1695   build_reset (&builder);
1696
1697   return GST_RTSP_OK;
1698
1699   /* ERRORS */
1700 select_error:
1701   {
1702     res = GST_RTSP_ESYS;
1703     goto cleanup;
1704   }
1705 select_timeout:
1706   {
1707     res = GST_RTSP_ETIMEOUT;
1708     goto cleanup;
1709   }
1710 stopped:
1711   {
1712     res = GST_RTSP_EINTR;
1713     goto cleanup;
1714   }
1715 eof:
1716   {
1717     res = GST_RTSP_EEOF;
1718     goto cleanup;
1719   }
1720 read_error:
1721 cleanup:
1722   {
1723     build_reset (&builder);
1724     gst_rtsp_message_unset (message);
1725     return res;
1726   }
1727 }
1728
1729 /**
1730  * gst_rtsp_connection_close:
1731  * @conn: a #GstRTSPConnection
1732  *
1733  * Close the connected @conn.
1734  * 
1735  * Returns: #GST_RTSP_OK on success.
1736  */
1737 GstRTSPResult
1738 gst_rtsp_connection_close (GstRTSPConnection * conn)
1739 {
1740   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1741
1742   g_free (conn->ip);
1743   conn->ip = NULL;
1744
1745   REMOVE_POLLFD (conn->fdset, &conn->fd0);
1746   REMOVE_POLLFD (conn->fdset, &conn->fd1);
1747   conn->writefd = NULL;
1748   conn->readfd = NULL;
1749
1750   return GST_RTSP_OK;
1751 }
1752
1753 /**
1754  * gst_rtsp_connection_free:
1755  * @conn: a #GstRTSPConnection
1756  *
1757  * Close and free @conn.
1758  * 
1759  * Returns: #GST_RTSP_OK on success.
1760  */
1761 GstRTSPResult
1762 gst_rtsp_connection_free (GstRTSPConnection * conn)
1763 {
1764   GstRTSPResult res;
1765
1766   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1767
1768   res = gst_rtsp_connection_close (conn);
1769   gst_poll_free (conn->fdset);
1770   g_timer_destroy (conn->timer);
1771   g_free (conn->username);
1772   g_free (conn->passwd);
1773   gst_rtsp_connection_clear_auth_params (conn);
1774   g_free (conn);
1775 #ifdef G_OS_WIN32
1776   WSACleanup ();
1777 #endif
1778
1779   return res;
1780 }
1781
1782 /**
1783  * gst_rtsp_connection_poll:
1784  * @conn: a #GstRTSPConnection
1785  * @events: a bitmask of #GstRTSPEvent flags to check
1786  * @revents: location for result flags 
1787  * @timeout: a timeout
1788  *
1789  * Wait up to the specified @timeout for the connection to become available for
1790  * at least one of the operations specified in @events. When the function returns
1791  * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1792  * @conn.
1793  *
1794  * @timeout can be #NULL, in which case this function might block forever.
1795  *
1796  * This function can be cancelled with gst_rtsp_connection_flush().
1797  * 
1798  * Returns: #GST_RTSP_OK on success.
1799  *
1800  * Since: 0.10.15
1801  */
1802 GstRTSPResult
1803 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1804     GstRTSPEvent * revents, GTimeVal * timeout)
1805 {
1806   GstClockTime to;
1807   gint retval;
1808
1809   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1810   g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
1811   g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
1812   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
1813   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1814
1815   gst_poll_set_controllable (conn->fdset, TRUE);
1816
1817   /* add fd to writer set when asked to */
1818   gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
1819       events & GST_RTSP_EV_WRITE);
1820
1821   /* add fd to reader set when asked to */
1822   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
1823
1824   /* configure timeout if any */
1825   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1826
1827   do {
1828     retval = gst_poll_wait (conn->fdset, to);
1829   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1830
1831   if (retval == 0)
1832     goto select_timeout;
1833
1834   if (retval == -1) {
1835     if (errno == EBUSY)
1836       goto stopped;
1837     else
1838       goto select_error;
1839   }
1840
1841   *revents = 0;
1842   if (events & GST_RTSP_EV_READ) {
1843     if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
1844       *revents |= GST_RTSP_EV_READ;
1845   }
1846   if (events & GST_RTSP_EV_WRITE) {
1847     if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
1848       *revents |= GST_RTSP_EV_WRITE;
1849   }
1850   return GST_RTSP_OK;
1851
1852   /* ERRORS */
1853 select_timeout:
1854   {
1855     return GST_RTSP_ETIMEOUT;
1856   }
1857 select_error:
1858   {
1859     return GST_RTSP_ESYS;
1860   }
1861 stopped:
1862   {
1863     return GST_RTSP_EINTR;
1864   }
1865 }
1866
1867 /**
1868  * gst_rtsp_connection_next_timeout:
1869  * @conn: a #GstRTSPConnection
1870  * @timeout: a timeout
1871  *
1872  * Calculate the next timeout for @conn, storing the result in @timeout.
1873  * 
1874  * Returns: #GST_RTSP_OK.
1875  */
1876 GstRTSPResult
1877 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
1878 {
1879   gdouble elapsed;
1880   glong sec;
1881   gulong usec;
1882
1883   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1884   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
1885
1886   elapsed = g_timer_elapsed (conn->timer, &usec);
1887   if (elapsed >= conn->timeout) {
1888     sec = 0;
1889     usec = 0;
1890   } else {
1891     sec = conn->timeout - elapsed;
1892   }
1893
1894   timeout->tv_sec = sec;
1895   timeout->tv_usec = usec;
1896
1897   return GST_RTSP_OK;
1898 }
1899
1900 /**
1901  * gst_rtsp_connection_reset_timeout:
1902  * @conn: a #GstRTSPConnection
1903  *
1904  * Reset the timeout of @conn.
1905  * 
1906  * Returns: #GST_RTSP_OK.
1907  */
1908 GstRTSPResult
1909 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
1910 {
1911   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1912
1913   g_timer_start (conn->timer);
1914
1915   return GST_RTSP_OK;
1916 }
1917
1918 /**
1919  * gst_rtsp_connection_flush:
1920  * @conn: a #GstRTSPConnection
1921  * @flush: start or stop the flush
1922  *
1923  * Start or stop the flushing action on @conn. When flushing, all current
1924  * and future actions on @conn will return #GST_RTSP_EINTR until the connection
1925  * is set to non-flushing mode again.
1926  * 
1927  * Returns: #GST_RTSP_OK.
1928  */
1929 GstRTSPResult
1930 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
1931 {
1932   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1933
1934   gst_poll_set_flushing (conn->fdset, flush);
1935
1936   return GST_RTSP_OK;
1937 }
1938
1939 /**
1940  * gst_rtsp_connection_set_auth:
1941  * @conn: a #GstRTSPConnection
1942  * @method: authentication method
1943  * @user: the user
1944  * @pass: the password
1945  *
1946  * Configure @conn for authentication mode @method with @user and @pass as the
1947  * user and password respectively.
1948  * 
1949  * Returns: #GST_RTSP_OK.
1950  */
1951 GstRTSPResult
1952 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
1953     GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
1954 {
1955   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1956
1957   if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
1958           || g_strrstr (user, ":") != NULL))
1959     return GST_RTSP_EINVAL;
1960
1961   /* Make sure the username and passwd are being set for authentication */
1962   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
1963     return GST_RTSP_EINVAL;
1964
1965   /* ":" chars are not allowed in usernames for basic auth */
1966   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
1967     return GST_RTSP_EINVAL;
1968
1969   g_free (conn->username);
1970   g_free (conn->passwd);
1971
1972   conn->auth_method = method;
1973   conn->username = g_strdup (user);
1974   conn->passwd = g_strdup (pass);
1975
1976   return GST_RTSP_OK;
1977 }
1978
1979 /**
1980  * str_case_hash:
1981  * @key: ASCII string to hash
1982  *
1983  * Hashes @key in a case-insensitive manner.
1984  *
1985  * Returns: the hash code.
1986  **/
1987 static guint
1988 str_case_hash (gconstpointer key)
1989 {
1990   const char *p = key;
1991   guint h = g_ascii_toupper (*p);
1992
1993   if (h)
1994     for (p += 1; *p != '\0'; p++)
1995       h = (h << 5) - h + g_ascii_toupper (*p);
1996
1997   return h;
1998 }
1999
2000 /**
2001  * str_case_equal:
2002  * @v1: an ASCII string
2003  * @v2: another ASCII string
2004  *
2005  * Compares @v1 and @v2 in a case-insensitive manner
2006  *
2007  * Returns: %TRUE if they are equal (modulo case)
2008  **/
2009 static gboolean
2010 str_case_equal (gconstpointer v1, gconstpointer v2)
2011 {
2012   const char *string1 = v1;
2013   const char *string2 = v2;
2014
2015   return g_ascii_strcasecmp (string1, string2) == 0;
2016 }
2017
2018 /**
2019  * gst_rtsp_connection_set_auth_param:
2020  * @conn: a #GstRTSPConnection
2021  * @param: authentication directive
2022  * @value: value
2023  *
2024  * Setup @conn with authentication directives. This is not necesary for
2025  * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2026  * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2027  * in the WWW-Authenticate response header and can include realm, domain,
2028  * nonce, opaque, stale, algorithm, qop as per RFC2617.
2029  * 
2030  * Since: 0.10.20
2031  */
2032 void
2033 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2034     const gchar * param, const gchar * value)
2035 {
2036   g_return_if_fail (conn != NULL);
2037   g_return_if_fail (param != NULL);
2038
2039   if (conn->auth_params == NULL) {
2040     conn->auth_params =
2041         g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2042   }
2043   g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2044 }
2045
2046 /**
2047  * gst_rtsp_connection_clear_auth_params:
2048  * @conn: a #GstRTSPConnection
2049  *
2050  * Clear the list of authentication directives stored in @conn.
2051  *
2052  * Since: 0.10.20
2053  */
2054 void
2055 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2056 {
2057   g_return_if_fail (conn != NULL);
2058
2059   if (conn->auth_params != NULL) {
2060     g_hash_table_destroy (conn->auth_params);
2061     conn->auth_params = NULL;
2062   }
2063 }
2064
2065 static GstRTSPResult
2066 set_qos_dscp (gint fd, guint qos_dscp)
2067 {
2068   union gst_sockaddr
2069   {
2070     struct sockaddr sa;
2071     struct sockaddr_in6 sa_in6;
2072     struct sockaddr_storage sa_stor;
2073   } sa;
2074   socklen_t slen = sizeof (sa);
2075   gint af;
2076   gint tos;
2077
2078   if (fd == -1)
2079     return GST_RTSP_OK;
2080
2081   if (getsockname (fd, &sa.sa, &slen) < 0)
2082     goto no_getsockname;
2083
2084   af = sa.sa.sa_family;
2085
2086   /* if this is an IPv4-mapped address then do IPv4 QoS */
2087   if (af == AF_INET6) {
2088     if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2089       af = AF_INET;
2090   }
2091
2092   /* extract and shift 6 bits of the DSCP */
2093   tos = (qos_dscp & 0x3f) << 2;
2094
2095   switch (af) {
2096     case AF_INET:
2097       if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2098         goto no_setsockopt;
2099       break;
2100     case AF_INET6:
2101 #ifdef IPV6_TCLASS
2102       if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2103         goto no_setsockopt;
2104       break;
2105 #endif
2106     default:
2107       goto wrong_family;
2108   }
2109
2110   return GST_RTSP_OK;
2111
2112   /* ERRORS */
2113 no_getsockname:
2114 no_setsockopt:
2115   {
2116     return GST_RTSP_ESYS;
2117   }
2118
2119 wrong_family:
2120   {
2121     return GST_RTSP_ERROR;
2122   }
2123 }
2124
2125 /**
2126  * gst_rtsp_connection_set_qos_dscp:
2127  * @conn: a #GstRTSPConnection
2128  * @qos_dscp: DSCP value
2129  *
2130  * Configure @conn to use the specified DSCP value.
2131  *
2132  * Returns: #GST_RTSP_OK on success.
2133  *
2134  * Since: 0.10.20
2135  */
2136 GstRTSPResult
2137 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2138 {
2139   GstRTSPResult res;
2140
2141   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2142   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2143   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2144
2145   res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2146   if (res == GST_RTSP_OK)
2147     res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2148
2149   return res;
2150 }
2151
2152
2153 /**
2154  * gst_rtsp_connection_get_url:
2155  * @conn: a #GstRTSPConnection
2156  *
2157  * Retrieve the URL of the other end of @conn.
2158  *
2159  * Returns: The URL. This value remains valid until the
2160  * connection is closed.
2161  *
2162  * Since: 0.10.23
2163  */
2164 GstRTSPUrl *
2165 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2166 {
2167   g_return_val_if_fail (conn != NULL, NULL);
2168
2169   return conn->url;
2170 }
2171
2172 /**
2173  * gst_rtsp_connection_get_ip:
2174  * @conn: a #GstRTSPConnection
2175  *
2176  * Retrieve the IP address of the other end of @conn.
2177  *
2178  * Returns: The IP address as a string. this value remains valid until the
2179  * connection is closed.
2180  *
2181  * Since: 0.10.20
2182  */
2183 const gchar *
2184 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2185 {
2186   g_return_val_if_fail (conn != NULL, NULL);
2187
2188   return conn->ip;
2189 }
2190
2191 /**
2192  * gst_rtsp_connection_set_tunneled:
2193  * @conn: a #GstRTSPConnection
2194  * @tunneled: the new state
2195  *
2196  * Set the HTTP tunneling state of the connection. This must be configured before
2197  * the @conn is connected.
2198  *
2199  * Since: 0.10.23
2200  */
2201 void
2202 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2203 {
2204   g_return_if_fail (conn != NULL);
2205   g_return_if_fail (conn->readfd == NULL);
2206   g_return_if_fail (conn->writefd == NULL);
2207
2208   conn->tunneled = tunneled;
2209 }
2210
2211 /**
2212  * gst_rtsp_connection_is_tunneled:
2213  * @conn: a #GstRTSPConnection
2214  *
2215  * Get the tunneling state of the connection. 
2216  *
2217  * Returns: if @conn is using HTTP tunneling.
2218  *
2219  * Since: 0.10.23
2220  */
2221 gboolean
2222 gst_rtsp_connection_is_tunneled (GstRTSPConnection * conn)
2223 {
2224   g_return_val_if_fail (conn != NULL, FALSE);
2225
2226   return conn->tunneled;
2227 }
2228
2229
2230 #define READ_COND   (G_IO_IN | G_IO_HUP | G_IO_ERR)
2231 #define WRITE_COND  (G_IO_OUT | G_IO_ERR)
2232
2233 typedef struct
2234 {
2235   GString *str;
2236   guint cseq;
2237 } GstRTSPRec;
2238
2239 /* async functions */
2240 struct _GstRTSPWatch
2241 {
2242   GSource source;
2243
2244   GstRTSPConnection *conn;
2245
2246   GstRTSPBuilder builder;
2247   GstRTSPMessage message;
2248
2249   GPollFD readfd;
2250   GPollFD writefd;
2251   gboolean write_added;
2252
2253   /* queued message for transmission */
2254   GList *messages;
2255   guint8 *write_data;
2256   guint write_off;
2257   guint write_len;
2258   guint write_cseq;
2259
2260   GstRTSPWatchFuncs funcs;
2261
2262   gpointer user_data;
2263   GDestroyNotify notify;
2264 };
2265
2266 static gboolean
2267 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2268 {
2269   GstRTSPWatch *watch = (GstRTSPWatch *) source;
2270
2271   *timeout = (watch->conn->timeout * 1000);
2272
2273   return FALSE;
2274 }
2275
2276 static gboolean
2277 gst_rtsp_source_check (GSource * source)
2278 {
2279   GstRTSPWatch *watch = (GstRTSPWatch *) source;
2280
2281   if (watch->readfd.revents & READ_COND)
2282     return TRUE;
2283
2284   if (watch->writefd.revents & WRITE_COND)
2285     return TRUE;
2286
2287   return FALSE;
2288 }
2289
2290 static gboolean
2291 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
2292     gpointer user_data)
2293 {
2294   GstRTSPWatch *watch = (GstRTSPWatch *) source;
2295   GstRTSPResult res;
2296
2297   /* first read as much as we can */
2298   if (watch->readfd.revents & READ_COND) {
2299     do {
2300       res = build_next (&watch->builder, &watch->message, watch->conn);
2301       if (res == GST_RTSP_EINTR)
2302         break;
2303       if (res == GST_RTSP_EEOF)
2304         goto eof;
2305       if (res != GST_RTSP_OK)
2306         goto error;
2307
2308       if (watch->funcs.message_received)
2309         watch->funcs.message_received (watch, &watch->message,
2310             watch->user_data);
2311
2312       gst_rtsp_message_unset (&watch->message);
2313       build_reset (&watch->builder);
2314     } while (FALSE);
2315   }
2316
2317   if (watch->writefd.revents & WRITE_COND) {
2318     do {
2319       if (watch->write_data == NULL) {
2320         GstRTSPRec *data;
2321
2322         if (!watch->messages)
2323           goto done;
2324
2325         /* no data, get a new message from the queue */
2326         data = watch->messages->data;
2327         watch->messages = g_list_delete_link (watch->messages, watch->messages);
2328
2329         watch->write_off = 0;
2330         watch->write_len = data->str->len;
2331         watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
2332         watch->write_cseq = data->cseq;
2333
2334         g_slice_free (GstRTSPRec, data);
2335       }
2336
2337       res = write_bytes (watch->writefd.fd, watch->write_data,
2338           &watch->write_off, watch->write_len);
2339       if (res == GST_RTSP_EINTR)
2340         break;
2341       if (res != GST_RTSP_OK)
2342         goto error;
2343
2344       if (watch->funcs.message_sent)
2345         watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
2346
2347     done:
2348       if (watch->messages == NULL && watch->write_added) {
2349         g_source_remove_poll ((GSource *) watch, &watch->writefd);
2350         watch->write_added = FALSE;
2351         watch->writefd.revents = 0;
2352       }
2353       g_free (watch->write_data);
2354       watch->write_data = NULL;
2355     } while (FALSE);
2356   }
2357
2358   return TRUE;
2359
2360   /* ERRORS */
2361 eof:
2362   {
2363     if (watch->funcs.closed)
2364       watch->funcs.closed (watch, watch->user_data);
2365     return FALSE;
2366   }
2367 error:
2368   {
2369     if (watch->funcs.error)
2370       watch->funcs.error (watch, res, watch->user_data);
2371     return FALSE;
2372   }
2373 }
2374
2375 static void
2376 gst_rtsp_source_finalize (GSource * source)
2377 {
2378   GstRTSPWatch *watch = (GstRTSPWatch *) source;
2379   GList *walk;
2380
2381   build_reset (&watch->builder);
2382
2383   for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2384     GstRTSPRec *data = walk->data;
2385
2386     g_string_free (data->str, TRUE);
2387     g_slice_free (GstRTSPRec, data);
2388   }
2389   g_list_free (watch->messages);
2390   g_free (watch->write_data);
2391
2392   if (watch->notify)
2393     watch->notify (watch->user_data);
2394 }
2395
2396 static GSourceFuncs gst_rtsp_source_funcs = {
2397   gst_rtsp_source_prepare,
2398   gst_rtsp_source_check,
2399   gst_rtsp_source_dispatch,
2400   gst_rtsp_source_finalize
2401 };
2402
2403 /**
2404  * gst_rtsp_watch_new:
2405  * @conn: a #GstRTSPConnection
2406  * @funcs: watch functions
2407  * @user_data: user data to pass to @funcs
2408  * @notify: notify when @user_data is not referenced anymore
2409  *
2410  * Create a watch object for @conn. The functions provided in @funcs will be
2411  * called with @user_data when activity happened on the watch.
2412  *
2413  * The new watch is usually created so that it can be attached to a
2414  * maincontext with gst_rtsp_watch_attach(). 
2415  *
2416  * @conn must exist for the entire lifetime of the watch.
2417  *
2418  * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2419  * communication. Free with gst_rtsp_watch_unref () after usage.
2420  *
2421  * Since: 0.10.23
2422  */
2423 GstRTSPWatch *
2424 gst_rtsp_watch_new (GstRTSPConnection * conn,
2425     GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2426 {
2427   GstRTSPWatch *result;
2428
2429   g_return_val_if_fail (conn != NULL, NULL);
2430   g_return_val_if_fail (funcs != NULL, NULL);
2431   g_return_val_if_fail (conn->readfd != NULL, NULL);
2432   g_return_val_if_fail (conn->writefd != NULL, NULL);
2433
2434   result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2435       sizeof (GstRTSPWatch));
2436
2437   result->conn = conn;
2438   result->builder.state = STATE_START;
2439
2440   result->readfd.fd = conn->readfd->fd;
2441   result->readfd.events = READ_COND;
2442   result->readfd.revents = 0;
2443
2444   result->writefd.fd = conn->writefd->fd;
2445   result->writefd.events = WRITE_COND;
2446   result->writefd.revents = 0;
2447   result->write_added = FALSE;
2448
2449   result->funcs = *funcs;
2450   result->user_data = user_data;
2451   result->notify = notify;
2452
2453   /* only add the read fd, the write fd is only added when we have data
2454    * to send. */
2455   g_source_add_poll ((GSource *) result, &result->readfd);
2456
2457   return result;
2458 }
2459
2460 /**
2461  * gst_rtsp_watch_attach:
2462  * @watch: a #GstRTSPWatch
2463  * @context: a GMainContext (if NULL, the default context will be used)
2464  *
2465  * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2466  *
2467  * Returns: the ID (greater than 0) for the watch within the GMainContext. 
2468  *
2469  * Since: 0.10.23
2470  */
2471 guint
2472 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2473 {
2474   g_return_val_if_fail (watch != NULL, 0);
2475
2476   return g_source_attach ((GSource *) watch, context);
2477 }
2478
2479 /**
2480  * gst_rtsp_watch_unref:
2481  * @watch: a #GstRTSPWatch
2482  *
2483  * Decreases the reference count of @watch by one. If the resulting reference
2484  * count is zero the watch and associated memory will be destroyed.
2485  *
2486  * Since: 0.10.23
2487  */
2488 void
2489 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2490 {
2491   g_return_if_fail (watch != NULL);
2492
2493   g_source_unref ((GSource *) watch);
2494 }
2495
2496 /**
2497  * gst_rtsp_watch_queue_message:
2498  * @watch: a #GstRTSPWatch
2499  * @message: a #GstRTSPMessage
2500  *
2501  * Queue a @message for transmission in @watch. The contents of this 
2502  * message will be serialized and transmitted when the connection of the
2503  * watch becomes writable.
2504  *
2505  * The return value of this function will be returned as the cseq argument in
2506  * the message_sent callback.
2507  *
2508  * Returns: the sequence number of the message or -1 if the cseq could not be
2509  * determined.
2510  *
2511  * Since: 0.10.23
2512  */
2513 guint
2514 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2515 {
2516   GstRTSPRec *data;
2517   gchar *header;
2518   guint cseq;
2519
2520   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2521   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2522
2523   /* get the cseq from the message, when we finish writing this message on the
2524    * socket we will have to pass the cseq to the callback. */
2525   if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2526           0) == GST_RTSP_OK) {
2527     cseq = atoi (header);
2528   } else {
2529     cseq = -1;
2530   }
2531
2532   /* make a record with the message as a string ans cseq */
2533   data = g_slice_new (GstRTSPRec);
2534   data->str = message_to_string (watch->conn, message);
2535   data->cseq = cseq;
2536
2537   /* add the record to a queue */
2538   watch->messages = g_list_append (watch->messages, data);
2539
2540   /* make sure the main context will now also check for writability on the
2541    * socket */
2542   if (!watch->write_added) {
2543     g_source_add_poll ((GSource *) watch, &watch->writefd);
2544     watch->write_added = TRUE;
2545   }
2546   return cseq;
2547 }