Move SDP and RTSP from helper objects in -good to a reusable library.
[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 #ifdef HAVE_CONFIG_H
44 #  include <config.h>
45 #endif
46
47 #include <stdio.h>
48 #include <errno.h>
49 #include <unistd.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <fcntl.h>
53 #include <time.h>
54
55
56 /* we include this here to get the G_OS_* defines */
57 #include <glib.h>
58
59 #ifdef G_OS_WIN32
60 #include <winsock2.h>
61 #define EINPROGRESS WSAEINPROGRESS
62 #else
63 #include <sys/ioctl.h>
64 #include <netdb.h>
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #endif
69
70 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
71 #include <sys/filio.h>
72 #endif
73
74 #include "gstrtspconnection.h"
75 #include "gstrtspbase64.h"
76
77 /* the select call is also performed on the control sockets, that way
78  * we can send special commands to unlock or restart the select call */
79 #define CONTROL_RESTART        'R'      /* restart the select call */
80 #define CONTROL_STOP           'S'      /* stop the select call */
81 #define CONTROL_SOCKETS(conn)  conn->control_sock
82 #define WRITE_SOCKET(conn)     conn->control_sock[1]
83 #define READ_SOCKET(conn)      conn->control_sock[0]
84
85 #define SEND_COMMAND(conn, command)              \
86 G_STMT_START {                                  \
87   unsigned char c; c = command;                 \
88   write (WRITE_SOCKET(conn), &c, 1);             \
89 } G_STMT_END
90
91 #define READ_COMMAND(conn, command, res)         \
92 G_STMT_START {                                  \
93   res = read(READ_SOCKET(conn), &command, 1);    \
94 } G_STMT_END
95
96 #ifdef G_OS_WIN32
97 #define IOCTL_SOCKET ioctlsocket
98 #define CLOSE_SOCKET(sock) closesocket(sock);
99 #else
100 #define IOCTL_SOCKET ioctl
101 #define CLOSE_SOCKET(sock) close(sock);
102 #endif
103
104 #ifdef G_OS_WIN32
105 static int
106 inet_aton (const char *c, struct in_addr *paddr)
107 {
108   /* note that inet_addr is deprecated on unix because
109    * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
110    * address. */
111   paddr->s_addr = inet_addr (c);
112
113   if (paddr->s_addr == INADDR_NONE)
114     return 0;
115
116   return 1;
117 }
118 #endif
119
120 GstRTSPResult
121 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
122 {
123   gint ret;
124   GstRTSPConnection *newconn;
125
126 #ifdef G_OS_WIN32
127   unsigned long flags;
128 #endif /* G_OS_WIN32 */
129
130   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
131
132   newconn = g_new0 (GstRTSPConnection, 1);
133
134 #ifdef G_OS_WIN32
135   /* This should work on UNIX too. PF_UNIX sockets replaced with pipe */
136   /* pipe( CONTROL_SOCKETS(newconn) ) */
137   if ((ret = pipe (CONTROL_SOCKETS (newconn))) < 0)
138     goto no_socket_pair;
139
140   ioctlsocket (READ_SOCKET (newconn), FIONBIO, &flags);
141   ioctlsocket (WRITE_SOCKET (newconn), FIONBIO, &flags);
142 #else
143   if ((ret =
144           socketpair (PF_UNIX, SOCK_STREAM, 0, CONTROL_SOCKETS (newconn))) < 0)
145     goto no_socket_pair;
146
147   fcntl (READ_SOCKET (newconn), F_SETFL, O_NONBLOCK);
148   fcntl (WRITE_SOCKET (newconn), F_SETFL, O_NONBLOCK);
149 #endif
150
151   newconn->url = url;
152   newconn->fd = -1;
153   newconn->timer = g_timer_new ();
154
155   newconn->auth_method = GST_RTSP_AUTH_NONE;
156   newconn->username = NULL;
157   newconn->passwd = NULL;
158
159   *conn = newconn;
160
161   return GST_RTSP_OK;
162
163   /* ERRORS */
164 no_socket_pair:
165   {
166     g_free (newconn);
167     return GST_RTSP_ESYS;
168   }
169 }
170
171 GstRTSPResult
172 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
173 {
174   gint fd;
175   struct sockaddr_in sa_in;
176   struct hostent *hostinfo;
177   char **addrs;
178   const gchar *ip;
179   gchar ipbuf[INET_ADDRSTRLEN];
180   struct in_addr addr;
181   gint ret;
182   guint16 port;
183   GstRTSPUrl *url;
184   fd_set writefds;
185   fd_set readfds;
186   struct timeval tv, *tvp;
187   gint max_fd, retval;
188
189 #ifdef G_OS_WIN32
190   unsigned long flags;
191 #endif /* G_OS_WIN32 */
192
193   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
194   g_return_val_if_fail (conn->url != NULL, GST_RTSP_EINVAL);
195   g_return_val_if_fail (conn->fd < 0, GST_RTSP_EINVAL);
196
197   url = conn->url;
198
199   /* first check if it already is an IP address */
200   if (inet_aton (url->host, &addr)) {
201     ip = url->host;
202   } else {
203     hostinfo = gethostbyname (url->host);
204     if (!hostinfo)
205       goto not_resolved;        /* h_errno set */
206
207     if (hostinfo->h_addrtype != AF_INET)
208       goto not_ip;              /* host not an IP host */
209
210     addrs = hostinfo->h_addr_list;
211     ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
212         sizeof (ipbuf));
213   }
214
215   /* get the port from the url */
216   gst_rtsp_url_get_port (url, &port);
217
218   memset (&sa_in, 0, sizeof (sa_in));
219   sa_in.sin_family = AF_INET;   /* network socket */
220   sa_in.sin_port = htons (port);        /* on port */
221   sa_in.sin_addr.s_addr = inet_addr (ip);       /* on host ip */
222
223   fd = socket (AF_INET, SOCK_STREAM, 0);
224   if (fd == -1)
225     goto sys_error;
226
227   /* set to non-blocking mode so that we can cancel the connect */
228 #ifndef G_OS_WIN32
229   fcntl (fd, F_SETFL, O_NONBLOCK);
230 #else
231   ioctlsocket (fd, FIONBIO, &flags);
232 #endif /* G_OS_WIN32 */
233
234   /* we are going to connect ASYNC now */
235   ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
236   if (ret == 0)
237     goto done;
238   if (errno != EINPROGRESS)
239     goto sys_error;
240
241   /* wait for connect to complete up to the specified timeout or until we got
242    * interrupted. */
243   FD_ZERO (&writefds);
244   FD_SET (fd, &writefds);
245   FD_ZERO (&readfds);
246   FD_SET (READ_SOCKET (conn), &readfds);
247
248   if (timeout->tv_sec != 0 || timeout->tv_usec != 0) {
249     tv.tv_sec = timeout->tv_sec;
250     tv.tv_usec = timeout->tv_usec;
251     tvp = &tv;
252   } else {
253     tvp = NULL;
254   }
255
256   max_fd = MAX (fd, READ_SOCKET (conn));
257
258   do {
259     retval = select (max_fd + 1, &readfds, &writefds, NULL, tvp);
260   } while ((retval == -1 && errno == EINTR));
261
262   if (retval == 0)
263     goto timeout;
264   else if (retval == -1)
265     goto sys_error;
266
267 done:
268   conn->fd = fd;
269   conn->ip = g_strdup (ip);
270
271   return GST_RTSP_OK;
272
273 sys_error:
274   {
275     if (fd != -1)
276       CLOSE_SOCKET (fd);
277     return GST_RTSP_ESYS;
278   }
279 not_resolved:
280   {
281     return GST_RTSP_ENET;
282   }
283 not_ip:
284   {
285     return GST_RTSP_ENOTIP;
286   }
287 timeout:
288   {
289     return GST_RTSP_ETIMEOUT;
290   }
291 }
292
293 static void
294 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
295 {
296   switch (conn->auth_method) {
297     case GST_RTSP_AUTH_BASIC:{
298       gchar *user_pass =
299           g_strdup_printf ("%s:%s", conn->username, conn->passwd);
300       gchar *user_pass64 =
301           gst_rtsp_base64_encode (user_pass, strlen (user_pass));
302       gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
303
304       gst_rtsp_message_add_header (message, GST_RTSP_HDR_AUTHORIZATION,
305           auth_string);
306
307       g_free (user_pass);
308       g_free (user_pass64);
309       g_free (auth_string);
310       break;
311     }
312     default:
313       /* Nothing to do */
314       break;
315   }
316 }
317
318 static void
319 add_date_header (GstRTSPMessage * message)
320 {
321   GTimeVal tv;
322   gchar date_string[100];
323
324   g_get_current_time (&tv);
325   strftime (date_string, sizeof (date_string), "%a, %d %b %Y %H:%M:%S GMT",
326       gmtime (&tv.tv_sec));
327
328   gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
329 }
330
331 GstRTSPResult
332 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
333     guint size, GTimeVal * timeout)
334 {
335   guint towrite;
336   fd_set writefds;
337   fd_set readfds;
338   int max_fd;
339   gint retval;
340   struct timeval tv, *tvp;
341
342   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
343   g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
344
345   FD_ZERO (&writefds);
346   FD_SET (conn->fd, &writefds);
347   FD_ZERO (&readfds);
348   FD_SET (READ_SOCKET (conn), &readfds);
349
350   max_fd = MAX (conn->fd, READ_SOCKET (conn));
351
352   if (timeout) {
353     tv.tv_sec = timeout->tv_sec;
354     tv.tv_usec = timeout->tv_usec;
355     tvp = &tv;
356   } else {
357     tvp = NULL;
358   }
359
360   towrite = size;
361
362   while (towrite > 0) {
363     gint written;
364
365     do {
366       retval = select (max_fd + 1, &readfds, &writefds, NULL, tvp);
367     } while ((retval == -1 && errno == EINTR));
368
369     if (retval == 0)
370       goto timeout;
371
372     if (retval == -1)
373       goto select_error;
374
375     if (FD_ISSET (READ_SOCKET (conn), &readfds)) {
376       /* read all stop commands */
377       while (TRUE) {
378         gchar command;
379         int res;
380
381         READ_COMMAND (conn, command, res);
382         if (res <= 0) {
383           /* no more commands */
384           break;
385         }
386       }
387       goto stopped;
388     }
389
390     /* now we can write */
391     written = write (conn->fd, data, towrite);
392     if (written < 0) {
393       if (errno != EAGAIN && errno != EINTR)
394         goto write_error;
395     } else {
396       towrite -= written;
397       data += written;
398     }
399   }
400   return GST_RTSP_OK;
401
402   /* ERRORS */
403 timeout:
404   {
405     return GST_RTSP_ETIMEOUT;
406   }
407 select_error:
408   {
409     return GST_RTSP_ESYS;
410   }
411 stopped:
412   {
413     return GST_RTSP_EINTR;
414   }
415 write_error:
416   {
417     return GST_RTSP_ESYS;
418   }
419 }
420
421 GstRTSPResult
422 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
423     GTimeVal * timeout)
424 {
425   GString *str = NULL;
426   GstRTSPResult res;
427
428 #ifdef G_OS_WIN32
429   WSADATA w;
430   int error;
431 #endif
432
433   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
434   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
435
436 #ifdef G_OS_WIN32
437   error = WSAStartup (0x0202, &w);
438
439   if (error)
440     goto startup_error;
441
442   if (w.wVersion != 0x0202)
443     goto version_error;
444 #endif
445
446   str = g_string_new ("");
447
448   switch (message->type) {
449     case GST_RTSP_MESSAGE_REQUEST:
450       /* create request string, add CSeq */
451       g_string_append_printf (str, "%s %s RTSP/1.0\r\n"
452           "CSeq: %d\r\n",
453           gst_rtsp_method_as_text (message->type_data.request.method),
454           message->type_data.request.uri, conn->cseq++);
455       /* add session id if we have one */
456       if (conn->session_id[0] != '\0') {
457         gst_rtsp_message_add_header (message, GST_RTSP_HDR_SESSION,
458             conn->session_id);
459       }
460       /* add any authentication headers */
461       add_auth_header (conn, message);
462       break;
463     case GST_RTSP_MESSAGE_RESPONSE:
464       /* create response string */
465       g_string_append_printf (str, "RTSP/1.0 %d %s\r\n",
466           message->type_data.response.code, message->type_data.response.reason);
467       break;
468     case GST_RTSP_MESSAGE_DATA:
469     {
470       guint8 data_header[4];
471
472       /* prepare data header */
473       data_header[0] = '$';
474       data_header[1] = message->type_data.data.channel;
475       data_header[2] = (message->body_size >> 8) & 0xff;
476       data_header[3] = message->body_size & 0xff;
477
478       /* create string with header and data */
479       str = g_string_append_len (str, (gchar *) data_header, 4);
480       str =
481           g_string_append_len (str, (gchar *) message->body,
482           message->body_size);
483       break;
484     }
485     default:
486       g_assert_not_reached ();
487       break;
488   }
489
490   /* append headers and body */
491   if (message->type != GST_RTSP_MESSAGE_DATA) {
492     /* add date header */
493     add_date_header (message);
494
495     /* append headers */
496     gst_rtsp_message_append_headers (message, str);
497
498     /* append Content-Length and body if needed */
499     if (message->body != NULL && message->body_size > 0) {
500       gchar *len;
501
502       len = g_strdup_printf ("%d", message->body_size);
503       g_string_append_printf (str, "%s: %s\r\n",
504           gst_rtsp_header_as_text (GST_RTSP_HDR_CONTENT_LENGTH), len);
505       g_free (len);
506       /* header ends here */
507       g_string_append (str, "\r\n");
508       str =
509           g_string_append_len (str, (gchar *) message->body,
510           message->body_size);
511     } else {
512       /* just end headers */
513       g_string_append (str, "\r\n");
514     }
515   }
516
517   /* write request */
518   res =
519       gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len, timeout);
520
521   g_string_free (str, TRUE);
522
523   return res;
524
525 #ifdef G_OS_WIN32
526 startup_error:
527   {
528     g_warning ("Error %d on WSAStartup", error);
529     return GST_RTSP_EWSASTART;
530   }
531 version_error:
532   {
533     g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
534         w.wVersion);
535     WSACleanup ();
536     return GST_RTSP_EWSAVERSION;
537   }
538 #endif
539 }
540
541 static GstRTSPResult
542 read_line (gint fd, gchar * buffer, guint size)
543 {
544   guint idx;
545   gchar c;
546   gint r;
547
548   idx = 0;
549   while (TRUE) {
550     r = read (fd, &c, 1);
551     if (r == 0) {
552       goto eof;
553     } else if (r < 0) {
554       if (errno != EAGAIN && errno != EINTR)
555         goto read_error;
556     } else {
557       if (c == '\n')            /* end on \n */
558         break;
559       if (c == '\r')            /* ignore \r */
560         continue;
561
562       if (idx < size - 1)
563         buffer[idx++] = c;
564     }
565   }
566   buffer[idx] = '\0';
567
568   return GST_RTSP_OK;
569
570 eof:
571   {
572     return GST_RTSP_EEOF;
573   }
574 read_error:
575   {
576     return GST_RTSP_ESYS;
577   }
578 }
579
580 static void
581 read_string (gchar * dest, gint size, gchar ** src)
582 {
583   gint idx;
584
585   idx = 0;
586   /* skip spaces */
587   while (g_ascii_isspace (**src))
588     (*src)++;
589
590   while (!g_ascii_isspace (**src) && **src != '\0') {
591     if (idx < size - 1)
592       dest[idx++] = **src;
593     (*src)++;
594   }
595   if (size > 0)
596     dest[idx] = '\0';
597 }
598
599 static void
600 read_key (gchar * dest, gint size, gchar ** src)
601 {
602   gint idx;
603
604   idx = 0;
605   while (**src != ':' && **src != '\0') {
606     if (idx < size - 1)
607       dest[idx++] = **src;
608     (*src)++;
609   }
610   if (size > 0)
611     dest[idx] = '\0';
612 }
613
614 static GstRTSPResult
615 parse_response_status (gchar * buffer, GstRTSPMessage * msg)
616 {
617   GstRTSPResult res;
618   gchar versionstr[20];
619   gchar codestr[4];
620   gint code;
621   gchar *bptr;
622
623   bptr = buffer;
624
625   read_string (versionstr, sizeof (versionstr), &bptr);
626   read_string (codestr, sizeof (codestr), &bptr);
627   code = atoi (codestr);
628
629   while (g_ascii_isspace (*bptr))
630     bptr++;
631
632   if (strcmp (versionstr, "RTSP/1.0") == 0)
633     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
634         parse_error);
635   else if (strncmp (versionstr, "RTSP/", 5) == 0) {
636     GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
637         parse_error);
638     msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
639   } else
640     goto parse_error;
641
642   return GST_RTSP_OK;
643
644 parse_error:
645   {
646     return GST_RTSP_EPARSE;
647   }
648 }
649
650 static GstRTSPResult
651 parse_request_line (gchar * buffer, GstRTSPMessage * msg)
652 {
653   GstRTSPResult res = GST_RTSP_OK;
654   gchar versionstr[20];
655   gchar methodstr[20];
656   gchar urlstr[4096];
657   gchar *bptr;
658   GstRTSPMethod method;
659
660   bptr = buffer;
661
662   read_string (methodstr, sizeof (methodstr), &bptr);
663   method = gst_rtsp_find_method (methodstr);
664
665   read_string (urlstr, sizeof (urlstr), &bptr);
666   if (*urlstr == '\0')
667     res = GST_RTSP_EPARSE;
668
669   read_string (versionstr, sizeof (versionstr), &bptr);
670
671   if (*bptr != '\0')
672     res = GST_RTSP_EPARSE;
673
674   if (strcmp (versionstr, "RTSP/1.0") == 0) {
675     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
676       res = GST_RTSP_EPARSE;
677   } else if (strncmp (versionstr, "RTSP/", 5) == 0) {
678     if (gst_rtsp_message_init_request (msg, method, urlstr) != GST_RTSP_OK)
679       res = GST_RTSP_EPARSE;
680     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
681   } else {
682     gst_rtsp_message_init_request (msg, method, urlstr);
683     msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
684     res = GST_RTSP_EPARSE;
685   }
686
687   return res;
688 }
689
690 /* parsing lines means reading a Key: Value pair */
691 static GstRTSPResult
692 parse_line (gchar * buffer, GstRTSPMessage * msg)
693 {
694   gchar key[32];
695   gchar *bptr;
696   GstRTSPHeaderField field;
697
698   bptr = buffer;
699
700   /* read key */
701   read_key (key, sizeof (key), &bptr);
702   if (*bptr != ':')
703     goto no_column;
704
705   bptr++;
706
707   field = gst_rtsp_find_header_field (key);
708   if (field != GST_RTSP_HDR_INVALID) {
709     while (g_ascii_isspace (*bptr))
710       bptr++;
711     gst_rtsp_message_add_header (msg, field, bptr);
712   }
713
714   return GST_RTSP_OK;
715
716 no_column:
717   {
718     return GST_RTSP_EPARSE;
719   }
720 }
721
722 GstRTSPResult
723 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
724     GTimeVal * timeout)
725 {
726   fd_set readfds;
727   guint toread;
728   gint retval;
729   struct timeval tv_timeout, *ptv_timeout = NULL;
730
731 #ifndef G_OS_WIN32
732   gint avail;
733 #else
734   gulong avail;
735 #endif
736
737   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
738   g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
739
740   if (size == 0)
741     return GST_RTSP_OK;
742
743   toread = size;
744
745   /* if the call fails, just go in the select.. it should not fail. Else if
746    * there is enough data to read, skip the select call al together.*/
747   if (IOCTL_SOCKET (conn->fd, FIONREAD, &avail) < 0)
748     avail = 0;
749   else if (avail >= toread)
750     goto do_read;
751
752   /* configure timeout if any */
753   if (timeout != NULL) {
754     tv_timeout.tv_sec = timeout->tv_sec;
755     tv_timeout.tv_usec = timeout->tv_usec;
756     ptv_timeout = &tv_timeout;
757   }
758
759   FD_ZERO (&readfds);
760   FD_SET (conn->fd, &readfds);
761   FD_SET (READ_SOCKET (conn), &readfds);
762
763   while (toread > 0) {
764     gint bytes;
765
766     do {
767       retval = select (FD_SETSIZE, &readfds, NULL, NULL, ptv_timeout);
768     } while ((retval == -1 && errno == EINTR));
769
770     if (retval == -1)
771       goto select_error;
772
773     /* check for timeout */
774     if (retval == 0)
775       goto select_timeout;
776
777     if (FD_ISSET (READ_SOCKET (conn), &readfds)) {
778       /* read all stop commands */
779       while (TRUE) {
780         gchar command;
781         int res;
782
783         READ_COMMAND (conn, command, res);
784         if (res <= 0) {
785           /* no more commands */
786           break;
787         }
788       }
789       goto stopped;
790     }
791
792   do_read:
793     /* if we get here there is activity on the real fd since the select
794      * completed and the control socket was not readable. */
795     bytes = read (conn->fd, data, toread);
796
797     if (bytes == 0) {
798       goto eof;
799     } else if (bytes < 0) {
800       if (errno != EAGAIN && errno != EINTR)
801         goto read_error;
802     } else {
803       toread -= bytes;
804       data += bytes;
805     }
806   }
807   return GST_RTSP_OK;
808
809   /* ERRORS */
810 select_error:
811   {
812     return GST_RTSP_ESYS;
813   }
814 select_timeout:
815   {
816     return GST_RTSP_ETIMEOUT;
817   }
818 stopped:
819   {
820     return GST_RTSP_EINTR;
821   }
822 eof:
823   {
824     return GST_RTSP_EEOF;
825   }
826 read_error:
827   {
828     return GST_RTSP_ESYS;
829   }
830 }
831
832 static GstRTSPResult
833 read_body (GstRTSPConnection * conn, glong content_length, GstRTSPMessage * msg,
834     GTimeVal * timeout)
835 {
836   guint8 *body;
837   GstRTSPResult res;
838
839   if (content_length <= 0) {
840     body = NULL;
841     content_length = 0;
842     goto done;
843   }
844
845   body = g_malloc (content_length + 1);
846   body[content_length] = '\0';
847
848   GST_RTSP_CHECK (gst_rtsp_connection_read (conn, body, content_length,
849           timeout), read_error);
850
851   content_length += 1;
852
853 done:
854   gst_rtsp_message_take_body (msg, (guint8 *) body, content_length);
855
856   return GST_RTSP_OK;
857
858   /* ERRORS */
859 read_error:
860   {
861     g_free (body);
862     return res;
863   }
864 }
865
866 GstRTSPResult
867 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * msg,
868     GTimeVal * timeout)
869 {
870   gchar buffer[4096];
871   gint line;
872   glong content_length;
873   GstRTSPResult res;
874   gboolean need_body;
875
876   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
877   g_return_val_if_fail (msg != NULL, GST_RTSP_EINVAL);
878
879   line = 0;
880
881   need_body = TRUE;
882
883   res = GST_RTSP_OK;
884   /* parse first line and headers */
885   while (res == GST_RTSP_OK) {
886     guint8 c;
887
888     /* read first character, this identifies data messages */
889     GST_RTSP_CHECK (gst_rtsp_connection_read (conn, &c, 1, timeout),
890         read_error);
891
892     /* check for data packet, first character is $ */
893     if (c == '$') {
894       guint16 size;
895
896       /* data packets are $<1 byte channel><2 bytes length,BE><data bytes> */
897
898       /* read channel, which is the next char */
899       GST_RTSP_CHECK (gst_rtsp_connection_read (conn, &c, 1, timeout),
900           read_error);
901
902       /* now we create a data message */
903       gst_rtsp_message_init_data (msg, c);
904
905       /* next two bytes are the length of the data */
906       GST_RTSP_CHECK (gst_rtsp_connection_read (conn, (guint8 *) & size, 2,
907               timeout), read_error);
908
909       size = GUINT16_FROM_BE (size);
910
911       /* and read the body */
912       res = read_body (conn, size, msg, timeout);
913       need_body = FALSE;
914       break;
915     } else {
916       gint offset = 0;
917
918       /* we have a regular response */
919       if (c != '\r') {
920         buffer[0] = c;
921         offset = 1;
922       }
923       /* should not happen */
924       if (c == '\n')
925         break;
926
927       /* read lines */
928       GST_RTSP_CHECK (read_line (conn->fd, buffer + offset,
929               sizeof (buffer) - offset), read_error);
930
931       if (buffer[0] == '\0')
932         break;
933
934       if (line == 0) {
935         /* first line, check for response status */
936         if (g_str_has_prefix (buffer, "RTSP")) {
937           res = parse_response_status (buffer, msg);
938         } else {
939           res = parse_request_line (buffer, msg);
940         }
941       } else {
942         /* else just parse the line */
943         parse_line (buffer, msg);
944       }
945     }
946     line++;
947   }
948
949   /* read the rest of the body if needed */
950   if (need_body) {
951     gchar *session_id;
952     gchar *hdrval;
953
954     /* see if there is a Content-Length header */
955     if (gst_rtsp_message_get_header (msg, GST_RTSP_HDR_CONTENT_LENGTH,
956             &hdrval, 0) == GST_RTSP_OK) {
957       /* there is, read the body */
958       content_length = atol (hdrval);
959       GST_RTSP_CHECK (read_body (conn, content_length, msg, timeout),
960           read_error);
961     }
962
963     /* save session id in the connection for further use */
964     if (gst_rtsp_message_get_header (msg, GST_RTSP_HDR_SESSION,
965             &session_id, 0) == GST_RTSP_OK) {
966       gint maxlen, i;
967
968       /* default session timeout */
969       conn->timeout = 60;
970
971       maxlen = sizeof (conn->session_id) - 1;
972       /* the sessionid can have attributes marked with ;
973        * Make sure we strip them */
974       for (i = 0; session_id[i] != '\0'; i++) {
975         if (session_id[i] == ';') {
976           maxlen = i;
977           /* parse timeout */
978           do {
979             i++;
980           } while (g_ascii_isspace (session_id[i]));
981           if (g_str_has_prefix (&session_id[i], "timeout=")) {
982             gint to;
983
984             /* if we parsed something valid, configure */
985             if ((to = atoi (&session_id[i + 9])) > 0)
986               conn->timeout = to;
987           }
988           break;
989         }
990       }
991
992       /* make sure to not overflow */
993       strncpy (conn->session_id, session_id, maxlen);
994       conn->session_id[maxlen] = '\0';
995     }
996   }
997   return res;
998
999 read_error:
1000   {
1001     return res;
1002   }
1003 }
1004
1005 GstRTSPResult
1006 gst_rtsp_connection_close (GstRTSPConnection * conn)
1007 {
1008   gint res;
1009
1010   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1011
1012   g_free (conn->ip);
1013   conn->ip = NULL;
1014
1015   if (conn->fd != -1) {
1016     res = CLOSE_SOCKET (conn->fd);
1017 #ifdef G_OS_WIN32
1018     WSACleanup ();
1019 #endif
1020     conn->fd = -1;
1021     if (res != 0)
1022       goto sys_error;
1023   }
1024
1025   return GST_RTSP_OK;
1026
1027 sys_error:
1028   {
1029     return GST_RTSP_ESYS;
1030   }
1031 }
1032
1033 GstRTSPResult
1034 gst_rtsp_connection_free (GstRTSPConnection * conn)
1035 {
1036   GstRTSPResult res;
1037
1038   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1039
1040 #ifdef G_OS_WIN32
1041   WSACleanup ();
1042 #endif
1043   res = gst_rtsp_connection_close (conn);
1044   g_timer_destroy (conn->timer);
1045   g_free (conn->username);
1046   g_free (conn->passwd);
1047   g_free (conn);
1048
1049   return res;
1050 }
1051
1052 GstRTSPResult
1053 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
1054 {
1055   gdouble elapsed;
1056   glong sec;
1057   gulong usec;
1058
1059   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1060   g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
1061
1062   elapsed = g_timer_elapsed (conn->timer, &usec);
1063   if (elapsed >= conn->timeout) {
1064     sec = 0;
1065     usec = 0;
1066   } else {
1067     sec = conn->timeout - elapsed;
1068   }
1069
1070   timeout->tv_sec = sec;
1071   timeout->tv_usec = usec;
1072
1073   return GST_RTSP_OK;
1074 }
1075
1076 GstRTSPResult
1077 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
1078 {
1079   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1080
1081   g_timer_start (conn->timer);
1082
1083   return GST_RTSP_OK;
1084 }
1085
1086 GstRTSPResult
1087 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
1088 {
1089   g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1090
1091   if (flush) {
1092     SEND_COMMAND (conn, CONTROL_STOP);
1093   } else {
1094     while (TRUE) {
1095       gchar command;
1096       int res;
1097
1098       READ_COMMAND (conn, command, res);
1099       if (res <= 0) {
1100         /* no more commands */
1101         break;
1102       }
1103     }
1104   }
1105   return GST_RTSP_OK;
1106 }
1107
1108 GstRTSPResult
1109 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
1110     GstRTSPAuthMethod method, gchar * user, gchar * pass)
1111 {
1112   /* Digest isn't implemented yet */
1113   if (method == GST_RTSP_AUTH_DIGEST)
1114     return GST_RTSP_ENOTIMPL;
1115
1116   /* Make sure the username and passwd are being set for authentication */
1117   if (method == GST_RTSP_AUTH_NONE && (user == NULL || pass == NULL))
1118     return GST_RTSP_EINVAL;
1119
1120   /* ":" chars are not allowed in usernames for basic auth */
1121   if (method == GST_RTSP_AUTH_BASIC && g_strrstr (user, ":") != NULL)
1122     return GST_RTSP_EINVAL;
1123
1124   g_free (conn->username);
1125   g_free (conn->passwd);
1126
1127   conn->auth_method = method;
1128   conn->username = g_strdup (user);
1129   conn->passwd = g_strdup (pass);
1130
1131   return GST_RTSP_OK;
1132 }