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