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