rtsp: weekday and month names in RTSP date string should be in C locale
[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   static const char wkdays[7][4] =
1026       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1027   static const char months[12][4] =
1028       { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
1029     "Nov", "Dec"
1030   };
1031   struct tm tm;
1032   time_t t;
1033
1034   time (&t);
1035
1036 #ifdef HAVE_GMTIME_R
1037   gmtime_r (&t, &tm);
1038 #else
1039   tm = *gmtime (&t);
1040 #endif
1041
1042   g_snprintf (date_string, len, "%s, %02d %s %04d %02d:%02d:%02d GMT",
1043       wkdays[tm.tm_wday], tm.tm_mday, months[tm.tm_mon], tm.tm_year + 1900,
1044       tm.tm_hour, tm.tm_min, tm.tm_sec);
1045 }
1046
1047 static GstRTSPResult
1048 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
1049 {
1050   guint left;
1051
1052   if (G_UNLIKELY (*idx > size))
1053     return GST_RTSP_ERROR;
1054
1055   left = size - *idx;
1056
1057   while (left) {
1058     gint r;
1059
1060     r = WRITE_SOCKET (fd, &buffer[*idx], left);
1061     if (G_UNLIKELY (r == 0)) {
1062       return GST_RTSP_EINTR;
1063     } else if (G_UNLIKELY (r < 0)) {
1064       if (ERRNO_IS_EAGAIN)
1065         return GST_RTSP_EINTR;
1066       if (!ERRNO_IS_EINTR)
1067         return GST_RTSP_ESYS;
1068     } else {
1069       left -= r;
1070       *idx += r;
1071     }
1072   }
1073   return GST_RTSP_OK;
1074 }
1075
1076 static gint
1077 fill_raw_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1078 {
1079   gint out = 0;
1080
1081   if (G_UNLIKELY (conn->initial_buffer != NULL)) {
1082     gsize left = strlen (&conn->initial_buffer[conn->initial_buffer_offset]);
1083
1084     out = MIN (left, size);
1085     memcpy (buffer, &conn->initial_buffer[conn->initial_buffer_offset], out);
1086
1087     if (left == (gsize) out) {
1088       g_free (conn->initial_buffer);
1089       conn->initial_buffer = NULL;
1090       conn->initial_buffer_offset = 0;
1091     } else
1092       conn->initial_buffer_offset += out;
1093   }
1094
1095   if (G_LIKELY (size > (guint) out)) {
1096     gint r;
1097
1098     r = READ_SOCKET (conn->readfd->fd, &buffer[out], size - out);
1099     if (r <= 0) {
1100       if (out == 0)
1101         out = r;
1102     } else
1103       out += r;
1104   }
1105
1106   return out;
1107 }
1108
1109 static gint
1110 fill_bytes (GstRTSPConnection * conn, guint8 * buffer, guint size)
1111 {
1112   DecodeCtx *ctx = conn->ctxp;
1113   gint out = 0;
1114
1115   if (ctx) {
1116     while (size > 0) {
1117       guint8 in[sizeof (ctx->out) * 4 / 3];
1118       gint r;
1119
1120       while (size > 0 && ctx->cout < ctx->coutl) {
1121         /* we have some leftover bytes */
1122         *buffer++ = ctx->out[ctx->cout++];
1123         size--;
1124         out++;
1125       }
1126
1127       /* got what we needed? */
1128       if (size == 0)
1129         break;
1130
1131       /* try to read more bytes */
1132       r = fill_raw_bytes (conn, in, sizeof (in));
1133       if (r <= 0) {
1134         if (out == 0)
1135           out = r;
1136         break;
1137       }
1138
1139       ctx->cout = 0;
1140       ctx->coutl =
1141           g_base64_decode_step ((gchar *) in, r, ctx->out, &ctx->state,
1142           &ctx->save);
1143     }
1144   } else {
1145     out = fill_raw_bytes (conn, buffer, size);
1146   }
1147
1148   return out;
1149 }
1150
1151 static GstRTSPResult
1152 read_bytes (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1153 {
1154   guint left;
1155
1156   if (G_UNLIKELY (*idx > size))
1157     return GST_RTSP_ERROR;
1158
1159   left = size - *idx;
1160
1161   while (left) {
1162     gint r;
1163
1164     r = fill_bytes (conn, &buffer[*idx], left);
1165     if (G_UNLIKELY (r == 0)) {
1166       return GST_RTSP_EEOF;
1167     } else if (G_UNLIKELY (r < 0)) {
1168       if (ERRNO_IS_EAGAIN)
1169         return GST_RTSP_EINTR;
1170       if (!ERRNO_IS_EINTR)
1171         return GST_RTSP_ESYS;
1172     } else {
1173       left -= r;
1174       *idx += r;
1175     }
1176   }
1177   return GST_RTSP_OK;
1178 }
1179
1180 /* The code below tries to handle clients using \r, \n or \r\n to indicate the
1181  * end of a line. It even does its best to handle clients which mix them (even
1182  * though this is a really stupid idea (tm).) It also handles Line White Space
1183  * (LWS), where a line end followed by whitespace is considered LWS. This is
1184  * the method used in RTSP (and HTTP) to break long lines.
1185  */
1186 static GstRTSPResult
1187 read_line (GstRTSPConnection * conn, guint8 * buffer, guint * idx, guint size)
1188 {
1189   while (TRUE) {
1190     guint8 c;
1191     gint r;
1192
1193     if (conn->read_ahead == READ_AHEAD_EOH) {
1194       /* the last call to read_line() already determined that we have reached
1195        * the end of the headers, so convey that information now */
1196       conn->read_ahead = 0;
1197       break;
1198     } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1199       /* the last call to read_line() left off after having read \r\n */
1200       c = '\n';
1201     } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1202       /* the last call to read_line() left off after having read \r\n\r */
1203       c = '\r';
1204     } else if (conn->read_ahead != 0) {
1205       /* the last call to read_line() left us with a character to start with */
1206       c = (guint8) conn->read_ahead;
1207       conn->read_ahead = 0;
1208     } else {
1209       /* read the next character */
1210       r = fill_bytes (conn, &c, 1);
1211       if (G_UNLIKELY (r == 0)) {
1212         return GST_RTSP_EEOF;
1213       } else if (G_UNLIKELY (r < 0)) {
1214         if (ERRNO_IS_EAGAIN)
1215           return GST_RTSP_EINTR;
1216         if (!ERRNO_IS_EINTR)
1217           return GST_RTSP_ESYS;
1218         continue;
1219       }
1220     }
1221
1222     /* special treatment of line endings */
1223     if (c == '\r' || c == '\n') {
1224       guint8 read_ahead;
1225
1226     retry:
1227       /* need to read ahead one more character to know what to do... */
1228       r = fill_bytes (conn, &read_ahead, 1);
1229       if (G_UNLIKELY (r == 0)) {
1230         return GST_RTSP_EEOF;
1231       } else if (G_UNLIKELY (r < 0)) {
1232         if (ERRNO_IS_EAGAIN) {
1233           /* remember the original character we read and try again next time */
1234           if (conn->read_ahead == 0)
1235             conn->read_ahead = c;
1236           return GST_RTSP_EINTR;
1237         }
1238         if (!ERRNO_IS_EINTR)
1239           return GST_RTSP_ESYS;
1240         goto retry;
1241       }
1242
1243       if (read_ahead == ' ' || read_ahead == '\t') {
1244         if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1245           /* got \r\n\r followed by whitespace, treat it as a normal line
1246            * followed by one starting with LWS */
1247           conn->read_ahead = read_ahead;
1248           break;
1249         } else {
1250           /* got LWS, change the line ending to a space and continue */
1251           c = ' ';
1252           conn->read_ahead = read_ahead;
1253         }
1254       } else if (conn->read_ahead == READ_AHEAD_CRLFCR) {
1255         if (read_ahead == '\r' || read_ahead == '\n') {
1256           /* got \r\n\r\r or \r\n\r\n, treat it as the end of the headers */
1257           conn->read_ahead = READ_AHEAD_EOH;
1258           break;
1259         } else {
1260           /* got \r\n\r followed by something else, this is not really
1261            * supported since we have probably just eaten the first character
1262            * of the body or the next message, so just ignore the second \r
1263            * and live with it... */
1264           conn->read_ahead = read_ahead;
1265           break;
1266         }
1267       } else if (conn->read_ahead == READ_AHEAD_CRLF) {
1268         if (read_ahead == '\r') {
1269           /* got \r\n\r so far, need one more character... */
1270           conn->read_ahead = READ_AHEAD_CRLFCR;
1271           goto retry;
1272         } else if (read_ahead == '\n') {
1273           /* got \r\n\n, treat it as the end of the headers */
1274           conn->read_ahead = READ_AHEAD_EOH;
1275           break;
1276         } else {
1277           /* found the end of a line, keep read_ahead for the next line */
1278           conn->read_ahead = read_ahead;
1279           break;
1280         }
1281       } else if (c == read_ahead) {
1282         /* got double \r or \n, treat it as the end of the headers */
1283         conn->read_ahead = READ_AHEAD_EOH;
1284         break;
1285       } else if (c == '\r' && read_ahead == '\n') {
1286         /* got \r\n so far, still need more to know what to do... */
1287         conn->read_ahead = READ_AHEAD_CRLF;
1288         goto retry;
1289       } else {
1290         /* found the end of a line, keep read_ahead for the next line */
1291         conn->read_ahead = read_ahead;
1292         break;
1293       }
1294     }
1295
1296     if (G_LIKELY (*idx < size - 1))
1297       buffer[(*idx)++] = c;
1298   }
1299   buffer[*idx] = '\0';
1300
1301   return GST_RTSP_OK;
1302 }
1303
1304 /**
1305  * gst_rtsp_connection_write:
1306  * @conn: a #GstRTSPConnection
1307  * @data: the data to write
1308  * @size: the size of @data
1309  * @timeout: a timeout value or #NULL
1310  *
1311  * Attempt to write @size bytes of @data to the connected @conn, blocking up to
1312  * the specified @timeout. @timeout can be #NULL, in which case this function
1313  * might block forever.
1314  * 
1315  * This function can be cancelled with gst_rtsp_connection_flush().
1316  *
1317  * Returns: #GST_RTSP_OK on success.
1318  */
1319 GstRTSPResult
1320 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
1321     guint size, GTimeVal * timeout)
1322 {
1323   guint offset;
1324   gint retval;
1325   GstClockTime to;
1326   GstRTSPResult res;
1327
1328   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1329   g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
1330   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
1331
1332   gst_poll_set_controllable (conn->fdset, TRUE);
1333   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, TRUE);
1334   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, FALSE);
1335   /* clear all previous poll results */
1336   gst_poll_fd_ignored (conn->fdset, conn->writefd);
1337   gst_poll_fd_ignored (conn->fdset, conn->readfd);
1338
1339   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1340
1341   offset = 0;
1342
1343   while (TRUE) {
1344     /* try to write */
1345     res = write_bytes (conn->writefd->fd, data, &offset, size);
1346     if (G_LIKELY (res == GST_RTSP_OK))
1347       break;
1348     if (G_UNLIKELY (res != GST_RTSP_EINTR))
1349       goto write_error;
1350
1351     /* not all is written, wait until we can write more */
1352     do {
1353       retval = gst_poll_wait (conn->fdset, to);
1354     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1355
1356     if (G_UNLIKELY (retval == 0))
1357       goto timeout;
1358
1359     if (G_UNLIKELY (retval == -1)) {
1360       if (errno == EBUSY)
1361         goto stopped;
1362       else
1363         goto select_error;
1364     }
1365
1366     /* could also be an error with read socket */
1367     if (gst_poll_fd_has_error (conn->fdset, conn->readfd))
1368       goto socket_error;
1369   }
1370   return GST_RTSP_OK;
1371
1372   /* ERRORS */
1373 timeout:
1374   {
1375     return GST_RTSP_ETIMEOUT;
1376   }
1377 select_error:
1378   {
1379     return GST_RTSP_ESYS;
1380   }
1381 stopped:
1382   {
1383     return GST_RTSP_EINTR;
1384   }
1385 socket_error:
1386   {
1387     return GST_RTSP_ENET;
1388   }
1389 write_error:
1390   {
1391     return res;
1392   }
1393 }
1394
1395 static GString *
1396 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
1397 {
1398   GString *str = NULL;
1399
1400   str = g_string_new ("");
1401
1402   switch (message->type) {
1403     case GST_RTSP_MESSAGE_REQUEST:
1404       /* create request string, add CSeq */
1405       g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
1406           "CSeq: %d\r\n",
1407           gst_rtsp_method_as_text (message->type_data.request.method),
1408           message->type_data.request.uri, conn->cseq++);
1409       /* add session id if we have one */
1410       if (conn->session_id[0] != '\0') {
1411         gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
1412         gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
1413             conn->session_id);
1414       }
1415       /* add any authentication headers */
1416       add_auth_header (conn, message);
1417       break;
1418     case GST_RTSP_MESSAGE_RESPONSE:
1419       /* create response string */
1420       g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
1421           message->type_data.response.code, message->type_data.response.reason);
1422       break;
1423     case GST_RTSP_MESSAGE_HTTP_REQUEST:
1424       /* create request string */
1425       g_string_append_printf (str, "%s %s HTTP/%s\r\n",
1426           gst_rtsp_method_as_text (message->type_data.request.method),
1427           message->type_data.request.uri,
1428           gst_rtsp_version_as_text (message->type_data.request.version));
1429       /* add any authentication headers */
1430       add_auth_header (conn, message);
1431       break;
1432     case GST_RTSP_MESSAGE_HTTP_RESPONSE:
1433       /* create response string */
1434       g_string_append_printf (str, "HTTP/%s %d %s\r\n",
1435           gst_rtsp_version_as_text (message->type_data.request.version),
1436           message->type_data.response.code, message->type_data.response.reason);
1437       break;
1438     case GST_RTSP_MESSAGE_DATA:
1439     {
1440       guint8 data_header[4];
1441
1442       /* prepare data header */
1443       data_header[0] = '$';
1444       data_header[1] = message->type_data.data.channel;
1445       data_header[2] = (message->body_size >> 8) & 0xff;
1446       data_header[3] = message->body_size & 0xff;
1447
1448       /* create string with header and data */
1449       str = g_string_append_len (str, (gchar *) data_header, 4);
1450       str =
1451           g_string_append_len (str, (gchar *) message->body,
1452           message->body_size);
1453       break;
1454     }
1455     default:
1456       g_string_free (str, TRUE);
1457       g_return_val_if_reached (NULL);
1458       break;
1459   }
1460
1461   /* append headers and body */
1462   if (message->type != GST_RTSP_MESSAGE_DATA) {
1463     gchar date_string[100];
1464
1465     gen_date_string (date_string, sizeof (date_string));
1466
1467     /* add date header */
1468     gst_rtsp_message_remove_header (message, GST_RTSP_HDR_DATE, -1);
1469     gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
1470
1471     /* append headers */
1472     gst_rtsp_message_append_headers (message, str);
1473
1474     /* append Content-Length and body if needed */
1475     if (message->body != NULL && message->body_size > 0) {
1476       gchar *len;
1477
1478       len = g_strdup_printf ("%d", message->body_size);
1479       g_string_append_printf (str, "%s: %s\r\n",
1480           gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
1481       g_free (len);
1482       /* header ends here */
1483       g_string_append (str, "\r\n");
1484       str =
1485           g_string_append_len (str, (gchar *) message->body,
1486           message->body_size);
1487     } else {
1488       /* just end headers */
1489       g_string_append (str, "\r\n");
1490     }
1491   }
1492
1493   return str;
1494 }
1495
1496 /**
1497  * gst_rtsp_connection_send:
1498  * @conn: a #GstRTSPConnection
1499  * @message: the message to send
1500  * @timeout: a timeout value or #NULL
1501  *
1502  * Attempt to send @message to the connected @conn, blocking up to
1503  * the specified @timeout. @timeout can be #NULL, in which case this function
1504  * might block forever.
1505  * 
1506  * This function can be cancelled with gst_rtsp_connection_flush().
1507  *
1508  * Returns: #GST_RTSP_OK on success.
1509  */
1510 GstRTSPResult
1511 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
1512     GTimeVal * timeout)
1513 {
1514   GString *string = NULL;
1515   GstRTSPResult res;
1516   gchar *str;
1517   gsize len;
1518
1519   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1520   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1521
1522   if (G_UNLIKELY (!(string = message_to_string (conn, message))))
1523     goto no_message;
1524
1525   if (conn->tunneled) {
1526     str = g_base64_encode ((const guchar *) string->str, string->len);
1527     g_string_free (string, TRUE);
1528     len = strlen (str);
1529   } else {
1530     str = string->str;
1531     len = string->len;
1532     g_string_free (string, FALSE);
1533   }
1534
1535   /* write request */
1536   res = gst_rtsp_connection_write (conn, (guint8 *) str, len, timeout);
1537
1538   g_free (str);
1539
1540   return res;
1541
1542 no_message:
1543   {
1544     g_warning ("Wrong message");
1545     return GST_RTSP_EINVAL;
1546   }
1547 }
1548
1549 static GstRTSPResult
1550 parse_string (gchar * dest, gint size, gchar ** src)
1551 {
1552   GstRTSPResult res = GST_RTSP_OK;
1553   gint idx;
1554
1555   idx = 0;
1556   /* skip spaces */
1557   while (g_ascii_isspace (**src))
1558     (*src)++;
1559
1560   while (!g_ascii_isspace (**src) && **src != '\0') {
1561     if (idx < size - 1)
1562       dest[idx++] = **src;
1563     else
1564       res = GST_RTSP_EPARSE;
1565     (*src)++;
1566   }
1567   if (size > 0)
1568     dest[idx] = '\0';
1569
1570   return res;
1571 }
1572
1573 static GstRTSPResult
1574 parse_protocol_version (gchar * protocol, GstRTSPMsgType * type,
1575     GstRTSPVersion * version)
1576 {
1577   GstRTSPResult res = GST_RTSP_OK;
1578   gchar *ver;
1579
1580   if (G_LIKELY ((ver = strchr (protocol, '/')) != NULL)) {
1581     guint major;
1582     guint minor;
1583     gchar dummychar;
1584
1585     *ver++ = '\0';
1586
1587     /* the version number must be formatted as X.Y with nothing following */
1588     if (sscanf (ver, "%u.%u%c", &major, &minor, &dummychar) != 2)
1589       res = GST_RTSP_EPARSE;
1590
1591     if (g_ascii_strcasecmp (protocol, "RTSP") == 0) {
1592       if (major != 1 || minor != 0) {
1593         *version = GST_RTSP_VERSION_INVALID;
1594         res = GST_RTSP_ERROR;
1595       }
1596     } else if (g_ascii_strcasecmp (protocol, "HTTP") == 0) {
1597       if (*type == GST_RTSP_MESSAGE_REQUEST)
1598         *type = GST_RTSP_MESSAGE_HTTP_REQUEST;
1599       else if (*type == GST_RTSP_MESSAGE_RESPONSE)
1600         *type = GST_RTSP_MESSAGE_HTTP_RESPONSE;
1601
1602       if (major == 1 && minor == 1) {
1603         *version = GST_RTSP_VERSION_1_1;
1604       } else if (major != 1 || minor != 0) {
1605         *version = GST_RTSP_VERSION_INVALID;
1606         res = GST_RTSP_ERROR;
1607       }
1608     } else
1609       res = GST_RTSP_EPARSE;
1610   } else
1611     res = GST_RTSP_EPARSE;
1612
1613   return res;
1614 }
1615
1616 static GstRTSPResult
1617 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
1618 {
1619   GstRTSPResult res = GST_RTSP_OK;
1620   GstRTSPResult res2;
1621   gchar versionstr[20];
1622   gchar codestr[4];
1623   gint code;
1624   gchar *bptr;
1625
1626   bptr = (gchar *) buffer;
1627
1628   if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1629     res = GST_RTSP_EPARSE;
1630
1631   if (parse_string (codestr, sizeof (codestr), &bptr) != GST_RTSP_OK)
1632     res = GST_RTSP_EPARSE;
1633   code = atoi (codestr);
1634   if (G_UNLIKELY (*codestr == '\0' || code < 0 || code >= 600))
1635     res = GST_RTSP_EPARSE;
1636
1637   while (g_ascii_isspace (*bptr))
1638     bptr++;
1639
1640   if (G_UNLIKELY (gst_rtsp_message_init_response (msg, code, bptr,
1641               NULL) != GST_RTSP_OK))
1642     res = GST_RTSP_EPARSE;
1643
1644   res2 = parse_protocol_version (versionstr, &msg->type,
1645       &msg->type_data.response.version);
1646   if (G_LIKELY (res == GST_RTSP_OK))
1647     res = res2;
1648
1649   return res;
1650 }
1651
1652 static GstRTSPResult
1653 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
1654 {
1655   GstRTSPResult res = GST_RTSP_OK;
1656   GstRTSPResult res2;
1657   gchar versionstr[20];
1658   gchar methodstr[20];
1659   gchar urlstr[4096];
1660   gchar *bptr;
1661   GstRTSPMethod method;
1662
1663   bptr = (gchar *) buffer;
1664
1665   if (parse_string (methodstr, sizeof (methodstr), &bptr) != GST_RTSP_OK)
1666     res = GST_RTSP_EPARSE;
1667   method = gst_rtsp_find_method (methodstr);
1668
1669   if (parse_string (urlstr, sizeof (urlstr), &bptr) != GST_RTSP_OK)
1670     res = GST_RTSP_EPARSE;
1671   if (G_UNLIKELY (*urlstr == '\0'))
1672     res = GST_RTSP_EPARSE;
1673
1674   if (parse_string (versionstr, sizeof (versionstr), &bptr) != GST_RTSP_OK)
1675     res = GST_RTSP_EPARSE;
1676
1677   if (G_UNLIKELY (*bptr != '\0'))
1678     res = GST_RTSP_EPARSE;
1679
1680   if (G_UNLIKELY (gst_rtsp_message_init_request (msg, method,
1681               urlstr) != GST_RTSP_OK))
1682     res = GST_RTSP_EPARSE;
1683
1684   res2 = parse_protocol_version (versionstr, &msg->type,
1685       &msg->type_data.request.version);
1686   if (G_LIKELY (res == GST_RTSP_OK))
1687     res = res2;
1688
1689   if (G_LIKELY (msg->type == GST_RTSP_MESSAGE_REQUEST)) {
1690     /* GET and POST are not allowed as RTSP methods */
1691     if (msg->type_data.request.method == GST_RTSP_GET ||
1692         msg->type_data.request.method == GST_RTSP_POST) {
1693       msg->type_data.request.method = GST_RTSP_INVALID;
1694       if (res == GST_RTSP_OK)
1695         res = GST_RTSP_ERROR;
1696     }
1697   } else if (msg->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
1698     /* only GET and POST are allowed as HTTP methods */
1699     if (msg->type_data.request.method != GST_RTSP_GET &&
1700         msg->type_data.request.method != GST_RTSP_POST) {
1701       msg->type_data.request.method = GST_RTSP_INVALID;
1702       if (res == GST_RTSP_OK)
1703         res = GST_RTSP_ERROR;
1704     }
1705   }
1706
1707   return res;
1708 }
1709
1710 /* parsing lines means reading a Key: Value pair */
1711 static GstRTSPResult
1712 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1713 {
1714   GstRTSPHeaderField field;
1715   gchar *line = (gchar *) buffer;
1716   gchar *value;
1717
1718   if ((value = strchr (line, ':')) == NULL || value == line)
1719     goto parse_error;
1720
1721   /* trim space before the colon */
1722   if (value[-1] == ' ')
1723     value[-1] = '\0';
1724
1725   /* replace the colon with a NUL */
1726   *value++ = '\0';
1727
1728   /* find the header */
1729   field = gst_rtsp_find_header_field (line);
1730   if (field == GST_RTSP_HDR_INVALID)
1731     goto done;
1732
1733   /* split up the value in multiple key:value pairs if it contains comma(s) */
1734   while (*value != '\0') {
1735     gchar *next_value;
1736     gchar *comma = NULL;
1737     gboolean quoted = FALSE;
1738     guint comment = 0;
1739
1740     /* trim leading space */
1741     if (*value == ' ')
1742       value++;
1743
1744     /* for headers which may not appear multiple times, and thus may not
1745      * contain multiple values on the same line, we can short-circuit the loop
1746      * below and the entire value results in just one key:value pair*/
1747     if (!gst_rtsp_header_allow_multiple (field))
1748       next_value = value + strlen (value);
1749     else
1750       next_value = value;
1751
1752     /* find the next value, taking special care of quotes and comments */
1753     while (*next_value != '\0') {
1754       if ((quoted || comment != 0) && *next_value == '\\' &&
1755           next_value[1] != '\0')
1756         next_value++;
1757       else if (comment == 0 && *next_value == '"')
1758         quoted = !quoted;
1759       else if (!quoted && *next_value == '(')
1760         comment++;
1761       else if (comment != 0 && *next_value == ')')
1762         comment--;
1763       else if (!quoted && comment == 0) {
1764         /* To quote RFC 2068: "User agents MUST take special care in parsing
1765          * the WWW-Authenticate field value if it contains more than one
1766          * challenge, or if more than one WWW-Authenticate header field is
1767          * provided, since the contents of a challenge may itself contain a
1768          * comma-separated list of authentication parameters."
1769          *
1770          * What this means is that we cannot just look for an unquoted comma
1771          * when looking for multiple values in Proxy-Authenticate and
1772          * WWW-Authenticate headers. Instead we need to look for the sequence
1773          * "comma [space] token space token" before we can split after the
1774          * comma...
1775          */
1776         if (field == GST_RTSP_HDR_PROXY_AUTHENTICATE ||
1777             field == GST_RTSP_HDR_WWW_AUTHENTICATE) {
1778           if (*next_value == ',') {
1779             if (next_value[1] == ' ') {
1780               /* skip any space following the comma so we do not mistake it for
1781                * separating between two tokens */
1782               next_value++;
1783             }
1784             comma = next_value;
1785           } else if (*next_value == ' ' && next_value[1] != ',' &&
1786               next_value[1] != '=' && comma != NULL) {
1787             next_value = comma;
1788             comma = NULL;
1789             break;
1790           }
1791         } else if (*next_value == ',')
1792           break;
1793       }
1794
1795       next_value++;
1796     }
1797
1798     /* trim space */
1799     if (value != next_value && next_value[-1] == ' ')
1800       next_value[-1] = '\0';
1801
1802     if (*next_value != '\0')
1803       *next_value++ = '\0';
1804
1805     /* add the key:value pair */
1806     if (*value != '\0')
1807       gst_rtsp_message_add_header (msg, field, value);
1808
1809     value = next_value;
1810   }
1811
1812 done:
1813   return GST_RTSP_OK;
1814
1815   /* ERRORS */
1816 parse_error:
1817   {
1818     return GST_RTSP_EPARSE;
1819   }
1820 }
1821
1822 /* convert all consecutive whitespace to a single space */
1823 static void
1824 normalize_line (guint8 * buffer)
1825 {
1826   while (*buffer) {
1827     if (g_ascii_isspace (*buffer)) {
1828       guint8 *tmp;
1829
1830       *buffer++ = ' ';
1831       for (tmp = buffer; g_ascii_isspace (*tmp); tmp++) {
1832       }
1833       if (buffer != tmp)
1834         memmove (buffer, tmp, strlen ((gchar *) tmp) + 1);
1835     } else {
1836       buffer++;
1837     }
1838   }
1839 }
1840
1841 /* returns:
1842  *  GST_RTSP_OK when a complete message was read.
1843  *  GST_RTSP_EEOF: when the read socket is closed
1844  *  GST_RTSP_EINTR: when more data is needed.
1845  *  GST_RTSP_..: some other error occured.
1846  */
1847 static GstRTSPResult
1848 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1849     GstRTSPConnection * conn)
1850 {
1851   GstRTSPResult res;
1852
1853   while (TRUE) {
1854     switch (builder->state) {
1855       case STATE_START:
1856       {
1857         guint8 c;
1858
1859         builder->offset = 0;
1860         res =
1861             read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 1);
1862         if (res != GST_RTSP_OK)
1863           goto done;
1864
1865         c = builder->buffer[0];
1866
1867         /* we have 1 bytes now and we can see if this is a data message or
1868          * not */
1869         if (c == '$') {
1870           /* data message, prepare for the header */
1871           builder->state = STATE_DATA_HEADER;
1872         } else if (c == '\n' || c == '\r') {
1873           /* skip \n and \r */
1874           builder->offset = 0;
1875         } else {
1876           builder->line = 0;
1877           builder->state = STATE_READ_LINES;
1878         }
1879         break;
1880       }
1881       case STATE_DATA_HEADER:
1882       {
1883         res =
1884             read_bytes (conn, (guint8 *) builder->buffer, &builder->offset, 4);
1885         if (res != GST_RTSP_OK)
1886           goto done;
1887
1888         gst_rtsp_message_init_data (message, builder->buffer[1]);
1889
1890         builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1891         builder->body_data = g_malloc (builder->body_len + 1);
1892         builder->body_data[builder->body_len] = '\0';
1893         builder->offset = 0;
1894         builder->state = STATE_DATA_BODY;
1895         break;
1896       }
1897       case STATE_DATA_BODY:
1898       {
1899         res =
1900             read_bytes (conn, builder->body_data, &builder->offset,
1901             builder->body_len);
1902         if (res != GST_RTSP_OK)
1903           goto done;
1904
1905         /* we have the complete body now, store in the message adjusting the
1906          * length to include the traling '\0' */
1907         gst_rtsp_message_take_body (message,
1908             (guint8 *) builder->body_data, builder->body_len + 1);
1909         builder->body_data = NULL;
1910         builder->body_len = 0;
1911
1912         builder->state = STATE_END;
1913         break;
1914       }
1915       case STATE_READ_LINES:
1916       {
1917         res = read_line (conn, builder->buffer, &builder->offset,
1918             sizeof (builder->buffer));
1919         if (res != GST_RTSP_OK)
1920           goto done;
1921
1922         /* we have a regular response */
1923         if (builder->buffer[0] == '\0') {
1924           gchar *hdrval;
1925
1926           /* empty line, end of message header */
1927           /* see if there is a Content-Length header, but ignore it if this
1928            * is a POST request with an x-sessioncookie header */
1929           if (gst_rtsp_message_get_header (message,
1930                   GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK &&
1931               (message->type != GST_RTSP_MESSAGE_HTTP_REQUEST ||
1932                   message->type_data.request.method != GST_RTSP_POST ||
1933                   gst_rtsp_message_get_header (message,
1934                       GST_RTSP_HDR_X_SESSIONCOOKIE, NULL, 0) != GST_RTSP_OK)) {
1935             /* there is, prepare to read the body */
1936             builder->body_len = atol (hdrval);
1937             builder->body_data = g_try_malloc (builder->body_len + 1);
1938             /* we can't do much here, we need the length to know how many bytes
1939              * we need to read next and when allocation fails, something is
1940              * probably wrong with the length. */
1941             if (builder->body_data == NULL)
1942               goto invalid_body_len;
1943
1944             builder->body_data[builder->body_len] = '\0';
1945             builder->offset = 0;
1946             builder->state = STATE_DATA_BODY;
1947           } else {
1948             builder->state = STATE_END;
1949           }
1950           break;
1951         }
1952
1953         /* we have a line */
1954         normalize_line (builder->buffer);
1955         if (builder->line == 0) {
1956           /* first line, check for response status */
1957           if (memcmp (builder->buffer, "RTSP", 4) == 0 ||
1958               memcmp (builder->buffer, "HTTP", 4) == 0) {
1959             builder->status = parse_response_status (builder->buffer, message);
1960           } else {
1961             builder->status = parse_request_line (builder->buffer, message);
1962           }
1963         } else {
1964           /* else just parse the line */
1965           res = parse_line (builder->buffer, message);
1966           if (res != GST_RTSP_OK)
1967             builder->status = res;
1968         }
1969         builder->line++;
1970         builder->offset = 0;
1971         break;
1972       }
1973       case STATE_END:
1974       {
1975         gchar *session_cookie;
1976         gchar *session_id;
1977
1978         if (message->type == GST_RTSP_MESSAGE_DATA) {
1979           /* data messages don't have headers */
1980           res = GST_RTSP_OK;
1981           goto done;
1982         }
1983
1984         /* save the tunnel session in the connection */
1985         if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST &&
1986             !conn->manual_http &&
1987             conn->tstate == TUNNEL_STATE_NONE &&
1988             gst_rtsp_message_get_header (message, GST_RTSP_HDR_X_SESSIONCOOKIE,
1989                 &session_cookie, 0) == GST_RTSP_OK) {
1990           strncpy (conn->tunnelid, session_cookie, TUNNELID_LEN);
1991           conn->tunnelid[TUNNELID_LEN - 1] = '\0';
1992           conn->tunneled = TRUE;
1993         }
1994
1995         /* save session id in the connection for further use */
1996         if (message->type == GST_RTSP_MESSAGE_RESPONSE &&
1997             gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1998                 &session_id, 0) == GST_RTSP_OK) {
1999           gint maxlen, i;
2000
2001           maxlen = sizeof (conn->session_id) - 1;
2002           /* the sessionid can have attributes marked with ;
2003            * Make sure we strip them */
2004           for (i = 0; session_id[i] != '\0'; i++) {
2005             if (session_id[i] == ';') {
2006               maxlen = i;
2007               /* parse timeout */
2008               do {
2009                 i++;
2010               } while (g_ascii_isspace (session_id[i]));
2011               if (g_str_has_prefix (&session_id[i], "timeout=")) {
2012                 gint to;
2013
2014                 /* if we parsed something valid, configure */
2015                 if ((to = atoi (&session_id[i + 8])) > 0)
2016                   conn->timeout = to;
2017               }
2018               break;
2019             }
2020           }
2021
2022           /* make sure to not overflow */
2023           strncpy (conn->session_id, session_id, maxlen);
2024           conn->session_id[maxlen] = '\0';
2025         }
2026         res = builder->status;
2027         goto done;
2028       }
2029       default:
2030         res = GST_RTSP_ERROR;
2031         break;
2032     }
2033   }
2034 done:
2035   return res;
2036
2037   /* ERRORS */
2038 invalid_body_len:
2039   {
2040     GST_DEBUG ("could not allocate body");
2041     return GST_RTSP_ERROR;
2042   }
2043 }
2044
2045 /**
2046  * gst_rtsp_connection_read:
2047  * @conn: a #GstRTSPConnection
2048  * @data: the data to read
2049  * @size: the size of @data
2050  * @timeout: a timeout value or #NULL
2051  *
2052  * Attempt to read @size bytes into @data from the connected @conn, blocking up to
2053  * the specified @timeout. @timeout can be #NULL, in which case this function
2054  * might block forever.
2055  *
2056  * This function can be cancelled with gst_rtsp_connection_flush().
2057  *
2058  * Returns: #GST_RTSP_OK on success.
2059  */
2060 GstRTSPResult
2061 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
2062     GTimeVal * timeout)
2063 {
2064   guint offset;
2065   gint retval;
2066   GstClockTime to;
2067   GstRTSPResult res;
2068
2069   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2070   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
2071   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2072
2073   if (G_UNLIKELY (size == 0))
2074     return GST_RTSP_OK;
2075
2076   offset = 0;
2077
2078   /* configure timeout if any */
2079   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2080
2081   gst_poll_set_controllable (conn->fdset, TRUE);
2082   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2083   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2084
2085   while (TRUE) {
2086     res = read_bytes (conn, data, &offset, size);
2087     if (G_UNLIKELY (res == GST_RTSP_EEOF))
2088       goto eof;
2089     if (G_LIKELY (res == GST_RTSP_OK))
2090       break;
2091     if (G_UNLIKELY (res != GST_RTSP_EINTR))
2092       goto read_error;
2093
2094     do {
2095       retval = gst_poll_wait (conn->fdset, to);
2096     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2097
2098     /* check for timeout */
2099     if (G_UNLIKELY (retval == 0))
2100       goto select_timeout;
2101
2102     if (G_UNLIKELY (retval == -1)) {
2103       if (errno == EBUSY)
2104         goto stopped;
2105       else
2106         goto select_error;
2107     }
2108
2109     /* could also be an error with write socket */
2110     if (gst_poll_fd_has_error (conn->fdset, conn->writefd))
2111       goto socket_error;
2112
2113     gst_poll_set_controllable (conn->fdset, FALSE);
2114   }
2115   return GST_RTSP_OK;
2116
2117   /* ERRORS */
2118 select_error:
2119   {
2120     return GST_RTSP_ESYS;
2121   }
2122 select_timeout:
2123   {
2124     return GST_RTSP_ETIMEOUT;
2125   }
2126 stopped:
2127   {
2128     return GST_RTSP_EINTR;
2129   }
2130 eof:
2131   {
2132     return GST_RTSP_EEOF;
2133   }
2134 socket_error:
2135   {
2136     res = GST_RTSP_ENET;
2137   }
2138 read_error:
2139   {
2140     return res;
2141   }
2142 }
2143
2144 static GstRTSPMessage *
2145 gen_tunnel_reply (GstRTSPConnection * conn, GstRTSPStatusCode code,
2146     const GstRTSPMessage * request)
2147 {
2148   GstRTSPMessage *msg;
2149   GstRTSPResult res;
2150
2151   if (gst_rtsp_status_as_text (code) == NULL)
2152     code = GST_RTSP_STS_INTERNAL_SERVER_ERROR;
2153
2154   GST_RTSP_CHECK (gst_rtsp_message_new_response (&msg, code, NULL, request),
2155       no_message);
2156
2157   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_SERVER,
2158       "GStreamer RTSP Server");
2159   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONNECTION, "close");
2160   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CACHE_CONTROL, "no-store");
2161   gst_rtsp_message_add_header (msg, GST_RTSP_HDR_PRAGMA, "no-cache");
2162
2163   if (code == GST_RTSP_STS_OK) {
2164     if (conn->ip)
2165       gst_rtsp_message_add_header (msg, GST_RTSP_HDR_X_SERVER_IP_ADDRESS,
2166           conn->ip);
2167     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_CONTENT_TYPE,
2168         "application/x-rtsp-tunnelled");
2169   }
2170
2171   return msg;
2172
2173   /* ERRORS */
2174 no_message:
2175   {
2176     return NULL;
2177   }
2178 }
2179
2180 /**
2181  * gst_rtsp_connection_receive:
2182  * @conn: a #GstRTSPConnection
2183  * @message: the message to read
2184  * @timeout: a timeout value or #NULL
2185  *
2186  * Attempt to read into @message from the connected @conn, blocking up to
2187  * the specified @timeout. @timeout can be #NULL, in which case this function
2188  * might block forever.
2189  * 
2190  * This function can be cancelled with gst_rtsp_connection_flush().
2191  *
2192  * Returns: #GST_RTSP_OK on success.
2193  */
2194 GstRTSPResult
2195 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
2196     GTimeVal * timeout)
2197 {
2198   GstRTSPResult res;
2199   GstRTSPBuilder builder;
2200   gint retval;
2201   GstClockTime to;
2202
2203   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2204   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2205   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2206
2207   /* configure timeout if any */
2208   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2209
2210   gst_poll_set_controllable (conn->fdset, TRUE);
2211   gst_poll_fd_ctl_write (conn->fdset, conn->writefd, FALSE);
2212   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, TRUE);
2213
2214   memset (&builder, 0, sizeof (GstRTSPBuilder));
2215   while (TRUE) {
2216     res = build_next (&builder, message, conn);
2217     if (G_UNLIKELY (res == GST_RTSP_EEOF))
2218       goto eof;
2219     else if (G_LIKELY (res == GST_RTSP_OK)) {
2220       if (!conn->manual_http) {
2221         if (message->type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
2222           if (conn->tstate == TUNNEL_STATE_NONE &&
2223               message->type_data.request.method == GST_RTSP_GET) {
2224             GstRTSPMessage *response;
2225
2226             conn->tstate = TUNNEL_STATE_GET;
2227
2228             /* tunnel GET request, we can reply now */
2229             response = gen_tunnel_reply (conn, GST_RTSP_STS_OK, message);
2230             res = gst_rtsp_connection_send (conn, response, timeout);
2231             gst_rtsp_message_free (response);
2232             if (res == GST_RTSP_OK)
2233               res = GST_RTSP_ETGET;
2234             goto cleanup;
2235           } else if (conn->tstate == TUNNEL_STATE_NONE &&
2236               message->type_data.request.method == GST_RTSP_POST) {
2237             conn->tstate = TUNNEL_STATE_POST;
2238
2239             /* tunnel POST request, the caller now has to link the two
2240              * connections. */
2241             res = GST_RTSP_ETPOST;
2242             goto cleanup;
2243           } else {
2244             res = GST_RTSP_EPARSE;
2245             goto cleanup;
2246           }
2247         } else if (message->type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
2248           res = GST_RTSP_EPARSE;
2249           goto cleanup;
2250         }
2251       }
2252
2253       break;
2254     } else if (G_UNLIKELY (res != GST_RTSP_EINTR))
2255       goto read_error;
2256
2257     do {
2258       retval = gst_poll_wait (conn->fdset, to);
2259     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2260
2261     /* check for timeout */
2262     if (G_UNLIKELY (retval == 0))
2263       goto select_timeout;
2264
2265     if (G_UNLIKELY (retval == -1)) {
2266       if (errno == EBUSY)
2267         goto stopped;
2268       else
2269         goto select_error;
2270     }
2271
2272     /* could also be an error with write socket */
2273     if (gst_poll_fd_has_error (conn->fdset, conn->writefd))
2274       goto socket_error;
2275
2276     gst_poll_set_controllable (conn->fdset, FALSE);
2277   }
2278
2279   /* we have a message here */
2280   build_reset (&builder);
2281
2282   return GST_RTSP_OK;
2283
2284   /* ERRORS */
2285 select_error:
2286   {
2287     res = GST_RTSP_ESYS;
2288     goto cleanup;
2289   }
2290 select_timeout:
2291   {
2292     res = GST_RTSP_ETIMEOUT;
2293     goto cleanup;
2294   }
2295 stopped:
2296   {
2297     res = GST_RTSP_EINTR;
2298     goto cleanup;
2299   }
2300 eof:
2301   {
2302     res = GST_RTSP_EEOF;
2303     goto cleanup;
2304   }
2305 socket_error:
2306   {
2307     res = GST_RTSP_ENET;
2308     goto cleanup;
2309   }
2310 read_error:
2311 cleanup:
2312   {
2313     build_reset (&builder);
2314     gst_rtsp_message_unset (message);
2315     return res;
2316   }
2317 }
2318
2319 /**
2320  * gst_rtsp_connection_close:
2321  * @conn: a #GstRTSPConnection
2322  *
2323  * Close the connected @conn. After this call, the connection is in the same
2324  * state as when it was first created.
2325  * 
2326  * Returns: #GST_RTSP_OK on success.
2327  */
2328 GstRTSPResult
2329 gst_rtsp_connection_close (GstRTSPConnection * conn)
2330 {
2331   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2332
2333   g_free (conn->ip);
2334   conn->ip = NULL;
2335
2336   conn->read_ahead = 0;
2337
2338   g_free (conn->initial_buffer);
2339   conn->initial_buffer = NULL;
2340   conn->initial_buffer_offset = 0;
2341
2342   REMOVE_POLLFD (conn->fdset, &conn->fd0);
2343   REMOVE_POLLFD (conn->fdset, &conn->fd1);
2344   conn->writefd = NULL;
2345   conn->readfd = NULL;
2346   conn->tunneled = FALSE;
2347   conn->tstate = TUNNEL_STATE_NONE;
2348   conn->ctxp = NULL;
2349   g_free (conn->username);
2350   conn->username = NULL;
2351   g_free (conn->passwd);
2352   conn->passwd = NULL;
2353   gst_rtsp_connection_clear_auth_params (conn);
2354   conn->timeout = 60;
2355   conn->cseq = 0;
2356   conn->session_id[0] = '\0';
2357
2358   return GST_RTSP_OK;
2359 }
2360
2361 /**
2362  * gst_rtsp_connection_free:
2363  * @conn: a #GstRTSPConnection
2364  *
2365  * Close and free @conn.
2366  * 
2367  * Returns: #GST_RTSP_OK on success.
2368  */
2369 GstRTSPResult
2370 gst_rtsp_connection_free (GstRTSPConnection * conn)
2371 {
2372   GstRTSPResult res;
2373
2374   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2375
2376   res = gst_rtsp_connection_close (conn);
2377   gst_poll_free (conn->fdset);
2378   g_timer_destroy (conn->timer);
2379   gst_rtsp_url_free (conn->url);
2380   g_free (conn->proxy_host);
2381   g_free (conn);
2382 #ifdef G_OS_WIN32
2383   WSACleanup ();
2384 #endif
2385
2386   return res;
2387 }
2388
2389 /**
2390  * gst_rtsp_connection_poll:
2391  * @conn: a #GstRTSPConnection
2392  * @events: a bitmask of #GstRTSPEvent flags to check
2393  * @revents: location for result flags 
2394  * @timeout: a timeout
2395  *
2396  * Wait up to the specified @timeout for the connection to become available for
2397  * at least one of the operations specified in @events. When the function returns
2398  * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
2399  * @conn.
2400  *
2401  * @timeout can be #NULL, in which case this function might block forever.
2402  *
2403  * This function can be cancelled with gst_rtsp_connection_flush().
2404  * 
2405  * Returns: #GST_RTSP_OK on success.
2406  *
2407  * Since: 0.10.15
2408  */
2409 GstRTSPResult
2410 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
2411     GstRTSPEvent * revents, GTimeVal * timeout)
2412 {
2413   GstClockTime to;
2414   gint retval;
2415
2416   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2417   g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
2418   g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
2419   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2420   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2421
2422   gst_poll_set_controllable (conn->fdset, TRUE);
2423
2424   /* add fd to writer set when asked to */
2425   gst_poll_fd_ctl_write (conn->fdset, conn->writefd,
2426       events & GST_RTSP_EV_WRITE);
2427
2428   /* add fd to reader set when asked to */
2429   gst_poll_fd_ctl_read (conn->fdset, conn->readfd, events & GST_RTSP_EV_READ);
2430
2431   /* configure timeout if any */
2432   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
2433
2434   do {
2435     retval = gst_poll_wait (conn->fdset, to);
2436   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
2437
2438   if (G_UNLIKELY (retval == 0))
2439     goto select_timeout;
2440
2441   if (G_UNLIKELY (retval == -1)) {
2442     if (errno == EBUSY)
2443       goto stopped;
2444     else
2445       goto select_error;
2446   }
2447
2448   *revents = 0;
2449   if (events & GST_RTSP_EV_READ) {
2450     if (gst_poll_fd_can_read (conn->fdset, conn->readfd))
2451       *revents |= GST_RTSP_EV_READ;
2452   }
2453   if (events & GST_RTSP_EV_WRITE) {
2454     if (gst_poll_fd_can_write (conn->fdset, conn->writefd))
2455       *revents |= GST_RTSP_EV_WRITE;
2456   }
2457   return GST_RTSP_OK;
2458
2459   /* ERRORS */
2460 select_timeout:
2461   {
2462     return GST_RTSP_ETIMEOUT;
2463   }
2464 select_error:
2465   {
2466     return GST_RTSP_ESYS;
2467   }
2468 stopped:
2469   {
2470     return GST_RTSP_EINTR;
2471   }
2472 }
2473
2474 /**
2475  * gst_rtsp_connection_next_timeout:
2476  * @conn: a #GstRTSPConnection
2477  * @timeout: a timeout
2478  *
2479  * Calculate the next timeout for @conn, storing the result in @timeout.
2480  *
2481  * Returns: #GST_RTSP_OK.
2482  */
2483 GstRTSPResult
2484 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
2485 {
2486   gdouble elapsed;
2487   glong sec;
2488   gulong usec;
2489
2490   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2491   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
2492
2493   elapsed = g_timer_elapsed (conn->timer, &usec);
2494   if (elapsed >= conn->timeout) {
2495     sec = 0;
2496     usec = 0;
2497   } else {
2498     sec = conn->timeout - elapsed;
2499     if (usec <= G_USEC_PER_SEC)
2500       usec = G_USEC_PER_SEC - usec;
2501     else
2502       usec = 0;
2503   }
2504
2505   timeout->tv_sec = sec;
2506   timeout->tv_usec = usec;
2507
2508   return GST_RTSP_OK;
2509 }
2510
2511 /**
2512  * gst_rtsp_connection_reset_timeout:
2513  * @conn: a #GstRTSPConnection
2514  *
2515  * Reset the timeout of @conn.
2516  *
2517  * Returns: #GST_RTSP_OK.
2518  */
2519 GstRTSPResult
2520 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
2521 {
2522   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2523
2524   g_timer_start (conn->timer);
2525
2526   return GST_RTSP_OK;
2527 }
2528
2529 /**
2530  * gst_rtsp_connection_flush:
2531  * @conn: a #GstRTSPConnection
2532  * @flush: start or stop the flush
2533  *
2534  * Start or stop the flushing action on @conn. When flushing, all current
2535  * and future actions on @conn will return #GST_RTSP_EINTR until the connection
2536  * is set to non-flushing mode again.
2537  * 
2538  * Returns: #GST_RTSP_OK.
2539  */
2540 GstRTSPResult
2541 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
2542 {
2543   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2544
2545   gst_poll_set_flushing (conn->fdset, flush);
2546
2547   return GST_RTSP_OK;
2548 }
2549
2550 /**
2551  * gst_rtsp_connection_set_proxy:
2552  * @conn: a #GstRTSPConnection
2553  * @host: the proxy host
2554  * @port: the proxy port
2555  *
2556  * Set the proxy host and port.
2557  * 
2558  * Returns: #GST_RTSP_OK.
2559  *
2560  * Since: 0.10.23
2561  */
2562 GstRTSPResult
2563 gst_rtsp_connection_set_proxy (GstRTSPConnection * conn,
2564     const gchar * host, guint port)
2565 {
2566   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2567
2568   g_free (conn->proxy_host);
2569   conn->proxy_host = g_strdup (host);
2570   conn->proxy_port = port;
2571
2572   return GST_RTSP_OK;
2573 }
2574
2575 /**
2576  * gst_rtsp_connection_set_auth:
2577  * @conn: a #GstRTSPConnection
2578  * @method: authentication method
2579  * @user: the user
2580  * @pass: the password
2581  *
2582  * Configure @conn for authentication mode @method with @user and @pass as the
2583  * user and password respectively.
2584  * 
2585  * Returns: #GST_RTSP_OK.
2586  */
2587 GstRTSPResult
2588 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
2589     GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
2590 {
2591   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2592
2593   if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
2594           || g_strrstr (user, ":") != NULL))
2595     return GST_RTSP_EINVAL;
2596
2597   /* Make sure the username and passwd are being set for authentication */
2598   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
2599     return GST_RTSP_EINVAL;
2600
2601   /* ":" chars are not allowed in usernames for basic auth */
2602   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
2603     return GST_RTSP_EINVAL;
2604
2605   g_free (conn->username);
2606   g_free (conn->passwd);
2607
2608   conn->auth_method = method;
2609   conn->username = g_strdup (user);
2610   conn->passwd = g_strdup (pass);
2611
2612   return GST_RTSP_OK;
2613 }
2614
2615 /**
2616  * str_case_hash:
2617  * @key: ASCII string to hash
2618  *
2619  * Hashes @key in a case-insensitive manner.
2620  *
2621  * Returns: the hash code.
2622  **/
2623 static guint
2624 str_case_hash (gconstpointer key)
2625 {
2626   const char *p = key;
2627   guint h = g_ascii_toupper (*p);
2628
2629   if (h)
2630     for (p += 1; *p != '\0'; p++)
2631       h = (h << 5) - h + g_ascii_toupper (*p);
2632
2633   return h;
2634 }
2635
2636 /**
2637  * str_case_equal:
2638  * @v1: an ASCII string
2639  * @v2: another ASCII string
2640  *
2641  * Compares @v1 and @v2 in a case-insensitive manner
2642  *
2643  * Returns: %TRUE if they are equal (modulo case)
2644  **/
2645 static gboolean
2646 str_case_equal (gconstpointer v1, gconstpointer v2)
2647 {
2648   const char *string1 = v1;
2649   const char *string2 = v2;
2650
2651   return g_ascii_strcasecmp (string1, string2) == 0;
2652 }
2653
2654 /**
2655  * gst_rtsp_connection_set_auth_param:
2656  * @conn: a #GstRTSPConnection
2657  * @param: authentication directive
2658  * @value: value
2659  *
2660  * Setup @conn with authentication directives. This is not necesary for
2661  * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
2662  * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
2663  * in the WWW-Authenticate response header and can include realm, domain,
2664  * nonce, opaque, stale, algorithm, qop as per RFC2617.
2665  * 
2666  * Since: 0.10.20
2667  */
2668 void
2669 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
2670     const gchar * param, const gchar * value)
2671 {
2672   g_return_if_fail (conn != NULL);
2673   g_return_if_fail (param != NULL);
2674
2675   if (conn->auth_params == NULL) {
2676     conn->auth_params =
2677         g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
2678   }
2679   g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
2680 }
2681
2682 /**
2683  * gst_rtsp_connection_clear_auth_params:
2684  * @conn: a #GstRTSPConnection
2685  *
2686  * Clear the list of authentication directives stored in @conn.
2687  *
2688  * Since: 0.10.20
2689  */
2690 void
2691 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
2692 {
2693   g_return_if_fail (conn != NULL);
2694
2695   if (conn->auth_params != NULL) {
2696     g_hash_table_destroy (conn->auth_params);
2697     conn->auth_params = NULL;
2698   }
2699 }
2700
2701 static GstRTSPResult
2702 set_qos_dscp (gint fd, guint qos_dscp)
2703 {
2704   union gst_sockaddr sa;
2705   socklen_t slen = sizeof (sa);
2706   gint af;
2707   gint tos;
2708
2709   if (fd == -1)
2710     return GST_RTSP_OK;
2711
2712   if (getsockname (fd, &sa.sa, &slen) < 0)
2713     goto no_getsockname;
2714
2715   af = sa.sa.sa_family;
2716
2717   /* if this is an IPv4-mapped address then do IPv4 QoS */
2718   if (af == AF_INET6) {
2719     if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
2720       af = AF_INET;
2721   }
2722
2723   /* extract and shift 6 bits of the DSCP */
2724   tos = (qos_dscp & 0x3f) << 2;
2725
2726   switch (af) {
2727     case AF_INET:
2728       if (SETSOCKOPT (fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
2729         goto no_setsockopt;
2730       break;
2731     case AF_INET6:
2732 #ifdef IPV6_TCLASS
2733       if (SETSOCKOPT (fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof (tos)) < 0)
2734         goto no_setsockopt;
2735       break;
2736 #endif
2737     default:
2738       goto wrong_family;
2739   }
2740
2741   return GST_RTSP_OK;
2742
2743   /* ERRORS */
2744 no_getsockname:
2745 no_setsockopt:
2746   {
2747     return GST_RTSP_ESYS;
2748   }
2749
2750 wrong_family:
2751   {
2752     return GST_RTSP_ERROR;
2753   }
2754 }
2755
2756 /**
2757  * gst_rtsp_connection_set_qos_dscp:
2758  * @conn: a #GstRTSPConnection
2759  * @qos_dscp: DSCP value
2760  *
2761  * Configure @conn to use the specified DSCP value.
2762  *
2763  * Returns: #GST_RTSP_OK on success.
2764  *
2765  * Since: 0.10.20
2766  */
2767 GstRTSPResult
2768 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
2769 {
2770   GstRTSPResult res;
2771
2772   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2773   g_return_val_if_fail (conn->readfd != NULL, GST_RTSP_EINVAL);
2774   g_return_val_if_fail (conn->writefd != NULL, GST_RTSP_EINVAL);
2775
2776   res = set_qos_dscp (conn->fd0.fd, qos_dscp);
2777   if (res == GST_RTSP_OK)
2778     res = set_qos_dscp (conn->fd1.fd, qos_dscp);
2779
2780   return res;
2781 }
2782
2783
2784 /**
2785  * gst_rtsp_connection_get_url:
2786  * @conn: a #GstRTSPConnection
2787  *
2788  * Retrieve the URL of the other end of @conn.
2789  *
2790  * Returns: The URL. This value remains valid until the
2791  * connection is freed.
2792  *
2793  * Since: 0.10.23
2794  */
2795 GstRTSPUrl *
2796 gst_rtsp_connection_get_url (const GstRTSPConnection * conn)
2797 {
2798   g_return_val_if_fail (conn != NULL, NULL);
2799
2800   return conn->url;
2801 }
2802
2803 /**
2804  * gst_rtsp_connection_get_ip:
2805  * @conn: a #GstRTSPConnection
2806  *
2807  * Retrieve the IP address of the other end of @conn.
2808  *
2809  * Returns: The IP address as a string. this value remains valid until the
2810  * connection is closed.
2811  *
2812  * Since: 0.10.20
2813  */
2814 const gchar *
2815 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
2816 {
2817   g_return_val_if_fail (conn != NULL, NULL);
2818
2819   return conn->ip;
2820 }
2821
2822 /**
2823  * gst_rtsp_connection_set_ip:
2824  * @conn: a #GstRTSPConnection
2825  * @ip: an ip address
2826  *
2827  * Set the IP address of the server.
2828  *
2829  * Since: 0.10.23
2830  */
2831 void
2832 gst_rtsp_connection_set_ip (GstRTSPConnection * conn, const gchar * ip)
2833 {
2834   g_return_if_fail (conn != NULL);
2835
2836   g_free (conn->ip);
2837   conn->ip = g_strdup (ip);
2838 }
2839
2840 /**
2841  * gst_rtsp_connection_get_readfd:
2842  * @conn: a #GstRTSPConnection
2843  *
2844  * Get the file descriptor for reading.
2845  *
2846  * Returns: the file descriptor used for reading or -1 on error. The file
2847  * descriptor remains valid until the connection is closed.
2848  *
2849  * Since: 0.10.23
2850  */
2851 gint
2852 gst_rtsp_connection_get_readfd (const GstRTSPConnection * conn)
2853 {
2854   g_return_val_if_fail (conn != NULL, -1);
2855   g_return_val_if_fail (conn->readfd != NULL, -1);
2856
2857   return conn->readfd->fd;
2858 }
2859
2860 /**
2861  * gst_rtsp_connection_get_writefd:
2862  * @conn: a #GstRTSPConnection
2863  *
2864  * Get the file descriptor for writing.
2865  *
2866  * Returns: the file descriptor used for writing or -1 on error. The file
2867  * descriptor remains valid until the connection is closed.
2868  *
2869  * Since: 0.10.23
2870  */
2871 gint
2872 gst_rtsp_connection_get_writefd (const GstRTSPConnection * conn)
2873 {
2874   g_return_val_if_fail (conn != NULL, -1);
2875   g_return_val_if_fail (conn->writefd != NULL, -1);
2876
2877   return conn->writefd->fd;
2878 }
2879
2880 /**
2881  * gst_rtsp_connection_set_http_mode:
2882  * @conn: a #GstRTSPConnection
2883  * @enable: %TRUE to enable manual HTTP mode
2884  *
2885  * By setting the HTTP mode to %TRUE the message parsing will support HTTP
2886  * messages in addition to the RTSP messages. It will also disable the
2887  * automatic handling of setting up an HTTP tunnel.
2888  *
2889  * Since: 0.10.25
2890  */
2891 void
2892 gst_rtsp_connection_set_http_mode (GstRTSPConnection * conn, gboolean enable)
2893 {
2894   g_return_if_fail (conn != NULL);
2895
2896   conn->manual_http = enable;
2897 }
2898
2899 /**
2900  * gst_rtsp_connection_set_tunneled:
2901  * @conn: a #GstRTSPConnection
2902  * @tunneled: the new state
2903  *
2904  * Set the HTTP tunneling state of the connection. This must be configured before
2905  * the @conn is connected.
2906  *
2907  * Since: 0.10.23
2908  */
2909 void
2910 gst_rtsp_connection_set_tunneled (GstRTSPConnection * conn, gboolean tunneled)
2911 {
2912   g_return_if_fail (conn != NULL);
2913   g_return_if_fail (conn->readfd == NULL);
2914   g_return_if_fail (conn->writefd == NULL);
2915
2916   conn->tunneled = tunneled;
2917 }
2918
2919 /**
2920  * gst_rtsp_connection_is_tunneled:
2921  * @conn: a #GstRTSPConnection
2922  *
2923  * Get the tunneling state of the connection. 
2924  *
2925  * Returns: if @conn is using HTTP tunneling.
2926  *
2927  * Since: 0.10.23
2928  */
2929 gboolean
2930 gst_rtsp_connection_is_tunneled (const GstRTSPConnection * conn)
2931 {
2932   g_return_val_if_fail (conn != NULL, FALSE);
2933
2934   return conn->tunneled;
2935 }
2936
2937 /**
2938  * gst_rtsp_connection_get_tunnelid:
2939  * @conn: a #GstRTSPConnection
2940  *
2941  * Get the tunnel session id the connection. 
2942  *
2943  * Returns: returns a non-empty string if @conn is being tunneled over HTTP.
2944  *
2945  * Since: 0.10.23
2946  */
2947 const gchar *
2948 gst_rtsp_connection_get_tunnelid (const GstRTSPConnection * conn)
2949 {
2950   g_return_val_if_fail (conn != NULL, NULL);
2951
2952   if (!conn->tunneled)
2953     return NULL;
2954
2955   return conn->tunnelid;
2956 }
2957
2958 /**
2959  * gst_rtsp_connection_do_tunnel:
2960  * @conn: a #GstRTSPConnection
2961  * @conn2: a #GstRTSPConnection or %NULL
2962  *
2963  * If @conn received the first tunnel connection and @conn2 received
2964  * the second tunnel connection, link the two connections together so that
2965  * @conn manages the tunneled connection.
2966  *
2967  * After this call, @conn2 cannot be used anymore and must be freed with
2968  * gst_rtsp_connection_free().
2969  *
2970  * If @conn2 is %NULL then only the base64 decoding context will be setup for
2971  * @conn.
2972  *
2973  * Returns: return GST_RTSP_OK on success.
2974  *
2975  * Since: 0.10.23
2976  */
2977 GstRTSPResult
2978 gst_rtsp_connection_do_tunnel (GstRTSPConnection * conn,
2979     GstRTSPConnection * conn2)
2980 {
2981   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
2982
2983   if (conn2 != NULL) {
2984     g_return_val_if_fail (conn->tstate == TUNNEL_STATE_GET, GST_RTSP_EINVAL);
2985     g_return_val_if_fail (conn2->tstate == TUNNEL_STATE_POST, GST_RTSP_EINVAL);
2986     g_return_val_if_fail (!memcmp (conn2->tunnelid, conn->tunnelid,
2987             TUNNELID_LEN), GST_RTSP_EINVAL);
2988
2989     /* both connections have fd0 as the read/write socket. start by taking the
2990      * socket from conn2 and set it as the socket in conn */
2991     conn->fd1 = conn2->fd0;
2992
2993     /* clean up some of the state of conn2 */
2994     gst_poll_remove_fd (conn2->fdset, &conn2->fd0);
2995     conn2->fd0.fd = -1;
2996     conn2->readfd = conn2->writefd = NULL;
2997
2998     /* We make fd0 the write socket and fd1 the read socket. */
2999     conn->writefd = &conn->fd0;
3000     conn->readfd = &conn->fd1;
3001
3002     conn->tstate = TUNNEL_STATE_COMPLETE;
3003   }
3004
3005   /* we need base64 decoding for the readfd */
3006   conn->ctx.state = 0;
3007   conn->ctx.save = 0;
3008   conn->ctx.cout = 0;
3009   conn->ctx.coutl = 0;
3010   conn->ctxp = &conn->ctx;
3011
3012   return GST_RTSP_OK;
3013 }
3014
3015 #define READ_ERR    (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
3016 #define READ_COND   (G_IO_IN | READ_ERR)
3017 #define WRITE_ERR   (G_IO_HUP | G_IO_ERR | G_IO_NVAL)
3018 #define WRITE_COND  (G_IO_OUT | WRITE_ERR)
3019
3020 typedef struct
3021 {
3022   guint8 *data;
3023   guint size;
3024   guint id;
3025 } GstRTSPRec;
3026
3027 /* async functions */
3028 struct _GstRTSPWatch
3029 {
3030   GSource source;
3031
3032   GstRTSPConnection *conn;
3033
3034   GstRTSPBuilder builder;
3035   GstRTSPMessage message;
3036
3037   GPollFD readfd;
3038   GPollFD writefd;
3039
3040   /* queued message for transmission */
3041   guint id;
3042   GMutex *mutex;
3043   GQueue *messages;
3044   guint8 *write_data;
3045   guint write_off;
3046   guint write_size;
3047   guint write_id;
3048
3049   GstRTSPWatchFuncs funcs;
3050
3051   gpointer user_data;
3052   GDestroyNotify notify;
3053 };
3054
3055 static gboolean
3056 gst_rtsp_source_prepare (GSource * source, gint * timeout)
3057 {
3058   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3059
3060   if (watch->conn->initial_buffer != NULL)
3061     return TRUE;
3062
3063   *timeout = (watch->conn->timeout * 1000);
3064
3065   return FALSE;
3066 }
3067
3068 static gboolean
3069 gst_rtsp_source_check (GSource * source)
3070 {
3071   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3072
3073   if (watch->readfd.revents & READ_COND)
3074     return TRUE;
3075
3076   if (watch->writefd.revents & WRITE_COND)
3077     return TRUE;
3078
3079   return FALSE;
3080 }
3081
3082 static gboolean
3083 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback G_GNUC_UNUSED,
3084     gpointer user_data G_GNUC_UNUSED)
3085 {
3086   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3087   GstRTSPResult res = GST_RTSP_ERROR;
3088   gboolean keep_running = TRUE;
3089
3090   /* first read as much as we can */
3091   if (watch->readfd.revents & READ_COND || watch->conn->initial_buffer != NULL) {
3092     do {
3093       if (watch->readfd.revents & READ_ERR)
3094         goto read_error;
3095
3096       res = build_next (&watch->builder, &watch->message, watch->conn);
3097       if (res == GST_RTSP_EINTR)
3098         break;
3099       else if (G_UNLIKELY (res == GST_RTSP_EEOF)) {
3100         watch->readfd.events = 0;
3101         watch->readfd.revents = 0;
3102         g_source_remove_poll ((GSource *) watch, &watch->readfd);
3103         /* When we are in tunnelled mode, the read socket can be closed and we
3104          * should be prepared for a new POST method to reopen it */
3105         if (watch->conn->tstate == TUNNEL_STATE_COMPLETE) {
3106           /* remove the read connection for the tunnel */
3107           /* we accept a new POST request */
3108           watch->conn->tstate = TUNNEL_STATE_GET;
3109           /* and signal that we lost our tunnel */
3110           if (watch->funcs.tunnel_lost)
3111             res = watch->funcs.tunnel_lost (watch, watch->user_data);
3112           goto read_done;
3113         } else
3114           goto eof;
3115       } else if (G_LIKELY (res == GST_RTSP_OK)) {
3116         if (!watch->conn->manual_http &&
3117             watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3118           if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3119               watch->message.type_data.request.method == GST_RTSP_GET) {
3120             GstRTSPMessage *response;
3121             GstRTSPStatusCode code;
3122
3123             watch->conn->tstate = TUNNEL_STATE_GET;
3124
3125             if (watch->funcs.tunnel_start)
3126               code = watch->funcs.tunnel_start (watch, watch->user_data);
3127             else
3128               code = GST_RTSP_STS_OK;
3129
3130             /* queue the response */
3131             response = gen_tunnel_reply (watch->conn, code, &watch->message);
3132             gst_rtsp_watch_send_message (watch, response, NULL);
3133             gst_rtsp_message_free (response);
3134             goto read_done;
3135           } else if (watch->conn->tstate == TUNNEL_STATE_NONE &&
3136               watch->message.type_data.request.method == GST_RTSP_POST) {
3137             watch->conn->tstate = TUNNEL_STATE_POST;
3138
3139             /* in the callback the connection should be tunneled with the
3140              * GET connection */
3141             if (watch->funcs.tunnel_complete)
3142               watch->funcs.tunnel_complete (watch, watch->user_data);
3143             goto read_done;
3144           }
3145         }
3146       }
3147
3148       if (!watch->conn->manual_http) {
3149         /* if manual HTTP support is not enabled, then restore the message to
3150          * what it would have looked like without the support for parsing HTTP
3151          * messages being present */
3152         if (watch->message.type == GST_RTSP_MESSAGE_HTTP_REQUEST) {
3153           watch->message.type = GST_RTSP_MESSAGE_REQUEST;
3154           watch->message.type_data.request.method = GST_RTSP_INVALID;
3155           if (watch->message.type_data.request.version != GST_RTSP_VERSION_1_0)
3156             watch->message.type_data.request.version = GST_RTSP_VERSION_INVALID;
3157           res = GST_RTSP_EPARSE;
3158         } else if (watch->message.type == GST_RTSP_MESSAGE_HTTP_RESPONSE) {
3159           watch->message.type = GST_RTSP_MESSAGE_RESPONSE;
3160           if (watch->message.type_data.response.version != GST_RTSP_VERSION_1_0)
3161             watch->message.type_data.response.version =
3162                 GST_RTSP_VERSION_INVALID;
3163           res = GST_RTSP_EPARSE;
3164         }
3165       }
3166
3167       if (G_LIKELY (res == GST_RTSP_OK)) {
3168         if (watch->funcs.message_received)
3169           watch->funcs.message_received (watch, &watch->message,
3170               watch->user_data);
3171       } else {
3172         goto read_error;
3173       }
3174
3175     read_done:
3176       gst_rtsp_message_unset (&watch->message);
3177       build_reset (&watch->builder);
3178     } while (FALSE);
3179   }
3180
3181   if (watch->writefd.revents & WRITE_COND) {
3182     if (watch->writefd.revents & WRITE_ERR)
3183       goto write_error;
3184
3185     g_mutex_lock (watch->mutex);
3186     do {
3187       if (watch->write_data == NULL) {
3188         GstRTSPRec *rec;
3189
3190         /* get a new message from the queue */
3191         rec = g_queue_pop_tail (watch->messages);
3192         if (rec == NULL)
3193           break;
3194
3195         watch->write_off = 0;
3196         watch->write_data = rec->data;
3197         watch->write_size = rec->size;
3198         watch->write_id = rec->id;
3199
3200         g_slice_free (GstRTSPRec, rec);
3201       }
3202
3203       res = write_bytes (watch->writefd.fd, watch->write_data,
3204           &watch->write_off, watch->write_size);
3205       g_mutex_unlock (watch->mutex);
3206
3207       if (res == GST_RTSP_EINTR)
3208         goto write_blocked;
3209       else if (G_LIKELY (res == GST_RTSP_OK)) {
3210         if (watch->funcs.message_sent)
3211           watch->funcs.message_sent (watch, watch->write_id, watch->user_data);
3212       } else {
3213         goto write_error;
3214       }
3215       g_mutex_lock (watch->mutex);
3216
3217       g_free (watch->write_data);
3218       watch->write_data = NULL;
3219     } while (TRUE);
3220
3221     watch->writefd.events = WRITE_ERR;
3222
3223     g_mutex_unlock (watch->mutex);
3224   }
3225
3226 write_blocked:
3227   return keep_running;
3228
3229   /* ERRORS */
3230 eof:
3231   {
3232     if (watch->funcs.closed)
3233       watch->funcs.closed (watch, watch->user_data);
3234
3235     /* always stop when the readfd returns EOF in non-tunneled mode */
3236     return FALSE;
3237   }
3238 read_error:
3239   {
3240     watch->readfd.events = 0;
3241     watch->readfd.revents = 0;
3242     g_source_remove_poll ((GSource *) watch, &watch->readfd);
3243     keep_running = (watch->writefd.events != 0);
3244
3245     if (keep_running) {
3246       if (watch->funcs.error_full)
3247         GST_RTSP_CHECK (watch->funcs.error_full (watch, res, &watch->message,
3248                 0, watch->user_data), error);
3249       else
3250         goto error;
3251     } else
3252       goto eof;
3253   }
3254 write_error:
3255   {
3256     watch->writefd.events = 0;
3257     watch->writefd.revents = 0;
3258     g_source_remove_poll ((GSource *) watch, &watch->writefd);
3259     keep_running = (watch->readfd.events != 0);
3260
3261     if (keep_running) {
3262       if (watch->funcs.error_full)
3263         GST_RTSP_CHECK (watch->funcs.error_full (watch, res, NULL,
3264                 watch->write_id, watch->user_data), error);
3265       else
3266         goto error;
3267     } else
3268       goto eof;
3269   }
3270 error:
3271   {
3272     if (watch->funcs.error)
3273       watch->funcs.error (watch, res, watch->user_data);
3274
3275     return keep_running;
3276   }
3277 }
3278
3279 static void
3280 gst_rtsp_rec_free (gpointer data)
3281 {
3282   GstRTSPRec *rec = data;
3283
3284   g_free (rec->data);
3285   g_slice_free (GstRTSPRec, rec);
3286 }
3287
3288 static void
3289 gst_rtsp_source_finalize (GSource * source)
3290 {
3291   GstRTSPWatch *watch = (GstRTSPWatch *) source;
3292
3293   build_reset (&watch->builder);
3294   gst_rtsp_message_unset (&watch->message);
3295
3296   g_queue_foreach (watch->messages, (GFunc) gst_rtsp_rec_free, NULL);
3297   g_queue_free (watch->messages);
3298   watch->messages = NULL;
3299   g_free (watch->write_data);
3300
3301   g_mutex_free (watch->mutex);
3302
3303   if (watch->notify)
3304     watch->notify (watch->user_data);
3305 }
3306
3307 static GSourceFuncs gst_rtsp_source_funcs = {
3308   gst_rtsp_source_prepare,
3309   gst_rtsp_source_check,
3310   gst_rtsp_source_dispatch,
3311   gst_rtsp_source_finalize,
3312   NULL,
3313   NULL
3314 };
3315
3316 /**
3317  * gst_rtsp_watch_new:
3318  * @conn: a #GstRTSPConnection
3319  * @funcs: watch functions
3320  * @user_data: user data to pass to @funcs
3321  * @notify: notify when @user_data is not referenced anymore
3322  *
3323  * Create a watch object for @conn. The functions provided in @funcs will be
3324  * called with @user_data when activity happened on the watch.
3325  *
3326  * The new watch is usually created so that it can be attached to a
3327  * maincontext with gst_rtsp_watch_attach(). 
3328  *
3329  * @conn must exist for the entire lifetime of the watch.
3330  *
3331  * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
3332  * communication. Free with gst_rtsp_watch_unref () after usage.
3333  *
3334  * Since: 0.10.23
3335  */
3336 GstRTSPWatch *
3337 gst_rtsp_watch_new (GstRTSPConnection * conn,
3338     GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
3339 {
3340   GstRTSPWatch *result;
3341
3342   g_return_val_if_fail (conn != NULL, NULL);
3343   g_return_val_if_fail (funcs != NULL, NULL);
3344   g_return_val_if_fail (conn->readfd != NULL, NULL);
3345   g_return_val_if_fail (conn->writefd != NULL, NULL);
3346
3347   result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
3348       sizeof (GstRTSPWatch));
3349
3350   result->conn = conn;
3351   result->builder.state = STATE_START;
3352
3353   result->mutex = g_mutex_new ();
3354   result->messages = g_queue_new ();
3355
3356   result->readfd.fd = -1;
3357   result->writefd.fd = -1;
3358
3359   gst_rtsp_watch_reset (result);
3360
3361   result->funcs = *funcs;
3362   result->user_data = user_data;
3363   result->notify = notify;
3364
3365   return result;
3366 }
3367
3368 /**
3369  * gst_rtsp_watch_reset:
3370  * @watch: a #GstRTSPWatch
3371  *
3372  * Reset @watch, this is usually called after gst_rtsp_connection_do_tunnel()
3373  * when the file descriptors of the connection might have changed.
3374  *
3375  * Since: 0.10.23
3376  */
3377 void
3378 gst_rtsp_watch_reset (GstRTSPWatch * watch)
3379 {
3380   if (watch->readfd.fd != -1)
3381     g_source_remove_poll ((GSource *) watch, &watch->readfd);
3382   if (watch->writefd.fd != -1)
3383     g_source_remove_poll ((GSource *) watch, &watch->writefd);
3384
3385   watch->readfd.fd = watch->conn->readfd->fd;
3386   watch->readfd.events = READ_COND;
3387   watch->readfd.revents = 0;
3388
3389   watch->writefd.fd = watch->conn->writefd->fd;
3390   watch->writefd.events = WRITE_ERR;
3391   watch->writefd.revents = 0;
3392
3393   if (watch->readfd.fd != -1)
3394     g_source_add_poll ((GSource *) watch, &watch->readfd);
3395   if (watch->writefd.fd != -1)
3396     g_source_add_poll ((GSource *) watch, &watch->writefd);
3397 }
3398
3399 /**
3400  * gst_rtsp_watch_attach:
3401  * @watch: a #GstRTSPWatch
3402  * @context: a GMainContext (if NULL, the default context will be used)
3403  *
3404  * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
3405  *
3406  * Returns: the ID (greater than 0) for the watch within the GMainContext. 
3407  *
3408  * Since: 0.10.23
3409  */
3410 guint
3411 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
3412 {
3413   g_return_val_if_fail (watch != NULL, 0);
3414
3415   return g_source_attach ((GSource *) watch, context);
3416 }
3417
3418 /**
3419  * gst_rtsp_watch_unref:
3420  * @watch: a #GstRTSPWatch
3421  *
3422  * Decreases the reference count of @watch by one. If the resulting reference
3423  * count is zero the watch and associated memory will be destroyed.
3424  *
3425  * Since: 0.10.23
3426  */
3427 void
3428 gst_rtsp_watch_unref (GstRTSPWatch * watch)
3429 {
3430   g_return_if_fail (watch != NULL);
3431
3432   g_source_unref ((GSource *) watch);
3433 }
3434
3435 /**
3436  * gst_rtsp_watch_write_data:
3437  * @watch: a #GstRTSPWatch
3438  * @data: the data to queue
3439  * @size: the size of @data
3440  * @id: location for a message ID or %NULL
3441  *
3442  * Write @data using the connection of the @watch. If it cannot be sent
3443  * immediately, it will be queued for transmission in @watch. The contents of
3444  * @message will then be serialized and transmitted when the connection of the
3445  * @watch becomes writable. In case the @message is queued, the ID returned in
3446  * @id will be non-zero and used as the ID argument in the message_sent
3447  * callback.
3448  *
3449  * This function will take ownership of @data and g_free() it after use.
3450  *
3451  * Returns: #GST_RTSP_OK on success.
3452  *
3453  * Since: 0.10.25
3454  */
3455 GstRTSPResult
3456 gst_rtsp_watch_write_data (GstRTSPWatch * watch, const guint8 * data,
3457     guint size, guint * id)
3458 {
3459   GstRTSPResult res;
3460   GstRTSPRec *rec;
3461   guint off = 0;
3462   GMainContext *context = NULL;
3463
3464   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3465   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3466   g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3467
3468   g_mutex_lock (watch->mutex);
3469
3470   /* try to send the message synchronously first */
3471   if (watch->messages->length == 0) {
3472     res = write_bytes (watch->writefd.fd, data, &off, size);
3473     if (res != GST_RTSP_EINTR) {
3474       if (id != NULL)
3475         *id = 0;
3476       g_free ((gpointer) data);
3477       goto done;
3478     }
3479   }
3480
3481   /* make a record with the data and id for sending async */
3482   rec = g_slice_new (GstRTSPRec);
3483   if (off == 0) {
3484     rec->data = (guint8 *) data;
3485     rec->size = size;
3486   } else {
3487     rec->data = g_memdup (data + off, size - off);
3488     rec->size = size - off;
3489     g_free ((gpointer) data);
3490   }
3491
3492   do {
3493     /* make sure rec->id is never 0 */
3494     rec->id = ++watch->id;
3495   } while (G_UNLIKELY (rec->id == 0));
3496
3497   /* add the record to a queue. FIXME we would like to have an upper limit here */
3498   g_queue_push_head (watch->messages, rec);
3499
3500   /* make sure the main context will now also check for writability on the
3501    * socket */
3502   if (watch->writefd.events != WRITE_COND) {
3503     watch->writefd.events = WRITE_COND;
3504     context = ((GSource *) watch)->context;
3505   }
3506
3507   if (id != NULL)
3508     *id = rec->id;
3509   res = GST_RTSP_OK;
3510
3511 done:
3512   g_mutex_unlock (watch->mutex);
3513
3514   if (context)
3515     g_main_context_wakeup (context);
3516
3517   return res;
3518 }
3519
3520 /**
3521  * gst_rtsp_watch_send_message:
3522  * @watch: a #GstRTSPWatch
3523  * @message: a #GstRTSPMessage
3524  * @id: location for a message ID or %NULL
3525  *
3526  * Send a @message using the connection of the @watch. If it cannot be sent
3527  * immediately, it will be queued for transmission in @watch. The contents of
3528  * @message will then be serialized and transmitted when the connection of the
3529  * @watch becomes writable. In case the @message is queued, the ID returned in
3530  * @id will be non-zero and used as the ID argument in the message_sent
3531  * callback.
3532  *
3533  * Returns: #GST_RTSP_OK on success.
3534  *
3535  * Since: 0.10.25
3536  */
3537 GstRTSPResult
3538 gst_rtsp_watch_send_message (GstRTSPWatch * watch, GstRTSPMessage * message,
3539     guint * id)
3540 {
3541   GString *str;
3542   guint size;
3543
3544   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3545   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3546
3547   /* make a record with the message as a string and id */
3548   str = message_to_string (watch->conn, message);
3549   size = str->len;
3550   return gst_rtsp_watch_write_data (watch,
3551       (guint8 *) g_string_free (str, FALSE), size, id);
3552 }
3553
3554 /**
3555  * gst_rtsp_watch_queue_data:
3556  * @watch: a #GstRTSPWatch
3557  * @data: the data to queue
3558  * @size: the size of @data
3559  *
3560  * Queue @data for transmission in @watch. It will be transmitted when the
3561  * connection of the @watch becomes writable.
3562  *
3563  * This function will take ownership of @data and g_free() it after use.
3564  *
3565  * The return value of this function will be used as the id argument in the
3566  * message_sent callback.
3567  *
3568  * Deprecated: Use gst_rtsp_watch_write_data()
3569  *
3570  * Returns: an id.
3571  *
3572  * Since: 0.10.24
3573  */
3574 #ifndef GST_REMOVE_DEPRECATED
3575 #ifdef GST_DISABLE_DEPRECATED
3576 guint
3577 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3578     guint size);
3579 #endif
3580 guint
3581 gst_rtsp_watch_queue_data (GstRTSPWatch * watch, const guint8 * data,
3582     guint size)
3583 {
3584   GstRTSPRec *rec;
3585   GMainContext *context = NULL;
3586
3587   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3588   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
3589   g_return_val_if_fail (size != 0, GST_RTSP_EINVAL);
3590
3591   g_mutex_lock (watch->mutex);
3592
3593   /* make a record with the data and id */
3594   rec = g_slice_new (GstRTSPRec);
3595   rec->data = (guint8 *) data;
3596   rec->size = size;
3597   do {
3598     /* make sure rec->id is never 0 */
3599     rec->id = ++watch->id;
3600   } while (G_UNLIKELY (rec->id == 0));
3601
3602   /* add the record to a queue. FIXME we would like to have an upper limit here */
3603   g_queue_push_head (watch->messages, rec);
3604
3605   /* make sure the main context will now also check for writability on the
3606    * socket */
3607   if (watch->writefd.events != WRITE_COND) {
3608     watch->writefd.events = WRITE_COND;
3609     context = ((GSource *) watch)->context;
3610   }
3611   g_mutex_unlock (watch->mutex);
3612
3613   if (context)
3614     g_main_context_wakeup (context);
3615
3616   return rec->id;
3617 }
3618 #endif /* GST_REMOVE_DEPRECATED */
3619
3620 /**
3621  * gst_rtsp_watch_queue_message:
3622  * @watch: a #GstRTSPWatch
3623  * @message: a #GstRTSPMessage
3624  *
3625  * Queue a @message for transmission in @watch. The contents of this
3626  * message will be serialized and transmitted when the connection of the
3627  * @watch becomes writable.
3628  *
3629  * The return value of this function will be used as the id argument in the
3630  * message_sent callback.
3631  *
3632  * Deprecated: Use gst_rtsp_watch_send_message()
3633  *
3634  * Returns: an id.
3635  *
3636  * Since: 0.10.23
3637  */
3638 #ifndef GST_REMOVE_DEPRECATED
3639 #ifdef GST_DISABLE_DEPRECATED
3640 guint
3641 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message);
3642 #endif
3643 guint
3644 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
3645 {
3646   GString *str;
3647   guint size;
3648
3649   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
3650   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3651
3652   /* make a record with the message as a string and id */
3653   str = message_to_string (watch->conn, message);
3654   size = str->len;
3655   return gst_rtsp_watch_queue_data (watch,
3656       (guint8 *) g_string_free (str, FALSE), size);
3657 }
3658 #endif /* GST_REMOVE_DEPRECATED */