[svn r310] Added new function to recorder: CHANGE_CHANNEL, which try to move to the next valid channel, instead of passing a valid channel name.
4 * @file gmyth/gmyth_socket.c
6 * @brief <p> MythTV socket implementation, according to the MythTV Project
9 * This component provides basic socket functionalities to interact with
13 * Copyright (C) 2006 INdT - Instituto Nokia de Tecnologia.
14 * @author Rosfran Lins Borges <rosfran.borges@indt.org.br>
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU Lesser General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU Lesser General Public License
29 * along with this program; if not, write to the Free Software
30 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
37 #include "gmyth_socket.h"
40 #include <glib/gprintf.h>
42 #include <arpa/inet.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <sys/param.h>
52 #include <netinet/in.h>
56 #if defined(HAVE_IFADDRS_H)
59 #include <sys/ioctl.h>
62 #include "gmyth_stringlist.h"
63 #include "gmyth_uri.h"
64 #include "gmyth_debug.h"
67 #define MYTH_SEPARATOR "[]:[]"
68 #define MYTH_PROTOCOL_FIELD_SIZE 8
70 /* max number of iterations */
71 #define MYTHTV_MAX_VERSION_CHECKS 40
73 // FIXME: put this in the right place
74 #define MYTHTV_VERSION_DEFAULT 30
76 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
78 static gchar* local_hostname = NULL;
80 static void gmyth_socket_class_init (GMythSocketClass *klass);
81 static void gmyth_socket_init (GMythSocket *object);
83 static void gmyth_socket_dispose (GObject *object);
84 static void gmyth_socket_finalize (GObject *object);
86 G_DEFINE_TYPE(GMythSocket, gmyth_socket, G_TYPE_OBJECT)
89 gmyth_socket_class_init (GMythSocketClass *klass)
91 GObjectClass *gobject_class;
93 gobject_class = (GObjectClass *) klass;
95 gobject_class->dispose = gmyth_socket_dispose;
96 gobject_class->finalize = gmyth_socket_finalize;
100 gmyth_socket_init (GMythSocket *gmyth_socket)
103 /* gmyth_socket->local_hostname = NULL; */
107 /** Gets the some important address translation info, from the client socket
108 * that will open a connection.
110 * @return gint that represents the error number from getaddrinfo().
113 gmyth_socket_toaddrinfo (const gchar *addr, gint port, struct addrinfo **addrInfo )
115 struct addrinfo hints;
116 gchar *portStr = NULL;
117 gint errorn = EADDRNOTAVAIL;
119 g_return_val_if_fail ( addr != NULL, -1 );
121 /* hints = g_malloc0 ( sizeof(struct addrinfo) ); */
122 memset ( &hints, 0, sizeof(struct addrinfo) );
123 hints.ai_family = AF_INET;
124 hints.ai_socktype = SOCK_STREAM;
125 /* hints.ai_flags = AI_NUMERICHOST; */
128 portStr = g_strdup_printf ( "%d", port );
132 if ( ( errorn = getaddrinfo(addr, portStr, &hints, addrInfo) ) != 0 ) {
133 g_printerr( "[%s] Socket ERROR: %s\n", __FUNCTION__, gai_strerror(errorn) );
136 /* g_free (hints); */
141 gmyth_socket_find_match_address_uri( GMythURI* uri, gchar *address ) {
143 if ( g_ascii_strcasecmp( gmyth_uri_get_host( uri ), address ) == 0 ) {
144 //g_printerr( "Found URI: %s !!!\n", rui_uri_getvalue(uri) );
152 #if defined(HAVE_IFADDRS_H)
154 /** Gets the list of all local network interfaces.
156 * @param current_connections A list with all the network interfaces are valid,
157 * to be applied just like a filter.
158 * @return List with all the local net interfaces.
161 gmyth_socket_get_local_addrs( GList *current_connections ) {
163 GList *local_addrs = NULL;
165 struct ifaddrs *ifaddr = g_malloc0( sizeof(struct ifaddrs) );
166 struct ifaddrs *i = g_malloc0( sizeof(struct ifaddrs) );
168 gchar *addr = g_new0( gchar, NI_MAXHOST+1 );
172 if (getifaddrs(&ifaddr) != 0)
174 g_printerr("No addresses for interfaces!\n");
178 for ( i = ifaddr; i != NULL; i = i->ifa_next ) {
179 if (!(i->ifa_flags & IFF_UP))
181 if (i->ifa_flags & IFF_LOOPBACK)
183 if ( getnameinfo(i->ifa_addr, sizeof(struct sockaddr), addr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0 ) {
185 ifname = i->ifa_name;
186 ifIdx = if_nametoindex(ifname);
188 if ( current_connections == NULL || ( current_connections != NULL &&
189 g_list_find_custom( current_connections, (gchar *)addr,
190 (GCompareFunc)gmyth_socket_find_match_address_uri ) == NULL ) )
192 local_addrs = g_list_append( local_addrs, g_strdup( addr ) );
195 if ( addr != NULL ) {
197 addr = g_new0( gchar, NI_MAXHOST+1 );
201 } /* iterates over network interfaces */
211 static const gchar *PATH_PROC_NET_DEV = "/proc/net/dev";
213 /** Gets the list of all local network interfaces (using the /proc/net/dev directory).
215 * @param current_connections A list with all the network interfaces are valid,
216 * to be applied just like a filter.
217 * @return List with all the local net interfaces.
220 gmyth_socket_get_local_addrs( GList *current_connections )
223 GList *local_addrs = NULL;
231 s = socket(AF_INET, SOCK_DGRAM, 0);
234 fd = fopen(PATH_PROC_NET_DEV, "r");
235 fgets(buffer, sizeof(buffer)-1, fd);
236 fgets(buffer, sizeof(buffer)-1, fd);
240 if (fgets(buffer, sizeof(buffer)-1, fd) == NULL)
242 sep = strrchr(buffer, ':');
245 while (*ifname == ' ')
248 strcpy(req.ifr_name, ifname);
249 if (ioctl(s, SIOCGIFFLAGS, &req) < 0)
251 if (!(req.ifr_flags & IFF_UP))
253 if (req.ifr_flags & IFF_LOOPBACK)
255 if (ioctl(s, SIOCGIFADDR, &req) < 0)
257 g_strlcpy( ifaddr, inet_ntoa(((struct sockaddr_in*)&req.ifr_addr)->sin_addr), sizeof(struct ifaddr)-1 );
258 local_addrs = g_list_append( local_addrs, g_strdup( ifaddr ) );
260 gmyth_debug( "( from the /proc/net/dev) Interface name: %s, address: %s\n",
272 * Get only the local addresses from the primary interface
275 gmyth_socket_get_primary_addr()
278 gchar *if_eth0 = g_new0( gchar, sizeof(struct ifaddr)-1 );
279 GList *if_tmp = NULL;
281 GList *interfs = gmyth_socket_get_local_addrs( NULL );
283 if ( interfs != NULL && ( g_list_length( interfs ) > 0 ) )
285 /* get the first occurrence (primary interface) */
286 if_tmp = g_list_first( interfs );
288 if ( if_tmp != NULL )
289 g_strlcpy (if_eth0, (gchar *)if_tmp->data, sizeof(struct ifaddr)-1 );
293 if ( interfs != NULL )
294 g_list_free( interfs );
299 /** This function retrieves the local hostname of the
302 * @return GString* get local hostname.
305 gmyth_socket_get_local_hostname ()
309 if ( local_hostname != NULL && strlen(local_hostname) > 0 )
310 return g_string_new( local_hostname );
312 gchar *localaddr = NULL;
313 gboolean found_addr = FALSE;
314 struct addrinfo* addr_info_data = NULL, *addr_info0 = NULL;
315 struct sockaddr_in* sa = NULL;
316 gchar localhostname[MAXHOSTNAMELEN];
318 if (gethostname (localhostname, MAXHOSTNAMELEN) != 0 ) {
319 gmyth_debug ( "Error on gethostname" );
321 localhostname[MAXHOSTNAMELEN-1] = 0;
323 gint err = gmyth_socket_toaddrinfo (localhostname, -1, &addr_info_data );
325 if ( err == EADDRNOTAVAIL )
327 g_warning( "[%s] Address (%s) not available. (reason = %d)\n", __FUNCTION__, localhostname, err );
331 g_static_mutex_lock( &mutex );
333 addr_info0 = addr_info_data;
335 while( addr_info0 != NULL && addr_info0->ai_addr != NULL &&
336 ( sa = (struct sockaddr_in*)addr_info0->ai_addr ) != NULL && !found_addr ) {
337 localaddr = inet_ntoa( sa->sin_addr );
339 if ( localaddr != NULL && ( g_strrstr( localaddr, "127" ) == NULL ) ) {
340 str = g_string_new (localaddr);
346 if (localaddr != NULL) {
352 addr_info0 = addr_info0->ai_next;
355 freeaddrinfo (addr_info_data);
356 addr_info_data = NULL;
358 if ( found_addr == FALSE ) {
359 gchar *prim_addr = gmyth_socket_get_primary_addr();
361 if ( prim_addr != NULL ) {
362 g_warning("[%s] Could not determine the local alphanumerical hostname. Setting to %s\n",
363 __FUNCTION__, prim_addr );
365 str = g_string_new (prim_addr);
368 str = g_string_new (localhostname);
372 g_static_mutex_unlock (&mutex);
374 if ( str != NULL && str->str != NULL )
375 local_hostname = g_strdup( str->str );
381 gmyth_socket_dispose (GObject *object)
383 GMythSocket *gmyth_socket = GMYTH_SOCKET(object);
385 /* disconnect socket */
386 gmyth_socket_close_connection (gmyth_socket);
388 g_free (gmyth_socket->hostname);
389 gmyth_socket->hostname = NULL;
391 g_free (local_hostname);
393 local_hostname = NULL;
395 G_OBJECT_CLASS (gmyth_socket_parent_class)->dispose (object);
399 gmyth_socket_finalize (GObject *object)
401 g_signal_handlers_destroy (object);
403 G_OBJECT_CLASS (gmyth_socket_parent_class)->finalize (object);
406 /** Creates a new instance of GMythSocket.
408 * @return a new instance of GMythSocket.
413 GMythSocket *gmyth_socket = GMYTH_SOCKET (g_object_new(GMYTH_SOCKET_TYPE, NULL));
415 gmyth_socket->mythtv_version = MYTHTV_VERSION_DEFAULT;
420 /** Try to open an asynchronous connection to the MythTV backend.
422 * @param fd Socket descriptor.
423 * @param remote Remote address.
424 * @param len Newly created socket length field.
425 * @param timeout Timeval argument with the time interval to timeout before closing.
426 * @param err Error message number.
427 * @return Any numerical value below 0, if an error had been found.
430 gmyth_socket_try_connect ( gint fd, struct sockaddr *remote, gint len,
431 struct timeval *timeout, gint *err)
433 /*g_return_val_if_fail( timeout != NULL, 0 );*/
434 gint saveflags, ret, back_err;
438 saveflags = fcntl( fd, F_GETFL, 0 );
439 if( saveflags < 0 ) {
440 g_warning( "[%s] Problems when getting socket flags on fcntl.\n", __FUNCTION__ );
445 /* Set non blocking */
446 if( fcntl( fd, F_SETFL, saveflags | O_NONBLOCK ) < 0) {
447 g_warning( "[%s] Problems when setting non-blocking using fcntl.\n", __FUNCTION__ );
452 /* This will return immediately */
453 *err= connect ( fd, remote, len );
457 if( fcntl( fd, F_SETFL, saveflags ) < 0) {
458 g_warning( "[%s] Problems when trying to restore flags with fcntl.\n", __FUNCTION__ );
463 /* return unless the connection was successful or the connect is
464 still in progress. */
465 if( *err < 0 && back_err != EINPROGRESS) {
466 g_warning( "[%s] Connection unsucessfully (it is not in progress).\n", __FUNCTION__ );
474 *err = select( FD_SETSIZE, NULL, &fd_w, NULL, timeout);
476 g_warning( "[%s] Connection unsucessfull (timed out).\n", __FUNCTION__ );
481 /* 0 means it timeout out & no fds changed */
488 /* Get the return code from the connect */
490 *err=getsockopt( fd, SOL_SOCKET, SO_ERROR, &ret, (socklen_t *) &len);
493 g_warning( "[%s] Connection usnsucessfull.\n", __FUNCTION__ );
498 /* ret=0 means success, otherwise it contains the errno */
508 /** Connects to the backend.
510 * @param gmyth_socket The GMythSocket instance.
511 * @param hostname The backend hostname or IP address.
512 * @param port The backend port.
513 * @return TRUE if success, FALSE if error.
518 gmyth_socket_connect (GMythSocket *gmyth_socket,
519 const gchar *hostname, gint port)
521 return gmyth_socket_connect_with_timeout (gmyth_socket,
526 gmyth_socket_connect_with_timeout (GMythSocket *gmyth_socket,
527 const gchar *hostname, gint port, guint timeout)
529 struct addrinfo *addr_info_data = NULL, *addr_info0 = NULL;
534 gmyth_debug ("CONNECTING %s:%d", hostname, port);
536 if ( hostname == NULL )
537 gmyth_debug ( "Invalid hostname parameter!\n");
539 /* store hostname and port number */
540 if (gmyth_socket->hostname != NULL) {
541 //g_free (gmyth_socket->hostname);
542 gmyth_socket->hostname = NULL;
545 errno = gmyth_socket_toaddrinfo ( hostname, port, &addr_info_data );
547 g_return_val_if_fail( addr_info_data != NULL && hostname != NULL, FALSE );
549 gmyth_socket->hostname = g_strdup( hostname );
550 gmyth_socket->port = port;
552 for ( addr_info0 = addr_info_data; addr_info0; addr_info0 = addr_info_data->ai_next ) {
553 /* init socket descriptor */
554 gmyth_socket->sd = socket( addr_info0->ai_family, addr_info0->ai_socktype,
555 addr_info0->ai_protocol );
557 if ( gmyth_socket->sd < 0 )
560 struct timeval *timeout_val = g_new0 (struct timeval, 1);
562 /*timeout_val = g_new0 (struct timeval, 1);*/
564 timeout_val->tv_sec = timeout;
565 timeout_val->tv_usec = 0;
567 timeout_val->tv_sec = 5;
568 timeout_val->tv_usec = 100;
571 if (gmyth_socket_try_connect (gmyth_socket->sd, (struct sockaddr *)addr_info0->ai_addr,
572 addr_info0->ai_addrlen, timeout_val, &ret_code ) < 0 )
574 g_printerr( "[%s] Error connecting to backend!\n", __FUNCTION__ );
575 if (ret_code == ETIMEDOUT)
576 g_printerr( "[%s]\tBackend host unreachable!\n", __FUNCTION__ );
578 close (gmyth_socket->sd);
579 gmyth_socket->sd = -1;
580 g_printerr ("ERROR: %s\n", gai_strerror(ret_code));
581 g_free (timeout_val);
585 g_free (timeout_val);
587 /* only will be reached if none of the error above occurred */
591 freeaddrinfo (addr_info_data);
592 addr_info_data = NULL;
594 if (gmyth_socket->sd_io_ch != NULL) {
595 g_io_channel_unref (gmyth_socket->sd_io_ch);
596 gmyth_socket->sd_io_ch = NULL;
599 gmyth_socket->sd_io_ch = g_io_channel_unix_new (gmyth_socket->sd);
601 //GIOFlags flags = g_io_channel_get_flags (gmyth_socket->sd_io_ch);
602 /* unset the nonblock flag */
603 //flags &= ~G_IO_FLAG_NONBLOCK;
604 /* unset the nonblocking stuff for some time, because GNUTLS doesn't like
606 //g_io_channel_set_flags (gmyth_socket->sd_io_ch, flags, NULL);
608 ret = ( ret_code == 0 ) ? TRUE : FALSE ;
612 /** Gets the GIOChannel associated to the given GMythSocket.
614 * @param gmyth_socket The GMythSocket instance.
617 gmyth_socket_get_io_channel( GMythSocket *gmyth_socket )
619 g_return_val_if_fail( gmyth_socket != NULL, NULL );
621 return gmyth_socket->sd_io_ch;
624 /** Verifies if the socket is able to read.
626 * @param gmyth_socket The GMythSocket instance.
627 * @return TRUE if the socket is able to read, FALSE if not.
630 gmyth_socket_is_able_to_read( GMythSocket *gmyth_socket )
634 /* verify if the input (read) buffer is ready to receive data */
635 GIOCondition io_cond = g_io_channel_get_buffer_condition( gmyth_socket->sd_io_ch );
637 if ( ( io_cond & G_IO_IN ) == 0 ) {
638 g_warning ("[%s] IO channel is not able to send data!\n", __FUNCTION__);
646 /** Verifies if the socket is able to write.
648 * @param gmyth_socket The GMythSocket instance.
649 * @return TRUE if the socket is able to write, FALSE if not.
652 gmyth_socket_is_able_to_write( GMythSocket *gmyth_socket )
656 /* verify if the input (read) buffer is ready to receive data */
657 GIOCondition io_cond = g_io_channel_get_buffer_condition( gmyth_socket->sd_io_ch );
659 if ( ( ( io_cond & G_IO_OUT ) == 0 ) || ( ( io_cond & G_IO_HUP ) == 0 ) ) {
660 g_warning ("[%s] IO channel is not able to send data!\n", __FUNCTION__);
668 /** Sends a command to the backend.
670 * @param gmyth_socket the GMythSocket instance.
671 * @param command The string command to be sent.
674 gmyth_socket_send_command(GMythSocket *gmyth_socket, GString *command)
678 GIOStatus io_status = G_IO_STATUS_NORMAL;
679 //GIOCondition io_cond;
680 GError* error = NULL;
683 gchar *buffer = NULL;
685 gsize bytes_written = 0;
687 if( command == NULL || ( command->len <= 0 ) || command->str == NULL ) {
688 g_warning ("[%s] Invalid NULL command parameter!\n", __FUNCTION__);
693 //g_static_mutex_lock( &mutex );
694 gmyth_debug ("Sending command to backend: %s\n", command->str);
696 buffer = g_strnfill( BUFLEN, ' ' );
697 g_snprintf( buffer, MYTH_PROTOCOL_FIELD_SIZE+1, "%-8d", command->len);
699 command = g_string_prepend(command, buffer);
701 /* write bytes to socket */
702 io_status = g_io_channel_write_chars( gmyth_socket->sd_io_ch, command->str,
703 command->len, &bytes_written, &error );
706 if( (io_status == G_IO_STATUS_ERROR) || ( bytes_written <= 0 ) ) {
707 g_warning ("[%s] Error while writing to socket", __FUNCTION__);
709 } else if ( bytes_written < command->len ) {
710 g_warning ("[%s] Not all data was written socket", __FUNCTION__);
714 io_status = g_io_channel_flush( gmyth_socket->sd_io_ch, &error );
716 if ( ( bytes_written != command->len ) || ( io_status == G_IO_STATUS_ERROR ) )
718 g_warning ("[%s] Some problem occurred when sending data to the socket\n", __FUNCTION__);
723 //g_static_mutex_unlock( &mutex );
725 if ( error != NULL ) {
726 g_printerr( "[%s] Error found reading data from IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
728 g_error_free( error );
737 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
738 * supported by the backend and send the "ANN" command.
740 * @param gmyth_socket the GMythSocket instance.
741 * @param hostname_backend The backend hostname or IP address.
742 * @param port The backend port to connect.
743 * @param blocking_client A flag to choose between blocking and non-blocking
744 * @param with_events Sets the connection flag to receive events.
745 * backend connection.
748 gmyth_socket_connect_to_backend_and_events (GMythSocket *gmyth_socket,
749 const gchar *hostname_backend, gint port, gboolean blocking_client,
750 gboolean with_events)
752 if (!gmyth_socket_connect (gmyth_socket, hostname_backend, port)) {
753 g_warning ("[%s] Could not open socket to backend machine [%s]\n", __FUNCTION__,
758 if ( gmyth_socket_check_protocol_version (gmyth_socket) ) {
761 GString *base_str = g_string_new("");
762 GString *hostname = NULL;
764 hostname = gmyth_socket_get_local_hostname();
766 g_string_printf(base_str, "ANN %s %s %u",
767 (blocking_client ? "Playback" : "Monitor"),
768 hostname->str, with_events);
770 gmyth_socket_send_command (gmyth_socket, base_str);
771 result = gmyth_socket_receive_response (gmyth_socket);
773 if (result != NULL) {
774 gmyth_debug ("Response received from backend: %s", result->str);
775 g_string_free (result, TRUE);
778 g_string_free (hostname, TRUE);
779 g_string_free (base_str, TRUE);
783 g_warning ("[%s] GMythSocket could not connect to the backend", __FUNCTION__);
788 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
789 * supported by the backend and send the "ANN" command.
791 * @param gmyth_socket the GMythSocket instance.
792 * @param hostname_backend The backend hostname or IP address.
793 * @param port The backend port to connect.
794 * @param blocking_client A flag to choose between blocking and non-blocking
797 gmyth_socket_connect_to_backend (GMythSocket *gmyth_socket,
798 const gchar *hostname_backend, gint port, gboolean blocking_client)
800 if (!gmyth_socket_connect_to_backend_and_events ( gmyth_socket, hostname_backend, port,
801 blocking_client, FALSE) ) {
802 gmyth_debug ("Could not open socket to backend machine [%s]\n",
811 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
812 * supported by the backend and send the "ANN" command.
814 * @param gmyth_socket the GMythSocket instance.
815 * @param hostname_backend The backend hostname or IP address.
816 * @param port The backend port to connect.
817 * @param blocking_client A flag to choose between blocking and non-blocking
820 gmyth_socket_connect_to_backend_events (GMythSocket *gmyth_socket,
821 const gchar *hostname_backend, gint port, gboolean blocking_client)
823 if (!gmyth_socket_connect_to_backend_and_events ( gmyth_socket, hostname_backend, port,
824 blocking_client, TRUE) ) {
825 gmyth_debug ("Could not open socket to backend machine in order to receive events [%s]\n",
833 /** Closes the socket connection to the backend.
835 * @param gmyth_socket The GMythSocket instance.
838 gmyth_socket_close_connection (GMythSocket *gmyth_socket)
840 close (gmyth_socket->sd);
841 gmyth_socket->sd = -1;
843 if (gmyth_socket->sd_io_ch != NULL) {
844 g_io_channel_unref (gmyth_socket->sd_io_ch);
845 gmyth_socket->sd_io_ch = NULL;
850 /** Try the MythTV version numbers, and get the version returned by
851 * the possible REJECT message, in order to contruct a new
852 * MythTV version request.
854 * @param gmyth_socket The GMythSocket instance.
855 * @param mythtv_version The Mythtv protocol version to be tested
857 * @return The actual MythTV the client is connected to.
860 gmyth_socket_check_protocol_version_number (GMythSocket *gmyth_socket, gint mythtv_version)
862 GString *response = NULL;
863 GString *payload = NULL;
865 gint mythtv_new_version = MYTHTV_CANNOT_NEGOTIATE_VERSION;
866 guint max_iterations = MYTHTV_MAX_VERSION_CHECKS;
869 payload = g_string_new ("MYTH_PROTO_VERSION");
870 g_string_append_printf( payload, " %d", mythtv_version );
872 gmyth_socket_send_command(gmyth_socket, payload);
873 response = gmyth_socket_receive_response(gmyth_socket);
875 if (response == NULL) {
876 g_warning ("[%s] Check protocol version error! Not answered!", __FUNCTION__);
881 res = g_str_has_prefix (response->str, "ACCEPT");
883 g_warning ("[%s] Protocol version request error: %s", __FUNCTION__, response->str);
884 /* get the version number returned by the REJECT message */
885 if ( ( res = g_str_has_prefix (response->str, "REJECT") ) == TRUE ) {
886 gchar *new_version = NULL;
887 new_version = g_strrstr( response->str, "]" );
888 if (new_version!=NULL) {
889 ++new_version; /* skip ']' character */
890 if ( new_version != NULL ) {
891 gmyth_debug ( "[%s] got MythTV version = %s.\n", __FUNCTION__, new_version );
892 mythtv_version = (gint)g_ascii_strtoull (new_version, NULL, 10 );
893 /* do reconnection to the socket (socket is closed if the MythTV version was wrong) */
894 gmyth_socket_connect( gmyth_socket, gmyth_socket->hostname, gmyth_socket->port );
896 if ( --max_iterations > 0 )
897 goto try_new_version;
905 /* change the return value to a valid one */
907 mythtv_new_version = mythtv_version;
908 gmyth_socket->mythtv_version = mythtv_new_version;
912 if ( payload != NULL )
913 g_string_free (payload, TRUE);
914 if ( response != NULL )
915 g_string_free (response, TRUE);
917 return mythtv_new_version;
920 /** Verifies if the Mythtv backend supported the GMyth supported version.
922 * @param gmyth_socket The GMythSocket instance.
923 * @return TRUE if supports, FALSE if not.
926 gmyth_socket_check_protocol_version (GMythSocket *gmyth_socket)
928 return ( ( gmyth_socket->mythtv_version =
929 gmyth_socket_check_protocol_version_number ( gmyth_socket,
930 MYTHTV_VERSION_DEFAULT ) ) != MYTHTV_CANNOT_NEGOTIATE_VERSION );
933 /** Returns the Mythtv backend supported version.
935 * @param gmyth_socket The GMythSocket instance.
936 * @return The actual MythTV version number.
939 gmyth_socket_get_protocol_version (GMythSocket *gmyth_socket)
941 return gmyth_socket->mythtv_version;
944 /** Receives a backend answer after a gmyth_socket_send_command_call ().
946 * @param gmyth_socket The GMythSocket instance.
947 * @return The response received, or NULL if error or nothing was received.
950 gmyth_socket_receive_response(GMythSocket *gmyth_socket)
952 GIOStatus io_status = G_IO_STATUS_NORMAL;
953 GError* error = NULL;
958 gsize bytes_read = 0;
960 GIOCondition io_cond = g_io_channel_get_buffer_condition (gmyth_socket->sd_io_ch);
962 g_return_val_if_fail( gmyth_socket != NULL, NULL );
964 /* verify if the input (read) buffer is ready to receive data */
966 //g_static_mutex_lock( &mutex );
968 //buffer = g_new0 (gchar, MYTH_PROTOCOL_FIELD_SIZE);
969 buffer = g_strnfill (MYTH_PROTOCOL_FIELD_SIZE, ' ');
970 io_status = g_io_channel_read_chars (gmyth_socket->sd_io_ch, buffer, MYTH_PROTOCOL_FIELD_SIZE, &bytes_read, &error);
972 /* verify if the input (read) buffer is ready to receive data */
973 io_cond = g_io_channel_get_buffer_condition (gmyth_socket->sd_io_ch);
975 gmyth_debug ( "[%s] Bytes read = %d\n", __FUNCTION__, bytes_read );
977 if( (io_status == G_IO_STATUS_ERROR) || (bytes_read <= 0) ) {
978 g_warning ("[%s] Error in mythprotocol response from backend\n", __FUNCTION__);
983 io_status = g_io_channel_flush( gmyth_socket->sd_io_ch, &error );
984 /* verify if the input (read) buffer is ready to receive data */
985 io_cond = g_io_channel_get_buffer_condition( gmyth_socket->sd_io_ch );
987 //if ( ( io_cond & G_IO_IN ) != 0 ) {
988 //gchar *buffer_aux = NULL;
990 /* removes trailing whitespace */
991 //buffer_aux = g_strstrip (buffer);
992 len = (gint)g_ascii_strtoull ( g_strstrip (buffer), NULL, 10 );
994 if (buffer != NULL) {
1000 if (buffer_aux != NULL) {
1001 g_free (buffer_aux);
1006 buffer = g_new0 (gchar, len+1);
1009 io_status = g_io_channel_read_chars( gmyth_socket->sd_io_ch, buffer, len, &bytes_read, &error);
1010 buffer[bytes_read] = '\0';
1014 //g_static_mutex_unlock( &mutex );
1016 gmyth_debug ("Response received from backend: {%s}\n", buffer);
1018 if ( ( bytes_read != len ) || ( io_status == G_IO_STATUS_ERROR ) )
1021 str = g_string_new (buffer);
1023 if ( error != NULL ) {
1024 g_printerr( "[%s] Error found receiving response from the IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
1026 g_error_free (error);
1033 /** Format a Mythtv command from the str_list entries and send it to backend.
1035 * @param gmyth_socket The GMythSocket instance.
1036 * @param str_list The string list to form the command
1037 * @return TRUE if command was sent, FALSE if any error happens.
1040 gmyth_socket_write_stringlist(GMythSocket *gmyth_socket, GMythStringList* str_list)
1043 GList *tmp_list = NULL;
1044 GPtrArray *ptr_array = NULL;
1045 gchar *str_array = NULL;
1047 g_static_mutex_lock( &mutex );
1049 ptr_array = g_ptr_array_sized_new (g_list_length(str_list->glist));
1051 // FIXME: change this implementation!
1052 tmp_list = str_list->glist;
1053 for(; tmp_list; tmp_list = tmp_list->next) {
1054 if ( tmp_list->data != NULL ) {
1055 g_ptr_array_add(ptr_array, ((GString*)tmp_list->data)->str);
1057 g_ptr_array_add (ptr_array, "");
1060 g_ptr_array_add(ptr_array, NULL); // g_str_joinv() needs a NULL terminated string
1062 str_array = g_strjoinv (MYTH_SEPARATOR, (gchar **) (ptr_array->pdata));
1064 g_static_mutex_unlock( &mutex );
1066 gmyth_debug ( "[%s] Sending socket request: %s\n", __FUNCTION__, str_array );
1068 // Sends message to backend
1069 // TODO: implement looping to send remaining data, and add timeout testing!
1070 GString *command = g_string_new(str_array);
1071 gmyth_socket_send_command(gmyth_socket, command);
1072 g_string_free (command, TRUE);
1075 g_ptr_array_free (ptr_array, TRUE);
1080 /* Receives a backend command response and split it into the given string list.
1082 * @param gmyth_socket The GMythSocket instance.
1083 * @param str_list the string list to be filled.
1084 * @return The number of received strings.
1087 gmyth_socket_read_stringlist (GMythSocket *gmyth_socket, GMythStringList* str_list)
1093 response = gmyth_socket_receive_response(gmyth_socket);
1094 g_static_mutex_lock( &mutex );
1096 gmyth_string_list_clear_all (str_list);
1097 str_array = g_strsplit (response->str, MYTH_SEPARATOR, -1);
1099 for (i=0; i< g_strv_length (str_array); i++) {
1100 gmyth_string_list_append_char_array (str_list, str_array[i] );
1102 g_static_mutex_unlock( &mutex );
1104 g_string_free (response, TRUE);
1105 g_strfreev (str_array);
1107 return gmyth_string_list_length (str_list);
1110 /** Formats a Mythtv protocol command based on str_list and sends it to
1111 * the connected backend. The backend response is overwritten into str_list.
1113 * @param gmyth_socket The GMythSocket instance.
1114 * @param str_list The string list to be sent, and on which the answer
1116 * @return TRUE if command was sent and an answer was received, FALSE if any
1120 gmyth_socket_sendreceive_stringlist (GMythSocket *gmyth_socket, GMythStringList *str_list)
1122 gmyth_socket_write_stringlist (gmyth_socket, str_list);
1124 return gmyth_socket_read_stringlist (gmyth_socket, str_list);