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