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