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