fbf2db09efa0f2fed1e82462175ad0a37fed4616
[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 #ifdef G_OS_WIN32
99 #define FIONREAD_TYPE gulong
100 #define IOCTL_SOCKET ioctlsocket
101 #define READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
102 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
103 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
104 #define CLOSE_SOCKET(sock) closesocket (sock)
105 #define ERRNO_IS_NOT_EAGAIN (WSAGetLastError () != WSAEWOULDBLOCK)
106 #define ERRNO_IS_NOT_EINTR (WSAGetLastError () != WSAEINTR)
107 /* According to Microsoft's connect() documentation this one returns
108  * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
109 #define ERRNO_IS_NOT_EINPROGRESS (WSAGetLastError () != WSAEWOULDBLOCK)
110 #else
111 #define FIONREAD_TYPE gint
112 #define IOCTL_SOCKET ioctl
113 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
114 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
115 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
116 #define CLOSE_SOCKET(sock) close (sock)
117 #define ERRNO_IS_NOT_EAGAIN (errno != EAGAIN)
118 #define ERRNO_IS_NOT_EINTR (errno != EINTR)
119 #define ERRNO_IS_NOT_EINPROGRESS (errno != EINPROGRESS)
120 #endif
121
122 #ifdef G_OS_WIN32
123 static int
124 inet_aton (const char *c, struct in_addr *paddr)
125 {
126   /* note that inet_addr is deprecated on unix because
127    * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
128    * address. */
129   paddr->s_addr = inet_addr (c);
130
131   if (paddr->s_addr == INADDR_NONE)
132     return 0;
133
134   return 1;
135 }
136 #endif
137
138 /**
139  * gst_rtsp_connection_create:
140  * @url: a #GstRTSPUrl 
141  * @conn: a #GstRTSPConnection
142  *
143  * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
144  * The connection will not yet attempt to connect to @url, use
145  * gst_rtsp_connection_connect().
146  *
147  * Returns: #GST_RTSP_OK when @conn contains a valid connection.
148  */
149 GstRTSPResult
150 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
151 {
152   GstRTSPConnection *newconn;
153
154   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
155
156   newconn = g_new0 (GstRTSPConnection, 1);
157
158   if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
159     goto no_fdset;
160
161   newconn->url = url;
162   newconn->fd.fd = -1;
163   newconn->timer = g_timer_new ();
164
165   newconn->auth_method = GST_RTSP_AUTH_NONE;
166   newconn->username = NULL;
167   newconn->passwd = NULL;
168   newconn->auth_params = NULL;
169
170   *conn = newconn;
171
172   return GST_RTSP_OK;
173
174   /* ERRORS */
175 no_fdset:
176   {
177     g_free (newconn);
178     return GST_RTSP_ESYS;
179   }
180 }
181
182 /**
183  * gst_rtsp_connection_connect:
184  * @conn: a #GstRTSPConnection 
185  * @timeout: a #GTimeVal timeout
186  *
187  * Attempt to connect to the url of @conn made with
188  * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
189  * forever. If @timeout contains a valid timeout, this function will return
190  * #GST_RTSP_ETIMEOUT after the timeout expired.
191  *
192  * This function can be cancelled with gst_rtsp_connection_flush().
193  *
194  * Returns: #GST_RTSP_OK when a connection could be made.
195  */
196 GstRTSPResult
197 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
198 {
199   gint fd;
200   struct sockaddr_in sa_in;
201   struct hostent *hostinfo;
202   const gchar *ip;
203   struct in_addr addr;
204   gint ret;
205   guint16 port;
206   GstRTSPUrl *url;
207   GstClockTime to;
208   gint retval;
209
210 #ifdef G_OS_WIN32
211   unsigned long flags = 1;
212   struct in_addr *addrp;
213 #else
214   char **addrs;
215   gchar ipbuf[INET_ADDRSTRLEN];
216 #endif /* G_OS_WIN32 */
217
218   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
219   g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
220   g_return_val_if_fail (conn->fd.fd < 0, GST_RTSP_EINVAL);
221
222   url = conn->url;
223
224   /* first check if it already is an IP address */
225   if (inet_aton (url->host, &addr)) {
226     ip = url->host;
227   } else {
228     hostinfo = gethostbyname (url->host);
229     if (!hostinfo)
230       goto not_resolved;        /* h_errno set */
231
232     if (hostinfo->h_addrtype != AF_INET)
233       goto not_ip;              /* host not an IP host */
234 #ifdef G_OS_WIN32
235     addrp = (struct in_addr *) hostinfo->h_addr_list[0];
236     /* this is not threadsafe */
237     ip = inet_ntoa (*addrp);
238 #else
239     addrs = hostinfo->h_addr_list;
240     ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
241         sizeof (ipbuf));
242 #endif /* G_OS_WIN32 */
243   }
244
245   /* get the port from the url */
246   gst_rtsp_url_get_port (url, &port);
247
248   memset (&sa_in, 0, sizeof (sa_in));
249   sa_in.sin_family = AF_INET;   /* network socket */
250   sa_in.sin_port = htons (port);        /* on port */
251   sa_in.sin_addr.s_addr = inet_addr (ip);       /* on host ip */
252
253   fd = socket (AF_INET, SOCK_STREAM, 0);
254   if (fd == -1)
255     goto sys_error;
256
257   /* set to non-blocking mode so that we can cancel the connect */
258 #ifndef G_OS_WIN32
259   fcntl (fd, F_SETFL, O_NONBLOCK);
260 #else
261   ioctlsocket (fd, FIONBIO, &flags);
262 #endif /* G_OS_WIN32 */
263
264   /* add the socket to our fdset */
265   conn->fd.fd = fd;
266   gst_poll_add_fd (conn->fdset, &conn->fd);
267
268   /* we are going to connect ASYNC now */
269   ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
270   if (ret == 0)
271     goto done;
272   if (ERRNO_IS_NOT_EINPROGRESS)
273     goto sys_error;
274
275   /* wait for connect to complete up to the specified timeout or until we got
276    * interrupted. */
277   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, TRUE);
278
279   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
280
281   do {
282     retval = gst_poll_wait (conn->fdset, to);
283   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
284
285   if (retval == 0)
286     goto timeout;
287   else if (retval == -1)
288     goto sys_error;
289
290   /* we can still have an error connecting on windows */
291   if (gst_poll_fd_has_error (conn->fdset, &conn->fd))
292     goto sys_error;
293
294   gst_poll_fd_ignored (conn->fdset, &conn->fd);
295
296 done:
297   conn->ip = g_strdup (ip);
298
299   return GST_RTSP_OK;
300
301 sys_error:
302   {
303     GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
304     if (conn->fd.fd >= 0) {
305       GST_DEBUG ("remove fd %d", conn->fd.fd);
306       gst_poll_remove_fd (conn->fdset, &conn->fd);
307       conn->fd.fd = -1;
308     }
309     if (fd >= 0)
310       CLOSE_SOCKET (fd);
311     return GST_RTSP_ESYS;
312   }
313 not_resolved:
314   {
315     GST_ERROR ("could not resolve %s", url->host);
316     return GST_RTSP_ENET;
317   }
318 not_ip:
319   {
320     GST_ERROR ("not an IP address");
321     return GST_RTSP_ENOTIP;
322   }
323 timeout:
324   {
325     GST_ERROR ("timeout");
326     if (conn->fd.fd >= 0) {
327       GST_DEBUG ("remove fd %d", conn->fd.fd);
328       gst_poll_remove_fd (conn->fdset, &conn->fd);
329       conn->fd.fd = -1;
330     }
331     if (fd >= 0)
332       CLOSE_SOCKET (fd);
333     return GST_RTSP_ETIMEOUT;
334   }
335 }
336
337 static void
338 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
339 {
340   static const char hexdigits[] = "0123456789abcdef";
341   int i;
342
343   for (i = 0; i < 16; i++) {
344     string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
345     string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
346   }
347   string[32] = 0;
348 }
349
350 static void
351 auth_digest_compute_hex_urp (const gchar * username,
352     const gchar * realm, const gchar * password, gchar hex_urp[33])
353 {
354   struct MD5Context md5_context;
355   unsigned char digest[16];
356
357   MD5Init (&md5_context);
358   MD5Update (&md5_context, username, strlen (username));
359   MD5Update (&md5_context, ":", 1);
360   MD5Update (&md5_context, realm, strlen (realm));
361   MD5Update (&md5_context, ":", 1);
362   MD5Update (&md5_context, password, strlen (password));
363   MD5Final (digest, &md5_context);
364   md5_digest_to_hex_string (digest, hex_urp);
365 }
366
367 static void
368 auth_digest_compute_response (const gchar * method,
369     const gchar * uri, const gchar * hex_a1, const gchar * nonce,
370     gchar response[33])
371 {
372   char hex_a2[33];
373   struct MD5Context md5_context;
374   unsigned char digest[16];
375
376   /* compute A2 */
377   MD5Init (&md5_context);
378   MD5Update (&md5_context, method, strlen (method));
379   MD5Update (&md5_context, ":", 1);
380   MD5Update (&md5_context, uri, strlen (uri));
381   MD5Final (digest, &md5_context);
382   md5_digest_to_hex_string (digest, hex_a2);
383
384   /* compute KD */
385   MD5Init (&md5_context);
386   MD5Update (&md5_context, hex_a1, strlen (hex_a1));
387   MD5Update (&md5_context, ":", 1);
388   MD5Update (&md5_context, nonce, strlen (nonce));
389   MD5Update (&md5_context, ":", 1);
390
391   MD5Update (&md5_context, hex_a2, 32);
392   MD5Final (digest, &md5_context);
393   md5_digest_to_hex_string (digest, response);
394 }
395
396 static void
397 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
398 {
399   switch (conn->auth_method) {
400     case GST_RTSP_AUTH_BASIC:{
401       gchar *user_pass =
402           g_strdup_printf ("%s:%s", conn->username, conn->passwd);
403       gchar *user_pass64 =
404           gst_rtsp_base64_encode (user_pass, strlen (user_pass));
405       gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
406
407       gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
408           auth_string);
409
410       g_free (user_pass);
411       g_free (user_pass64);
412       break;
413     }
414     case GST_RTSP_AUTH_DIGEST:{
415       gchar response[33], hex_urp[33];
416       gchar *auth_string, *auth_string2;
417       gchar *realm;
418       gchar *nonce;
419       gchar *opaque;
420       const gchar *uri;
421       const gchar *method;
422
423       /* we need to have some params set */
424       if (conn->auth_params == NULL)
425         break;
426
427       /* we need the realm and nonce */
428       realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
429       nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
430       if (realm == NULL || nonce == NULL)
431         break;
432
433       auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
434           hex_urp);
435
436       method = gst_rtsp_method_as_text (message->type_data.request.method);
437       uri = message->type_data.request.uri;
438
439       /* Assume no qop, algorithm=md5, stale=false */
440       /* For algorithm MD5, a1 = urp. */
441       auth_digest_compute_response (method, uri, hex_urp, nonce, response);
442       auth_string = g_strdup_printf ("Digest username=\"%s\", "
443           "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
444           conn->username, realm, nonce, uri, response);
445
446       opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
447       if (opaque) {
448         auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
449             opaque);
450         g_free (auth_string);
451         auth_string = auth_string2;
452       }
453       gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
454           auth_string);
455       break;
456     }
457     default:
458       /* Nothing to do */
459       break;
460   }
461 }
462
463 static void
464 add_date_header (GstRTSPMessage * message)
465 {
466   GTimeVal tv;
467   gchar date_string[100];
468   time_t t;
469
470 #ifdef HAVE_GMTIME_R
471   struct tm tm_;
472 #endif
473
474   g_get_current_time (&tv);
475   t = (time_t) tv.tv_sec;
476
477 #ifdef HAVE_GMTIME_R
478   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
479       gmtime_r (&t, &tm_));
480 #else
481   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
482       gmtime (&t));
483 #endif
484
485   gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
486 }
487
488 /**
489  * gst_rtsp_connection_write:
490  * @conn: a #GstRTSPConnection
491  * @data: the data to write
492  * @size: the size of @data
493  * @timeout: a timeout value or #NULL
494  *
495  * Attempt to write @size bytes of @data to the connected @conn, blocking up to
496  * the specified @timeout. @timeout can be #NULL, in which case this function
497  * might block forever.
498  * 
499  * This function can be cancelled with gst_rtsp_connection_flush().
500  *
501  * Returns: #GST_RTSP_OK on success.
502  */
503 GstRTSPResult
504 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
505     guint size, GTimeVal * timeout)
506 {
507   guint towrite;
508   gint retval;
509   GstClockTime to;
510
511   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
512   g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
513   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
514
515   gst_poll_set_controllable (conn->fdset, TRUE);
516   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, TRUE);
517   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, FALSE);
518   /* clear all previous poll results */
519   gst_poll_fd_ignored (conn->fdset, &conn->fd);
520
521   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
522
523   towrite = size;
524
525   while (towrite > 0) {
526     gint written;
527
528     do {
529       retval = gst_poll_wait (conn->fdset, to);
530     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
531
532     if (retval == 0)
533       goto timeout;
534
535     if (retval == -1) {
536       if (errno == EBUSY)
537         goto stopped;
538       else
539         goto select_error;
540     }
541
542     /* now we can write */
543     written = WRITE_SOCKET (conn->fd.fd, data, towrite);
544     if (written < 0) {
545       if (ERRNO_IS_NOT_EAGAIN && ERRNO_IS_NOT_EINTR)
546         goto write_error;
547     } else {
548       towrite -= written;
549       data += written;
550     }
551   }
552   return GST_RTSP_OK;
553
554   /* ERRORS */
555 timeout:
556   {
557     return GST_RTSP_ETIMEOUT;
558   }
559 select_error:
560   {
561     return GST_RTSP_ESYS;
562   }
563 stopped:
564   {
565     return GST_RTSP_EINTR;
566   }
567 write_error:
568   {
569     return GST_RTSP_ESYS;
570   }
571 }
572
573 /**
574  * gst_rtsp_connection_send:
575  * @conn: a #GstRTSPConnection
576  * @message: the message to send
577  * @timeout: a timeout value or #NULL
578  *
579  * Attempt to send @message to the connected @conn, blocking up to
580  * the specified @timeout. @timeout can be #NULL, in which case this function
581  * might block forever.
582  * 
583  * This function can be cancelled with gst_rtsp_connection_flush().
584  *
585  * Returns: #GST_RTSP_OK on success.
586  */
587 GstRTSPResult
588 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
589     GTimeVal * timeout)
590 {
591   GString *str = NULL;
592   GstRTSPResult res;
593
594 #ifdef G_OS_WIN32
595   WSADATA w;
596   int error;
597 #endif
598
599   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
600   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
601
602 #ifdef G_OS_WIN32
603   error = WSAStartup (0x0202, &w);
604
605   if (error)
606     goto startup_error;
607
608   if (w.wVersion != 0x0202)
609     goto version_error;
610 #endif
611
612   str = g_string_new ("");
613
614   switch (message->type) {
615     case GST_RTSP_MESSAGE_REQUEST:
616       /* create request string, add CSeq */
617       g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
618           "CSeq: %d\r\n",
619           gst_rtsp_method_as_text (message->type_data.request.method),
620           message->type_data.request.uri, conn->cseq++);
621       /* add session id if we have one */
622       if (conn->session_id[0] != '\0') {
623         gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
624             conn->session_id);
625       }
626       /* add any authentication headers */
627       add_auth_header (conn, message);
628       break;
629     case GST_RTSP_MESSAGE_RESPONSE:
630       /* create response string */
631       g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
632           message->type_data.response.code, message->type_data.response.reason);
633       break;
634     case GST_RTSP_MESSAGE_DATA:
635     {
636       guint8 data_header[4];
637
638       /* prepare data header */
639       data_header[0] = '$';
640       data_header[1] = message->type_data.data.channel;
641       data_header[2] = (message->body_size >> 8) & 0xff;
642       data_header[3] = message->body_size & 0xff;
643
644       /* create string with header and data */
645       str = g_string_append_len (str, (gchar *) data_header, 4);
646       str =
647           g_string_append_len (str, (gchar *) message->body,
648           message->body_size);
649       break;
650     }
651     default:
652       g_return_val_if_reached (GST_RTSP_EINVAL);
653       break;
654   }
655
656   /* append headers and body */
657   if (message->type != GST_RTSP_MESSAGE_DATA) {
658     /* add date header */
659     add_date_header (message);
660
661     /* append headers */
662     gst_rtsp_message_append_headers (message, str);
663
664     /* append Content-Length and body if needed */
665     if (message->body != NULL && message->body_size > 0) {
666       gchar *len;
667
668       len = g_strdup_printf ("%d", message->body_size);
669       g_string_append_printf (str, "%s: %s\r\n",
670           gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
671       g_free (len);
672       /* header ends here */
673       g_string_append (str, "\r\n");
674       str =
675           g_string_append_len (str, (gchar *) message->body,
676           message->body_size);
677     } else {
678       /* just end headers */
679       g_string_append (str, "\r\n");
680     }
681   }
682
683   /* write request */
684   res =
685       gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len, timeout);
686
687   g_string_free (str, TRUE);
688
689   return res;
690
691 #ifdef G_OS_WIN32
692 startup_error:
693   {
694     g_warning ("Error %d on WSAStartup", error);
695     return GST_RTSP_EWSASTART;
696   }
697 version_error:
698   {
699     g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
700         w.wVersion);
701     WSACleanup ();
702     return GST_RTSP_EWSAVERSION;
703   }
704 #endif
705 }
706
707 static GstRTSPResult
708 read_line (gint fd, gchar * buffer, guint size)
709 {
710   guint idx;
711   gchar c;
712   gint r;
713
714   idx = 0;
715   while (TRUE) {
716     r = READ_SOCKET (fd, &c, 1);
717     if (r == 0) {
718       goto eof;
719     } else if (r < 0) {
720       if (ERRNO_IS_NOT_EAGAIN && ERRNO_IS_NOT_EINTR)
721         goto read_error;
722     } else {
723       if (c == '\n')            /* end on \n */
724         break;
725       if (c == '\r')            /* ignore \r */
726         continue;
727
728       if (idx < size - 1)
729         buffer[idx++] = c;
730     }
731   }
732   buffer[idx] = '\0';
733
734   return GST_RTSP_OK;
735
736 eof:
737   {
738     return GST_RTSP_EEOF;
739   }
740 read_error:
741   {
742     return GST_RTSP_ESYS;
743   }
744 }
745
746 static void
747 read_string (gchar * dest, gint size, gchar ** src)
748 {
749   gint idx;
750
751   idx = 0;
752   /* skip spaces */
753   while (g_ascii_isspace (**src))
754     (*src)++;
755
756   while (!g_ascii_isspace (**src) && **src != '\0') {
757     if (idx < size - 1)
758       dest[idx++] = **src;
759     (*src)++;
760   }
761   if (size > 0)
762     dest[idx] = '\0';
763 }
764
765 static void
766 read_key (gchar * dest, gint size, gchar ** src)
767 {
768   gint idx;
769
770   idx = 0;
771   while (**src != ':' && **src != '\0') {
772     if (idx < size - 1)
773       dest[idx++] = **src;
774     (*src)++;
775   }
776   if (size > 0)
777     dest[idx] = '\0';
778 }
779
780 static GstRTSPResult
781 parse_response_status (gchar * buffer, GstRTSPMessage * msg)
782 {
783   GstRTSPResult res;
784   gchar versionstr[20];
785   gchar codestr[4];
786   gint code;
787   gchar *bptr;
788
789   bptr = buffer;
790
791   read_string (versionstr, sizeof (versionstr), &bptr);
792   read_string (codestr, sizeof (codestr), &bptr);
793   code = atoi (codestr);
794
795   while (g_ascii_isspace (*bptr))
796     bptr++;
797
798   if (strcmp (versionstr, "RTSP/1.0") == 0)
799     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
800         parse_error);
801   else if (strncmp (versionstr, "RTSP/", 5) == 0) {
802     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
803         parse_error);
804     msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
805   } else
806     goto parse_error;
807
808   return GST_RTSP_OK;
809
810 parse_error:
811   {
812     return GST_RTSP_EPARSE;
813   }
814 }
815
816 static GstRTSPResult
817 parse_request_line (gchar * buffer, GstRTSPMessage * msg)
818 {
819   GstRTSPResult res = GST_RTSP_OK;
820   gchar versionstr[20];
821   gchar methodstr[20];
822   gchar urlstr[4096];
823   gchar *bptr;
824   GstRTSPMethod method;
825
826   bptr = buffer;
827
828   read_string (methodstr, sizeof (methodstr), &bptr);
829   method = gst_rtsp_find_method (methodstr);
830
831   read_string (urlstr, sizeof (urlstr), &bptr);
832   if (*urlstr == '\0')
833     res = GST_RTSP_EPARSE;
834
835   read_string (versionstr, sizeof (versionstr), &bptr);
836
837   if (*bptr != '\0')
838     res = GST_RTSP_EPARSE;
839
840   if (strcmp (versionstr, "RTSP/1.0") == 0) {
841     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
842       res = GST_RTSP_EPARSE;
843   } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
844     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
845       res = GST_RTSP_EPARSE;
846     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
847   } else {
848     gst_rtsp_message_init_request (msg, method, urlstr);
849     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
850     res = GST_RTSP_EPARSE;
851   }
852
853   return res;
854 }
855
856 /* parsing lines means reading a Key: Value pair */
857 static GstRTSPResult
858 parse_line (gchar * buffer, GstRTSPMessage * msg)
859 {
860   gchar key[32];
861   gchar *bptr;
862   GstRTSPHeaderField field;
863
864   bptr = buffer;
865
866   /* read key */
867   read_key (key, sizeof (key), &bptr);
868   if (*bptr != ':')
869     goto no_column;
870
871   bptr++;
872
873   field = gst_rtsp_find_header_field (key);
874   if (field != GST_RTSP_HDR_INVALID) {
875     while (g_ascii_isspace (*bptr))
876       bptr++;
877     gst_rtsp_message_add_header (msg, field, bptr);
878   }
879
880   return GST_RTSP_OK;
881
882 no_column:
883   {
884     return GST_RTSP_EPARSE;
885   }
886 }
887
888 /**
889  * gst_rtsp_connection_read_internal:
890  * @conn: a #GstRTSPConnection
891  * @data: the data to read
892  * @size: the size of @data
893  * @timeout: a timeout value or #NULL
894  * @allow_interrupt: can the pending read be interrupted
895  *
896  * Attempt to read @size bytes into @data from the connected @conn, blocking up to
897  * the specified @timeout. @timeout can be #NULL, in which case this function
898  * might block forever.
899  * 
900  * This function can be cancelled with gst_rtsp_connection_flush() only if
901  * @allow_interrupt is set.
902  *
903  * Returns: #GST_RTSP_OK on success.
904  */
905 static GstRTSPResult
906 gst_rtsp_connection_read_internal (GstRTSPConnection * conn, guint8 * data,
907     guint size, GTimeVal * timeout, gboolean allow_interrupt)
908 {
909   guint toread;
910   gint retval;
911   GstClockTime to;
912   FIONREAD_TYPE avail;
913
914   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
915   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
916   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
917
918   if (size == 0)
919     return GST_RTSP_OK;
920
921   toread = size;
922
923   /* configure timeout if any */
924   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
925
926   /* if the call fails, just go in the select.. it should not fail. Else if
927    * there is enough data to read, skip the select call al together.*/
928   if (IOCTL_SOCKET (conn->fd.fd, FIONREAD, &avail) < 0)
929     avail = 0;
930   else if (avail >= toread)
931     goto do_read;
932
933   gst_poll_set_controllable (conn->fdset, allow_interrupt);
934   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, FALSE);
935   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, TRUE);
936
937   while (toread > 0) {
938     gint bytes;
939
940     do {
941       retval = gst_poll_wait (conn->fdset, to);
942     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
943
944     if (retval == -1) {
945       if (errno == EBUSY)
946         goto stopped;
947       else
948         goto select_error;
949     }
950
951     /* check for timeout */
952     if (retval == 0)
953       goto select_timeout;
954
955   do_read:
956     /* if we get here there is activity on the real fd since the select
957      * completed and the control socket was not readable. */
958     bytes = READ_SOCKET (conn->fd.fd, data, toread);
959     if (bytes == 0) {
960       goto eof;
961     } else if (bytes < 0) {
962       if (ERRNO_IS_NOT_EAGAIN && ERRNO_IS_NOT_EINTR)
963         goto read_error;
964     } else {
965       toread -= bytes;
966       data += bytes;
967     }
968   }
969   return GST_RTSP_OK;
970
971   /* ERRORS */
972 select_error:
973   {
974     return GST_RTSP_ESYS;
975   }
976 select_timeout:
977   {
978     return GST_RTSP_ETIMEOUT;
979   }
980 stopped:
981   {
982     return GST_RTSP_EINTR;
983   }
984 eof:
985   {
986     return GST_RTSP_EEOF;
987   }
988 read_error:
989   {
990     return GST_RTSP_ESYS;
991   }
992 }
993
994 /**
995  * gst_rtsp_connection_read:
996  * @conn: a #GstRTSPConnection
997  * @data: the data to read
998  * @size: the size of @data
999  * @timeout: a timeout value or #NULL
1000  *
1001  * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1002  * the specified @timeout. @timeout can be #NULL, in which case this function
1003  * might block forever.
1004  *
1005  * This function can be cancelled with gst_rtsp_connection_flush().
1006  *
1007  * Returns: #GST_RTSP_OK on success.
1008  */
1009 GstRTSPResult
1010 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1011     GTimeVal * timeout)
1012 {
1013   return gst_rtsp_connection_read_internal (conn, data, size, timeout, TRUE);
1014 }
1015
1016
1017 static GstRTSPResult
1018 read_body (GstRTSPConnection * conn, glong content_length, GstRTSPMessage * msg,
1019     GTimeVal * timeout)
1020 {
1021   guint8 *body;
1022   GstRTSPResult res;
1023
1024   if (content_length <= 0) {
1025     body = NULL;
1026     content_length = 0;
1027     goto done;
1028   }
1029
1030   body = g_malloc (content_length + 1);
1031   body[content_length] = '\0';
1032
1033   GST_RTSP_CHECK (gst_rtsp_connection_read_internal (conn, body, content_length,
1034           timeout, FALSE), read_error);
1035
1036   content_length += 1;
1037
1038 done:
1039   gst_rtsp_message_take_body (msg, (guint8 *) body, content_length);
1040
1041   return GST_RTSP_OK;
1042
1043   /* ERRORS */
1044 read_error:
1045   {
1046     g_free (body);
1047     return res;
1048   }
1049 }
1050
1051 /**
1052  * gst_rtsp_connection_receive:
1053  * @conn: a #GstRTSPConnection
1054  * @message: the message to read
1055  * @timeout: a timeout value or #NULL
1056  *
1057  * Attempt to read into @message from the connected @conn, blocking up to
1058  * the specified @timeout. @timeout can be #NULL, in which case this function
1059  * might block forever.
1060  * 
1061  * This function can be cancelled with gst_rtsp_connection_flush().
1062  *
1063  * Returns: #GST_RTSP_OK on success.
1064  */
1065 GstRTSPResult
1066 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1067     GTimeVal * timeout)
1068 {
1069   gchar buffer[4096];
1070   gint line;
1071   glong content_length;
1072   GstRTSPResult res;
1073   gboolean need_body;
1074
1075   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1076   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1077
1078   line = 0;
1079
1080   need_body = TRUE;
1081
1082   res = GST_RTSP_OK;
1083   /* parse first line and headers */
1084   while (res == GST_RTSP_OK) {
1085     guint8 c;
1086
1087     /* read first character, this identifies data messages */
1088     /* This is the only read() that we allow to be interrupted */
1089     GST_RTSP_CHECK (gst_rtsp_connection_read_internal (conn, &c, 1, timeout,
1090             TRUE), read_error);
1091
1092     /* check for data packet, first character is $ */
1093     if (c == '$') {
1094       guint16 size;
1095
1096       /* data packets are $<1 byte channel><2 bytes length,BE><data bytes> */
1097
1098       /* read channel, which is the next char */
1099       GST_RTSP_CHECK (gst_rtsp_connection_read_internal (conn, &c, 1, timeout,
1100               FALSE), read_error);
1101
1102       /* now we create a data message */
1103       gst_rtsp_message_init_data (message, c);
1104
1105       /* next two bytes are the length of the data */
1106       GST_RTSP_CHECK (gst_rtsp_connection_read_internal (conn,
1107               (guint8 *) & size, 2, timeout, FALSE), read_error);
1108
1109       size = GUINT16_FROM_BE (size);
1110
1111       /* and read the body */
1112       res = read_body (conn, size, message, timeout);
1113       need_body = FALSE;
1114       break;
1115     } else {
1116       gint offset = 0;
1117
1118       /* we have a regular response */
1119       if (c != '\r') {
1120         buffer[0] = c;
1121         offset = 1;
1122       }
1123       /* should not happen */
1124       if (c == '\n')
1125         break;
1126
1127       /* read lines */
1128       GST_RTSP_CHECK (read_line (conn->fd.fd, buffer + offset,
1129               sizeof (buffer) - offset), read_error);
1130
1131       if (buffer[0] == '\0')
1132         break;
1133
1134       if (line == 0) {
1135         /* first line, check for response status */
1136         if (g_str_has_prefix (buffer, "RTSP")) {
1137           res = parse_response_status (buffer, message);
1138         } else {
1139           res = parse_request_line (buffer, message);
1140         }
1141       } else {
1142         /* else just parse the line */
1143         parse_line (buffer, message);
1144       }
1145     }
1146     line++;
1147   }
1148
1149   /* read the rest of the body if needed */
1150   if (need_body) {
1151     gchar *session_id;
1152     gchar *hdrval;
1153
1154     /* see if there is a Content-Length header */
1155     if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CONTENT_LENGTH,
1156             &hdrval, 0) == GST_RTSP_OK) {
1157       /* there is, read the body */
1158       content_length = atol (hdrval);
1159       GST_RTSP_CHECK (read_body (conn, content_length, message, timeout),
1160           read_error);
1161     }
1162
1163     /* save session id in the connection for further use */
1164     if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1165             &session_id, 0) == GST_RTSP_OK) {
1166       gint maxlen, i;
1167
1168       /* default session timeout */
1169       conn->timeout = 60;
1170
1171       maxlen = sizeof (conn->session_id) - 1;
1172       /* the sessionid can have attributes marked with ;
1173        * Make sure we strip them */
1174       for (i = 0; session_id[i] != '\0'; i++) {
1175         if (session_id[i] == ';') {
1176           maxlen = i;
1177           /* parse timeout */
1178           do {
1179             i++;
1180           } while (g_ascii_isspace (session_id[i]));
1181           if (g_str_has_prefix (&session_id[i], "timeout=")) {
1182             gint to;
1183
1184             /* if we parsed something valid, configure */
1185             if ((to = atoi (&session_id[i + 9])) > 0)
1186               conn->timeout = to;
1187           }
1188           break;
1189         }
1190       }
1191
1192       /* make sure to not overflow */
1193       strncpy (conn->session_id, session_id, maxlen);
1194       conn->session_id[maxlen] = '\0';
1195     }
1196   }
1197   return res;
1198
1199 read_error:
1200   {
1201     return res;
1202   }
1203 }
1204
1205 /**
1206  * gst_rtsp_connection_close:
1207  * @conn: a #GstRTSPConnection
1208  *
1209  * Close the connected @conn.
1210  * 
1211  * Returns: #GST_RTSP_OK on success.
1212  */
1213 GstRTSPResult
1214 gst_rtsp_connection_close (GstRTSPConnection * conn)
1215 {
1216   gint res;
1217
1218   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1219
1220   g_free (conn->ip);
1221   conn->ip = NULL;
1222
1223   if (conn->fd.fd != -1) {
1224     gst_poll_remove_fd (conn->fdset, &conn->fd);
1225     res = CLOSE_SOCKET (conn->fd.fd);
1226     conn->fd.fd = -1;
1227 #ifdef G_OS_WIN32
1228     WSACleanup ();
1229 #endif
1230     if (res != 0)
1231       goto sys_error;
1232   }
1233
1234   return GST_RTSP_OK;
1235
1236 sys_error:
1237   {
1238     return GST_RTSP_ESYS;
1239   }
1240 }
1241
1242 /**
1243  * gst_rtsp_connection_free:
1244  * @conn: a #GstRTSPConnection
1245  *
1246  * Close and free @conn.
1247  * 
1248  * Returns: #GST_RTSP_OK on success.
1249  */
1250 GstRTSPResult
1251 gst_rtsp_connection_free (GstRTSPConnection * conn)
1252 {
1253   GstRTSPResult res;
1254
1255   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1256
1257   res = gst_rtsp_connection_close (conn);
1258   gst_poll_free (conn->fdset);
1259 #ifdef G_OS_WIN32
1260   WSACleanup ();
1261 #endif
1262   g_timer_destroy (conn->timer);
1263   g_free (conn->username);
1264   g_free (conn->passwd);
1265   gst_rtsp_connection_clear_auth_params (conn);
1266   g_free (conn);
1267
1268   return res;
1269 }
1270
1271 /**
1272  * gst_rtsp_connection_poll:
1273  * @conn: a #GstRTSPConnection
1274  * @events: a bitmask of #GstRTSPEvent flags to check
1275  * @revents: location for result flags 
1276  * @timeout: a timeout
1277  *
1278  * Wait up to the specified @timeout for the connection to become available for
1279  * at least one of the operations specified in @events. When the function returns
1280  * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1281  * @conn.
1282  *
1283  * @timeout can be #NULL, in which case this function might block forever.
1284  *
1285  * This function can be cancelled with gst_rtsp_connection_flush().
1286  * 
1287  * Returns: #GST_RTSP_OK on success.
1288  *
1289  * Since: 0.10.15
1290  */
1291 GstRTSPResult
1292 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1293     GstRTSPEvent * revents, GTimeVal * timeout)
1294 {
1295   GstClockTime to;
1296   gint retval;
1297
1298   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1299   g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
1300   g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
1301   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
1302
1303   gst_poll_set_controllable (conn->fdset, TRUE);
1304
1305   /* add fd to writer set when asked to */
1306   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, events & GST_RTSP_EV_WRITE);
1307
1308   /* add fd to reader set when asked to */
1309   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, events & GST_RTSP_EV_READ);
1310
1311   /* configure timeout if any */
1312   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1313
1314   do {
1315     retval = gst_poll_wait (conn->fdset, to);
1316   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1317
1318   if (retval == 0)
1319     goto select_timeout;
1320
1321   if (retval == -1) {
1322     if (errno == EBUSY)
1323       goto stopped;
1324     else
1325       goto select_error;
1326   }
1327
1328   *revents = 0;
1329   if (events & GST_RTSP_EV_READ) {
1330     if (gst_poll_fd_can_read (conn->fdset, &conn->fd))
1331       *revents |= GST_RTSP_EV_READ;
1332   }
1333   if (events & GST_RTSP_EV_WRITE) {
1334     if (gst_poll_fd_can_write (conn->fdset, &conn->fd))
1335       *revents |= GST_RTSP_EV_WRITE;
1336   }
1337   return GST_RTSP_OK;
1338
1339   /* ERRORS */
1340 select_timeout:
1341   {
1342     return GST_RTSP_ETIMEOUT;
1343   }
1344 select_error:
1345   {
1346     return GST_RTSP_ESYS;
1347   }
1348 stopped:
1349   {
1350     return GST_RTSP_EINTR;
1351   }
1352 }
1353
1354 /**
1355  * gst_rtsp_connection_next_timeout:
1356  * @conn: a #GstRTSPConnection
1357  * @timeout: a timeout
1358  *
1359  * Calculate the next timeout for @conn, storing the result in @timeout.
1360  * 
1361  * Returns: #GST_RTSP_OK.
1362  */
1363 GstRTSPResult
1364 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
1365 {
1366   gdouble elapsed;
1367   glong sec;
1368   gulong usec;
1369
1370   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1371   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
1372
1373   elapsed = g_timer_elapsed (conn->timer, &usec);
1374   if (elapsed >= conn->timeout) {
1375     sec = 0;
1376     usec = 0;
1377   } else {
1378     sec = conn->timeout - elapsed;
1379   }
1380
1381   timeout->tv_sec = sec;
1382   timeout->tv_usec = usec;
1383
1384   return GST_RTSP_OK;
1385 }
1386
1387 /**
1388  * gst_rtsp_connection_reset_timeout:
1389  * @conn: a #GstRTSPConnection
1390  *
1391  * Reset the timeout of @conn.
1392  * 
1393  * Returns: #GST_RTSP_OK.
1394  */
1395 GstRTSPResult
1396 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
1397 {
1398   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1399
1400   g_timer_start (conn->timer);
1401
1402   return GST_RTSP_OK;
1403 }
1404
1405 /**
1406  * gst_rtsp_connection_flush:
1407  * @conn: a #GstRTSPConnection
1408  * @flush: start or stop the flush
1409  *
1410  * Start or stop the flushing action on @conn. When flushing, all current
1411  * and future actions on @conn will return #GST_RTSP_EINTR until the connection
1412  * is set to non-flushing mode again.
1413  * 
1414  * Returns: #GST_RTSP_OK.
1415  */
1416 GstRTSPResult
1417 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
1418 {
1419   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1420
1421   gst_poll_set_flushing (conn->fdset, flush);
1422
1423   return GST_RTSP_OK;
1424 }
1425
1426 /**
1427  * gst_rtsp_connection_set_auth:
1428  * @conn: a #GstRTSPConnection
1429  * @method: authentication method
1430  * @user: the user
1431  * @pass: the password
1432  *
1433  * Configure @conn for authentication mode @method with @user and @pass as the
1434  * user and password respectively.
1435  * 
1436  * Returns: #GST_RTSP_OK.
1437  */
1438 GstRTSPResult
1439 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
1440     GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
1441 {
1442   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1443
1444   if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
1445           || g_strrstr (user, ":") != NULL))
1446     return GST_RTSP_EINVAL;
1447
1448   /* Make sure the username and passwd are being set for authentication */
1449   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
1450     return GST_RTSP_EINVAL;
1451
1452   /* ":" chars are not allowed in usernames for basic auth */
1453   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
1454     return GST_RTSP_EINVAL;
1455
1456   g_free (conn->username);
1457   g_free (conn->passwd);
1458
1459   conn->auth_method = method;
1460   conn->username = g_strdup (user);
1461   conn->passwd = g_strdup (pass);
1462
1463   return GST_RTSP_OK;
1464 }
1465
1466 /**
1467  * str_case_hash:
1468  * @key: ASCII string to hash
1469  *
1470  * Hashes @key in a case-insensitive manner.
1471  *
1472  * Returns: the hash code.
1473  **/
1474 static guint
1475 str_case_hash (gconstpointer key)
1476 {
1477   const char *p = key;
1478   guint h = g_ascii_toupper (*p);
1479
1480   if (h)
1481     for (p += 1; *p != '\0'; p++)
1482       h = (h << 5) - h + g_ascii_toupper (*p);
1483
1484   return h;
1485 }
1486
1487 /**
1488  * str_case_equal:
1489  * @v1: an ASCII string
1490  * @v2: another ASCII string
1491  *
1492  * Compares @v1 and @v2 in a case-insensitive manner
1493  *
1494  * Returns: %TRUE if they are equal (modulo case)
1495  **/
1496 static gboolean
1497 str_case_equal (gconstpointer v1, gconstpointer v2)
1498 {
1499   const char *string1 = v1;
1500   const char *string2 = v2;
1501
1502   return g_ascii_strcasecmp (string1, string2) == 0;
1503 }
1504
1505 /**
1506  * gst_rtsp_connection_set_auth_param:
1507  * @conn: a #GstRTSPConnection
1508  * @param: authentication directive
1509  * @value: value
1510  *
1511  * Setup @conn with authentication directives. This is not necesary for
1512  * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
1513  * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
1514  * in the WWW-Authenticate response header and can include realm, domain,
1515  * nonce, opaque, stale, algorithm, qop as per RFC2617.
1516  * 
1517  * Since: 0.10.20
1518  */
1519 void
1520 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
1521     const gchar * param, const gchar * value)
1522 {
1523   g_return_if_fail (conn != NULL);
1524   g_return_if_fail (param != NULL);
1525
1526   if (conn->auth_params == NULL) {
1527     conn->auth_params =
1528         g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
1529   }
1530   g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
1531 }
1532
1533 /**
1534  * gst_rtsp_connection_clear_auth_params:
1535  * @conn: a #GstRTSPConnection
1536  *
1537  * Clear the list of authentication directives stored in @conn.
1538  *
1539  * Since: 0.10.20
1540  */
1541 void
1542 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
1543 {
1544   g_return_if_fail (conn != NULL);
1545
1546   if (conn->auth_params != NULL) {
1547     g_hash_table_destroy (conn->auth_params);
1548     conn->auth_params = NULL;
1549   }
1550 }
1551
1552 /**
1553  * gst_rtsp_connection_set_qos_dscp:
1554  * @conn: a #GstRTSPConnection
1555  * @qos_dscp: DSCP value
1556  *
1557  * Configure @conn to use the specified DSCP value.
1558  *
1559  * Returns: #GST_RTSP_OK on success.
1560  *
1561  * Since: 0.10.20
1562  */
1563 GstRTSPResult
1564 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
1565 {
1566   struct sockaddr_storage sa_s;
1567   socklen_t sa_sl = sizeof (sa_s);
1568   gint af;
1569   gint tos;
1570
1571   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1572   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
1573
1574   if (getsockname (conn->fd.fd, (struct sockaddr *) &sa_s, &sa_sl) < 0)
1575     goto no_getsockname;
1576
1577   af = sa_s.ss_family;
1578
1579   /* if this is an IPv4-mapped address then do IPv4 QoS */
1580   if (af == AF_INET6) {
1581     struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) &sa_s;
1582
1583     if (IN6_IS_ADDR_V4MAPPED (&saddr6->sin6_addr))
1584       af = AF_INET;
1585   }
1586
1587   /* extract and shift 6 bits of the DSCP */
1588   tos = (qos_dscp & 0x3f) << 2;
1589
1590   switch (af) {
1591     case AF_INET:
1592       if (SETSOCKOPT (conn->fd.fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
1593         goto no_setsockopt;
1594       break;
1595     case AF_INET6:
1596 #ifdef IPV6_TCLASS
1597       if (SETSOCKOPT (conn->fd.fd, IPPROTO_IPV6, IPV6_TCLASS, &tos,
1598               sizeof (tos)) < 0)
1599         goto no_setsockopt;
1600       break;
1601 #endif
1602     default:
1603       goto wrong_family;
1604   }
1605
1606   return GST_RTSP_OK;
1607
1608   /* ERRORS */
1609 no_getsockname:
1610 no_setsockopt:
1611   {
1612     return GST_RTSP_ESYS;
1613   }
1614
1615 wrong_family:
1616   {
1617     return GST_RTSP_ERROR;
1618   }
1619 }
1620
1621 /**
1622  * gst_rtsp_connection_get_ip:
1623  * @conn: a #GstRTSPConnection
1624  *
1625  * Retrieve the IP address of the other end of @conn.
1626  *
1627  * Returns: The IP address as a string. this value remains valid until the
1628  * connection is closed.
1629  *
1630  * Since: 0.10.20
1631  */
1632 const gchar *
1633 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
1634 {
1635   g_return_val_if_fail (conn != NULL, NULL);
1636
1637   return conn->ip;
1638 }