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