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