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