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