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