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