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