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