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