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