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