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