rtspconnection: Fix warning about using unitialized value.
[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 READ_SOCKET(fd, buf, len) recv (fd, (char *)buf, len, 0)
100 #define WRITE_SOCKET(fd, buf, len) send (fd, (const char *)buf, len, 0)
101 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, (const char *)val, len)
102 #define CLOSE_SOCKET(sock) closesocket (sock)
103 #define ERRNO_IS_EAGAIN (WSAGetLastError () == WSAEWOULDBLOCK)
104 #define ERRNO_IS_EINTR (WSAGetLastError () == WSAEINTR)
105 /* According to Microsoft's connect() documentation this one returns
106  * WSAEWOULDBLOCK and not WSAEINPROGRESS. */
107 #define ERRNO_IS_EINPROGRESS (WSAGetLastError () == WSAEWOULDBLOCK)
108 #else
109 #define READ_SOCKET(fd, buf, len) read (fd, buf, len)
110 #define WRITE_SOCKET(fd, buf, len) write (fd, buf, len)
111 #define SETSOCKOPT(sock, level, name, val, len) setsockopt (sock, level, name, val, len)
112 #define CLOSE_SOCKET(sock) close (sock)
113 #define ERRNO_IS_EAGAIN (errno == EAGAIN)
114 #define ERRNO_IS_EINTR (errno == EINTR)
115 #define ERRNO_IS_EINPROGRESS (errno == EINPROGRESS)
116 #endif
117
118 struct _GstRTSPConnection
119 {
120   /*< private > */
121   /* URL for the connection */
122   GstRTSPUrl *url;
123
124   /* connection state */
125   GstPollFD fd;
126   GstPoll *fdset;
127   gchar *ip;
128
129   /* Session state */
130   gint cseq;                    /* sequence number */
131   gchar session_id[512];        /* session id */
132   gint timeout;                 /* session timeout in seconds */
133   GTimer *timer;                /* timeout timer */
134
135   /* Authentication */
136   GstRTSPAuthMethod auth_method;
137   gchar *username;
138   gchar *passwd;
139   GHashTable *auth_params;
140 };
141
142 #ifdef G_OS_WIN32
143 static int
144 inet_aton (const char *c, struct in_addr *paddr)
145 {
146   /* note that inet_addr is deprecated on unix because
147    * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
148    * address. */
149   paddr->s_addr = inet_addr (c);
150
151   if (paddr->s_addr == INADDR_NONE)
152     return 0;
153
154   return 1;
155 }
156 #endif
157
158 enum
159 {
160   STATE_START = 0,
161   STATE_DATA_HEADER,
162   STATE_DATA_BODY,
163   STATE_READ_LINES,
164   STATE_END,
165   STATE_LAST
166 };
167
168 /* a structure for constructing RTSPMessages */
169 typedef struct
170 {
171   gint state;
172   guint8 buffer[4096];
173   guint offset;
174
175   guint line;
176   guint8 *body_data;
177   glong body_len;
178 } GstRTSPBuilder;
179
180 static void
181 build_reset (GstRTSPBuilder * builder)
182 {
183   g_free (builder->body_data);
184   memset (builder, 0, sizeof (builder));
185 }
186
187 /**
188  * gst_rtsp_connection_create:
189  * @url: a #GstRTSPUrl 
190  * @conn: storage for a #GstRTSPConnection
191  *
192  * Create a newly allocated #GstRTSPConnection from @url and store it in @conn.
193  * The connection will not yet attempt to connect to @url, use
194  * gst_rtsp_connection_connect().
195  *
196  * Returns: #GST_RTSP_OK when @conn contains a valid connection.
197  */
198 GstRTSPResult
199 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
200 {
201   GstRTSPConnection *newconn;
202 #ifdef G_OS_WIN32
203   WSADATA w;
204   int error;
205 #endif
206
207   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
208
209 #ifdef G_OS_WIN32
210   error = WSAStartup (0x0202, &w);
211
212   if (error)
213     goto startup_error;
214
215   if (w.wVersion != 0x0202)
216     goto version_error;
217 #endif
218
219   newconn = g_new0 (GstRTSPConnection, 1);
220
221   if ((newconn->fdset = gst_poll_new (TRUE)) == NULL)
222     goto no_fdset;
223
224   newconn->url = url;
225   newconn->fd.fd = -1;
226   newconn->timer = g_timer_new ();
227   newconn->timeout = 60;
228
229   newconn->auth_method = GST_RTSP_AUTH_NONE;
230   newconn->username = NULL;
231   newconn->passwd = NULL;
232   newconn->auth_params = NULL;
233
234   *conn = newconn;
235
236   return GST_RTSP_OK;
237
238   /* ERRORS */
239 #ifdef G_OS_WIN32
240 startup_error:
241   {
242     g_warning ("Error %d on WSAStartup", error);
243     return GST_RTSP_EWSASTART;
244   }
245 version_error:
246   {
247     g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
248         w.wVersion);
249     WSACleanup ();
250     return GST_RTSP_EWSAVERSION;
251   }
252 #endif
253 no_fdset:
254   {
255     g_free (newconn);
256 #ifdef G_OS_WIN32
257     WSACleanup ();
258 #endif
259     return GST_RTSP_ESYS;
260   }
261 }
262
263 /**
264  * gst_rtsp_connection_accept:
265  * @sock: a socket
266  * @conn: storage for a #GstRTSPConnection
267  *
268  * Accept a new connection on @sock and create a new #GstRTSPConnection for
269  * handling communication on new socket.
270  *
271  * Returns: #GST_RTSP_OK when @conn contains a valid connection.
272  *
273  * Since: 0.10.23
274  */
275 GstRTSPResult
276 gst_rtsp_connection_accept (gint sock, GstRTSPConnection ** conn)
277 {
278   int fd;
279   unsigned int address_len;
280   GstRTSPConnection *newconn = NULL;
281   struct sockaddr_in address;
282   GstRTSPUrl *url;
283
284   address_len = sizeof (address);
285   memset (&address, 0, address_len);
286
287   fd = accept (sock, (struct sockaddr *) &address, &address_len);
288   if (fd == -1)
289     goto accept_failed;
290
291   /* set to non-blocking mode so that we can cancel the communication */
292 #ifndef G_OS_WIN32
293   fcntl (fd, F_SETFL, O_NONBLOCK);
294 #else
295   ioctlsocket (fd, FIONBIO, &flags);
296 #endif /* G_OS_WIN32 */
297
298   /* create a url for the client address */
299   url = g_new0 (GstRTSPUrl, 1);
300   url->host = g_strdup_printf ("%s", inet_ntoa (address.sin_addr));
301   url->port = address.sin_port;
302
303   /* now create the connection object */
304   gst_rtsp_connection_create (url, &newconn);
305   newconn->fd.fd = fd;
306   gst_poll_add_fd (newconn->fdset, &newconn->fd);
307
308   *conn = newconn;
309
310   return GST_RTSP_OK;
311
312   /* ERRORS */
313 accept_failed:
314   {
315     return GST_RTSP_ESYS;
316   }
317 }
318
319 /**
320  * gst_rtsp_connection_connect:
321  * @conn: a #GstRTSPConnection 
322  * @timeout: a #GTimeVal timeout
323  *
324  * Attempt to connect to the url of @conn made with
325  * gst_rtsp_connection_create(). If @timeout is #NULL this function can block
326  * forever. If @timeout contains a valid timeout, this function will return
327  * #GST_RTSP_ETIMEOUT after the timeout expired.
328  *
329  * This function can be cancelled with gst_rtsp_connection_flush().
330  *
331  * Returns: #GST_RTSP_OK when a connection could be made.
332  */
333 GstRTSPResult
334 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
335 {
336   gint fd;
337   struct sockaddr_in sa_in;
338   struct hostent *hostinfo;
339   const gchar *ip;
340   struct in_addr addr;
341   gint ret;
342   guint16 port;
343   GstRTSPUrl *url;
344   GstClockTime to;
345   gint retval;
346
347 #ifdef G_OS_WIN32
348   unsigned long flags = 1;
349   struct in_addr *addrp;
350 #else
351   char **addrs;
352   gchar ipbuf[INET_ADDRSTRLEN];
353 #endif /* G_OS_WIN32 */
354
355   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
356   g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
357   g_return_val_if_fail (conn->fd.fd < 0, GST_RTSP_EINVAL);
358
359   url = conn->url;
360
361   /* first check if it already is an IP address */
362   if (inet_aton (url->host, &addr)) {
363     ip = url->host;
364   } else {
365     hostinfo = gethostbyname (url->host);
366     if (!hostinfo)
367       goto not_resolved;        /* h_errno set */
368
369     if (hostinfo->h_addrtype != AF_INET)
370       goto not_ip;              /* host not an IP host */
371 #ifdef G_OS_WIN32
372     addrp = (struct in_addr *) hostinfo->h_addr_list[0];
373     /* this is not threadsafe */
374     ip = inet_ntoa (*addrp);
375 #else
376     addrs = hostinfo->h_addr_list;
377     ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
378         sizeof (ipbuf));
379 #endif /* G_OS_WIN32 */
380   }
381
382   /* get the port from the url */
383   gst_rtsp_url_get_port (url, &port);
384
385   memset (&sa_in, 0, sizeof (sa_in));
386   sa_in.sin_family = AF_INET;   /* network socket */
387   sa_in.sin_port = htons (port);        /* on port */
388   sa_in.sin_addr.s_addr = inet_addr (ip);       /* on host ip */
389
390   fd = socket (AF_INET, SOCK_STREAM, 0);
391   if (fd == -1)
392     goto sys_error;
393
394   /* set to non-blocking mode so that we can cancel the connect */
395 #ifndef G_OS_WIN32
396   fcntl (fd, F_SETFL, O_NONBLOCK);
397 #else
398   ioctlsocket (fd, FIONBIO, &flags);
399 #endif /* G_OS_WIN32 */
400
401   /* add the socket to our fdset */
402   conn->fd.fd = fd;
403   gst_poll_add_fd (conn->fdset, &conn->fd);
404
405   /* we are going to connect ASYNC now */
406   ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
407   if (ret == 0)
408     goto done;
409   if (!ERRNO_IS_EINPROGRESS)
410     goto sys_error;
411
412   /* wait for connect to complete up to the specified timeout or until we got
413    * interrupted. */
414   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, TRUE);
415
416   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
417
418   do {
419     retval = gst_poll_wait (conn->fdset, to);
420   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
421
422   if (retval == 0)
423     goto timeout;
424   else if (retval == -1)
425     goto sys_error;
426
427   /* we can still have an error connecting on windows */
428   if (gst_poll_fd_has_error (conn->fdset, &conn->fd)) {
429     socklen_t len = sizeof (errno);
430     getsockopt (conn->fd.fd, SOL_SOCKET, SO_ERROR, &errno, &len);
431     goto sys_error;
432   }
433
434   gst_poll_fd_ignored (conn->fdset, &conn->fd);
435
436 done:
437   conn->ip = g_strdup (ip);
438
439   return GST_RTSP_OK;
440
441 sys_error:
442   {
443     GST_ERROR ("system error %d (%s)", errno, g_strerror (errno));
444     if (conn->fd.fd >= 0) {
445       GST_DEBUG ("remove fd %d", conn->fd.fd);
446       gst_poll_remove_fd (conn->fdset, &conn->fd);
447       conn->fd.fd = -1;
448     }
449     if (fd >= 0)
450       CLOSE_SOCKET (fd);
451     return GST_RTSP_ESYS;
452   }
453 not_resolved:
454   {
455     GST_ERROR ("could not resolve %s", url->host);
456     return GST_RTSP_ENET;
457   }
458 not_ip:
459   {
460     GST_ERROR ("not an IP address");
461     return GST_RTSP_ENOTIP;
462   }
463 timeout:
464   {
465     GST_ERROR ("timeout");
466     if (conn->fd.fd >= 0) {
467       GST_DEBUG ("remove fd %d", conn->fd.fd);
468       gst_poll_remove_fd (conn->fdset, &conn->fd);
469       conn->fd.fd = -1;
470     }
471     if (fd >= 0)
472       CLOSE_SOCKET (fd);
473     return GST_RTSP_ETIMEOUT;
474   }
475 }
476
477 static void
478 md5_digest_to_hex_string (unsigned char digest[16], char string[33])
479 {
480   static const char hexdigits[] = "0123456789abcdef";
481   int i;
482
483   for (i = 0; i < 16; i++) {
484     string[i * 2] = hexdigits[(digest[i] >> 4) & 0x0f];
485     string[i * 2 + 1] = hexdigits[digest[i] & 0x0f];
486   }
487   string[32] = 0;
488 }
489
490 static void
491 auth_digest_compute_hex_urp (const gchar * username,
492     const gchar * realm, const gchar * password, gchar hex_urp[33])
493 {
494   struct MD5Context md5_context;
495   unsigned char digest[16];
496
497   MD5Init (&md5_context);
498   MD5Update (&md5_context, username, strlen (username));
499   MD5Update (&md5_context, ":", 1);
500   MD5Update (&md5_context, realm, strlen (realm));
501   MD5Update (&md5_context, ":", 1);
502   MD5Update (&md5_context, password, strlen (password));
503   MD5Final (digest, &md5_context);
504   md5_digest_to_hex_string (digest, hex_urp);
505 }
506
507 static void
508 auth_digest_compute_response (const gchar * method,
509     const gchar * uri, const gchar * hex_a1, const gchar * nonce,
510     gchar response[33])
511 {
512   char hex_a2[33];
513   struct MD5Context md5_context;
514   unsigned char digest[16];
515
516   /* compute A2 */
517   MD5Init (&md5_context);
518   MD5Update (&md5_context, method, strlen (method));
519   MD5Update (&md5_context, ":", 1);
520   MD5Update (&md5_context, uri, strlen (uri));
521   MD5Final (digest, &md5_context);
522   md5_digest_to_hex_string (digest, hex_a2);
523
524   /* compute KD */
525   MD5Init (&md5_context);
526   MD5Update (&md5_context, hex_a1, strlen (hex_a1));
527   MD5Update (&md5_context, ":", 1);
528   MD5Update (&md5_context, nonce, strlen (nonce));
529   MD5Update (&md5_context, ":", 1);
530
531   MD5Update (&md5_context, hex_a2, 32);
532   MD5Final (digest, &md5_context);
533   md5_digest_to_hex_string (digest, response);
534 }
535
536 static void
537 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
538 {
539   switch (conn->auth_method) {
540     case GST_RTSP_AUTH_BASIC:{
541       gchar *user_pass =
542           g_strdup_printf ("%s:%s", conn->username, conn->passwd);
543       gchar *user_pass64 =
544           gst_rtsp_base64_encode (user_pass, strlen (user_pass));
545       gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
546
547       gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
548           auth_string);
549
550       g_free (user_pass);
551       g_free (user_pass64);
552       break;
553     }
554     case GST_RTSP_AUTH_DIGEST:{
555       gchar response[33], hex_urp[33];
556       gchar *auth_string, *auth_string2;
557       gchar *realm;
558       gchar *nonce;
559       gchar *opaque;
560       const gchar *uri;
561       const gchar *method;
562
563       /* we need to have some params set */
564       if (conn->auth_params == NULL)
565         break;
566
567       /* we need the realm and nonce */
568       realm = (gchar *) g_hash_table_lookup (conn->auth_params, "realm");
569       nonce = (gchar *) g_hash_table_lookup (conn->auth_params, "nonce");
570       if (realm == NULL || nonce == NULL)
571         break;
572
573       auth_digest_compute_hex_urp (conn->username, realm, conn->passwd,
574           hex_urp);
575
576       method = gst_rtsp_method_as_text (message->type_data.request.method);
577       uri = message->type_data.request.uri;
578
579       /* Assume no qop, algorithm=md5, stale=false */
580       /* For algorithm MD5, a1 = urp. */
581       auth_digest_compute_response (method, uri, hex_urp, nonce, response);
582       auth_string = g_strdup_printf ("Digest username=\"%s\", "
583           "realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
584           conn->username, realm, nonce, uri, response);
585
586       opaque = (gchar *) g_hash_table_lookup (conn->auth_params, "opaque");
587       if (opaque) {
588         auth_string2 = g_strdup_printf ("%s, opaque=\"%s\"", auth_string,
589             opaque);
590         g_free (auth_string);
591         auth_string = auth_string2;
592       }
593       gst_rtsp_message_take_header (message, GST_RTSP_HDR_AUTHORIZATION,
594           auth_string);
595       break;
596     }
597     default:
598       /* Nothing to do */
599       break;
600   }
601 }
602
603 static void
604 add_date_header (GstRTSPMessage * message)
605 {
606   GTimeVal tv;
607   gchar date_string[100];
608   time_t t;
609
610 #ifdef HAVE_GMTIME_R
611   struct tm tm_;
612 #endif
613
614   g_get_current_time (&tv);
615   t = (time_t) tv.tv_sec;
616
617 #ifdef HAVE_GMTIME_R
618   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
619       gmtime_r (&t, &tm_));
620 #else
621   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
622       gmtime (&t));
623 #endif
624
625   gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
626 }
627
628 static GstRTSPResult
629 write_bytes (gint fd, const guint8 * buffer, guint * idx, guint size)
630 {
631   guint left;
632
633   if (*idx > size)
634     return GST_RTSP_ERROR;
635
636   left = size - *idx;
637
638   while (left) {
639     gint r;
640
641     r = WRITE_SOCKET (fd, &buffer[*idx], left);
642     if (r == 0) {
643       return GST_RTSP_EINTR;
644     } else if (r < 0) {
645       if (ERRNO_IS_EAGAIN)
646         return GST_RTSP_EINTR;
647       if (!ERRNO_IS_EINTR)
648         return GST_RTSP_ESYS;
649     } else {
650       left -= r;
651       *idx += r;
652     }
653   }
654   return GST_RTSP_OK;
655 }
656
657 static GstRTSPResult
658 read_bytes (gint fd, guint8 * buffer, guint * idx, guint size)
659 {
660   guint left;
661
662   if (*idx > size)
663     return GST_RTSP_ERROR;
664
665   left = size - *idx;
666
667   while (left) {
668     gint r;
669
670     r = READ_SOCKET (fd, &buffer[*idx], left);
671     if (r == 0) {
672       return GST_RTSP_EEOF;
673     } else if (r < 0) {
674       if (ERRNO_IS_EAGAIN)
675         return GST_RTSP_EINTR;
676       if (!ERRNO_IS_EINTR)
677         return GST_RTSP_ESYS;
678     } else {
679       left -= r;
680       *idx += r;
681     }
682   }
683   return GST_RTSP_OK;
684 }
685
686 static GstRTSPResult
687 read_line (gint fd, guint8 * buffer, guint * idx, guint size)
688 {
689   while (TRUE) {
690     guint8 c;
691     gint r;
692
693     r = READ_SOCKET (fd, &c, 1);
694     if (r == 0) {
695       return GST_RTSP_EEOF;
696     } else if (r < 0) {
697       if (ERRNO_IS_EAGAIN)
698         return GST_RTSP_EINTR;
699       if (!ERRNO_IS_EINTR)
700         return GST_RTSP_ESYS;
701     } else {
702       if (c == '\n')            /* end on \n */
703         break;
704       if (c == '\r')            /* ignore \r */
705         continue;
706
707       if (*idx < size - 1)
708         buffer[(*idx)++] = c;
709     }
710   }
711   buffer[*idx] = '\0';
712
713   return GST_RTSP_OK;
714 }
715
716 /**
717  * gst_rtsp_connection_write:
718  * @conn: a #GstRTSPConnection
719  * @data: the data to write
720  * @size: the size of @data
721  * @timeout: a timeout value or #NULL
722  *
723  * Attempt to write @size bytes of @data to the connected @conn, blocking up to
724  * the specified @timeout. @timeout can be #NULL, in which case this function
725  * might block forever.
726  * 
727  * This function can be cancelled with gst_rtsp_connection_flush().
728  *
729  * Returns: #GST_RTSP_OK on success.
730  */
731 GstRTSPResult
732 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
733     guint size, GTimeVal * timeout)
734 {
735   guint offset;
736   gint retval;
737   GstClockTime to;
738   GstRTSPResult res;
739
740   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
741   g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
742   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
743
744   gst_poll_set_controllable (conn->fdset, TRUE);
745   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, TRUE);
746   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, FALSE);
747   /* clear all previous poll results */
748   gst_poll_fd_ignored (conn->fdset, &conn->fd);
749
750   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
751
752   offset = 0;
753
754   while (TRUE) {
755     /* try to write */
756     res = write_bytes (conn->fd.fd, data, &offset, size);
757     if (res == GST_RTSP_OK)
758       break;
759     if (res != GST_RTSP_EINTR)
760       goto write_error;
761
762     /* not all is written, wait until we can write more */
763     do {
764       retval = gst_poll_wait (conn->fdset, to);
765     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
766
767     if (retval == 0)
768       goto timeout;
769
770     if (retval == -1) {
771       if (errno == EBUSY)
772         goto stopped;
773       else
774         goto select_error;
775     }
776   }
777   return GST_RTSP_OK;
778
779   /* ERRORS */
780 timeout:
781   {
782     return GST_RTSP_ETIMEOUT;
783   }
784 select_error:
785   {
786     return GST_RTSP_ESYS;
787   }
788 stopped:
789   {
790     return GST_RTSP_EINTR;
791   }
792 write_error:
793   {
794     return res;
795   }
796 }
797
798 static GString *
799 message_to_string (GstRTSPConnection * conn, GstRTSPMessage * message)
800 {
801   GString *str = NULL;
802
803   str = g_string_new ("");
804
805   switch (message->type) {
806     case GST_RTSP_MESSAGE_REQUEST:
807       /* create request string, add CSeq */
808       g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
809           "CSeq: %d\r\n",
810           gst_rtsp_method_as_text (message->type_data.request.method),
811           message->type_data.request.uri, conn->cseq++);
812       /* add session id if we have one */
813       if (conn->session_id[0] != '\0') {
814         gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
815             conn->session_id);
816       }
817       /* add any authentication headers */
818       add_auth_header (conn, message);
819       break;
820     case GST_RTSP_MESSAGE_RESPONSE:
821       /* create response string */
822       g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
823           message->type_data.response.code, message->type_data.response.reason);
824       break;
825     case GST_RTSP_MESSAGE_DATA:
826     {
827       guint8 data_header[4];
828
829       /* prepare data header */
830       data_header[0] = '$';
831       data_header[1] = message->type_data.data.channel;
832       data_header[2] = (message->body_size >> 8) & 0xff;
833       data_header[3] = message->body_size & 0xff;
834
835       /* create string with header and data */
836       str = g_string_append_len (str, (gchar *) data_header, 4);
837       str =
838           g_string_append_len (str, (gchar *) message->body,
839           message->body_size);
840       break;
841     }
842     default:
843       g_string_free (str, TRUE);
844       g_return_val_if_reached (NULL);
845       break;
846   }
847
848   /* append headers and body */
849   if (message->type != GST_RTSP_MESSAGE_DATA) {
850     /* add date header */
851     add_date_header (message);
852
853     /* append headers */
854     gst_rtsp_message_append_headers (message, str);
855
856     /* append Content-Length and body if needed */
857     if (message->body != NULL && message->body_size > 0) {
858       gchar *len;
859
860       len = g_strdup_printf ("%d", message->body_size);
861       g_string_append_printf (str, "%s: %s\r\n",
862           gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
863       g_free (len);
864       /* header ends here */
865       g_string_append (str, "\r\n");
866       str =
867           g_string_append_len (str, (gchar *) message->body,
868           message->body_size);
869     } else {
870       /* just end headers */
871       g_string_append (str, "\r\n");
872     }
873   }
874
875   return str;
876 }
877
878 /**
879  * gst_rtsp_connection_send:
880  * @conn: a #GstRTSPConnection
881  * @message: the message to send
882  * @timeout: a timeout value or #NULL
883  *
884  * Attempt to send @message to the connected @conn, blocking up to
885  * the specified @timeout. @timeout can be #NULL, in which case this function
886  * might block forever.
887  * 
888  * This function can be cancelled with gst_rtsp_connection_flush().
889  *
890  * Returns: #GST_RTSP_OK on success.
891  */
892 GstRTSPResult
893 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
894     GTimeVal * timeout)
895 {
896   GString *str = NULL;
897   GstRTSPResult res;
898
899   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
900   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
901
902   if (!(str = message_to_string (conn, message)))
903     goto no_message;
904
905   /* write request */
906   res =
907       gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len, timeout);
908
909   g_string_free (str, TRUE);
910
911   return res;
912
913 no_message:
914   {
915     g_warning ("Wrong message");
916     return GST_RTSP_EINVAL;
917   }
918 }
919
920 static void
921 parse_string (gchar * dest, gint size, gchar ** src)
922 {
923   gint idx;
924
925   idx = 0;
926   /* skip spaces */
927   while (g_ascii_isspace (**src))
928     (*src)++;
929
930   while (!g_ascii_isspace (**src) && **src != '\0') {
931     if (idx < size - 1)
932       dest[idx++] = **src;
933     (*src)++;
934   }
935   if (size > 0)
936     dest[idx] = '\0';
937 }
938
939 static void
940 parse_key (gchar * dest, gint size, gchar ** src)
941 {
942   gint idx;
943
944   idx = 0;
945   while (**src != ':' && **src != '\0') {
946     if (idx < size - 1)
947       dest[idx++] = **src;
948     (*src)++;
949   }
950   if (size > 0)
951     dest[idx] = '\0';
952 }
953
954 static GstRTSPResult
955 parse_response_status (guint8 * buffer, GstRTSPMessage * msg)
956 {
957   GstRTSPResult res;
958   gchar versionstr[20];
959   gchar codestr[4];
960   gint code;
961   gchar *bptr;
962
963   bptr = (gchar *) buffer;
964
965   parse_string (versionstr, sizeof (versionstr), &bptr);
966   parse_string (codestr, sizeof (codestr), &bptr);
967   code = atoi (codestr);
968
969   while (g_ascii_isspace (*bptr))
970     bptr++;
971
972   if (strcmp (versionstr, "RTSP/1.0") == 0)
973     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
974         parse_error);
975   else if (strncmp (versionstr, "RTSP/", 5) == 0) {
976     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
977         parse_error);
978     msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
979   } else
980     goto parse_error;
981
982   return GST_RTSP_OK;
983
984 parse_error:
985   {
986     return GST_RTSP_EPARSE;
987   }
988 }
989
990 static GstRTSPResult
991 parse_request_line (guint8 * buffer, GstRTSPMessage * msg)
992 {
993   GstRTSPResult res = GST_RTSP_OK;
994   gchar versionstr[20];
995   gchar methodstr[20];
996   gchar urlstr[4096];
997   gchar *bptr;
998   GstRTSPMethod method;
999
1000   bptr = (gchar *) buffer;
1001
1002   parse_string (methodstr, sizeof (methodstr), &bptr);
1003   method = gst_rtsp_find_method (methodstr);
1004
1005   parse_string (urlstr, sizeof (urlstr), &bptr);
1006   if (*urlstr == '\0')
1007     res = GST_RTSP_EPARSE;
1008
1009   parse_string (versionstr, sizeof (versionstr), &bptr);
1010
1011   if (*bptr != '\0')
1012     res = GST_RTSP_EPARSE;
1013
1014   if (strcmp (versionstr, "RTSP/1.0") == 0) {
1015     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
1016       res = GST_RTSP_EPARSE;
1017   } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
1018     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
1019       res = GST_RTSP_EPARSE;
1020     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1021   } else {
1022     gst_rtsp_message_init_request (msg, method, urlstr);
1023     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
1024     res = GST_RTSP_EPARSE;
1025   }
1026
1027   return res;
1028 }
1029
1030 /* parsing lines means reading a Key: Value pair */
1031 static GstRTSPResult
1032 parse_line (guint8 * buffer, GstRTSPMessage * msg)
1033 {
1034   gchar key[32];
1035   gchar *bptr;
1036   GstRTSPHeaderField field;
1037
1038   bptr = (gchar *) buffer;
1039
1040   /* read key */
1041   parse_key (key, sizeof (key), &bptr);
1042   if (*bptr != ':')
1043     goto no_column;
1044
1045   bptr++;
1046
1047   field = gst_rtsp_find_header_field (key);
1048   if (field != GST_RTSP_HDR_INVALID) {
1049     while (g_ascii_isspace (*bptr))
1050       bptr++;
1051     gst_rtsp_message_add_header (msg, field, bptr);
1052   }
1053
1054   return GST_RTSP_OK;
1055
1056 no_column:
1057   {
1058     return GST_RTSP_EPARSE;
1059   }
1060 }
1061
1062 /* returns:
1063  *  GST_RTSP_OK when a complete message was read.
1064  *  GST_RTSP_EEOF: when the socket is closed
1065  *  GST_RTSP_EINTR: when more data is needed.
1066  *  GST_RTSP_..: some other error occured.
1067  */
1068 static GstRTSPResult
1069 build_next (GstRTSPBuilder * builder, GstRTSPMessage * message,
1070     GstRTSPConnection * conn)
1071 {
1072   GstRTSPResult res;
1073
1074   while (TRUE) {
1075     switch (builder->state) {
1076       case STATE_START:
1077         builder->offset = 0;
1078         res =
1079             read_bytes (conn->fd.fd, (guint8 *) builder->buffer,
1080             &builder->offset, 1);
1081         if (res != GST_RTSP_OK)
1082           goto done;
1083
1084         /* we have 1 bytes now and we can see if this is a data message or
1085          * not */
1086         if (builder->buffer[0] == '$') {
1087           /* data message, prepare for the header */
1088           builder->state = STATE_DATA_HEADER;
1089         } else {
1090           builder->line = 0;
1091           builder->state = STATE_READ_LINES;
1092         }
1093         break;
1094       case STATE_DATA_HEADER:
1095       {
1096         res =
1097             read_bytes (conn->fd.fd, (guint8 *) builder->buffer,
1098             &builder->offset, 4);
1099         if (res != GST_RTSP_OK)
1100           goto done;
1101
1102         gst_rtsp_message_init_data (message, builder->buffer[1]);
1103
1104         builder->body_len = (builder->buffer[2] << 8) | builder->buffer[3];
1105         builder->body_data = g_malloc (builder->body_len + 1);
1106         builder->body_data[builder->body_len] = '\0';
1107         builder->offset = 0;
1108         builder->state = STATE_DATA_BODY;
1109         break;
1110       }
1111       case STATE_DATA_BODY:
1112       {
1113         res = read_bytes (conn->fd.fd, builder->body_data, &builder->offset,
1114             builder->body_len);
1115         if (res != GST_RTSP_OK)
1116           goto done;
1117
1118         /* we have the complete body now, store in the message adjusting the
1119          * length to include the traling '\0' */
1120         gst_rtsp_message_take_body (message,
1121             (guint8 *) builder->body_data, builder->body_len + 1);
1122         builder->body_data = NULL;
1123         builder->body_len = 0;
1124
1125         builder->state = STATE_END;
1126         break;
1127       }
1128       case STATE_READ_LINES:
1129       {
1130         res = read_line (conn->fd.fd, builder->buffer, &builder->offset,
1131             sizeof (builder->buffer));
1132         if (res != GST_RTSP_OK)
1133           goto done;
1134
1135         /* we have a regular response */
1136         if (builder->buffer[0] == '\r') {
1137           builder->buffer[0] = '\0';
1138         }
1139
1140         if (builder->buffer[0] == '\0') {
1141           gchar *hdrval;
1142
1143           /* empty line, end of message header */
1144           /* see if there is a Content-Length header */
1145           if (gst_rtsp_message_get_header (message,
1146                   GST_RTSP_HDR_CONTENT_LENGTH, &hdrval, 0) == GST_RTSP_OK) {
1147             /* there is, prepare to read the body */
1148             builder->body_len = atol (hdrval);
1149             builder->body_data = g_malloc (builder->body_len + 1);
1150             builder->body_data[builder->body_len] = '\0';
1151             builder->offset = 0;
1152             builder->state = STATE_DATA_BODY;
1153           } else {
1154             builder->state = STATE_END;
1155           }
1156           break;
1157         }
1158
1159         /* we have a line */
1160         if (builder->line == 0) {
1161           /* first line, check for response status */
1162           if (memcmp (builder->buffer, "RTSP", 4) == 0) {
1163             res = parse_response_status (builder->buffer, message);
1164           } else {
1165             res = parse_request_line (builder->buffer, message);
1166           }
1167         } else {
1168           /* else just parse the line */
1169           parse_line (builder->buffer, message);
1170         }
1171         builder->line++;
1172         builder->offset = 0;
1173         break;
1174       }
1175       case STATE_END:
1176       {
1177         gchar *session_id;
1178
1179         if (message->type == GST_RTSP_MESSAGE_DATA) {
1180           /* data messages don't have headers */
1181           res = GST_RTSP_OK;
1182           goto done;
1183         }
1184
1185         /* save session id in the connection for further use */
1186         if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_SESSION,
1187                 &session_id, 0) == GST_RTSP_OK) {
1188           gint maxlen, i;
1189
1190           maxlen = sizeof (conn->session_id) - 1;
1191           /* the sessionid can have attributes marked with ;
1192            * Make sure we strip them */
1193           for (i = 0; session_id[i] != '\0'; i++) {
1194             if (session_id[i] == ';') {
1195               maxlen = i;
1196               /* parse timeout */
1197               do {
1198                 i++;
1199               } while (g_ascii_isspace (session_id[i]));
1200               if (g_str_has_prefix (&session_id[i], "timeout=")) {
1201                 gint to;
1202
1203                 /* if we parsed something valid, configure */
1204                 if ((to = atoi (&session_id[i + 9])) > 0)
1205                   conn->timeout = to;
1206               }
1207               break;
1208             }
1209           }
1210
1211           /* make sure to not overflow */
1212           strncpy (conn->session_id, session_id, maxlen);
1213           conn->session_id[maxlen] = '\0';
1214         }
1215         res = GST_RTSP_OK;
1216         goto done;
1217       }
1218       default:
1219         res = GST_RTSP_ERROR;
1220         break;
1221     }
1222   }
1223 done:
1224   return res;
1225 }
1226
1227 /**
1228  * gst_rtsp_connection_read:
1229  * @conn: a #GstRTSPConnection
1230  * @data: the data to read
1231  * @size: the size of @data
1232  * @timeout: a timeout value or #NULL
1233  *
1234  * Attempt to read @size bytes into @data from the connected @conn, blocking up to
1235  * the specified @timeout. @timeout can be #NULL, in which case this function
1236  * might block forever.
1237  *
1238  * This function can be cancelled with gst_rtsp_connection_flush().
1239  *
1240  * Returns: #GST_RTSP_OK on success.
1241  */
1242 GstRTSPResult
1243 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
1244     GTimeVal * timeout)
1245 {
1246   guint offset;
1247   gint retval;
1248   GstClockTime to;
1249   GstRTSPResult res;
1250
1251   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1252   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
1253   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
1254
1255   if (size == 0)
1256     return GST_RTSP_OK;
1257
1258   offset = 0;
1259
1260   /* configure timeout if any */
1261   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1262
1263   gst_poll_set_controllable (conn->fdset, TRUE);
1264   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, FALSE);
1265   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, TRUE);
1266
1267   while (TRUE) {
1268     res = read_bytes (conn->fd.fd, data, &offset, size);
1269     if (res == GST_RTSP_EEOF)
1270       goto eof;
1271     if (res == GST_RTSP_OK)
1272       break;
1273     if (res != GST_RTSP_EINTR)
1274       goto read_error;
1275
1276     do {
1277       retval = gst_poll_wait (conn->fdset, to);
1278     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1279
1280     /* check for timeout */
1281     if (retval == 0)
1282       goto select_timeout;
1283
1284     if (retval == -1) {
1285       if (errno == EBUSY)
1286         goto stopped;
1287       else
1288         goto select_error;
1289     }
1290     gst_poll_set_controllable (conn->fdset, FALSE);
1291   }
1292   return GST_RTSP_OK;
1293
1294   /* ERRORS */
1295 select_error:
1296   {
1297     return GST_RTSP_ESYS;
1298   }
1299 select_timeout:
1300   {
1301     return GST_RTSP_ETIMEOUT;
1302   }
1303 stopped:
1304   {
1305     return GST_RTSP_EINTR;
1306   }
1307 eof:
1308   {
1309     return GST_RTSP_EEOF;
1310   }
1311 read_error:
1312   {
1313     return res;
1314   }
1315 }
1316
1317
1318 /**
1319  * gst_rtsp_connection_receive:
1320  * @conn: a #GstRTSPConnection
1321  * @message: the message to read
1322  * @timeout: a timeout value or #NULL
1323  *
1324  * Attempt to read into @message from the connected @conn, blocking up to
1325  * the specified @timeout. @timeout can be #NULL, in which case this function
1326  * might block forever.
1327  * 
1328  * This function can be cancelled with gst_rtsp_connection_flush().
1329  *
1330  * Returns: #GST_RTSP_OK on success.
1331  */
1332 GstRTSPResult
1333 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * message,
1334     GTimeVal * timeout)
1335 {
1336   GstRTSPResult res;
1337   GstRTSPBuilder builder = { 0 };
1338   gint retval;
1339   GstClockTime to;
1340
1341   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1342   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
1343
1344   /* configure timeout if any */
1345   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1346
1347   gst_poll_set_controllable (conn->fdset, TRUE);
1348   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, FALSE);
1349   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, TRUE);
1350
1351   while (TRUE) {
1352     res = build_next (&builder, message, conn);
1353     if (res == GST_RTSP_EEOF)
1354       goto eof;
1355     if (res == GST_RTSP_OK)
1356       break;
1357     if (res != GST_RTSP_EINTR)
1358       goto read_error;
1359
1360     do {
1361       retval = gst_poll_wait (conn->fdset, to);
1362     } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1363
1364     /* check for timeout */
1365     if (retval == 0)
1366       goto select_timeout;
1367
1368     if (retval == -1) {
1369       if (errno == EBUSY)
1370         goto stopped;
1371       else
1372         goto select_error;
1373     }
1374     gst_poll_set_controllable (conn->fdset, FALSE);
1375   }
1376
1377   /* we have a message here */
1378   build_reset (&builder);
1379
1380   return GST_RTSP_OK;
1381
1382   /* ERRORS */
1383 select_error:
1384   {
1385     res = GST_RTSP_ESYS;
1386     goto cleanup;
1387   }
1388 select_timeout:
1389   {
1390     res = GST_RTSP_ETIMEOUT;
1391     goto cleanup;
1392   }
1393 stopped:
1394   {
1395     res = GST_RTSP_EINTR;
1396     goto cleanup;
1397   }
1398 eof:
1399   {
1400     res = GST_RTSP_EEOF;
1401     goto cleanup;
1402   }
1403 read_error:
1404 cleanup:
1405   {
1406     build_reset (&builder);
1407     gst_rtsp_message_unset (message);
1408     return res;
1409   }
1410 }
1411
1412 /**
1413  * gst_rtsp_connection_close:
1414  * @conn: a #GstRTSPConnection
1415  *
1416  * Close the connected @conn.
1417  * 
1418  * Returns: #GST_RTSP_OK on success.
1419  */
1420 GstRTSPResult
1421 gst_rtsp_connection_close (GstRTSPConnection * conn)
1422 {
1423   gint res;
1424
1425   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1426
1427   g_free (conn->ip);
1428   conn->ip = NULL;
1429
1430   if (conn->fd.fd != -1) {
1431     gst_poll_remove_fd (conn->fdset, &conn->fd);
1432     res = CLOSE_SOCKET (conn->fd.fd);
1433     conn->fd.fd = -1;
1434     if (res != 0)
1435       goto sys_error;
1436   }
1437
1438   return GST_RTSP_OK;
1439
1440 sys_error:
1441   {
1442     return GST_RTSP_ESYS;
1443   }
1444 }
1445
1446 /**
1447  * gst_rtsp_connection_free:
1448  * @conn: a #GstRTSPConnection
1449  *
1450  * Close and free @conn.
1451  * 
1452  * Returns: #GST_RTSP_OK on success.
1453  */
1454 GstRTSPResult
1455 gst_rtsp_connection_free (GstRTSPConnection * conn)
1456 {
1457   GstRTSPResult res;
1458
1459   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1460
1461   res = gst_rtsp_connection_close (conn);
1462   gst_poll_free (conn->fdset);
1463   g_timer_destroy (conn->timer);
1464   g_free (conn->username);
1465   g_free (conn->passwd);
1466   gst_rtsp_connection_clear_auth_params (conn);
1467   g_free (conn);
1468 #ifdef G_OS_WIN32
1469   WSACleanup ();
1470 #endif
1471
1472   return res;
1473 }
1474
1475 /**
1476  * gst_rtsp_connection_poll:
1477  * @conn: a #GstRTSPConnection
1478  * @events: a bitmask of #GstRTSPEvent flags to check
1479  * @revents: location for result flags 
1480  * @timeout: a timeout
1481  *
1482  * Wait up to the specified @timeout for the connection to become available for
1483  * at least one of the operations specified in @events. When the function returns
1484  * with #GST_RTSP_OK, @revents will contain a bitmask of available operations on
1485  * @conn.
1486  *
1487  * @timeout can be #NULL, in which case this function might block forever.
1488  *
1489  * This function can be cancelled with gst_rtsp_connection_flush().
1490  * 
1491  * Returns: #GST_RTSP_OK on success.
1492  *
1493  * Since: 0.10.15
1494  */
1495 GstRTSPResult
1496 gst_rtsp_connection_poll (GstRTSPConnection * conn, GstRTSPEvent events,
1497     GstRTSPEvent * revents, GTimeVal * timeout)
1498 {
1499   GstClockTime to;
1500   gint retval;
1501
1502   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1503   g_return_val_if_fail (events != 0, GST_RTSP_EINVAL);
1504   g_return_val_if_fail (revents != NULL, GST_RTSP_EINVAL);
1505   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
1506
1507   gst_poll_set_controllable (conn->fdset, TRUE);
1508
1509   /* add fd to writer set when asked to */
1510   gst_poll_fd_ctl_write (conn->fdset, &conn->fd, events & GST_RTSP_EV_WRITE);
1511
1512   /* add fd to reader set when asked to */
1513   gst_poll_fd_ctl_read (conn->fdset, &conn->fd, events & GST_RTSP_EV_READ);
1514
1515   /* configure timeout if any */
1516   to = timeout ? GST_TIMEVAL_TO_TIME (*timeout) : GST_CLOCK_TIME_NONE;
1517
1518   do {
1519     retval = gst_poll_wait (conn->fdset, to);
1520   } while (retval == -1 && (errno == EINTR || errno == EAGAIN));
1521
1522   if (retval == 0)
1523     goto select_timeout;
1524
1525   if (retval == -1) {
1526     if (errno == EBUSY)
1527       goto stopped;
1528     else
1529       goto select_error;
1530   }
1531
1532   *revents = 0;
1533   if (events & GST_RTSP_EV_READ) {
1534     if (gst_poll_fd_can_read (conn->fdset, &conn->fd))
1535       *revents |= GST_RTSP_EV_READ;
1536   }
1537   if (events & GST_RTSP_EV_WRITE) {
1538     if (gst_poll_fd_can_write (conn->fdset, &conn->fd))
1539       *revents |= GST_RTSP_EV_WRITE;
1540   }
1541   return GST_RTSP_OK;
1542
1543   /* ERRORS */
1544 select_timeout:
1545   {
1546     return GST_RTSP_ETIMEOUT;
1547   }
1548 select_error:
1549   {
1550     return GST_RTSP_ESYS;
1551   }
1552 stopped:
1553   {
1554     return GST_RTSP_EINTR;
1555   }
1556 }
1557
1558 /**
1559  * gst_rtsp_connection_next_timeout:
1560  * @conn: a #GstRTSPConnection
1561  * @timeout: a timeout
1562  *
1563  * Calculate the next timeout for @conn, storing the result in @timeout.
1564  * 
1565  * Returns: #GST_RTSP_OK.
1566  */
1567 GstRTSPResult
1568 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
1569 {
1570   gdouble elapsed;
1571   glong sec;
1572   gulong usec;
1573
1574   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1575   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
1576
1577   elapsed = g_timer_elapsed (conn->timer, &usec);
1578   if (elapsed >= conn->timeout) {
1579     sec = 0;
1580     usec = 0;
1581   } else {
1582     sec = conn->timeout - elapsed;
1583   }
1584
1585   timeout->tv_sec = sec;
1586   timeout->tv_usec = usec;
1587
1588   return GST_RTSP_OK;
1589 }
1590
1591 /**
1592  * gst_rtsp_connection_reset_timeout:
1593  * @conn: a #GstRTSPConnection
1594  *
1595  * Reset the timeout of @conn.
1596  * 
1597  * Returns: #GST_RTSP_OK.
1598  */
1599 GstRTSPResult
1600 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
1601 {
1602   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1603
1604   g_timer_start (conn->timer);
1605
1606   return GST_RTSP_OK;
1607 }
1608
1609 /**
1610  * gst_rtsp_connection_flush:
1611  * @conn: a #GstRTSPConnection
1612  * @flush: start or stop the flush
1613  *
1614  * Start or stop the flushing action on @conn. When flushing, all current
1615  * and future actions on @conn will return #GST_RTSP_EINTR until the connection
1616  * is set to non-flushing mode again.
1617  * 
1618  * Returns: #GST_RTSP_OK.
1619  */
1620 GstRTSPResult
1621 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
1622 {
1623   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1624
1625   gst_poll_set_flushing (conn->fdset, flush);
1626
1627   return GST_RTSP_OK;
1628 }
1629
1630 /**
1631  * gst_rtsp_connection_set_auth:
1632  * @conn: a #GstRTSPConnection
1633  * @method: authentication method
1634  * @user: the user
1635  * @pass: the password
1636  *
1637  * Configure @conn for authentication mode @method with @user and @pass as the
1638  * user and password respectively.
1639  * 
1640  * Returns: #GST_RTSP_OK.
1641  */
1642 GstRTSPResult
1643 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
1644     GstRTSPAuthMethod method, const gchar * user, const gchar * pass)
1645 {
1646   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1647
1648   if (method == GST_RTSP_AUTH_DIGEST && ((user == NULL || pass == NULL)
1649           || g_strrstr (user, ":") != NULL))
1650     return GST_RTSP_EINVAL;
1651
1652   /* Make sure the username and passwd are being set for authentication */
1653   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
1654     return GST_RTSP_EINVAL;
1655
1656   /* ":" chars are not allowed in usernames for basic auth */
1657   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
1658     return GST_RTSP_EINVAL;
1659
1660   g_free (conn->username);
1661   g_free (conn->passwd);
1662
1663   conn->auth_method = method;
1664   conn->username = g_strdup (user);
1665   conn->passwd = g_strdup (pass);
1666
1667   return GST_RTSP_OK;
1668 }
1669
1670 /**
1671  * str_case_hash:
1672  * @key: ASCII string to hash
1673  *
1674  * Hashes @key in a case-insensitive manner.
1675  *
1676  * Returns: the hash code.
1677  **/
1678 static guint
1679 str_case_hash (gconstpointer key)
1680 {
1681   const char *p = key;
1682   guint h = g_ascii_toupper (*p);
1683
1684   if (h)
1685     for (p += 1; *p != '\0'; p++)
1686       h = (h << 5) - h + g_ascii_toupper (*p);
1687
1688   return h;
1689 }
1690
1691 /**
1692  * str_case_equal:
1693  * @v1: an ASCII string
1694  * @v2: another ASCII string
1695  *
1696  * Compares @v1 and @v2 in a case-insensitive manner
1697  *
1698  * Returns: %TRUE if they are equal (modulo case)
1699  **/
1700 static gboolean
1701 str_case_equal (gconstpointer v1, gconstpointer v2)
1702 {
1703   const char *string1 = v1;
1704   const char *string2 = v2;
1705
1706   return g_ascii_strcasecmp (string1, string2) == 0;
1707 }
1708
1709 /**
1710  * gst_rtsp_connection_set_auth_param:
1711  * @conn: a #GstRTSPConnection
1712  * @param: authentication directive
1713  * @value: value
1714  *
1715  * Setup @conn with authentication directives. This is not necesary for
1716  * methods #GST_RTSP_AUTH_NONE and #GST_RTSP_AUTH_BASIC. For
1717  * #GST_RTSP_AUTH_DIGEST, directives should be taken from the digest challenge
1718  * in the WWW-Authenticate response header and can include realm, domain,
1719  * nonce, opaque, stale, algorithm, qop as per RFC2617.
1720  * 
1721  * Since: 0.10.20
1722  */
1723 void
1724 gst_rtsp_connection_set_auth_param (GstRTSPConnection * conn,
1725     const gchar * param, const gchar * value)
1726 {
1727   g_return_if_fail (conn != NULL);
1728   g_return_if_fail (param != NULL);
1729
1730   if (conn->auth_params == NULL) {
1731     conn->auth_params =
1732         g_hash_table_new_full (str_case_hash, str_case_equal, g_free, g_free);
1733   }
1734   g_hash_table_insert (conn->auth_params, g_strdup (param), g_strdup (value));
1735 }
1736
1737 /**
1738  * gst_rtsp_connection_clear_auth_params:
1739  * @conn: a #GstRTSPConnection
1740  *
1741  * Clear the list of authentication directives stored in @conn.
1742  *
1743  * Since: 0.10.20
1744  */
1745 void
1746 gst_rtsp_connection_clear_auth_params (GstRTSPConnection * conn)
1747 {
1748   g_return_if_fail (conn != NULL);
1749
1750   if (conn->auth_params != NULL) {
1751     g_hash_table_destroy (conn->auth_params);
1752     conn->auth_params = NULL;
1753   }
1754 }
1755
1756 /**
1757  * gst_rtsp_connection_set_qos_dscp:
1758  * @conn: a #GstRTSPConnection
1759  * @qos_dscp: DSCP value
1760  *
1761  * Configure @conn to use the specified DSCP value.
1762  *
1763  * Returns: #GST_RTSP_OK on success.
1764  *
1765  * Since: 0.10.20
1766  */
1767 GstRTSPResult
1768 gst_rtsp_connection_set_qos_dscp (GstRTSPConnection * conn, guint qos_dscp)
1769 {
1770   union gst_sockaddr
1771   {
1772     struct sockaddr sa;
1773     struct sockaddr_in6 sa_in6;
1774     struct sockaddr_storage sa_stor;
1775   } sa;
1776   socklen_t slen = sizeof (sa);
1777   gint af;
1778   gint tos;
1779
1780   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1781   g_return_val_if_fail (conn->fd.fd >= 0, GST_RTSP_EINVAL);
1782
1783   if (getsockname (conn->fd.fd, &sa.sa, &slen) < 0)
1784     goto no_getsockname;
1785
1786   af = sa.sa.sa_family;
1787
1788   /* if this is an IPv4-mapped address then do IPv4 QoS */
1789   if (af == AF_INET6) {
1790
1791     if (IN6_IS_ADDR_V4MAPPED (&sa.sa_in6.sin6_addr))
1792       af = AF_INET;
1793   }
1794
1795   /* extract and shift 6 bits of the DSCP */
1796   tos = (qos_dscp & 0x3f) << 2;
1797
1798   switch (af) {
1799     case AF_INET:
1800       if (SETSOCKOPT (conn->fd.fd, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)) < 0)
1801         goto no_setsockopt;
1802       break;
1803     case AF_INET6:
1804 #ifdef IPV6_TCLASS
1805       if (SETSOCKOPT (conn->fd.fd, IPPROTO_IPV6, IPV6_TCLASS, &tos,
1806               sizeof (tos)) < 0)
1807         goto no_setsockopt;
1808       break;
1809 #endif
1810     default:
1811       goto wrong_family;
1812   }
1813
1814   return GST_RTSP_OK;
1815
1816   /* ERRORS */
1817 no_getsockname:
1818 no_setsockopt:
1819   {
1820     return GST_RTSP_ESYS;
1821   }
1822
1823 wrong_family:
1824   {
1825     return GST_RTSP_ERROR;
1826   }
1827 }
1828
1829 /**
1830  * gst_rtsp_connection_get_ip:
1831  * @conn: a #GstRTSPConnection
1832  *
1833  * Retrieve the IP address of the other end of @conn.
1834  *
1835  * Returns: The IP address as a string. this value remains valid until the
1836  * connection is closed.
1837  *
1838  * Since: 0.10.20
1839  */
1840 const gchar *
1841 gst_rtsp_connection_get_ip (const GstRTSPConnection * conn)
1842 {
1843   g_return_val_if_fail (conn != NULL, NULL);
1844
1845   return conn->ip;
1846 }
1847
1848 #define READ_COND   (G_IO_IN | G_IO_HUP | G_IO_ERR)
1849 #define WRITE_COND  (G_IO_OUT | G_IO_ERR)
1850
1851 typedef struct
1852 {
1853   GString *str;
1854   guint cseq;
1855 } GstRTSPRec;
1856
1857 /* async functions */
1858 struct _GstRTSPWatch
1859 {
1860   GSource source;
1861
1862   GstRTSPConnection *conn;
1863
1864   GstRTSPBuilder builder;
1865   GstRTSPMessage message;
1866
1867   GPollFD readfd;
1868   GPollFD writefd;
1869   gboolean write_added;
1870
1871   /* queued message for transmission */
1872   GList *messages;
1873   guint8 *write_data;
1874   guint write_off;
1875   guint write_len;
1876   guint write_cseq;
1877
1878   GstRTSPWatchFuncs funcs;
1879
1880   gpointer user_data;
1881   GDestroyNotify notify;
1882 };
1883
1884 static gboolean
1885 gst_rtsp_source_prepare (GSource * source, gint * timeout)
1886 {
1887   GstRTSPWatch *watch = (GstRTSPWatch *) source;
1888
1889   *timeout = (watch->conn->timeout * 1000);
1890
1891   return FALSE;
1892 }
1893
1894 static gboolean
1895 gst_rtsp_source_check (GSource * source)
1896 {
1897   GstRTSPWatch *watch = (GstRTSPWatch *) source;
1898
1899   if (watch->readfd.revents & READ_COND)
1900     return TRUE;
1901
1902   if (watch->writefd.revents & WRITE_COND)
1903     return TRUE;
1904
1905   return FALSE;
1906 }
1907
1908 static gboolean
1909 gst_rtsp_source_dispatch (GSource * source, GSourceFunc callback,
1910     gpointer user_data)
1911 {
1912   GstRTSPWatch *watch = (GstRTSPWatch *) source;
1913   GstRTSPResult res;
1914
1915   /* first read as much as we can */
1916   if (watch->readfd.revents & READ_COND) {
1917     do {
1918       res = build_next (&watch->builder, &watch->message, watch->conn);
1919       if (res == GST_RTSP_EINTR)
1920         break;
1921       if (res == GST_RTSP_EEOF)
1922         goto eof;
1923       if (res != GST_RTSP_OK)
1924         goto error;
1925
1926       if (watch->funcs.message_received)
1927         watch->funcs.message_received (watch, &watch->message,
1928             watch->user_data);
1929
1930       gst_rtsp_message_unset (&watch->message);
1931       build_reset (&watch->builder);
1932     } while (FALSE);
1933   }
1934
1935   if (watch->writefd.revents & WRITE_COND) {
1936     do {
1937       if (watch->write_data == NULL) {
1938         GstRTSPRec *data;
1939
1940         if (!watch->messages)
1941           goto done;
1942
1943         /* no data, get a new message from the queue */
1944         data = watch->messages->data;
1945         watch->messages = g_list_delete_link (watch->messages, watch->messages);
1946
1947         watch->write_off = 0;
1948         watch->write_len = data->str->len;
1949         watch->write_data = (guint8 *) g_string_free (data->str, FALSE);
1950         watch->write_cseq = data->cseq;
1951
1952         g_slice_free (GstRTSPRec, data);
1953       }
1954
1955       res = write_bytes (watch->writefd.fd, watch->write_data,
1956           &watch->write_off, watch->write_len);
1957       if (res == GST_RTSP_EINTR)
1958         break;
1959       if (res != GST_RTSP_OK)
1960         goto error;
1961
1962       if (watch->funcs.message_sent)
1963         watch->funcs.message_sent (watch, watch->write_cseq, watch->user_data);
1964
1965     done:
1966       if (watch->messages == NULL && watch->write_added) {
1967         g_source_remove_poll ((GSource *) watch, &watch->writefd);
1968         watch->write_added = FALSE;
1969         watch->writefd.revents = 0;
1970       }
1971       g_free (watch->write_data);
1972       watch->write_data = NULL;
1973     } while (FALSE);
1974   }
1975
1976   return TRUE;
1977
1978   /* ERRORS */
1979 eof:
1980   {
1981     if (watch->funcs.closed)
1982       watch->funcs.closed (watch, watch->user_data);
1983     return FALSE;
1984   }
1985 error:
1986   {
1987     if (watch->funcs.error)
1988       watch->funcs.error (watch, res, watch->user_data);
1989     return FALSE;
1990   }
1991 }
1992
1993 static void
1994 gst_rtsp_source_finalize (GSource * source)
1995 {
1996   GstRTSPWatch *watch = (GstRTSPWatch *) source;
1997   GList *walk;
1998
1999   build_reset (&watch->builder);
2000
2001   for (walk = watch->messages; walk; walk = g_list_next (walk)) {
2002     GstRTSPRec *data = walk->data;
2003
2004     g_string_free (data->str, TRUE);
2005     g_slice_free (GstRTSPRec, data);
2006   }
2007   g_list_free (watch->messages);
2008   g_free (watch->write_data);
2009
2010   if (watch->notify)
2011     watch->notify (watch->user_data);
2012 }
2013
2014 static GSourceFuncs gst_rtsp_source_funcs = {
2015   gst_rtsp_source_prepare,
2016   gst_rtsp_source_check,
2017   gst_rtsp_source_dispatch,
2018   gst_rtsp_source_finalize
2019 };
2020
2021 /**
2022  * gst_rtsp_watch_new:
2023  * @conn: a #GstRTSPConnection
2024  * @funcs: watch functions
2025  * @user_data: user data to pass to @funcs
2026  *
2027  * Create a watch object for @conn. The functions provided in @funcs will be
2028  * called with @user_data when activity happened on the watch.
2029  *
2030  * The new watch is usually created so that it can be attached to a
2031  * maincontext with gst_rtsp_watch_attach(). 
2032  *
2033  * @conn must exist for the entire lifetime of the watch.
2034  *
2035  * Returns: a #GstRTSPWatch that can be used for asynchronous RTSP
2036  * communication. Free with gst_rtsp_watch_unref () after usage.
2037  *
2038  * Since: 0.10.23
2039  */
2040 GstRTSPWatch *
2041 gst_rtsp_watch_new (GstRTSPConnection * conn,
2042     GstRTSPWatchFuncs * funcs, gpointer user_data, GDestroyNotify notify)
2043 {
2044   GstRTSPWatch *result;
2045
2046   g_return_val_if_fail (conn != NULL, NULL);
2047   g_return_val_if_fail (funcs != NULL, NULL);
2048
2049   result = (GstRTSPWatch *) g_source_new (&gst_rtsp_source_funcs,
2050       sizeof (GstRTSPWatch));
2051
2052   result->conn = conn;
2053   result->builder.state = STATE_START;
2054
2055   result->readfd.fd = conn->fd.fd;
2056   result->readfd.events = READ_COND;
2057   result->readfd.revents = 0;
2058
2059   result->writefd.fd = conn->fd.fd;
2060   result->writefd.events = WRITE_COND;
2061   result->writefd.revents = 0;
2062   result->write_added = FALSE;
2063
2064   result->funcs = *funcs;
2065   result->user_data = user_data;
2066   result->notify = notify;
2067
2068   /* only add the read fd, the write fd is only added when we have data
2069    * to send. */
2070   g_source_add_poll ((GSource *) result, &result->readfd);
2071
2072   return result;
2073 }
2074
2075 /**
2076  * gst_rtsp_watch_attach:
2077  * @watch: a #GstRTSPWatch
2078  * @context: a GMainContext (if NULL, the default context will be used)
2079  *
2080  * Adds a #GstRTSPWatch to a context so that it will be executed within that context.
2081  *
2082  * Returns: the ID (greater than 0) for the watch within the GMainContext. 
2083  *
2084  * Since: 0.10.23
2085  */
2086 guint
2087 gst_rtsp_watch_attach (GstRTSPWatch * watch, GMainContext * context)
2088 {
2089   g_return_val_if_fail (watch != NULL, 0);
2090
2091   return g_source_attach ((GSource *) watch, context);
2092 }
2093
2094 /**
2095  * gst_rtsp_watch_free:
2096  * @watch: a #GstRTSPWatch
2097  *
2098  * Decreases the reference count of @watch by one. If the resulting reference
2099  * count is zero the watch and associated memory will be destroyed.
2100  *
2101  * Since: 0.10.23
2102  */
2103 void
2104 gst_rtsp_watch_unref (GstRTSPWatch * watch)
2105 {
2106   g_return_if_fail (watch != NULL);
2107
2108   g_source_unref ((GSource *) watch);
2109 }
2110
2111 /**
2112  * gst_rtsp_watch_queue_message:
2113  * @watch: a #GstRTSPWatch
2114  * @message: a #GstRTSPMessage
2115  *
2116  * Queue a @message for transmission in @watch. The contents of this 
2117  * message will be serialized and transmitted when the connection of the
2118  * watch becomes writable.
2119  *
2120  * The return value of this function will be returned as the cseq argument in
2121  * the message_sent callback.
2122  *
2123  * Returns: the sequence number of the message or -1 if the cseq could not be
2124  * determined.
2125  *
2126  * Since: 0.10.23
2127  */
2128 guint
2129 gst_rtsp_watch_queue_message (GstRTSPWatch * watch, GstRTSPMessage * message)
2130 {
2131   GstRTSPRec *data;
2132   gchar *header;
2133   guint cseq;
2134
2135   g_return_val_if_fail (watch != NULL, GST_RTSP_EINVAL);
2136   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2137
2138   /* get the cseq from the message, when we finish writing this message on the
2139    * socket we will have to pass the cseq to the callback. */
2140   if (gst_rtsp_message_get_header (message, GST_RTSP_HDR_CSEQ, &header,
2141           0) == GST_RTSP_OK) {
2142     cseq = atoi (header);
2143   } else {
2144     cseq = -1;
2145   }
2146
2147   /* make a record with the message as a string ans cseq */
2148   data = g_slice_new (GstRTSPRec);
2149   data->str = message_to_string (watch->conn, message);
2150   data->cseq = cseq;
2151
2152   /* add the record to a queue */
2153   watch->messages = g_list_append (watch->messages, data);
2154
2155   /* make sure the main context will now also check for writability on the
2156    * socket */
2157   if (!watch->write_added) {
2158     g_source_add_poll ((GSource *) watch, &watch->writefd);
2159     watch->write_added = TRUE;
2160   }
2161   return cseq;
2162 }