rtspconnection: we can use GLib 2.18 API unconditionally now
[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   return GST_RTSP_OK;
1342
1343   /* ERRORS */
1344 timeout:
1345   {
1346     return GST_RTSP_ETIMEOUT;
1347   }
1348 select_error:
1349   {
1350     return GST_RTSP_ESYS;
1351   }
1352 stopped:
1353   {
1354     return GST_RTSP_EINTR;
1355   }
1356 write_error:
1357   {
1358     return res;
1359   }
1360 }
1361
1362 static GString *
1363 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1364 {
1365   GString *str = NULL;
1366
1367   str = g_string_new ("");
1368
1369   switch (message->type) {
1370     case GST_RTSP_MESSAGE_REQUEST:
1371       /* create request string, add CSeq */
1372       g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1373           "CSeq: %d\r\n",
1374           gst_rtsp_method_as_text (message->type_data.request.method),
1375           message->type_data.request.uri, conn->cseq++);
1376       /* add session id if we have one */
1377       if (conn->session_id[0] != '\0') {
1378         gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1379         gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1380             conn->session_id);
1381       }
1382       /* add any authentication headers */
1383       add_auth_header (conn, message);
1384       break;
1385     case GST_RTSP_MESSAGE_RESPONSE:
1386       /* create response string */
1387       g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1388           message->type_data.response.code, message->type_data.response.reason);
1389       break;
1390     case GST_RTSP_MESSAGE_HTTP_REQUEST:
1391       /* create request string */
1392       g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1393           gst_rtsp_method_as_text (message->type_data.request.method),
1394           message->type_data.request.uri,
1395           gst_rtsp_version_as_text (message->type_data.request.version));
1396       /* add any authentication headers */
1397       add_auth_header (conn, message);
1398       break;
1399     case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1400       /* create response string */
1401       g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1402           gst_rtsp_version_as_text (message->type_data.request.version),
1403           message->type_data.response.code, message->type_data.response.reason);
1404       break;
1405     case GST_RTSP_MESSAGE_DATA:
1406     {
1407       guint8 data_header[4];
1408
1409       /* prepare data header */
1410       data_header[0] = '$';
1411       data_header[1] = message->type_data.data.channel;
1412       data_header[2] = (message->body_size >> 8) & 0xff;
1413       data_header[3] = message->body_size & 0xff;
1414
1415       /* create string with header and data */
1416       str = g_string_append_len (str, (gchar *) data_header, 4);
1417       str =
1418           g_string_append_len (str, (gchar *) message->body,
1419           message->body_size);
1420       break;
1421     }
1422     default:
1423       g_string_free (str, TRUE);
1424       g_return_val_if_reached (NULL);
1425       break;
1426   }
1427
1428   /* append headers and body */
1429   if (message->type != GST_RTSP_MESSAGE_DATA) {
1430     gchar date_string[100];
1431
1432     gen_date_string (date_string, sizeof (date_string));
1433
1434     /* add date header */
1435     gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1436     gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1437
1438     /* append headers */
1439     gst_rtsp_message_append_headers (message, str);
1440
1441     /* append Content-Length and body if needed */
1442     if (message->body != NULL && message->body_size > 0) {
1443       gchar *len;
1444
1445       len = g_strdup_printf ("%d", message->body_size);
1446       g_string_append_printf (str, "%s: %s\r\n",
1447           gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1448       g_free (len);
1449       /* header ends here */
1450       g_string_append (str, "\r\n");
1451       str =
1452           g_string_append_len (str, (gchar *) message->body,
1453           message->body_size);
1454     } else {
1455       /* just end headers */
1456       g_string_append (str, "\r\n");
1457     }
1458   }
1459
1460   return str;
1461 }
1462
1463 /**
1464  * gst_rtsp_connection_send:
1465  * @conn: a #GstRTSPConnection
1466  * @message: the message to send
1467  * @timeout: a timeout value or #NULL
1468  *
1469  * Attempt to send @message to the connected @conn, blocking up to
1470  * the specified @timeout. @timeout can be #NULL, in which case this function
1471  * might block forever.
1472  * 
1473  * This function can be cancelled with gst_rtsp_connection_flush().
1474  *
1475  * Returns: #GST_RTSP_OK on success.
1476  */
1477 GstRTSPResult
1478 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1479     GTimeVal * timeout)
1480 {
1481   GString *string = NULL;
1482   GstRTSPResult res;
1483   gchar *str;
1484   gsize len;
1485
1486   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1487   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1488
1489   if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1490     goto no_message;
1491
1492   if (conn->tunneled) {
1493     str = g_base64_encode ((const guchar *) string->str, string->len);
1494     g_string_free (string, TRUE);
1495     len = strlen (str);
1496   } else {
1497     str = string->str;
1498     len = string->len;
1499     g_string_free (string, FALSE);
1500   }
1501
1502   /* write request */
1503   res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1504
1505   g_free (str);
1506
1507   return res;
1508
1509 no_message:
1510   {
1511     g_warning ("Wrong message");
1512     return GST_RTSP_EINVAL;
1513   }
1514 }
1515
1516 static GstRTSPResult
1517 parse_string (gchar * dest, gint size, gchar ** src)
1518 {
1519   GstRTSPResult res = GST_RTSP_OK;
1520   gint idx;
1521
1522   idx = 0;
1523   /* skip spaces */
1524   while (g_ascii_isspace (**src))
1525     (*src)++;
1526
1527   while (!g_ascii_isspace (**src) && **src != '\0') {
1528     if (idx < size - 1)
1529       dest[idx++] = **src;
1530     else
1531       res = GST_RTSP_EPARSE;
1532     (*src)++;
1533   }
1534   if (size > 0)
1535     dest[idx] = '\0';
1536
1537   return res;
1538 }
1539
1540 static GstRTSPResult
1541 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1542     GstRTSPVersion * version)
1543 {
1544   GstRTSPResult res = GST_RTSP_OK;
1545   gchar *ver;
1546
1547   if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1548     guint major;
1549     guint minor;
1550     gchar dummychar;
1551
1552     *ver++ = '\0';
1553
1554     /* the version number must be formatted as X.Y with nothing following */
1555     if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1556       res = GST_RTSP_EPARSE;
1557
1558     if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1559       if (major != 1 || minor != 0) {
1560         *version = GST_RTSP_VERSION_INVALID;
1561         res = GST_RTSP_ERROR;
1562       }
1563     } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1564       if (*type == GST_RTSP_MESSAGE_REQUEST)
1565         *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1566       else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1567         *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1568
1569       if (major == 1 && minor == 1) {
1570         *version = GST_RTSP_VERSION_1_1;
1571       } else if (major != 1 || minor != 0) {
1572         *version = GST_RTSP_VERSION_INVALID;
1573         res = GST_RTSP_ERROR;
1574       }
1575     } else
1576       res = GST_RTSP_EPARSE;
1577   } else
1578     res = GST_RTSP_EPARSE;
1579
1580   return res;
1581 }
1582
1583 static GstRTSPResult
1584 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1585 {
1586   GstRTSPResult res = GST_RTSP_OK;
1587   GstRTSPResult res2;
1588   gchar versionstr[20];
1589   gchar codestr[4];
1590   gint code;
1591   gchar *bptr;
1592
1593   bptr = (gchar *) buffer;
1594
1595   if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1596     res = GST_RTSP_EPARSE;
1597
1598   if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1599     res = GST_RTSP_EPARSE;
1600   code = atoi (codestr);
1601   if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1602     res = GST_RTSP_EPARSE;
1603
1604   while (g_ascii_isspace (*bptr))
1605     bptr++;
1606
1607   if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1608               NULL) != GST_RTSP_OK))
1609     res = GST_RTSP_EPARSE;
1610
1611   res2 = parse_protocol_version (versionstr, &msg->type,
1612       &msg->type_data.response.version);
1613   if (G_LIKELY (res == GST_RTSP_OK))
1614     res = res2;
1615
1616   return res;
1617 }
1618
1619 static GstRTSPResult
1620 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1621 {
1622   GstRTSPResult res = GST_RTSP_OK;
1623   GstRTSPResult res2;
1624   gchar versionstr[20];
1625   gchar methodstr[20];
1626   gchar urlstr[4096];
1627   gchar *bptr;
1628   GstRTSPMethod method;
1629
1630   bptr = (gchar *) buffer;
1631
1632   if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1633     res = GST_RTSP_EPARSE;
1634   method = gst_rtsp_find_method (methodstr);
1635
1636   if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1637     res = GST_RTSP_EPARSE;
1638   if (G_UNLIKELY (*urlstr == '\0'))
1639     res = GST_RTSP_EPARSE;
1640
1641   if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1642     res = GST_RTSP_EPARSE;
1643
1644   if (G_UNLIKELY (*bptr != '\0'))
1645     res = GST_RTSP_EPARSE;
1646
1647   if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1648               urlstr) != GST_RTSP_OK))
1649     res = GST_RTSP_EPARSE;
1650
1651   res2 = parse_protocol_version (versionstr, &msg->type,
1652       &msg->type_data.request.version);
1653   if (G_LIKELY (res == GST_RTSP_OK))
1654     res = res2;
1655
1656   if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1657     /* GET and POST are not allowed as RTSP methods */
1658     if (msg->type_data.request.method == GST_RTSP_GET ||
1659         msg->type_data.request.method == GST_RTSP_POST) {
1660       msg->type_data.request.method = GST_RTSP_INVALID;
1661       if (res == GST_RTSP_OK)
1662         res = GST_RTSP_ERROR;
1663     }
1664   } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1665     /* only GET and POST are allowed as HTTP 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   }
1673
1674   return res;
1675 }
1676
1677 /* parsing lines means reading a Key: Value pair */
1678 static GstRTSPResult
1679 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1680 {
1681   GstRTSPHeaderField field;
1682   gchar *line = (gchar *) buffer;
1683   gchar *value;
1684
1685   if ((value = strchr (line, ':')) == NULL || value == line)
1686     goto parse_error;
1687
1688   /* trim space before the colon */
1689   if (value[-1] == ' ')
1690     value[-1] = '\0';
1691
1692   /* replace the colon with a NUL */
1693   *value++ = '\0';
1694
1695   /* find the header */
1696   field = gst_rtsp_find_header_field (line);
1697   if (field == GST_RTSP_HDR_INVALID)
1698     goto done;
1699
1700   /* split up the value in multiple key:value pairs if it contains comma(s) */
1701   while (*value != '\0') {
1702     gchar *next_value;
1703     gchar *comma = NULL;
1704     gboolean quoted = FALSE;
1705     guint comment = 0;
1706
1707     /* trim leading space */
1708     if (*value == ' ')
1709       value++;
1710
1711     /* for headers which may not appear multiple times, and thus may not
1712      * contain multiple values on the same line, we can short-circuit the loop
1713      * below and the entire value results in just one key:value pair*/
1714     if (!gst_rtsp_header_allow_multiple (field))
1715       next_value = value + strlen (value);
1716     else
1717       next_value = value;
1718
1719     /* find the next value, taking special care of quotes and comments */
1720     while (*next_value != '\0') {
1721       if ((quoted || comment != 0) && *next_value == '\\' &&
1722           next_value[1] != '\0')
1723         next_value++;
1724       else if (comment == 0 && *next_value == '"')
1725         quoted = !quoted;
1726       else if (!quoted && *next_value == '(')
1727         comment++;
1728       else if (comment != 0 && *next_value == ')')
1729         comment--;
1730       else if (!quoted && comment == 0) {
1731         /* To quote RFC 2068: "User agents MUST take special care in parsing
1732          * the WWW-Authenticate field value if it contains more than one
1733          * challenge, or if more than one WWW-Authenticate header field is
1734          * provided, since the contents of a challenge may itself contain a
1735          * comma-separated list of authentication parameters."
1736          *
1737          * What this means is that we cannot just look for an unquoted comma
1738          * when looking for multiple values in Proxy-Authenticate and
1739          * WWW-Authenticate headers. Instead we need to look for the sequence
1740          * "comma [space] token space token" before we can split after the
1741          * comma...
1742          */
1743         if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1744             field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1745           if (*next_value == ',') {
1746             if (next_value[1] == ' ') {
1747               /* skip any space following the comma so we do not mistake it for
1748                * separating between two tokens */
1749               next_value++;
1750             }
1751             comma = next_value;
1752           } else if (*next_value == ' ' && next_value[1] != ',' &&
1753               next_value[1] != '=' && comma != NULL) {
1754             next_value = comma;
1755             comma = NULL;
1756             break;
1757           }
1758         } else if (*next_value == ',')
1759           break;
1760       }
1761
1762       next_value++;
1763     }
1764
1765     /* trim space */
1766     if (value != next_value && next_value[-1] == ' ')
1767       next_value[-1] = '\0';
1768
1769     if (*next_value != '\0')
1770       *next_value++ = '\0';
1771
1772     /* add the key:value pair */
1773     if (*value != '\0')
1774       gst_rtsp_message_add_header (msg, field, value);
1775
1776     value = next_value;
1777   }
1778
1779 done:
1780   return GST_RTSP_OK;
1781
1782   /* ERRORS */
1783 parse_error:
1784   {
1785     return GST_RTSP_EPARSE;
1786   }
1787 }
1788
1789 /* convert all consecutive whitespace to a single space */
1790 static void
1791 normalize_line (guint8 * buffer)
1792 {
1793   while (*buffer) {
1794     if (g_ascii_isspace (*buffer)) {
1795       guint8 *tmp;
1796
1797       *buffer++ = ' ';
1798       for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1799       }
1800       if (buffer != tmp)
1801         memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1802     } else {
1803       buffer++;
1804     }
1805   }
1806 }
1807
1808 /* returns:
1809  *  GST_RTSP_OK when a complete message was read.
1810  *  GST_RTSP_EEOF: when the socket is closed
1811  *  GST_RTSP_EINTR: when more data is needed.
1812  *  GST_RTSP_..: some other error occured.
1813  */
1814 static GstRTSPResult
1815 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1816     GstRTSPConnection * conn)
1817 {
1818   GstRTSPResult res;
1819
1820   while (TRUE) {
1821     switch (builder->state) {
1822       case STATE_START:
1823         builder->offset = 0;
1824         res =
1825             read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1826         if (res != GST_RTSP_OK)
1827           goto done;
1828
1829         /* we have 1 bytes now and we can see if this is a data message or
1830          * not */
1831         if (builder->buffer[0] == '$') {
1832           /* data message, prepare for the header */
1833           builder->state = STATE_DATA_HEADER;
1834         } else {
1835           builder->line = 0;
1836           builder->state = STATE_READ_LINES;
1837         }
1838         break;
1839       case STATE_DATA_HEADER:
1840       {
1841         res =
1842             read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1843         if (res != GST_RTSP_OK)
1844           goto done;
1845
1846         gst_rtsp_message_init_data (message, builder->buffer[1]);
1847
1848         builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1849         builder->body_data = g_malloc (builder->body_len + 1);
1850         builder->body_data[builder->body_len] = '\0';
1851         builder->offset = 0;
1852         builder->state = STATE_DATA_BODY;
1853         break;
1854       }
1855       case STATE_DATA_BODY:
1856       {
1857         res =
1858             read_bytes (conn, builder->body_data, &builder->offset,
1859             builder->body_len);
1860         if (res != GST_RTSP_OK)
1861           goto done;
1862
1863         /* we have the complete body now, store in the message adjusting the
1864          * length to include the traling '\0' */
1865         gst_rtsp_message_take_body (message,
1866             (guint8 *) builder->body_data, builder->body_len + 1);
1867         builder->body_data = NULL;
1868         builder->body_len = 0;
1869
1870         builder->state = STATE_END;
1871         break;
1872       }
1873       case STATE_READ_LINES:
1874       {
1875         res = read_line (conn, builder->buffer, &builder->offset,
1876             sizeof (builder->buffer));
1877         if (res != GST_RTSP_OK)
1878           goto done;
1879
1880         /* we have a regular response */
1881         if (builder->buffer[0] == '\0') {
1882           gchar *hdrval;
1883
1884           /* empty line, end of message header */
1885           /* see if there is a Content-Length header, but ignore it if this
1886            * is a POST request with an x-sessioncookie header */
1887           if (gst_rtsp_message_get_header (message,
1888                   GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1889               (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1890                   message->type_data.request.method != GST_RTSP_POST ||
1891                   gst_rtsp_message_get_header (message,
1892                       GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1893             /* there is, prepare to read the body */
1894             builder->body_len = atol (hdrval);
1895             builder->body_data = g_malloc (builder->body_len + 1);
1896             builder->body_data[builder->body_len] = '\0';
1897             builder->offset = 0;
1898             builder->state = STATE_DATA_BODY;
1899           } else {
1900             builder->state = STATE_END;
1901           }
1902           break;
1903         }
1904
1905         /* we have a line */
1906         normalize_line (builder->buffer);
1907         if (builder->line == 0) {
1908           /* first line, check for response status */
1909           if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1910               memcmp (builder->buffer, "HTTP", 4) == 0) {
1911             builder->status = parse_response_status (builder->buffer, message);
1912           } else {
1913             builder->status = parse_request_line (builder->buffer, message);
1914           }
1915         } else {
1916           /* else just parse the line */
1917           res = parse_line (builder->buffer, message);
1918           if (res != GST_RTSP_OK)
1919             builder->status = res;
1920         }
1921         builder->line++;
1922         builder->offset = 0;
1923         break;
1924       }
1925       case STATE_END:
1926       {
1927         gchar *session_cookie;
1928         gchar *session_id;
1929
1930         if (message->type == GST_RTSP_MESSAGE_DATA) {
1931           /* data messages don't have headers */
1932           res = GST_RTSP_OK;
1933           goto done;
1934         }
1935
1936         /* save the tunnel session in the connection */
1937         if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1938             !conn->manual_http &&
1939             conn->tstate == TUNNEL_STATE_NONE &&
1940             gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1941                 &session_cookie, 0) == GST_RTSP_OK) {
1942           strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1943           conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1944           conn->tunneled = TRUE;
1945         }
1946
1947         /* save session id in the connection for further use */
1948         if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1949             gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1950                 &session_id, 0) == GST_RTSP_OK) {
1951           gint maxlen, i;
1952
1953           maxlen = sizeof (conn->session_id) - 1;
1954           /* the sessionid can have attributes marked with ;
1955            * Make sure we strip them */
1956           for (i = 0; session_id[i] != '\0'; i++) {
1957             if (session_id[i] == ';') {
1958               maxlen = i;
1959               /* parse timeout */
1960               do {
1961                 i++;
1962               } while (g_ascii_isspace (session_id[i]));
1963               if (g_str_has_prefix (&session_id[i], "timeout=")) {
1964                 gint to;
1965
1966                 /* if we parsed something valid, configure */
1967                 if ((to = atoi (&session_id[i + 8])) > 0)
1968                   conn->timeout = to;
1969               }
1970               break;
1971             }
1972           }
1973
1974           /* make sure to not overflow */
1975           strncpy (conn->session_id, session_id, maxlen);
1976           conn->session_id[maxlen] = '\0';
1977         }
1978         res = builder->status;
1979         goto done;
1980       }
1981       default:
1982         res = GST_RTSP_ERROR;
1983         break;
1984     }
1985   }
1986 done:
1987   return res;
1988 }
1989
1990 /**
1991  * gst_rtsp_connection_read:
1992  * @conn: a #GstRTSPConnection
1993  * @data: the data to read
1994  * @size: the size of @data
1995  * @timeout: a timeout value or #NULL
1996  *
1997  * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1998  * the specified @timeout. @timeout can be #NULL, in which case this function
1999  * might block forever.
2000  *
2001  * This function can be cancelled with gst_rtsp_connection_flush().
2002  *
2003  * Returns: #GST_RTSP_OK on success.
2004  */
2005 GstRTSPResult
2006 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
2007     GTimeVal * timeout)
2008 {
2009   guint offset;
2010   gint retval;
2011   GstClockTime to;
2012   GstRTSPResult res;
2013
2014   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2015   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
2016   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2017
2018   if (G_UNLIKELY (size == 0))
2019     return GST_RTSP_OK;
2020
2021   offset = 0;
2022
2023   /* configure timeout if any */
2024   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2025
2026   gst_poll_set_controllable (conn->fdset, TRUE);
2027   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2028   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2029
2030   while (TRUE) {
2031     res = read_bytes (conn, data, &offset, size);
2032     if (G_UNLIKELY (res == GST_RTSP_EEOF))
2033       goto eof;
2034     if (G_LIKELY (res == GST_RTSP_OK))
2035       break;
2036     if (G_UNLIKELY (res != GST_RTSP_EINTR))
2037       goto read_error;
2038
2039     do {
2040       retval = gst_poll_wait (conn->fdset, to);
2041     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2042
2043     /* check for timeout */
2044     if (G_UNLIKELY (retval == 0))
2045       goto select_timeout;
2046
2047     if (G_UNLIKELY (retval == -1)) {
2048       if (errno == EBUSY)
2049         goto stopped;
2050       else
2051         goto select_error;
2052     }
2053     gst_poll_set_controllable (conn->fdset, FALSE);
2054   }
2055   return GST_RTSP_OK;
2056
2057   /* ERRORS */
2058 select_error:
2059   {
2060     return GST_RTSP_ESYS;
2061   }
2062 select_timeout:
2063   {
2064     return GST_RTSP_ETIMEOUT;
2065   }
2066 stopped:
2067   {
2068     return GST_RTSP_EINTR;
2069   }
2070 eof:
2071   {
2072     return GST_RTSP_EEOF;
2073   }
2074 read_error:
2075   {
2076     return res;
2077   }
2078 }
2079
2080 static GstRTSPMessage *
2081 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
2082     const GstRTSPMessage * request)
2083 {
2084   GstRTSPMessage *msg;
2085   GstRTSPResult res;
2086
2087   if (gst_rtsp_status_as_text (code) == NULL)
2088     code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
2089
2090   GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
2091       no_message);
2092
2093   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
2094       "GStreamer RTSP Server");
2095   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2096   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2097   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2098
2099   if (code == GST_RTSP_STS_OK) {
2100     if (conn->ip)
2101       gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2102           conn->ip);
2103     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2104         "application/x-rtsp-tunnelled");
2105   }
2106
2107   return msg;
2108
2109   /* ERRORS */
2110 no_message:
2111   {
2112     return NULL;
2113   }
2114 }
2115
2116 /**
2117  * gst_rtsp_connection_receive:
2118  * @conn: a #GstRTSPConnection
2119  * @message: the message to read
2120  * @timeout: a timeout value or #NULL
2121  *
2122  * Attempt to read into @message from the connected @conn, blocking up to
2123  * the specified @timeout. @timeout can be #NULL, in which case this function
2124  * might block forever.
2125  * 
2126  * This function can be cancelled with gst_rtsp_connection_flush().
2127  *
2128  * Returns: #GST_RTSP_OK on success.
2129  */
2130 GstRTSPResult
2131 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2132     GTimeVal * timeout)
2133 {
2134   GstRTSPResult res;
2135   GstRTSPBuilder builder;
2136   gint retval;
2137   GstClockTime to;
2138
2139   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2140   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2141   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2142
2143   /* configure timeout if any */
2144   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2145
2146   gst_poll_set_controllable (conn->fdset, TRUE);
2147   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2148   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2149
2150   memset (&builder, 0, sizeof (GstRTSPBuilder));
2151   while (TRUE) {
2152     res = build_next (&builder, message, conn);
2153     if (G_UNLIKELY (res == GST_RTSP_EEOF))
2154       goto eof;
2155     else if (G_LIKELY (res == GST_RTSP_OK)) {
2156       if (!conn->manual_http) {
2157         if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2158           if (conn->tstate == TUNNEL_STATE_NONE &&
2159               message->type_data.request.method == GST_RTSP_GET) {
2160             GstRTSPMessage *response;
2161
2162             conn->tstate = TUNNEL_STATE_GET;
2163
2164             /* tunnel GET request, we can reply now */
2165             response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2166             res = gst_rtsp_connection_send (conn, response, timeout);
2167             gst_rtsp_message_free (response);
2168             if (res == GST_RTSP_OK)
2169               res = GST_RTSP_ETGET;
2170             goto cleanup;
2171           } else if (conn->tstate == TUNNEL_STATE_NONE &&
2172               message->type_data.request.method == GST_RTSP_POST) {
2173             conn->tstate = TUNNEL_STATE_POST;
2174
2175             /* tunnel POST request, the caller now has to link the two
2176              * connections. */
2177             res = GST_RTSP_ETPOST;
2178             goto cleanup;
2179           } else {
2180             res = GST_RTSP_EPARSE;
2181             goto cleanup;
2182           }
2183         } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2184           res = GST_RTSP_EPARSE;
2185           goto cleanup;
2186         }
2187       }
2188
2189       break;
2190     } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2191       goto read_error;
2192
2193     do {
2194       retval = gst_poll_wait (conn->fdset, to);
2195     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2196
2197     /* check for timeout */
2198     if (G_UNLIKELY (retval == 0))
2199       goto select_timeout;
2200
2201     if (G_UNLIKELY (retval == -1)) {
2202       if (errno == EBUSY)
2203         goto stopped;
2204       else
2205         goto select_error;
2206     }
2207     gst_poll_set_controllable (conn->fdset, FALSE);
2208   }
2209
2210   /* we have a message here */
2211   build_reset (&builder);
2212
2213   return GST_RTSP_OK;
2214
2215   /* ERRORS */
2216 select_error:
2217   {
2218     res = GST_RTSP_ESYS;
2219     goto cleanup;
2220   }
2221 select_timeout:
2222   {
2223     res = GST_RTSP_ETIMEOUT;
2224     goto cleanup;
2225   }
2226 stopped:
2227   {
2228     res = GST_RTSP_EINTR;
2229     goto cleanup;
2230   }
2231 eof:
2232   {
2233     res = GST_RTSP_EEOF;
2234     goto cleanup;
2235   }
2236 read_error:
2237 cleanup:
2238   {
2239     build_reset (&builder);
2240     gst_rtsp_message_unset (message);
2241     return res;
2242   }
2243 }
2244
2245 /**
2246  * gst_rtsp_connection_close:
2247  * @conn: a #GstRTSPConnection
2248  *
2249  * Close the connected @conn. After this call, the connection is in the same
2250  * state as when it was first created.
2251  * 
2252  * Returns: #GST_RTSP_OK on success.
2253  */
2254 GstRTSPResult
2255 gst_rtsp_connection_close (GstRTSPConnection * conn)
2256 {
2257   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2258
2259   g_free (conn->ip);
2260   conn->ip = NULL;
2261
2262   conn->read_ahead = 0;
2263
2264   g_free (conn->initial_buffer);
2265   conn->initial_buffer = NULL;
2266   conn->initial_buffer_offset = 0;
2267
2268   REMOVE_POLLFD (conn->fdset, &conn->fd0);
2269   REMOVE_POLLFD (conn->fdset, &conn->fd1);
2270   conn->writefd = NULL;
2271   conn->readfd = NULL;
2272   conn->tunneled = FALSE;
2273   conn->tstate = TUNNEL_STATE_NONE;
2274   conn->ctxp = NULL;
2275   g_free (conn->username);
2276   conn->username = NULL;
2277   g_free (conn->passwd);
2278   conn->passwd = NULL;
2279   gst_rtsp_connection_clear_auth_params (conn);
2280   conn->timeout = 60;
2281   conn->cseq = 0;
2282   conn->session_id[0] = '\0';
2283
2284   return GST_RTSP_OK;
2285 }
2286
2287 /**
2288  * gst_rtsp_connection_free:
2289  * @conn: a #GstRTSPConnection
2290  *
2291  * Close and free @conn.
2292  * 
2293  * Returns: #GST_RTSP_OK on success.
2294  */
2295 GstRTSPResult
2296 gst_rtsp_connection_free (GstRTSPConnection * conn)
2297 {
2298   GstRTSPResult res;
2299
2300   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2301
2302   res = gst_rtsp_connection_close (conn);
2303   gst_poll_free (conn->fdset);
2304   g_timer_destroy (conn->timer);
2305   gst_rtsp_url_free (conn->url);
2306   g_free (conn->proxy_host);
2307   g_free (conn);
2308 #ifdef G_OS_WIN32
2309   WSACleanup ();
2310 #endif
2311
2312   return res;
2313 }
2314
2315 /**
2316  * gst_rtsp_connection_poll:
2317  * @conn: a #GstRTSPConnection
2318  * @events: a bitmask of #GstRTSPEvent flags to check
2319  * @revents: location for result flags 
2320  * @timeout: a timeout
2321  *
2322  * Wait up to the specified @timeout for the connection to become available for
2323  * at least one of the operations specified in @events. When the function returns
2324  * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2325  * @conn.
2326  *
2327  * @timeout can be #NULL, in which case this function might block forever.
2328  *
2329  * This function can be cancelled with gst_rtsp_connection_flush().
2330  * 
2331  * Returns: #GST_RTSP_OK on success.
2332  *
2333  * Since: 0.10.15
2334  */
2335 GstRTSPResult
2336 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2337     GstRTSPEvent * revents, GTimeVal * timeout)
2338 {
2339   GstClockTime to;
2340   gint retval;
2341
2342   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2343   g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2344   g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2345   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2346   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2347
2348   gst_poll_set_controllable (conn->fdset, TRUE);
2349
2350   /* add fd to writer set when asked to */
2351   gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2352       events & GST_RTSP_EV_WRITE);
2353
2354   /* add fd to reader set when asked to */
2355   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2356
2357   /* configure timeout if any */
2358   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2359
2360   do {
2361     retval = gst_poll_wait (conn->fdset, to);
2362   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2363
2364   if (G_UNLIKELY (retval == 0))
2365     goto select_timeout;
2366
2367   if (G_UNLIKELY (retval == -1)) {
2368     if (errno == EBUSY)
2369       goto stopped;
2370     else
2371       goto select_error;
2372   }
2373
2374   *revents = 0;
2375   if (events & GST_RTSP_EV_READ) {
2376     if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2377       *revents |= GST_RTSP_EV_READ;
2378   }
2379   if (events & GST_RTSP_EV_WRITE) {
2380     if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2381       *revents |= GST_RTSP_EV_WRITE;
2382   }
2383   return GST_RTSP_OK;
2384
2385   /* ERRORS */
2386 select_timeout:
2387   {
2388     return GST_RTSP_ETIMEOUT;
2389   }
2390 select_error:
2391   {
2392     return GST_RTSP_ESYS;
2393   }
2394 stopped:
2395   {
2396     return GST_RTSP_EINTR;
2397   }
2398 }
2399
2400 /**
2401  * gst_rtsp_connection_next_timeout:
2402  * @conn: a #GstRTSPConnection
2403  * @timeout: a timeout
2404  *
2405  * Calculate the next timeout for @conn, storing the result in @timeout.
2406  * 
2407  * Returns: #GST_RTSP_OK.
2408  */
2409 GstRTSPResult
2410 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2411 {
2412   gdouble elapsed;
2413   glong sec;
2414   gulong usec;
2415
2416   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2417   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2418
2419   elapsed = g_timer_elapsed (conn->timer, &usec);
2420   if (elapsed >= conn->timeout) {
2421     sec = 0;
2422     usec = 0;
2423   } else {
2424     sec = conn->timeout - elapsed;
2425   }
2426
2427   timeout->tv_sec = sec;
2428   timeout->tv_usec = usec;
2429
2430   return GST_RTSP_OK;
2431 }
2432
2433 /**
2434  * gst_rtsp_connection_reset_timeout:
2435  * @conn: a #GstRTSPConnection
2436  *
2437  * Reset the timeout of @conn.
2438  * 
2439  * Returns: #GST_RTSP_OK.
2440  */
2441 GstRTSPResult
2442 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2443 {
2444   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2445
2446   g_timer_start (conn->timer);
2447
2448   return GST_RTSP_OK;
2449 }
2450
2451 /**
2452  * gst_rtsp_connection_flush:
2453  * @conn: a #GstRTSPConnection
2454  * @flush: start or stop the flush
2455  *
2456  * Start or stop the flushing action on @conn. When flushing, all current
2457  * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2458  * is set to non-flushing mode again.
2459  * 
2460  * Returns: #GST_RTSP_OK.
2461  */
2462 GstRTSPResult
2463 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2464 {
2465   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2466
2467   gst_poll_set_flushing (conn->fdset, flush);
2468
2469   return GST_RTSP_OK;
2470 }
2471
2472 /**
2473  * gst_rtsp_connection_set_proxy:
2474  * @conn: a #GstRTSPConnection
2475  * @host: the proxy host
2476  * @port: the proxy port
2477  *
2478  * Set the proxy host and port.
2479  * 
2480  * Returns: #GST_RTSP_OK.
2481  *
2482  * Since: 0.10.23
2483  */
2484 GstRTSPResult
2485 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2486     const gchar * host, guint port)
2487 {
2488   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2489
2490   g_free (conn->proxy_host);
2491   conn->proxy_host = g_strdup (host);
2492   conn->proxy_port = port;
2493
2494   return GST_RTSP_OK;
2495 }
2496
2497 /**
2498  * gst_rtsp_connection_set_auth:
2499  * @conn: a #GstRTSPConnection
2500  * @method: authentication method
2501  * @user: the user
2502  * @pass: the password
2503  *
2504  * Configure @conn for authentication mode @method with @user and @pass as the
2505  * user and password respectively.
2506  * 
2507  * Returns: #GST_RTSP_OK.
2508  */
2509 GstRTSPResult
2510 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2511     GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2512 {
2513   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2514
2515   if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2516           || g_strrstr (user, ":") != NULL))
2517     return GST_RTSP_EINVAL;
2518
2519   /* Make sure the username and passwd are being set for authentication */
2520   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2521     return GST_RTSP_EINVAL;
2522
2523   /* ":" chars are not allowed in usernames for basic auth */
2524   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2525     return GST_RTSP_EINVAL;
2526
2527   g_free (conn->username);
2528   g_free (conn->passwd);
2529
2530   conn->auth_method = method;
2531   conn->username = g_strdup (user);
2532   conn->passwd = g_strdup (pass);
2533
2534   return GST_RTSP_OK;
2535 }
2536
2537 /**
2538  * str_case_hash:
2539  * @key: ASCII string to hash
2540  *
2541  * Hashes @key in a case-insensitive manner.
2542  *
2543  * Returns: the hash code.
2544  **/
2545 static guint
2546 str_case_hash (gconstpointer key)
2547 {
2548   const char *p = key;
2549   guint h = g_ascii_toupper (*p);
2550
2551   if (h)
2552     for (p += 1; *p != '\0'; p++)
2553       h = (h << 5) - h + g_ascii_toupper (*p);
2554
2555   return h;
2556 }
2557
2558 /**
2559  * str_case_equal:
2560  * @v1: an ASCII string
2561  * @v2: another ASCII string
2562  *
2563  * Compares @v1 and @v2 in a case-insensitive manner
2564  *
2565  * Returns: %TRUE if they are equal (modulo case)
2566  **/
2567 static gboolean
2568 str_case_equal (gconstpointer v1, gconstpointer v2)
2569 {
2570   const char *string1 = v1;
2571   const char *string2 = v2;
2572
2573   return g_ascii_strcasecmp (string1, string2) == 0;
2574 }
2575
2576 /**
2577  * gst_rtsp_connection_set_auth_param:
2578  * @conn: a #GstRTSPConnection
2579  * @param: authentication directive
2580  * @value: value
2581  *
2582  * Setup @conn with authentication directives. This is not necesary for
2583  * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2584  * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2585  * in the WWW-Authenticate response header and can include realm, domain,
2586  * nonce, opaque, stale, algorithm, qop as per RFC2617.
2587  * 
2588  * Since: 0.10.20
2589  */
2590 void
2591 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2592     const gchar * param, const gchar * value)
2593 {
2594   g_return_if_fail (conn != NULL);
2595   g_return_if_fail (param != NULL);
2596
2597   if (conn->auth_params == NULL) {
2598     conn->auth_params =
2599         g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2600   }
2601   g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2602 }
2603
2604 /**
2605  * gst_rtsp_connection_clear_auth_params:
2606  * @conn: a #GstRTSPConnection
2607  *
2608  * Clear the list of authentication directives stored in @conn.
2609  *
2610  * Since: 0.10.20
2611  */
2612 void
2613 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2614 {
2615   g_return_if_fail (conn != NULL);
2616
2617   if (conn->auth_params != NULL) {
2618     g_hash_table_destroy (conn->auth_params);
2619     conn->auth_params = NULL;
2620   }
2621 }
2622
2623 static GstRTSPResult
2624 set_qos_dscp (gint fd, guint qos_dscp)
2625 {
2626   union gst_sockaddr sa;
2627   socklen_t slen = sizeof (sa);
2628   gint af;
2629   gint tos;
2630
2631   if (fd == -1)
2632     return GST_RTSP_OK;
2633
2634   if (getsockname (fd, &sa.sa, &slen) < 0)
2635     goto no_getsockname;
2636
2637   af = sa.sa.sa_family;
2638
2639   /* if this is an IPv4-mapped address then do IPv4 QoS */
2640   if (af == AF_INET6) {
2641     if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2642       af = AF_INET;
2643   }
2644
2645   /* extract and shift 6 bits of the DSCP */
2646   tos = (qos_dscp & 0x3f) << 2;
2647
2648   switch (af) {
2649     case AF_INET:
2650       if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2651         goto no_setsockopt;
2652       break;
2653     case AF_INET6:
2654 #ifdef IPV6_TCLASS
2655       if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2656         goto no_setsockopt;
2657       break;
2658 #endif
2659     default:
2660       goto wrong_family;
2661   }
2662
2663   return GST_RTSP_OK;
2664
2665   /* ERRORS */
2666 no_getsockname:
2667 no_setsockopt:
2668   {
2669     return GST_RTSP_ESYS;
2670   }
2671
2672 wrong_family:
2673   {
2674     return GST_RTSP_ERROR;
2675   }
2676 }
2677
2678 /**
2679  * gst_rtsp_connection_set_qos_dscp:
2680  * @conn: a #GstRTSPConnection
2681  * @qos_dscp: DSCP value
2682  *
2683  * Configure @conn to use the specified DSCP value.
2684  *
2685  * Returns: #GST_RTSP_OK on success.
2686  *
2687  * Since: 0.10.20
2688  */
2689 GstRTSPResult
2690 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2691 {
2692   GstRTSPResult res;
2693
2694   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2695   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2696   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2697
2698   res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2699   if (res == GST_RTSP_OK)
2700     res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2701
2702   return res;
2703 }
2704
2705
2706 /**
2707  * gst_rtsp_connection_get_url:
2708  * @conn: a #GstRTSPConnection
2709  *
2710  * Retrieve the URL of the other end of @conn.
2711  *
2712  * Returns: The URL. This value remains valid until the
2713  * connection is freed.
2714  *
2715  * Since: 0.10.23
2716  */
2717 GstRTSPUrl *
2718 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2719 {
2720   g_return_val_if_fail (conn != NULL, NULL);
2721
2722   return conn->url;
2723 }
2724
2725 /**
2726  * gst_rtsp_connection_get_ip:
2727  * @conn: a #GstRTSPConnection
2728  *
2729  * Retrieve the IP address of the other end of @conn.
2730  *
2731  * Returns: The IP address as a string. this value remains valid until the
2732  * connection is closed.
2733  *
2734  * Since: 0.10.20
2735  */
2736 const gchar *
2737 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2738 {
2739   g_return_val_if_fail (conn != NULL, NULL);
2740
2741   return conn->ip;
2742 }
2743
2744 /**
2745  * gst_rtsp_connection_set_ip:
2746  * @conn: a #GstRTSPConnection
2747  * @ip: an ip address
2748  *
2749  * Set the IP address of the server.
2750  *
2751  * Since: 0.10.23
2752  */
2753 void
2754 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2755 {
2756   g_return_if_fail (conn != NULL);
2757
2758   g_free (conn->ip);
2759   conn->ip = g_strdup (ip);
2760 }
2761
2762 /**
2763  * gst_rtsp_connection_get_readfd:
2764  * @conn: a #GstRTSPConnection
2765  *
2766  * Get the file descriptor for reading.
2767  *
2768  * Returns: the file descriptor used for reading or -1 on error. The file
2769  * descriptor remains valid until the connection is closed.
2770  *
2771  * Since: 0.10.23
2772  */
2773 gint
2774 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2775 {
2776   g_return_val_if_fail (conn != NULL, -1);
2777   g_return_val_if_fail (conn->readfd != NULL, -1);
2778
2779   return conn->readfd->fd;
2780 }
2781
2782 /**
2783  * gst_rtsp_connection_get_writefd:
2784  * @conn: a #GstRTSPConnection
2785  *
2786  * Get the file descriptor for writing.
2787  *
2788  * Returns: the file descriptor used for writing or -1 on error. The file
2789  * descriptor remains valid until the connection is closed.
2790  *
2791  * Since: 0.10.23
2792  */
2793 gint
2794 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2795 {
2796   g_return_val_if_fail (conn != NULL, -1);
2797   g_return_val_if_fail (conn->writefd != NULL, -1);
2798
2799   return conn->writefd->fd;
2800 }
2801
2802 /**
2803  * gst_rtsp_connection_set_http_mode:
2804  * @conn: a #GstRTSPConnection
2805  * @enable: %TRUE to enable manual HTTP mode
2806  *
2807  * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2808  * messages in addition to the RTSP messages. It will also disable the
2809  * automatic handling of setting up an HTTP tunnel.
2810  *
2811  * Since: 0.10.25
2812  */
2813 void
2814 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2815 {
2816   g_return_if_fail (conn != NULL);
2817
2818   conn->manual_http = enable;
2819 }
2820
2821 /**
2822  * gst_rtsp_connection_set_tunneled:
2823  * @conn: a #GstRTSPConnection
2824  * @tunneled: the new state
2825  *
2826  * Set the HTTP tunneling state of the connection. This must be configured before
2827  * the @conn is connected.
2828  *
2829  * Since: 0.10.23
2830  */
2831 void
2832 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2833 {
2834   g_return_if_fail (conn != NULL);
2835   g_return_if_fail (conn->readfd == NULL);
2836   g_return_if_fail (conn->writefd == NULL);
2837
2838   conn->tunneled = tunneled;
2839 }
2840
2841 /**
2842  * gst_rtsp_connection_is_tunneled:
2843  * @conn: a #GstRTSPConnection
2844  *
2845  * Get the tunneling state of the connection. 
2846  *
2847  * Returns: if @conn is using HTTP tunneling.
2848  *
2849  * Since: 0.10.23
2850  */
2851 gboolean
2852 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2853 {
2854   g_return_val_if_fail (conn != NULL, FALSE);
2855
2856   return conn->tunneled;
2857 }
2858
2859 /**
2860  * gst_rtsp_connection_get_tunnelid:
2861  * @conn: a #GstRTSPConnection
2862  *
2863  * Get the tunnel session id the connection. 
2864  *
2865  * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2866  *
2867  * Since: 0.10.23
2868  */
2869 const gchar *
2870 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2871 {
2872   g_return_val_if_fail (conn != NULL, NULL);
2873
2874   if (!conn->tunneled)
2875     return NULL;
2876
2877   return conn->tunnelid;
2878 }
2879
2880 /**
2881  * gst_rtsp_connection_do_tunnel:
2882  * @conn: a #GstRTSPConnection
2883  * @conn2: a #GstRTSPConnection or %NULL
2884  *
2885  * If @conn received the first tunnel connection and @conn2 received
2886  * the second tunnel connection, link the two connections together so that
2887  * @conn manages the tunneled connection.
2888  *
2889  * After this call, @conn2 cannot be used anymore and must be freed with
2890  * gst_rtsp_connection_free().
2891  *
2892  * If @conn2 is %NULL then only the base64 decoding context will be setup for
2893  * @conn.
2894  *
2895  * Returns: return GST_RTSP_OK on success.
2896  *
2897  * Since: 0.10.23
2898  */
2899 GstRTSPResult
2900 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2901     GstRTSPConnection * conn2)
2902 {
2903   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2904
2905   if (conn2 != NULL) {
2906     g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2907     g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2908     g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2909             TUNNELID_LEN), GST_RTSP_EINVAL);
2910
2911     /* both connections have fd0 as the read/write socket. start by taking the
2912      * socket from conn2 and set it as the socket in conn */
2913     conn->fd1 = conn2->fd0;
2914
2915     /* clean up some of the state of conn2 */
2916     gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2917     conn2->fd0.fd = -1;
2918     conn2->readfd = conn2->writefd = NULL;
2919
2920     /* We make fd0 the write socket and fd1 the read socket. */
2921     conn->writefd = &conn->fd0;
2922     conn->readfd = &conn->fd1;
2923
2924     conn->tstate = TUNNEL_STATE_COMPLETE;
2925   }
2926
2927   /* we need base64 decoding for the readfd */
2928   conn->ctx.state = 0;
2929   conn->ctx.save = 0;
2930   conn->ctx.cout = 0;
2931   conn->ctx.coutl = 0;
2932   conn->ctxp = &conn->ctx;
2933
2934   return GST_RTSP_OK;
2935 }
2936
2937 #define READ_COND   (G_IO_IN | G_IO_HUP | G_IO_ERR)
2938 #define WRITE_COND  (G_IO_OUT | G_IO_ERR)
2939
2940 typedef struct
2941 {
2942   guint8 *data;
2943   guint size;
2944   guint id;
2945 } GstRTSPRec;
2946
2947 /* async functions */
2948 struct _GstRTSPWatch
2949 {
2950   GSource source;
2951
2952   GstRTSPConnection *conn;
2953
2954   GstRTSPBuilder builder;
2955   GstRTSPMessage message;
2956
2957   GPollFD readfd;
2958   GPollFD writefd;
2959   gboolean write_added;
2960
2961   /* queued message for transmission */
2962   guint id;
2963   GMutex *mutex;
2964   GQueue *messages;
2965   guint8 *write_data;
2966   guint write_off;
2967   guint write_size;
2968   guint write_id;
2969
2970   GstRTSPWatchFuncs funcs;
2971
2972   gpointer user_data;
2973   GDestroyNotify notify;
2974 };
2975
2976 static gboolean
2977 gst_rtsp_source_prepare (GSource * source, gint * timeout)
2978 {
2979   GstRTSPWatch *watch = (GstRTSPWatch *) source;
2980
2981   if (watch->conn->initial_buffer != NULL)
2982     return TRUE;
2983
2984   *timeout = (watch->conn->timeout * 1000);
2985
2986   return FALSE;
2987 }
2988
2989 static gboolean
2990 gst_rtsp_source_check (GSource * source)
2991 {
2992   GstRTSPWatch *watch = (GstRTSPWatch *) source;
2993
2994   if (watch->readfd.revents & READ_COND)
2995     return TRUE;
2996
2997   if (watch->writefd.revents & WRITE_COND)
2998     return TRUE;
2999
3000   return FALSE;
3001 }
3002
3003 static gboolean
3004 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
3005     gpointer user_data G_GNUC_UNUSED)
3006 {
3007   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3008   GstRTSPResult res;
3009
3010   /* first read as much as we can */
3011   if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
3012     do {
3013       res = build_next (&watch->builder, &watch->message, watch->conn);
3014       if (res == GST_RTSP_EINTR)
3015         break;
3016       else if (G_UNLIKELY (res == GST_RTSP_EEOF))
3017         goto eof;
3018       else if (G_LIKELY (res == GST_RTSP_OK)) {
3019         if (!watch->conn->manual_http &&
3020             watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3021           if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3022               watch->message.type_data.request.method == GST_RTSP_GET) {
3023             GstRTSPMessage *response;
3024             GstRTSPStatusCode code;
3025
3026             watch->conn->tstate = TUNNEL_STATE_GET;
3027
3028             if (watch->funcs.tunnel_start)
3029               code = watch->funcs.tunnel_start (watch, watch->user_data);
3030             else
3031               code = GST_RTSP_STS_OK;
3032
3033             /* queue the response */
3034             response = gen_tunnel_reply (watch->conn, code, &watch->message);
3035             gst_rtsp_watch_send_message (watch, response, NULL);
3036             gst_rtsp_message_free (response);
3037             goto read_done;
3038           } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3039               watch->message.type_data.request.method == GST_RTSP_POST) {
3040             watch->conn->tstate = TUNNEL_STATE_POST;
3041
3042             /* in the callback the connection should be tunneled with the
3043              * GET connection */
3044             if (watch->funcs.tunnel_complete)
3045               watch->funcs.tunnel_complete (watch, watch->user_data);
3046             goto read_done;
3047           }
3048         }
3049       }
3050
3051       if (!watch->conn->manual_http) {
3052         /* if manual HTTP support is not enabled, then restore the message to
3053          * what it would have looked like without the support for parsing HTTP
3054          * messages being present */
3055         if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3056           watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3057           watch->message.type_data.request.method = GST_RTSP_INVALID;
3058           if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3059             watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3060           res = GST_RTSP_EPARSE;
3061         } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3062           watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3063           if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3064             watch->message.type_data.response.version =
3065                 GST_RTSP_VERSION_INVALID;
3066           res = GST_RTSP_EPARSE;
3067         }
3068       }
3069
3070       if (G_LIKELY (res == GST_RTSP_OK)) {
3071         if (watch->funcs.message_received)
3072           watch->funcs.message_received (watch, &watch->message,
3073               watch->user_data);
3074       } else {
3075         if (watch->funcs.error_full)
3076           GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3077                   0, watch->user_data), error);
3078         else
3079           goto error;
3080       }
3081
3082     read_done:
3083       gst_rtsp_message_unset (&watch->message);
3084       build_reset (&watch->builder);
3085     } while (FALSE);
3086   }
3087
3088   if (watch->writefd.revents & WRITE_COND) {
3089     g_mutex_lock (watch->mutex);
3090     do {
3091       if (watch->write_data == NULL) {
3092         GstRTSPRec *rec;
3093
3094         /* get a new message from the queue */
3095         rec = g_queue_pop_tail (watch->messages);
3096         if (rec == NULL)
3097           goto done;
3098
3099         watch->write_off = 0;
3100         watch->write_data = rec->data;
3101         watch->write_size = rec->size;
3102         watch->write_id = rec->id;
3103
3104         g_slice_free (GstRTSPRec, rec);
3105       }
3106
3107       res = write_bytes (watch->writefd.fd, watch->write_data,
3108           &watch->write_off, watch->write_size);
3109       g_mutex_unlock (watch->mutex);
3110       if (res == GST_RTSP_EINTR)
3111         goto write_blocked;
3112       else if (G_LIKELY (res == GST_RTSP_OK)) {
3113         if (watch->funcs.message_sent)
3114           watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3115       } else {
3116         if (watch->funcs.error_full)
3117           GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3118                   watch->write_id, watch->user_data), error);
3119         else
3120           goto error;
3121       }
3122       g_mutex_lock (watch->mutex);
3123
3124       g_free (watch->write_data);
3125       watch->write_data = NULL;
3126     } while (TRUE);
3127
3128   done:
3129     if (watch->write_added) {
3130       g_source_remove_poll ((GSource *) watch, &watch->writefd);
3131       watch->write_added = FALSE;
3132       watch->writefd.revents = 0;
3133     }
3134
3135     g_mutex_unlock (watch->mutex);
3136   }
3137
3138 write_blocked:
3139   return TRUE;
3140
3141   /* ERRORS */
3142 eof:
3143   {
3144     if (watch->funcs.closed)
3145       watch->funcs.closed (watch, watch->user_data);
3146     return FALSE;
3147   }
3148 error:
3149   {
3150     if (watch->funcs.error)
3151       watch->funcs.error (watch, res, watch->user_data);
3152     return FALSE;
3153   }
3154 }
3155
3156 static void
3157 gst_rtsp_rec_free (gpointer data)
3158 {
3159   GstRTSPRec *rec = data;
3160
3161   g_free (rec->data);
3162   g_slice_free (GstRTSPRec, rec);
3163 }
3164
3165 static void
3166 gst_rtsp_source_finalize (GSource * source)
3167 {
3168   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3169
3170   build_reset (&watch->builder);
3171   gst_rtsp_message_unset (&watch->message);
3172
3173   g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3174   g_queue_free (watch->messages);
3175   watch->messages = NULL;
3176
3177   g_mutex_free (watch->mutex);
3178
3179   g_free (watch->write_data);
3180
3181   if (watch->notify)
3182     watch->notify (watch->user_data);
3183 }
3184
3185 static GSourceFuncs gst_rtsp_source_funcs = {
3186   gst_rtsp_source_prepare,
3187   gst_rtsp_source_check,
3188   gst_rtsp_source_dispatch,
3189   gst_rtsp_source_finalize,
3190   NULL,
3191   NULL
3192 };
3193
3194 /**
3195  * gst_rtsp_watch_new:
3196  * @conn: a #GstRTSPConnection
3197  * @funcs: watch functions
3198  * @user_data: user data to pass to @funcs
3199  * @notify: notify when @user_data is not referenced anymore
3200  *
3201  * Create a watch object for @conn. The functions provided in @funcs will be
3202  * called with @user_data when activity happened on the watch.
3203  *
3204  * The new watch is usually created so that it can be attached to a
3205  * maincontext with gst_rtsp_watch_attach(). 
3206  *
3207  * @conn must exist for the entire lifetime of the watch.
3208  *
3209  * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3210  * communication. Free with gst_rtsp_watch_unref () after usage.
3211  *
3212  * Since: 0.10.23
3213  */
3214 GstRTSPWatch *
3215 gst_rtsp_watch_new (GstRTSPConnection * conn,
3216     GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3217 {
3218   GstRTSPWatch *result;
3219
3220   g_return_val_if_fail (conn != NULL, NULL);
3221   g_return_val_if_fail (funcs != NULL, NULL);
3222   g_return_val_if_fail (conn->readfd != NULL, NULL);
3223   g_return_val_if_fail (conn->writefd != NULL, NULL);
3224
3225   result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3226       sizeof (GstRTSPWatch));
3227
3228   result->conn = conn;
3229   result->builder.state = STATE_START;
3230
3231   result->mutex = g_mutex_new ();
3232   result->messages = g_queue_new ();
3233
3234   result->readfd.fd = -1;
3235   result->writefd.fd = -1;
3236
3237   gst_rtsp_watch_reset (result);
3238
3239   result->funcs = *funcs;
3240   result->user_data = user_data;
3241   result->notify = notify;
3242
3243   /* only add the read fd, the write fd is only added when we have data
3244    * to send. */
3245   g_source_add_poll ((GSource *) result, &result->readfd);
3246
3247   return result;
3248 }
3249
3250 /**
3251  * gst_rtsp_watch_reset:
3252  * @watch: a #GstRTSPWatch
3253  *
3254  * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3255  * when the file descriptors of the connection might have changed.
3256  *
3257  * Since: 0.10.23
3258  */
3259 void
3260 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3261 {
3262   if (watch->readfd.fd != -1)
3263     g_source_remove_poll ((GSource *) watch, &watch->readfd);
3264   if (watch->writefd.fd != -1)
3265     g_source_remove_poll ((GSource *) watch, &watch->writefd);
3266
3267   watch->readfd.fd = watch->conn->readfd->fd;
3268   watch->readfd.events = READ_COND;
3269   watch->readfd.revents = 0;
3270
3271   watch->writefd.fd = watch->conn->writefd->fd;
3272   watch->writefd.events = WRITE_COND;
3273   watch->writefd.revents = 0;
3274   watch->write_added = FALSE;
3275
3276   g_source_add_poll ((GSource *) watch, &watch->readfd);
3277 }
3278
3279 /**
3280  * gst_rtsp_watch_attach:
3281  * @watch: a #GstRTSPWatch
3282  * @context: a GMainContext (if NULL, the default context will be used)
3283  *
3284  * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3285  *
3286  * Returns: the ID (greater than 0) for the watch within the GMainContext. 
3287  *
3288  * Since: 0.10.23
3289  */
3290 guint
3291 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3292 {
3293   g_return_val_if_fail (watch != NULL, 0);
3294
3295   return g_source_attach ((GSource *) watch, context);
3296 }
3297
3298 /**
3299  * gst_rtsp_watch_unref:
3300  * @watch: a #GstRTSPWatch
3301  *
3302  * Decreases the reference count of @watch by one. If the resulting reference
3303  * count is zero the watch and associated memory will be destroyed.
3304  *
3305  * Since: 0.10.23
3306  */
3307 void
3308 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3309 {
3310   g_return_if_fail (watch != NULL);
3311
3312   g_source_unref ((GSource *) watch);
3313 }
3314
3315 /**
3316  * gst_rtsp_watch_write_data:
3317  * @watch: a #GstRTSPWatch
3318  * @data: the data to queue
3319  * @size: the size of @data
3320  * @id: location for a message ID or %NULL
3321  *
3322  * Write @data using the connection of the @watch. If it cannot be sent
3323  * immediately, it will be queued for transmission in @watch. The contents of
3324  * @message will then be serialized and transmitted when the connection of the
3325  * @watch becomes writable. In case the @message is queued, the ID returned in
3326  * @id will be non-zero and used as the ID argument in the message_sent
3327  * callback.
3328  *
3329  * This function will take ownership of @data and g_free() it after use.
3330  *
3331  * Returns: #GST_RTSP_OK on success.
3332  *
3333  * Since: 0.10.25
3334  */
3335 GstRTSPResult
3336 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3337     guint size, guint * id)
3338 {
3339   GstRTSPResult res;
3340   GstRTSPRec *rec;
3341   guint off = 0;
3342
3343   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3344   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3345   g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3346
3347   g_mutex_lock (watch->mutex);
3348
3349   if (watch->messages->length == 0) {
3350     res = write_bytes (watch->writefd.fd, data, &off, size);
3351     if (res != GST_RTSP_EINTR) {
3352       if (id != NULL)
3353         *id = 0;
3354       g_free ((gpointer) data);
3355       goto done;
3356     }
3357   }
3358
3359   /* make a record with the data and id */
3360   rec = g_slice_new (GstRTSPRec);
3361   if (off == 0) {
3362     rec->data = (guint8 *) data;
3363     rec->size = size;
3364   } else {
3365     rec->data = g_memdup (data + off, size - off);
3366     rec->size = size - off;
3367     g_free ((gpointer) data);
3368   }
3369
3370   do {
3371     /* make sure rec->id is never 0 */
3372     rec->id = ++watch->id;
3373   } while (G_UNLIKELY (rec->id == 0));
3374
3375   /* add the record to a queue. FIXME we would like to have an upper limit here */
3376   g_queue_push_head (watch->messages, rec);
3377
3378   /* make sure the main context will now also check for writability on the
3379    * socket */
3380   if (!watch->write_added) {
3381     g_source_add_poll ((GSource *) watch, &watch->writefd);
3382     watch->write_added = TRUE;
3383   }
3384
3385   if (id != NULL)
3386     *id = rec->id;
3387   res = GST_RTSP_OK;
3388
3389 done:
3390   g_mutex_unlock (watch->mutex);
3391   return res;
3392 }
3393
3394 /**
3395  * gst_rtsp_watch_send_message:
3396  * @watch: a #GstRTSPWatch
3397  * @message: a #GstRTSPMessage
3398  * @id: location for a message ID or %NULL
3399  *
3400  * Send a @message using the connection of the @watch. If it cannot be sent
3401  * immediately, it will be queued for transmission in @watch. The contents of
3402  * @message will then be serialized and transmitted when the connection of the
3403  * @watch becomes writable. In case the @message is queued, the ID returned in
3404  * @id will be non-zero and used as the ID argument in the message_sent
3405  * callback.
3406  *
3407  * Returns: #GST_RTSP_OK on success.
3408  *
3409  * Since: 0.10.25
3410  */
3411 GstRTSPResult
3412 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3413     guint * id)
3414 {
3415   GString *str;
3416   guint size;
3417
3418   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3419   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3420
3421   /* make a record with the message as a string and id */
3422   str = message_to_string (watch->conn, message);
3423   size = str->len;
3424   return gst_rtsp_watch_write_data (watch,
3425       (guint8 *) g_string_free (str, FALSE), size, id);
3426 }
3427
3428 /**
3429  * gst_rtsp_watch_queue_data:
3430  * @watch: a #GstRTSPWatch
3431  * @data: the data to queue
3432  * @size: the size of @data
3433  *
3434  * Queue @data for transmission in @watch. It will be transmitted when the
3435  * connection of the @watch becomes writable.
3436  *
3437  * This function will take ownership of @data and g_free() it after use.
3438  *
3439  * The return value of this function will be used as the id argument in the
3440  * message_sent callback.
3441  *
3442  * Deprecated: Use gst_rtsp_watch_write_data()
3443  *
3444  * Returns: an id.
3445  *
3446  * Since: 0.10.24
3447  */
3448 #ifndef GST_REMOVE_DEPRECATED
3449 guint
3450 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3451     guint size)
3452 {
3453   GstRTSPRec *rec;
3454
3455   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3456   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3457   g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3458
3459   g_mutex_lock (watch->mutex);
3460
3461   /* make a record with the data and id */
3462   rec = g_slice_new (GstRTSPRec);
3463   rec->data = (guint8 *) data;
3464   rec->size = size;
3465   do {
3466     /* make sure rec->id is never 0 */
3467     rec->id = ++watch->id;
3468   } while (G_UNLIKELY (rec->id == 0));
3469
3470   /* add the record to a queue. FIXME we would like to have an upper limit here */
3471   g_queue_push_head (watch->messages, rec);
3472
3473   /* make sure the main context will now also check for writability on the
3474    * socket */
3475   if (!watch->write_added) {
3476     g_source_add_poll ((GSource *) watch, &watch->writefd);
3477     watch->write_added = TRUE;
3478   }
3479
3480   g_mutex_unlock (watch->mutex);
3481   return rec->id;
3482 }
3483 #endif /* GST_REMOVE_DEPRECATED */
3484
3485 /**
3486  * gst_rtsp_watch_queue_message:
3487  * @watch: a #GstRTSPWatch
3488  * @message: a #GstRTSPMessage
3489  *
3490  * Queue a @message for transmission in @watch. The contents of this
3491  * message will be serialized and transmitted when the connection of the
3492  * @watch becomes writable.
3493  *
3494  * The return value of this function will be used as the id argument in the
3495  * message_sent callback.
3496  *
3497  * Deprecated: Use gst_rtsp_watch_send_message()
3498  *
3499  * Returns: an id.
3500  *
3501  * Since: 0.10.23
3502  */
3503 #ifndef GST_REMOVE_DEPRECATED
3504 guint
3505 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3506 {
3507   GString *str;
3508   guint size;
3509
3510   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3511   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3512
3513   /* make a record with the message as a string and id */
3514   str = message_to_string (watch->conn, message);
3515   size = str->len;
3516   return gst_rtsp_watch_queue_data (watch,
3517       (guint8 *) g_string_free (str, FALSE), size);
3518 }
3519 #endif /* GST_REMOVE_DEPRECATED */