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