rtspconnection: calculate better timeout value
[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   gint ctimeout;
2486
2487   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2488   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2489
2490   ctimeout = conn->timeout;
2491   if (ctimeout >= 20) {
2492     /* Because we should act before the timeout we timeout 5
2493      * seconds in advance. */
2494     ctimeout -= 5;
2495   } else if (ctimeout >= 5) {
2496     /* else timeout 20% earlier */
2497     ctimeout -= ctimeout / 5;
2498   } else if (ctimeout >= 1) {
2499     /* else timeout 1 second earlier */
2500     ctimeout -= 1;
2501   }
2502
2503   elapsed = g_timer_elapsed (conn->timer, &usec);
2504   if (elapsed >= ctimeout) {
2505     sec = 0;
2506     usec = 0;
2507   } else {
2508     sec = ctimeout - elapsed;
2509     if (usec <= G_USEC_PER_SEC)
2510       usec = G_USEC_PER_SEC - usec;
2511     else
2512       usec = 0;
2513   }
2514
2515   timeout->tv_sec = sec;
2516   timeout->tv_usec = usec;
2517
2518   return GST_RTSP_OK;
2519 }
2520
2521 /**
2522  * gst_rtsp_connection_reset_timeout:
2523  * @conn: a #GstRTSPConnection
2524  *
2525  * Reset the timeout of @conn.
2526  *
2527  * Returns: #GST_RTSP_OK.
2528  */
2529 GstRTSPResult
2530 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2531 {
2532   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2533
2534   g_timer_start (conn->timer);
2535
2536   return GST_RTSP_OK;
2537 }
2538
2539 /**
2540  * gst_rtsp_connection_flush:
2541  * @conn: a #GstRTSPConnection
2542  * @flush: start or stop the flush
2543  *
2544  * Start or stop the flushing action on @conn. When flushing, all current
2545  * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2546  * is set to non-flushing mode again.
2547  * 
2548  * Returns: #GST_RTSP_OK.
2549  */
2550 GstRTSPResult
2551 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2552 {
2553   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2554
2555   gst_poll_set_flushing (conn->fdset, flush);
2556
2557   return GST_RTSP_OK;
2558 }
2559
2560 /**
2561  * gst_rtsp_connection_set_proxy:
2562  * @conn: a #GstRTSPConnection
2563  * @host: the proxy host
2564  * @port: the proxy port
2565  *
2566  * Set the proxy host and port.
2567  * 
2568  * Returns: #GST_RTSP_OK.
2569  *
2570  * Since: 0.10.23
2571  */
2572 GstRTSPResult
2573 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2574     const gchar * host, guint port)
2575 {
2576   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2577
2578   g_free (conn->proxy_host);
2579   conn->proxy_host = g_strdup (host);
2580   conn->proxy_port = port;
2581
2582   return GST_RTSP_OK;
2583 }
2584
2585 /**
2586  * gst_rtsp_connection_set_auth:
2587  * @conn: a #GstRTSPConnection
2588  * @method: authentication method
2589  * @user: the user
2590  * @pass: the password
2591  *
2592  * Configure @conn for authentication mode @method with @user and @pass as the
2593  * user and password respectively.
2594  * 
2595  * Returns: #GST_RTSP_OK.
2596  */
2597 GstRTSPResult
2598 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2599     GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2600 {
2601   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2602
2603   if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2604           || g_strrstr (user, ":") != NULL))
2605     return GST_RTSP_EINVAL;
2606
2607   /* Make sure the username and passwd are being set for authentication */
2608   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2609     return GST_RTSP_EINVAL;
2610
2611   /* ":" chars are not allowed in usernames for basic auth */
2612   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2613     return GST_RTSP_EINVAL;
2614
2615   g_free (conn->username);
2616   g_free (conn->passwd);
2617
2618   conn->auth_method = method;
2619   conn->username = g_strdup (user);
2620   conn->passwd = g_strdup (pass);
2621
2622   return GST_RTSP_OK;
2623 }
2624
2625 /**
2626  * str_case_hash:
2627  * @key: ASCII string to hash
2628  *
2629  * Hashes @key in a case-insensitive manner.
2630  *
2631  * Returns: the hash code.
2632  **/
2633 static guint
2634 str_case_hash (gconstpointer key)
2635 {
2636   const char *p = key;
2637   guint h = g_ascii_toupper (*p);
2638
2639   if (h)
2640     for (p += 1; *p != '\0'; p++)
2641       h = (h << 5) - h + g_ascii_toupper (*p);
2642
2643   return h;
2644 }
2645
2646 /**
2647  * str_case_equal:
2648  * @v1: an ASCII string
2649  * @v2: another ASCII string
2650  *
2651  * Compares @v1 and @v2 in a case-insensitive manner
2652  *
2653  * Returns: %TRUE if they are equal (modulo case)
2654  **/
2655 static gboolean
2656 str_case_equal (gconstpointer v1, gconstpointer v2)
2657 {
2658   const char *string1 = v1;
2659   const char *string2 = v2;
2660
2661   return g_ascii_strcasecmp (string1, string2) == 0;
2662 }
2663
2664 /**
2665  * gst_rtsp_connection_set_auth_param:
2666  * @conn: a #GstRTSPConnection
2667  * @param: authentication directive
2668  * @value: value
2669  *
2670  * Setup @conn with authentication directives. This is not necesary for
2671  * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2672  * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2673  * in the WWW-Authenticate response header and can include realm, domain,
2674  * nonce, opaque, stale, algorithm, qop as per RFC2617.
2675  * 
2676  * Since: 0.10.20
2677  */
2678 void
2679 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2680     const gchar * param, const gchar * value)
2681 {
2682   g_return_if_fail (conn != NULL);
2683   g_return_if_fail (param != NULL);
2684
2685   if (conn->auth_params == NULL) {
2686     conn->auth_params =
2687         g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2688   }
2689   g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2690 }
2691
2692 /**
2693  * gst_rtsp_connection_clear_auth_params:
2694  * @conn: a #GstRTSPConnection
2695  *
2696  * Clear the list of authentication directives stored in @conn.
2697  *
2698  * Since: 0.10.20
2699  */
2700 void
2701 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2702 {
2703   g_return_if_fail (conn != NULL);
2704
2705   if (conn->auth_params != NULL) {
2706     g_hash_table_destroy (conn->auth_params);
2707     conn->auth_params = NULL;
2708   }
2709 }
2710
2711 static GstRTSPResult
2712 set_qos_dscp (gint fd, guint qos_dscp)
2713 {
2714   union gst_sockaddr sa;
2715   socklen_t slen = sizeof (sa);
2716   gint af;
2717   gint tos;
2718
2719   if (fd == -1)
2720     return GST_RTSP_OK;
2721
2722   if (getsockname (fd, &sa.sa, &slen) < 0)
2723     goto no_getsockname;
2724
2725   af = sa.sa.sa_family;
2726
2727   /* if this is an IPv4-mapped address then do IPv4 QoS */
2728   if (af == AF_INET6) {
2729     if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2730       af = AF_INET;
2731   }
2732
2733   /* extract and shift 6 bits of the DSCP */
2734   tos = (qos_dscp & 0x3f) << 2;
2735
2736   switch (af) {
2737     case AF_INET:
2738       if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2739         goto no_setsockopt;
2740       break;
2741     case AF_INET6:
2742 #ifdef IPV6_TCLASS
2743       if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2744         goto no_setsockopt;
2745       break;
2746 #endif
2747     default:
2748       goto wrong_family;
2749   }
2750
2751   return GST_RTSP_OK;
2752
2753   /* ERRORS */
2754 no_getsockname:
2755 no_setsockopt:
2756   {
2757     return GST_RTSP_ESYS;
2758   }
2759
2760 wrong_family:
2761   {
2762     return GST_RTSP_ERROR;
2763   }
2764 }
2765
2766 /**
2767  * gst_rtsp_connection_set_qos_dscp:
2768  * @conn: a #GstRTSPConnection
2769  * @qos_dscp: DSCP value
2770  *
2771  * Configure @conn to use the specified DSCP value.
2772  *
2773  * Returns: #GST_RTSP_OK on success.
2774  *
2775  * Since: 0.10.20
2776  */
2777 GstRTSPResult
2778 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2779 {
2780   GstRTSPResult res;
2781
2782   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2783   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2784   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2785
2786   res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2787   if (res == GST_RTSP_OK)
2788     res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2789
2790   return res;
2791 }
2792
2793
2794 /**
2795  * gst_rtsp_connection_get_url:
2796  * @conn: a #GstRTSPConnection
2797  *
2798  * Retrieve the URL of the other end of @conn.
2799  *
2800  * Returns: The URL. This value remains valid until the
2801  * connection is freed.
2802  *
2803  * Since: 0.10.23
2804  */
2805 GstRTSPUrl *
2806 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2807 {
2808   g_return_val_if_fail (conn != NULL, NULL);
2809
2810   return conn->url;
2811 }
2812
2813 /**
2814  * gst_rtsp_connection_get_ip:
2815  * @conn: a #GstRTSPConnection
2816  *
2817  * Retrieve the IP address of the other end of @conn.
2818  *
2819  * Returns: The IP address as a string. this value remains valid until the
2820  * connection is closed.
2821  *
2822  * Since: 0.10.20
2823  */
2824 const gchar *
2825 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2826 {
2827   g_return_val_if_fail (conn != NULL, NULL);
2828
2829   return conn->ip;
2830 }
2831
2832 /**
2833  * gst_rtsp_connection_set_ip:
2834  * @conn: a #GstRTSPConnection
2835  * @ip: an ip address
2836  *
2837  * Set the IP address of the server.
2838  *
2839  * Since: 0.10.23
2840  */
2841 void
2842 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2843 {
2844   g_return_if_fail (conn != NULL);
2845
2846   g_free (conn->ip);
2847   conn->ip = g_strdup (ip);
2848 }
2849
2850 /**
2851  * gst_rtsp_connection_get_readfd:
2852  * @conn: a #GstRTSPConnection
2853  *
2854  * Get the file descriptor for reading.
2855  *
2856  * Returns: the file descriptor used for reading or -1 on error. The file
2857  * descriptor remains valid until the connection is closed.
2858  *
2859  * Since: 0.10.23
2860  */
2861 gint
2862 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2863 {
2864   g_return_val_if_fail (conn != NULL, -1);
2865   g_return_val_if_fail (conn->readfd != NULL, -1);
2866
2867   return conn->readfd->fd;
2868 }
2869
2870 /**
2871  * gst_rtsp_connection_get_writefd:
2872  * @conn: a #GstRTSPConnection
2873  *
2874  * Get the file descriptor for writing.
2875  *
2876  * Returns: the file descriptor used for writing or -1 on error. The file
2877  * descriptor remains valid until the connection is closed.
2878  *
2879  * Since: 0.10.23
2880  */
2881 gint
2882 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2883 {
2884   g_return_val_if_fail (conn != NULL, -1);
2885   g_return_val_if_fail (conn->writefd != NULL, -1);
2886
2887   return conn->writefd->fd;
2888 }
2889
2890 /**
2891  * gst_rtsp_connection_set_http_mode:
2892  * @conn: a #GstRTSPConnection
2893  * @enable: %TRUE to enable manual HTTP mode
2894  *
2895  * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2896  * messages in addition to the RTSP messages. It will also disable the
2897  * automatic handling of setting up an HTTP tunnel.
2898  *
2899  * Since: 0.10.25
2900  */
2901 void
2902 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2903 {
2904   g_return_if_fail (conn != NULL);
2905
2906   conn->manual_http = enable;
2907 }
2908
2909 /**
2910  * gst_rtsp_connection_set_tunneled:
2911  * @conn: a #GstRTSPConnection
2912  * @tunneled: the new state
2913  *
2914  * Set the HTTP tunneling state of the connection. This must be configured before
2915  * the @conn is connected.
2916  *
2917  * Since: 0.10.23
2918  */
2919 void
2920 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2921 {
2922   g_return_if_fail (conn != NULL);
2923   g_return_if_fail (conn->readfd == NULL);
2924   g_return_if_fail (conn->writefd == NULL);
2925
2926   conn->tunneled = tunneled;
2927 }
2928
2929 /**
2930  * gst_rtsp_connection_is_tunneled:
2931  * @conn: a #GstRTSPConnection
2932  *
2933  * Get the tunneling state of the connection. 
2934  *
2935  * Returns: if @conn is using HTTP tunneling.
2936  *
2937  * Since: 0.10.23
2938  */
2939 gboolean
2940 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2941 {
2942   g_return_val_if_fail (conn != NULL, FALSE);
2943
2944   return conn->tunneled;
2945 }
2946
2947 /**
2948  * gst_rtsp_connection_get_tunnelid:
2949  * @conn: a #GstRTSPConnection
2950  *
2951  * Get the tunnel session id the connection. 
2952  *
2953  * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2954  *
2955  * Since: 0.10.23
2956  */
2957 const gchar *
2958 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2959 {
2960   g_return_val_if_fail (conn != NULL, NULL);
2961
2962   if (!conn->tunneled)
2963     return NULL;
2964
2965   return conn->tunnelid;
2966 }
2967
2968 /**
2969  * gst_rtsp_connection_do_tunnel:
2970  * @conn: a #GstRTSPConnection
2971  * @conn2: a #GstRTSPConnection or %NULL
2972  *
2973  * If @conn received the first tunnel connection and @conn2 received
2974  * the second tunnel connection, link the two connections together so that
2975  * @conn manages the tunneled connection.
2976  *
2977  * After this call, @conn2 cannot be used anymore and must be freed with
2978  * gst_rtsp_connection_free().
2979  *
2980  * If @conn2 is %NULL then only the base64 decoding context will be setup for
2981  * @conn.
2982  *
2983  * Returns: return GST_RTSP_OK on success.
2984  *
2985  * Since: 0.10.23
2986  */
2987 GstRTSPResult
2988 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2989     GstRTSPConnection * conn2)
2990 {
2991   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2992
2993   if (conn2 != NULL) {
2994     g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2995     g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2996     g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2997             TUNNELID_LEN), GST_RTSP_EINVAL);
2998
2999     /* both connections have fd0 as the read/write socket. start by taking the
3000      * socket from conn2 and set it as the socket in conn */
3001     conn->fd1 = conn2->fd0;
3002
3003     /* clean up some of the state of conn2 */
3004     gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
3005     conn2->fd0.fd = -1;
3006     conn2->readfd = conn2->writefd = NULL;
3007
3008     /* We make fd0 the write socket and fd1 the read socket. */
3009     conn->writefd = &conn->fd0;
3010     conn->readfd = &conn->fd1;
3011
3012     conn->tstate = TUNNEL_STATE_COMPLETE;
3013   }
3014
3015   /* we need base64 decoding for the readfd */
3016   conn->ctx.state = 0;
3017   conn->ctx.save = 0;
3018   conn->ctx.cout = 0;
3019   conn->ctx.coutl = 0;
3020   conn->ctxp = &conn->ctx;
3021
3022   return GST_RTSP_OK;
3023 }
3024
3025 #define READ_ERR    (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
3026 #define READ_COND   (G_IO_IN | READ_ERR)
3027 #define WRITE_ERR   (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
3028 #define WRITE_COND  (G_IO_OUT | WRITE_ERR)
3029
3030 typedef struct
3031 {
3032   guint8 *data;
3033   guint size;
3034   guint id;
3035 } GstRTSPRec;
3036
3037 /* async functions */
3038 struct _GstRTSPWatch
3039 {
3040   GSource source;
3041
3042   GstRTSPConnection *conn;
3043
3044   GstRTSPBuilder builder;
3045   GstRTSPMessage message;
3046
3047   GPollFD readfd;
3048   GPollFD writefd;
3049
3050   /* queued message for transmission */
3051   guint id;
3052   GMutex *mutex;
3053   GQueue *messages;
3054   guint8 *write_data;
3055   guint write_off;
3056   guint write_size;
3057   guint write_id;
3058
3059   GstRTSPWatchFuncs funcs;
3060
3061   gpointer user_data;
3062   GDestroyNotify notify;
3063 };
3064
3065 static gboolean
3066 gst_rtsp_source_prepare (GSource * source, gint * timeout)
3067 {
3068   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3069
3070   if (watch->conn->initial_buffer != NULL)
3071     return TRUE;
3072
3073   *timeout = (watch->conn->timeout * 1000);
3074
3075   return FALSE;
3076 }
3077
3078 static gboolean
3079 gst_rtsp_source_check (GSource * source)
3080 {
3081   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3082
3083   if (watch->readfd.revents & READ_COND)
3084     return TRUE;
3085
3086   if (watch->writefd.revents & WRITE_COND)
3087     return TRUE;
3088
3089   return FALSE;
3090 }
3091
3092 static gboolean
3093 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
3094     gpointer user_data G_GNUC_UNUSED)
3095 {
3096   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3097   GstRTSPResult res = GST_RTSP_ERROR;
3098   gboolean keep_running = TRUE;
3099
3100   /* first read as much as we can */
3101   if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
3102     do {
3103       if (watch->readfd.revents & READ_ERR)
3104         goto read_error;
3105
3106       res = build_next (&watch->builder, &watch->message, watch->conn);
3107       if (res == GST_RTSP_EINTR)
3108         break;
3109       else if (G_UNLIKELY (res == GST_RTSP_EEOF)) {
3110         watch->readfd.events = 0;
3111         watch->readfd.revents = 0;
3112         g_source_remove_poll ((GSource *) watch, &watch->readfd);
3113         /* When we are in tunnelled mode, the read socket can be closed and we
3114          * should be prepared for a new POST method to reopen it */
3115         if (watch->conn->tstate == TUNNEL_STATE_COMPLETE) {
3116           /* remove the read connection for the tunnel */
3117           /* we accept a new POST request */
3118           watch->conn->tstate = TUNNEL_STATE_GET;
3119           /* and signal that we lost our tunnel */
3120           if (watch->funcs.tunnel_lost)
3121             res = watch->funcs.tunnel_lost (watch, watch->user_data);
3122           goto read_done;
3123         } else
3124           goto eof;
3125       } else if (G_LIKELY (res == GST_RTSP_OK)) {
3126         if (!watch->conn->manual_http &&
3127             watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3128           if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3129               watch->message.type_data.request.method == GST_RTSP_GET) {
3130             GstRTSPMessage *response;
3131             GstRTSPStatusCode code;
3132
3133             watch->conn->tstate = TUNNEL_STATE_GET;
3134
3135             if (watch->funcs.tunnel_start)
3136               code = watch->funcs.tunnel_start (watch, watch->user_data);
3137             else
3138               code = GST_RTSP_STS_OK;
3139
3140             /* queue the response */
3141             response = gen_tunnel_reply (watch->conn, code, &watch->message);
3142             gst_rtsp_watch_send_message (watch, response, NULL);
3143             gst_rtsp_message_free (response);
3144             goto read_done;
3145           } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3146               watch->message.type_data.request.method == GST_RTSP_POST) {
3147             watch->conn->tstate = TUNNEL_STATE_POST;
3148
3149             /* in the callback the connection should be tunneled with the
3150              * GET connection */
3151             if (watch->funcs.tunnel_complete)
3152               watch->funcs.tunnel_complete (watch, watch->user_data);
3153             goto read_done;
3154           }
3155         }
3156       }
3157
3158       if (!watch->conn->manual_http) {
3159         /* if manual HTTP support is not enabled, then restore the message to
3160          * what it would have looked like without the support for parsing HTTP
3161          * messages being present */
3162         if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3163           watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3164           watch->message.type_data.request.method = GST_RTSP_INVALID;
3165           if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3166             watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3167           res = GST_RTSP_EPARSE;
3168         } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3169           watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3170           if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3171             watch->message.type_data.response.version =
3172                 GST_RTSP_VERSION_INVALID;
3173           res = GST_RTSP_EPARSE;
3174         }
3175       }
3176
3177       if (G_LIKELY (res == GST_RTSP_OK)) {
3178         if (watch->funcs.message_received)
3179           watch->funcs.message_received (watch, &watch->message,
3180               watch->user_data);
3181       } else {
3182         goto read_error;
3183       }
3184
3185     read_done:
3186       gst_rtsp_message_unset (&watch->message);
3187       build_reset (&watch->builder);
3188     } while (FALSE);
3189   }
3190
3191   if (watch->writefd.revents & WRITE_COND) {
3192     if (watch->writefd.revents & WRITE_ERR)
3193       goto write_error;
3194
3195     g_mutex_lock (watch->mutex);
3196     do {
3197       if (watch->write_data == NULL) {
3198         GstRTSPRec *rec;
3199
3200         /* get a new message from the queue */
3201         rec = g_queue_pop_tail (watch->messages);
3202         if (rec == NULL)
3203           break;
3204
3205         watch->write_off = 0;
3206         watch->write_data = rec->data;
3207         watch->write_size = rec->size;
3208         watch->write_id = rec->id;
3209
3210         g_slice_free (GstRTSPRec, rec);
3211       }
3212
3213       res = write_bytes (watch->writefd.fd, watch->write_data,
3214           &watch->write_off, watch->write_size);
3215       g_mutex_unlock (watch->mutex);
3216
3217       if (res == GST_RTSP_EINTR)
3218         goto write_blocked;
3219       else if (G_LIKELY (res == GST_RTSP_OK)) {
3220         if (watch->funcs.message_sent)
3221           watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3222       } else {
3223         goto write_error;
3224       }
3225       g_mutex_lock (watch->mutex);
3226
3227       g_free (watch->write_data);
3228       watch->write_data = NULL;
3229     } while (TRUE);
3230
3231     watch->writefd.events = WRITE_ERR;
3232
3233     g_mutex_unlock (watch->mutex);
3234   }
3235
3236 write_blocked:
3237   return keep_running;
3238
3239   /* ERRORS */
3240 eof:
3241   {
3242     if (watch->funcs.closed)
3243       watch->funcs.closed (watch, watch->user_data);
3244
3245     /* always stop when the readfd returns EOF in non-tunneled mode */
3246     return FALSE;
3247   }
3248 read_error:
3249   {
3250     watch->readfd.events = 0;
3251     watch->readfd.revents = 0;
3252     g_source_remove_poll ((GSource *) watch, &watch->readfd);
3253     keep_running = (watch->writefd.events != 0);
3254
3255     if (keep_running) {
3256       if (watch->funcs.error_full)
3257         GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3258                 0, watch->user_data), error);
3259       else
3260         goto error;
3261     } else
3262       goto eof;
3263   }
3264 write_error:
3265   {
3266     watch->writefd.events = 0;
3267     watch->writefd.revents = 0;
3268     g_source_remove_poll ((GSource *) watch, &watch->writefd);
3269     keep_running = (watch->readfd.events != 0);
3270
3271     if (keep_running) {
3272       if (watch->funcs.error_full)
3273         GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3274                 watch->write_id, watch->user_data), error);
3275       else
3276         goto error;
3277     } else
3278       goto eof;
3279   }
3280 error:
3281   {
3282     if (watch->funcs.error)
3283       watch->funcs.error (watch, res, watch->user_data);
3284
3285     return keep_running;
3286   }
3287 }
3288
3289 static void
3290 gst_rtsp_rec_free (gpointer data)
3291 {
3292   GstRTSPRec *rec = data;
3293
3294   g_free (rec->data);
3295   g_slice_free (GstRTSPRec, rec);
3296 }
3297
3298 static void
3299 gst_rtsp_source_finalize (GSource * source)
3300 {
3301   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3302
3303   build_reset (&watch->builder);
3304   gst_rtsp_message_unset (&watch->message);
3305
3306   g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3307   g_queue_free (watch->messages);
3308   watch->messages = NULL;
3309   g_free (watch->write_data);
3310
3311   g_mutex_free (watch->mutex);
3312
3313   if (watch->notify)
3314     watch->notify (watch->user_data);
3315 }
3316
3317 static GSourceFuncs gst_rtsp_source_funcs = {
3318   gst_rtsp_source_prepare,
3319   gst_rtsp_source_check,
3320   gst_rtsp_source_dispatch,
3321   gst_rtsp_source_finalize,
3322   NULL,
3323   NULL
3324 };
3325
3326 /**
3327  * gst_rtsp_watch_new:
3328  * @conn: a #GstRTSPConnection
3329  * @funcs: watch functions
3330  * @user_data: user data to pass to @funcs
3331  * @notify: notify when @user_data is not referenced anymore
3332  *
3333  * Create a watch object for @conn. The functions provided in @funcs will be
3334  * called with @user_data when activity happened on the watch.
3335  *
3336  * The new watch is usually created so that it can be attached to a
3337  * maincontext with gst_rtsp_watch_attach(). 
3338  *
3339  * @conn must exist for the entire lifetime of the watch.
3340  *
3341  * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3342  * communication. Free with gst_rtsp_watch_unref () after usage.
3343  *
3344  * Since: 0.10.23
3345  */
3346 GstRTSPWatch *
3347 gst_rtsp_watch_new (GstRTSPConnection * conn,
3348     GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3349 {
3350   GstRTSPWatch *result;
3351
3352   g_return_val_if_fail (conn != NULL, NULL);
3353   g_return_val_if_fail (funcs != NULL, NULL);
3354   g_return_val_if_fail (conn->readfd != NULL, NULL);
3355   g_return_val_if_fail (conn->writefd != NULL, NULL);
3356
3357   result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3358       sizeof (GstRTSPWatch));
3359
3360   result->conn = conn;
3361   result->builder.state = STATE_START;
3362
3363   result->mutex = g_mutex_new ();
3364   result->messages = g_queue_new ();
3365
3366   result->readfd.fd = -1;
3367   result->writefd.fd = -1;
3368
3369   gst_rtsp_watch_reset (result);
3370
3371   result->funcs = *funcs;
3372   result->user_data = user_data;
3373   result->notify = notify;
3374
3375   return result;
3376 }
3377
3378 /**
3379  * gst_rtsp_watch_reset:
3380  * @watch: a #GstRTSPWatch
3381  *
3382  * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3383  * when the file descriptors of the connection might have changed.
3384  *
3385  * Since: 0.10.23
3386  */
3387 void
3388 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3389 {
3390   if (watch->readfd.fd != -1)
3391     g_source_remove_poll ((GSource *) watch, &watch->readfd);
3392   if (watch->writefd.fd != -1)
3393     g_source_remove_poll ((GSource *) watch, &watch->writefd);
3394
3395   watch->readfd.fd = watch->conn->readfd->fd;
3396   watch->readfd.events = READ_COND;
3397   watch->readfd.revents = 0;
3398
3399   watch->writefd.fd = watch->conn->writefd->fd;
3400   watch->writefd.events = WRITE_ERR;
3401   watch->writefd.revents = 0;
3402
3403   if (watch->readfd.fd != -1)
3404     g_source_add_poll ((GSource *) watch, &watch->readfd);
3405   if (watch->writefd.fd != -1)
3406     g_source_add_poll ((GSource *) watch, &watch->writefd);
3407 }
3408
3409 /**
3410  * gst_rtsp_watch_attach:
3411  * @watch: a #GstRTSPWatch
3412  * @context: a GMainContext (if NULL, the default context will be used)
3413  *
3414  * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3415  *
3416  * Returns: the ID (greater than 0) for the watch within the GMainContext. 
3417  *
3418  * Since: 0.10.23
3419  */
3420 guint
3421 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3422 {
3423   g_return_val_if_fail (watch != NULL, 0);
3424
3425   return g_source_attach ((GSource *) watch, context);
3426 }
3427
3428 /**
3429  * gst_rtsp_watch_unref:
3430  * @watch: a #GstRTSPWatch
3431  *
3432  * Decreases the reference count of @watch by one. If the resulting reference
3433  * count is zero the watch and associated memory will be destroyed.
3434  *
3435  * Since: 0.10.23
3436  */
3437 void
3438 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3439 {
3440   g_return_if_fail (watch != NULL);
3441
3442   g_source_unref ((GSource *) watch);
3443 }
3444
3445 /**
3446  * gst_rtsp_watch_write_data:
3447  * @watch: a #GstRTSPWatch
3448  * @data: the data to queue
3449  * @size: the size of @data
3450  * @id: location for a message ID or %NULL
3451  *
3452  * Write @data using the connection of the @watch. If it cannot be sent
3453  * immediately, it will be queued for transmission in @watch. The contents of
3454  * @message will then be serialized and transmitted when the connection of the
3455  * @watch becomes writable. In case the @message is queued, the ID returned in
3456  * @id will be non-zero and used as the ID argument in the message_sent
3457  * callback.
3458  *
3459  * This function will take ownership of @data and g_free() it after use.
3460  *
3461  * Returns: #GST_RTSP_OK on success.
3462  *
3463  * Since: 0.10.25
3464  */
3465 GstRTSPResult
3466 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3467     guint size, guint * id)
3468 {
3469   GstRTSPResult res;
3470   GstRTSPRec *rec;
3471   guint off = 0;
3472   GMainContext *context = NULL;
3473
3474   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3475   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3476   g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3477
3478   g_mutex_lock (watch->mutex);
3479
3480   /* try to send the message synchronously first */
3481   if (watch->messages->length == 0) {
3482     res = write_bytes (watch->writefd.fd, data, &off, size);
3483     if (res != GST_RTSP_EINTR) {
3484       if (id != NULL)
3485         *id = 0;
3486       g_free ((gpointer) data);
3487       goto done;
3488     }
3489   }
3490
3491   /* make a record with the data and id for sending async */
3492   rec = g_slice_new (GstRTSPRec);
3493   if (off == 0) {
3494     rec->data = (guint8 *) data;
3495     rec->size = size;
3496   } else {
3497     rec->data = g_memdup (data + off, size - off);
3498     rec->size = size - off;
3499     g_free ((gpointer) data);
3500   }
3501
3502   do {
3503     /* make sure rec->id is never 0 */
3504     rec->id = ++watch->id;
3505   } while (G_UNLIKELY (rec->id == 0));
3506
3507   /* add the record to a queue. FIXME we would like to have an upper limit here */
3508   g_queue_push_head (watch->messages, rec);
3509
3510   /* make sure the main context will now also check for writability on the
3511    * socket */
3512   if (watch->writefd.events != WRITE_COND) {
3513     watch->writefd.events = WRITE_COND;
3514     context = ((GSource *) watch)->context;
3515   }
3516
3517   if (id != NULL)
3518     *id = rec->id;
3519   res = GST_RTSP_OK;
3520
3521 done:
3522   g_mutex_unlock (watch->mutex);
3523
3524   if (context)
3525     g_main_context_wakeup (context);
3526
3527   return res;
3528 }
3529
3530 /**
3531  * gst_rtsp_watch_send_message:
3532  * @watch: a #GstRTSPWatch
3533  * @message: a #GstRTSPMessage
3534  * @id: location for a message ID or %NULL
3535  *
3536  * Send a @message using the connection of the @watch. If it cannot be sent
3537  * immediately, it will be queued for transmission in @watch. The contents of
3538  * @message will then be serialized and transmitted when the connection of the
3539  * @watch becomes writable. In case the @message is queued, the ID returned in
3540  * @id will be non-zero and used as the ID argument in the message_sent
3541  * callback.
3542  *
3543  * Returns: #GST_RTSP_OK on success.
3544  *
3545  * Since: 0.10.25
3546  */
3547 GstRTSPResult
3548 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3549     guint * id)
3550 {
3551   GString *str;
3552   guint size;
3553
3554   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3555   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3556
3557   /* make a record with the message as a string and id */
3558   str = message_to_string (watch->conn, message);
3559   size = str->len;
3560   return gst_rtsp_watch_write_data (watch,
3561       (guint8 *) g_string_free (str, FALSE), size, id);
3562 }
3563
3564 /**
3565  * gst_rtsp_watch_queue_data:
3566  * @watch: a #GstRTSPWatch
3567  * @data: the data to queue
3568  * @size: the size of @data
3569  *
3570  * Queue @data for transmission in @watch. It will be transmitted when the
3571  * connection of the @watch becomes writable.
3572  *
3573  * This function will take ownership of @data and g_free() it after use.
3574  *
3575  * The return value of this function will be used as the id argument in the
3576  * message_sent callback.
3577  *
3578  * Deprecated: Use gst_rtsp_watch_write_data()
3579  *
3580  * Returns: an id.
3581  *
3582  * Since: 0.10.24
3583  */
3584 #ifndef GST_REMOVE_DEPRECATED
3585 #ifdef GST_DISABLE_DEPRECATED
3586 guint
3587 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3588     guint size);
3589 #endif
3590 guint
3591 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3592     guint size)
3593 {
3594   GstRTSPRec *rec;
3595   GMainContext *context = NULL;
3596
3597   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3598   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3599   g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3600
3601   g_mutex_lock (watch->mutex);
3602
3603   /* make a record with the data and id */
3604   rec = g_slice_new (GstRTSPRec);
3605   rec->data = (guint8 *) data;
3606   rec->size = size;
3607   do {
3608     /* make sure rec->id is never 0 */
3609     rec->id = ++watch->id;
3610   } while (G_UNLIKELY (rec->id == 0));
3611
3612   /* add the record to a queue. FIXME we would like to have an upper limit here */
3613   g_queue_push_head (watch->messages, rec);
3614
3615   /* make sure the main context will now also check for writability on the
3616    * socket */
3617   if (watch->writefd.events != WRITE_COND) {
3618     watch->writefd.events = WRITE_COND;
3619     context = ((GSource *) watch)->context;
3620   }
3621   g_mutex_unlock (watch->mutex);
3622
3623   if (context)
3624     g_main_context_wakeup (context);
3625
3626   return rec->id;
3627 }
3628 #endif /* GST_REMOVE_DEPRECATED */
3629
3630 /**
3631  * gst_rtsp_watch_queue_message:
3632  * @watch: a #GstRTSPWatch
3633  * @message: a #GstRTSPMessage
3634  *
3635  * Queue a @message for transmission in @watch. The contents of this
3636  * message will be serialized and transmitted when the connection of the
3637  * @watch becomes writable.
3638  *
3639  * The return value of this function will be used as the id argument in the
3640  * message_sent callback.
3641  *
3642  * Deprecated: Use gst_rtsp_watch_send_message()
3643  *
3644  * Returns: an id.
3645  *
3646  * Since: 0.10.23
3647  */
3648 #ifndef GST_REMOVE_DEPRECATED
3649 #ifdef GST_DISABLE_DEPRECATED
3650 guint
3651 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message);
3652 #endif
3653 guint
3654 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3655 {
3656   GString *str;
3657   guint size;
3658
3659   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3660   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3661
3662   /* make a record with the message as a string and id */
3663   str = message_to_string (watch->conn, message);
3664   size = str->len;
3665   return gst_rtsp_watch_queue_data (watch,
3666       (guint8 *) g_string_free (str, FALSE), size);
3667 }
3668 #endif /* GST_REMOVE_DEPRECATED */