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