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