2 * Copyright (C) <2005,2006> Wim Taymans <wim@fluendo.com>
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.
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.
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.
20 * Unless otherwise indicated, Source Code is licensed under MIT license.
21 * See further explanation attached in License Statement (distributed in the file
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:
31 * The above copyright notice and this permission notice shall be included in all
32 * copies or substantial portions of the Software.
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
56 /* we include this here to get the G_OS_* defines */
61 #define EINPROGRESS WSAEINPROGRESS
63 #include <sys/ioctl.h>
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
70 #ifdef HAVE_FIONREAD_IN_SYS_FILIO
71 #include <sys/filio.h>
74 #include "gstrtspconnection.h"
75 #include "gstrtspbase64.h"
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]
85 #define SEND_COMMAND(conn, command) \
87 unsigned char c; c = command; \
88 write (WRITE_SOCKET(conn), &c, 1); \
91 #define READ_COMMAND(conn, command, res) \
93 res = read(READ_SOCKET(conn), &command, 1); \
97 #define IOCTL_SOCKET ioctlsocket
98 #define CLOSE_SOCKET(sock) closesocket(sock);
100 #define IOCTL_SOCKET ioctl
101 #define CLOSE_SOCKET(sock) close(sock);
106 inet_aton (const char *c, struct in_addr *paddr)
108 /* note that inet_addr is deprecated on unix because
109 * inet_addr returns -1 (INADDR_NONE) for the valid 255.255.255.255
111 paddr->s_addr = inet_addr (c);
113 if (paddr->s_addr == INADDR_NONE)
121 gst_rtsp_connection_create (GstRTSPUrl * url, GstRTSPConnection ** conn)
124 GstRTSPConnection *newconn;
128 #endif /* G_OS_WIN32 */
130 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
132 newconn = g_new0 (GstRTSPConnection, 1);
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)
140 ioctlsocket (READ_SOCKET (newconn), FIONBIO, &flags);
141 ioctlsocket (WRITE_SOCKET (newconn), FIONBIO, &flags);
144 socketpair (PF_UNIX, SOCK_STREAM, 0, CONTROL_SOCKETS (newconn))) < 0)
147 fcntl (READ_SOCKET (newconn), F_SETFL, O_NONBLOCK);
148 fcntl (WRITE_SOCKET (newconn), F_SETFL, O_NONBLOCK);
153 newconn->timer = g_timer_new ();
155 newconn->auth_method = GST_RTSP_AUTH_NONE;
156 newconn->username = NULL;
157 newconn->passwd = NULL;
167 return GST_RTSP_ESYS;
172 gst_rtsp_connection_connect (GstRTSPConnection * conn, GTimeVal * timeout)
175 struct sockaddr_in sa_in;
176 struct hostent *hostinfo;
179 gchar ipbuf[INET_ADDRSTRLEN];
186 struct timeval tv, *tvp;
191 #endif /* G_OS_WIN32 */
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);
199 /* first check if it already is an IP address */
200 if (inet_aton (url->host, &addr)) {
203 hostinfo = gethostbyname (url->host);
205 goto not_resolved; /* h_errno set */
207 if (hostinfo->h_addrtype != AF_INET)
208 goto not_ip; /* host not an IP host */
210 addrs = hostinfo->h_addr_list;
211 ip = inet_ntop (AF_INET, (struct in_addr *) addrs[0], ipbuf,
215 /* get the port from the url */
216 gst_rtsp_url_get_port (url, &port);
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 */
223 fd = socket (AF_INET, SOCK_STREAM, 0);
227 /* set to non-blocking mode so that we can cancel the connect */
229 fcntl (fd, F_SETFL, O_NONBLOCK);
231 ioctlsocket (fd, FIONBIO, &flags);
232 #endif /* G_OS_WIN32 */
234 /* we are going to connect ASYNC now */
235 ret = connect (fd, (struct sockaddr *) &sa_in, sizeof (sa_in));
238 if (errno != EINPROGRESS)
241 /* wait for connect to complete up to the specified timeout or until we got
244 FD_SET (fd, &writefds);
246 FD_SET (READ_SOCKET (conn), &readfds);
248 if (timeout->tv_sec != 0 || timeout->tv_usec != 0) {
249 tv.tv_sec = timeout->tv_sec;
250 tv.tv_usec = timeout->tv_usec;
256 max_fd = MAX (fd, READ_SOCKET (conn));
259 retval = select (max_fd + 1, &readfds, &writefds, NULL, tvp);
260 } while ((retval == -1 && errno == EINTR));
264 else if (retval == -1)
269 conn->ip = g_strdup (ip);
277 return GST_RTSP_ESYS;
281 return GST_RTSP_ENET;
285 return GST_RTSP_ENOTIP;
289 return GST_RTSP_ETIMEOUT;
294 add_auth_header (GstRTSPConnection * conn, GstRTSPMessage * message)
296 switch (conn->auth_method) {
297 case GST_RTSP_AUTH_BASIC:{
299 g_strdup_printf ("%s:%s", conn->username, conn->passwd);
301 gst_rtsp_base64_encode (user_pass, strlen (user_pass));
302 gchar *auth_string = g_strdup_printf ("Basic %s", user_pass64);
304 gst_rtsp_message_add_header (message, GST_RTSP_HDR_AUTHORIZATION,
308 g_free (user_pass64);
309 g_free (auth_string);
319 add_date_header (GstRTSPMessage * message)
322 gchar date_string[100];
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));
328 gst_rtsp_message_add_header (message, GST_RTSP_HDR_DATE, date_string);
332 gst_rtsp_connection_write (GstRTSPConnection * conn, const guint8 * data,
333 guint size, GTimeVal * timeout)
340 struct timeval tv, *tvp;
342 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
343 g_return_val_if_fail (data != NULL || size == 0, GST_RTSP_EINVAL);
346 FD_SET (conn->fd, &writefds);
348 FD_SET (READ_SOCKET (conn), &readfds);
350 max_fd = MAX (conn->fd, READ_SOCKET (conn));
353 tv.tv_sec = timeout->tv_sec;
354 tv.tv_usec = timeout->tv_usec;
362 while (towrite > 0) {
366 retval = select (max_fd + 1, &readfds, &writefds, NULL, tvp);
367 } while ((retval == -1 && errno == EINTR));
375 if (FD_ISSET (READ_SOCKET (conn), &readfds)) {
376 /* read all stop commands */
381 READ_COMMAND (conn, command, res);
383 /* no more commands */
390 /* now we can write */
391 written = write (conn->fd, data, towrite);
393 if (errno != EAGAIN && errno != EINTR)
405 return GST_RTSP_ETIMEOUT;
409 return GST_RTSP_ESYS;
413 return GST_RTSP_EINTR;
417 return GST_RTSP_ESYS;
422 gst_rtsp_connection_send (GstRTSPConnection * conn, GstRTSPMessage * message,
433 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
434 g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
437 error = WSAStartup (0x0202, &w);
442 if (w.wVersion != 0x0202)
446 str = g_string_new ("");
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"
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,
460 /* add any authentication headers */
461 add_auth_header (conn, message);
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);
468 case GST_RTSP_MESSAGE_DATA:
470 guint8 data_header[4];
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;
478 /* create string with header and data */
479 str = g_string_append_len (str, (gchar *) data_header, 4);
481 g_string_append_len (str, (gchar *) message->body,
486 g_assert_not_reached ();
490 /* append headers and body */
491 if (message->type != GST_RTSP_MESSAGE_DATA) {
492 /* add date header */
493 add_date_header (message);
496 gst_rtsp_message_append_headers (message, str);
498 /* append Content-Length and body if needed */
499 if (message->body != NULL && message->body_size > 0) {
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);
506 /* header ends here */
507 g_string_append (str, "\r\n");
509 g_string_append_len (str, (gchar *) message->body,
512 /* just end headers */
513 g_string_append (str, "\r\n");
519 gst_rtsp_connection_write (conn, (guint8 *) str->str, str->len, timeout);
521 g_string_free (str, TRUE);
528 g_warning ("Error %d on WSAStartup", error);
529 return GST_RTSP_EWSASTART;
533 g_warning ("Windows sockets are not version 0x202 (current 0x%x)",
536 return GST_RTSP_EWSAVERSION;
542 read_line (gint fd, gchar * buffer, guint size)
550 r = read (fd, &c, 1);
554 if (errno != EAGAIN && errno != EINTR)
557 if (c == '\n') /* end on \n */
559 if (c == '\r') /* ignore \r */
572 return GST_RTSP_EEOF;
576 return GST_RTSP_ESYS;
581 read_string (gchar * dest, gint size, gchar ** src)
587 while (g_ascii_isspace (**src))
590 while (!g_ascii_isspace (**src) && **src != '\0') {
600 read_key (gchar * dest, gint size, gchar ** src)
605 while (**src != ':' && **src != '\0') {
615 parse_response_status (gchar * buffer, GstRTSPMessage * msg)
618 gchar versionstr[20];
625 read_string (versionstr, sizeof (versionstr), &bptr);
626 read_string (codestr, sizeof (codestr), &bptr);
627 code = atoi (codestr);
629 while (g_ascii_isspace (*bptr))
632 if (strcmp (versionstr, "RTSP/1.0") == 0)
633 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
635 else if (strncmp (versionstr, "RTSP/", 5) == 0) {
636 GST_RTSP_CHECK (gst_rtsp_message_init_response (msg, code, bptr, NULL),
638 msg->type_data.response.version = GST_RTSP_VERSION_INVALID;
646 return GST_RTSP_EPARSE;
651 parse_request_line (gchar * buffer, GstRTSPMessage * msg)
653 GstRTSPResult res = GST_RTSP_OK;
654 gchar versionstr[20];
658 GstRTSPMethod method;
662 read_string (methodstr, sizeof (methodstr), &bptr);
663 method = gst_rtsp_find_method (methodstr);
665 read_string (urlstr, sizeof (urlstr), &bptr);
667 res = GST_RTSP_EPARSE;
669 read_string (versionstr, sizeof (versionstr), &bptr);
672 res = GST_RTSP_EPARSE;
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;
682 gst_rtsp_message_init_request (msg, method, urlstr);
683 msg->type_data.request.version = GST_RTSP_VERSION_INVALID;
684 res = GST_RTSP_EPARSE;
690 /* parsing lines means reading a Key: Value pair */
692 parse_line (gchar * buffer, GstRTSPMessage * msg)
696 GstRTSPHeaderField field;
701 read_key (key, sizeof (key), &bptr);
707 field = gst_rtsp_find_header_field (key);
708 if (field != GST_RTSP_HDR_INVALID) {
709 while (g_ascii_isspace (*bptr))
711 gst_rtsp_message_add_header (msg, field, bptr);
718 return GST_RTSP_EPARSE;
723 gst_rtsp_connection_read (GstRTSPConnection * conn, guint8 * data, guint size,
729 struct timeval tv_timeout, *ptv_timeout = NULL;
737 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
738 g_return_val_if_fail (data != NULL, GST_RTSP_EINVAL);
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)
749 else if (avail >= toread)
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;
760 FD_SET (conn->fd, &readfds);
761 FD_SET (READ_SOCKET (conn), &readfds);
767 retval = select (FD_SETSIZE, &readfds, NULL, NULL, ptv_timeout);
768 } while ((retval == -1 && errno == EINTR));
773 /* check for timeout */
777 if (FD_ISSET (READ_SOCKET (conn), &readfds)) {
778 /* read all stop commands */
783 READ_COMMAND (conn, command, res);
785 /* no more commands */
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);
799 } else if (bytes < 0) {
800 if (errno != EAGAIN && errno != EINTR)
812 return GST_RTSP_ESYS;
816 return GST_RTSP_ETIMEOUT;
820 return GST_RTSP_EINTR;
824 return GST_RTSP_EEOF;
828 return GST_RTSP_ESYS;
833 read_body (GstRTSPConnection * conn, glong content_length, GstRTSPMessage * msg,
839 if (content_length <= 0) {
845 body = g_malloc (content_length + 1);
846 body[content_length] = '\0';
848 GST_RTSP_CHECK (gst_rtsp_connection_read (conn, body, content_length,
849 timeout), read_error);
854 gst_rtsp_message_take_body (msg, (guint8 *) body, content_length);
867 gst_rtsp_connection_receive (GstRTSPConnection * conn, GstRTSPMessage * msg,
872 glong content_length;
876 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
877 g_return_val_if_fail (msg != NULL, GST_RTSP_EINVAL);
884 /* parse first line and headers */
885 while (res == GST_RTSP_OK) {
888 /* read first character, this identifies data messages */
889 GST_RTSP_CHECK (gst_rtsp_connection_read (conn, &c, 1, timeout),
892 /* check for data packet, first character is $ */
896 /* data packets are $<1 byte channel><2 bytes length,BE><data bytes> */
898 /* read channel, which is the next char */
899 GST_RTSP_CHECK (gst_rtsp_connection_read (conn, &c, 1, timeout),
902 /* now we create a data message */
903 gst_rtsp_message_init_data (msg, c);
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);
909 size = GUINT16_FROM_BE (size);
911 /* and read the body */
912 res = read_body (conn, size, msg, timeout);
918 /* we have a regular response */
923 /* should not happen */
928 GST_RTSP_CHECK (read_line (conn->fd, buffer + offset,
929 sizeof (buffer) - offset), read_error);
931 if (buffer[0] == '\0')
935 /* first line, check for response status */
936 if (g_str_has_prefix (buffer, "RTSP")) {
937 res = parse_response_status (buffer, msg);
939 res = parse_request_line (buffer, msg);
942 /* else just parse the line */
943 parse_line (buffer, msg);
949 /* read the rest of the body if needed */
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),
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) {
968 /* default session timeout */
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] == ';') {
980 } while (g_ascii_isspace (session_id[i]));
981 if (g_str_has_prefix (&session_id[i], "timeout=")) {
984 /* if we parsed something valid, configure */
985 if ((to = atoi (&session_id[i + 9])) > 0)
992 /* make sure to not overflow */
993 strncpy (conn->session_id, session_id, maxlen);
994 conn->session_id[maxlen] = '\0';
1006 gst_rtsp_connection_close (GstRTSPConnection * conn)
1010 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1015 if (conn->fd != -1) {
1016 res = CLOSE_SOCKET (conn->fd);
1029 return GST_RTSP_ESYS;
1034 gst_rtsp_connection_free (GstRTSPConnection * conn)
1038 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1043 res = gst_rtsp_connection_close (conn);
1044 g_timer_destroy (conn->timer);
1045 g_free (conn->username);
1046 g_free (conn->passwd);
1053 gst_rtsp_connection_next_timeout (GstRTSPConnection * conn, GTimeVal * timeout)
1059 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1060 g_return_val_if_fail (timeout != NULL, GST_RTSP_EINVAL);
1062 elapsed = g_timer_elapsed (conn->timer, &usec);
1063 if (elapsed >= conn->timeout) {
1067 sec = conn->timeout - elapsed;
1070 timeout->tv_sec = sec;
1071 timeout->tv_usec = usec;
1077 gst_rtsp_connection_reset_timeout (GstRTSPConnection * conn)
1079 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1081 g_timer_start (conn->timer);
1087 gst_rtsp_connection_flush (GstRTSPConnection * conn, gboolean flush)
1089 g_return_val_if_fail (conn != NULL, GST_RTSP_EINVAL);
1092 SEND_COMMAND (conn, CONTROL_STOP);
1098 READ_COMMAND (conn, command, res);
1100 /* no more commands */
1109 gst_rtsp_connection_set_auth (GstRTSPConnection * conn,
1110 GstRTSPAuthMethod method, gchar * user, gchar * pass)
1112 /* Digest isn't implemented yet */
1113 if (method == GST_RTSP_AUTH_DIGEST)
1114 return GST_RTSP_ENOTIMPL;
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;
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;
1124 g_free (conn->username);
1125 g_free (conn->passwd);
1127 conn->auth_method = method;
1128 conn->username = g_strdup (user);
1129 conn->passwd = g_strdup (pass);